Новости Joomla

joomLab Gallery - плагин галереи изображений для Joomla

👩‍💻 joomLab Gallery - плагин галереи изображений для Joomla.Плагин joomLab Gallery позволит Вам добавлять в любой материал неограниченное количество галерей, а главное удобно управлять файлами и эффектами в каждой галерее.Плагин использует популярны скрипты Swiper.js и FancyBox. Первый для крутой организации и эффектов галерей, а второй для красивого и функционального показа оригинальных изображений на Вашем сайте.На данный момент плагин имеет 10 макетов вывода - это 10 различных эффектов галерей и Вы можете совмещать все 10 в 1 материале.Плагин позволяет гибко настраивать индивидуально каждую галерею в материале. Вы можете выбрать макет, эффекты и даже можете управлять функциями всплывающего окна изображения.Недостатки.Такой вид реализации не предусматривает выбор изображения на сервере. Т.е. Вы не можете выбрать уже добавленное фото, только загружать заново. Плагин не предоставляет возможности доступа к медиа-менеджеру.Плагин бесплатный. Разработчик - участник нашего сообщества Александр Новиков (@pro-portal).Страница расширения@joomlafeed#joomla #расширения

Готовлю большой выпуск, включающий интервью с участниками Joomla Ну что, интересная инициатива от...

Готовлю большой выпуск, включающий интервью с участниками Joomla Ну что, интересная инициатива от...

Готовлю большой выпуск, включающий интервью с участниками Joomla 🖨Ну что, интересная инициатива от @webtolkru в виде интервью с разными участниками весьма меня увлекла. Я, вооружившись данным примером, решил подготовить выпуск для NorrNext (@norrnext) и экстраполировал идею на международный масштаб. Теперь готовлю эксклюзивный выпуск с участниками Joomla сообщества со всего мира, которые, в той или иной мере, внесли свой вклад в развитие и популяризацию системы. Будут беседы с людьми из разных стран и фото с юбилейной символикой 📸Работа в процессе 👆 📝О результатах оповещу отдельно.

0 Пользователей и 1 Гость просматривают эту тему.
  • 5 Ответов
  • 4761 Просмотров
*

xchesh

  • Захожу иногда
  • 277
  • 10 / 1
Подскажите пожалуйста, есть ли готовое расширение, для массового добавления пользователей.
Например у меня есть таблица xls или файл XML с какой-либо структурой.
Не очень хочется писать свою обработку...
*

Aeliot

  • Захожу иногда
  • 107
  • 2 / 0
Re: Импорт пользователей в Joomla 2.5
« Ответ #1 : 15.02.2013, 21:04:15 »
изв. не туда запостил
*

xchesh

  • Захожу иногда
  • 277
  • 10 / 1
Re: Импорт пользователей в Joomla 2.5
« Ответ #2 : 18.02.2013, 09:20:09 »
Да собственно уже и не нужно.
Сам написал скрипт добавления юзверей
*

Aeliot

  • Захожу иногда
  • 107
  • 2 / 0
Re: Импорт пользователей в Joomla 2.5
« Ответ #3 : 05.03.2013, 17:40:01 »
О. А поделиться можешь?
А то мне предстоит вбить в базу пару сотен человек и разнести их по разным группам.
*

xchesh

  • Захожу иногда
  • 277
  • 10 / 1
Re: Импорт пользователей в Joomla 2.5
« Ответ #4 : 11.03.2013, 12:38:52 »
О. А поделиться можешь?
А то мне предстоит вбить в базу пару сотен человек и разнести их по разным группам.
Конечно.
users.php
Код: php
<?php
/**
 * @package     Joomla.Platform
 * @subpackage  User
 *
 * @copyright   Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE
 */

/**
 * Authorisation helper class, provides static methods to perform various tasks relevant
 * to the Joomla user and authorisation classes
 *
 * This class has influences and some method logic from the Horde Auth package
 *
 * @package     Joomla.Platform
 * @subpackage  User
 * @since       11.1
 */
abstract class JUserHelper
{
/**
* Method to add a user to a group.
*
* @param   integer  $userId   The id of the user.
* @param   integer  $groupId  The id of the group.
*
* @return  mixed  Boolean true on success, Exception on error.
*
* @since   11.1
*/
public static function addUserToGroup($userId, $groupId)
{
// Get the user object.
$user = new JUser((int) $userId);

// Add the user to the group if necessary.
if (!in_array($groupId, $user->groups))
{
// Get the title of the group.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('title'));
$query->from($db->quoteName('#__usergroups'));
$query->where($db->quoteName('id'). ' = ' . (int) $groupId);
$db->setQuery($query);
$title = $db->loadResult();

// Check for a database error.
if ($db->getErrorNum())
{
return new Exception($db->getErrorMsg());
}

// If the group does not exist, return an exception.
if (!$title)
{
return new Exception(JText::_('JLIB_USER_EXCEPTION_ACCESS_USERGROUP_INVALID'));
}

// Add the group data to the user object.
$user->groups[$title] = $groupId;

// Store the user object.
if (!$user->save())
{
return new Exception($user->getError());
}
}

// Set the group data for any preloaded user objects.
$temp = JFactory::getUser((int) $userId);
$temp->groups = $user->groups;

// Set the group data for the user object in the session.
$temp = JFactory::getUser();
if ($temp->id == $userId)
{
$temp->groups = $user->groups;
}

return true;
}

/**
* Method to get a list of groups a user is in.
*
* @param   integer  $userId  The id of the user.
*
* @return  mixed  Array on success, JException on error.
*
* @since   11.1
*/
public static function getUserGroups($userId)
{
// Get the user object.
$user = JUser::getInstance((int) $userId);

return isset($user->groups)? $user->groups : array();
}

/**
* Method to remove a user from a group.
*
* @param   integer  $userId   The id of the user.
* @param   integer  $groupId  The id of the group.
*
* @return  mixed  Boolean true on success, JException on error.
*
* @since   11.1
*/
public static function removeUserFromGroup($userId, $groupId)
{
// Get the user object.
$user = JUser::getInstance((int) $userId);

// Remove the user from the group if necessary.
$key = array_search($groupId, $user->groups);
if ($key !== false)
{
// Remove the user from the group.
unset($user->groups[$key]);

// Store the user object.
if (!$user->save())
{
return new JException($user->getError());
}
}

// Set the group data for any preloaded user objects.
$temp = JFactory::getUser((int) $userId);
$temp->groups = $user->groups;

// Set the group data for the user object in the session.
$temp = JFactory::getUser();
if ($temp->id == $userId)
{
$temp->groups = $user->groups;
}

return true;
}

/**
* Method to set the groups for a user.
*
* @param   integer  $userId  The id of the user.
* @param   array    $groups  An array of group ids to put the user in.
*
* @return  mixed  Boolean true on success, Exception on error.
*
* @since   11.1
*/
public static function setUserGroups($userId, $groups)
{
// Get the user object.
$user = JUser::getInstance((int) $userId);

// Set the group ids.
JArrayHelper::toInteger($groups);
$user->groups = $groups;

// Get the titles for the user groups.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('id'). ', ' . $db->quoteName('title'));
$query->from($db->quoteName('#__usergroups'));
$query->where($db->quoteName('id'). ' = ' . implode(' OR ' . $db->quoteName('id'). ' = ', $user->groups));
$db->setQuery($query);
$results = $db->loadObjectList();

// Check for a database error.
if ($db->getErrorNum())
{
return new Exception($db->getErrorMsg());
}

// Set the titles for the user groups.
for ($i = 0, $n = count($results); $i < $n; $i++)
{
$user->groups[$results[$i]->id] = $results[$i]->title;
}

// Store the user object.
if (!$user->save())
{
return new Exception($user->getError());
}

// Set the group data for any preloaded user objects.
$temp = JFactory::getUser((int) $userId);
$temp->groups = $user->groups;

// Set the group data for the user object in the session.
$temp = JFactory::getUser();
if ($temp->id == $userId)
{
$temp->groups = $user->groups;
}

return true;
}

/**
* Gets the user profile information
*
* @param   integer  $userId  The id of the user.
*
* @return  object
*
* @since   11.1
*/
public function getProfile($userId = 0)
{
if ($userId == 0)
{
$user = JFactory::getUser();
$userId = $user->id;
}

// Get the dispatcher and load the user's plugins.
$dispatcher = JDispatcher::getInstance();
JPluginHelper::importPlugin('user');

$data = new JObject;
$data->id = $userId;

// Trigger the data preparation event.
$dispatcher->trigger('onContentPrepareData', array('com_users.profile', &$data));

return $data;
}

/**
* Method to activate a user
*
* @param   string  $activation  Activation string
*
* @return  boolean  True on success
*
* @since   11.1
*/
public static function activateUser($activation)
{
// Initialize some variables.
$db = JFactory::getDbo();
$query = $db->getQuery(true);

// Let's get the id of the user we want to activate
$query->select($db->quoteName('id'));
$query->from($db->quoteName('#__users'));
$query->where($db->quoteName('activation'). ' = ' . $db->quote($activation));
$query->where($db->quoteName('block'). ' = 1');
$query->where($db->quoteName('lastvisitDate'). ' = ' . $db->quote('0000-00-00 00:00:00'));
$db->setQuery($query);
$id = intval($db->loadResult());

// Is it a valid user to activate?
if ($id)
{
$user = JUser::getInstance((int) $id);

$user->set('block', '0');
$user->set('activation', '');

// Time to take care of business.... store the user.
if (!$user->save())
{
JError::raiseWarning("SOME_ERROR_CODE", $user->getError());
return false;
}
}
else
{
JError::raiseWarning("SOME_ERROR_CODE", JText::_('JLIB_USER_ERROR_UNABLE_TO_FIND_USER'));
return false;
}

return true;
}

/**
* Returns userid if a user exists
*
* @param   string  $username  The username to search on.
*
* @return  integer  The user id or 0 if not found.
*
* @since   11.1
*/
public static function getUserId($username)
{
// Initialise some variables
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('id'));
$query->from($db->quoteName('#__users'));
$query->where($db->quoteName('username'). ' = ' . $db->quote($username));
$db->setQuery($query, 0, 1);
return $db->loadResult();
}

/**
* Formats a password using the current encryption.
*
* @param   string   $plaintext     The plaintext password to encrypt.
* @param   string   $salt          The salt to use to encrypt the password. []
*                                  If not present, a new salt will be
*                                  generated.
* @param   string   $encryption    The kind of password encryption to use.
*                                  Defaults to md5-hex.
* @param   boolean  $show_encrypt  Some password systems prepend the kind of
*                                  encryption to the crypted password ({SHA},
*                                  etc). Defaults to false.
*
* @return  string  The encrypted password.
*
* @since   11.1
*/
public static function getCryptedPassword($plaintext, $salt = '', $encryption = 'md5-hex', $show_encrypt = false)
{
// Get the salt to use.
$salt = JUserHelper::getSalt($encryption, $salt, $plaintext);

// Encrypt the password.
switch ($encryption)
{
case 'plain':
return $plaintext;

case 'sha':
$encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext));
return ($show_encrypt)? '{SHA}' . $encrypted : $encrypted;

case 'crypt':
case 'crypt-des':
case 'crypt-md5':
case 'crypt-blowfish':
return ($show_encrypt ? '{crypt}' : ''). crypt($plaintext, $salt);

case 'md5-base64':
$encrypted = base64_encode(mhash(MHASH_MD5, $plaintext));
return ($show_encrypt)? '{MD5}' . $encrypted : $encrypted;

case 'ssha':
$encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext . $salt). $salt);
return ($show_encrypt)? '{SSHA}' . $encrypted : $encrypted;

case 'smd5':
$encrypted = base64_encode(mhash(MHASH_MD5, $plaintext . $salt). $salt);
return ($show_encrypt)? '{SMD5}' . $encrypted : $encrypted;

case 'aprmd5':
$length = strlen($plaintext);
$context = $plaintext . '$apr1$' . $salt;
$binary = JUserHelper::_bin(md5($plaintext . $salt . $plaintext));

for ($i = $length; $i > 0; $i -= 16)
{
$context .= substr($binary, 0, ($i > 16 ? 16 : $i));
}
for ($i = $length; $i > 0; $i >>= 1)
{
$context .= ($i & 1)? chr(0) : $plaintext[0];
}

$binary = JUserHelper::_bin(md5($context));

for ($i = 0; $i < 1000; $i++)
{
$new = ($i & 1)? $plaintext : substr($binary, 0, 16);
if ($i % 3)
{
$new .= $salt;
}
if ($i % 7)
{
$new .= $plaintext;
}
$new .= ($i & 1)? substr($binary, 0, 16) : $plaintext;
$binary = JUserHelper::_bin(md5($new));
}

$p = array();
for ($i = 0; $i < 5; $i++)
{
$k = $i + 6;
$j = $i + 12;
if ($j == 16)
{
$j = 5;
}
$p[] = JUserHelper::_toAPRMD5((ord($binary[$i]) << 16) | (ord($binary[$k]) << 8) | (ord($binary[$j])), 5);
}

return '$apr1$' . $salt . '$' . implode('', $p). JUserHelper::_toAPRMD5(ord($binary[11]), 3);

case 'md5-hex':
default:
$encrypted = ($salt)? md5($plaintext . $salt) : md5($plaintext);
return ($show_encrypt)? '{MD5}' . $encrypted : $encrypted;
}
}

/**
* Returns a salt for the appropriate kind of password encryption.
* Optionally takes a seed and a plaintext password, to extract the seed
* of an existing password, or for encryption types that use the plaintext
* in the generation of the salt.
*
* @param   string  $encryption  The kind of password encryption to use.
*                               Defaults to md5-hex.
* @param   string  $seed        The seed to get the salt from (probably a
*                               previously generated password). Defaults to
*                               generating a new seed.
* @param   string  $plaintext   The plaintext password that we're generating
*                               a salt for. Defaults to none.
*
* @return  string  The generated or extracted salt.
*
* @since   11.1
*/
public static function getSalt($encryption = 'md5-hex', $seed = '', $plaintext = '')
{
// Encrypt the password.
switch ($encryption)
{
case 'crypt':
case 'crypt-des':
if ($seed)
{
return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 2);
}
else
{
return substr(md5(mt_rand()), 0, 2);
}
break;

case 'crypt-md5':
if ($seed)
{
return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 12);
}
else
{
return '<?php
/**
 * @package     Joomla.Platform
 * @subpackage  User
 *
 * @copyright   Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE
 */

/**
 * Authorisation helper class, provides static methods to perform various tasks relevant
 * to the Joomla user and authorisation classes
 *
 * This class has influences and some method logic from the Horde Auth package
 *
 * @package     Joomla.Platform
 * @subpackage  User
 * @since       11.1
 */
abstract class JUserHelper
{
/**
* Method to add a user to a group.
*
* @param   integer  $userId   The id of the user.
* @param   integer  $groupId  The id of the group.
*
* @return  mixed  Boolean true on success, Exception on error.
*
* @since   11.1
*/
public static function addUserToGroup($userId, $groupId)
{
// Get the user object.
$user = new JUser((int) $userId);

// Add the user to the group if necessary.
if (!in_array($groupId, $user->groups))
{
// Get the title of the group.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('title'));
$query->from($db->quoteName('#__usergroups'));
$query->where($db->quoteName('id'). ' = ' . (int) $groupId);
$db->setQuery($query);
$title = $db->loadResult();

// Check for a database error.
if ($db->getErrorNum())
{
return new Exception($db->getErrorMsg());
}

// If the group does not exist, return an exception.
if (!$title)
{
return new Exception(JText::_('JLIB_USER_EXCEPTION_ACCESS_USERGROUP_INVALID'));
}

// Add the group data to the user object.
$user->groups[$title] = $groupId;

// Store the user object.
if (!$user->save())
{
return new Exception($user->getError());
}
}

// Set the group data for any preloaded user objects.
$temp = JFactory::getUser((int) $userId);
$temp->groups = $user->groups;

// Set the group data for the user object in the session.
$temp = JFactory::getUser();
if ($temp->id == $userId)
{
$temp->groups = $user->groups;
}

return true;
}

/**
* Method to get a list of groups a user is in.
*
* @param   integer  $userId  The id of the user.
*
* @return  mixed  Array on success, JException on error.
*
* @since   11.1
*/
public static function getUserGroups($userId)
{
// Get the user object.
$user = JUser::getInstance((int) $userId);

return isset($user->groups)? $user->groups : array();
}

/**
* Method to remove a user from a group.
*
* @param   integer  $userId   The id of the user.
* @param   integer  $groupId  The id of the group.
*
* @return  mixed  Boolean true on success, JException on error.
*
* @since   11.1
*/
public static function removeUserFromGroup($userId, $groupId)
{
// Get the user object.
$user = JUser::getInstance((int) $userId);

// Remove the user from the group if necessary.
$key = array_search($groupId, $user->groups);
if ($key !== false)
{
// Remove the user from the group.
unset($user->groups[$key]);

// Store the user object.
if (!$user->save())
{
return new JException($user->getError());
}
}

// Set the group data for any preloaded user objects.
$temp = JFactory::getUser((int) $userId);
$temp->groups = $user->groups;

// Set the group data for the user object in the session.
$temp = JFactory::getUser();
if ($temp->id == $userId)
{
$temp->groups = $user->groups;
}

return true;
}

/**
* Method to set the groups for a user.
*
* @param   integer  $userId  The id of the user.
* @param   array    $groups  An array of group ids to put the user in.
*
* @return  mixed  Boolean true on success, Exception on error.
*
* @since   11.1
*/
public static function setUserGroups($userId, $groups)
{
// Get the user object.
$user = JUser::getInstance((int) $userId);

// Set the group ids.
JArrayHelper::toInteger($groups);
$user->groups = $groups;

// Get the titles for the user groups.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('id'). ', ' . $db->quoteName('title'));
$query->from($db->quoteName('#__usergroups'));
$query->where($db->quoteName('id'). ' = ' . implode(' OR ' . $db->quoteName('id'). ' = ', $user->groups));
$db->setQuery($query);
$results = $db->loadObjectList();

// Check for a database error.
if ($db->getErrorNum())
{
return new Exception($db->getErrorMsg());
}

// Set the titles for the user groups.
for ($i = 0, $n = count($results); $i < $n; $i++)
{
$user->groups[$results[$i]->id] = $results[$i]->title;
}

// Store the user object.
if (!$user->save())
{
return new Exception($user->getError());
}

// Set the group data for any preloaded user objects.
$temp = JFactory::getUser((int) $userId);
$temp->groups = $user->groups;

// Set the group data for the user object in the session.
$temp = JFactory::getUser();
if ($temp->id == $userId)
{
$temp->groups = $user->groups;
}

return true;
}

/**
* Gets the user profile information
*
* @param   integer  $userId  The id of the user.
*
* @return  object
*
* @since   11.1
*/
public function getProfile($userId = 0)
{
if ($userId == 0)
{
$user = JFactory::getUser();
$userId = $user->id;
}

// Get the dispatcher and load the user's plugins.
$dispatcher = JDispatcher::getInstance();
JPluginHelper::importPlugin('user');

$data = new JObject;
$data->id = $userId;

// Trigger the data preparation event.
$dispatcher->trigger('onContentPrepareData', array('com_users.profile', &$data));

return $data;
}

/**
* Method to activate a user
*
* @param   string  $activation  Activation string
*
* @return  boolean  True on success
*
* @since   11.1
*/
public static function activateUser($activation)
{
// Initialize some variables.
$db = JFactory::getDbo();
$query = $db->getQuery(true);

// Let's get the id of the user we want to activate
$query->select($db->quoteName('id'));
$query->from($db->quoteName('#__users'));
$query->where($db->quoteName('activation'). ' = ' . $db->quote($activation));
$query->where($db->quoteName('block'). ' = 1');
$query->where($db->quoteName('lastvisitDate'). ' = ' . $db->quote('0000-00-00 00:00:00'));
$db->setQuery($query);
$id = intval($db->loadResult());

// Is it a valid user to activate?
if ($id)
{
$user = JUser::getInstance((int) $id);

$user->set('block', '0');
$user->set('activation', '');

// Time to take care of business.... store the user.
if (!$user->save())
{
JError::raiseWarning("SOME_ERROR_CODE", $user->getError());
return false;
}
}
else
{
JError::raiseWarning("SOME_ERROR_CODE", JText::_('JLIB_USER_ERROR_UNABLE_TO_FIND_USER'));
return false;
}

return true;
}

/**
* Returns userid if a user exists
*
* @param   string  $username  The username to search on.
*
* @return  integer  The user id or 0 if not found.
*
* @since   11.1
*/
public static function getUserId($username)
{
// Initialise some variables
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('id'));
$query->from($db->quoteName('#__users'));
$query->where($db->quoteName('username'). ' = ' . $db->quote($username));
$db->setQuery($query, 0, 1);
return $db->loadResult();
}

/**
* Formats a password using the current encryption.
*
* @param   string   $plaintext     The plaintext password to encrypt.
* @param   string   $salt          The salt to use to encrypt the password. []
*                                  If not present, a new salt will be
*                                  generated.
* @param   string   $encryption    The kind of password encryption to use.
*                                  Defaults to md5-hex.
* @param   boolean  $show_encrypt  Some password systems prepend the kind of
*                                  encryption to the crypted password ({SHA},
*                                  etc). Defaults to false.
*
* @return  string  The encrypted password.
*
* @since   11.1
*/
public static function getCryptedPassword($plaintext, $salt = '', $encryption = 'md5-hex', $show_encrypt = false)
{
// Get the salt to use.
$salt = JUserHelper::getSalt($encryption, $salt, $plaintext);

// Encrypt the password.
switch ($encryption)
{
case 'plain':
return $plaintext;

case 'sha':
$encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext));
return ($show_encrypt)? '{SHA}' . $encrypted : $encrypted;

case 'crypt':
case 'crypt-des':
case 'crypt-md5':
case 'crypt-blowfish':
return ($show_encrypt ? '{crypt}' : ''). crypt($plaintext, $salt);

case 'md5-base64':
$encrypted = base64_encode(mhash(MHASH_MD5, $plaintext));
return ($show_encrypt)? '{MD5}' . $encrypted : $encrypted;

case 'ssha':
$encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext . $salt). $salt);
return ($show_encrypt)? '{SSHA}' . $encrypted : $encrypted;

case 'smd5':
$encrypted = base64_encode(mhash(MHASH_MD5, $plaintext . $salt). $salt);
return ($show_encrypt)? '{SMD5}' . $encrypted : $encrypted;

case 'aprmd5':
$length = strlen($plaintext);
$context = $plaintext . '$apr1$' . $salt;
$binary = JUserHelper::_bin(md5($plaintext . $salt . $plaintext));

for ($i = $length; $i > 0; $i -= 16)
{
$context .= substr($binary, 0, ($i > 16 ? 16 : $i));
}
for ($i = $length; $i > 0; $i >>= 1)
{
$context .= ($i & 1)? chr(0) : $plaintext[0];
}

$binary = JUserHelper::_bin(md5($context));

for ($i = 0; $i < 1000; $i++)
{
$new = ($i & 1)? $plaintext : substr($binary, 0, 16);
if ($i % 3)
{
$new .= $salt;
}
if ($i % 7)
{
$new .= $plaintext;
}
$new .= ($i & 1)? substr($binary, 0, 16) : $plaintext;
$binary = JUserHelper::_bin(md5($new));
}

$p = array();
for ($i = 0; $i < 5; $i++)
{
$k = $i + 6;
$j = $i + 12;
if ($j == 16)
{
$j = 5;
}
$p[] = JUserHelper::_toAPRMD5((ord($binary[$i]) << 16) | (ord($binary[$k]) << 8) | (ord($binary[$j])), 5);
}

return '$apr1$' . $salt . '$' . implode('', $p). JUserHelper::_toAPRMD5(ord($binary[11]), 3);

case 'md5-hex':
default:
$encrypted = ($salt)? md5($plaintext . $salt) : md5($plaintext);
return ($show_encrypt)? '{MD5}' . $encrypted : $encrypted;
}
}

/**
* Returns a salt for the appropriate kind of password encryption.
* Optionally takes a seed and a plaintext password, to extract the seed
* of an existing password, or for encryption types that use the plaintext
* in the generation of the salt.
*
* @param   string  $encryption  The kind of password encryption to use.
*                               Defaults to md5-hex.
* @param   string  $seed        The seed to get the salt from (probably a
*                               previously generated password). Defaults to
*                               generating a new seed.
* @param   string  $plaintext   The plaintext password that we're generating
*                               a salt for. Defaults to none.
*
* @return  string  The generated or extracted salt.
*
* @since   11.1
*/
public static function getSalt($encryption = 'md5-hex', $seed = '', $plaintext = '')
{
// Encrypt the password.
switch ($encryption)
{
case 'crypt':
case 'crypt-des':
if ($seed)
{
return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 2);
}
else
{
return substr(md5(mt_rand()), 0, 2);
}
break;

case 'crypt-md5':
if ($seed)
{
return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 12);
}
else
{
return '$1$' . substr(md5(mt_rand()), 0, 8). '$';
}
break;

case 'crypt-blowfish':
if ($seed)
{
return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 16);
}
else
{
return '$2$' . substr(md5(mt_rand()), 0, 12). '$';
}
break;

case 'ssha':
if ($seed)
{
return substr(preg_replace('|^{SSHA}|', '', $seed), -20);
}
else
{
return mhash_keygen_s2k(MHASH_SHA1, $plaintext, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
}
break;

case 'smd5':
if ($seed)
{
return substr(preg_replace('|^{SMD5}|', '', $seed), -16);
}
else
{
return mhash_keygen_s2k(MHASH_MD5, $plaintext, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
}
break;

case 'aprmd5': /* 64 characters that are valid for APRMD5 passwords. */
$APRMD5 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

if ($seed)
{
return substr(preg_replace('/^\$apr1\$(.{8}).*/', '\\1', $seed), 0, 8);
}
else
{
$salt = '';
for ($i = 0; $i < 8; $i++)
{
$salt .= $APRMD5{rand(0, 63)};
}
return $salt;
}
break;

default:
$salt = '';
if ($seed)
{
$salt = $seed;
}
return $salt;
break;
}
}

/**
* Generate a random password
*
* @param   integer  $length  Length of the password to generate
*
* @return  string  Random Password
*
* @since   11.1
*/
public static function genRandomPassword($length = 8)
{
$salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$base = strlen($salt);
$makepass = '';

/*
* Start with a cryptographic strength random string, then convert it to
* a string with the numeric base of the salt.
* Shift the base conversion on each character so the character
* distribution is even, and randomize the start shift so it's not
* predictable.
*/
$random = JCrypt::genRandomBytes($length + 1);
$shift = ord($random[0]);
for ($i = 1; $i <= $length; ++$i)
{
$makepass .= $salt[($shift + ord($random[$i])) % $base];
$shift += ord($random[$i]);
}

return $makepass;
}

/**
* Converts to allowed 64 characters for APRMD5 passwords.
*
* @param   string   $value  The value to convert.
* @param   integer  $count  The number of characters to convert.
*
* @return  string  $value converted to the 64 MD5 characters.
*
* @since   11.1
*/
protected static function _toAPRMD5($value, $count)
{
/* 64 characters that are valid for APRMD5 passwords. */
$APRMD5 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

$aprmd5 = '';
$count = abs($count);
while (--$count)
{
$aprmd5 .= $APRMD5[$value & 0x3f];
$value >>= 6;
}
return $aprmd5;
}

/**
* Converts hexadecimal string to binary data.
*
* @param   string  $hex  Hex data.
*
* @return  string  Binary data.
*
* @since   11.1
*/
private static function _bin($hex)
{
$bin = '';
$length = strlen($hex);
for ($i = 0; $i < $length; $i += 2)
{
$tmp = sscanf(substr($hex, $i, 2), '%x');
$bin .= chr(array_shift($tmp));
}
return $bin;
}
}

class JCrypt
{
/**
* @var    JCryptCipher  The encryption cipher object.
* @since  12.1
*/
private $_cipher;

/**
* @var    JCryptKey  The encryption key[/pair)].
* @since  12.1
*/
private $_key;

/**
* Object Constructor takes an optional key to be used for encryption/decryption. If no key is given then the
* secret word from the configuration object is used.
*
* @param   JCryptCipher  $cipher  The encryption cipher object.
* @param   JCryptKey     $key     The encryption key[/pair)].
*
* @since   12.1
*/
public function __construct(JCryptCipher $cipher = null, JCryptKey $key = null)
{
// Set the encryption key[/pair)].
$this->_key = $key;

// Set the encryption cipher.
$this->_cipher = isset($cipher)? $cipher : new JCryptCipherSimple;
}

/**
* Method to decrypt a data string.
*
* @param   string  $data  The encrypted string to decrypt.
*
* @return  string  The decrypted data string.
*
* @since   12.1
*/
public function decrypt($data)
{
return $this->_cipher->decrypt($data, $this->_key);
}

/**
* Method to encrypt a data string.
*
* @param   string  $data  The data string to encrypt.
*
* @return  string  The encrypted data string.
*
* @since   12.1
*/
public function encrypt($data)
{
return $this->_cipher->encrypt($data, $this->_key);
}

/**
* Method to generate a new encryption key[/pair] object.
*
* @param   array  $options  Key generation options.
*
* @return  JCryptKey
*
* @since   12.1
*/
public function generateKey(array $options = array())
{
return $this->_cipher->generateKey($options);
}

/**
* Method to set the encryption key[/pair] object.
*
* @param   JCryptKey  $key  The key object to set.
*
* @return  JCrypt
*
* @since   12.1
*/
public function setKey(JCryptKey $key)
{
$this->_key = $key;

return $this;
}

/**
* Generate random bytes.
*
* @param   integer  $length  Length of the random data to generate
*
* @return  string  Random binary data
*
* @since  12.1
*/
public static function genRandomBytes($length = 16)
{
$sslStr = '';
/*
* if a secure randomness generator exists and we don't
* have a buggy PHP version use it.
*/
if (function_exists('openssl_random_pseudo_bytes')
&& (version_compare(PHP_VERSION, '5.3.4') >= 0 || IS_WIN))
{
$sslStr = openssl_random_pseudo_bytes($length, $strong);
if ($strong)
{
return $sslStr;
}
}

/*
* Collect any entropy available in the system along with a number
* of time measurements of operating system randomness.
*/
$bitsPerRound = 2;
$maxTimeMicro = 400;
$shaHashLength = 20;
$randomStr = '';
$total = $length;

// Check if we can use /dev/urandom.
$urandom = false;
$handle = null;

// This is PHP 5.3.3 and up
if (function_exists('stream_set_read_buffer') && @is_readable('/dev/urandom'))
{
$handle = @fopen('/dev/urandom', 'rb');
if ($handle)
{
$urandom = true;
}
}

while ($length > strlen($randomStr))
{
$bytes = ($total > $shaHashLength)? $shaHashLength : $total;
$total -= $bytes;
/*
* Collect any entropy available from the PHP system and filesystem.
* If we have ssl data that isn't strong, we use it once.
*/
$entropy = rand(). uniqid(mt_rand(), true). $sslStr;
$entropy .= implode('', @fstat(fopen(__FILE__, 'r')));
$entropy .= memory_get_usage();
$sslStr = '';
if ($urandom)
{
stream_set_read_buffer($handle, 0);
$entropy .= @fread($handle, $bytes);
}
else
{
/*
* There is no external source of entropy so we repeat calls
* to mt_rand until we are assured there's real randomness in
* the result.
*
* Measure the time that the operations will take on average.
*/
$samples = 3;
$duration = 0;
for ($pass = 0; $pass < $samples; ++$pass)
{
$microStart = microtime(true) * 1000000;
$hash = sha1(mt_rand(), true);
for ($count = 0; $count < 50; ++$count)
{
$hash = sha1($hash, true);
}
$microEnd = microtime(true) * 1000000;
$entropy .= $microStart . $microEnd;
if ($microStart > $microEnd)
{
$microEnd += 1000000;
}
$duration += $microEnd - $microStart;
}
$duration = $duration / $samples;

/*
* Based on the average time, determine the total rounds so that
* the total running time is bounded to a reasonable number.
*/
$rounds = (int) (($maxTimeMicro / $duration) * 50);

/*
* Take additional measurements. On average we can expect
* at least $bitsPerRound bits of entropy from each measurement.
*/
$iter = $bytes * (int) ceil(8 / $bitsPerRound);
for ($pass = 0; $pass < $iter; ++$pass)
{
$microStart = microtime(true);
$hash = sha1(mt_rand(), true);
for ($count = 0; $count < $rounds; ++$count)
{
$hash = sha1($hash, true);
}
$entropy .= $microStart . microtime(true);
}
}

$randomStr .= sha1($entropy, true);
}

if ($urandom)
{
@fclose($handle);
}

return substr($randomStr, 0, $length);
}
}
$' . substr(md5(mt_rand()), 0, 8). '$';
}
break;

case 'crypt-blowfish':
if ($seed)
{
return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 16);
}
else
{
return 'php$' . substr(md5(mt_rand()), 0, 12). '$';
}
break;

case 'ssha':
if ($seed)
{
return substr(preg_replace('|^{SSHA}|', '', $seed), -20);
}
else
{
return mhash_keygen_s2k(MHASH_SHA1, $plaintext, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
}
break;

case 'smd5':
if ($seed)
{
return substr(preg_replace('|^{SMD5}|', '', $seed), -16);
}
else
{
return mhash_keygen_s2k(MHASH_MD5, $plaintext, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
}
break;

case 'aprmd5': /* 64 characters that are valid for APRMD5 passwords. */
$APRMD5 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

if ($seed)
{
return substr(preg_replace('/^\$apr1\$(.{8}).*/', '\\1', $seed), 0, 8);
}
else
{
$salt = '';
for ($i = 0; $i < 8; $i++)
{
$salt .= $APRMD5{rand(0, 63)};
}
return $salt;
}
break;

default:
$salt = '';
if ($seed)
{
$salt = $seed;
}
return $salt;
break;
}
}

/**
* Generate a random password
*
* @param   integer  $length  Length of the password to generate
*
* @return  string  Random Password
*
* @since   11.1
*/
public static function genRandomPassword($length = 8)
{
$salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$base = strlen($salt);
$makepass = '';

/*
* Start with a cryptographic strength random string, then convert it to
* a string with the numeric base of the salt.
* Shift the base conversion on each character so the character
* distribution is even, and randomize the start shift so it's not
* predictable.
*/
$random = JCrypt::genRandomBytes($length + 1);
$shift = ord($random[0]);
for ($i = 1; $i <= $length; ++$i)
{
$makepass .= $salt[($shift + ord($random[$i])) % $base];
$shift += ord($random[$i]);
}

return $makepass;
}

/**
* Converts to allowed 64 characters for APRMD5 passwords.
*
* @param   string   $value  The value to convert.
* @param   integer  $count  The number of characters to convert.
*
* @return  string  $value converted to the 64 MD5 characters.
*
* @since   11.1
*/
protected static function _toAPRMD5($value, $count)
{
/* 64 characters that are valid for APRMD5 passwords. */
$APRMD5 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

$aprmd5 = '';
$count = abs($count);
while (--$count)
{
$aprmd5 .= $APRMD5[$value & 0x3f];
$value >>= 6;
}
return $aprmd5;
}

/**
* Converts hexadecimal string to binary data.
*
* @param   string  $hex  Hex data.
*
* @return  string  Binary data.
*
* @since   11.1
*/
private static function _bin($hex)
{
$bin = '';
$length = strlen($hex);
for ($i = 0; $i < $length; $i += 2)
{
$tmp = sscanf(substr($hex, $i, 2), '%x');
$bin .= chr(array_shift($tmp));
}
return $bin;
}
}

class JCrypt
{
/**
* @var    JCryptCipher  The encryption cipher object.
* @since  12.1
*/
private $_cipher;

/**
* @var    JCryptKey  The encryption key[/pair)].
* @since  12.1
*/
private $_key;

/**
* Object Constructor takes an optional key to be used for encryption/decryption. If no key is given then the
* secret word from the configuration object is used.
*
* @param   JCryptCipher  $cipher  The encryption cipher object.
* @param   JCryptKey     $key     The encryption key[/pair)].
*
* @since   12.1
*/
public function __construct(JCryptCipher $cipher = null, JCryptKey $key = null)
{
// Set the encryption key[/pair)].
$this->_key = $key;

// Set the encryption cipher.
$this->_cipher = isset($cipher)? $cipher : new JCryptCipherSimple;
}

/**
* Method to decrypt a data string.
*
* @param   string  $data  The encrypted string to decrypt.
*
* @return  string  The decrypted data string.
*
* @since   12.1
*/
public function decrypt($data)
{
return $this->_cipher->decrypt($data, $this->_key);
}

/**
* Method to encrypt a data string.
*
* @param   string  $data  The data string to encrypt.
*
* @return  string  The encrypted data string.
*
* @since   12.1
*/
public function encrypt($data)
{
return $this->_cipher->encrypt($data, $this->_key);
}

/**
* Method to generate a new encryption key[/pair] object.
*
* @param   array  $options  Key generation options.
*
* @return  JCryptKey
*
* @since   12.1
*/
public function generateKey(array $options = array())
{
return $this->_cipher->generateKey($options);
}

/**
* Method to set the encryption key[/pair] object.
*
* @param   JCryptKey  $key  The key object to set.
*
* @return  JCrypt
*
* @since   12.1
*/
public function setKey(JCryptKey $key)
{
$this->_key = $key;

return $this;
}

/**
* Generate random bytes.
*
* @param   integer  $length  Length of the random data to generate
*
* @return  string  Random binary data
*
* @since  12.1
*/
public static function genRandomBytes($length = 16)
{
$sslStr = '';
/*
* if a secure randomness generator exists and we don't
* have a buggy PHP version use it.
*/
if (function_exists('openssl_random_pseudo_bytes')
&& (version_compare(PHP_VERSION, '5.3.4') >= 0 || IS_WIN))
{
$sslStr = openssl_random_pseudo_bytes($length, $strong);
if ($strong)
{
return $sslStr;
}
}

/*
* Collect any entropy available in the system along with a number
* of time measurements of operating system randomness.
*/
$bitsPerRound = 2;
$maxTimeMicro = 400;
$shaHashLength = 20;
$randomStr = '';
$total = $length;

// Check if we can use /dev/urandom.
$urandom = false;
$handle = null;

// This is PHP 5.3.3 and up
if (function_exists('stream_set_read_buffer') && @is_readable('/dev/urandom'))
{
$handle = @fopen('/dev/urandom', 'rb');
if ($handle)
{
$urandom = true;
}
}

while ($length > strlen($randomStr))
{
$bytes = ($total > $shaHashLength)? $shaHashLength : $total;
$total -= $bytes;
/*
* Collect any entropy available from the PHP system and filesystem.
* If we have ssl data that isn't strong, we use it once.
*/
$entropy = rand(). uniqid(mt_rand(), true). $sslStr;
$entropy .= implode('', @fstat(fopen(__FILE__, 'r')));
$entropy .= memory_get_usage();
$sslStr = '';
if ($urandom)
{
stream_set_read_buffer($handle, 0);
$entropy .= @fread($handle, $bytes);
}
else
{
/*
* There is no external source of entropy so we repeat calls
* to mt_rand until we are assured there's real randomness in
* the result.
*
* Measure the time that the operations will take on average.
*/
$samples = 3;
$duration = 0;
for ($pass = 0; $pass < $samples; ++$pass)
{
$microStart = microtime(true) * 1000000;
$hash = sha1(mt_rand(), true);
for ($count = 0; $count < 50; ++$count)
{
$hash = sha1($hash, true);
}
$microEnd = microtime(true) * 1000000;
$entropy .= $microStart . $microEnd;
if ($microStart > $microEnd)
{
$microEnd += 1000000;
}
$duration += $microEnd - $microStart;
}
$duration = $duration / $samples;

/*
* Based on the average time, determine the total rounds so that
* the total running time is bounded to a reasonable number.
*/
$rounds = (int) (($maxTimeMicro / $duration) * 50);

/*
* Take additional measurements. On average we can expect
* at least $bitsPerRound bits of entropy from each measurement.
*/
$iter = $bytes * (int) ceil(8 / $bitsPerRound);
for ($pass = 0; $pass < $iter; ++$pass)
{
$microStart = microtime(true);
$hash = sha1(mt_rand(), true);
for ($count = 0; $count < $rounds; ++$count)
{
$hash = sha1($hash, true);
}
$entropy .= $microStart . microtime(true);
}
}

$randomStr .= sha1($entropy, true);
}

if ($urandom)
{
@fclose($handle);
}

return substr($randomStr, 0, $length);
}
}

index.php
Код: php
<?php
include 'user.php';
/*--mysqlconnect--*/
$dblocation = "localhost";
$dbname = "db_name";
$dbuser = "db_user";
$dbpasswd = "db_password";
$dbcnx = @mysql_connect($dblocation,$dbuser,$dbpasswd);
if (!$dbcnx){
  echo( "<P>В настоящий момент сервер базы данных не доступен, поэтому
            корректное отображение страницы невозможно.</P>" );
  die();
}
if (!@mysql_select_db($dbname, $dbcnx)){
  echo( "<P>В настоящий момент база данных не доступна, поэтому
            корректное отображение страницы невозможно.</P>" );
  die();
}
/*--mysql connect--*/
if (file_exists('users.xml')) {
    $xml = simplexml_load_file('users.xml');
    foreach ($xml as $row){
        $username = $row->Cell[0];
        $name = iconv("utf-8", "windows-1251", $row->Cell[1]);
//        $name = $row->Cell[1];
        $email = $row->Cell[7];
        $salt = JUserHelper::genRandomPassword(32);
        $crypt = JUserHelper::getCryptedPassword($row->Cell[8], $salt);
        $pass = $crypt . ':' . $salt;
        echo $username.'<br>'.$name.'<br/>'.$email.'<br>'.$pass.'<br>';
        $query = "INSERT INTO `jlbr_users`(`id`, `name`, `username`, `email`, `password`, `usertype`, `block`, `sendEmail`, `registerDate`, `lastvisitDate`, `activation`, `params`, `lastResetTime`, `resetCount`) VALUES ('','$name','$username','$email','$pass','','','','','','','','','');";
        query($query);
    }
    foreach(select() as $id){
        $query2  = "INSERT INTO `jlbr_user_usergroup_map`(`user_id`, `group_id`) VALUES ('$id[id]','9')";
        query($query2);
    }
    
} else {
    exit('Не удалось открыть файл users.xml.');
}

function query($query){
    $creat = mysql_query($query);
    if ($creat){
        echo 'Norm all';
        echo '<br><br>';
    }else{
       echo "<p><b>Error: ".mysql_error()."</b></p>";
       die();
    }
}
function select(){
    $ath = mysql_query("SELECT * FROM jlbr_users WHERE id>800 ORDER by id;");
    if($ath){
      while($author = mysql_fetch_assoc($ath)){
          $arr[]=$author;
      }
      return $arr;
    }else{
      echo "<p><b>Error: ".mysql_error()."</b></p>";
      die();
    }
}
?>

users.xml
Код: xml
<?xml version="1.0" encoding="utf-8"?>
 <Table>
  <Row>
  <Cell>trololoevna</Cell>
  <Cell>Трололоевна</Cell>
  <Cell>Анна</Cell>
  <Cell>Аладиновна</Cell>
  <Cell>Пекин</Cell>
  <Cell>Служба Логистики</Cell>
  <Cell>Специалист по троллям</Cell>
  <Cell>trololoevna@mail.ru</Cell>
  <Cell type="Number">111111</Cell>
  </Row>
  <Row>
  <Cell>ololoev</Cell>
  <Cell>Ололоев</Cell>
  <Cell>Игорь</Cell>
  <Cell>Касмадрыныч</Cell>
  <Cell>Алмата</Cell>
  <Cell>Управление компанией</Cell>
  <Cell>Генеральный директор</Cell>
  <Cell>ololoev@mail.ru</Cell>
  <Cell type="Number">98747598346543</Cell>
  </Row>
</Table>
*

xchesh

  • Захожу иногда
  • 277
  • 10 / 1
Re: Импорт пользователей в Joomla 2.5
« Ответ #5 : 11.03.2013, 12:42:17 »
XML формировал из обычного xls файла средствами excel.
Последний cell(имеющий аттрибут number) является паролем.
Чтобы оставить сообщение,
Вам необходимо Войти или Зарегистрироваться
 

Компонент для Joomla 4 Менеджер Мета Тегов

Автор azm1n

Ответов: 2
Просмотров: 975
Последний ответ 09.05.2025, 11:30:21
от azm1n
Ищу расширение 301 редиректов для Joomla 4

Автор azm1n

Ответов: 1
Просмотров: 1087
Последний ответ 04.05.2025, 22:41:05
от azm1n
Расширения для Joomla для просмотра анонимно историй в Instagram

Автор bgh97079

Ответов: 0
Просмотров: 1097
Последний ответ 24.12.2024, 19:47:43
от bgh97079
Импорт статей

Автор Jenek

Ответов: 1
Просмотров: 2242
Последний ответ 06.07.2023, 16:37:09
от beliyadm
Телефонный справочник для Joomla 4

Автор kunsaid

Ответов: 2
Просмотров: 2631
Последний ответ 28.06.2023, 17:35:43
от kunsaid