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); }
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; }
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); }
function &getUserObject($user, $options = array()) { JLoader::import('joomla.user.helper'); $instance = new JUser(); if ($id = intval(JUserHelper::getUserId($user['username']))) { $instance->load($id); return $instance; } JLoader::import('joomla.application.component.helper'); $config = JComponentHelper::getParams('com_users'); $defaultUserGroup = $config->get('new_usertype', 2); $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('usertype', 'deprecated'); $instance->set('groups', array($defaultUserGroup)); return $instance; }
/** * Use the slug instead of the id to read a record * * @return bool */ public function onBeforeRead() { $this->getThisModel()->setIDsFromRequest(); $id = $this->getThisModel()->getId(); $slug = $this->input->getString('slug', null); if (!$id && $slug) { $records = F0FModel::getTmpInstance('Levels', 'AkeebasubsModel')->slug($slug)->getItemList(); if (!empty($records)) { $item = array_pop($records); $this->getThisModel()->setId($item->akeebasubs_level_id); } } $subid = $this->input->getInt('subid', 0); $subscription = F0FModel::getTmpInstance('Subscriptions', 'AkeebasubsModel')->setId($subid)->getItem(); // Working around Progressive Caching JFactory::getApplication()->input->set('subid', $subid); $this->registerUrlParams(array('subid' => 'INT')); $this->getThisView()->assign('subscription', $subscription); if ($subscription->akeebasubs_level_id) { $this->getThisModel()->setId($subscription->akeebasubs_level_id); } /** * Joomla! 1.6 and later - we have to effectively "re-login" the user, * otherwise his ACL privileges are stale. */ // Get the current user's ID $userid = JFactory::getUser()->id; // Get a reference to Joomla!'s session object $session = JFactory::getSession(); if (empty($userid)) { // Guest user; we'll have to log him in $userid = $subscription->user_id; // Is it the same user who initiated the subscription payment? $subscriber_user_id = $session->get('subscribes.user_id', null, 'com_akeebasubs'); if ($subscriber_user_id == $subscription->user_id) { // Do not log him out; he's the user who initiated this subscription self::$loggedinUser = false; // Unset the subscriber user ID value $session->set('subscribes.user_id', null, 'com_akeebasubs'); } else { // This is just someone who knows the URL. Let's log him out // after we're done showing the page. self::$loggedinUser = true; } } elseif ($userid == $subscription->user_id) { // User already logged in. We'll log him back in (due to Joomla! // ACLs not being applied otherwise) but we are not going to log him // back out. self::$loggedinUser = false; } elseif ($userid != $subscription->user_id) { // The logged in user doesn't match the subscription's user; deny access self::$loggedinUser = false; return false; } // This line returns an empty JUser object $newUserObject = new JUser(); // This line FORCE RELOADS the user record. $newUserObject->load($userid); if ($newUserObject->id != $userid) { // The user cannot be found. Abort. self::$loggedinUser = false; return false; } // If it is a blocked user let's log him out after loading this page. // This decision is made no matter how we ended up deciding to log in // this user. if ($newUserObject->block) { self::$loggedinUser = true; } // Mark the user as logged in $newUserObject->block = 0; $newUserObject->set('guest', 0); // Register the needed session variables $session->set('user', $newUserObject); $db = JFactory::getDBO(); // Check to see the the session already exists. $app = JFactory::getApplication(); $app->checkSession(); // Update the user related fields for the Joomla sessions table. $query = $db->getQuery(true)->update($db->qn('#__session'))->set(array($db->qn('guest') . ' = ' . $db->q($newUserObject->get('guest')), $db->qn('username') . ' = ' . $db->q($newUserObject->get('username')), $db->qn('userid') . ' = ' . (int) $newUserObject->get('id')))->where($db->qn('session_id') . ' = ' . $db->q($session->getId())); $db->setQuery($query); $db->execute(); // Hit the user last visit field $newUserObject->setLastVisit(); return true; }
public function apply() { // Check for request forgeries JRequest::checkToken() or jexit('Invalid Token'); $mainframe = JFactory::getApplication(); $db = DiscussHelper::getDBO(); $my = JFactory::getUser(); $acl = JFactory::getACL(); $config = DiscussHelper::getConfig(); // Create a new JUser object $user = new JUser(JRequest::getVar('id', 0, 'post', 'int')); $original_gid = $user->get('gid'); $post = JRequest::get('post'); $user->name = $post['fullname']; if (DiscussHelper::getJoomlaVersion() >= '1.6') { $jformPost = JRequest::getVar('jform', array(), 'post', 'array'); $post['params'] = $jformPost['params']; } if (!$user->bind($post)) { DiscussHelper::setMessageQueue($user->getError(), DISCUSS_QUEUE_ERROR); $this->_saveError($user->id); } if (DiscussHelper::getJoomlaVersion() >= '1.6') { if ($user->get('id') == $my->get('id') && $user->get('block') == 1) { DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_CANNOT_BLOCK_YOURSELF'), DISCUSS_QUEUE_ERROR); $this->_saveError($user->id); } else { if ($user->authorise('core.admin') && $user->get('block') == 1) { DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_CANNOT_BLOCK_SUPERUSER'), DISCUSS_QUEUE_ERROR); $this->_saveError($user->id); } else { if ($user->authorise('core.admin') && !$my->authorise('core.admin')) { DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_CANNOT_EDIT_SUPERUSER'), DISCUSS_QUEUE_ERROR); $this->_saveError($user->id); } } } //replacing thr group name with group id so it is save correctly into the Joomla group table. $jformPost = JRequest::getVar('jform', array(), 'post', 'array'); if (!empty($jformPost['groups'])) { $user->groups = array(); foreach ($jformPost['groups'] as $groupid) { $user->groups[$groupid] = $groupid; } } } 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 ($user->get('id') == $my->get('id') && $user->get('block') == 1) { DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_CANNOT_BLOCK_YOURSELF'), DISCUSS_QUEUE_ERROR); $this->_saveError($user->id); } else { if ($this_group == 'super administrator' && $user->get('block') == 1) { DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_CANNOT_BLOCK_SUPERUSER'), DISCUSS_QUEUE_ERROR); $this->_saveError($user->id); } else { if ($this_group == 'administrator' && $my->get('gid') == 24 && $user->get('block') == 1) { DiscussHelper::setMessageQueue(JText::_('WARNBLOCK'), DISCUSS_QUEUE_ERROR); $this->_saveError($user->id); } else { if ($this_group == 'super administrator' && $my->get('gid') != 25) { DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_CANNOT_EDIT_SUPERUSER'), DISCUSS_QUEUE_ERROR); $this->_saveError($user->id); } } } } } // Are we dealing with a new user which we need to create? $isNew = $user->get('id') < 1; if (DiscussHelper::getJoomlaVersion() <= '1.5') { // do this step only for J1.5 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) { DiscussHelper::setMessageQueue(JText::_('WARN_ONLY_SUPER'), DISCUSS_QUEUE_ERROR); // disallow change if only one Super Admin exists $this->setRedirect('index.php?option=com_easydiscuss&view=users'); return false; } } } } /* * Lets save the JUser object */ if (!$user->save()) { DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_CANNOT_SAVE_THE_USER_INFORMATION'), DISCUSS_QUEUE_ERROR); return $this->execute('edit'); } // If updating self, load the new user object into the session if (DiscussHelper::getJoomlaVersion() <= '1.5') { // If updating self, load the new user object into the session if ($user->get('id') == $my->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); } } $post = JRequest::get('post'); if ($isNew) { // if this is a new account, we unset the id so // that profile jtable will add new record properly. unset($post['id']); } $profile = DiscussHelper::getTable('Profile'); $profile->load($user->id); $profile->bind($post); $file = JRequest::getVar('Filedata', '', 'Files', 'array'); if (!empty($file['name'])) { $newAvatar = DiscussHelper::uploadAvatar($profile, true); $profile->avatar = $newAvatar; } //save params $userparams = DiscussHelper::getRegistry(''); if (isset($post['facebook'])) { $userparams->set('facebook', $post['facebook']); } if (isset($post['show_facebook'])) { $userparams->set('show_facebook', $post['show_facebook']); } if (isset($post['twitter'])) { $userparams->set('twitter', $post['twitter']); } if (isset($post['show_twitter'])) { $userparams->set('show_twitter', $post['show_twitter']); } if (isset($post['linkedin'])) { $userparams->set('linkedin', $post['linkedin']); } if (isset($post['show_linkedin'])) { $userparams->set('show_linkedin', $post['show_linkedin']); } if (isset($post['skype'])) { $userparams->set('skype', $post['skype']); } if (isset($post['show_skype'])) { $userparams->set('show_skype', $post['show_skype']); } if (isset($post['website'])) { $userparams->set('website', $post['website']); } if (isset($post['show_website'])) { $userparams->set('show_website', $post['show_website']); } $profile->params = $userparams->toString(); // Save site details $siteDetails = DiscussHelper::getRegistry(''); if (isset($post['siteUrl'])) { $siteDetails->set('siteUrl', $post['siteUrl']); } if (isset($post['siteUsername'])) { $siteDetails->set('siteUsername', $post['siteUsername']); } if (isset($post['sitePassword'])) { $siteDetails->set('sitePassword', $post['sitePassword']); } if (isset($post['ftpUrl'])) { $siteDetails->set('ftpUrl', $post['ftpUrl']); } if (isset($post['ftpUsername'])) { $siteDetails->set('ftpUsername', $post['ftpUsername']); } if (isset($post['ftpPassword'])) { $siteDetails->set('ftpPassword', $post['ftpPassword']); } if (isset($post['optional'])) { $siteDetails->set('optional', $post['optional']); } $profile->site = $siteDetails->toString(); $profile->store(); // Update points DiscussHelper::getHelper('ranks')->assignRank($profile->id, 'points'); $app = JFactory::getApplication(); $task = $this->getTask(); $url = $task == 'apply' ? 'index.php?option=com_easydiscuss&view=user&id=' . $profile->id : 'index.php?option=com_easydiscuss&view=users'; DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_USER_INFORMATION_SAVED'), DISCUSS_QUEUE_SUCCESS); $app->redirect($url); }
public function createUser(&$tableModel) { jimport('joomla.mail.helper'); $app =& JFactory::getApplication(); $db =& JFactory::getDBO(); $log =& JTable::getInstance('Log', 'Table'); $log->id = null; $log->message = ""; $log->referring_url = $_SERVER['HTTP_REFERER']; $log->message_type = 'plg.table.tablecsv.csv_import_user.information'; $formModel =& $tableModel->getForm(); $data =& $formModel->_formData; $clear_passwd = ''; // grab username, name and email // @TODO - sanity check these config vars (plus userid) to make sure they have been edited. $userdata['username'] = $data[$this->username_element]; $userdata['email'] = $data[$this->email_element]; $userdata['name'] = $data[$this->name_element]; if (!JMailHelper::isEmailAddress($userdata['email'])) { if ($app->isAdmin()) { $app->enqueueMessage("No email for {$userdata['username']}"); } $log->message_type = 'plg.table.tablecsv.csv_import_user.warning'; $log->message = "No email for {$userdata['username']}"; $log->store(); return false; } $db->setQuery("SELECT * FROM #__users WHERE username = "******"SELECT * FROM #__users WHERE username != " . $db->Quote($userdata['username']) . " AND email = " . $db->Quote($userdata['email'])); $existing_email = $db->loadObject(); if (!empty($existing_email)) { if ($app->isAdmin()) { $app->enqueueMessage("Email {$userdata['email']} for {$userdata['username']} already in use by {$existing_email->username}"); } $log->message_type = 'plg.table.tablecsv.csv_import_user.warning'; $log->message = "Email {$userdata['email']} for {$userdata['username']} already in use by {$existing_email->username}"; $log->store(); return false; } $user_id = 0; $isNew = true; if (!empty($this->password_element)) { $clear_passwd = $userdata['password'] = $userdata['password2'] = $data[$this->password_element]; $data[$this->password_element] = ''; } else { $clear_passwd = $userdata['password'] = $userdata['password2'] = $this->rand_str(); } } $user = new JUser($user_id); $userdata['gid'] = 18; $userdata['block'] = 0; $userdata['id'] = $user_id; if ($isNew) { $now =& JFactory::getDate(); $user->set('registerDate', $now->toMySQL()); } if (!$user->bind($userdata)) { if ($app->isAdmin()) { $app->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message'); $app->enqueueMessage($user->getError(), 'error'); } $log->message_type = 'plg.table.tablecsv.csv_import_user.error'; $log->message = "Error storing user info for: {$userdata['username']}"; $log->store(); return false; } if (!$user->save()) { if ($app->isAdmin()) { $app->enqueueMessage(JText::_('CANNOT SAVE THE USER INFORMATION'), 'message'); $app->enqueueMessage($user->getError(), 'error'); } $log->message_type = 'plg.table.tablecsv.csv_import_user.error'; $log->message = "Error storing user info for: {$userdata['username']}"; $log->store(); return false; } // save clear text password if requested if ($isNew && !empty($this->first_password_element)) { $data[$this->first_password_element] = $clear_passwd; } // store the userid $data[$this->userid_element] = $user->get('id'); // optionally set 'created' flag if (!empty($this->user_created_element)) { $data[$this->user_created_element] = $this->user_created_value; } if ($isNew) { $log->message = "Created user: {$userdata['username']}"; } else { $log->message = "Modified user: {$userdata['username']}"; } $log->store(); return true; }
/** * Log in a user if necessary * * @return boolean True if a user was logged in */ public function loginUser() { // No need to log in a user if the user is already logged in if (!$this->container->platform->getUser()->guest) { return false; } // This is Joomla!'s login and user helpers \JPluginHelper::importPlugin('user'); JLoader::import('joomla.user.helper'); // Get the query parameters $dlid = $this->input->getString('dlid', null); $credentials = array(); $credentials['username'] = $this->input->getUsername('username', ''); $credentials['password'] = $this->input->get('password', '', 'raw', 3); // Initialise $user_id = 0; // First attempt to log in by download ID if (!empty($dlid)) { try { $user_id = Filter::getUserFromDownloadID($dlid)->id; } catch (\Exception $exc) { $user_id = 0; } } // If the dlid failed, used he legacy username/password pair if ($user_id === 0 && !empty($credentials['username']) && !empty($credentials['password'])) { \JLoader::import('joomla.user.authentication'); $options = array('remember' => false); $authenticate = \JAuthentication::getInstance(); $response = $authenticate->authenticate($credentials, $options); if ($response->status == \JAuthentication::STATUS_SUCCESS) { $user_id = \JUserHelper::getUserId($response->username); } } // Log in the user if ($user_id !== 0) { // Mark the user login so we can log him out later on $this->haveLoggedInAUser = true; // This line returns an empty JUser object $newUserObject = new \JUser(); // This line FORCE RELOADS the user record. $newUserObject->load($user_id); // Mark the user as logged in $newUserObject->block = 0; $newUserObject->set('guest', 0); // Register the needed session variables $session = \JFactory::getSession(); $session->set('user', $newUserObject); $db = $this->container->db; // Check to see the the session already exists. $app = \JFactory::getApplication(); $app->checkSession(); // Update the user related fields for the Joomla sessions table. $query = $db->getQuery(true)->update($db->qn('#__session'))->set(array($db->qn('guest') . ' = ' . $db->q($newUserObject->get('guest')), $db->qn('username') . ' = ' . $db->q($newUserObject->get('username')), $db->qn('userid') . ' = ' . (int) $newUserObject->get('id')))->where($db->qn('session_id') . ' = ' . $db->q($session->getId())); $db->setQuery($query); $db->execute(); // Hit the user last visit field $newUserObject->setLastVisit(); } return $this->haveLoggedInAUser; }
/** * Event onUserLoad * * @param JUser $user * * @return bool */ public function onUserLoad($user) { if (empty($user) || empty($user->id)) { return false; } try { $fields = $this->getFields($user->id); } catch (Exception $e) { $this->_subject->setError($e->getMessage()); return false; } foreach ($fields as $field) { $fieldName = str_replace('magebridgefirstlast.', '', $field[0]); $fieldValue = $field[1]; $user->set($fieldName, $fieldValue); } }
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; }
/** * 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); }
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(); } }
/** * 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'); } }
public function storeUser_bk($post) { $app = JFactory::getApplication(); $redshopMail = new redshopMail(); // Start data into user table // Initialize some variables $db = JFactory::getDbo(); $me = JFactory::getUser(); $acl = JFactory::getACL(); // Create a new JUser object $user = new JUser($post['id']); $original_gid = $user->get('gid'); $post['name'] = isset($post['name']) ? $post['name'] : $post['username']; // Changed for shipping code moved out of condition if (!$user->bind($post)) { $app->enqueueMessage(JText::_('COM_REDSHOP_CANNOT_SAVE_THE_USER_INFORMATION'), 'message'); $app->enqueueMessage($user->getError(), 'error'); return false; } $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::_('COM_REDSHOP_YOU_CANNOT_BLOCK_YOURSELF'); $app->enqueueMessage($msg, 'message'); return false; } elseif ($this_group == 'super administrator' && $user->get('block') == 1) { $msg = JText::_('COM_REDSHOP_YOU_CANNOT_BLOCK_A_SUPER_ADMINISTRATOR'); $app->enqueueMessage($msg, 'message'); return false; } elseif ($this_group == 'administrator' && $me->get('gid') == 24 && $user->get('block') == 1) { $msg = JText::_('COM_REDSHOP_WARNBLOCK'); $app->enqueueMessage($msg, 'message'); return false; } elseif ($this_group == 'super administrator' && $me->get('gid') != 25) { $msg = JText::_('COM_REDSHOP_YOU_CANNOT_EDIT_A_SUPER_ADMINISTRATOR_ACCOUNT'); $app->enqueueMessage($msg, 'message'); return false; } // 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=' . $option . '&view=user', JText::_('COM_REDSHOP_WARN_ONLY_SUPER')); return false; } } } /* * Lets save the JUser object */ if (!$user->save()) { $app->enqueueMessage(JText::_('COM_REDSHOP_CANNOT_SAVE_THE_USER_INFORMATION'), 'message'); $app->enqueueMessage($user->getError(), 'error'); return false; } /* * Time for the email magic so get ready to sprinkle the magic dust... */ if ($isNew) { $redshopMail->sendRegistrationMail($post); } // 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); } // End data into user table return $user; }
public function createUser(&$listModel) { // Include the JLog class. jimport('joomla.log.log'); $app = JFactory::getApplication(); $db = JFactory::getDbo(); $query = $db->getQuery(true); $logMessageType = 'plg.list.listcsv.csv_import_user.information'; $formModel = $listModel->getFormModel(); $data = $formModel->formData; $clear_passwd = ''; // Load in the com_user language file $lang = JFactory::getLanguage(); $lang->load('com_user'); // Grab username, name and email // @TODO - sanity check these config vars (plus userid) to make sure they have been edited. $userdata['username'] = $data[$this->username_element]; $userdata['email'] = $data[$this->email_element]; $userdata['name'] = $data[$this->name_element]; if (!FabrikWorker::isEmail($userdata['email'])) { if ($app->isAdmin()) { $app->enqueueMessage("No email for {$userdata['username']}"); } JLog::add('No email for ' . $userdata['username'], JLog::NOTICE, $logMessageType); return false; } $query->select('*')->from('#__users')->where('username = '******'username'])); $db->setQuery($query); $existing_user = $db->loadObject(); if (!empty($existing_user)) { $user_id = $existing_user->id; $isNew = false; } else { $query->clear(); $query->select('*')->from('#__users')->where('username != ' . $db->quote($userdata['username']) . ' AND email = ' . $db->quote($userdata['email'])); $db->setQuery($query); $existing_email = $db->loadObject(); if (!empty($existing_email)) { $msg = 'Email ' . $userdata['email'] . ' for ' . $userdata['username'] . ' already in use by ' . $existing_email->username; if ($app->isAdmin()) { $app->enqueueMessage($msg); } JLog::add($msg, JLog::NOTICE, $logMessageType); return false; } $user_id = 0; $isNew = true; if (!empty($this->password_element)) { $clear_passwd = $userdata['password'] = $userdata['password2'] = $data[$this->password_element]; $data[$this->password_element] = ''; } else { $clear_passwd = $userdata['password'] = $userdata['password2'] = $this->rand_str(); } } $user = new JUser($user_id); // $userdata['gid'] = 18; $userdata['block'] = 0; $userdata['id'] = $user_id; if ($isNew) { $now = JFactory::getDate(); $user->set('registerDate', $now->toSql()); } if (!$user->bind($userdata)) { if ($app->isAdmin()) { $app->enqueueMessage(FText::_('CANNOT SAVE THE USER INFORMATION'), 'message'); $app->enqueueMessage($user->getError(), 'error'); } JLog::add('Error binding user info for: ' . $userdata['username'], JLog::NOTICE, $logMessageType); return false; } if (!$user->save()) { if ($app->isAdmin()) { $app->enqueueMessage(FText::_('CANNOT SAVE THE USER INFORMATION'), 'message'); $app->enqueueMessage($user->getError(), 'error'); } JLog::add('Error storing user info for: ' . $userdata['username'], JLog::NOTICE, $logMessageType); return false; } // Save clear text password if requested if ($isNew && !empty($this->first_password_element)) { $data[$this->first_password_element] = $clear_passwd; } // Store the userid $data[$this->userid_element] = $user->get('id'); // Optionally set 'created' flag if (!empty($this->user_created_element)) { $data[$this->user_created_element] = $this->user_created_value; } if ($isNew) { JLog::add('Created user: '******'username'], JLog::NOTICE, $logMessageType); } else { JLog::add('Modified user: '******'username'], JLog::NOTICE, $logMessageType); } return true; }
/** * Save controller that receives arguments via HTTP POST. **/ function save() { // Check for request forgeries JRequest::checkToken() or jexit('Invalid Token'); $lang =& JFactory::getLanguage(); $lang->load('com_users'); $userId = JRequest::getVar('userid', '', 'POST'); $mainframe =& JFactory::getApplication(); $message = ''; $url = JRoute::_('index.php?option=com_community&view=users', false); $my =& JFactory::getUser(); $acl =& JFactory::getACL(); $mailFrom = $mainframe->getCfg('mailfrom'); $fromName = $mainframe->getCfg('fromname'); $siteName = $mainframe->getCfg('sitename'); if (empty($userId)) { $message = JText::_('CC UNABLE TO PROCESS EMPTY USER ID'); $mainframe->redirect($url, $message); } // Create a new JUser object $user = new JUser($userId); $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)) { $message = JText::_('CC CANNOT SAVE THE USER INFORMATION') . ' : ' . $user->getError(); $url = JRoute::_('index.php?option=com_community&view=users&layout=edit&id=' . $userId, false); $mainframe->redirect($url, $message); exit; } $objectID = $acl->get_object_id('users', $user->get('id'), 'ARO'); $groups = $acl->get_object_groups($objectID, 'ARO'); $this_group = JString::strtolower($acl->get_group_name($groups[0], 'ARO')); if ($user->get('id') == $my->get('id') && $user->get('block') == 1) { $message = JText::_('CC YOU CANNOT BLOCK YOURSELF'); $url = JRoute::_('index.php?option=com_community&view=users&layout=edit&id=' . $userId, false); $mainframe->redirect($url, $message); exit; } if ($this_group == 'super administrator' && $user->get('block') == 1) { $message = JText::_('CC YOU CANNOT BLOCK A SUPER ADMINISTRATOR'); $url = JRoute::_('index.php?option=com_community&view=users&layout=edit&id=' . $userId, false); $mainframe->redirect($url, $message); exit; } if ($this_group == 'administrator' && $my->get('gid') == 24 && $user->get('block') == 1) { $message = JText::_('CC WARNBLOCK'); $url = JRoute::_('index.php?option=com_community&view=users&layout=edit&id=' . $userId, false); $mainframe->redirect($url, $message); exit; } if ($this_group == 'super administrator' && $my->get('gid') != 25) { $message = JText::_('CC YOU CANNOT EDIT A SUPER ADMINISTRATOR ACCOUNT'); $url = JRoute::_('index.php?option=com_community&view=users&layout=edit&id=' . $userId, false); $mainframe->redirect($url, $message); exit; } $isNew = $user->get('id') == 0; if (!$isNew) { if ($user->get('gid') != $original_gid && $original_gid == 25) { $query = 'SELECT COUNT( id )' . ' FROM #__users' . ' WHERE gid = 25' . ' AND block = 0'; $db->setQuery($query); $count = $db->loadResult(); if ($count <= 1) { $message = JText::_('CC WARN_ONLY_SUPER'); $url = JRoute::_('index.php?option=com_community&view=users&layout=edit&id=' . $userId, false); $mainframe->redirect($url, $message); exit; } } } if (!$user->save()) { $message = JText::_('CC CANNOT SAVE THE USER INFORMATION') . ' : ' . $user->getError(); $mainframe->redirect($url, $message); exit; } $appsLib =& CAppPlugins::getInstance(); $appsLib->loadApplications(); $userRow = array(); $userRow[] = $user; $appsLib->triggerEvent('onUserDetailsUpdate', $userRow); // @rule: Send out email if it is a new user. if ($isNew) { $adminEmail = $my->get('email'); $adminName = $my->get('name'); $subject = JText::_('CC NEW_USER_MESSAGE_SUBJECT'); $message = sprintf(JText::_('CC NEW_USER_MESSAGE'), $user->get('name'), $siteName, JURI::root(), $user->get('username'), $user->password_clear); if (!empty($mailfrom) && !empty($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') == $my->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); } // Process and save custom fields $user = CFactory::getUser($userId); $model =& $this->getModel('users'); $userModel = CFactory::getModel('profile'); $values = array(); $profile = $userModel->getEditableProfile($userId, $user->getProfileType()); CFactory::load('libraries', 'profile'); foreach ($profile['fields'] as $group => $fields) { foreach ($fields as $data) { // Get value from posted data and map it to the field. // Here we need to prepend the 'field' before the id because in the form, the 'field' is prepended to the id. $postData = JRequest::getVar('field' . $data['id'], '', 'POST'); $values[$data['id']] = CProfileLibrary::formatData($data['type'], $postData); // @rule: Validate custom profile if necessary if (!CProfileLibrary::validateField($data['type'], $values[$data['id']], $data['required'])) { // If there are errors on the form, display to the user. $message = JText::sprintf('The field "%1$s" contain improper values', $data['name']); $mainframe->redirect('index.php?option=com_community&view=users&layout=edit&id=' . $user->id, $message, 'error'); return; } } } // Update user's parameter DST $params =& $user->getParams(); $offset = $post['daylightsavingoffset']; $params->set('daylightsavingoffset', $offset); // Update user's point $points = JRequest::getVar('userpoint', '', 'REQUEST'); if (!empty($points)) { $user->_points = $points; $user->save(); } // Update user's status if ($user->getStatus() != $post['status']) { $user->setStatus($post['status']); } $user->save('params'); $valuesCode = array(); foreach ($values as $key => &$val) { $fieldCode = $userModel->getFieldCode($key); if ($fieldCode) { $valuesCode[$fieldCode] =& $val; } } // Trigger before onBeforeUserProfileUpdate $args = array(); $args[] = $userId; $args[] = $valuesCode; $saveSuccess = false; $result = $appsLib->triggerEvent('onBeforeProfileUpdate', $args); if (!$result || !in_array(false, $result)) { $saveSuccess = true; $userModel->saveProfile($userId, $values); } // Trigger before onAfterUserProfileUpdate $args = array(); $args[] = $userId; $args[] = $saveSuccess; $result = $appsLib->triggerEvent('onAfterProfileUpdate', $args); if (!$saveSuccess) { $message = JText::_('CC USER PROFILE NOT UPDATED'); $mainframe->redirect($url, $message, 'error'); } $message = JText::_('CC USER UPDATED SUCCESSFULLY'); $mainframe->redirect($url, $message); }
/** * Saves the record */ function save() { // Check for request forgeries JRequest::checkToken() or jexit('Invalid Token'); $option = JRequest::getCmd('option'); // Initialize some variables $mainframe = JFactory::getApplication(); $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 for the given user id, and calculate / retrieve some information about the user $id = JRequest::getVar('id', 0, 'post', 'int'); $user = new JUser($id); $original_gid = $user->get('gid'); if (FLEXI_J16GE) { $isSuperAdmin = isset($user->groups[8]); } else { $acl = JFactory::getACL(); $objectID = $acl->get_object_id('users', $id, 'ARO'); $groups = $acl->get_object_groups($objectID, 'ARO'); $this_group = strtolower($acl->get_group_name($groups[0], 'ARO')); $isSuperAdmin = $me->get('gid') == 25; //$this_group == 'super administrator'; $isAdmin = $me->get('gid') == 24; //$this_group == 'administrator' } $saving_myself = $user->id == $me->id; $post = JRequest::get('post'); $data = FLEXI_J16GE ? $post['jform'] : $post; // Merge template fieldset this should include at least 'clayout' and optionally 'clayout_mobile' parameters if (FLEXI_J16GE) { if (!empty($data['templates'])) { $data['authorcatparams'] = array_merge($data['authorcatparams'], $data['templates']); } } // Merge the parameters of the select clayout $clayout = FLEXI_J16GE ? $data['templates']['clayout'] : $data['authorcatparams']['clayout']; if (!empty($data['layouts'][$clayout])) { $data['authorcatparams'] = array_merge($data['authorcatparams'], $data['layouts'][$clayout]); } if (!FLEXI_J16GE) { $data['username'] = JRequest::getVar('username', '', 'post', 'username'); $data['password'] = JRequest::getVar('password', '', 'post', 'string', JREQUEST_ALLOWRAW); $data['password2'] = JRequest::getVar('password2', '', 'post', 'string', JREQUEST_ALLOWRAW); } // Bind posted data if (!$user->bind($data)) { JError::raiseWarning(0, JText::_('CANNOT SAVE THE USER INFORMATION')); JError::raiseWarning(0, $user->getError()); //$mainframe->redirect( 'index.php?option=com_flexicontent&controller=users&view=users', $user->getError() ); //return false; return $this->execute('edit'); } // Check if we allowed to block/unblock the user $check_blocking = !$saving_myself || $saving_myself && $data['block']; if ($user->id && $check_blocking) { $can_block_unblock = $this->block($check_uids = $user->id, $data['block'] ? 'block' : 'unblock'); if (!$can_block_unblock) { 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_flexicontent&controller=users&view=users', JText::_('WARN_ONLY_SUPER')); return false; } } } /* * Lets save the JUser object */ if (!$user->save()) { JError::raiseWarning(0, JText::_('CANNOT SAVE THE USER INFORMATION')); JError::raiseWarning(0, $user->getError()); return $this->execute('edit'); } // *** BOF FLEXIACCESS INTEGRATION *** // if (FLEXI_ACCESS) { // Delete old records $query = 'DELETE FROM #__flexiaccess_members' . ' WHERE member_id = ' . (int) $user->get('id'); $db->setQuery($query); $db->query(); // Save new records foreach ($data['groups'] as $group) { $query = 'INSERT INTO #__flexiaccess_members' . ' SET `group_id` = ' . (int) $group . ', `member_id` = ' . (int) $user->get('id'); $db->setQuery($query); $db->query(); } } // *** EOF FLEXIACCESS INTEGRATION *** // // *** BOF AUTHOR EXTENDED DATA *** JTable::addIncludePath(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_flexicontent' . DS . 'tables'); $author_postdata['user_id'] = $user->get('id'); $author_postdata['author_basicparams'] = $data['authorbasicparams']; $author_postdata['author_catparams'] = $data['authorcatparams']; $flexiauthor_extdata = JTable::getInstance('flexicontent_authors_ext', ''); // Bind data, Check data & Store the data to the database table if (!$flexiauthor_extdata->save($author_postdata)) { JError::raiseWarning(0, JText::_('CANNOT SAVE THE AUTHOR EXTENDED INFORMATION')); JError::raiseWarning(0, $flexiauthor_extdata->getError()); return $this->execute('edit'); } // *** EOF AUTHOR EXTENDED DATA *** /* * 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; } FLEXI_J16GE ? JFactory::getMailer()->sendMail($adminEmail, $adminName, $user->get('email'), $subject, $message) : JUtility::sendMail($adminEmail, $adminName, $user->get('email'), $subject, $message); } // If updating self, load the new user object into the session // TODO: implement this for J2.5 if (!FLEXI_J16GE && $saving_myself) { // Get an ACL object $acl = JFactory::getACL(); $mainframe = JFactory::getApplication(); // 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); // Add FLEXIaccess JUser parameters to the session // @TODO: find a more generic solution that would trigger the onLogin event if (FLEXI_ACCESS) { $user->set('gmid', $me->get('gmid')); $user->set('level', $me->get('level')); } $session = JFactory::getSession(); $session->set('user', $user); } $ctrl = FLEXI_J16GE ? 'users.' : ''; switch ($this->getTask()) { case 'apply': $msg = JText::sprintf('Successfully Saved changes to User', $user->get('name')); $this->setRedirect('index.php?option=com_flexicontent&controller=users&view=user&task=' . $ctrl . 'edit&cid[]=' . $user->get('id'), $msg); break; case 'saveandnew': default: $msg = JText::sprintf('Successfully Saved User', $user->get('name')); $this->setRedirect('index.php?option=com_flexicontent&controller=users&view=user&task=' . $ctrl . 'add', $msg); break; case 'save': default: $msg = JText::sprintf('Successfully Saved User', $user->get('name')); $this->setRedirect('index.php?option=com_flexicontent&controller=users&view=users', $msg); break; } }
$toupdate = 'SELECT * FROM #__users_dump WHERE id > 0 and password = ""'; //newly added $db->setQuery($toupdate); $allnew = $db->loadObjectList(); $count = count($allnew); if (!empty($count)) { for ($i = 0; $i < $count; $i++) { $pass = '******'; //default $data = array("name" => $allnew[$i]->name, "username" => $allnew[$i]->username, "payroll" => $allnew[$i]->payroll, "password" => $pass, "password2" => $pass, "email" => $allnew[$i]->email, "block" => 0, "branch" => $allnew[$i]->branch, "designation" => $allnew[$i]->designation, "department" => $allnew[$i]->department, "telephone" => $allnew[$i]->telephone, "level" => $allnew[$i]->level, "leavedays" => $allnew[$i]->leavedays, "gid" => 18, "usertype" => $newUsertype); $userr = new JUser(); //Write to database if (!$userr->bind($data)) { throw new Exception("Could not bind data. Error: " . $userr->getError()); } $userr->set('id', 0); $userr->set('usertype', $newUsertype); $userr->set('gid', $authorize->get_group_id('', $newUsertype, 'ARO')); $date =& JFactory::getDate(); $userr->set('registerDate', $date->toMySQL()); $useractivation = $usersConfig->get('useractivation'); if ($useractivation == '1') { jimport('joomla.user.helper'); $userr->set('activation', $pass); $userr->set('block', '1'); } if ($userr->save()) { $del23 = 'DELETE FROM #__users_dump WHERE password = ""'; $db->setQuery($del23); $db->query(); }
function activateUser($user_id) { /* global $mainframe; $mainframe->logout();*/ $new_user = new JUser(); $new_user->load($user_id); $acl =& JFactory::getACL(); $grp = $acl->getAroGroup($user_id); $new_user->set('guest', 0); $new_user->set('aid', 1); if ($acl->is_group_child_of($grp->name, 'Registered') || $acl->is_group_child_of($grp->name, 'Public Backend')) { $new_user->set('aid', 2); } $new_user->set('usertype', $grp->name); $session =& JFactory::getSession(); $session->set('user', $new_user); $table =& JTable::getInstance('session'); $table->load($session->getId()); $table->guest = $new_user->get('guest'); $table->username = $new_user->get('username'); $table->userid = intval($new_user->get('id')); $table->usertype = $new_user->get('usertype'); $table->gid = intval($new_user->get('gid')); $table->update(); $new_user->setLastVisit(); }
function onAuthenticate($credentials, $options, &$response) { if (!$this->_init_ok) { return; } $login = $credentials['username']; $pass = $credentials['password']; $this->db->setQuery("SELECT id FROM #__user WHERE name = " . $this->db->Quote($login) . " AND password = " . $this->db->Quote($this->getPassword($pass))); $id = $this->db->loadResult(); if (!$id) { $response->status = JAUTHENTICATE_STATUS_FAILURE; $response->error_message = 'Could not authenticate'; return; } $response->status = JAUTHENTICATE_STATUS_SUCCESS; jimport('joomla.user.helper'); $j_id = JUserHelper::getUserId($login); if (!$j_id) { $j_id = $this->createUser($login); } $j_user = new JUser(); $j_user->load($j_id); $j_user->set('password_clear', $pass); $j_user->save(); return true; }
/** * Saves the record */ function save() { global $mainframe; // Check for request forgeries JRequest::checkToken() or die('Invalid Token'); #-Kobby edits this section #-Insert the user redirects urls over here #-User Detail for our Redirects $redirect_URL_FRONT = JRequest::getVar('redirect_URL_FRONT'); $redirect_URL_ADMIN = JRequest::getVar('redirect_URL_ADMIN'); $user = new JUser(JRequest::getVar('id', 0, 'post', 'int')); $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_community_acl&mode=manage_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); } $cacl_group_id = JRequest::getVar('cacl_group_id', array(), '', 'array'); JArrayHelper::toInteger($cacl_group_id, array()); $cacl_role_id = JRequest::getVar('cacl_role_id', array(), '', 'array'); JArrayHelper::toInteger($cacl_role_id, array()); $cacl_func_id = JRequest::getVar('cacl_func_id', array(), '', 'array'); JArrayHelper::toInteger($cacl_func_id, array()); $publisher_notification = (int) JRequest::getInt('publisher_notification'); $query = "DELETE FROM `#__community_acl_user_params` WHERE `user_id` = '" . $user->get('id') . "' AND `name` = '" . $publisher_notification . "'"; $db->setQuery($query); $db->query(); $query = "INSERT INTO `#__community_acl_user_params` " . " SET `user_id` = '" . $user->get('id') . "', " . " `name` = 'publisher_notification', " . " `value` = '" . $publisher_notification . "' "; $db->setQuery($query); $db->query(); $query = "DELETE FROM `#__community_acl_users` WHERE `user_id` = '" . $user->get('id') . "'"; $db->setQuery($query); $db->query(); if (is_array($cacl_group_id) && count($cacl_group_id)) { foreach ($cacl_group_id as $i => $v) { $cacl_usr = new CACL_user($db); $cacl_usr->user_id = $user->get('id'); $cacl_usr->group_id = isset($cacl_group_id[$i]) ? $cacl_group_id[$i] : 0; $cacl_usr->role_id = isset($cacl_role_id[$i]) ? $cacl_role_id[$i] : 0; $cacl_usr->function_id = isset($cacl_func_id[$i]) ? $cacl_func_id[$i] : 0; $cacl_usr->redirect_FRONT = $redirect_URL_FRONT; $cacl_usr->redirect_ADMIN = $redirect_URL_ADMIN; $cacl_usr->store(); } } $query = "SELECT `id` FROM `#__community_acl_sites` WHERE `is_main` = '1'"; $db->setQuery($query); $sid = (int) $db->loadResult(); if ($sid > 0) { $main = new CACL_site($db); $main->load($sid); $config = new CACL_config($main->_site_db); $config->load(); if ($config->synchronize && $config->users_and_cb) { $sync = new CACL_syncronize($main); $sync->syncronize($user->get('id'), 'user'); $sync->syncronize($user->get('id'), 'cb_user'); } } switch ($this->getTask()) { case 'apply': $msg = JText::sprintf('Successfully Saved changes to User', $user->get('name')); $this->setRedirect('index.php?option=com_community_acl&mode=manage_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_community_acl&mode=manage_users', $msg); break; } }
function checkUserExistence() { $birthdate = urldecode(JRequest::getString('birthdate', NULL, 'method')); $fullname = urldecode(JRequest::getString('fullname', NULL, 'method')); $user = new JUser(); $user->set("birthdate", $birthdate); $user->set("name", $fullname); $db = JFactory::getDBO(); $id = $this->getUserId($db, $user); if ($id) { echo JText::_("SYSTEM_USER_EXISTS"); return; } }
function register_save() { $otherlanguage = JFactory::getLanguage(); $otherlanguage->load('com_user', JPATH_SITE); $usersConfig = JComponentHelper::getParams('com_users'); if ($usersConfig->get('allowUserRegistration') == '0') { JError::raiseError(403, JText::_('Access Forbidden')); return; } $authorize = JFactory::getACL(); $user = new JUser(); $system = 2; // ID of Registered $user->groups = array(); $user->groups[] = $system; // Bind the post array to the user object $post = JRequest::get('post'); if (!$user->bind($post, 'usertype')) { JError::raiseError(500, $user->getError()); } // Set some initial user values $user->set('id', 0); $date = JFactory::getDate(); $user->set('registerDate', $date->toSql()); $parent = JFactory::getUser(); $user->setParam('u' . $parent->id . '_parent_id', $parent->id); // If user activation is turned on, we need to set the activation information $useractivation = $usersConfig->get('useractivation'); if ($useractivation == 1 || $useractivation == 2) { jimport('joomla.user.helper'); $user->set('activation', JApplication::getHash(JUserHelper::genRandomPassword())); $user->set('block', '1'); } // If there was an error with registration, set the message and display form if (!$user->save()) { JError::raiseWarning('', JText::_($user->getError())); $this->setRedirect('index.php?option=com_joomdle&view=register'); return false; } // Add to profile type if needed $params = JComponentHelper::getParams('com_joomdle'); $children_pt = $params->get('children_profiletype'); if ($children_pt) { JoomdleHelperProfiletypes::add_user_to_profile($user->id, $children_pt); } // Send registration confirmation mail $password = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW); $password = preg_replace('/[\\x00-\\x1F\\x7F]/', '', $password); //Disallow control chars in the email // UserController::_sendMail($user, $password); JoomdleHelperSystem::send_registration_email($user->username, $password); $parent_user = JFactory::getUser(); // Set parent role in Moodle JoomdleHelperContent::call_method("add_parent_role", $user->username, $parent_user->username); $message = JText::_('COM_JOOMDLE_USER_CREATED'); $this->setRedirect('index.php?option=com_joomdle&view=register', $message); //XXX poenr un get current uri }
/** * 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'); } }
function doUserLogIn($username) { $my = new JUser(); jimport('joomla.user.helper'); if ($id = intval(JUserHelper::getUserId($username))) { $my->load($id); } else { return JError::raiseWarning('SOME_ERROR_CODE', 'MigrationAssistant (doUserLogIn): Failed to load user'); } // If the user is blocked, redirect with an error if ($my->get('block') == 1) { return JError::raiseWarning('SOME_ERROR_CODE', JText::_('E_NOLOGIN_BLOCKED')); } //Mark the user as logged in $my->set('guest', 0); // Discover the access group identifier // NOTE : this is a very basic for of permission handling, will be replaced by a full ACL in 1.6 jimport('joomla.factory'); $acl =& JFactory::getACL(); $grp = $acl->getAroGroup($my->get('id')); $my->set('aid', 1); if ($acl->is_group_child_of($grp->name, 'Registered', 'ARO') || $acl->is_group_child_of($grp->name, 'Public Backend', 'ARO')) { // fudge Authors, Editors, Publishers and Super Administrators into the special access group $my->set('aid', 2); } //Set the usertype based on the ACL group name $my->set('usertype', $grp->name); // Register the needed session variables $session =& JFactory::getSession(); $session->set('user', $my); // Get the session object $table =& JTable::getInstance('session'); $table->load($session->getId()); $table->guest = $my->get('guest'); $table->username = $my->get('username'); $table->userid = intval($my->get('id')); $table->usertype = $my->get('usertype'); $table->gid = intval($my->get('gid')); $table->update(); // Hit the user last visit field $my->setLastVisit(); // Set remember me option $lifetime = time() + 365 * 24 * 60 * 60; setcookie('usercookie[username]', $my->get('username'), $lifetime, '/'); setcookie('usercookie[password]', $my->get('password'), $lifetime, '/'); }
/** * 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; } }
/** * Check that username is not greater than 150 characters * * @param JUser $user * @param array &$data * * @return array $data */ protected function trimNamePassword($user, &$data) { // Check that username is not greater than 150 characters $username = $data['username']; if (strlen($username) > 150) { $username = JString::substr($username, 0, 150); $user->set('username', $username); } // Check that password is not greater than 100 characters @FIXME - 55 for j3.2 if (strlen($data['password']) > 100) { $data['password'] = JString::substr($data['password'], 0, 100); } return $data; }
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); }
public function importdata() { ob_clean(); $thumb = new thumbnail(); $obj_img = new thumbnail_images(); $session = JFactory::getSession(); /* Get all posted data */ $new_line = JRequest::getVar('new_line'); $post = $session->get('ImportPost'); $files = $session->get('Importfile'); $file_name = $session->get('Importfilename'); /* Load the table model */ switch ($post['import']) { case 'products': $row = $this->getTable('product_detail'); break; case 'categories': $row = $this->getTable('category_detail'); break; } /** * check is redCRM is installed or not */ $redhelper = new redhelper(); $isredcrm = false; if ($redhelper->isredCRM()) { $isredcrm = true; } /* Loop through the CSV file */ /* First line first as that is the column headers */ $line = 1; $headers = array(); $correctlines = 0; $handle = fopen(JPATH_ROOT . '/components/com_redshop/assets/importcsv/' . $post['import'] . '/' . $file_name, "r"); $separator = ","; if ($post['separator'] != "") { $separator = $post['separator']; } list($susec, $ssec) = explode(" ", microtime()); $start_micro_time = (double) $susec + (double) $ssec; $session->set('start_micro_time', $start_micro_time); while (($data = fgetcsv($handle, 0, $separator, '"')) !== false) { if ($this->getTimeLeft() > 0) { // Skip headers if ($line == 1) { foreach ($data as $key => $name) { /* Set the column headers */ $headers[$key] = $name; } } else { if ($line > $new_line) { $rawdata = array(); foreach ($data as $key => $name) { // Bind the data if ($headers[$key] == 'category_full_image' && $post['import'] == 'categories') { $image_name = basename($name); $rawdata[$headers[$key]] = $image_name; if ($image_name != "") { @fopen($name, "r"); $dest = REDSHOP_FRONT_IMAGES_RELPATH . 'category/' . $image_name; // Copy If file is not already exist if (!file_exists($dest)) { copy($name, $dest); } } } elseif ($headers[$key] == 'sitepath' && $post['import'] == 'products') { $this->sitepath = $rawdata[$headers[$key]] = $name; } else { $rawdata[$headers[$key]] = $name; } } // Import categories if ($post['import'] == 'categories') { $category_id = $rawdata['category_id']; $query = "SELECT COUNT(*) FROM " . $this->_table_prefix . "category WHERE category_id = '" . $category_id . "'"; $this->_db->setQuery($query); $cidCount = $this->_db->loadResult(); // Updating category $row = $this->getTable('category_detail'); if ($cidCount > 0) { $row->load($category_id); } else { $row->category_id = $category_id; } $row->category_name = $rawdata['category_name']; $row->category_short_description = $rawdata['category_short_description']; $row->category_description = $rawdata['category_description']; $row->category_template = $rawdata['category_template']; $row->category_more_template = $rawdata['category_more_template']; $row->products_per_page = $rawdata['products_per_page']; $row->category_thumb_image = $rawdata['category_thumb_image']; $row->category_full_image = $rawdata['category_full_image']; $row->metakey = $rawdata['metakey']; $row->metadesc = $rawdata['metadesc']; $row->metalanguage_setting = $rawdata['metalanguage_setting']; $row->metarobot_info = $rawdata['metarobot_info']; $row->pagetitle = $rawdata['pagetitle']; $row->pageheading = $rawdata['pageheading']; $row->sef_url = $rawdata['sef_url']; $row->published = $rawdata['published']; $row->category_pdate = $rawdata['category_pdate']; $row->ordering = $rawdata['ordering']; if ($cidCount > 0) { // Update if (!$row->store()) { return JText::_('COM_REDSHOP_ERROR_DURING_IMPORT'); } } else { // Insert $ret = $this->_db->insertObject($this->_table_prefix . 'category', $row, 'category_id'); if (!$ret) { return JText::_('COM_REDSHOP_ERROR_DURING_IMPORT'); } } $query = "SELECT COUNT(*) FROM " . $this->_table_prefix . "category_xref " . "WHERE category_parent_id='" . $rawdata['category_parent_id'] . "' " . "AND category_child_id='" . $row->category_id . "' "; $this->_db->setQuery($query); $count = $this->_db->loadResult(); if ($count == 0) { // Remove existing $query = "DELETE FROM `" . $this->_table_prefix . "category_xref` WHERE `category_child_id` = '" . $row->category_id . "' "; $this->_db->setQuery($query); $this->_db->Query(); $query = "INSERT INTO " . $this->_table_prefix . "category_xref VALUES('" . $rawdata['category_parent_id'] . "','" . $row->category_id . "') "; $this->_db->setQuery($query); $this->_db->Query(); } $correctlines++; } // Import products if ($post['import'] == 'products' && isset($rawdata['product_number'])) { $rawdata['product_price'] = '' . str_replace(',', '.', $rawdata['product_price']) . ''; $product_id = $this->getProductIdByNumber($rawdata['product_number']); if ((int) $product_id > 0) { $rawdata['product_id'] = (int) $product_id; } // Product Description is optional - no need to add column in csv everytime. if (isset($rawdata['product_desc']) === true) { $rawdata['product_desc'] = htmlentities($rawdata['product_desc']); } // Product Short Description is also optional - no need to add column in csv everytime. if (isset($rawdata['product_s_desc']) === true) { $rawdata['product_s_desc'] = htmlentities($rawdata['product_s_desc']); } if (isset($rawdata['manufacturer_name'])) { $query = "SELECT `manufacturer_id` FROM `" . $this->_table_prefix . "manufacturer` " . "WHERE `manufacturer_name` = '" . $rawdata['manufacturer_name'] . "' "; $this->_db->setQuery($query); $manufacturer_id = $this->_db->loadResult(); $rawdata['manufacturer_id'] = $manufacturer_id; } // Updating/inserting product $row = $this->getTable('product_detail'); $row->load($rawdata['product_id']); // Do not update with blank imagecategory_id if ($rawdata['product_thumb_image'] == "") { unset($rawdata['product_thumb_image']); } if ($rawdata['product_full_image'] == "") { unset($rawdata['product_full_image']); } if ($rawdata['product_back_full_image'] == "") { unset($rawdata['product_back_full_image']); } if ($rawdata['product_preview_back_image'] == "") { unset($rawdata['product_preview_back_image']); } $row->bind($rawdata); // Set boolean for Error $isError = false; if ((int) $product_id > 0) { // Update if (!$row->store()) { $isError = true; return JText::_('COM_REDSHOP_ERROR_DURING_IMPORT'); } } else { // Insert $row->product_id = (int) $rawdata['product_id']; $ret = $this->_db->insertObject($this->_table_prefix . 'product', $row, 'product_id'); if (!$ret) { $isError = true; return JText::_('COM_REDSHOP_ERROR_DURING_IMPORT'); } } if (!$isError) { // Last inserted product id $product_id = $row->product_id; // Product Full Image $product_full_image = trim($rawdata['product_full_image']); if ($product_full_image != "") { $src = $this->sitepath . "components/com_redshop/assets/images/product/" . $product_full_image; @fopen($src, "r"); $dest = REDSHOP_FRONT_IMAGES_RELPATH . 'product/' . $product_full_image; // Copy If file is not already exist if (!file_exists($dest)) { @copy($name, $dest); } } $section_images = $rawdata['images']; $image_name = explode("#", $section_images); if (is_array($image_name)) { for ($i = 0; $i < count($image_name); $i++) { if (trim($image_name[$i]) != "") { $src = $this->sitepath . "components/com_redshop/assets/images/product/" . trim($image_name[$i]); @fopen($src, "r"); $dest = REDSHOP_FRONT_IMAGES_RELPATH . 'product/' . trim($image_name[$i]); // Copy If file is not already exist if (!file_exists($dest)) { @copy($src, $dest); } } } } $section_images_order = $rawdata['images_order']; $section_images_alternattext = $rawdata['images_alternattext']; // Section videos $section_video = $rawdata['video']; $image_name = explode("#", $section_video); if (is_array($image_name)) { for ($i = 0; $i < count($image_name); $i++) { if (trim($image_name[$i]) != "") { $src = $this->sitepath . "components/com_redshop/assets/video/product/" . trim($image_name[$i]); @fopen($src, "r"); $dest = JPATH_COMPONENT_SITE . '/assets/video/product/' . trim($image_name[$i]); // Copy If file is not already exist if (!file_exists($dest)) { @copy($src, $dest); } } } } $section_video_order = $rawdata['video_order']; $section_video_alternattext = $rawdata['video_alternattext']; // Section document $section_document = $rawdata['document']; $image_name = explode("#", $section_document); if (is_array($image_name)) { for ($i = 0; $i < count($image_name); $i++) { if (trim($image_name[$i]) != "") { $src = $this->sitepath . "components/com_redshop/assets/document/product/" . trim($image_name[$i]); @fopen($src, "r"); $dest = REDSHOP_FRONT_DOCUMENT_RELPATH . 'product/' . trim($image_name[$i]); // Copy If file is not already exist if (!file_exists($dest)) { @copy($src, $dest); } } } } $section_document_order = $rawdata['document_order']; $section_document_alternattext = $rawdata['document_alternattext']; // Section Download if (isset($rawdata['download'])) { $section_download = $rawdata['download']; $image_name = explode("#", $section_download); if (is_array($image_name)) { for ($i = 0; $i < count($image_name); $i++) { if (trim($image_name[$i]) != "") { $src = $this->sitepath . "components/com_redshop/assets/download/product/" . trim($image_name[$i]); @fopen($src, "r"); $dest = JPATH_COMPONENT_SITE . '/assets/download/product/' . trim($image_name[$i]); // Copy If file is not already exist if (!file_exists($dest)) { @copy($src, $dest); } } } } } $section_download_order = $rawdata['download_order']; $section_download_alternattext = $rawdata['download_alternattext']; $category_id = $rawdata['category_id']; // Insert into media $query = "SELECT count(*) FROM `" . $this->_table_prefix . "media` " . "WHERE `media_name` LIKE '" . $product_full_image . "' " . "AND `media_section` LIKE 'product' " . "AND `section_id`='" . $product_id . "' " . "AND `media_type` LIKE 'images' " . "AND `published`=1 "; $this->_db->setQuery($query); $count = $this->_db->loadResult(); if ($count <= 0) { $rows = $this->getTable('media_detail'); $rows->media_id = 0; $rows->media_name = $product_full_image; $rows->media_section = 'product'; $rows->section_id = $product_id; $rows->media_type = 'images'; $rows->media_mimetype = ''; $rows->published = 1; if (!$rows->store()) { $this->setError($this->_db->getErrorMsg()); } } // Product Extra Field Import $newkeys = array(); array_walk($rawdata, 'checkkeys', $newkeys); if (count($newkeys) > 0) { foreach ($newkeys as $fieldkey) { $this->importProductExtrafieldData($fieldkey, $rawdata, $product_id); } } $correctlines++; } // Category product relation insert $category_id = ''; $category_name = ''; if (isset($rawdata['category_id'])) { $category_id = $rawdata['category_id']; } if (isset($rawdata['category_name'])) { $category_name = $rawdata['category_name']; } if ($category_id != "" || $category_name != "") { $category = false; if ($category_id != "") { $categoryArr = explode("###", $rawdata['category_id']); } else { $categoryArr = explode("###", $rawdata['category_name']); $category = true; } // Remove all current product category $query = "DELETE FROM `" . $this->_table_prefix . "product_category_xref` WHERE `product_id` = " . $product_id; $this->_db->setQuery($query); $this->_db->Query(); for ($i = 0; $i < count($categoryArr); $i++) { if ($category) { $query = "SELECT category_id FROM `" . $this->_table_prefix . "category` " . "WHERE `category_name` = '" . $categoryArr[$i] . "' "; $this->_db->setQuery($query); $category_id = $this->_db->loadResult(); } else { $category_id = $categoryArr[$i]; } $query = "SELECT COUNT(*) FROM " . $this->_table_prefix . "product_category_xref " . "WHERE category_id = '" . $category_id . "' " . "AND product_id = '" . $product_id . "' "; $this->_db->setQuery($query); $count = $this->_db->loadResult(); if ($count <= 0) { $query = "INSERT IGNORE INTO `" . $this->_table_prefix . "product_category_xref` " . "(`category_id`, `product_id`) " . "VALUES ('" . $category_id . "', '" . $product_id . "')"; $this->_db->setQuery($query); $this->_db->Query(); } } } // Importing accessory product $accessory_products = $rawdata['accessory_products']; if ($accessory_products != "") { $accessory_products = explode("###", $rawdata['accessory_products']); for ($i = 0; $i < count($accessory_products); $i++) { $accids = explode("~", $accessory_products[$i]); $accessory_product_sku = $accids[0]; $accessory_price = $accids[1]; $query = 'SELECT COUNT(*) AS total FROM `' . $this->_table_prefix . 'product_accessory` AS pa ' . 'LEFT JOIN ' . $this->_table_prefix . 'product p ON p.product_id = pa.child_product_id ' . 'WHERE pa.`product_id`="' . $product_id . '" ' . 'AND p.product_number="' . $accessory_product_sku . '" '; $this->_db->setQuery($query); $total = $this->_db->loadresult(); $query = "SELECT product_id FROM `" . $this->_table_prefix . "product` WHERE `product_number`='" . $accessory_product_sku . "' "; $this->_db->setQuery($query); $child_product_id = $this->_db->loadresult(); if ($total <= 0) { $query = "INSERT IGNORE INTO `" . $this->_table_prefix . "product_accessory` " . "(`accessory_id`, `product_id`, `child_product_id`, `accessory_price`) " . "VALUES ('', '" . $product_id . "', '" . $child_product_id . "', '" . $accessory_price . "')"; } else { $query = "UPDATE `" . $this->_table_prefix . "product_accessory` " . "SET `accessory_price`='" . $accessory_price . "' " . "WHERE `product_id`='" . $product_id . "' " . "AND `child_product_id`='" . $child_product_id . "'"; } $this->_db->setQuery($query); $this->_db->Query(); } } $product_stock = $rawdata['product_stock']; $query = "SELECT COUNT(*) AS total FROM `" . $this->_table_prefix . "product_stockroom_xref` " . "WHERE `product_id`='" . $product_id . "' " . "AND `stockroom_id`='" . DEFAULT_STOCKROOM . "'"; $this->_db->setQuery($query); $total = $this->_db->loadresult(); if ($product_stock && DEFAULT_STOCKROOM != 0) { if ($total <= 0) { $query = "INSERT INTO `" . $this->_table_prefix . "product_stockroom_xref` " . "(`product_id`, `stockroom_id`, `quantity`) " . "VALUES ('" . $product_id . "', '" . DEFAULT_STOCKROOM . "', '" . $product_stock . "') "; } else { $query = "UPDATE `" . $this->_table_prefix . "product_stockroom_xref` " . "SET `quantity`='" . $product_stock . "' " . "WHERE `product_id`='" . $product_id . "' " . "AND `stockroom_id`='" . DEFAULT_STOCKROOM . "'"; } $this->_db->setQuery($query); $this->_db->Query(); } // Import image section $section_images = explode("#", $section_images); $section_images_order = explode("#", $section_images_order); $section_images_alternattext = explode("#", $section_images_alternattext); if (is_array($section_images)) { for ($s = 0; $s < count($section_images); $s++) { if (trim($section_images[$s]) != "") { $ordering = 0; if (isset($section_images_order[$s])) { $ordering = $section_images_order[$s]; } $media_alternate_text = ""; if (isset($section_images_alternattext[$s])) { $media_alternate_text = $section_images_alternattext[$s]; } $query = "SELECT media_id FROM `" . $this->_table_prefix . "media` " . "WHERE `media_name` LIKE '" . $section_images[$s] . "' " . "AND `media_section`='product' " . "AND `section_id`='" . $product_id . "' " . "AND `media_type` LIKE 'images' "; $this->_db->setQuery($query); $count = $this->_db->loadResult(); if ($count <= 0) { $rows = $this->getTable('media_detail'); $rows->media_id = 0; $rows->media_name = trim($section_images[$s]); $rows->media_section = 'product'; $rows->section_id = $product_id; $rows->media_type = 'images'; $rows->media_mimetype = ''; $rows->published = 1; $rows->media_alternate_text = $media_alternate_text; $rows->ordering = $ordering; if (!$rows->store()) { $this->setError($this->_db->getErrorMsg()); } } else { $query = "UPDATE `" . $this->_table_prefix . "media` " . "SET `media_alternate_text` = '" . $media_alternate_text . "', " . "`ordering` = '" . $ordering . "' " . "WHERE `media_id`='" . $count . "' "; $this->_db->setQuery($query); $this->_db->Query(); } } } } // Import video section $section_video = explode("#", $section_video); $section_video_order = explode("#", $section_video_order); $section_video_alternattext = explode("#", $section_video_alternattext); if (is_array($section_video)) { for ($s = 0; $s < count($section_video); $s++) { if (trim($section_video[$s]) != "") { $ordering = 0; if (isset($section_video_order[$s])) { $ordering = $section_video_order[$s]; } $media_alternate_text = ""; if (isset($section_video_alternattext[$s])) { $media_alternate_text = $section_video_alternattext[$s]; } $query = "SELECT count(*) FROM `" . $this->_table_prefix . "media` " . "WHERE `media_name` LIKE '" . $section_video[$s] . "' " . "AND `media_section`='product' " . "AND `section_id` = '" . $product_id . "' " . "AND `media_type`='video' "; $this->_db->setQuery($query); $count = $this->_db->loadResult(); if ($count <= 0) { $rows = $this->getTable('media_detail'); $rows->media_id = 0; $rows->media_name = trim($section_video[$s]); $rows->media_section = 'product'; $rows->section_id = $product_id; $rows->media_type = 'video'; $rows->media_mimetype = ''; $rows->published = 1; $rows->media_alternate_text = $media_alternate_text; $rows->ordering = $ordering; if (!$rows->store()) { $this->setError($this->_db->getErrorMsg()); } } } } } // Import document section $section_document = explode("#", $section_document); $section_document_order = explode("#", $section_document_order); $section_document_alternattext = explode("#", $section_document_alternattext); if (is_array($section_document)) { for ($s = 0; $s < count($section_document); $s++) { if (trim($section_document[$s]) != "") { $ordering = 0; if (isset($section_document_order[$s])) { $ordering = $section_document_order[$s]; } $media_alternate_text = ""; if (isset($section_document_alternattext[$s])) { $media_alternate_text = $section_document_alternattext[$s]; } $query = "SELECT count(*) FROM `" . $this->_table_prefix . "media` " . "WHERE `media_name` LIKE '" . $section_document[$s] . "' " . "AND `media_section`='product' " . "AND `section_id` = '" . $product_id . "' " . "AND `media_type`='document' "; $this->_db->setQuery($query); $count = $this->_db->loadResult(); if ($count <= 0) { $rows = $this->getTable('media_detail'); $rows->media_id = 0; $rows->media_name = trim($section_download[$s]); $rows->media_section = 'product'; $rows->section_id = $product_id; $rows->media_type = 'document'; $rows->media_mimetype = ''; $rows->published = 1; $rows->media_alternate_text = $media_alternate_text; $rows->ordering = $ordering; if (!$rows->store()) { $this->setError($this->_db->getErrorMsg()); } } } } } // Import download section $section_download = explode("#", $section_download); $section_download_order = explode("#", $section_download_order); $section_download_alternattext = explode("#", $section_download_alternattext); if (is_array($section_download)) { for ($s = 0; $s < count($section_download); $s++) { if (trim($section_download[$s]) != "") { $ordering = 0; if (isset($section_download_order[$s])) { $ordering = $section_download_order[$s]; } $media_alternate_text = ""; if (isset($section_download_alternattext[$s])) { $media_alternate_text = $section_download_alternattext[$s]; } $query = "SELECT count(*) FROM `" . $this->_table_prefix . "media` " . "WHERE `media_name` LIKE '" . $section_download[$s] . "' " . "AND `media_section`='product' " . "AND `section_id`='" . $product_id . "' " . "AND `media_type`='download' "; $this->_db->setQuery($query); $count = $this->_db->loadResult(); if ($count <= 0) { $rows = $this->getTable('media_detail'); $rows->media_id = 0; $rows->media_name = trim($section_download[$s]); $rows->media_section = 'product'; $rows->section_id = $product_id; $rows->media_type = 'download'; $rows->media_mimetype = ''; $rows->published = 1; $rows->media_alternate_text = $media_alternate_text; $rows->ordering = $ordering; if (!$rows->store()) { $this->setError($this->_db->getErrorMsg()); } } } } } } // Import Manufacturers if ($post['import'] == 'manufacturer') { $manufacturer_id = $rawdata['manufacturer_id']; $product_id = $rawdata['product_id']; $prd = explode('|', $product_id); $prd_final = implode(',', $prd); // Updating manufacturer $row = $this->getTable('manufacturer_detail'); $row->load($manufacturer_id); $row->manufacturer_name = $rawdata['manufacturer_name']; $row->manufacturer_desc = $rawdata['manufacturer_desc']; $row->manufacturer_email = $rawdata['manufacturer_email']; $row->product_per_page = $rawdata['product_per_page']; $row->template_id = $rawdata['template_id']; $row->metakey = $rawdata['metakey']; $row->metadesc = $rawdata['metadesc']; $row->metalanguage_setting = $rawdata['metalanguage_setting']; $row->metarobot_info = $rawdata['metarobot_info']; $row->pagetitle = $rawdata['pagetitle']; $row->pageheading = $rawdata['pageheading']; $row->sef_url = $rawdata['sef_url']; $row->published = $rawdata['published']; $row->ordering = $rawdata['ordering']; $row->manufacturer_url = $rawdata['manufacturer_url']; if (!$row->store()) { return JText::_('ERROR_DURING_IMPORT'); } else { $rows = $this->getTable('manufacturer_detail'); $rows->manufacturer_id = $manufacturer_id; $rows->manufacturer_name = $rawdata['manufacturer_name']; $rows->manufacturer_desc = $rawdata['manufacturer_desc']; $rows->manufacturer_email = $rawdata['manufacturer_email']; $rows->product_per_page = $rawdata['product_per_page']; $rows->template_id = $rawdata['template_id']; $rows->metakey = $rawdata['metakey']; $rows->metadesc = $rawdata['metadesc']; $rows->metalanguage_setting = $rawdata['metalanguage_setting']; $rows->metarobot_info = $rawdata['metarobot_info']; $rows->pagetitle = $rawdata['pagetitle']; $rows->pageheading = $rawdata['pageheading']; $rows->sef_url = $rawdata['sef_url']; $rows->published = $rawdata['published']; $rows->ordering = $rawdata['ordering']; $rows->manufacturer_url = $rawdata['manufacturer_url']; if (!$rows->store()) { $this->setError($this->_db->getErrorMsg()); return false; } $rows->set('manufacturer_id', $manufacturer_id); $ret = $this->_db->insertObject($this->_table_prefix . 'manufacturer', $rows, 'manufacturer_id'); } if (count($prd) > 0) { $query = "UPDATE `" . $this->_table_prefix . "product` " . "SET `manufacturer_id` = " . $manufacturer_id . " " . "WHERE `product_id` IN(" . $prd_final . ") "; $this->_db->setQuery($query); $this->_db->Query(); } $correctlines++; } // Import attributes if ($post['import'] == 'attributes') { $product_id = $this->getProductIdByNumber($rawdata['product_number']); // Insert product attributes $attribute_id = ""; $attribute_name = $rawdata['attribute_name']; $attribute_ordering = $rawdata['attribute_ordering']; $allow_multiple_selection = $rawdata['allow_multiple_selection']; $hide_attribute_price = $rawdata['hide_attribute_price']; $attribute_display_type = $rawdata['display_type']; $attribute_required = $rawdata['attribute_required']; $query = "SELECT `attribute_id` FROM `" . $this->_table_prefix . "product_attribute` WHERE `product_id` = " . $product_id . " AND `attribute_name` = '" . $attribute_name . "'"; $this->_db->setQuery($query); $attribute_id = $this->_db->loadResult(); // Get table Instance $attrow = $this->getTable('product_attribute'); $attrow->load($attribute_id); $attrow->attribute_name = $attribute_name; if ($attribute_ordering != '') { $attrow->ordering = $attribute_ordering; } if ($allow_multiple_selection != '') { $attrow->allow_multiple_selection = $allow_multiple_selection; } if ($hide_attribute_price != '') { $attrow->hide_attribute_price = $hide_attribute_price; } if ($attribute_required != '') { $attrow->attribute_required = $attribute_required; } if ($attribute_display_type != '') { $attrow->display_type = $attribute_display_type; } $attrow->product_id = $product_id; if ($attrow->store()) { $att_insert_id = $attrow->attribute_id; // Insert product attributes property $property_id = 0; $property_name = $rawdata['property_name']; if ($property_name != "") { $property_ordering = $rawdata['property_ordering']; $property_price = $rawdata['property_price']; $property_number = $rawdata['property_virtual_number']; $setdefault_selected = $rawdata['setdefault_selected']; $setdisplay_type = $rawdata['setdisplay_type']; $setrequire_selected = $rawdata['required_sub_attribute']; $oprand = $rawdata['oprand']; $property_image = @basename($rawdata['property_image']); $property_main_image = @basename($rawdata['property_main_image']); $query = "SELECT `property_id` FROM `" . $this->_table_prefix . "product_attribute_property` WHERE `attribute_id` = " . $att_insert_id . " AND `property_name` = '" . $property_name . "'"; $this->_db->setQuery($query); $property_id = $this->_db->loadResult(); // Get Table Instance $proprow = $this->getTable('attribute_property'); $proprow->load($property_id); $proprow->attribute_id = $att_insert_id; $proprow->property_name = $property_name; if ($property_price != "") { $proprow->property_price = $property_price; } if ($property_ordering != "") { $proprow->ordering = $property_ordering; } if ($property_number != "") { $proprow->property_number = $property_number; } if ($setdefault_selected != "") { $proprow->setdefault_selected = $setdefault_selected; } if ($setrequire_selected != "") { $proprow->setrequire_selected = $setrequire_selected; } if ($setdisplay_type != "") { $proprow->setdisplay_type = $setdisplay_type; } if ($oprand == '+' || $oprand == '-' || $oprand == '*' || $oprand == '/' || $oprand == '=') { $proprow->oprand = $oprand; } if ($property_image) { $proprow->property_image = $property_image; } if ($property_main_image) { $proprow->property_main_image = $property_main_image; } if ($proprow->store()) { $prop_insert_id = $proprow->property_id; $mainstock = $rawdata['property_stock']; if ($mainstock != "") { $mainstock_split = explode("#", $mainstock); for ($r = 0; $r < count($mainstock_split); $r++) { if ($mainstock_split[$r] != "") { $mainquaexplode = explode(":", $mainstock_split[$r]); if (count($mainquaexplode) == 2) { $query_mainins_stockroom = "SELECT * FROM `" . $this->_table_prefix . "stockroom` WHERE `stockroom_id` = '" . $mainquaexplode[0] . "'"; $this->_db->setQuery($query_mainins_stockroom); $stock_id = $this->_db->loadObjectList(); if (count($stock_id) > 0) { $query_mainins = "SELECT * FROM `" . $this->_table_prefix . "product_attribute_stockroom_xref` WHERE `stockroom_id` = '" . $mainquaexplode[0] . "' and section='property' and section_id='" . $prop_insert_id . "'"; $this->_db->setQuery($query_mainins); $product_id = $this->_db->loadObjectList(); if (count($product_id) > 0) { $update_row_query = "update `" . $this->_table_prefix . "product_attribute_stockroom_xref` set quantity='" . $mainquaexplode[1] . "' where `stockroom_id` = '" . $mainquaexplode[0] . "' and section='property' and section_id='" . $prop_insert_id . "'"; $this->_db->setQuery($update_row_query); $this->_db->Query(); } else { $insert_row_query = "insert into `" . $this->_table_prefix . "product_attribute_stockroom_xref` set quantity='" . $mainquaexplode[1] . "',`stockroom_id` = '" . $mainquaexplode[0] . "',section='property',section_id='" . $prop_insert_id . "'"; $this->_db->setQuery($insert_row_query); $this->_db->Query(); } } } } } } /** * update property stock placement */ if ($isredcrm && isset($rawdata['property_stock_placement']) && trim($rawdata['property_stock_placement']) != "") { $property_save = array(); $property_save['stockposition'] = $rawdata['property_stock_placement']; $property_save['product_id'] = $attrow->product_id; $property_save['property_id'] = $prop_insert_id; $this->storePropertyStockPosition($property_save); unset($property_save); } if ($property_image != "") { $property_image_path = $rawdata['property_image']; @fopen($property_image_path, "r"); $dest = REDSHOP_FRONT_IMAGES_RELPATH . 'product_attributes/' . $property_image; // Copy If file is not already exist if (!file_exists($dest)) { @copy($property_image_path, $dest); } } if ($property_main_image != "") { $property_image_path = $rawdata['property_main_image']; @fopen($property_image_path, "r"); $dest = REDSHOP_FRONT_IMAGES_RELPATH . 'property/' . $property_main_image; // Copy If file is not already exist if (!file_exists($dest)) { @copy($property_image_path, $dest); } } // Redshop product attribute subproperty $subattribute_color_id = ""; $subattribute_color_name = $rawdata['subattribute_color_name']; if ($subattribute_color_name != "") { $subattribute_color_ordering = $rawdata['subattribute_color_ordering']; $subattribute_setdefault_selected = $rawdata['subattribute_setdefault_selected']; $subattribute_color_title = $rawdata['subattribute_color_title']; $subattribute_color_number = $rawdata['subattribute_virtual_number']; $subattribute_color_price = $rawdata['subattribute_color_price']; $oprand = $rawdata['subattribute_color_oprand']; $subattribute_color_image = @basename($rawdata['subattribute_color_image']); $query = "SELECT `subattribute_color_id` FROM `" . $this->_table_prefix . "product_subattribute_color` WHERE `subattribute_id` = " . $prop_insert_id . " AND `subattribute_color_name` = '" . $subattribute_color_name . "'"; $this->_db->setQuery($query); $subattribute_color_id = $this->_db->loadResult(); // Get Table Instance $subproprow = $this->getTable('subattribute_property'); $subproprow->load($subattribute_color_id); $subproprow->subattribute_color_name = $subattribute_color_name; if ($subattribute_color_price != "") { $subproprow->subattribute_color_price = $subattribute_color_price; } if ($subattribute_color_ordering != "") { $subproprow->ordering = $subattribute_color_ordering; } if ($subattribute_setdefault_selected != "") { $subproprow->setdefault_selected = $subattribute_setdefault_selected; } if ($subattribute_color_title != "") { $subproprow->subattribute_color_title = $subattribute_color_title; } if ($subattribute_color_number != "") { $subproprow->subattribute_color_number = $subattribute_color_number; } if ($oprand == '+' || $oprand == '-' || $oprand == '*' || $oprand == '/' || $oprand == '=') { $subproprow->oprand = $oprand; } if ($subattribute_color_image) { $subproprow->subattribute_color_image = $subattribute_color_image; } $subproprow->subattribute_id = $prop_insert_id; $query = "INSERT IGNORE INTO `" . $this->_table_prefix . "product_subattribute_color` (\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`subattribute_color_id` ,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`subattribute_color_name` ,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`subattribute_color_price` ,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`oprand` ,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`subattribute_color_image` ,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`subattribute_id`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`ordering`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`setdefault_selected`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`subattribute_color_title`\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES (\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $subattribute_color_id . "', '" . $subattribute_color_name . "', '" . $subattribute_color_price . "', '" . $oprand . "', '" . $subattribute_color_image . "', '" . $prop_insert_id . "', '" . $subattribute_color_ordering . "', '" . $subattribute_setdefault_selected . "', '" . $subattribute_color_title . "'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)"; if ($subproprow->store()) { $prop_insert_id_sub = $subproprow->subattribute_color_id; $mainstock = $rawdata['subattribute_stock']; if ($mainstock != "") { $mainstock_split = explode("#", $mainstock); for ($r = 0; $r < count($mainstock_split); $r++) { if ($mainstock_split[$r] != "") { $mainquaexplode = explode(":", $mainstock_split[$r]); if (count($mainquaexplode) == 2) { $query_mainins_stockroom = "SELECT * FROM `" . $this->_table_prefix . "stockroom` WHERE `stockroom_id` = '" . $mainquaexplode[0] . "'"; $this->_db->setQuery($query_mainins_stockroom); $stock_id = $this->_db->loadObjectList(); if (count($stock_id) > 0) { $query_mainins = "SELECT * FROM `" . $this->_table_prefix . "product_attribute_stockroom_xref` WHERE `stockroom_id` = '" . $mainquaexplode[0] . "' and section='subproperty' and section_id='" . $prop_insert_id_sub . "'"; $this->_db->setQuery($query_mainins); $product_id = $this->_db->loadObjectList(); if (count($product_id) > 0) { $update_row_query = "update `" . $this->_table_prefix . "product_attribute_stockroom_xref` set quantity='" . $mainquaexplode[1] . "' where `stockroom_id` = '" . $mainquaexplode[0] . "' and section='subproperty' and section_id='" . $prop_insert_id_sub . "'"; $this->_db->setQuery($update_row_query); $this->_db->Query(); } else { $insert_row_query = "insert into `" . $this->_table_prefix . "product_attribute_stockroom_xref` set quantity='" . $mainquaexplode[1] . "',`stockroom_id` = '" . $mainquaexplode[0] . "',section='subproperty',section_id='" . $prop_insert_id_sub . "'"; $this->_db->setQuery($insert_row_query); $this->_db->Query(); } } } } } } /** * update property stock placement */ if ($isredcrm && isset($rawdata['subattribute_stock_placement']) && trim($rawdata['subattribute_stock_placement']) != "") { $subproperty_save = array(); $subproperty_save['stockposition'] = $rawdata['subattribute_stock_placement']; $subproperty_save['product_id'] = $attrow->product_id; $subproperty_save['subattribute_color_id'] = $prop_insert_id_sub; $this->storePropertyStockPosition($subproperty_save, 'subproperty'); unset($subproperty_save); } if ($subattribute_color_image != "") { $subproperty_image_path = $rawdata['subattribute_color_image']; @fopen($subproperty_image_path, "r"); $dest = REDSHOP_FRONT_IMAGES_RELPATH . 'subcolor/' . $subattribute_color_image; // Copy If file is not already exist if (!file_exists($dest)) { @copy($subproperty_image_path, $dest); } } } } } } $correctlines++; } } // Import fields if ($post['import'] == 'fields') { $field_id = $rawdata['field_id']; $field_title = $rawdata['field_title']; $field_name_field = $rawdata['field_name_field']; $field_type = $rawdata['field_type']; $field_desc = $rawdata['field_desc']; $field_class = $rawdata['field_class']; $field_section = $rawdata['field_section']; $field_maxlength = $rawdata['field_maxlength']; $field_cols = $rawdata['field_cols']; $field_rows = $rawdata['field_rows']; $field_size = $rawdata['field_size']; $field_show_in_front = $rawdata['field_show_in_front']; $required = $rawdata['required']; $published = $rawdata['published']; $data_id = $rawdata['data_id']; $data_txt = $rawdata['data_txt']; $itemid = $rawdata['itemid']; $section = $rawdata['section']; $data_insert_id = 0; if ($section == 1) { $itemid = $this->getProductIdByNumber($rawdata['data_number']); } $value_id = $rawdata['value_id']; $field_value = $rawdata['field_value']; $field_name_value = $rawdata['field_name']; // Get field id $query = $this->_db->getQuery(true)->select('field_id')->from($this->_db->quoteName('#__redshop_fields'))->where($this->_db->quoteName('field_id') . ' = ' . $this->_db->quote($field_id)); $this->_db->setQuery($query); $field_id_dv = $this->_db->loadResult(); $field_title = $rawdata['field_title']; $field_name = $rawdata['field_name_field']; // Get Data Id $query = $this->_db->getQuery(true)->select('data_id')->from($this->_db->quoteName('#__redshop_fields_data'))->where($this->_db->quoteName('fieldid') . ' = ' . $this->_db->quote($field_id))->where($this->_db->quoteName('itemid') . ' = ' . $this->_db->quote($itemid)); $this->_db->setQuery($query); $ch_data_id = $this->_db->loadResult(); // Get Value Id $query = $this->_db->getQuery(true)->select('value_id')->from($this->_db->quoteName('#__redshop_fields_value'))->where($this->_db->quoteName('field_id') . ' = ' . $this->_db->quote($field_id))->where($this->_db->quoteName('value_id') . ' = ' . $this->_db->quote($value_id)); $this->_db->setQuery($query); $ch_value_id = $this->_db->loadResult(); if ($field_title != "" && $field_id_dv == '') { $query = "INSERT IGNORE INTO `" . $this->_table_prefix . "fields` (\r\n\t\t\t\t\t\t\t\t`field_title` ,\r\n\t\t\t\t\t\t\t\t`field_name` ,\r\n\t\t\t\t\t\t\t\t`field_type`,\r\n\t\t\t\t\t\t\t\t`field_desc`,\r\n\t\t\t\t\t\t\t\t`field_class`,\r\n\t\t\t\t\t\t\t\t`field_section`,\r\n\t\t\t\t\t\t\t\t`field_maxlength`,\r\n\t\t\t\t\t\t\t\t`field_cols`,\r\n\t\t\t\t\t\t\t\t`field_rows`,\r\n\t\t\t\t\t\t\t\t`field_size`,\r\n\t\t\t\t\t\t\t\t`field_show_in_front`,\r\n\t\t\t\t\t\t\t\t`required`,\r\n\t\t\t\t\t\t\t\t`published`\r\n\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\tVALUES (\r\n\t\t\t\t\t\t\t\t'" . $field_title . "',\r\n\t\t\t\t\t\t\t\t'" . $field_name . "',\r\n\t\t\t\t\t\t\t\t'" . $field_type . "',\r\n\t\t\t\t\t\t\t\t'" . $field_desc . "',\r\n\t\t\t\t\t\t\t\t'" . $field_class . "',\r\n\t\t\t\t\t\t\t\t'" . $field_section . "',\r\n\t\t\t\t\t\t\t\t'" . $field_maxlength . "',\r\n\t\t\t\t\t\t\t\t'" . $field_cols . "',\r\n\t\t\t\t\t\t\t\t'" . $field_rows . "',\r\n\t\t\t\t\t\t\t\t'" . $field_size . "',\r\n\t\t\t\t\t\t\t\t'" . $field_show_in_front . "',\r\n\t\t\t\t\t\t\t\t'" . $required . "',\r\n\t\t\t\t\t\t\t\t'" . $published . "'\r\n\t\t\t\t\t\t\t\t)"; $this->_db->setQuery($query); $this->_db->Query(); $data_insert_id = $this->_db->insertid(); } if ($data_insert_id == 0) { $new_field_id = $field_id; } else { $new_field_id = $data_insert_id; } if (!$ch_data_id) { $query = "INSERT IGNORE INTO `" . $this->_table_prefix . "fields_data` " . "(`data_id`,`fieldid` ,`data_txt` ,`itemid`,`section`) " . "VALUES ('','" . $new_field_id . "','" . $data_txt . "','" . $itemid . "','" . $section . "')"; $this->_db->setQuery($query); $this->_db->Query(); } else { $query = "UPDATE `" . $this->_table_prefix . "fields_data` " . "SET `fieldid` = '" . $field_id . "', " . "`data_txt` = '" . $data_txt . "', " . "`itemid` = '" . $itemid . "', " . "`section` = '" . $section . "' " . "WHERE `data_id` = '" . $ch_data_id . "' "; $this->_db->setQuery($query); $this->_db->Query(); } if ($value_id != '') { if (!$ch_value_id) { $query = "INSERT IGNORE INTO `" . $this->_table_prefix . "fields_value` " . "(`value_id`, `field_id`, `field_value`, `field_name`) " . "VALUES ('" . $value_id . "','" . $new_field_id . "','" . $field_value . "','" . $field_name_value . "')"; $this->_db->setQuery($query); $this->_db->Query(); } else { $query = "UPDATE `" . $this->_table_prefix . "fields_value` " . "SET `field_value` = '" . $field_value . "', " . "`field_name` = '" . $field_name_value . "' " . "WHERE `value_id` = '" . $value_id . "' "; $this->_db->setQuery($query); $this->_db->Query(); } } $correctlines++; } // Import fields if ($post['import'] == 'fields_data') { $field_id = $rawdata['field_id']; $field_product_number = $rawdata['data_number']; $field_data_txt = $rawdata['data_txt']; if ($field_product_number && $field_id) { $product_id = $this->getProductIdByNumber($field_product_number); if ($product_id) { $q = "SELECT count(fieldid) as fieldexist FROM `" . $this->_table_prefix . "fields_data` " . "WHERE `fieldid` = '" . $field_id . "' " . "AND itemid ='" . $product_id . "' " . "AND section ='1' "; $this->_db->setQuery($q); $fieldexist = $this->_db->loadResult(); if ($fieldexist == 0) { $query = "INSERT IGNORE INTO `" . $this->_table_prefix . "fields_data` " . "(`fieldid`, `data_txt`, `itemid`, `section` ) " . "VALUES ('" . $field_id . "', '" . $field_data_txt . "', '" . $product_id . "', '1') "; $this->_db->setQuery($query); $this->_db->Query(); } else { $query = "UPDATE `" . $this->_table_prefix . "fields_data` SET\r\n\t\t\t\t\t\t\t\t\t\t\t`data_txt` = '" . $field_data_txt . "'\r\n\t\t\t\t\t\t\t\t\t\t\t WHERE `fieldid` = '" . $field_id . "'\r\n\t\t AND itemid ='" . $product_id . "'\r\n\t\t AND \tsection ='1' "; $this->_db->setQuery($query); $this->_db->Query(); } $correctlines++; } } } // Import Related Products if ($post['import'] == 'related_product') { $relpid = $this->getProductIdByNumber($rawdata['related_sku']); $pid = $this->getProductIdByNumber($rawdata['product_sku']); $query = "INSERT IGNORE INTO `" . $this->_table_prefix . "product_related` (`related_id`, `product_id`) VALUES ('" . $relpid . "', '" . $pid . "')"; $this->_db->setQuery($query); if ($this->_db->Query()) { $correctlines++; } } // Import users if ($post['import'] == 'users') { $app = JFactory::getApplication(); $q = "SELECT * FROM `" . $this->_table_prefix . "shopper_group` " . "WHERE `shopper_group_name` = '" . $rawdata['shopper_group_name'] . "'"; $this->_db->setQuery($q); $shopper_group_data = $this->_db->loadObject(); // Insert shopper group if not available if (count($shopper_group_data) <= 0) { $shopper = $this->getTable('shopper_group_detail'); $shopper->load(); $shopper->shopper_group_name = $rawdata['shopper_group_name']; $shopper->shopper_group_customer_type = 1; $shopper->shopper_group_portal = 0; $shopper->store(); // Get last shopper group id $shopper_group_id = $shopper->shopper_group_id; } else { // Get shopper group id $shopper_group_id = $shopper_group_data->shopper_group_id; } // Get redshop user info table $reduser = $this->getTable('user_detail'); // Check for user available if ($rawdata['id'] > 0) { $q = "SELECT * FROM `#__users` " . "WHERE `email` = '" . trim($rawdata['email']) . "' "; $this->_db->setQuery($q); $joomusers = $this->_db->loadObject(); if (count($joomusers) == 0) { $user_id = 0; } else { $user_id = $joomusers->id; } // Initialize some variables $db = JFactory::getDbo(); $me = JFactory::getUser(); $acl = JFactory::getACL(); $MailFrom = $app->getCfg('mailfrom'); $FromName = $app->getCfg('fromname'); $SiteName = $app->getCfg('sitename'); // Create a new JUser object $user = new JUser($user_id); $user->set('username', trim($rawdata['username'])); $user->set('name', $rawdata['name']); $user->set('email', trim($rawdata['email'])); $user->set('password', $rawdata['password']); $user->set('password_clear', $rawdata['password']); $user->set('block', $rawdata['block']); $user->set('sendEmail', $rawdata['sendEmail']); // Set some initial user values $user->set('usertype', $rawdata['usertype']); $user->set('gid', $rawdata['gid']); $date = JFactory::getDate(); $user->set('registerDate', $date->toMySQL()); if ($user->save()) { $reduser->set('user_id', $user->id); $reduser->set('user_email', trim($rawdata['email'])); $reduser->set('firstname', $rawdata['firstname']); $reduser->set('address_type', 'BT'); $reduser->set('lastname', $rawdata['lastname']); $reduser->set('company_name', $rawdata['company_name']); $reduser->set('vat_number', $rawdata['vat_number']); $reduser->set('tax_exempt', $rawdata['tax_exempt']); $reduser->set('shopper_group_id', $shopper_group_id); $reduser->set('is_company', $rawdata['is_company']); $reduser->set('address', $rawdata['address']); $reduser->set('city', $rawdata['city']); $reduser->set('country_code', $rawdata['country_code']); $reduser->set('state_code', $rawdata['state_code']); $reduser->set('zipcode', $rawdata['zipcode']); $reduser->set('phone', $rawdata['phone']); $reduser->set('tax_exempt_approved', $rawdata['tax_exempt_approved']); $reduser->set('approved', $rawdata['approved']); if (count($joomusers) == 0) { $reduser->set('users_info_id', $rawdata['users_info_id']); $ret = $this->_db->insertObject($this->_table_prefix . 'users_info', $reduser, 'users_info_id'); } else { $user_id = $joomusers->id; $q = "SELECT * FROM `" . $this->_table_prefix . "users_info` " . "WHERE `user_id` = '" . $user_id . "'"; $this->_db->setQuery($q); $redusers = $this->_db->loadObject(); if (count($redusers) > 0) { $reduser->set('users_info_id', $redusers->users_info_id); $ret = $this->_db->updateObject($this->_table_prefix . 'users_info', $reduser, 'users_info_id'); } else { $reduser->set('users_info_id', $rawdata['users_info_id']); $ret = $this->_db->insertObject($this->_table_prefix . 'users_info', $reduser, 'users_info_id'); } } if ($ret) { $correctlines++; } } } else { $q = "SELECT * FROM `" . $this->_table_prefix . "users_info` " . "WHERE `user_email` = '" . $rawdata['email'] . "' "; $this->_db->setQuery($q); $redusers = $this->_db->loadObject(); $reduser->set('user_id', $rawdata['id']); $reduser->set('user_email', trim($rawdata['email'])); $reduser->set('firstname', $rawdata['firstname']); $reduser->set('address_type', 'BT'); $reduser->set('lastname', $rawdata['lastname']); $reduser->set('company_name', $rawdata['company_name']); $reduser->set('vat_number', $rawdata['vat_number']); $reduser->set('tax_exempt', $rawdata['tax_exempt']); $reduser->set('shopper_group_id', $shopper_group_id); $reduser->set('is_company', $rawdata['is_company']); $reduser->set('address', $rawdata['address']); $reduser->set('city', $rawdata['city']); $reduser->set('country_code', $rawdata['country_code']); $reduser->set('state_code', $rawdata['state_code']); $reduser->set('zipcode', $rawdata['zipcode']); $reduser->set('phone', $rawdata['phone']); $reduser->set('tax_exempt_approved', $rawdata['tax_exempt_approved']); $reduser->set('approved', $rawdata['approved']); if (count($redusers) > 0) { $reduser->set('users_info_id', $redusers->users_info_id); $ret = $this->_db->updateObject($this->_table_prefix . 'users_info', $reduser, 'users_info_id'); } else { $reduser->set('users_info_id', $rawdata['users_info_id']); $ret = $this->_db->insertObject($this->_table_prefix . 'users_info', $reduser, 'users_info_id'); } if ($ret) { $correctlines++; } } } // Shipping Address Import if ($post['import'] == 'shipping_address') { if (trim($rawdata['username']) != "") { $q = "SELECT id FROM `#__users` " . "WHERE `username` = '" . trim($rawdata['username']) . "' "; $this->_db->setQuery($q); $joom_user_id = $this->_db->loadResult(); if ($joom_user_id > 0) { $reduser = $this->getTable('user_detail'); $reduser->set('user_id', $joom_user_id); $reduser->set('user_email', trim($rawdata['email'])); $reduser->set('firstname', $rawdata['firstname']); $reduser->set('address_type', 'ST'); $reduser->set('lastname', $rawdata['lastname']); $reduser->set('company_name', $rawdata['company_name']); $reduser->set('address', $rawdata['address']); $reduser->set('city', $rawdata['city']); $reduser->set('country_code', $rawdata['country_code']); $reduser->set('state_code', $rawdata['state_code']); $reduser->set('zipcode', $rawdata['zipcode']); $reduser->set('phone', $rawdata['phone']); $reduser->set('users_info_id', 0); $ret = $this->_db->insertObject($this->_table_prefix . 'users_info', $reduser, 'users_info_id'); if ($ret) { $correctlines++; } } } } // Shopper group Import if ($post['import'] == 'shopper_group_price') { $ret = $this->importShopperGroupPrice($rawdata); if ($ret) { $correctlines++; } } // Import stockroom data if ($post['import'] == 'product_stockroom_data') { $product_number = $rawdata['Product_SKU']; $product_stock = $rawdata['stock']; $preorder_stock = 0; $ordered_preorder = 0; $stockroom_id = $rawdata['stockroom_id']; if ($product_number) { $product_id = $this->getProductIdByNumber($product_number); if ($product_id) { echo $q = "SELECT product_id FROM `" . $this->_table_prefix . "product_stockroom_xref` where product_id ='" . $product_id . "' and stockroom_id ='" . $stockroom_id . "'"; $this->_db->setQuery($q); $stock_exists = $this->_db->loadResult(); if ($stock_exists == 0) { $query = 'INSERT INTO ' . $this->_table_prefix . 'product_stockroom_xref ' . '(product_id,stockroom_id,quantity,preorder_stock, ordered_preorder) ' . 'VALUE("' . $product_id . '","' . $stockroom_id . '","' . $product_stock . '","' . $preorder_stock . '","' . $ordered_preorder . '")'; $this->_db->setQuery($query); if (!$this->_db->query()) { $this->setError($this->_db->getErrorMsg()); return false; } } else { $query = "UPDATE `" . $this->_table_prefix . "product_stockroom_xref` SET\r\n\t\t\t\t\t\t\t\t\t\t\t`quantity` = '" . $product_stock . "'\r\n\t\t\t\t\t\t\t\t\t\t\t WHERE `product_id` = '" . $product_id . "' and stockroom_id = '" . $stockroom_id . "'"; $this->_db->setQuery($query); $this->_db->Query(); } $correctlines++; } } } // Import Economic group Products if ($post['import'] == 'economic_group_product') { $product_number = $rawdata['product_number']; $product_group = $rawdata['product_group']; if ($product_group == "") { $product_group = 1; } if ($product_number) { $product_id = $this->getProductIdByNumber($product_number); if ($product_id) { $query = "UPDATE `" . $this->_table_prefix . "product` SET\r\n\t\t\t\t\t\t\t\t\t\t\t`accountgroup_id` = '" . $product_group . "'\r\n\t\t\t\t\t\t\t\t\t\t\t WHERE `product_id` = '" . $product_id . "'"; $this->_db->setQuery($query); $this->_db->Query(); $correctlines++; } } } } } $line++; } else { $blank = ""; $text = "" . $line . "`_`" . $blank . ""; ob_clean(); echo $text; exit; } } fclose($handle); $blank = ""; $text = "`_`" . $line . "`_`" . $line . ""; ob_clean(); echo $text; exit; }