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

/libraries/joomla/user/helper.php

https://bitbucket.org/biojazzard/joomla-eboracast
PHP | 599 lines | 328 code | 85 blank | 186 comment | 37 complexity | 082c54a55d6be6660934bc809ef1c696 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, MIT, BSD-3-Clause
  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. ->select($db->quoteName('title'))
  44. ->from($db->quoteName('#__usergroups'))
  45. ->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. ->select($db->quoteName('id') . ', ' . $db->quoteName('title'))
  142. ->from($db->quoteName('#__usergroups'))
  143. ->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. $db = JFactory::getDbo();
  204. // Let's get the id of the user we want to activate
  205. $query = $db->getQuery(true)
  206. ->select($db->quoteName('id'))
  207. ->from($db->quoteName('#__users'))
  208. ->where($db->quoteName('activation') . ' = ' . $db->quote($activation))
  209. ->where($db->quoteName('block') . ' = 1')
  210. ->where($db->quoteName('lastvisitDate') . ' = ' . $db->quote('0000-00-00 00:00:00'));
  211. $db->setQuery($query);
  212. $id = (int) $db->loadResult();
  213. // Is it a valid user to activate?
  214. if ($id)
  215. {
  216. $user = JUser::getInstance((int) $id);
  217. $user->set('block', '0');
  218. $user->set('activation', '');
  219. // Time to take care of business.... store the user.
  220. if (!$user->save())
  221. {
  222. JLog::add($user->getError(), JLog::WARNING, 'jerror');
  223. return false;
  224. }
  225. }
  226. else
  227. {
  228. JLog::add(JText::_('JLIB_USER_ERROR_UNABLE_TO_FIND_USER'), JLog::WARNING, 'jerror');
  229. return false;
  230. }
  231. return true;
  232. }
  233. /**
  234. * Returns userid if a user exists
  235. *
  236. * @param string $username The username to search on.
  237. *
  238. * @return integer The user id or 0 if not found.
  239. *
  240. * @since 11.1
  241. */
  242. public static function getUserId($username)
  243. {
  244. // Initialise some variables
  245. $db = JFactory::getDbo();
  246. $query = $db->getQuery(true)
  247. ->select($db->quoteName('id'))
  248. ->from($db->quoteName('#__users'))
  249. ->where($db->quoteName('username') . ' = ' . $db->quote($username));
  250. $db->setQuery($query, 0, 1);
  251. return $db->loadResult();
  252. }
  253. /**
  254. * Formats a password using the current encryption.
  255. *
  256. * @param string $plaintext The plaintext password to encrypt.
  257. * @param string $salt The salt to use to encrypt the password. []
  258. * If not present, a new salt will be
  259. * generated.
  260. * @param string $encryption The kind of password encryption to use.
  261. * Defaults to md5-hex.
  262. * @param boolean $show_encrypt Some password systems prepend the kind of
  263. * encryption to the crypted password ({SHA},
  264. * etc). Defaults to false.
  265. *
  266. * @return string The encrypted password.
  267. *
  268. * @since 11.1
  269. */
  270. public static function getCryptedPassword($plaintext, $salt = '', $encryption = 'md5-hex', $show_encrypt = false)
  271. {
  272. // Get the salt to use.
  273. $salt = self::getSalt($encryption, $salt, $plaintext);
  274. // Encrypt the password.
  275. switch ($encryption)
  276. {
  277. case 'plain':
  278. return $plaintext;
  279. case 'sha':
  280. $encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext));
  281. return ($show_encrypt) ? '{SHA}' . $encrypted : $encrypted;
  282. case 'crypt':
  283. case 'crypt-des':
  284. case 'crypt-md5':
  285. case 'crypt-blowfish':
  286. return ($show_encrypt ? '{crypt}' : '') . crypt($plaintext, $salt);
  287. case 'md5-base64':
  288. $encrypted = base64_encode(mhash(MHASH_MD5, $plaintext));
  289. return ($show_encrypt) ? '{MD5}' . $encrypted : $encrypted;
  290. case 'ssha':
  291. $encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext . $salt) . $salt);
  292. return ($show_encrypt) ? '{SSHA}' . $encrypted : $encrypted;
  293. case 'smd5':
  294. $encrypted = base64_encode(mhash(MHASH_MD5, $plaintext . $salt) . $salt);
  295. return ($show_encrypt) ? '{SMD5}' . $encrypted : $encrypted;
  296. case 'aprmd5':
  297. $length = strlen($plaintext);
  298. $context = $plaintext . '$apr1$' . $salt;
  299. $binary = self::_bin(md5($plaintext . $salt . $plaintext));
  300. for ($i = $length; $i > 0; $i -= 16)
  301. {
  302. $context .= substr($binary, 0, ($i > 16 ? 16 : $i));
  303. }
  304. for ($i = $length; $i > 0; $i >>= 1)
  305. {
  306. $context .= ($i & 1) ? chr(0) : $plaintext[0];
  307. }
  308. $binary = self::_bin(md5($context));
  309. for ($i = 0; $i < 1000; $i++)
  310. {
  311. $new = ($i & 1) ? $plaintext : substr($binary, 0, 16);
  312. if ($i % 3)
  313. {
  314. $new .= $salt;
  315. }
  316. if ($i % 7)
  317. {
  318. $new .= $plaintext;
  319. }
  320. $new .= ($i & 1) ? substr($binary, 0, 16) : $plaintext;
  321. $binary = self::_bin(md5($new));
  322. }
  323. $p = array();
  324. for ($i = 0; $i < 5; $i++)
  325. {
  326. $k = $i + 6;
  327. $j = $i + 12;
  328. if ($j == 16)
  329. {
  330. $j = 5;
  331. }
  332. $p[] = self::_toAPRMD5((ord($binary[$i]) << 16) | (ord($binary[$k]) << 8) | (ord($binary[$j])), 5);
  333. }
  334. return '$apr1$' . $salt . '$' . implode('', $p) . self::_toAPRMD5(ord($binary[11]), 3);
  335. case 'md5-hex':
  336. default:
  337. $encrypted = ($salt) ? md5($plaintext . $salt) : md5($plaintext);
  338. return ($show_encrypt) ? '{MD5}' . $encrypted : $encrypted;
  339. }
  340. }
  341. /**
  342. * Returns a salt for the appropriate kind of password encryption.
  343. * Optionally takes a seed and a plaintext password, to extract the seed
  344. * of an existing password, or for encryption types that use the plaintext
  345. * in the generation of the salt.
  346. *
  347. * @param string $encryption The kind of password encryption to use.
  348. * Defaults to md5-hex.
  349. * @param string $seed The seed to get the salt from (probably a
  350. * previously generated password). Defaults to
  351. * generating a new seed.
  352. * @param string $plaintext The plaintext password that we're generating
  353. * a salt for. Defaults to none.
  354. *
  355. * @return string The generated or extracted salt.
  356. *
  357. * @since 11.1
  358. */
  359. public static function getSalt($encryption = 'md5-hex', $seed = '', $plaintext = '')
  360. {
  361. // Encrypt the password.
  362. switch ($encryption)
  363. {
  364. case 'crypt':
  365. case 'crypt-des':
  366. if ($seed)
  367. {
  368. return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 2);
  369. }
  370. else
  371. {
  372. return substr(md5(mt_rand()), 0, 2);
  373. }
  374. break;
  375. case 'crypt-md5':
  376. if ($seed)
  377. {
  378. return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 12);
  379. }
  380. else
  381. {
  382. return '$1$' . substr(md5(mt_rand()), 0, 8) . '$';
  383. }
  384. break;
  385. case 'crypt-blowfish':
  386. if ($seed)
  387. {
  388. return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 16);
  389. }
  390. else
  391. {
  392. return '$2$' . substr(md5(mt_rand()), 0, 12) . '$';
  393. }
  394. break;
  395. case 'ssha':
  396. if ($seed)
  397. {
  398. return substr(preg_replace('|^{SSHA}|', '', $seed), -20);
  399. }
  400. else
  401. {
  402. return mhash_keygen_s2k(MHASH_SHA1, $plaintext, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
  403. }
  404. break;
  405. case 'smd5':
  406. if ($seed)
  407. {
  408. return substr(preg_replace('|^{SMD5}|', '', $seed), -16);
  409. }
  410. else
  411. {
  412. return mhash_keygen_s2k(MHASH_MD5, $plaintext, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
  413. }
  414. break;
  415. case 'aprmd5': /* 64 characters that are valid for APRMD5 passwords. */
  416. $APRMD5 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  417. if ($seed)
  418. {
  419. return substr(preg_replace('/^\$apr1\$(.{8}).*/', '\\1', $seed), 0, 8);
  420. }
  421. else
  422. {
  423. $salt = '';
  424. for ($i = 0; $i < 8; $i++)
  425. {
  426. $salt .= $APRMD5{rand(0, 63)};
  427. }
  428. return $salt;
  429. }
  430. break;
  431. default:
  432. $salt = '';
  433. if ($seed)
  434. {
  435. $salt = $seed;
  436. }
  437. return $salt;
  438. break;
  439. }
  440. }
  441. /**
  442. * Generate a random password
  443. *
  444. * @param integer $length Length of the password to generate
  445. *
  446. * @return string Random Password
  447. *
  448. * @since 11.1
  449. */
  450. public static function genRandomPassword($length = 8)
  451. {
  452. $salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  453. $base = strlen($salt);
  454. $makepass = '';
  455. /*
  456. * Start with a cryptographic strength random string, then convert it to
  457. * a string with the numeric base of the salt.
  458. * Shift the base conversion on each character so the character
  459. * distribution is even, and randomize the start shift so it's not
  460. * predictable.
  461. */
  462. $random = JCrypt::genRandomBytes($length + 1);
  463. $shift = ord($random[0]);
  464. for ($i = 1; $i <= $length; ++$i)
  465. {
  466. $makepass .= $salt[($shift + ord($random[$i])) % $base];
  467. $shift += ord($random[$i]);
  468. }
  469. return $makepass;
  470. }
  471. /**
  472. * Converts to allowed 64 characters for APRMD5 passwords.
  473. *
  474. * @param string $value The value to convert.
  475. * @param integer $count The number of characters to convert.
  476. *
  477. * @return string $value converted to the 64 MD5 characters.
  478. *
  479. * @since 11.1
  480. */
  481. protected static function _toAPRMD5($value, $count)
  482. {
  483. /* 64 characters that are valid for APRMD5 passwords. */
  484. $APRMD5 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  485. $aprmd5 = '';
  486. $count = abs($count);
  487. while (--$count)
  488. {
  489. $aprmd5 .= $APRMD5[$value & 0x3f];
  490. $value >>= 6;
  491. }
  492. return $aprmd5;
  493. }
  494. /**
  495. * Converts hexadecimal string to binary data.
  496. *
  497. * @param string $hex Hex data.
  498. *
  499. * @return string Binary data.
  500. *
  501. * @since 11.1
  502. */
  503. private static function _bin($hex)
  504. {
  505. $bin = '';
  506. $length = strlen($hex);
  507. for ($i = 0; $i < $length; $i += 2)
  508. {
  509. $tmp = sscanf(substr($hex, $i, 2), '%x');
  510. $bin .= chr(array_shift($tmp));
  511. }
  512. return $bin;
  513. }
  514. }