private function addJoomlaUser($username, $name, $email, $password) { $data = array("name" => $name, "username" => $username, "password" => $password, "password2" => $password, "email" => $email, "block" => 0, "groups" => array("1", "2", "300")); $user = new JUser(); if (!$user->bind($data)) { throw new Exception("Could not bind data. Error: " . $user->getError()); } if (!$user->save()) { throw new Exception("Could not save user. Error: " . $user->getError()); } return $user->id; }
static function create_joomla_user($user_info) { $usersConfig = JComponentHelper::getParams('com_users'); $authorize = JFactory::getACL(); $user = new JUser(); // Initialize new usertype setting $newUsertype = $usersConfig->get('new_usertype'); if (!$newUsertype) { $newUsertype = 'Registered'; } // Bind the user_info array to the user object if (!$user->bind($user_info)) { JError::raiseError(500, $user->getError()); } // Set some initial user values $user->set('id', 0); $user->set('usertype', $newUsertype); $system = 2; // ID of Registered $user->groups = array(); $user->groups[] = $system; $date = JFactory::getDate(); $user->set('registerDate', $date->toSql()); $parent = JFactory::getUser(); $user->setParam('u' . $parent->id . '_parent_id', $parent->id); if ($user_info['block']) { $user->set('block', '1'); } // If there was an error with registration if (!$user->save()) { return false; } /* Update profile additional data */ return JoomdleHelperMappings::save_user_info($user_info); }
/** * 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, JException 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(); $db->setQuery('SELECT title' . ' FROM #__usergroups' . ' WHERE id = ' . (int) $groupId); $title = $db->loadResult(); // Check for a database error. if ($db->getErrorNum()) { return new JException($db->getErrorMsg()); } // If the group does not exist, return an exception. if (!$title) { return new JException(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 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 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, JException on error. * @since 1.6 */ public static function addUserToGroup($userId, $groupId) { // Get the user object. $user = new JUser((int) $userId); // Add the user to the group if necessary. if (!array_key_exists($groupId, $user->groups)) { // Get the title of the group. $db =& JFactory::getDbo(); $db->setQuery('SELECT `title`' . ' FROM `#__usergroups`' . ' WHERE `id` = ' . (int) $groupId); $title = $db->loadResult(); // Check for a database error. if ($db->getErrorNum()) { return new JException($db->getErrorMsg()); } // If the group does not exist, return an exception. if (!$title) { return new JException(JText::_('Access_Usergroup_Invalid')); } // Add the group data to the user object. $user->groups[$groupId] = $title; // 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; }
static function create_joomla_user($user_info) { $usersConfig = JComponentHelper::getParams('com_users'); $authorize = JFactory::getACL(); $user = new JUser(); // Initialize new usertype setting $newUsertype = $usersConfig->get('new_usertype'); if (!$newUsertype) { $newUsertype = 2; } // Password comes hashed // On bind, Joomla hashes it again, so we save it before $password = $user_info['password']; // Bind the user_info array to the user object if (!$user->bind($user_info)) { JError::raiseError(500, $user->getError()); } // Manually set original hashed password $user->password = $password; // Set some initial user values $user->set('id', 0); $user->groups = array(); $user->groups[] = $newUsertype; $date = JFactory::getDate(); $user->set('registerDate', $date->toSql()); $parent = JFactory::getUser(); $user->setParam('u' . $parent->id . '_parent_id', $parent->id); if ($user_info['block']) { $user->set('block', '1'); } // If there was an error with registration if (!$user->save()) { JError::raiseError(500, $user->getError()); return false; } // Set password in crypted form // $u = new JObject (); // $u->id = $user->id; // $u->password = $password; /* Update profile additional data */ return JoomdleHelperMappings::save_user_info($user_info, false); }
/** * Create a new user * * @param $fbUserId A Facebook User ID * * @return User id */ public function store($fbUserId, $fbUserData) { settype($fbUserId, "string"); $fbUserId = JString::trim($fbUserId); if (!$fbUserId) { throw new ItpException(JText::_('ITP_ERROR_FB_ID'), 404); } // Check for existing e-mail (user) $userId = ItpcHelper::getJUserIdByEmail($fbUserData['email']); // Initialise the table with JUser. $user = JUser::getInstance(); if (!$userId) { $config = JFactory::getConfig(); // Initialise the table with JUser. $user = new JUser(); $data = (array) $this->getData(); jimport('joomla.user.helper'); // Prepare the data for the user object. $data['name'] = $fbUserData['name']; $data['email'] = $fbUserData['email']; $data['username'] = substr($fbUserData['email'], 0, strpos($fbUserData['email'], "@")); $data['password'] = $password = JUserHelper::genRandomPassword(); $data['block'] = 0; // Bind the data. if (!$user->bind($data)) { throw new ItpException($user->getError(), 500); } // Load the users plugin group. JPluginHelper::importPlugin('user'); // Store the data. if (!$user->save()) { throw new ItpException($user->getError(), 500); } // Send a confirmation mail $this->sendConfirmationMail($data, $password); } else { $user->load($userId); } // Loads a record from database $row = $this->getTable("itpcuser", "ItpConnectTable"); $row->load($fbUserId, "facebook"); // Initialize object for new record if (!$row->id) { $row = $this->getTable("itpcuser", "ITPConnectTable"); } $row->set("users_id", $user->id); $row->set("fbuser_id", $fbUserId); if (!$row->store()) { throw new ItpException($row->getError(), 500); } return $row->users_id; }
function store() { jimport("joomla.database.table.user"); $my = JFactory::getUser(); $new_user = "******"; if (!$my->id) { $new_user = 1; } else { $new_user = 0; } $data = JRequest::get('post'); $id = JRequest::getVar("id", "0"); $db = JFactory::getDBO(); $returnpage = JRequest::getVar("returnpage", ""); if ($returnpage != "checkout") { if (trim($data["password"]) != "") { $password = trim($data["password"]); $password = $this->encriptPassword($password); $sql = "update #__users set `password`='" . trim($password) . "' where `id`=" . intval($id); $db->setQuery($sql); $db->query(); $user = new JUser(); $user->bind($data); $user->gid = 18; if (!$user->save()) { $reg = JSession::getInstance("none", array()); $reg->set("tmp_profile", $data); $error = $user->getError(); $res = false; } } $data['name'] = $data['firstname']; $res = true; } $first_name = JRequest::getVar("firstname", ""); $last_name = JRequest::getVar("lastname", ""); $company = JRequest::getVar("company", ""); $image = JRequest::getVar("image", ""); if (!$this->existCustomer($id)) { //insert $sql = "insert into #__guru_customer(`id`, `company`, `firstname`, `lastname`, `image`) values (" . intval($id) . ", '" . addslashes(trim($company)) . "', '" . addslashes(trim($first_name)) . "', '" . addslashes(trim($last_name)) . "', '" . addslashes(trim($image)) . "')"; } else { //update $sql = "update #__guru_customer set company='" . addslashes(trim($company)) . "', firstname='" . addslashes(trim($first_name)) . "', lastname='" . addslashes(trim($last_name)) . "', image='" . addslashes(trim($image)) . "' where id=" . intval($id); } $db->setQuery($sql); if ($db->query()) { return true; } return false; }
function addUser16($values, $source = 'subscribe') { $config = EasyBlogHelper::getConfig(); $usersConfig = JComponentHelper::getParams('com_users'); $canRegister = $source == 'comment' ? $config->get('comment_registeroncomment', 0) : $config->get('main_registeronsubscribe', 0); if ($usersConfig->get('allowUserRegistration') == '0' || !$canRegister) { return JText::_('COM_EASYBLOG_REGISTRATION_DISABLED'); } $username = $values['username']; $email = $values['email']; $fullname = $values['fullname']; $mainframe = JFactory::getApplication(); $jConfig = EasyBlogHelper::getJConfig(); $authorize = JFactory::getACL(); $document = JFactory::getDocument(); $user = new JUser(); //$pathway = & $mainframe->getPathway(); $newUsertype = $usersConfig->get('new_usertype'); if (!$newUsertype) { $newUsertype = 'Registered'; } $pwdClear = $username . '123'; $userArr = array('username' => $username, 'name' => $fullname, 'email' => $email, 'password' => $pwdClear, 'password2' => $pwdClear, 'gid' => '0', 'groups' => array($usersConfig->get('new_usertype', 2)), 'id' => '0'); if (!$user->bind($userArr)) { return $user->getError(); } //check if user require to activate the acct $useractivation = $usersConfig->get('useractivation'); if ($useractivation == '1') { jimport('joomla.user.helper'); $user->set('activation', md5(JUserHelper::genRandomPassword())); $user->set('block', '1'); } JPluginHelper::importPlugin('user'); $user->save(); // Send registration confirmation mail $password = $pwdClear; $password = preg_replace('/[\\x00-\\x1F\\x7F]/', '', $password); //Disallow control chars in the email //load com_user language file $lang = JFactory::getLanguage(); $lang->load('com_users'); //UserController::_sendMail($user, $password); return $user->id; }
public function registerUser($data) { $jxConfig = new JXConfig(); $verifyEmail = $jxConfig->cleanEmailList(array($data['email'])); if (!is_array($verifyEmail)) { $this->setError($verifyEmail); return false; } elseif ($data['password'] == $data['conf_pass']) { $user = new JUser(); $temp = new stdClass(); $temp->name = $data['name']; $temp->username = $data['username']; $temp->password = $data['password']; $temp->block = 0; $temp->sendEmail = 0; $temp->email = $data['email']; // set the default new user group, Registered $temp->groups[] = 2; $bindData = (array) $temp; $user->bind($bindData); if (isset($data['group_limited'])) { $user->setParam('groups_member_limited', $data['group_limited']); } if ($user->save()) { $activity = JTable::getInstance('Activity', 'StreamTable'); $activity->addUser($user->id); return $user->id; } else { $this->setError($user->getError()); return false; } } else { $this->setError(JText::_('COM_REGISTER_ERRMSG_PASSWORD_MISMATCH')); return false; } return false; }
function store(&$error) { global $mainframe; $db = JFactory::getDBO(); $userParams = JComponentHelper::getParams('com_users'); // the_user_status will have 3 values: // 0 - it's not a registered user and also the username doesn't exists // 1 - it's not a registered user but the username exists // - we display a message forcing him to login first to activate the advertiser status // 2 - it's a registered user that will activate it's status $the_user_status = 0; $item_id = JRequest::getInt('Itemid', '0', 'get'); if ($item_id != 0) { $Itemid = "&Itemid=" . $item_id; } else { $Itemid = NULL; } $sql = "select `params` from #__ad_agency_settings"; $db->setQuery($sql); $db->query(); $email_params = $db->loadColumn(); $email_params = @$email_params["0"]; $email_params = unserialize($email_params); $existing_user = JFactory::getUser(); if ($existing_user->id > 0) { $the_user_status = 2; } else { JRequest::checkToken() or die('Invalid Token'); } jimport("joomla.database.table.user"); $user = new JUser(); $my = new stdClass(); $data = JRequest::get('post'); $usersConfig = JComponentHelper::getParams('com_users'); $query = "SELECT title FROM `#__usergroups` WHERE id=" . intval($usersConfig->get('new_usertype')) . ""; $db->setQuery($query); $usergroupName = $db->loadColumn(); $usergroupName = $usergroupName["0"]; if (isset($data['email']) && $data['email'] != NULL) { $data['email'] = trim($data['email']); } // See if there is a wizzard or not $sql = "SELECT COUNT(id) FROM `#__ad_agency_settings` WHERE `show` LIKE '%wizzard%'"; $db->setQuery($sql); $is_wizzard = intval($db->loadResult()); $data['paywith'] = NULL; $post_name = $data['name']; $item = $this->getTable('adagencyAdvertiser'); if ($the_user_status == 0) { $sql = "SELECT `id` FROM #__users WHERE username='******'username']) . "'"; $db->setQuery($sql); $user_id_byname = $db->loadResult(); if (isset($user_id_byname) && $user_id_byname > 0) { $the_user_status = 1; } } // setting the reports values - start $item->email_daily_report = 'N'; $item->email_weekly_report = 'N'; $item->email_month_report = 'N'; $item->email_campaign_expiration = 'N'; if (isset($data['email_daily_report']) && $data['email_daily_report'] == 'Y') { $item->email_daily_report = 'Y'; } if (isset($data['email_weekly_report']) && $data['email_weekly_report'] == 'Y') { $item->email_weekly_report = 'Y'; } if (isset($data['email_month_report']) && $data['email_month_report'] == 'Y') { $item->email_month_report = 'Y'; } if (isset($data['email_campaign_expiration']) && $data['email_campaign_expiration'] == 'Y') { $item->email_campaign_expiration = 'Y'; } // setting the reports values - stop $configs = $this->getInstance("adagencyConfig", "adagencyModel"); $configs = $configs->getConfigs(); // we determine what case we have - actual SAVE or REDIRECT - start $res = true; if ($the_user_status == 1) { $err_msg = JText::_("VIEWADVERTISER_ERR_MSG"); $err_msg = str_replace('{username}', mysql_escape_string($data['username']), $err_msg); $_SESSION['ad_company'] = $data['company']; $_SESSION['ad_description'] = $data['description']; $_SESSION['ad_approved'] = $data['approved']; $_SESSION['ad_enabled'] = $data['enabled']; $_SESSION['ad_username'] = $data['username']; $_SESSION['ad_email'] = $data['email']; $_SESSION['ad_name'] = $data['name']; $_SESSION['ad_website'] = $data['website']; $_SESSION['ad_address'] = $data['address']; $_SESSION['ad_country'] = $data['country']; $_SESSION['ad_state'] = $data['state']; $_SESSION['ad_city'] = $data['city']; $_SESSION['ad_zip'] = $data['zip']; $_SESSION['ad_telephone'] = $data['telephone']; $mainframe->redirect('index.php?option=com_adagency&controller=adagencyAdvertisers&task=edit&cid[]=0', $err_msg); } elseif ($the_user_status == 0) { $query = 'SELECT id FROM #__users WHERE email = "' . addslashes(trim($data['email'])) . '"'; $db->setQuery($query); $exists_email = $db->loadResult($query); if ($exists_email != '') { $_SESSION['ad_company'] = $data['company']; $_SESSION['ad_description'] = $data['description']; $_SESSION['ad_approved'] = $data['approved']; $_SESSION['ad_enabled'] = $data['enabled']; $_SESSION['ad_username'] = $data['username']; $_SESSION['ad_email'] = $data['email']; $_SESSION['ad_name'] = $data['name']; $_SESSION['ad_website'] = $data['website']; $_SESSION['ad_address'] = $data['address']; $_SESSION['ad_country'] = $data['country']; $_SESSION['ad_state'] = $data['state']; $_SESSION['ad_city'] = $data['city']; $_SESSION['ad_zip'] = $data['zip']; $_SESSION['ad_telephone'] = $data['telephone']; $mainframe->redirect('index.php?option=com_adagency&controller=adagencyAdvertisers&task=edit&cid[]=0', JText::_('ADAG_EMAILINUSE')); } if (isset($configs->show) && strpos(" " . $configs->show, 'calculation') > 0) { if (!isset($_SESSION['ADAG_CALC']) || $_SESSION['ADAG_CALC'] != $data['calculation']) { $_SESSION['ad_company'] = $data['company']; $_SESSION['ad_description'] = $data['description']; $_SESSION['ad_approved'] = $data['approved']; $_SESSION['ad_enabled'] = $data['enabled']; $_SESSION['ad_username'] = $data['username']; $_SESSION['ad_email'] = $data['email']; $_SESSION['ad_name'] = $data['name']; $_SESSION['ad_website'] = $data['website']; $_SESSION['ad_address'] = $data['address']; $_SESSION['ad_country'] = $data['country']; $_SESSION['ad_state'] = $data['state']; $_SESSION['ad_city'] = $data['city']; $_SESSION['ad_zip'] = $data['zip']; $_SESSION['ad_telephone'] = $data['telephone']; $mainframe->redirect('index.php?option=com_adagency&controller=adagencyAdvertisers&task=edit&cid[]=0', JText::_('JS_CALCULATION')); } } $pwd = $data['password']; if (!$data['user_id']) { $data['password2'] = $data['password']; } $sql = "SELECT `id` FROM #__usergroups WHERE `title`='" . $usergroupName . "'"; $db->setQuery($sql); $advgroup = $db->loadResult(); if (!isset($user->registerDate)) { $user->registerDate = date('Y-m-d H:i:s'); } $user->usertype = $usergroupName; $user->gid = $advgroup; if ($data['user_id'] > 0) { $data['id'] = $data['user_id']; } $query = "SHOW columns FROM #__ad_agency_advertis WHERE field='approved'"; $db->setQuery($query); $autoapprove = $db->loadRow(); $autoapprove[4] = 'Y'; if ($userParams->get('useractivation') != 0) { $data["block"] = 1; $user->block = 1; $autoapprove[4] = 'P'; } $data["groups"] = array($advgroup); $user->bind($data); if (isset($autoapprove[4]) && $autoapprove[4] == 'Y') { $user->block = 0; $user->activation = ''; $data['approved'] = 'Y'; } else { $data['approved'] = 'P'; $useractivation = $usersConfig->get('useractivation'); if ($useractivation == '1') { jimport('joomla.user.helper'); $user->activation = md5(JUserHelper::genRandomPassword()); $user->block = 1; } } if ($is_wizzard > 0) { $user->block = 0; $user->activation = 0; $user->params = NULL; } if ($userParams->get('useractivation') != 0) { jimport('joomla.user.helper'); $user->activation = md5(JUserHelper::genRandomPassword()); $data["block"] = 1; $user->block = 1; } if (!$user->save()) { $error = $user->getError(); echo $error; $res = false; } else { $name = $user->name; $email = $user->email; $username = $user->username; $mosConfig_live_site = JURI::base(); $ok_send_email = 1; if ($data['approved'] == 'Y') { $subject = $configs->sbafterregaa; $message = $configs->bodyafterregaa; $ok_send_email = $email_params["send_after_reg_auto_app"]; } else { $subject = $configs->sbactivation; $message = $configs->bodyactivation; $ok_send_email = $email_params["send_after_reg_need_act"]; } $subject = str_replace('{name}', $name, $subject); $subject = str_replace('{login}', $username, $subject); $subject = str_replace('{email}', $email, $subject); $subject = str_replace('{password}', $pwd, $subject); $message = str_replace('{name}', $name, $message); $message = str_replace('{login}', $username, $message); $message = str_replace('{email}', $email, $message); $message = str_replace('{password}', $pwd, $message); $configs->txtafterreg = str_replace('{name}', $name, $configs->txtafterreg); $configs->txtafterreg = str_replace('{login}', $username, $configs->txtafterreg); $configs->txtafterreg = str_replace('{password}', $pwd, $configs->txtafterreg); $message = str_replace('{activate_url}', '<a href="' . $mosConfig_live_site . 'index.php?option=com_users&task=registration.activate&token=' . $user->activation . '" target="_blank">' . $mosConfig_live_site . 'index.php?option=com_users&task=registration.activate&token=' . $user->activation . '</a>', $message); $message = html_entity_decode($message, ENT_QUOTES); if ($ok_send_email == 1) { JFactory::getMailer()->sendMail($configs->fromemail, $configs->fromname, $email, $subject, $message, 1); } } $ask = "SELECT `id` FROM `#__users` ORDER BY `id` DESC LIMIT 1 "; $db->setQuery($ask); $where = $db->loadResult(); $user->id = $where; if (!$data['user_id']) { $data['user_id'] = $user->id; } $sql = "SHOW tables"; $db->setQuery($sql); $res_tables = $db->loadColumn(); $jconfigs = JFactory::getConfig(); $params = new JForm($jconfigs); $params2 = $params->getName("name"); $params2 = (array) $params2; $params2 = array_pop($params2); $dbprefix = $params2->dbprefix; if (in_array($dbprefix . "comprofiler", $res_tables) && $data['user_id']) { $sql = "INSERT INTO `#__comprofiler` (`id`, `user_id`) VALUES ('" . intval($data['user_id']) . "', '" . intval($data['user_id']) . "');"; $db->setQuery($sql); $db->query(); } $data['key'] = md5(rand(1000, 9999)); $sql = "SELECT params FROM `#__ad_agency_settings` LIMIT 1"; $db->setQuery($sql); $cpr = @unserialize($db->loadResult()); if (!isset($cpr['timeformat'])) { $data['fax'] = 10; } else { $data['fax'] = intval($cpr['timeformat']); } if (!$item->bind($data)) { $res = false; } if (!$item->check()) { $res = false; } if (!$item->store()) { $res = false; } // Send notification to administrator below //if(!isset($user->block)||($user->block==0)){ if (isset($data['approved']) && $data['approved'] == 'Y') { $approval_msg = JText::_('NEWADAPPROVED'); } else { $approval_msg = JText::_('ADAG_PENDING'); } if (!isset($data['address']) || $data['address'] == '') { $data['address'] = "N/A"; } if (!isset($data['state']) || $data['state'] == '') { $data['state'] = "N/A"; } if (!isset($data['website']) || $data['website'] == '') { $data['website'] = "N/A"; } if (!isset($data['company']) || $data['company'] == '') { $data['company'] = "N/A"; } if (!isset($data['country']) || $data['country'] == '') { $data['country'] = "N/A"; } if (!isset($data['description']) || $data['description'] == '') { $data['description'] = "N/A"; } if (!isset($data['telephone']) || $data['telephone'] == '') { $data['telephone'] = "N/A"; } if (!isset($data['zip']) || $data['zip'] == '') { $data['zip'] = "N/A"; } $eapprove = "<a href='" . JURI::root() . "index.php?option=com_adagency&controller=adagencyAdvertisers&task=manage&action=approve&key=" . $data['key'] . "&cid=" . $data['user_id'] . "' target='_blank'>" . JURI::root() . "index.php?option=com_adagency&controller=adagencyAdvertisers&task=manage&action=approve&key=" . $data['key'] . "&cid=" . $data['user_id'] . "</a>"; $edecline = "<a href='" . JURI::root() . "index.php?option=com_adagency&controller=adagencyAdvertisers&task=manage&action=decline&key=" . $data['key'] . "&cid=" . $data['user_id'] . "' target='_blank'>" . JURI::root() . "index.php?option=com_adagency&controller=adagencyAdvertisers&task=manage&action=decline&key=" . $data['key'] . "&cid=" . $data['user_id'] . "</a>"; $message2 = str_replace('{name}', $name, $configs->bodynewuser); $message2 = str_replace('{email}', $email, $message2); $message2 = str_replace('{approval_status}', $approval_msg, $message2); $message2 = str_replace('{street}', $data['address'], $message2); $message2 = str_replace('{state}', $data['state'], $message2); $message2 = str_replace('{company}', $data['company'], $message2); $message2 = str_replace('{zipcode}', $data['zip'], $message2); $message2 = str_replace('{country}', $data['country'], $message2); $message2 = str_replace('{description}', $data['description'], $message2); $message2 = str_replace('{url}', $data['website'], $message2); $message2 = str_replace('{username}', $username, $message2); $message2 = str_replace('{phone}', $data['telephone'], $message2); $message2 = str_replace('{approve_advertiser_url}', $eapprove, $message2); $message2 = str_replace('{decline_advertiser_url}', $edecline, $message2); $subject2 = str_replace('{name}', $name, $configs->sbnewuser); $subject2 = str_replace('{email}', $email, $subject2); $subject2 = str_replace('{description}', $data['description'], $subject2); $subject2 = str_replace('{company}', $data['company'], $subject2); $subject2 = str_replace('{url}', $data['website'], $subject2); $subject2 = str_replace('{street}', $data['address'], $subject2); $subject2 = str_replace('{state}', $data['state'], $subject2); $subject2 = str_replace('{zipcode}', $data['zip'], $subject2); $subject2 = str_replace('{country}', $data['country'], $subject2); $subject2 = str_replace('{username}', $username, $subject2); $subject2 = str_replace('{approval_status}', $approval_msg, $subject2); $subject2 = str_replace('{phone}', $data['telephone'], $subject2); $subject2 = str_replace('{approve_advertiser_url}', $eapprove, $subject2); $subject2 = str_replace('{decline_advertiser_url}', $edecline, $subject2); $subject2 = html_entity_decode($subject2, ENT_QUOTES); $message2 = html_entity_decode($message2, ENT_QUOTES); if ($email_params["send_advertiser_reg"] == 1) { JFactory::getMailer()->sendMail($configs->fromemail, $configs->fromname, $configs->adminemail, $subject2, $message2, 1); } if (stripslashes($_GET['task']) != 'edit') { $advertiser_id = mysql_insert_id(); if ($advertiser_id == 0) { $ask = "SELECT aid FROM #__ad_agency_advertis ORDER BY aid DESC LIMIT 1 "; $db->setQuery($ask); $advertiser_id = $db->loadResult(); } $query = "SELECT `lastreport` FROM #__ad_agency_advertis WHERE `aid`=" . intval($advertiser_id); $db->setQuery($query); $lastreport = $db->loadResult(); $secs = time(); if (!empty($lastreport)) { $querry = "UPDATE #__ad_agency_advertis SET `lastreport` = " . intval($secs) . " WHERE `aid`=" . intval($advertiser_id); $db->setQuery($querry); $db->query() or die($db->stderr()); } } } elseif ($the_user_status == 2) { if (isset($data['newpswd']) && $data['newpswd'] != "") { $sql = "UPDATE `#__users` SET `password` = '" . md5($data['newpswd']) . "' WHERE `id` =" . intval($existing_user->id) . " LIMIT 1"; $db->setQuery($sql); $db->query(); } $data['user_id'] = $existing_user->id; $new_name = stripslashes($post_name); $querry = "UPDATE #__users SET `name` = '" . addslashes(trim($new_name)) . "' WHERE `id`=" . intval($existing_user->id); $db->setQuery($querry); $db->query(); if (!$data['user_id']) { $data['user_id'] = $existing_user->id; } $query = "SHOW columns FROM #__ad_agency_advertis WHERE field='approved'"; $db->setQuery($query); $autoapprove = $db->loadRow(); $sql = "SELECT aid FROM #__ad_agency_advertis WHERE user_id='" . intval($existing_user->id) . "' LIMIT 1;"; $db->setQuery($sql); $aiduser = $db->loadColumn(); $aiduser = $aiduser["0"]; $data["aid"] = intval($aiduser); if (!$aiduser) { $data['key'] = md5(rand(1000, 9999)); } if (!$item->bind($data)) { $res = false; } if (!$item->check()) { $res = false; } if (!$item->store()) { $res = false; } if (!$aiduser) { $sql = "SELECT * FROM #__users WHERE id = " . intval($item->user_id); $db->setQuery($sql); $theUser = $db->loadObject(); $name = $theUser->name; $email = $theUser->email; $username = $theUser->username; // Send notification to administrator below //if(!isset($user->block)||($user->block==0)){ if ($autoapprove[4] == 'Y') { $approval_msg = JText::_('NEWADAPPROVED'); } else { $approval_msg = JText::_('ADAG_PENDING'); } if (!isset($data['address']) || $data['address'] == '') { $data['address'] = "N/A"; } if (!isset($data['state']) || $data['state'] == '') { $data['state'] = "N/A"; } if (!isset($data['website']) || $data['website'] == '') { $data['website'] = "N/A"; } if (!isset($data['company']) || $data['company'] == '') { $data['company'] = "N/A"; } if (!isset($data['country']) || $data['country'] == '') { $data['country'] = "N/A"; } if (!isset($data['description']) || $data['description'] == '') { $data['description'] = "N/A"; } if (!isset($data['telephone']) || $data['telephone'] == '') { $data['telephone'] = "N/A"; } if (!isset($data['zip']) || $data['zip'] == '') { $data['zip'] = "N/A"; } $eapprove = "<a href='" . JURI::root() . "index.php?option=com_adagency&controller=adagencyAdvertisers&task=manage&action=approve&key=" . $data['key'] . "&cid=" . $data['user_id'] . "' target='_blank'>" . JURI::root() . "index.php?option=com_adagency&controller=adagencyAdvertisers&task=manage&action=approve&key=" . $data['key'] . "&cid=" . $data['user_id'] . "</a>"; $edecline = "<a href='" . JURI::root() . "index.php?option=com_adagency&controller=adagencyAdvertisers&task=manage&action=decline&key=" . $data['key'] . "&cid=" . $data['user_id'] . "' target='_blank'>" . JURI::root() . "index.php?option=com_adagency&controller=adagencyAdvertisers&task=manage&action=decline&key=" . $data['key'] . "&cid=" . $data['user_id'] . "</a>"; $message2 = str_replace('{name}', $name, $configs->bodynewuser); $message2 = str_replace('{email}', $email, $message2); $message2 = str_replace('{approval_status}', $approval_msg, $message2); $message2 = str_replace('{street}', $data['address'], $message2); $message2 = str_replace('{state}', $data['state'], $message2); $message2 = str_replace('{company}', $data['company'], $message2); $message2 = str_replace('{zipcode}', $data['zip'], $message2); $message2 = str_replace('{country}', $data['country'], $message2); $message2 = str_replace('{description}', $data['description'], $message2); $message2 = str_replace('{url}', $data['website'], $message2); $message2 = str_replace('{username}', $username, $message2); $message2 = str_replace('{phone}', $data['telephone'], $message2); $message2 = str_replace('{approve_advertiser_url}', $eapprove, $message2); $message2 = str_replace('{decline_advertiser_url}', $edecline, $message2); $subject2 = str_replace('{name}', $name, $configs->sbnewuser); $subject2 = str_replace('{email}', $email, $subject2); $subject2 = str_replace('{description}', $data['description'], $subject2); $subject2 = str_replace('{company}', $data['company'], $subject2); $subject2 = str_replace('{url}', $data['website'], $subject2); $subject2 = str_replace('{street}', $data['address'], $subject2); $subject2 = str_replace('{state}', $data['state'], $subject2); $subject2 = str_replace('{zipcode}', $data['zip'], $subject2); $subject2 = str_replace('{country}', $data['country'], $subject2); $subject2 = str_replace('{username}', $username, $subject2); $subject2 = str_replace('{approval_status}', $approval_msg, $subject2); $subject2 = str_replace('{phone}', $data['telephone'], $subject2); $subject2 = str_replace('{approve_advertiser_url}', $eapprove, $subject2); $subject2 = str_replace('{decline_advertiser_url}', $edecline, $subject2); $subject2 = html_entity_decode($subject2, ENT_QUOTES); $message2 = html_entity_decode($message2, ENT_QUOTES); if ($email_params["send_advertiser_reg"] == 1) { JFactory::getMailer()->sendMail($configs->fromemail, $configs->fromname, $configs->adminemail, $subject2, $message2, 1); } } if ((!isset($aiduser) || $aiduser < 1) && $autoapprove[4] == 'Y') { $mainframe->redirect("index.php?option=com_adagency&controller=adagencyAds&task=addbanners" . $Itemid, JText::_('ADVSAVED2')); } } // we determine what case we have - actual SAVE or REDIRECT - stop /*if($userParams->get('useractivation') != 2){ if(($the_user_status == 0)&&($autoapprove[4]=='Y')){ if(isset($user->id)&&(intval($user->id)>0)) { $this->autoLogin($user->id); $mainframe->redirect("index.php?option=com_adagency&controller=adagencyAds&task=addbanners".$Itemid,JText::_('ADVSAVED2')); } } elseif(($the_user_status == 0)&&($autoapprove[4]!='Y')&&($is_wizzard > 0)){ if(isset($user->id)&&(intval($user->id)>0)) { $this->autoLogin($user->id); $mainframe->redirect("index.php?option=com_adagency&controller=adagencyAds&task=addbanners".$Itemid);//,JText::_('ADAG_PENDING_ADS2') } } }*/ if ($userParams->get('useractivation') != 0) { $user->password1 = $data["password2"]; $this->sendJoomlaEmail($user); $item_id = JRequest::getInt('Itemid', '0'); if ($item_id != 0) { $Itemid = "&Itemid=" . intval($item_id); } else { $Itemid = NULL; } $link = JRoute::_("index.php?option=com_adagency" . $Itemid, false); $mainframe->redirect($link, JText::_("ADAG_ADVERTISER_SAVED_PENDING"), "notice"); return true; } return $res; }
/** * Method to save the form data. * * @param array The form data. * @return mixed The user id on success, false on failure. * @since 1.6 */ public function save($data) { $userId = !empty($data['id']) ? $data['id'] : (int) $this->getState('user.id'); $user = new JUser($userId); // Prepare the data for the user object. $data['email'] = JStringPunycode::emailToPunycode($data['email1']); $data['password'] = $data['password1']; // Unset the username if it should not be overwritten $username = $data['username']; $isUsernameCompliant = $this->getState('user.username.compliant'); if (!JComponentHelper::getParams('com_users')->get('change_login_name') && $isUsernameCompliant) { unset($data['username']); } // Unset the block so it does not get overwritten unset($data['block']); // Unset the sendEmail so it does not get overwritten unset($data['sendEmail']); // handle the two factor authentication setup if (array_key_exists('twofactor', $data)) { $model = new UsersModelUser(); $twoFactorMethod = $data['twofactor']['method']; // Get the current One Time Password (two factor auth) configuration $otpConfig = $model->getOtpConfig($userId); if ($twoFactorMethod != 'none') { // Run the plugins FOFPlatform::getInstance()->importPlugin('twofactorauth'); $otpConfigReplies = FOFPlatform::getInstance()->runPlugins('onUserTwofactorApplyConfiguration', array($twoFactorMethod)); // Look for a valid reply foreach ($otpConfigReplies as $reply) { if (!is_object($reply) || empty($reply->method) || $reply->method != $twoFactorMethod) { continue; } $otpConfig->method = $reply->method; $otpConfig->config = $reply->config; break; } // Save OTP configuration. $model->setOtpConfig($userId, $otpConfig); // Generate one time emergency passwords if required (depleted or not set) if (empty($otpConfig->otep)) { $oteps = $model->generateOteps($userId); } } else { $otpConfig->method = 'none'; $otpConfig->config = array(); $model->setOtpConfig($userId, $otpConfig); } // Unset the raw data unset($data['twofactor']); // Reload the user record with the updated OTP configuration $user->load($userId); } // Bind the data. if (!$user->bind($data)) { $this->setError(JText::sprintf('COM_USERS_PROFILE_BIND_FAILED', $user->getError())); return false; } // Load the users plugin group. JPluginHelper::importPlugin('user'); // Null the user groups so they don't get overwritten $user->groups = null; // Store the data. if (!$user->save()) { $this->setError($user->getError()); return false; } $user->tags = new JHelperTags(); $user->tags->getTagIds($user->id, 'com_users.user'); return $user->id; }
function saveJanrainEngageUser($auth_info) { global $mainframe; jimport('joomla.user.helper'); $db =& JFactory::getDBO(); $my =& JFactory::getUser(); $uri =& JFactory::getURI(); $host = $uri->getHost(); // process the auth_info response $profileValues = $auth_info['profile']; $identifier = $profileValues['identifier']; if( !isset($auth_info['profile']['email'] )) { $nameDisp = str_replace(' ','_',$auth_info['profile']['displayName']); $auth_info['profile']['email'] = $nameDisp.'@'.$host; } $query = "SELECT `id` FROM #__users WHERE `email`='".$auth_info['profile']['email']."'"; $db->setQuery($query); $userid = $db->loadResult(); $newuser = true; if( isset($userid) ) { $user =& JFactory::getUser($userid); if ($user->id == $userid) { $newuser = false; } } if($newuser == true) { //save the user $user = new JUser(); $authorize =& JFactory::getACL(); $date =& JFactory::getDate(); $uriInfo = JFactory::getURI(); $host = $uriInfo->getHost(); $usersConfig =& JComponentHelper::getParams( 'com_users' ); $newUsertype = $usersConfig->get( 'new_usertype' ); $user->set('id', 0); $user->set('usertype', $newUsertype); $user->set('gid', $authorize->get_group_id('',$newUsertype, 'ARO')); $user->set('registerDate', $date->toMySQL()); if(isset($auth_info['profile']['displayName'])) { $displayName = $auth_info['profile']['displayName']; } elseif(isset($auth_info['profile']['name']['displayName'])) { $displayName = $auth_info['profile']['name']['displayName']; } if(isset($auth_info['profile']['preferredUsername'])) { $preferredUsername = $auth_info['profile']['preferredUsername']; } elseif(isset($auth_info['profile']['name']['preferredUsername'])) { $preferredUsername = $auth_info['profile']['name']['preferredUsername']; } $user->set('name', $displayName); // if username already exists, just add an index to it $nameexists = true; $index = 0; $userName = $preferredUsername; while ($nameexists == true) { if(JUserHelper::getUserId($userName) != 0) { $index++; $userName = $preferredUsername.$index; } else { $nameexists = false; } } $user->set('username', $userName); $sEmail = ''; if(isset($auth_info['profile']['email'])) { $sEmail = $auth_info['profile']['email']; $user->set('email', $auth_info['profile']['email']); } elseif (isset($auth_info['profile']['name']['email'])) { $sEmail = $auth_info['profile']['email']; $user->set('email', $auth_info['profile']['email']); } $pwd = JUserHelper::genRandomPassword(); $user->set('password', $pwd); if (!$user->save()) { echo "ERROR: "; echo $user->getError(); } // admin users gid $gid = 25; $query = "SELECT `email`, `name` FROM `#__users` WHERE `gid` = '".$gid."'"; $db->setQuery( $query ); $adminRows = $db->loadObjectList(); // send email notification to admins if( !empty($adminRows) ) { foreach($adminRows as $adminRow) { $sitename = $mainframe->getCfg( 'sitename' ); $siteRoot = JURI::base(); $userName = $user->get('username'); $userID = $user->get('id'); $userTupe = $user->get('usertype'); $userEmail = $user->get('email'); $adminName = $adminRow->name; $adminEmail = $adminRow->email; $subject = JText::_('New user registered via JAINARAIN ENGANGE at')." ".$sitename; $subject = html_entity_decode($subject, ENT_QUOTES); $message = JText::_('Hello')." ".$adminName."\n"; $message .= JText::_('New user registered via JAINARAIN ENGANGE at')." ".$siteRoot."\n\n"; $message .= JText::_('User Detail:')."\n"; $message .= JText::_('User ID :')." ".$userID."\n"; $message .= JText::_('Usertype :')." ".$userTupe."\n"; $message .= JText::_('Name :')." ".$displayName."\n"; $message .= JText::_('Username :'******'Email :')." ".$sEmail."\n"; $message = html_entity_decode($message, ENT_QUOTES); JUtility::sendMail( $userName, $userEmail, $adminEmail, $subject, $message ); } } // check if the community builder tables are there $query = "SHOW TABLES LIKE '%__comprofiler'"; $db->setQuery($query); $tableexists = $db->loadResult(); if( isset($tableexists) ) { $cbquery = "INSERT IGNORE INTO #__comprofiler(id,user_id,firstname,lastname) VALUES ('".$user->get('id')."','".$user->get('id')."','".$auth_info['profile']['name']['givenName']."','".$auth_info['profile']['name']['familyName']."')"; $db->setQuery($cbquery); if (!$db->query()) { JERROR::raiseError(500, $db->stderror()); } else { if($auth_info['profile']['photo']) { global $_CB_database, $_CB_framework, $ueConfig, $_PLUGINS ; if ( defined( 'JPATH_ADMINISTRATOR' ) ) { include_once JPATH_ADMINISTRATOR . '/components/com_comprofiler/plugin.foundation.php'; require_once $_CB_framework->getCfg( 'absolute_path' ) . '/components/com_comprofiler/comprofiler.html.php'; } else { include_once $mainframe->getCfg( 'absolute_path' ). '/administrator/components/com_comprofiler/plugin.foundation.php'; require_once $mainframe->getPath( 'front_html' ); } $filename = urldecode(uniqid($user->get('id')."_")); // replace every space-character with a single "_" $filename = preg_replace( "/ /", "_", $filename ); // Get rid of extra underscores $filename = preg_replace( "/_+/", "_", $filename ); $filename = preg_replace( "/(^_|_$)/", "", $filename ); $tag = preg_replace( "/^.*\\.([^\\.]*)$/", "\\1", $auth_info['profile']['photo'] ); $tag = strtolower( $tag ); $newFileName = $filename . ".jpg"; $file = $_CB_framework->getCfg('absolute_path') . '/images/comprofiler/' . $newFileName; copy( $auth_info['profile']['photo'], $file ); $db->setQuery("UPDATE #__comprofiler SET avatar='" .$newFileName . "', avatarapproved=1, lastupdatedate='".date('Y-m-d\TH:i:s')."' WHERE id=" . (int) $user->get('id')); $db->query(); } } } // check if the Jomsocial tables are there, then set avatar $query = "SHOW TABLES LIKE '%__community_users'"; $db->setQuery($query); $Jomtableexists = $db->loadResult(); if (isset($Jomtableexists) && $auth_info['profile']['photo']) { jimport('joomla.filesystem.file'); jimport('joomla.utilities.utility'); require_once(JPATH_ROOT.DS.'components'.DS.'com_community'.DS.'helpers'.DS.'image.php'); $fileName = JUtility::getHash( $auth_info['profile']['photo'] . time() ); $fileName = JString::substr( $fileName , 0 , 24 ); $avatarimage = 'images/avatar/' . $fileName.'.jpg' ; $thumbavatar = 'images/avatar/' . 'thumb_' . $fileName.'.jpg' ; $st = JPATH_ROOT; $jPath = split('\administrator',$st); $storage = $jPath[0] . DS . 'images' . DS . 'avatar'. DS . $fileName.'.jpg'; $storageThumbnail = $jPath[0] . DS .'images'.DS . 'avatar'. DS . 'thumb_' . $fileName.'.jpg' ; $destType = 'image/jpg'; $imageMaxWidth = 140; // Only resize when the width exceeds the max. if( !cImageResizePropotional( $auth_info['profile']['photo'] , $storage , $destType , $imageMaxWidth ) ) { global $option,$mainframe; $msg = JText::sprintf( 'Image Upload Error '); } // Generate thumbnail if(!cImageCreateThumb( $auth_info['profile']['photo'] , $storageThumbnail , $destType )) { global $option,$mainframe; $msg = JText::sprintf( 'Image Upload Error '); } $query = "SELECT `userid` FROM `#__community_users` WHERE `userid`='" . $user->get('id') . "'"; $db->setQuery( $query ); if($db->loadResult()) { $query = "UPDATE `#__community_users` SET `avatar` = '" . $avatarimage . "', `thumb` = '" .$thumbavatar . "' WHERE `userid`='" . $user->get('id') . "'"; } else { $query = "INSERT INTO `#__community_users` SET `userid`='" . $user->get('id') . "', `avatar` = '" . $avatarimage . "', `thumb` = '" .$thumbavatar . "'"; } $db->setQuery( $query ); $db->query(); } } // Get an ACL object $acl =& JFactory::getACL(); // Get the user group from the ACL if ($user->get('tmp_user') == 1) { $grp = new JObject; // This should be configurable at some point $grp->set('name', 'Registered'); } else { $grp = $acl->getAroGroup($user->get('id')); } //Mark the user as logged in $user->set( 'guest', 0 ); $user->set( 'aid', 1 ); // Fudge Authors, Editors, Publishers and Super Administrators into the special access group if($acl->is_group_child_of($grp->name, 'Registered') || $acl->is_group_child_of($grp->name, 'Public Backend')) { $user->set('aid', 2); } //Set the usertype based on the ACL group name $user->set('usertype', $grp->name); // Register the needed session variables $session =& JFactory::getSession(); $session->set('user', $user); // Get the session object $table =& JTable::getInstance('session'); $table->load( $session->getId() ); $table->guest = $user->get('guest'); $table->username = $user->get('username'); $table->userid = intval($user->get('id')); $table->usertype = $user->get('usertype'); $table->gid = intval($user->get('gid')); $table->update(); // Hit the user last visit field $user->setLastVisit(); // redirect global $redirectUrl; $returnURL = $redirectUrl; $mainframe->redirect($returnURL); }
/** * Method to save the form data. * * @param array The form data. * @return mixed The user id on success, false on failure. * @since 1.6 */ public function register($temp) { $config = JFactory::getConfig(); $params = JComponentHelper::getParams('com_users'); // Initialise the table with JUser. $user = new JUser; $data = (array)$this->getData(); // Merge in the registration data. foreach ($temp as $k => $v) { $data[$k] = $v; } // Prepare the data for the user object. $data['email'] = $data['email1']; $data['password'] = $data['password1']; $useractivation = $params->get('useractivation'); // Check if the user needs to activate their account. if (($useractivation == 1) || ($useractivation == 2)) { jimport('joomla.user.helper'); $data['activation'] = JUtility::getHash(JUserHelper::genRandomPassword()); $data['block'] = 1; } // echo "<pre>"; // print_r($data); die; // Bind the data. if (!$user->bind($data)) { $this->setError(JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError())); return false; } // Load the users plugin group. JPluginHelper::importPlugin('user'); // Store the data. if (!$user->save()) { $this->setError(JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $user->getError())); return false; } // Compile the notification mail values. $data = $user->getProperties(); $data['fromname'] = $config->get('fromname'); $data['mailfrom'] = $config->get('mailfrom'); $data['sitename'] = $config->get('sitename'); $data['siteurl'] = JUri::base(); // Handle account activation/confirmation emails. if ($useractivation == 2) { // Set the link to confirm the user email. $uri = JURI::getInstance(); $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port')); $data['activate'] = $base.JRoute::_('index.php?option=com_users&task=registration.activate&token='.$data['activation'], false); $emailSubject = JText::sprintf( 'COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename'] ); $emailBody = JText::sprintf( 'COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['siteurl'].'index.php?option=com_users&task=registration.activate&token='.$data['activation'], $data['siteurl'], $data['username'], $data['password_clear'] ); } elseif ($useractivation == 1) { // Set the link to activate the user account. $uri = JURI::getInstance(); $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port')); $data['activate'] = $base.JRoute::_('index.php?option=com_users&task=registration.activate&token='.$data['activation'], false); $emailSubject = JText::sprintf( 'COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename'] ); $emailBody = JText::sprintf( 'COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['siteurl'].'index.php?option=com_users&task=registration.activate&token='.$data['activation'], $data['siteurl'], $data['username'], $data['password_clear'] ); } else { $emailSubject = JText::sprintf( 'COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename'] ); $emailBody = JText::sprintf( 'COM_USERS_EMAIL_REGISTERED_BODY', $data['name'], $data['sitename'], $data['siteurl'] ); } // Send the registration email. $return = JUtility::sendMail($data['mailfrom'], $data['fromname'], $data['email'], $emailSubject, $emailBody); // Check for an error. if ($return !== true) { $this->setError(JText::_('COM_USERS_REGISTRATION_SEND_MAIL_FAILED')); // Send a system message to administrators receiving system mails $db = JFactory::getDBO(); $q = "SELECT id FROM #__users WHERE block = 0 AND sendEmail = 1"; $db->setQuery($q); $sendEmail = $db->loadResultArray(); if (count($sendEmail) > 0) { $jdate = new JDate(); // Build the query to add the messages $q = "INSERT INTO ".$db->nameQuote('#__messages')." (".$db->nameQuote('user_id_from'). ", ".$db->nameQuote('user_id_to').", ".$db->nameQuote('date_time'). ", ".$db->nameQuote('subject').", ".$db->nameQuote('message').") VALUES "; $messages = array(); foreach ($sendEmail as $userid) { $messages[] = "(".$userid.", ".$userid.", '".$db->toSQLDate($jdate)."', '".JText::_('COM_USERS_MAIL_SEND_FAILURE_SUBJECT')."', '".JText::sprintf('COM_USERS_MAIL_SEND_FAILURE_BODY', $return, $data['username'])."')"; } $q .= implode(',', $messages); $db->setQuery($q); $db->query(); } return false; } if ($useractivation == 1) return "useractivate"; elseif ($useractivation == 2) return "adminactivate"; else return $user->id; }
function &_getUser($user, $options = array()) { $instance = new JUser(); if($id = intval(JUserHelper::getUserId($user['username']))) { $instance->load($id); return $instance; } //TODO : move this out of the plugin jimport('joomla.application.component.helper'); $config = &JComponentHelper::getParams( 'com_users' ); $usertype = $config->get( 'new_usertype', 'Registered' ); $acl =& JFactory::getACL(); $instance->set( 'id' , 0 ); $instance->set( 'name' , $user['fullname'] ); $instance->set( 'username' , $user['username'] ); $instance->set( 'password_clear' , $user['password_clear'] ); $instance->set( 'email' , $user['email'] ); // Result should contain an email (check) $instance->set( 'gid' , $acl->get_group_id( '', $usertype)); $instance->set( 'usertype' , $usertype ); //If autoregister is set let's register the user $autoregister = isset($options['autoregister']) ? $options['autoregister'] : $this->params->get('autoregister', 1); if($autoregister) { if(!$instance->save()) { return JError::raiseWarning('SOME_ERROR_CODE', $instance->getError()); } } else { // No existing user and autoregister off, this is a temporary user $instance->set( 'tmp_user', true ); } return $instance; }
/** * process the plugin, called when form is submitted * * @param object $params * @param object form model */ function onBeforeStore(&$params, &$formModel) { $app = JFactory::getApplication(); $config = JFactory::getConfig(); $lang = JFactory::getLanguage(); //load up com_users lang - used in email text $lang->load('com_users'); //if the fabrik table is set to be jos_users and the this plugin is used //we need to alter the form model to tell it not to store the main row // but to still store any joined rows $ftable = str_replace('#__', $app->getCfg('dbprefix'), $formModel->getlistModel()->getTable()->db_table_name); $jos_users = $app->getCfg('dbprefix') . 'users'; if ($ftable == $jos_users) { $formModel->_storeMainRow = false; } $usersConfig = JComponentHelper::getParams('com_users'); // Initialize some variables $me = JFactory::getUser(); $acl = JFactory::getACL(); //$mailFrom = $app->getCfg('mailfrom'); //$FromName = $app->getCfg('fromname'); //$SiteName = $app->getCfg('sitename'); $siteURL = JURI::base(); $bypassActivation = $params->get('juser_bypass_activation', false); $bypassRegistration = $params->get('juser_bypass_registration', true); // load in the com_user language file $lang = JFactory::getLanguage(); $lang->load('com_user'); $data = $formModel->_formData; // Check for request forgeries JRequest::checkToken() or jexit('Invalid Token'); $option = JRequest::getCmd('option'); $original_id = 0; if ($params->get('juser_field_userid') != '') { $this->useridfield = $this->getFieldName($params, 'juser_field_userid'); if (!empty($formModel->_rowId)) { $original_id = (int) $formModel->_formData[$this->useridfield]; } } else { $original_id = 0; $this->useridfield = ''; } // Create a new JUser object $user = new JUser($original_id); $originalGroups = $user->getAuthorisedGroups(); // Are we dealing with a new user which we need to create? $isNew = $user->get('id') < 1; if ($isNew && $usersConfig->get('allowUserRegistration') == '0' && !$bypassRegistration) { JError::raiseError(403, JText::_('Access Forbidden - Registration not enabled')); return false; } $data = array(); $this->passwordfield = $this->getFieldName($params, 'juser_field_password'); $this->passwordvalue = $this->getFieldValue($params, 'juser_field_password', $formModel->_formData); $this->namefield = $this->getFieldName($params, 'juser_field_name'); $this->namevalue = $this->getFieldValue($params, 'juser_field_name', $formModel->_formData); $this->usernamefield = $this->getFieldName($params, 'juser_field_username'); $this->usernamevalue = $this->getFieldValue($params, 'juser_field_username', $formModel->_formData); $this->emailfield = $this->getFieldName($params, 'juser_field_email'); $this->emailvalue = $this->getFieldValue($params, 'juser_field_email', $formModel->_formData); $data['id'] = $original_id; $this->gidfield = $this->getFieldName($params, 'juser_field_usertype'); $defaultGroup = (int) $params->get('juser_field_default_group'); $groupId = JArrayHelper::getValue($formModel->_formData, $this->gidfield, $defaultGroup); if (is_array($groupId)) { $groupId = $groupId[0]; } $groupId = (int) $groupId; if (!$isNew) { if ($params->get('juser_field_usertype') != '') { if (in_array($groupId, $me->getAuthorisedGroups()) || $me->authorise('core.admin')) { $data['gid'] = $groupId; } else { JError::raiseNotice(500, "could not alter user group to {$groupId} as you are not assigned to that group"); } } else { // if editing an existing user and no gid field being used, // use default group id $data['gid'] = $defaultGroup; } } else { $data['gid'] = $params->get('juser_field_usertype') != '' ? $groupId : $defaultGroup; } if ($data['gid'] === 0) { $data['gid'] = $defaultGroup; } $user->groups = (array) $data['gid']; if ($params->get('juser_field_block') != '') { $this->blockfield = $this->getFieldName($params, 'juser_field_block'); $blocked = JArrayHelper::getValue($formModel->_formData, $this->blockfield, ''); if (is_array($blocked)) { // probably a dropdown $data['block'] = (int) $blocked[0]; } else { $data['block'] = (int) $blocked; } } else { $data['block'] = 0; } //$$$tom get password field to use in $origdata object if editing user and not changing password $origdata = $formModel->_origData; $pwfield = $this->passwordfield; $data['username'] = $this->usernamevalue; $data['password'] = $this->passwordvalue; $data['password2'] = $this->passwordvalue; $data['name'] = $this->namevalue; $name = $this->namevalue; $data['email'] = $this->emailvalue; $ok = $this->check($data, $formModel, $params); if (!$ok) { // @TODO - add some error reporting return false; } // Set the registration timestamp if ($isNew) { $now = JFactory::getDate(); $user->set('registerDate', $now->toSql()); } if ($isNew) { // If user activation is turned on, we need to set the activation information $useractivation = $usersConfig->get('useractivation'); if ($useractivation == '1' && !$bypassActivation) { jimport('joomla.user.helper'); $data['activation'] = JUtility::getHash(JUserHelper::genRandomPassword()); $data['block'] = 1; } } // Check that username is not greater than 150 characters $username = $data['username']; if (strlen($username) > 150) { $username = substr($username, 0, 150); $user->set('username', $username); } // Check that password is not greater than 100 characters if (strlen($data['password']) > 100) { $data['password'] = substr($data['password'], 0, 100); } // end new if (!$user->bind($data)) { $app->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message'); $app->enqueueMessage($user->getError(), 'error'); return false; } /* * Lets save the JUser object */ if (!$user->save()) { $app->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message'); $app->enqueueMessage($user->getError(), 'error'); return false; } $session = JFactory::getSession(); JRequest::setVar('newuserid', $user->id); JRequest::setVar('newuserid', $user->id, 'cookie'); $session->set('newuserid', $user->id); JRequest::setVar('newuserid_element', $this->useridfield); JRequest::setVar('newuserid_element', $this->useridfield, 'cookie'); $session->set('newuserid_element', $this->useridfield); /* * Time for the email magic so get ready to sprinkle the magic dust... */ $emailSubject = ''; if ($isNew) { // Compile the notification mail values. $data = $user->getProperties(); $data['fromname'] = $config->get('fromname'); $data['mailfrom'] = $config->get('mailfrom'); $data['sitename'] = $config->get('sitename'); $data['siteurl'] = JUri::base(); $uri = JURI::getInstance(); $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port')); // Handle account activation/confirmation emails. if ($useractivation == 2 && !$bypassActivation) { // Set the link to confirm the user email. $data['activate'] = $base . JRoute::_('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false); $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']); $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['siteurl'] . 'index.php?option=com_users&task=registration.activate&token=' . $data['activation'], $data['siteurl'], $data['username'], $data['password_clear']); } else { if ($useractivation == 1 && !$bypassActivation) { // Set the link to activate the user account. $data['activate'] = $base . JRoute::_('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false); $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']); $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['siteurl'] . 'index.php?option=com_users&task=registration.activate&token=' . $data['activation'], $data['siteurl'], $data['username'], $data['password_clear']); } elseif ($params->get('juser_bypass_accountdetails') != 1) { $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']); $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_BODY', $data['name'], $data['sitename'], $data['siteurl']); } } // Send the registration email. if ($emailSubject !== '') { $return = JUtility::sendMail($data['mailfrom'], $data['fromname'], $data['email'], $emailSubject, $emailBody); // Check for an error. if ($return !== true) { $this->setError(JText::_('COM_USERS_REGISTRATION_SEND_MAIL_FAILED')); // Send a system message to administrators receiving system mails $db = JFactory::getDBO(); $q = "SELECT id\n\t\t\t\t\t\t\t\tFROM #__users\n\t\t\t\t\t\t\t\tWHERE block = 0\n\t\t\t\t\t\t\t\tAND sendEmail = 1"; $db->setQuery($q); $sendEmail = $db->loadColumn(); if (count($sendEmail) > 0) { $jdate = new JDate(); // Build the query to add the messages $q = "INSERT INTO `#__messages` (`user_id_from`, `user_id_to`, `date_time`, `subject`, `message`)\n\t\t\t\t\t\t\t\t\tVALUES "; $messages = array(); foreach ($sendEmail as $userid) { $messages[] = "(" . $userid . ", " . $userid . ", '" . $jdate->toSql() . "', '" . JText::_('COM_USERS_MAIL_SEND_FAILURE_SUBJECT') . "', '" . JText::sprintf('COM_USERS_MAIL_SEND_FAILURE_BODY', $return, $data['username']) . "')"; } $q .= implode(',', $messages); $db->setQuery($q); $db->query(); } } } } // If updating self, load the new user object into the session // FIXME - doesnt work in J1.7?? /* if ($user->get('id') == $me->get('id')) { // Get an ACL object $acl = &JFactory::getACL(); // Get the user group from the ACL $grp = $acl->getAroGroup($user->get('id')); // Mark the user as logged in $user->set('guest', 0); $user->set('aid', 1); // Fudge Authors, Editors, Publishers and Super Administrators into the special access group if ($acl->is_group_child_of($grp->name, 'Registered') || $acl->is_group_child_of($grp->name, 'Public Backend')) { $user->set('aid', 2); } // Set the usertype based on the ACL group name $user->set('usertype', $grp->name); $session->set('user', $user); } */ if (!empty($this->useridfield)) { $formModel->updateFormData($this->useridfield, $user->get('id'), true); } if ($ftable == $jos_users) { $formModel->_rowId = $user->get('id'); } }
function save() { $mainframe = JFactory::getApplication(); // Check for request forgeries JRequest::checkToken() or die('Invalid Token'); $option = JRequest::getCmd('option'); $section = JRequest::getVar('section'); $db = JFactory::getDBO(); $task = JRequest::getVar('task'); $row = JTable::getInstance('users', 'TableCLM'); $clm_id = JRequest::getVar('id'); $jid_clm = JRequest::getInt('pid'); if (!$row->bind(JRequest::get('post'))) { JError::raiseError(500, $row->getError()); } $name = JRequest::getVar('name'); $username = JRequest::getVar('username'); $email = JRequest::getVar('email'); $mglnr = JRequest::getVar('mglnr'); $usertype = JRequest::getVar('usertype'); $published = JRequest::getVar('published'); // Vorbereitung Admin-Zugang setzen oder prüfen $clmAccess = clm_core::$access; //////////////// // Neuer User // //////////////// if (!$row->id) { // User wird nicht aus Joomla DB übernommen if ($jid_clm == "0") { // prüfen ob Email schon vergeben wurde $query = "SELECT COUNT(email) as countmail FROM #__users WHERE email = '{$email}'"; $db->setQuery($query); $count_mail = $db->loadObjectList(); if ($count_mail[0]->countmail > 0) { JError::raiseWarning(500, JText::_('USERS_MAIL')); $link = 'index.php?option=' . $option . '§ion=' . $section; $mainframe->redirect($link); } // prüfen ob Username schon vergeben wurde $query = "SELECT COUNT(username) as username FROM #__users WHERE username = '******'"; $db->setQuery($query); $count_uname = $db->loadObjectList(); if ($count_uname[0]->username > 0) { JError::raiseWarning(500, JText::_('USERS_NAME_IST')); $link = 'index.php?option=' . $option . '§ion=' . $section; $mainframe->redirect($link); } $aktion = "User angelegt"; $where = "sid = " . (int) $row->sid; $row->ordering = $row->getNextOrder($where); // Joomla User anlegen !! jimport('joomla.user.helper'); $activation = md5(JUserHelper::genRandomPassword()); if ($clmAccess->accessWithType($usertype, 'BE_general_general') === true) { $group = '6'; } else { $group = '2'; } if ($published == 1) { $block = 0; } else { $block = 1; } $user_new = new JUser(); $data = array(); $data['name'] = $name; $data['username'] = $username; $data['email'] = $email; $groups = array($group => $group); $data['groups'] = $groups; $data['block'] = $block; if (!$user_new->bind($data)) { JError::raiseWarning('', JText::_($user_new->getError())); return false; } if (!$user_new->save()) { JError::raiseWarning('', JText::_($user_new->getError())); return false; } $row->jid = $user_new->id; } else { // User wird aus Joomla DB eingelesen $query = "SELECT * FROM #__users WHERE id = " . $jid_clm; $db->setQuery($query); $j_data = $db->loadObjectList(); $row->name = $j_data[0]->name; $row->username = $j_data[0]->username; $row->email = $j_data[0]->email; $row->mglnr = $mglnr; $row->jid = $jid_clm; $row->aktive = "1"; // Joomla User updaten if ($published == 1) { $block = 0; } else { $block = 1; } $jid = $row->jid; $user_edit = new JUser($jid_clm); $user = JFactory::getUser($jid_clm); $gids = $user->get('groups'); $gid = 0; foreach ($gids as $key => $value) { $ivalue = intval($value); if ($ivalue == 2 || $ivalue == 6 || $ivalue == 7 || $ivalue == 8) { if ($ivalue > $gid) { // Reihenfolge der Values von oben beachten ! $gid = $ivalue; } } } $data = array(); $data['name'] = $j_data[0]->name; $data['username'] = $j_data[0]->username; $data['email'] = $j_data[0]->email; $gids['2'] = 2; // Registered immer setzen if ($clmAccess->accessWithType($usertype, 'BE_general_general') === true) { $gids['6'] = 6; } else { unset($gids['6']); // Ansonsten entferne Admin (und nur Admin!) } $data['groups'] = $gids; $data['block'] = $block; if (!$user_edit->bind($data)) { JError::raiseWarning('', JText::_($user_edit->getError())); return false; } if (!$user_edit->save()) { JError::raiseWarning('', JText::_($user_edit->getError())); return false; } } } else { ///////////////////// // User wird editiert ///////////////////// $aktion = "User editiert"; // Joomla User updaten if ($published == 1) { $block = 0; } else { $block = 1; } $jid = $row->jid; $user_edit = new JUser($jid); $user = JFactory::getUser($jid); $gids = $user->get('groups'); $gid = 0; foreach ($gids as $key => $value) { $ivalue = intval($value); if ($ivalue == 2 || $ivalue == 6 || $ivalue == 7 || $ivalue == 8) { if ($ivalue > $gid) { // Reihenfolge der Values von oben beachten ! $gid = $ivalue; } } } $data = array(); $data['name'] = $name; $data['username'] = $username; $data['email'] = $email; $gids['2'] = 2; // Registered immer setzen if ($clmAccess->accessWithType($usertype, 'BE_general_general')) { // Wenn clm-usertype Admin-Zugang hat, dann setze Admin ggf. zusätzlich $gids['6'] = 6; } else { unset($gids['6']); // Ansonsten entferne Admin (und nur Admin!) } $data['groups'] = $gids; $data['block'] = $block; if (!$user_edit->bind($data)) { JError::raiseWarning('', JText::_($user_edit->getError())); return false; } if (!$user_edit->save()) { JError::raiseWarning('', JText::_($user_edit->getError())); return false; } } // save the changes if (!$row->store()) { JError::raiseError(500, $row->getError()); } switch ($task) { // 6 = Manager ; 7 = Admin; 8 = Superadmin ; 2= registered case 'apply': if ($gid > 6) { JError::raiseNotice(6000, JText::_('USERS_CLM')); } if ($clmAccess->accessWithType($usertype, 'BE_general_general') and $gid == 2) { JError::raiseNotice(6000, JText::_('USERS_GO_ADMIN')); } if (!$clmAccess->accessWithType($usertype, 'BE_general_general') and $gid == 6) { JError::raiseNotice(6000, JText::_('USERS_NO_ADMIN')); } $msg = JText::_('USERS_AENDERN'); $link = 'index.php?option=' . $option . '§ion=' . $section . '&task=edit&cid[]=' . $row->id; break; case 'save': default: if ($gid > 6) { JError::raiseNotice(6000, JText::_('USERS_CLM')); } if ($clmAccess->accessWithType($usertype, 'BE_general_general') and $gid == 2) { JError::raiseNotice(6000, JText::_('USERS_GO_ADMIN')); } if (!$clmAccess->accessWithType($usertype, 'BE_general_general') and $gid == 6) { JError::raiseNotice(6000, JText::_('USERS_NO_ADMIN')); } $msg = JText::_('USERS_BENUTZER_GESPEI'); $link = 'index.php?option=' . $option . '§ion=' . $section; break; } // Log schreiben $clmLog = new CLMLog(); $clmLog->aktion = $aktion; $clmLog->params = array('sid' => $row->sid, 'jid' => $row->jid); $clmLog->write(); $mainframe->redirect($link, $msg, "message"); }
/** * Saves the record */ function save() { global $mainframe; // Check for request forgeries JRequest::checkToken() or jexit('Invalid Token'); $option = JRequest::getCmd('option'); // Initialize some variables $db =& JFactory::getDBO(); $me =& JFactory::getUser(); $acl =& JFactory::getACL(); $MailFrom = $mainframe->getCfg('mailfrom'); $FromName = $mainframe->getCfg('fromname'); $SiteName = $mainframe->getCfg('sitename'); // Create a new JUser object $user = new JUser(JRequest::getVar('id', 0, 'post', 'int')); $original_gid = $user->get('gid'); $post = JRequest::get('post'); $post['username'] = JRequest::getVar('username', '', 'post', 'username'); $post['password'] = JRequest::getVar('password', '', 'post', 'string', JREQUEST_ALLOWRAW); $post['password2'] = JRequest::getVar('password2', '', 'post', 'string', JREQUEST_ALLOWRAW); if (!$user->bind($post)) { $mainframe->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message'); $mainframe->enqueueMessage($user->getError(), 'error'); //$mainframe->redirect( 'index.php?option=com_users', $user->getError() ); //return false; return $this->execute('edit'); } $objectID = $acl->get_object_id('users', $user->get('id'), 'ARO'); $groups = $acl->get_object_groups($objectID, 'ARO'); $this_group = strtolower($acl->get_group_name($groups[0], 'ARO')); if ($user->get('id') == $me->get('id') && $user->get('block') == 1) { $msg = JText::_('You cannot block Yourself!'); $mainframe->enqueueMessage($msg, 'message'); return $this->execute('edit'); } else { if ($this_group == 'super administrator' && $user->get('block') == 1) { $msg = JText::_('You cannot block a Super Administrator'); $mainframe->enqueueMessage($msg, 'message'); return $this->execute('edit'); } else { if ($this_group == 'administrator' && $me->get('gid') == 24 && $user->get('block') == 1) { $msg = JText::_('WARNBLOCK'); $mainframe->enqueueMessage($msg, 'message'); return $this->execute('edit'); } else { if ($this_group == 'super administrator' && $me->get('gid') != 25) { $msg = JText::_('You cannot edit a super administrator account'); $mainframe->enqueueMessage($msg, 'message'); return $this->execute('edit'); } } } } // Are we dealing with a new user which we need to create? $isNew = $user->get('id') < 1; if (!$isNew) { // if group has been changed and where original group was a Super Admin if ($user->get('gid') != $original_gid && $original_gid == 25) { // count number of active super admins $query = 'SELECT COUNT( id )' . ' FROM #__users' . ' WHERE gid = 25' . ' AND block = 0'; $db->setQuery($query); $count = $db->loadResult(); if ($count <= 1) { // disallow change if only one Super Admin exists $this->setRedirect('index.php?option=com_users', JText::_('WARN_ONLY_SUPER')); return false; } } } /* * Lets save the JUser object */ if (!$user->save()) { $mainframe->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message'); $mainframe->enqueueMessage($user->getError(), 'error'); return $this->execute('edit'); } /* * Time for the email magic so get ready to sprinkle the magic dust... */ if ($isNew) { $adminEmail = $me->get('email'); $adminName = $me->get('name'); $subject = JText::_('NEW_USER_MESSAGE_SUBJECT'); $message = sprintf(JText::_('NEW_USER_MESSAGE'), $user->get('name'), $SiteName, JURI::root(), $user->get('username'), $user->password_clear); if ($MailFrom != '' && $FromName != '') { $adminName = $FromName; $adminEmail = $MailFrom; } JUtility::sendMail($adminEmail, $adminName, $user->get('email'), $subject, $message); } // If updating self, load the new user object into the session if ($user->get('id') == $me->get('id')) { // Get an ACL object $acl =& JFactory::getACL(); // Get the user group from the ACL $grp = $acl->getAroGroup($user->get('id')); // Mark the user as logged in $user->set('guest', 0); $user->set('aid', 1); // Fudge Authors, Editors, Publishers and Super Administrators into the special access group if ($acl->is_group_child_of($grp->name, 'Registered') || $acl->is_group_child_of($grp->name, 'Public Backend')) { $user->set('aid', 2); } // Set the usertype based on the ACL group name $user->set('usertype', $grp->name); $session =& JFactory::getSession(); $session->set('user', $user); } switch ($this->getTask()) { case 'apply': $msg = JText::sprintf('Successfully Saved changes to User', $user->get('name')); $this->setRedirect('index.php?option=com_users&view=user&task=edit&cid[]=' . $user->get('id'), $msg); break; case 'save': default: $msg = JText::sprintf('Successfully Saved User', $user->get('name')); $this->setRedirect('index.php?option=com_users', $msg); break; } }
public function userJoomlaSave() { $jshopConfig = JSFactory::getConfig(); $post = $this->data; $user_shop = $this->user; if ($user_shop->user_id <= 0) { return 2; } $user = new JUser($user_shop->user_id); if (!$jshopConfig->not_update_user_joomla) { if ($user_shop->email) { $user->email = $user_shop->email; } if ($user_shop->f_name || $user_shop->l_name) { $user->name = $user_shop->f_name . ' ' . $user_shop->l_name; } } if ($post['password'] != '') { $data = array("password" => $post['password'], "password2" => $post['password']); $user->bind($data); } if ($this->admin_registration) { $user->username = $post['u_name']; $user->block = $post['block']; } if ($user->save()) { $this->user_joomla = $user; return 1; } else { $this->setError($user->getError()); return 0; } }
/** * Method to save the form data. * * @param array The form data. * @return mixed The user id on success, false on failure. * @since 1.6 */ public function save($data) { $userId = !empty($data['id']) ? $data['id'] : (int) $this->getState('user.id'); $user = new JUser($userId); // Prepare the data for the user object. $data['email'] = JStringPunycode::emailToPunycode($data['email1']); $data['password'] = $data['password1']; // Unset the username if it should not be overwritten $username = $data['username']; $isUsernameCompliant = $this->getState('user.username.compliant'); if (!JComponentHelper::getParams('com_users')->get('change_login_name') && $isUsernameCompliant) { unset($data['username']); } // Unset the block so it does not get overwritten unset($data['block']); // Unset the sendEmail so it does not get overwritten unset($data['sendEmail']); // Bind the data. if (!$user->bind($data)) { $this->setError(JText::sprintf('COM_USERS_PROFILE_BIND_FAILED', $user->getError())); return false; } // Load the users plugin group. JPluginHelper::importPlugin('user'); // Null the user groups so they don't get overwritten $user->groups = null; // Store the data. if (!$user->save()) { $this->setError($user->getError()); return false; } return $user->id; }
function saveUser($auth_info) { // process the auth_info response if ($auth_info['stat'] == 'ok') { $db =& JFactory::getDBO(); $rpxid = 'rpx' . md5($auth_info['profile']['identifier']); $query = "SELECT userid FROM #__rpx_mapping WHERE rpxid='" . $rpxid . "'"; $db->setQuery($query); $userid = $db->loadResult(); $newuser = true; if (isset($userid)) { $user =& JFactory::getUser($userid); if ($user->id == $userid) { $newuser = false; } else { // possible if previous registered, but meanwhile removed // we have a userid without user...remove from the rpx_mapping $query = "DELETE FROM #__rpx_mapping WHERE userid='" . $userid . "'"; $db->setQuery($query); $db->query(); } } if ($newuser == true) { // save the user $user = new JUser(); $authorize =& JFactory::getACL(); $newUsertype = 'Registered'; $user->set('id', 0); $user->set('usertype', ''); $user->set('gid', $authorize->get_group_id('', $newUsertype, 'ARO')); $date =& JFactory::getDate(); $user->set('registerDate', $date->toMySQL()); if (isset($auth_info['profile']['displayName'])) { $displayName = $auth_info['profile']['displayName']; } else { if (isset($auth_info['profile']['name']['displayName'])) { $displayName = $auth_info['profile']['name']['displayName']; } } if (isset($auth_info['profile']['preferredUsername'])) { $preferredUsername = $auth_info['profile']['preferredUsername']; } else { if (isset($auth_info['profile']['name']['preferredUsername'])) { $preferredUsername = $auth_info['profile']['name']['preferredUsername']; } } $user->set('name', $displayName); // if username already exists, just add an index to it $nameexists = true; $index = 0; $userName = $preferredUsername; while ($nameexists == true) { if (JUserHelper::getUserId($userName) != 0) { $index++; $userName = $preferredUsername . $index; } else { $nameexists = false; } } $user->set('username', $userName); $host = JFactory::getURI()->getHost(); $domain = substr($host, 4); // strips the www. if ($this->params->get('fakemail') == 0) { if (isset($auth_info['profile']['email'])) { $user->set('email', $auth_info['profile']['email']); } else { if (isset($auth_info['profile']['name']['email'])) { $user->set('email', $auth_info['profile']['email']); } else { $user->set('email', str_replace(" ", "_", $userName) . "@" . $domain); } } } else { $user->set('email', str_replace(" ", "_", $userName) . "@" . $domain); } $pwd = JUserHelper::genRandomPassword(); $user->set('password', $pwd); if (!$user->save()) { echo "ERROR: "; echo $user->getError(); } else { $query = "INSERT INTO #__rpx_mapping (userid, rpxid) VALUES ('" . $user->get('id') . "','" . $rpxid . "')"; $db->setQuery($query); if (!$db->query()) { JERROR::raiseError(500, $db->stderror()); } } // check if the community builder tables are there $query = "SHOW TABLES LIKE '%__comprofiler'"; $db->setQuery($query); $tableexists = $db->loadResult(); if (isset($tableexists)) { $cbquery = "INSERT IGNORE INTO #__comprofiler(id,user_id) VALUES ('" . $user->get('id') . "','" . $user->get('id') . "')"; $db->setQuery($cbquery); if (!$db->query()) { JERROR::raiseError(500, $db->stderror()); } } } // Get an ACL object $acl =& JFactory::getACL(); // Get the user group from the ACL if ($user->get('tmp_user') == 1) { $grp = new JObject(); // This should be configurable at some point $grp->set('name', 'Registered'); } else { $grp = $acl->getAroGroup($user->get('id')); } //Mark the user as logged in $user->set('guest', 0); $user->set('aid', 1); // Fudge Authors, Editors, Publishers and Super Administrators into the special access group if ($acl->is_group_child_of($grp->name, 'Registered') || $acl->is_group_child_of($grp->name, 'Public Backend')) { $user->set('aid', 2); } //Set the usertype based on the ACL group name $user->set('usertype', $grp->name); // Register the needed session variables $session =& JFactory::getSession(); $session->set('user', $user); // Get the session object $table =& JTable::getInstance('session'); $table->load($session->getId()); $table->guest = $user->get('guest'); $table->username = $user->get('username'); $table->userid = intval($user->get('id')); $table->usertype = $user->get('usertype'); $table->gid = intval($user->get('gid')); $table->update(); // Hit the user last visit field $user->setLastVisit(); } }
private function jvsave($member_id, $post) { $mainframe = JFactory :: getApplication(); $option = JRequest :: getCmd('option'); // Initialize some variables $msg = ""; $me = & JFactory :: getUser(); $MailFrom = $mainframe->getCfg('mailfrom'); $FromName = $mainframe->getCfg('fromname'); $SiteName = $mainframe->getCfg('sitename'); // Create a new JUser object $user = new JUser($member_id); $original_gid = $user->get('gid'); if (!$user->bind($post)) { $result = array (); $result['success'] = false; $result['title'] = 'Error'; $result['content'] = JText :: _('Failed Updating Member Information'); $result = oseJSON :: encode($result); oseExit($result); } // Are we dealing with a new user which we need to create? $isNew = ($user->get('id') < 1); if (!$isNew) { // if group has been changed and where original group was a Super Admin if ($user->get('gid') != $original_gid && $original_gid == 25) { // count number of active super admins $query = 'SELECT COUNT( id )' . ' FROM #__users' . ' WHERE gid = 25' . ' AND block = 0'; $this->db->setQuery($query); $count = $this->db->loadResult(); if ($count <= 1) { $result = array (); $result['success'] = false; $result['title'] = 'Error'; $result['content'] = JText :: _('Failed Updating Member Information'); $result = oseJSON :: encode($result); oseExit($result); } } } /* * Lets save the JUser object */ if (!$user->save()) { $result = array (); $result['success'] = false; $result['title'] = 'Error'; $result['content'] = $user->getError(); $result = oseJSON :: encode($result); oseExit($result); } // For new users, email username and password // Capture the new user id if ($isNew) { $newUserId = $user->get('id'); } else { $newUserId = null; } return $newUserId; }
/** * Method to save the form data. * * @param array $temp The form data. * * @return mixed The user id on success, false on failure. * * @since 1.6 */ public function register($temp) { $params = JComponentHelper::getParams('com_users'); // Initialise the table with JUser. $user = new JUser(); $data = (array) $this->getData(); // Merge in the registration data. foreach ($temp as $k => $v) { $data[$k] = $v; } // Prepare the data for the user object. $data['email'] = JStringPunycode::emailToPunycode($data['email1']); $data['password'] = $data['password1']; $useractivation = $params->get('useractivation'); $sendpassword = $params->get('sendpassword', 1); // Check if the user needs to activate their account. if ($useractivation == 1 || $useractivation == 2) { $data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword()); $data['block'] = 1; } // Bind the data. if (!$user->bind($data)) { $this->setError(JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError())); return false; } // Load the users plugin group. JPluginHelper::importPlugin('user'); // Store the data. if (!$user->save()) { $this->setError($user->getError()); return false; } $config = JFactory::getConfig(); $db = $this->getDbo(); $query = $db->getQuery(true); // Compile the notification mail values. $data = $user->getProperties(); $data['fromname'] = $config->get('fromname'); $data['mailfrom'] = $config->get('mailfrom'); $data['sitename'] = $config->get('sitename'); $data['siteurl'] = JUri::root(); // Handle account activation/confirmation emails. if ($useractivation == 2) { // Set the link to confirm the user email. $uri = JUri::getInstance(); $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port')); $data['activate'] = $base . JRoute::_('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false); $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']); if ($sendpassword) { $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['activate'], $data['siteurl'], $data['username'], $data['password_clear']); } else { $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY_NOPW', $data['name'], $data['sitename'], $data['activate'], $data['siteurl'], $data['username']); } } elseif ($useractivation == 1) { // Set the link to activate the user account. $uri = JUri::getInstance(); $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port')); $data['activate'] = $base . JRoute::_('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false); $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']); if ($sendpassword) { $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['activate'], $data['siteurl'], $data['username'], $data['password_clear']); } else { $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY_NOPW', $data['name'], $data['sitename'], $data['activate'], $data['siteurl'], $data['username']); } } else { $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']); if ($sendpassword) { $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_BODY', $data['name'], $data['sitename'], $data['siteurl'], $data['username'], $data['password_clear']); } else { $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_BODY_NOPW', $data['name'], $data['sitename'], $data['siteurl']); } } // Send the registration email. $return = JFactory::getMailer()->sendMail($data['mailfrom'], $data['fromname'], $data['email'], $emailSubject, $emailBody); // Send Notification mail to administrators if ($params->get('useractivation') < 2 && $params->get('mail_to_admin') == 1) { $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']); $emailBodyAdmin = JText::sprintf('COM_USERS_EMAIL_REGISTERED_NOTIFICATION_TO_ADMIN_BODY', $data['name'], $data['username'], $data['siteurl']); // Get all admin users $query->clear()->select($db->quoteName(array('name', 'email', 'sendEmail')))->from($db->quoteName('#__users'))->where($db->quoteName('sendEmail') . ' = ' . 1); $db->setQuery($query); try { $rows = $db->loadObjectList(); } catch (RuntimeException $e) { $this->setError(JText::sprintf('COM_USERS_DATABASE_ERROR', $e->getMessage()), 500); return false; } // Send mail to all superadministrators id foreach ($rows as $row) { $return = JFactory::getMailer()->sendMail($data['mailfrom'], $data['fromname'], $row->email, $emailSubject, $emailBodyAdmin); // Check for an error. if ($return !== true) { $this->setError(JText::_('COM_USERS_REGISTRATION_ACTIVATION_NOTIFY_SEND_MAIL_FAILED')); return false; } } } // Check for an error. if ($return !== true) { $this->setError(JText::_('COM_USERS_REGISTRATION_SEND_MAIL_FAILED')); // Send a system message to administrators receiving system mails $db = JFactory::getDbo(); $query->clear()->select($db->quoteName(array('name', 'email', 'sendEmail', 'id')))->from($db->quoteName('#__users'))->where($db->quoteName('block') . ' = ' . (int) 0)->where($db->quoteName('sendEmail') . ' = ' . (int) 1); $db->setQuery($query); try { $sendEmail = $db->loadColumn(); } catch (RuntimeException $e) { $this->setError(JText::sprintf('COM_USERS_DATABASE_ERROR', $e->getMessage()), 500); return false; } if (count($sendEmail) > 0) { $jdate = new JDate(); // Build the query to add the messages foreach ($sendEmail as $userid) { $values = array($db->quote($userid), $db->quote($userid), $db->quote($jdate->toSql()), $db->quote(JText::_('COM_USERS_MAIL_SEND_FAILURE_SUBJECT')), $db->quote(JText::sprintf('COM_USERS_MAIL_SEND_FAILURE_BODY', $return, $data['username']))); $query->clear()->insert($db->quoteName('#__messages'))->columns($db->quoteName(array('user_id_from', 'user_id_to', 'date_time', 'subject', 'message')))->values(implode(',', $values)); $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { $this->setError(JText::sprintf('COM_USERS_DATABASE_ERROR', $e->getMessage()), 500); return false; } } } return false; } if ($useractivation == 1) { return "useractivate"; } elseif ($useractivation == 2) { return "adminactivate"; } else { return $user->id; } }
protected function saveUser() { $user = KunenaUserHelper::get($this->user->id); // we only allow users to edit few fields $allow = array('name', 'email', 'password', 'password2', 'params'); if ($this->config->usernamechange) { if (version_compare(JVERSION, '2.5.5', '<') || JComponentHelper::getParams('com_users')->get('change_login_name', 1)) { $allow[] = 'username'; } } //clean request $post = JRequest::get('post'); $post['password'] = JRequest::getVar('password', '', 'post', 'string', JREQUEST_ALLOWRAW); // RAW input $post['password2'] = JRequest::getVar('password2', '', 'post', 'string', JREQUEST_ALLOWRAW); // RAW input if (empty($post['password']) || empty($post['password2'])) { unset($post['password'], $post['password2']); } $post = array_intersect_key($post, array_flip($allow)); // get the redirect $return = $user->getUrl(false); $err_return = $user->getUrl(false, 'edit'); // do a password safety check if (!empty($post['password']) && !empty($post['password2'])) { if (strlen($post['password']) < 5 && strlen($post['password2']) < 5) { if ($post['password'] != $post['password2']) { $msg = JText::_('COM_KUNENA_PROFILE_PASSWORD_MISMATCH'); $this->app->redirect($err_return, $msg, 'error'); } $msg = JText::_('COM_KUNENA_PROFILE_PASSWORD_NOT_MINIMUM'); $this->app->redirect($err_return, $msg, 'error'); } } $username = $this->user->get('username'); $user = new JUser($this->user->id); // Bind the form fields to the user table if (!$user->bind($post)) { return false; } // Store user to the database if (!$user->save(true)) { $this->app->enqueueMessage($user->getError(), 'notice'); return false; } // Reload the user. $this->user->load($this->user->id); $session = JFactory::getSession(); $session->set('user', $this->user); // update session if username has been changed if ($username && $username != $this->user->username) { $table = JTable::getInstance('session', 'JTable'); $table->load($session->getId()); $table->username = $this->user->username; $table->store(); } return true; }
public static function juserRegister($juser) { $result = array(); $oseMscconfig = oseRegistry::call('msc')->getConfig('', 'obj'); $config = JFactory::getConfig(); $params = JComponentHelper::getParams('com_users'); $newUserType = self::getNewUserType($params->get('new_usertype')); $juser['gid'] = $newUserType; $data = (array) self::getJuserData($juser); // Initialise the table with JUser. $user = new JUser; foreach ($juser as $k => $v) { $data[$k] = $v; } // Prepare the data for the user object. $useractivation = $params->get('useractivation'); // Check if the user needs to activate their account. if (($useractivation == 1) || ($useractivation == 2)) { jimport('joomla.user.helper'); $data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword()); $data['block'] = 1; } // Bind the data. if (!$user->bind($data)) { $result['success'] = false; $result['title'] = 'Error'; $result['content'] = JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError()); } // Load the users plugin group. JPluginHelper::importPlugin('user'); if (!$user->save()) { $result['success'] = false; $result['title'] = 'Error'; $result['reload'] = ($oseMscconfig->error_registration == 'refresh') ? true : false; ; $result['content'] = JText::_($user->getError()); } else { // Mark the user_id in order to user in payment form if (($useractivation == 1) || ($useractivation == 2)) { $session = JFactory::getSession(); $oseUser = array(); $oseUser['user_id'] = $user->id; $oseUser['block'] = true; $oseUser['activation'] = true; $session->set('ose_user', $oseUser); } $result['success'] = true; $result['user'] = $user; $result['title'] = 'Done'; $result['content'] = 'Juser saved successfully'; // Compile the notification mail values. $data = $user->getProperties(); $data['fromname'] = $config->get('fromname'); $data['mailfrom'] = $config->get('mailfrom'); $data['sitename'] = $config->get('sitename'); $data['siteurl'] = JUri::base(); if (JOOMLA16 == true) { // Handle account activation/confirmation emails. if ($useractivation == 2) { // Set the link to confirm the user email. $uri = JURI::getInstance(); $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port')); $data['activate'] = $base . JRoute::_('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false); $emailSubject = JText::sprintf('COM_USERS_OSEMSC_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']); $emailBody = JText::sprintf('COM_USERS_OSEMSC_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['siteurl'] . 'index.php?option=com_users&task=registration.activate&token=' . $data['activation'], $data['siteurl'], $data['username'], $data['password_clear']); } else if ($useractivation == 1) { // Set the link to activate the user account. $uri = JURI::getInstance(); $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port')); $data['activate'] = $base . JRoute::_('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false); $emailSubject = JText::sprintf('COM_USERS_OSEMSC_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']); $emailBody = JText::sprintf('COM_USERS_OSEMSC_EMAIL_REGISTERED_WITH_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['siteurl'] . 'index.php?option=com_users&task=registration.activate&token=' . $data['activation'], $data['siteurl'], $data['username'], $data['password_clear']); } else { $emailSubject = ""; $emailBody = ""; } // Send the registration email. if (!empty($emailSubject) && !empty($emailBody)) { if (JOOMLA30 == true) { $mailer = new JMail(); $return = $mailer->sendMail($data['mailfrom'], $data['fromname'], $data['email'], $emailSubject, $emailBody); } else { $return = JUtility::sendMail($data['mailfrom'], $data['fromname'], $data['email'], $emailSubject, $emailBody); } } else { $return = true; } // Check for an error. if ($return !== true) { $this->setError(JText::_('COM_USERS_REGISTRATION_SEND_MAIL_FAILED')); // Send a system message to administrators receiving system mails $db = JFactory::getDBO(); $q = "SELECT id FROM #__users WHERE block = 0 AND sendEmail = 1"; $db->setQuery($q); $sendEmail = $db->loadResultArray(); if (count($sendEmail) > 0) { $jdate = new JDate(); // Build the query to add the messages $q = "INSERT INTO `#__messages` (`user_id_from`, `user_id_to`, `date_time`, `subject`, `message`) VALUES "; $messages = array(); foreach ($sendEmail as $userid) { $messages[] = "(" . $userid . ", " . $userid . ", '" . $jdate->toMySQL() . "', '" . JText::_('COM_USERS_MAIL_SEND_FAILURE_SUBJECT') . "', '" . JText::sprintf('COM_USERS_MAIL_SEND_FAILURE_BODY', $return, $data['username']) . "')"; } $q .= implode(',', $messages); $db->setQuery($q); $db->query(); } //return false; } if ($useractivation == 1) { $result['user_active'] = "useractivate"; } else if ($useractivation == 2) { $result['user_active'] = "adminactivate"; } else { $result['user_active'] = null; } } else { $mainframe = JFactory::getApplication('SITE'); if ($useractivation == 1) { $password = $data['password_clear']; $db = JFactory::getDBO(); $name = $user->get('name'); $email = $user->get('email'); $username = $user->get('username'); $usersConfig = &JComponentHelper::getParams('com_users'); $sitename = $mainframe->getCfg('sitename'); $useractivation = $usersConfig->get('useractivation'); $mailfrom = $mainframe->getCfg('mailfrom'); $fromname = $mainframe->getCfg('fromname'); $siteURL = JURI::base(); $subject = sprintf(JText::_('ACCOUNT_DETAILS_FOR'), $name, $sitename); $subject = html_entity_decode($subject, ENT_QUOTES); $message = sprintf(JText::_('SEND_MSG_ACTIVATE'), $name, $sitename, $siteURL . "index.php?option=com_user&task=activate&activation=" . $user->get('activation'), $siteURL, $username, $password); $message = html_entity_decode($message, ENT_QUOTES); //get all super administrator $query = 'SELECT name, email, sendEmail' . ' FROM #__users' . ' WHERE LOWER( usertype ) = "super administrator"'; $db->setQuery($query); $rows = $db->loadObjectList(); // Send email to user if (!$mailfrom || !$fromname) { $fromname = $rows[0]->name; $mailfrom = $rows[0]->email; } JUtility::sendMail($mailfrom, $fromname, $email, $subject, $message); // Send notification to all administrators $subject2 = sprintf(JText::_('ACCOUNT_DETAILS_FOR'), $name, $sitename); $subject2 = html_entity_decode($subject2, ENT_QUOTES); // get superadministrators id foreach ($rows as $row) { if ($row->sendEmail) { $message2 = sprintf(JText::_('SEND_MSG_ADMIN'), $row->name, $sitename, $name, $email, $username); $message2 = html_entity_decode($message2, ENT_QUOTES); JUtility::sendMail($mailfrom, $fromname, $row->email, $subject2, $message2); } } } else { $name = $user->get('name'); $email = $user->get('email'); $username = $user->get('username'); $usersConfig = &JComponentHelper::getParams('com_users'); $sitename = $mainframe->getCfg('sitename'); $useractivation = $usersConfig->get('useractivation'); $mailfrom = $mainframe->getCfg('mailfrom'); $fromname = $mainframe->getCfg('fromname'); $siteURL = JURI::base(); $message = sprintf(JText::_('SEND_MSG'), $name, $sitename, $siteURL); } } } return $result; }
public function userJoomlaSave() { $post = $this->data; $params = $this->getUserParams(); if ($post["u_name"] == "") { $post["u_name"] = $post['email']; $this->user->u_name = $post["u_name"]; } if ($post["password"] == "") { $post["password"] = substr(md5('up' . time()), 0, 8); } $user = new JUser(); $data = array(); $data['groups'][] = $params->get('new_usertype', 2); $data['email'] = $post['email']; $data['password'] = $post['password']; $data['password2'] = $post['password2']; $data['name'] = $post['f_name'] . ' ' . $post['l_name']; $data['username'] = $post["u_name"]; $useractivation = $params->get('useractivation'); if ($this->admin_registration) { $data['block'] = $post['block']; } else { if ($useractivation == 1 || $useractivation == 2) { jimport('joomla.user.helper'); $data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword()); $data['block'] = 1; } } $this->userjoomla_data = $data; extract(js_add_trigger(get_defined_vars(), "beforeBind")); $user->bind($data); if (!$user->save()) { $this->user_joomla_id = 0; $this->savePostData(); saveToLog('error.log', 'Error registration-' . $user->getError()); $this->setError($user->getError()); return 0; } else { $this->user_joomla = $user; $this->user_joomla_id = $user->id; return $user->id; } }
/** * process the plugin, called when form is submitted * * @param object $params * @param object form */ function onBeforeStore(&$params, &$formModel) { $app =& JFactory::getApplication(); //if the fabrik table is set to be jos_users and the this plugin is used //we need to alter the form model to tell it not to store the main row // but to still store any joined rows $ftable = str_replace('#__', $app->getCfg('dbprefix'), $formModel->getTableModel()->getTable()->db_table_name); $jos_users = $app->getCfg('dbprefix') . 'users'; if ($ftable == $jos_users) { $formModel->_storeMainRow = false; } $usersConfig =& JComponentHelper::getParams('com_users'); // Initialize some variables $me =& JFactory::getUser(); $acl =& JFactory::getACL(); $MailFrom = $app->getCfg('mailfrom'); $FromName = $app->getCfg('fromname'); $SiteName = $app->getCfg('sitename'); $siteURL = COM_FABRIK_LIVESITE; $bypassActivation = $params->get('juser_bypass_activation', false); $bypassRegistration = $params->get('juser_bypass_registration', true); $usertype_max = (int) $params->get('juser_usertype_max', 18); // load in the com_user language file $lang =& JFactory::getLanguage(); $lang->load('com_user'); $data =& $formModel->_formData; // Check for request forgeries JRequest::checkToken() or jexit('Invalid Token'); $option = JRequest::getCmd('option'); $original_id = 0; if ($params->get('juser_field_userid') != '') { $this->useridfield = $this->getFieldName($params, 'juser_field_userid'); if (!empty($formModel->_rowId)) { $original_id = (int) $data[$this->useridfield]; } } else { $original_id = 0; $this->useridfield = ''; } // Create a new JUser object $user = new JUser($original_id); $original_gid = $user->get('gid'); // Are we dealing with a new user which we need to create? $isNew = $user->get('id') < 1; //$post = JRequest::get('post'); if ($isNew && $usersConfig->get('allowUserRegistration') == '0' && !$bypassRegistration) { JError::raiseError(403, JText::_('Access Forbidden - Registration not enabled')); return false; } //new $post = array(); $this->passwordfield = $this->getFieldName($params, 'juser_field_password'); $this->passwordvalue = $this->getFieldValue($params, 'juser_field_password', $data); $this->namefield = $this->getFieldName($params, 'juser_field_name'); $this->namevalue = $this->getFieldValue($params, 'juser_field_name', $data); $this->usernamefield = $this->getFieldName($params, 'juser_field_username'); $this->usernamevalue = $this->getFieldValue($params, 'juser_field_username', $data); $this->emailfield = $this->getFieldName($params, 'juser_field_email'); $this->emailvalue = $this->getFieldValue($params, 'juser_field_email', $data); $post['id'] = $original_id; if (!$isNew) { // for now, don't allow changing f GIDthru JUser plugin! // $post['gid'] = $original_gid; // $$$ hugh - let's allow gid to be changed as long as it doesn't // exceed the currently logged on user's level // yes, i know this duplicates codce from below, for now I'm just noodling around if ($params->get('juser_field_usertype') != '') { $this->gidfield = $this->getFieldName($params, 'juser_field_usertype'); $post['gid'] = JArrayHelper::getValue($data, $this->gidfield, 18); if (is_array($post['gid'])) { $post['gid'] = $post['gid'][0]; } $post['gid'] = (int) $post['gid']; if ($post['gid'] > $me->get('gid')) { $post['gid'] = $me->get('gid'); } } else { // if editing an existing user and no gid field being used, // use existing gid. $post['gid'] = $original_gid; } } else { if ($params->get('juser_field_usertype') != '') { $this->gidfield = $this->getFieldName($params, 'juser_field_usertype'); $post['gid'] = JArrayHelper::getValue($data, $this->gidfield, 18); if (is_array($post['gid'])) { $post['gid'] = $post['gid'][0]; } } else { $post['gid'] = 18; } } $post['gid'] = (int) $post['gid']; if ($post['gid'] === 0) { $post['gid'] = 18; } // $$$ hugh - added 'usertype_max' param, as a safety net to prevent GID's being // set to arbitrarily high values thru spoofing. if ($post['gid'] > $usertype_max && $post['gid'] != $original_gid) { //$post['gid'] = $usertype_max; $msg = JText::_('Attempting to set usertype above allowed level!'); $app->enqueueMessage($msg, 'message'); return false; } if ($params->get('juser_field_block') != '') { $this->blockfield = $this->getFieldName($params, 'juser_field_block'); $blocked = JArrayHelper::getValue($data, $this->blockfield, ''); if (is_array($blocked)) { // probably a dropdown $post['block'] = (int) $blocked[0]; } else { $post['block'] = (int) $blocked; } } else { $post['block'] = 0; } //$$$tom get password field to use in $origdata object if editing user and not changing password $origdata =& $formModel->_origData; $pwfield = $this->passwordfield; $post['username'] = $this->usernamevalue; $post['password'] = $this->passwordvalue; $post['password2'] = $this->passwordvalue; $post['name'] = $this->namevalue; $name = $this->namevalue; $post['email'] = $this->emailvalue; $ok = $this->check($post, $formModel, $params); if (!$ok) { // @TODO - add some error reporting return false; } // Set the registration timestamp if ($isNew) { $now =& JFactory::getDate(); $user->set('registerDate', $now->toMySQL()); } // Check that username is not greater than 25 characters $username = $post['username']; if (strlen($username) > 150) { $username = substr($username, 0, 150); $user->set('username', $username); } // Check that password is not greater than 100 characters if (strlen($post['password']) > 100) { $post['password'] = substr($post['password'], 0, 100); } //$$$tom Is password field empty on edit? if (!$isNew && strlen($password) == 0) { $keepPassword = true; } // end new if (!$user->bind($post)) { $app->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message'); $app->enqueueMessage($user->getError(), 'error'); return false; } // $$$ rob 23/05/2011 moved after bind as we want to ensure block is set to the right level based on the plugin and J's options if ($isNew) { // If user activation is turned on, we need to set the activation information $useractivation = $usersConfig->get('useractivation'); if ($useractivation == '1' && !$bypassActivation) { jimport('joomla.user.helper'); $user->set('activation', md5(JUserHelper::genRandomPassword())); $user->set('block', '1'); } } // $$$ rob 20/052011 if a new user then they won't have an acl group assigned if ($isNew) { $this_group = ''; } else { $objectID = $acl->get_object_id('users', $user->get('id'), 'ARO'); $groups = $acl->get_object_groups($objectID, 'ARO'); $this_group = strtolower($acl->get_group_name($groups[0], 'ARO')); } if (!$isNew) { if ($user->get('id') == $me->get('id') && $user->get('block') == 1) { $msg = JText::_('You cannot block Yourself!'); $app->enqueueMessage($msg, 'message'); return false; } else { if ($this_group == 'super administrator' && $user->get('block') == 1) { $msg = JText::_('You cannot block a Super Administrator'); $app->enqueueMessage($msg, 'message'); return false; } else { if ($this_group == 'administrator' && $me->get('gid') == 24 && $user->get('block') == 1) { $msg = JText::_('WARNBLOCK'); $app->enqueueMessage($msg, 'message'); return false; } else { if ($this_group == 'super administrator' && $me->get('gid') != 25) { $msg = JText::_('You cannot edit a super administrator account'); $app->enqueueMessage($msg, 'message'); return false; } } } } //$$$tom Keep original password if ($keepPassword) { //$user->set('password', $origdata->$pwfield); } // if group has been changed and where original group was a Super Admin if ($user->get('gid') != $original_gid && $original_gid == 25) { $db =& JFactory::getDBO(); // count number of active super admins $query = 'SELECT COUNT( id )' . ' FROM #__users' . ' WHERE gid = 25' . ' AND block = 0'; $db->setQuery($query); $count = $db->loadResult(); if ($count <= 1) { // disallow change if only one Super Admin exists $this->setRedirect('index.php?option=com_users', JText::_('WARN_ONLY_SUPER')); return false; } } } /* * Lets save the JUser object */ if (!$user->save()) { $app->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message'); $app->enqueueMessage($user->getError(), 'error'); return false; } $session =& JFactory::getSession(); JRequest::setVar('newuserid', $user->id); JRequest::setVar('newuserid', $user->id, 'cookie'); $session->set('newuserid', $user->id); JRequest::setVar('newuserid_element', $this->useridfield); JRequest::setVar('newuserid_element', $this->useridfield, 'cookie'); $session->set('newuserid_element', $this->useridfield); /* * Time for the email magic so get ready to sprinkle the magic dust... */ if ($isNew) { $adminEmail = $me->get('email'); $adminName = $me->get('name'); $subject = sprintf(JText::_('PLG_FABRIK_FORM_JUSER_ACCOUNT_DETAILS_FOR'), $name, $SiteName); $subject = html_entity_decode($subject, ENT_QUOTES); if ($useractivation == 1 && !$bypassActivation) { $message = sprintf(JText::_('PLG_FABRIK_FORM_JUSER_SEND_MSG_ACTIVATE'), $name, $SiteName, $siteURL . "index.php?option=com_user&task=activate&activation=" . $user->get('activation'), $siteURL, $username, $user->password_clear); } else { if ($params->get('juser_bypass_accountdetails', 0) != 1) { //$$$tom adding Bypass Joomla's "Account details for..." email $message = sprintf(JText::_('PLG_FABRIK_FORM_JUSER_SEND_MSG'), $name, $SiteName, $siteURL); } } $message = html_entity_decode($message, ENT_QUOTES); if ($MailFrom != '' && $FromName != '') { $adminName = $FromName; $adminEmail = $MailFrom; } if ($message) { //$$$tom see comment above about bypassing Joomla's email JUtility::sendMail($adminEmail, $adminName, $user->get('email'), $subject, $message); } } // If updating self, load the new user object into the session if ($user->get('id') == $me->get('id')) { // Get an ACL object $acl =& JFactory::getACL(); // Get the user group from the ACL $grp = $acl->getAroGroup($user->get('id')); // Mark the user as logged in $user->set('guest', 0); $user->set('aid', 1); // Fudge Authors, Editors, Publishers and Super Administrators into the special access group if ($acl->is_group_child_of($grp->name, 'Registered') || $acl->is_group_child_of($grp->name, 'Public Backend')) { $user->set('aid', 2); } // Set the usertype based on the ACL group name $user->set('usertype', $grp->name); $session->set('user', $user); } if (!empty($this->useridfield)) { $data[$this->useridfield] = $user->id; $data[$this->useridfield . '_raw'] = $user->id; } if ($ftable == $jos_users) { $formModel->_rowId = $user->get('id'); } }
/** * Method to save the form data. * * @param array The form data. * @return mixed The user id on success, false on failure. * @since 1.6 */ public function save($data) { $userId = !empty($data['id']) ? $data['id'] : (int) $this->getState('user.id'); $user = new JUser($userId); // Prepare the data for the user object. $data['email'] = $data['email1']; $data['password'] = $data['password1']; // Unset the username so it does not get overwritten unset($data['username']); // Unset the block so it does not get overwritten unset($data['block']); // Unset the sendEmail so it does not get overwritten unset($data['sendEmail']); // Bind the data. if (!$user->bind($data)) { $this->setError(JText::sprintf('USERS PROFILE BIND FAILED', $user->getError())); return false; } // Load the users plugin group. JPluginHelper::importPlugin('user'); // Null the user groups so they don't get overwritten $user->groups = null; // Store the data. if (!$user->save()) { $this->setError($user->getError()); return false; } return $user->id; }
/** * Bind the post data to the JUser object and the VM tables, then saves it * It is used to register new users * This function can also change already registered users, this is important when a registered user changes his email within the checkout. * * @author Max Milbers * @author Oscar van Eijk * @return boolean True is the save was successful, false otherwise. */ public static function storeVM25(&$data, $checkToken = TRUE, &$userModel, $opc_no_activation = false, &$opc) { $message = ''; $user = ''; $newId = 0; if ($checkToken) { JRequest::checkToken() or jexit('Invalid Token, while trying to save user'); } $mainframe = JFactory::getApplication(); if (empty($data)) { vmError('Developer notice, no data to store for user'); return false; } //To find out, if we have to register a new user, we take a look on the id of the usermodel object. //The constructor sets automatically the right id. $user = JFactory::getUser(); $user_id = $user->id; $new = $user->id < 1; if (empty($user_id)) { $user = new JUser(); //thealmega http://forum.virtuemart.net/index.php?topic=99755.msg393758#msg393758 } else { $user = JFactory::getUser($user_id); } $gid = $user->get('gid'); // Save original gid // Preformat and control user datas by plugin JPluginHelper::importPlugin('vmuserfield'); $dispatcher = JDispatcher::getInstance(); $valid = true; $dispatcher->trigger('plgVmOnBeforeUserfieldDataSave', array(&$valid, $user_id, &$data, $user)); // $valid must be false if plugin detect an error if ($valid == false) { return false; } // Before I used this "if($cart && !$new)" // This construction is necessary, because this function is used to register a new JUser, so we need all the JUser data in $data. // On the other hand this function is also used just for updating JUser data, like the email for the BT address. In this case the // name, username, password and so on is already stored in the JUser and dont need to be entered again. if (empty($data['email'])) { $email = $user->get('email'); if (!empty($email)) { $data['email'] = $email; } } $data['email'] = str_replace(array('\'', '"', ',', '%', '*', '/', '\\', '?', '^', '`', '{', '}', '|', '~'), array(''), $data['email']); unset($data['isRoot']); unset($data['groups']); unset($data['_authGroups']); //This is important, when a user changes his email address from the cart, //that means using view user layout edit_address (which is called from the cart) $user->set('email', $data['email']); if (empty($data['name'])) { $name = $user->get('name'); if (!empty($name)) { $data['name'] = $name; } } if (empty($data['name'])) { $data['name'] = ''; if (!empty($data['first_name'])) { $data['name'] = $data['first_name']; } if ($data['name'] == '_') { $data['name'] = ''; } if (!empty($data['last_name'])) { $data['name'] = $data['last_name']; } if ($data['name'] == '_') { $data['name'] = ''; } if (empty($data['name'])) { $data['name'] = $data['username']; } if ($data['name'] == '_') { $data['name'] = ''; } if (empty($data['name'])) { $data['name'] = $data['email']; } } if (empty($data['username'])) { $username = $user->get('username'); if (!empty($username)) { $data['username'] = $username; } else { $data['username'] = JRequest::getVar('username', '', 'post', 'username'); if (empty($data['username'])) { $data['username'] = $data['email']; } } } if (empty($data['password'])) { $data['password'] = JRequest::getVar('password', '', 'post', 'string', JREQUEST_ALLOWRAW); } if (empty($data['password2'])) { $data['password2'] = JRequest::getVar('password2', '', 'post', 'string', JREQUEST_ALLOWRAW); } if (!$new && !empty($data['password']) && empty($data['password2'])) { unset($data['password']); unset($data['password2']); } $usersConfig = JComponentHelper::getParams('com_users'); $usernamechange = $usersConfig->get('change_login_name', true); if (!$new) { if (empty($usernamechange)) { $data['username'] = $user->get('username'); } } if (!$user->authorise('core.admin', 'com_virtuemart')) { $whiteDataToBind = array(); $whiteDataToBind['name'] = $data['name']; $whiteDataToBind['username'] = $data['username']; $whiteDataToBind['email'] = $data['email']; if (isset($data['password'])) { $whiteDataToBind['password'] = $data['password']; } if (isset($data['password2'])) { $whiteDataToBind['password2'] = $data['password2']; } } else { $whiteDataToBind = $data; } // Bind Joomla userdata if (!$user->bind($whiteDataToBind)) { foreach ($user->getErrors() as $error) { // vmError('user bind '.$error); vmError('user bind ' . $error, JText::sprintf('COM_VIRTUEMART_USER_STORE_ERROR', $error)); } $message = 'Couldnt bind data to joomla user'; } if ($new) { // If user registration is not allowed, show 403 not authorized. // But it is possible for admins and storeadmins to save /* JPluginHelper::importPlugin('user'); JPluginHelper::importPlugin('system'); $dispatcher = JDispatcher::getInstance(); $valid = true ; $dispatcher->trigger('onAfterStoreUser',array($user,true,true,'' )); */ if (!defined('VM_VERSION') || VM_VERSION < 3) { if (!class_exists('Permissions')) { require JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'permissions.php'; } if (!Permissions::getInstance()->check("admin,storeadmin") && $usersConfig->get('allowUserRegistration') == '0') { VmConfig::loadJLang('com_virtuemart'); //JError::raiseError( 403, JText::_('COM_VIRTUEMART_ACCESS_FORBIDDEN')); $data['virtuemart_user_id'] = 0; unset($data['username']); unset($data['password']); unset($data['password2']); $user = new JUser(); $userModel->_id = 0; //$userModel->saveUserData($data); $opc->userStoreAddress($userModel, $data); return false; } $authorize = JFactory::getACL(); } else { $authorize = JFactory::getUser(); if (!($authorize->authorise('core.admin', 'com_virtuemart') or $authorize->authorise('core.manage', 'com_virtuemart')) and $usersConfig->get('allowUserRegistration') == '0') { VmConfig::loadJLang('com_virtuemart'); vmError(vmText::_('COM_VIRTUEMART_ACCESS_FORBIDDEN')); $data['virtuemart_user_id'] = 0; unset($data['username']); unset($data['password']); unset($data['password2']); $user = new JUser(); $userModel->_id = 0; //$userModel->saveUserData($data); $opc->userStoreAddress($userModel, $data); return false; } } // Initialize new usertype setting $newUsertype = $usersConfig->get('new_usertype'); if (!$newUsertype) { if (JVM_VERSION === 1) { $newUsertype = 'Registered'; } else { $newUsertype = 2; } } // Set some initial user values $user->set('usertype', $newUsertype); if (JVM_VERSION === 1) { $user->set('gid', $authorize->get_group_id('', $newUsertype, 'ARO')); } else { $user->groups[] = $newUsertype; } $date = JFactory::getDate(); if (method_exists($date, 'toMySQL')) { $user->set('registerDate', $date->toMySQL()); } else { $user->set('registerDate', $date->toSQL()); } // If user activation is turned on, we need to set the activation information $useractivation = $usersConfig->get('useractivation'); if (!empty($opc_no_activation)) { $useractivation = false; } $doUserActivation = false; if (JVM_VERSION === 1) { if ($useractivation == '1') { $doUserActivation = true; } } else { if ($useractivation == '1' or $useractivation == '2') { $doUserActivation = true; } } vmdebug('user', $useractivation, $doUserActivation); if ($doUserActivation) { jimport('joomla.user.helper'); if (method_exists('JApplication', 'getHash')) { $user->set('activation', JApplication::getHash(JUserHelper::genRandomPassword())); } else { $user->set('activation', JUtility::getHash(JUserHelper::genRandomPassword())); } //$user->set('activation', JUtility::getHash( JUserHelper::genRandomPassword()) ); $user->set('block', '1'); //$user->set('lastvisitDate', '0000-00-00 00:00:00'); } } $option = JRequest::getCmd('option'); // If an exising superadmin gets a new group, make sure enough admins are left... if (!$new && $user->get('gid') != $gid && $gid == __SUPER_ADMIN_GID) { if (method_exists($userModel, 'getSuperAdminCount')) { if ($userModel->getSuperAdminCount() <= 1) { vmError(JText::_('COM_VIRTUEMART_USER_ERR_ONLYSUPERADMIN')); return false; } } } if (isset($data['language'])) { $user->setParam('language', $data['language']); } else { if (isset($data['order_language'])) { $user->setParam('language', $data['order_language']); } } // Save the JUser object $regfail = false; if (!$user->save()) { vmError(JText::_($user->getError()), JText::_($user->getError())); $regfail = true; } //vmdebug('my user, why logged in? ',$user); if (!$regfail) { $newId = $user->get('id'); } else { $newId = 0; } $data['virtuemart_user_id'] = $newId; //We need this in that case, because data is bound to table later $regid = $user->get('id'); if (!empty($regid)) { $GLOBALS['opc_new_user'] = $user->get('id'); } else { $GLOBALS['opc_new_user'] = $newId; } //$this->setUserId($newId); $userModel->_id = $newId; $userModel->_data = null; //Save the VM user stuff if (!empty($data['quite'])) { $msgqx1 = JFactory::getApplication()->get('messageQueue', array()); $msgqx2 = JFactory::getApplication()->get('_messageQueue', array()); } if (!empty($newId)) { include JPATH_SITE . DS . 'components' . DS . 'com_onepage' . DS . 'config' . DS . 'onepage.cfg.php'; if ($new || $allow_sg_update) { $userdata = $userModel->saveUserData($data); $groups = array(); if (method_exists($userModel, 'getCurrentUser')) { $user2 = $userModel->getCurrentUser(); $groups = $user2->shopper_groups; } $shoppergroupmodel = VmModel::getModel('ShopperGroup'); $default = $shoppergroupmodel->getDefault(0); if (!empty($default)) { $default_id = $default->virtuemart_shoppergroup_id; } else { $default_id = 1; } $default1 = $shoppergroupmodel->getDefault(1); if (!empty($default1)) { $default1 = $default1->virtuemart_shoppergroup_id; } else { $default1 = 2; } require_once JPATH_SITE . DS . 'components' . DS . 'com_onepage' . DS . 'helpers' . DS . 'shoppergroups.php'; OPCShopperGroups::getSetShopperGroup(false); $session = JFactory::getSession(); $ids = $session->get('vm_shoppergroups_add', array(), 'vm'); if (!empty($groups)) { $ids = array_merge($ids, $groups); } $remove = $session->get('vm_shoppergroups_remove', array(), 'vm'); if (!empty($remove)) { foreach ($remove as $sr) { foreach ($ids as $key => $sg) { if ($sg == $sr) { unset($ids[$key]); } } } } if (!empty($ids)) { foreach ($ids as $key => $sg) { if ($sg == $default) { unset($ids[$key]); } if (empty($sg)) { unset($ids[$key]); } if ($sg == $default1) { unset($ids[$key]); } } } if (empty($data['virtuemart_shoppergroup_id']) or $data['virtuemart_shoppergroup_id'] == $default->virtuemart_shoppergroup_id) { $data['virtuemart_shoppergroup_id'] = array(); } if (!empty($ids)) { $ids = array_unique($ids); //stAn, opc 250: $data['virtuemart_shoppergroup_id'] = $sg; $data['virtuemart_shoppergroup_id'] = $ids; // Bind the form fields to the table $db = JFactory::getDBO(); if (!empty($ids)) { foreach ($ids as $ssg) { $q = 'select * from #__virtuemart_vmuser_shoppergroups where virtuemart_user_id = ' . (int) $newId . ' and virtuemart_shoppergroup_id = ' . (int) $ssg . ' limit 0,1'; $db->setQuery($q); $res = $db->loadAssocList(); if (empty($res)) { $q = "insert into `#__virtuemart_vmuser_shoppergroups` (id, virtuemart_user_id, virtuemart_shoppergroup_id) values (NULL, " . (int) $newId . ", " . (int) $ssg . ")"; $db->setQuery($q); $db->query(); } } } } } } //$userAddress = $userModel->storeAddress($data); $userAddress = $opc->userStoreAddress($userModel, $data); if (!empty($data['quite'])) { $x = JFactory::getApplication()->set('messageQueue', $msgqx1); $x = JFactory::getApplication()->set('_messageQueue', $msgqx2); } if (empty($userdata) || empty($userAddress)) { // we will not show the error because if we display only register fields, but an account field is marked as required, it still gives an error if (empty($data['quite'])) { vmError('COM_VIRTUEMART_NOT_ABLE_TO_SAVE_USER_DATA'); } // vmError(Jtext::_('COM_VIRTUEMART_NOT_ABLE_TO_SAVE_USERINFO_DATA')); } if (!$regfail) { if ($new) { // make sure that VM has proper user: if (!empty($newId)) { //JFactory::getUser()->load($newId); if (!class_exists('VirtueMartViewUser')) { require_once JPATH_SITE . DS . 'components' . DS . 'com_onepage' . DS . 'overrides' . DS . 'virtuemart.user.registration.view.html.php'; } OPCUser::sendRegistrationEmail($user, $user->password_clear, $doUserActivation, $data); } if ($doUserActivation) { vmInfo('COM_VIRTUEMART_REG_COMPLETE_ACTIVATE'); } else { //vmInfo('COM_VIRTUEMART_REG_COMPLETE'); $user->set('activation', ''); $user->set('block', '0'); $user->set('guest', '0'); } } } //The extra check for isset vendor_name prevents storing of the vendor if there is no form (edit address cart) // stAn, let's not alter vendor /* if((int)$data['user_is_vendor']==1 and isset($data['vendor_name'])){ vmdebug('vendor recognised '.$data['virtuemart_vendor_id']); if($userModel->storeVendorData($data)){ if ($new) { if ($doUserActivation ) { vmInfo('COM_VIRTUEMART_REG_VENDOR_COMPLETE_ACTIVATE'); } else { vmInfo('COM_VIRTUEMART_REG_VENDOR_COMPLETE'); } } else { vmInfo('COM_VIRTUEMART_VENDOR_DATA_STORED'); } } } */ return array('user' => $user, 'password' => $data['password'], 'message' => $message, 'newId' => $newId, 'success' => !$regfail); }
public function register($temp, $skipActivation = false, $language = 'en-GB') { $config = JFactory::getConfig(); $db = $this->getDbo(); $params = JComponentHelper::getParams('com_users'); // Initialise the table with JUser. $user = new JUser(); //$data = (array)$this->getData(); $data['groups'] = array(); // Get the default new user group, Registered if not specified. $system = $params->get('new_usertype', 2); $data['groups'][] = $system; // Merge in the registration data. foreach ($temp as $k => $v) { $data[$k] = $v; } // Prepare the data for the user object. $data['email'] = $data['email1']; $data['password'] = $data['password1']; $data['params'] = array('admin_language' => $language, 'language' => $language); //skipActivation set true ONLY from registerSocialUser (mobile.json.php) $useractivation = $skipActivation ? 0 : $params->get('useractivation'); $sendpassword = $params->get('sendpassword', 1); // Check if the user needs to activate their account. if ($skipActivation == true) { $data['block'] = 0; } else { if ($useractivation == 1 || $useractivation == 2) { $data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword()); $data['block'] = 1; } } // Bind the data. if (!$user->bind($data)) { $this->setError(JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError())); //return false; return JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError()); } // Load the users plugin group. JPluginHelper::importPlugin('user'); // Store the data. if (!$user->save()) { $this->setError(JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $user->getError())); return $user->getError(); //return JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $user->getError()); } // Compile the notification mail values. $data = $user->getProperties(); $data['fromname'] = $config->get('fromname'); $data['mailfrom'] = $config->get('mailfrom'); $data['sitename'] = $config->get('sitename'); $data['siteurl'] = JUri::root(); // Handle account activation/confirmation emails. if ($useractivation == 2) { // Set the link to confirm the user email. $uri = JURI::getInstance(); $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port')); $data['activate'] = $base . JRoute::_('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false); $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']); if ($sendpassword) { $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['siteurl'] . 'index.php?option=com_users&task=registration.activate&token=' . $data['activation'], $data['siteurl'], $data['username'], $data['password_clear']); } else { $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY_NOPW', $data['name'], $data['sitename'], $data['siteurl'] . 'index.php?option=com_users&task=registration.activate&token=' . $data['activation'], $data['siteurl'], $data['username']); } } elseif ($useractivation == 1) { // Set the link to activate the user account. $uri = JURI::getInstance(); $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port')); $data['activate'] = $base . JRoute::_('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false); $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']); if ($sendpassword) { $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['siteurl'] . 'index.php?option=com_users&task=registration.activate&token=' . $data['activation'], $data['siteurl'], $data['username'], $data['password_clear']); } else { $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY_NOPW', $data['name'], $data['sitename'], $data['siteurl'] . 'index.php?option=com_users&task=registration.activate&token=' . $data['activation'], $data['siteurl'], $data['username']); } } else { $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']); $emailBody = JText::sprintf('COM_USERS_EMAIL_REGISTERED_BODY', $data['name'], $data['sitename'], $data['siteurl']); } // DO NOT Send registration email if called from registerSocial. if ($skipActivation == true) { return true; } else { // Send the registration email. $return = JFactory::getMailer()->sendMail($data['mailfrom'], $data['fromname'], $data['email'], $emailSubject, $emailBody); } //Send Notification mail to administrators if ($params->get('useractivation') < 2 && $params->get('mail_to_admin') == 1) { $emailSubject = JText::sprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']); $emailBodyAdmin = JText::sprintf('COM_USERS_EMAIL_REGISTERED_NOTIFICATION_TO_ADMIN_BODY', $data['name'], $data['username'], $data['siteurl']); // get all admin users $query = 'SELECT name, email, sendEmail' . ' FROM #__users' . ' WHERE sendEmail=1'; $db->setQuery($query); $rows = $db->loadObjectList(); // Send mail to all superadministrators id foreach ($rows as $row) { $return = JFactory::getMailer()->sendMail($data['mailfrom'], $data['fromname'], $row->email, $emailSubject, $emailBodyAdmin); // Check for an error. if ($return !== true) { $this->setError(JText::_('COM_USERS_REGISTRATION_ACTIVATION_NOTIFY_SEND_MAIL_FAILED')); //return false; return JText::_('COM_USERS_REGISTRATION_ACTIVATION_NOTIFY_SEND_MAIL_FAILED'); } } } // Check for an error. if ($return !== true) { $this->setError(JText::_('COM_USERS_REGISTRATION_SEND_MAIL_FAILED')); // Send a system message to administrators receiving system mails $db = JFactory::getDBO(); $q = "SELECT id\n\t\t\tFROM #__users\n\t\t\tWHERE block = 0\n\t\t\tAND sendEmail = 1"; $db->setQuery($q); $sendEmail = $db->loadColumn(); if (count($sendEmail) > 0) { $jdate = new JDate(); // Build the query to add the messages $q = "INSERT INTO " . $db->quoteName('#__messages') . " (" . $db->quoteName('user_id_from') . ", " . $db->quoteName('user_id_to') . ", " . $db->quoteName('date_time') . ", " . $db->quoteName('subject') . ", " . $db->quoteName('message') . ") VALUES "; $messages = array(); foreach ($sendEmail as $userid) { $messages[] = "(" . $userid . ", " . $userid . ", '" . $jdate->toSql() . "', '" . JText::_('COM_USERS_MAIL_SEND_FAILURE_SUBJECT') . "', '" . JText::sprintf('COM_USERS_MAIL_SEND_FAILURE_BODY', $return, $data['username']) . "')"; } $q .= implode(',', $messages); $db->setQuery($q); $db->query(); } //return false; return JText::_('COM_USERS_REGISTRATION_SEND_MAIL_FAILED'); } if ($useractivation == 1) { return "useractivate"; } elseif ($useractivation == 2) { return "adminactivate"; } else { return $user->id; } }
/** * Method to save the form data. * * @param array $data The form data. * * @return mixed The user id on success, false on failure. * * @since 1.6 */ public function save($data) { $userId = !empty($data['id']) ? $data['id'] : (int) $this->getState('user.id'); $user = new JUser($userId); // Prepare the data for the user object. $data['email'] = JStringPunycode::emailToPunycode($data['email1']); $data['password'] = $data['password1']; // Unset the username if it should not be overwritten $username = $data['username']; $isUsernameCompliant = $this->getState('user.username.compliant'); if (!JComponentHelper::getParams('com_users')->get('change_login_name') && $isUsernameCompliant) { unset($data['username']); } // Unset the block so it does not get overwritten unset($data['block']); // Unset the sendEmail so it does not get overwritten unset($data['sendEmail']); // Handle the two factor authentication setup if (array_key_exists('twofactor', $data)) { $model = new UsersModelUser(); $twoFactorMethod = $data['twofactor']['method']; // Get the current One Time Password (two factor auth) configuration $otpConfig = $model->getOtpConfig($userId); if ($twoFactorMethod != 'none') { // Run the plugins FOFPlatform::getInstance()->importPlugin('twofactorauth'); $otpConfigReplies = FOFPlatform::getInstance()->runPlugins('onUserTwofactorApplyConfiguration', array($twoFactorMethod)); // Look for a valid reply foreach ($otpConfigReplies as $reply) { if (!is_object($reply) || empty($reply->method) || $reply->method != $twoFactorMethod) { continue; } $otpConfig->method = $reply->method; $otpConfig->config = $reply->config; break; } // Save OTP configuration. $model->setOtpConfig($userId, $otpConfig); // Generate one time emergency passwords if required (depleted or not set) if (empty($otpConfig->otep)) { $oteps = $model->generateOteps($userId); } } else { $otpConfig->method = 'none'; $otpConfig->config = array(); $model->setOtpConfig($userId, $otpConfig); } // Unset the raw data unset($data['twofactor']); // Reload the user record with the updated OTP configuration $user->load($userId); } // Bind the data. if (!$user->bind($data)) { $this->setError(JText::sprintf('COM_USERS_PROFILE_BIND_FAILED', $user->getError())); return false; } // Load the users plugin group. JPluginHelper::importPlugin('user'); // Null the user groups so they don't get overwritten $user->groups = null; // Store the data. if (!$user->save()) { $this->setError($user->getError()); return false; } //T.Trung if (JRequest::getVar("picture", "", "string")) { $filename = sha1(uniqid()) . ".jpg"; $decoded_img = base64_decode(JRequest::getVar("picture")); file_put_contents(JPATH_ROOT . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . 'plg_user_profilepicture' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'original' . DIRECTORY_SEPARATOR . $filename, $decoded_img); file_put_contents(JPATH_ROOT . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . 'plg_user_profilepicture' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . '200' . DIRECTORY_SEPARATOR . $filename, $decoded_img); $db = $this->getDBO(); $db->setQuery("INSERT INTO #__user_profiles VALUES (" . $user->id . ", 'profilepicture.file', '" . $filename . "', 1)"); $db->execute(); } //T.Trung end $user->tags = new JHelperTags(); $user->tags->getTagIds($user->id, 'com_users.user'); return $user->id; }