Example #1
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $email = $this->ask('Enter your email:');
     $password = $this->secret('Enter your password:'******'email' => $email, 'password' => $password);
     $this->user->store($data);
     $this->info('Admin user has been successfully created.');
 }
 /**
  * Create a Shibboleth session for the user ID
  *
  * @param  string $uid - The user ID
  * @return $_user (array) - The user infos array created when the user logs in
  */
 function login($uid)
 {
     /* This must be set for local.inc.php to register correctly the global variables in session
      * This is BAD. Logic should be migrated into a function and stop relying on global variables.
      */
     global $_uid, $is_allowedCreateCourse, $_real_cid, $_courseUser;
     global $is_courseMember, $is_courseTutor, $is_allowed_in_course, $_gid;
     $_uid = $uid;
     //is_allowedCreateCourse
     $user = User::store()->get_by_user_id($uid);
     if (empty($user)) {
         return;
     }
     $this->logout();
     Chamilo::session()->start();
     Session::write('_uid', $_uid);
     global $_user;
     $_user = (array) $user;
     $_SESSION['_user'] = $_user;
     $_SESSION['_user']['user_id'] = $_uid;
     $_SESSION['noredirection'] = true;
     //must be called before 'init_local.inc.php'
     event_login();
     //used in 'init_local.inc.php' this is BAD but and should be changed
     $loginFailed = false;
     $uidReset = true;
     $gidReset = true;
     $cidReset = false;
     //FALSE !!
     $mainDbName = Database::get_main_database();
     $includePath = api_get_path(INCLUDE_PATH);
     $no_redirection = true;
     require "{$includePath}/local.inc.php";
     return $_user;
 }
 function beforeFilter()
 {
     $this->__configureAuth();
     // Sets up global Auth User access
     App::import('Model', 'User');
     User::store($this->Auth->user());
 }
 /**
  * Log user in with Shibboleth authentication
  */
 function login()
 {
     if (Shibboleth::session()->is_logged_in()) {
         Redirect::home();
     }
     $user = Shibboleth::store()->get_user();
     if ($user->is_empty()) {
         $message = get_lang('no_login');
         Shibboleth::display()->error_page($message);
     }
     $is_new_user = !User::store()->shibboleth_id_exists($user->unique_id);
     if ($is_new_user && empty($user->email) && Shibboleth::config()->is_email_mandatory) {
         $form = ShibbolethEmailForm::instance();
         if ($email = $form->get_email()) {
             $user->email = $email;
         } else {
             $content = $form->display();
             Shibboleth::display()->page($content);
         }
     }
     Shibboleth::save($user);
     $chamilo_user = User::store()->get_by_shibboleth_id($user->unique_id);
     Shibboleth::session()->login($chamilo_user->user_id);
     if ($is_new_user && $user->status_request) {
         Shibboleth::redirect('/main/auth/shibboleth/app/view/request.php');
     } else {
         Shibboleth::redirect();
     }
 }
Example #5
0
 function beforeFilter()
 {
     App::import('Model', 'User');
     //Configure AuthComponent
     $this->Auth->authorize = 'actions';
     $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
     $this->Auth->logoutRedirect = array('controller' => 'pages', 'action' => 'home');
     $this->Auth->loginRedirect = array('controller' => 'posts', 'action' => 'index');
     $this->Auth->authError = "Não pode aceder a esta secção do site.";
     User::store($this->Auth->user());
 }
Example #6
0
 public static function store()
 {
     $user = new User($_POST);
     $errors = $user->validate();
     if (!$user || count($errors) > 0) {
         //Redirect::to("/", array('message' => "Failed to store user."));
         View::make("user/new.html", array('message' => "Failed to store user.", 'errors' => $errors));
     } else {
         $user->store();
         Redirect::to("/", array('message' => "Saved user."));
     }
 }
 public function register()
 {
     $data = Input::all();
     $rules = ['first_name' => ['required', 'min:3', 'max:35'], 'last_name' => ['required', 'min:3', 'max:35'], 'username' => ['required', 'alpha_num', 'min:3', 'max:35', 'unique:users'], 'email' => ['required', 'email', 'max:128', 'unique:users'], 'picture' => ['sometimes', 'mimes:jpeg,gif,png', 'max:2048'], 'password' => ['required', 'min:6', 'confirmed']];
     $validator = Validator::make($data, $rules);
     if ($validator->fails()) {
         return Alert::formError($validator);
     }
     $user = new User();
     $user_id = $user->store($data);
     $profile = new Profile();
     $profile->store($data, $user_id, Input::hasFile('picture'));
     $this->sendActivation($user_id, $data['email']);
     Auth::login($user);
     return Alert::activate($data['email']);
 }
Example #8
0
 public function procede()
 {
     try {
         if ($this->oRequest->existParam('login')) {
             if (!$this->oRequest->existParam('mail')) {
                 throw new Error("Le champ Email doit être renseigné.", 1033);
             }
             if (!$this->oRequest->existParam('rank')) {
                 throw new Error("Le champ Rang doit être renseigné.", 1033);
             }
             $sPassword = $this->checkPassword();
             if ($this->oRequest->existParam('edit')) {
                 $sPassword = $this->checkPassword();
                 $oUser = new User($this->oRequest->getParam('edit', 'int'), $this->oRequest->getParam('login', 'string'), $sPassword, $this->oRequest->getParam('mail', 'string'), md5(time() * rand()), $this->oRequest->getParam('rank', 'int'));
                 //Suppression
                 if ($this->oRequest->existParam('delete') && $this->oRequest->getParam('delete', 'boolean')) {
                     $oUser->delete();
                     Logger::log('admin', 'L\'utilisateur ' . $this->oRequest->getParam('login', 'string') . ' a été supprimé par ' . $this->oCurrentUser->getLogin());
                     $this->oView->addAlert('L\'utilisateur ' . $this->oRequest->getParam('login', 'string') . ' a été supprimé.', 'success');
                 } else {
                     //Edit
                     $oUser->update();
                     Logger::log('admin', 'L\'utilisateur ' . $this->oRequest->getParam('login', 'string') . ' a été modifié par ' . $this->oCurrentUser->getLogin());
                     $this->oView->addAlert('L\'utilisateur ' . $this->oRequest->getParam('login', 'string') . ' a été modifié.', 'success');
                 }
             } else {
                 if (!$this->oRequest->existParam('password')) {
                     throw new Error("Le champ Password doit être renseigné.", 1033);
                 }
                 if (!$this->oRequest->existParam('confirmation')) {
                     throw new Error("Le champ Confirmation doit être renseigné.", 1033);
                 }
                 $sPassword = $this->checkPassword();
                 $oUser = new User(0, $this->oRequest->getParam('login', 'string'), $sPassword, $this->oRequest->getParam('mail', 'string'), md5(time() * rand()), $this->oRequest->getParam('rank', 'int'));
                 $oUser->store();
                 Logger::log('admin', 'L\'utilisateur ' . $this->oRequest->getParam('login', 'string') . ' a été ajouté par ' . $this->oCurrentUser->getLogin());
                 $this->oView->addAlert('L\'utilisateur ' . $this->oRequest->getParam('login', 'string') . ' a été ajouté.', 'success');
             }
         }
     } catch (Exception $e) {
         $this->oView->addAlert($ex, 'danger');
     } finally {
         $this->createView();
     }
 }
 function beforeFilter()
 {
     //Salvo i dati dell'utente corrente nel modello User per accedervi da altri modelli
     App::import('Model', 'User');
     User::store($this->Auth->user());
     // --- ---
     $this->Auth->authorize = 'controller';
     $this->Auth->userScope = array('User.active' => 1);
     $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login', 'admin' => false);
     if (isset($this->params['admin']) && $this->params['admin']) {
         $this->layout = 'digigas';
     } else {
         $this->Auth->allow('*');
     }
     //$this->Auth->allow('*'); //temporaneo, da disabilitare
     $this->_emailSetUp();
     $this->_loadConfig();
 }
Example #10
0
 function beforeFilter()
 {
     Configure::write('Config.language', 'en');
     if ($this->RequestHandler->isAjax()) {
         Configure::write('debug', 0);
     }
     $this->Auth->fields = array('username' => 'username', 'password' => 'password');
     $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
     $this->Auth->loginRedirect = array('controller' => 'providers', 'action' => 'dashboard');
     $this->Auth->ajaxLogin = '******';
     $this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
     $this->Auth->autoRedirect = false;
     if ($user = $this->Auth->user()) {
         App::import('Model', 'User');
         User::store($this->Auth->user());
     }
     Configure::write('Twitter.apiRequestsRemaining', '?');
 }
Example #11
0
 public function store($data, $is_validate = true)
 {
     $config = (require_once CONFIG_ROOT . 'application.config.php');
     if ($this->validate($data)) {
         $ret = parent::store($data);
         if ($this->platform == self::ePlatform_Weixin || $this->platform == self::ePlatform_QQ) {
             $this->setAppId($config['platform'][$this->platform]['appid']);
             $this->setAppKey($config['platform'][$this->platform]['appkey']);
         } elseif ($this->platform == self::ePlatform_Guest) {
             //appid/openid need to add G_ prefix when in guest mode
             $this->setAppId($config['platform'][$this->platform]['prefix'] . $config['platform'][self::ePlatform_QQ]['appid']);
             $this->setAppKey($config['platform'][self::ePlatform_QQ]['appkey']);
         } else {
             //QQHall,WTLogin is not supported now
             $this->validationErrors[] = 'This platform is not supported now';
             $ret = $this->validationErrors;
         }
     } else {
         $ret = $this->validationErrors;
     }
     return $ret;
 }
Example #12
0
 public function procede()
 {
     try {
         if ($this->oRequest->existParam('code')) {
             if (!$this->oRequest->existParam('password')) {
                 throw new Error('Vous devez renseigner un password.', 1043);
             }
             if (!$this->oRequest->existParam('email')) {
                 throw new Error('Vous devez renseigner une adresse email.', 1043);
             }
             if (!$this->oRequest->existParam('login')) {
                 throw new Error('Vous devez renseigner un nom d\'utilisateur.', 1043);
             }
             $oInvite = new Invites(0, $this->oRequest->getParam('code', 'string'));
             if (!$oInvite->checkInvite()) {
                 throw new Error('Votre code d\'invitation n\'est pas valide.', 1043);
             }
             $sPassword = $this->oRequest->getParam('password', 'string');
             $sConfirmation = $this->oRequest->getParam('confirmation', 'string');
             if ($sPassword != $sConfirmation) {
                 throw new Error("Le password et la confirmation ne correspondent pas.", 1043);
             }
             $sPassword = User::cryptPassword($sPassword);
             $oUser = new User(0, $this->oRequest->getParam('login', 'string'), $sPassword, $this->oRequest->getParam('email', 'string'), md5(time() * rand()));
             $oUser->store();
             //On demande au modèle de vérifier l'identification
             $this->oCurrentUser->loadFromFormular($this->oRequest->getParam('login', 'string'), $this->oRequest->getParam('password', 'string'), false);
             $oInvite->usedBy($this->oCurrentUser->getId());
             Logger::log('admin', $this->oCurrentUser->getLogin() . ' a rejoint le site avec le code : ' . $this->oRequest->getParam('code', 'string'));
             $this->oView->addAlert("Redirection en cours ...", 'success');
             header("Location: http://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/index.php");
         }
     } catch (Error $e) {
         $this->oView->addAlert($e, 'danger');
     } finally {
         $this->oView->Create();
     }
 }
Example #13
0
function save_post($post_id)
{
    global $link, $db, $post, $current_user, $globals, $site_key;
    $post = new Post();
    $_POST['post'] = clean_text($_POST['post'], 0, false, 300);
    if (mb_strlen($_POST['post']) < 5) {
        echo 'ERROR: ' . _('texto muy corto');
        die;
    }
    if ($post_id > 0) {
        $post->id = $post_id;
        if (!$post->read()) {
            die;
        }
        if ((intval($_POST['user_id']) == $current_user->user_id && $current_user->user_id == $post->author && time() - $post->date < 3600 || $current_user->user_level == 'god' && time() - $post->date < 864000) && $_POST['key'] == $post->randkey) {
            $post->content = $_POST['post'];
            if (strlen($post->content) > 0) {
                $post->store();
            }
        } else {
            echo 'ERROR: ' . _('no tiene permisos para grabar');
            die;
        }
    } else {
        if ($current_user->user_id != intval($_POST['user_id'])) {
            die;
        }
        if ($current_user->user_karma < $globals['min_karma_for_posts']) {
            echo 'ERROR: ' . _('el karma es muy bajo');
            die;
        }
        // Check the post wasn't already stored
        $post->randkey = intval($_POST['key']);
        $post->author = $current_user->user_id;
        $post->content = $_POST['post'];
        $already_stored = intval($db->get_var("select count(*) from posts where post_user_id = {$current_user->user_id} and post_date > date_sub(now(), interval 12 hour) and post_randkey = {$post->randkey}")) + $post->same_text_count();
        if (!$already_stored) {
            // Verify that there are a period of 1 minute between posts.
            if (intval($db->get_var("select count(*) from posts where post_user_id = {$current_user->user_id} and post_date > date_sub(now(), interval 1 minute)")) > 0) {
                echo 'ERROR: ' . _('debe esperar 1 minuto entre notas');
                die;
            }
            $same_links = $post->same_links_count();
            if ($same_links > 2) {
                require_once mnminclude . 'user.php';
                $user = new User();
                $user->id = $current_user->user_id;
                $user->read();
                $reduction = $same_links * 0.2;
                $user->karma = $user->karma - $reduction;
                syslog(LOG_NOTICE, "Meneame: post_edit decreasing {$reduction} of karma to {$user->username} (now {$user->karma})");
                $user->store();
            }
            $post->store();
        } else {
            echo 'ERROR: ' . _('comentario grabado previamente');
            die;
        }
    }
    $post->print_summary();
}
Example #14
0
	static function save_from_post($link) {
		global $db, $current_user, $globals;

		require_once(mnminclude.'ban.php');

		$error = '';
		if(check_ban_proxy() && !$globals['development']) return _('dirección IP no permitida');

		// Check if is a POST of a comment

		if( ! ($link->votes > 0 && $link->date > $globals['now']-$globals['time_enabled_comments']*1.01 && 
				$link->comments < $globals['max_comments'] &&
				intval($_POST['link_id']) == $link->id && $current_user->authenticated && 
				intval($_POST['user_id']) == $current_user->user_id &&
				intval($_POST['randkey']) > 0
				)) {
			return _('comentario o usuario incorrecto');
		}

		if ($current_user->user_karma < $globals['min_karma_for_comments'] && $current_user->user_id != $link->author) {
			return _('karma demasiado bajo');
		}

		$comment = new Comment;

		$comment->link=$link->id;
		$comment->ip = $db->escape($globals['user_ip']);
		$comment->randkey=intval($_POST['randkey']);
		$comment->author=intval($_POST['user_id']);
		$comment->karma=round($current_user->user_karma);
		$comment->content=clean_text_with_tags($_POST['comment_content'], 0, false, 10000);
    $comment->parent=intval($_POST['parent_id']);

    //get level
    $parentComment = new Comment();
    $parentComment->id = intval($comment->parent);
    $parentComment->read_basic();
    if ($parentComment->nested_level > $globals['NESTED_COMMENTS_MAX_LEVEL']) {
				return _('Chegache ao nivel límite de comentarios aniñados...');
    }
    $comment->nested_level = $parentComment->nested_level + 1;


		// Check if is an admin comment
		if ($current_user->user_level == 'god' && $_POST['type'] == 'admin') {
			$comment->type = 'admin';
		} 

		// Don't allow to comment with a clone
		$hours = intval($globals['user_comments_clon_interval']);
		if ($hours > 0) {
			$clones = $current_user->get_clones($hours+1);
			if ( $clones) {
				$l = implode(',', $clones);
				$c = (int) $db->get_var("select count(*) from comments where comment_date > date_sub(now(), interval $hours hour) and comment_user_id in ($l)");
				if ($c > 0) {
					syslog(LOG_NOTICE, "Meneame, clon comment ($current_user->user_login, $comment->ip) in $link->uri");
					return _('ya hizo un comentario con usuarios clones');
				}
			}
		}

		// Basic check to avoid abuses from same IP
		if (!$current_user->admin && $current_user->user_karma < 6.2) { // Don't check in case of admin comments or higher karma

			// Avoid astroturfing from the same link's author
			if ($link->status != 'published' && $link->ip == $globals['user_ip'] && $link->author != $comment->author) {
				UserAuth::insert_clon($comment->author, $link->author, $link->ip);
				syslog(LOG_NOTICE, "Meneame, comment-link astroturfing ($current_user->user_login, $link->ip): ".$link->get_permalink());
				return _('no se puede comentar desde la misma IP del autor del envío');
			}

			// Avoid floods with clones from the same IP
			if (intval($db->get_var("select count(*) from comments where comment_link_id = $link->id and comment_ip='$comment->ip' and comment_user_id != $comment->author")) > 1) {
				syslog(LOG_NOTICE, "Meneame, comment astroturfing ($current_user->user_login, $comment->ip)");
				return _('demasiados comentarios desde la misma IP con usuarios diferentes');
			}
		}


		if (mb_strlen($comment->content) < 5 || ! preg_match('/[a-zA-Z:-]/', $_POST['comment_content'])) { // Check there are at least a valid char
			return _('texto muy breve o caracteres no válidos');
		}


		// Check the comment wasn't already stored
		$already_stored = intval($db->get_var("select count(*) from comments where comment_link_id = $comment->link and comment_user_id = $comment->author and comment_randkey = $comment->randkey"));
		if ($already_stored) {
			return _('comentario duplicado');
		}

		if (! $current_user->admin) {
			$comment->get_links();
			if ($comment->banned && $current_user->Date() > $globals['now'] - 86400) {
				syslog(LOG_NOTICE, "Meneame: comment not inserted, banned link ($current_user->user_login)");
				return _('comentario no insertado, enlace a sitio deshabilitado (y usuario reciente)');
			}

			// Lower karma to comments' spammers
			$comment_count = (int) $db->get_var("select count(*) from comments where comment_user_id = $current_user->user_id and comment_date > date_sub(now(), interval 3 minute)");
			// Check the text is not the same
			$same_count = $comment->same_text_count();
			$same_links_count = $comment->same_links_count();
			if ($comment->banned) $same_links_count *= 2;
			$same_count += $same_links_count;
		} else {
			$comment_count  = $same_count = 0;
		}

		$comment_limit = round(min($current_user->user_karma/6, 2) * 2.5);
		if ($comment_count > $comment_limit || $same_count > 2) {
			$reduction = 0;
			if ($comment_count > $comment_limit) {
				$reduction += ($comment_count-3) * 0.1;
			}
			if($same_count > 1) {
				$reduction += $same_count * 0.25;
			}
			if ($reduction > 0) {
				$user = new User;
				$user->id = $current_user->user_id;
				$user->read();
				$user->karma = $user->karma - $reduction;
				syslog(LOG_NOTICE, "Meneame: story decreasing $reduction of karma to $current_user->user_login (now $user->karma)");
				$user->store();
				$annotation = new Annotation("karma-$user->id");
				$annotation->append(_('texto repetido o abuso de enlaces en comentarios').": -$reduction, karma: $user->karma\n");
				$error .= ' ' . ('penalización de karma por texto repetido o abuso de enlaces');
			}
		}
		$db->transaction();
		$comment->store();
		$comment->insert_vote();
		$link->update_comments();
		$db->commit();
		// Comment stored, just redirect to it page
		header('Location: '.$link->get_permalink() . '#c-'.$comment->order);
		die;
		//return $error;
	}
Example #15
0
 /**
  * beforeFilter function called before filter
  *
  * @access public
  * @return void
  */
 public function beforeFilter()
 {
     $timezone = $this->SysParameter->findByParameterCode('system.timezone');
     // default to UTC if no timezone is set
     if (!(empty($timezone) || empty($timezone['SysParameter']['parameter_value']))) {
         $timezone = $timezone['SysParameter']['parameter_value'];
         // check that the timezone is valid
         if (isset($this->validTZ[$timezone])) {
             date_default_timezone_set($timezone);
         } else {
             $this->Session->setFlash(__('An invalid timezone is provided, please edit "system.timezone"', true));
         }
     }
     $this->Auth->autoRedirect = false;
     // backward compatible with original ipeer hash  method
     Security::setHash('md5');
     Configure::write('Security.salt', '');
     $locale = $this->SysParameter->findByParameterCode('display.locale');
     // default to eng if no locale is set
     if (!(empty($locale) || empty($locale['SysParameter']['parameter_value']))) {
         $locale = $locale['SysParameter']['parameter_value'];
         // TODO: check that the locale is valid
         Configure::write('Config.language', $locale);
     } else {
         Configure::write('Config.language', 'eng');
     }
     // if we have a session transfered to us
     if ($this->_hasSessionTransferData()) {
         if ($this->_authenticateWithSessionTransferData()) {
             if (method_exists($this, '_afterLogin')) {
                 $this->_afterLogin(false);
             }
         } else {
             $this->Session->setFlash($this->Auth->loginError, $this->Auth->flashElement, array(), 'auth');
         }
     }
     // store user in the singleton for global access
     User::store($this->Auth->user());
     $this->breadcrumb = Breadcrumb::create();
     if ($this->Auth->isAuthorized()) {
         // check if the user has permission to access the controller/action
         $permission = array_filter(array('controllers', ucwords($this->params['plugin']), ucwords($this->params['controller']), $this->params['action']));
         if (!User::hasPermission(join('/', $permission))) {
             $this->Session->setFlash('Error: You do not have permission to access the page.');
             $this->redirect('/home');
             return;
         }
         $this->_checkSystemVersion();
     }
     // for setting up google analytics
     $trackingId = $this->SysParameter->findByParameterCode('google_analytics.tracking_id');
     $domain = $this->SysParameter->findByParameterCode('google_analytics.domain');
     $customLogo = $this->SysParameter->findByParameterCode('banner.custom_logo');
     $this->set('trackingId', $trackingId);
     $this->set('domain', $domain);
     $this->set('customLogo', $customLogo);
     parent::beforeFilter();
 }
 /**
  * Import Users from a CSV file
  *
  * Sets up common User and Profile fields as well as
  * Newsletter list relations.
  * Fields and their mapping:
  *  Anrede    -> Titel
  *  Vorname
  *  Name
  *  eMail
  *  Firma
  *  Strasse    -> Zusammen mit Hausnummer in Adresse
  *  Hausnummer    -> Zusammen mit Strasse in Adresse
  *  PLZ
  *  Ort
  *  Land
  *  Bundesland    -> Evtl in Ort?
  *  Tel.-Vorwahl    -> Zusammen mit Tel.-Nummer in phone_office
  *  Tel.-Nummer        -> Zusammen mit Tel.-Vorwahl in phone_office
  *  Fax-Vorwahl        -> Zusammen mit Fax.-Nummer in phone_fax
  *  Fax-Nummer        -> Zusammen mit Fax.-Vorwahl in phone_fax
  *  Mobil-Vorwahl    -> Zusammen mit Mobil-Nummer in phone_mobile
  *  Mobil-Nummer    -> Zusammen mit Mobil-Vorwahl in phone_mobile
  *  P1    -> Interessen: Newsletter Listen, kommagetrennt
  *      -> Nicht vorhandene Listen werden angelegt
  *  P2    -> Antwort: ?
  *  P3    -> ?
  *  P4    -> Titel: ?
  *  P5    -> ?
  *  Ursprungsformular    -> ?
  *  Permission    -> ?
  *  Ausgetragen    -> Wenn true, alle Listenzuordnungen entfernen, sonst fehlende anlegen
  *  Anzahl Hard-Bounces    -> Nicht vorhanden?
  *  Status    -> Bedeutung?
  *  Sprache    -> Wird die verwendet?
  *  ID    -> Bedeutung?
  *  Eintragungsdatum    -> regdate
  *  Aenderungsdatum    -> ? (Nur regdate)
  *  Austragungsdatum    -> ? (Nur regdate)
  * @param   string    $file_name    The CSV file name
  */
 static function import_csv($file_name)
 {
     global $_ARRAYLANG;
     \Env::get('ClassLoader')->loadFile(ASCMS_LIBRARY_PATH . '/importexport/lib/csv.class.php');
     //DBG::activate(DBG_ADODB_ERROR|DBG_LOG_FIREPHP|DBG_PHP);
     $objUser = \FWUser::getFWUserObject()->objUser;
     $objCsv = new \CsvLib();
     $arrCsv = $objCsv->parse($file_name);
     //        $arrFields = $arrCsv['fieldnames'];
     $arrUsers = $arrCsv['data'];
     //DBG::log("Found ".count($arrUsers)." Users in the CSV file");
     foreach ($arrUsers as $arrUser) {
         //echo(var_export($arrUser, true)."<br />");// var_export($objUser, true)."<hr />"
         $email = $arrUser['3'];
         //DBG::log("Found e-mail $email");
         if (!\FWValidator::isEmail($email)) {
             self::$arrStatusMsg['error'][] = sprintf($_ARRAYLANG['TXT_ACCESS_IMPORT_MESSAGE_TEMPLATE'], $email, $_ARRAYLANG['TXT_ACCESS_IMPORT_ERROR_INVALID_EMAIL']);
             continue;
         }
         // TODO: I suppose that the imported file is ISO-8859-1 or so
         $title = utf8_encode($arrUser[0]);
         $gender = preg_match('//', $title) ? 'gender_male' : 'gender_female';
         $firstname = utf8_encode($arrUser[1]);
         $lastname = utf8_encode($arrUser[2]);
         $company = utf8_encode($arrUser[4]);
         $address = utf8_encode($arrUser[5]) . ' ' . utf8_encode($arrUser[6]);
         $zip = utf8_encode($arrUser[7]);
         $city = utf8_encode($arrUser[8]);
         $country = utf8_encode($arrUser[9]);
         $state = utf8_encode($arrUser[10]);
         if ($state) {
             $city .= ", {$state}";
         }
         $phone_office = utf8_encode($arrUser[11]) . ' ' . utf8_encode($arrUser[12]);
         $phone_fax = utf8_encode($arrUser[13]) . ' ' . utf8_encode($arrUser[14]);
         $phone_mobile = utf8_encode($arrUser[15]) . ' ' . utf8_encode($arrUser[16]);
         $p1_lists = utf8_encode($arrUser[17]);
         $unsubscribed = utf8_encode($arrUser[24]);
         $language = utf8_encode($arrUser[27]);
         // These are all unused for the time being
         //                $p2_answer = $arrUser[18];
         //                $p3 = $arrUser[19];
         //                $p4_title = $arrUser[20];
         //                $p5 = $arrUser[21];
         //                $source = $arrUser[22];
         //                $permission = $arrUser[23];
         //                $bounces = $arrUser[25];
         //                $status = $arrUser[26];
         //                $id = $arrUser[28];
         //                $date_subscribed = $arrUser[29];
         //                $date_changed = $arrUser[30];
         //                $date_unsubscribe = $arrUser[31];
         $objUser = new \User();
         $objUser = $objUser->getUsers(array('email' => array($email)));
         $new_user = false;
         if (!$objUser) {
             $new_user = true;
             $objUser = new \User();
             $objUser->setUsername(\User::makeUsername($lastname, $firstname));
             $objUser->setPassword(\User::makePassword());
             $objUser->setEmail($email);
         }
         // TODO: Make new Users active or inactive?
         //            $objUser->setActiveStatus(0);
         //            $objUser->setAdminStatus(0);
         $lang_id = \FWLanguage::getLanguageIdByCode($language);
         $objUser->setFrontendLanguage($lang_id);
         $objUser->setBackendLanguage($lang_id);
         $objUser->setProfile(array('gender' => array($gender), 'title' => array($title), 'firstname' => array($firstname), 'lastname' => array($lastname), 'company' => array($company), 'address' => array($address), 'city' => array($city), 'zip' => array($zip), 'country' => array($country), 'phone_office' => array($phone_office), 'phone_mobile' => array($phone_mobile), 'phone_fax' => array($phone_fax)));
         $arrLists = preg_split('/\\s*,\\s*/', $p1_lists, null, PREG_SPLIT_NO_EMPTY);
         $arrListId = array();
         if (preg_match('/false/i', $unsubscribed)) {
             // User has not unsubscribed (yet), collect the List IDs
             foreach ($arrLists as $list_name) {
                 $list_id = \Cx\Modules\Newsletter\Controller\NewsletterLib::getListIdByName($list_name);
                 //DBG::log("List '$list_name' => ID $list_id");
                 if (!$list_id) {
                     // TODO: Shall I do this?
                     $list_id = \Cx\Modules\Newsletter\Controller\NewsletterLib::_addList(addslashes($list_name));
                     self::$arrStatusMsg['ok'][] = sprintf($_ARRAYLANG['TXT_ACCESS_IMPORT_MESSAGE_TEMPLATE'], $list_name, $_ARRAYLANG['TXT_ACCESS_IMPORT_SUCCESS_LIST_CREATED']);
                 }
                 $arrListId[$list_id] = $list_id;
             }
         }
         $objUser->setNewsletterCategories($arrListId);
         if ($objUser->store()) {
             self::$arrStatusMsg['ok'][] = sprintf($_ARRAYLANG['TXT_ACCESS_IMPORT_MESSAGE_TEMPLATE'], $email, $new_user ? $_ARRAYLANG['TXT_ACCESS_IMPORT_SUCCESS_USER_CREATED'] : $_ARRAYLANG['TXT_ACCESS_IMPORT_SUCCESS_USER_UPDATED']);
         } else {
             self::$arrStatusMsg['error'][] = sprintf($_ARRAYLANG['TXT_ACCESS_IMPORT_MESSAGE_TEMPLATE'], $email, $_ARRAYLANG['TXT_ACCESS_IMPORT_ERROR_CREATING_USER']);
         }
     }
 }
Example #17
0
 public function register()
 {
     // POST: user_name, display_name, email, title, password, passwordc, captcha, spiderbro, csrf_token
     $post = $this->_app->request->post();
     // Get the alert message stream
     $ms = $this->_app->alerts;
     // Check the honeypot. 'spiderbro' is not a real field, it is hidden on the main page and must be submitted with its default value for this to be processed.
     if (!$post['spiderbro'] || $post['spiderbro'] != "http://") {
         error_log("Possible spam received:" . print_r($this->_app->request->post(), true));
         $ms->addMessage("danger", "Aww hellllls no!");
         $this->_app->halt(500);
         // Don't let on about why the request failed ;-)
     }
     // Load the request schema
     $requestSchema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/register.json");
     // Set up Fortress to process the request
     $rf = new \Fortress\HTTPRequestFortress($ms, $requestSchema, $post);
     // Security measure: do not allow registering new users until the master account has been created.
     if (!UserLoader::exists($this->_app->config('user_id_master'))) {
         $ms->addMessageTranslated("danger", "MASTER_ACCOUNT_NOT_EXISTS");
         $this->_app->halt(403);
     }
     // Check if registration is currently enabled
     if (!$this->_app->site->can_register) {
         $ms->addMessageTranslated("danger", "ACCOUNT_REGISTRATION_DISABLED");
         $this->_app->halt(403);
     }
     // Prevent the user from registering if he/she is already logged in
     if (!$this->_app->user->isGuest()) {
         $ms->addMessageTranslated("danger", "ACCOUNT_REGISTRATION_LOGOUT");
         $this->_app->halt(200);
     }
     // Sanitize data
     $rf->sanitize();
     // Validate, and halt on validation errors.
     $error = !$rf->validate(true);
     // Get the filtered data
     $data = $rf->data();
     // Check captcha, if required
     if ($this->_app->site->enable_captcha == "1") {
         if (!$data['captcha'] || md5($data['captcha']) != $_SESSION['userfrosting']['captcha']) {
             $ms->addMessageTranslated("danger", "CAPTCHA_FAIL");
             $error = true;
         }
     }
     // Remove captcha, password confirmation from object data
     $rf->removeFields(['captcha', 'passwordc']);
     // Perform desired data transformations.  Is this a feature we could add to Fortress?
     $data['user_name'] = strtolower(trim($data['user_name']));
     $data['display_name'] = trim($data['display_name']);
     $data['email'] = strtolower(trim($data['email']));
     $data['locale'] = $this->_app->site->default_locale;
     if ($this->_app->site->require_activation) {
         $data['active'] = 0;
     } else {
         $data['active'] = 1;
     }
     // Check if username or email already exists
     if (UserLoader::exists($data['user_name'], 'user_name')) {
         $ms->addMessageTranslated("danger", "ACCOUNT_USERNAME_IN_USE", $data);
         $error = true;
     }
     if (UserLoader::exists($data['email'], 'email')) {
         $ms->addMessageTranslated("danger", "ACCOUNT_EMAIL_IN_USE", $data);
         $error = true;
     }
     // Halt on any validation errors
     if ($error) {
         $this->_app->halt(400);
     }
     // Get default primary group (is_default = GROUP_DEFAULT_PRIMARY)
     $primaryGroup = GroupLoader::fetch(GROUP_DEFAULT_PRIMARY, "is_default");
     $data['primary_group_id'] = $primaryGroup->id;
     // Set default title for new users
     $data['title'] = $primaryGroup->new_user_title;
     // Hash password
     $data['password'] = Authentication::hashPassword($data['password']);
     // Create the user
     $user = new User($data);
     // Add user to default groups, including default primary group
     $defaultGroups = GroupLoader::fetchAll(GROUP_DEFAULT, "is_default");
     $user->addGroup($primaryGroup->id);
     foreach ($defaultGroups as $group_id => $group) {
         $user->addGroup($group_id);
     }
     // Store new user to database
     $user->store();
     if ($this->_app->site->require_activation) {
         // Create and send activation email
         $mail = new \PHPMailer();
         $mail->From = $this->_app->site->admin_email;
         $mail->FromName = $this->_app->site->site_title;
         $mail->addAddress($user->email);
         // Add a recipient
         $mail->addReplyTo($this->_app->site->admin_email, $this->_app->site->site_title);
         $mail->Subject = $this->_app->site->site_title . " - please activate your account";
         $mail->Body = $this->_app->view()->render("common/mail/activate-new.html", ["user" => $user]);
         $mail->isHTML(true);
         // Set email format to HTML
         if (!$mail->send()) {
             $ms->addMessageTranslated("danger", "MAIL_ERROR");
             error_log('Mailer Error: ' . $mail->ErrorInfo);
             $this->_app->halt(500);
         }
         // Activation required
         $ms->addMessageTranslated("success", "ACCOUNT_REGISTRATION_COMPLETE_TYPE2");
     } else {
         // No activation required
         $ms->addMessageTranslated("success", "ACCOUNT_REGISTRATION_COMPLETE_TYPE1");
     }
 }
Example #18
0
function save_post($post_id)
{
    global $link, $db, $post, $current_user, $globals, $site_key;
    $post = new Post();
    $_POST['post'] = clean_text_with_tags($_POST['post'], 0, false, $globals['posts_len']);
    if (mb_strlen($_POST['post']) < 5) {
        echo 'ERROR: ' . _('texto muy corto');
        die;
    }
    if ($post_id > 0) {
        $post->id = $post_id;
        if (!$post->read()) {
            die;
        }
        if ((intval($_POST['user_id']) == $current_user->user_id && $current_user->user_id == $post->author && time() - $post->date < 3600 || $current_user->user_level == 'god' && time() - $post->date < 864000) && $_POST['key'] == $post->randkey) {
            $post->content = $_POST['post'];
            if (strlen($post->content) > 0) {
                $post->store();
            }
        } else {
            echo 'ERROR: ' . _('no tiene permisos para grabar');
            die;
        }
    } else {
        if ($current_user->user_id != intval($_POST['user_id'])) {
            die;
        }
        if ($current_user->user_karma < $globals['min_karma_for_posts']) {
            echo 'ERROR: ' . _('el karma es muy bajo');
            die;
        }
        // Check the post wasn't already stored
        $post->randkey = intval($_POST['key']);
        $post->author = $current_user->user_id;
        $post->content = $_POST['post'];
        $dupe = intval($db->get_var("select count(*) from posts where post_user_id = {$current_user->user_id} and post_date > date_sub(now(), interval 1 hour) and post_randkey = {$post->randkey}"));
        if (!$dupe && !$post->same_text_count()) {
            // Verify that there are a period of 1 minute between posts.
            if (intval($db->get_var("select count(*) from posts where post_user_id = {$current_user->user_id} and post_date > date_sub(now(), interval 1 minute)")) > 0) {
                echo 'ERROR: ' . _('debe esperar 1 minuto entre notas');
                die;
            }
            $same_links = $post->same_links_count();
            if ($same_links > 2) {
                $user = new User();
                $user->id = $current_user->user_id;
                $user->read();
                $reduction = $same_links * 0.2;
                $user->karma = $user->karma - $reduction;
                syslog(LOG_NOTICE, "Meneame: post_edit decreasing {$reduction} of karma to {$user->username} (now {$user->karma})");
                $user->store();
                $annotation = new Annotation("karma-{$user->id}");
                $annotation->append(_('demasiados enlaces al mismo dominio en las notas') . ": -{$reduction}, karma: {$user->karma}\n");
            }
            // Check again for last seconds, ajax calls sometimes add two posts
            $dupe = intval($db->get_var("select count(*) from posts where post_user_id = {$current_user->user_id} and post_date > date_sub(now(), interval 10 second) and post_randkey = {$post->randkey}"));
            if (!$dupe) {
                $post->store();
            }
        } else {
            echo 'ERROR: ' . _('comentario grabado previamente');
            die;
        }
    }
    $post->print_summary();
}
Example #19
0
 /**
  * Searchs for an user with the given user id of the social media platform.
  * If there is no user, create one and directly log in.
  *
  * @param string $oauth_id the user id of the social media platform
  * @return bool
  * @throws OAuth_Exception
  */
 protected function getContrexxUser($oauth_id)
 {
     global $sessionObj;
     //\DBG::activate();
     $arrSettings = \User_Setting::getSettings();
     $provider = $this::OAUTH_PROVIDER;
     $FWUser = \FWUser::getFWUserObject();
     $objUser = $FWUser->objUser->getByNetwork($provider, $oauth_id);
     if (!$objUser) {
         // check whether the user is already logged in
         // if the user is logged in just add a new network to the user object
         if ($FWUser->objUser->login()) {
             $objUser = $FWUser->objUser;
             $this->addProviderToUserObject($provider, $oauth_id, $objUser);
             $objUser->getNetworks()->save();
             return true;
         }
         // create a new user with the default profile attributes
         $objUser = new \User();
         $objUser->setEmail($this->getEmail());
         $objUser->setAdminStatus(0);
         $objUser->setProfile(array('firstname' => array($this->getFirstname()), 'lastname' => array($this->getLastname())));
         $registrationRedirectNeeded = $arrSettings['sociallogin_show_signup']['status'];
         // if user_account_verification is true (1), then we need to do checkMandatoryCompliance(), because
         // the required fields must be set.
         if ($registrationRedirectNeeded == false && $arrSettings['user_account_verification']['value'] === 1) {
             $registrationRedirectNeeded = !$objUser->checkMandatoryCompliance();
         }
         $objUser->setActiveStatus(!$registrationRedirectNeeded);
         if ($registrationRedirectNeeded) {
             $objUser->setRestoreKey();
             $objUser->setRestoreKeyTime(intval($arrSettings['sociallogin_activation_timeout']['value']) * 60);
         }
         if (!empty($arrSettings['sociallogin_assign_to_groups']['value'])) {
             $groups = $arrSettings['sociallogin_assign_to_groups']['value'];
         } else {
             $groups = $arrSettings['assigne_to_groups']['value'];
         }
         $objUser->setGroups(explode(',', $groups));
         // if we can create the user without sign up page
         if (!$objUser->store()) {
             // if the email address already exists but not with the given oauth-provider
             throw new OAuth_Exception();
         }
         // add the social network to user
         $this->addProviderToUserObject($provider, $oauth_id, $objUser);
         $objUser->getNetworks()->save();
         // check whether there are empty mandatory fields or the setting to show sign up everytime
         if ($registrationRedirectNeeded) {
             // start session if no session is open
             if (!isset($sessionObj) || !is_object($sessionObj)) {
                 $sessionObj = \cmsSession::getInstance();
             }
             // write the user id to session so we can pre-fill the sign up form
             $_SESSION['user_id'] = $objUser->getId();
             // generate url for sign up page and redirect
             $signUpPageUri = \Cx\Core\Routing\Url::fromModuleAndCmd('Access', 'signup');
             \Cx\Core\Csrf\Controller\Csrf::header('Location: ' . $signUpPageUri->__toString());
             exit;
         }
     }
     $FWUser->loginUser($objUser);
 }
Example #20
0
 private function __setupAuth()
 {
     //Configure AuthComponent
     $this->Auth->authorize = 'controller';
     if (!isset($this->params['prefix']) || !in_array($this->params['prefix'], Configure::read('Routing.prefixes'))) {
         // all non-prefixed actions are allowed
         $this->Auth->allow('*');
     }
     $this->Auth->autoRedirect = false;
     $this->Auth->loginAction = '/login';
     $this->Auth->logoutRedirect = '/';
     $this->Auth->loginRedirect = '/pages/logged';
     //array('controller' => 'users', 'action' => 'profile');
     // What to say when the login was incorrect.
     $this->Auth->loginError = __('Falha no login. Por favor, verifique se o usuário e senha digitado estão corretos.', TRUE);
     // What to say when unauthorized access has detected
     $this->Auth->authError = __('Desculpe, você precisa estar autenticado para acessar esta página.', TRUE);
     // tmp var to load logged user information
     $this->activeUser = $this->Auth->user();
     if ($this->activeUser !== null) {
         // set control flag
         $this->userLogged = true;
         // Define a static access to user information
         App::import('Model', 'User');
         User::store($this->activeUser);
         // Define user information in view class
         $this->set('activeUser', $this->activeUser);
     }
 }
 static function test_new_no_affiliation_default()
 {
     self::init();
     self::helper()->setup_new_no_affiliation();
     $shib_user = Shibboleth::store()->get_user();
     self::assert($config = Shibboleth::config()->default_status == Shibboleth::STUDENT_STATUS);
     self::assert(!User::store()->shibboleth_id_exists($shib_user->unique_id));
     self::assert($shib_user->affiliation == '');
     Shibboleth::save($shib_user);
     $user = User::store()->get_by_shibboleth_id($shib_user->unique_id);
     self::assert($user->email == $shib_user->email);
     self::assert($user->firstname == 'John');
     self::assert($user->lastname == $shib_user->lastname);
     self::assert($user->persistent_id == $shib_user->persistent_id);
     self::assert($user->status == Shibboleth::STUDENT_STATUS);
     self::assert(!empty($user->password));
     self::assert(!empty($user->username));
 }
     $userdata = new User();
     $userdata->username = $user->user_login;
     if (!$userdata->read()) {
         echo "Error reading user data.";
         die;
     }
     // module system hook
     $vars = '';
     check_actions('admin_users_save', $vars);
     $userdata->username = trim(sanitize($_GET["login"], 3));
     $userdata->level = trim(sanitize($_GET["level"], 3));
     $userdata->email = trim(sanitize($_GET["email"], 3));
     if ($_GET["password"] && $_GET["password"] == $_GET["password2"]) {
         $userdata->pass = $_GET["password"];
     }
     $userdata->store();
     // breadcrumbs and page title
     $navwhere['text1'] = $main_smarty->get_config_vars('PLIGG_Visual_Header_AdminPanel');
     $navwhere['link1'] = getmyurl('admin', '');
     $navwhere['text2'] = $main_smarty->get_config_vars('PLIGG_Visual_Header_AdminPanel_1');
     $navwhere['link2'] = my_pligg_base . "/admin/admin_users.php";
     $navwhere['text3'] = $main_smarty->get_config_vars('PLIGG_Visual_Breadcrumb_Edit_User_Data_Saved');
     $main_smarty->assign('navbar_where', $navwhere);
     $main_smarty->assign('posttitle', " / " . $main_smarty->get_config_vars('PLIGG_Visual_Header_AdminPanel'));
     // pagename
     define('pagename', 'admin_users');
     $main_smarty->assign('pagename', pagename);
     header("Location: " . my_pligg_base . "/admin/admin_users.php?mode=view&user="******"login"] . "");
     die;
 } else {
     showmyerror('userdoesntexist');
 /**
  * Create a new Order 
  * 
  * @param integer $productId            productId
  * @param object  $objUser              \User object
  * @param string  $transactionReference transactionReference
  * @param array   $subscriptionOptions  subscriptionOptions
  * 
  * @return boolean
  * @throws OrderRepositoryException
  */
 public function createOrder($productId, \Cx\Modules\Crm\Model\Entity\Currency $currency, \User $objUser, $transactionReference, $subscriptionOptions = array())
 {
     if (\FWValidator::isEmpty($productId) || \FWValidator::isEmpty($subscriptionOptions) || \FWValidator::isEmpty($transactionReference) || \FWValidator::isEmpty($currency)) {
         return;
     }
     $contactId = $objUser->getCrmUserId();
     if (\FWValidator::isEmpty($contactId)) {
         return;
     }
     try {
         $order = new \Cx\Modules\Order\Model\Entity\Order();
         $order->setContactId($contactId);
         $order->setCurrency($currency);
         $productRepository = \Env::get('em')->getRepository('Cx\\Modules\\Pim\\Model\\Entity\\Product');
         $product = $productRepository->findOneBy(array('id' => $productId));
         //create subscription
         $subscription = $order->createSubscription($product, $subscriptionOptions);
         // set discount price for first payment period of subscription
         if (!empty($subscriptionOptions['oneTimeSalePrice'])) {
             $subscription->setPaymentAmount($subscriptionOptions['oneTimeSalePrice']);
         }
         $order->billSubscriptions();
         $invoices = $order->getInvoices();
         if (!empty($invoices)) {
             \DBG::msg(__METHOD__ . ": order has invoices");
             $paymentRepo = \Env::get('em')->getRepository('\\Cx\\Modules\\Order\\Model\\Entity\\Payment');
             foreach ($invoices as $invoice) {
                 if (!$invoice->getPaid()) {
                     \DBG::msg(__METHOD__ . ": lookup payment with transaction-reference {$transactionReference} and amount " . $invoice->getAmount());
                     $payment = $paymentRepo->findOneByCriteria(array('amount' => $invoice->getAmount(), 'transactionReference' => $transactionReference, 'invoice' => null));
                     if ($payment) {
                         \DBG::msg(__METHOD__ . ": payment found");
                         //set subscription-id to Subscription::$externalSubscriptionId
                         if ($subscription) {
                             \DBG::msg(__METHOD__ . ": trying to link to new subscription to the external subscription ID");
                             $referenceArry = explode('|', $payment->getTransactionReference());
                             if (isset($referenceArry[4]) && !empty($referenceArry[4])) {
                                 $subscription->setExternalSubscriptionId($referenceArry[4]);
                             }
                         }
                         $transactionData = $payment->getTransactionData();
                         if (!\FWValidator::isEmpty($transactionData) && isset($transactionData['contact']) && isset($transactionData['contact']['id'])) {
                             \DBG::msg(__METHOD__ . ": set externalPaymentCustomerIdProfileAttributeId of user to " . $transactionData['contact']['id']);
                             $objUser->setProfile(array(\Cx\Core\Setting\Controller\Setting::getValue('externalPaymentCustomerIdProfileAttributeId', 'MultiSite') => array(0 => $transactionData['contact']['id'])), true);
                             if (!$objUser->store()) {
                                 \DBG::msg('Order::createOrder() Updating user failed: ' . $objUser->getErrorMsg());
                             }
                         }
                         $invoice->addPayment($payment);
                         $payment->setInvoice($invoice);
                         \Env::get('em')->persist($invoice);
                         \Env::get('em')->persist($payment);
                         break;
                     }
                 }
             }
         }
         \Env::get('em')->persist($order);
         \Env::get('em')->flush();
         return $order;
     } catch (\Exception $e) {
         throw new OrderRepositoryException($e->getMessage());
     }
 }
Example #24
0
 public function setupMasterAccount()
 {
     $post = $this->_app->request->post();
     // Get the alert message stream
     $ms = $this->_app->alerts;
     // Check the honeypot. 'spiderbro' is not a real field, it is hidden on the main page and must be submitted with its default value for this to be processed.
     if (!$post['spiderbro'] || $post['spiderbro'] != "http://") {
         error_log("Possible spam received:" . print_r($this->_app->request->post(), true));
         $ms->addMessage("danger", "Aww hellllls no!");
         $this->_app->halt(500);
         // Don't let on about why the request failed ;-)
     }
     // Do not allow registering a master account if one has already been created
     if (UserLoader::exists($this->_app->config('user_id_master'))) {
         $ms->addMessageTranslated("danger", "MASTER_ACCOUNT_EXISTS");
         $this->_app->halt(403);
     }
     // Check the configuration token
     if ($post['root_account_config_token'] != $this->_app->site->root_account_config_token) {
         $ms->addMessageTranslated("danger", "CONFIG_TOKEN_MISMATCH");
         $this->_app->halt(403);
     }
     // Load the request schema
     $requestSchema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/register.json");
     // Set up Fortress to process the request
     $rf = new \Fortress\HTTPRequestFortress($ms, $requestSchema, $post);
     // Sanitize data
     $rf->sanitize();
     // Validate, and halt on validation errors.
     $error = !$rf->validate(true);
     // Get the filtered data
     $data = $rf->data();
     // Remove configuration token, password confirmation from object data
     $rf->removeFields(['root_account_config_token', 'passwordc']);
     // Perform desired data transformations.  Is this a feature we could add to Fortress?
     $data['user_name'] = strtolower(trim($data['user_name']));
     $data['display_name'] = trim($data['display_name']);
     $data['email'] = strtolower(trim($data['email']));
     $data['active'] = 1;
     $data['locale'] = $this->_app->site->default_locale;
     // Halt on any validation errors
     if ($error) {
         $this->_app->halt(400);
     }
     // Get default primary group (is_default = GROUP_DEFAULT_PRIMARY)
     $primaryGroup = GroupLoader::fetch(GROUP_DEFAULT_PRIMARY, "is_default");
     $data['primary_group_id'] = $primaryGroup->id;
     // Set default title for new users
     $data['title'] = $primaryGroup->new_user_title;
     // Hash password
     $data['password'] = Authentication::hashPassword($data['password']);
     // Create the user
     $user = new User($data, $this->_app->config('user_id_master'));
     // Add user to default groups, including default primary group
     $defaultGroups = GroupLoader::fetchAll(GROUP_DEFAULT, "is_default");
     $user->addGroup($primaryGroup->id);
     foreach ($defaultGroups as $group_id => $group) {
         $user->addGroup($group_id);
     }
     // Store new user to database, forcing it to insert the new user
     $user->store(true);
     // No activation required
     $ms->addMessageTranslated("success", "ACCOUNT_REGISTRATION_COMPLETE_TYPE1");
     // Update install status
     $this->_app->site->install_status = "new";
     $this->_app->site->root_account_config_token = "";
     $this->_app->site->store();
 }
Example #25
0
 public static function create($username, $password, $type = SESSION_REGULAR, $algo = 'sha512')
 {
     $username = trim($username);
     if (User::getByName($username)) {
         return false;
     }
     $o = new User();
     $o->name = $username;
     $o->type = $type;
     $o->time_created = sql_datetime(now());
     $o->id = $o->store();
     if (!$o->id) {
         return false;
     }
     $session = SessionHandler::getInstance();
     $o->password = Password::encrypt($o->id, $session->getEncryptKey(), $password, $algo);
     $o->store();
     // write again with password encoded using the user id
     dp($session->getUsername() . ' created user ' . $username . ' (' . $o->id . ') of type ' . $type);
     return $o->id;
 }
Example #26
0
 function beforeFilter()
 {
     $this->__configureAuth();
     App::import('Model', 'User');
     User::store($this->Auth->user());
 }
Example #27
0
$vote = new Vote('posts', $id, $current_user->user_id);
$vote->link = $id;
if ($vote->exists()) {
    error(_('ya se votó antes con el mismo usuario o IP'));
}
$votes_freq = intval($db->get_var("select count(*) from votes where vote_type='posts' and vote_user_id={$current_user->user_id} and vote_date > subtime(now(), '0:0:30') and vote_ip_int = " . $globals['user_ip_int']));
$freq = 6;
if ($votes_freq > $freq) {
    if ($current_user->user_id > 0 && $current_user->user_karma > 4) {
        // Crazy votes attack, decrease karma
        // she does not deserve it :-)
        $user = new User();
        $user->id = $current_user->user_id;
        $user->read();
        $user->karma = $user->karma - 0.1;
        $user->store();
        error(_('¡tranquilo cowboy!, tu karma ha bajado: ') . $user->karma);
    } else {
        error(_('¡tranquilo cowboy!'));
    }
}
$vote->value = $value * $current_user->user_karma;
$post = Post::from_db($id);
if (!$post) {
    error(_('nota no existente'));
}
if ($post->author == $current_user->user_id) {
    error(_('no puedes votar a tus comentarios'));
}
if ($post->date < time() - $globals['time_enabled_votes']) {
    error(_('votos cerrados'));
Example #28
0
 /**
  * Returns an array with all placeholders and their values to be
  * replaced in any shop mailtemplate for the given order ID.
  *
  * You only have to set the 'substitution' index value of your MailTemplate
  * array to the array returned.
  * Customer data is not included here.  See {@see Customer::getSubstitutionArray()}.
  * Note that this method is now mostly independent of the current session.
  * The language of the mail template is determined by the browser
  * language range stored with the order.
  * @access  private
  * @static
  * @param   integer $order_id     The order ID
  * @param   boolean $create_accounts  If true, creates User accounts
  *                                    and Coupon codes.  Defaults to true
  * @return  array                 The array with placeholders as keys
  *                                and values from the order on success,
  *                                false otherwise
  */
 static function getSubstitutionArray($order_id, $create_accounts = true)
 {
     global $_ARRAYLANG;
     /*
                 $_ARRAYLANG['TXT_SHOP_URI_FOR_DOWNLOAD'].":\r\n".
                 'http://'.$_SERVER['SERVER_NAME'].
                 "/index.php?section=download\r\n";
     */
     $objOrder = Order::getById($order_id);
     if (!$objOrder) {
         // Order not found
         return false;
     }
     $lang_id = $objOrder->lang_id();
     if (!intval($lang_id)) {
         $lang_id = \FWLanguage::getLangIdByIso639_1($lang_id);
     }
     $status = $objOrder->status();
     $customer_id = $objOrder->customer_id();
     $customer = Customer::getById($customer_id);
     $payment_id = $objOrder->payment_id();
     $shipment_id = $objOrder->shipment_id();
     $arrSubstitution = array('CUSTOMER_COUNTRY_ID' => $objOrder->billing_country_id(), 'LANG_ID' => $lang_id, 'NOW' => date(ASCMS_DATE_FORMAT_DATETIME), 'TODAY' => date(ASCMS_DATE_FORMAT_DATE), 'ORDER_ID' => $order_id, 'ORDER_ID_CUSTOM' => ShopLibrary::getCustomOrderId($order_id), 'ORDER_DATE' => date(ASCMS_DATE_FORMAT_DATE, strtotime($objOrder->date_time())), 'ORDER_TIME' => date(ASCMS_DATE_FORMAT_TIME, strtotime($objOrder->date_time())), 'ORDER_STATUS_ID' => $status, 'ORDER_STATUS' => $_ARRAYLANG['TXT_SHOP_ORDER_STATUS_' . $status], 'MODIFIED' => date(ASCMS_DATE_FORMAT_DATETIME, strtotime($objOrder->modified_on())), 'REMARKS' => $objOrder->note(), 'ORDER_SUM' => sprintf('% 9.2f', $objOrder->sum()), 'CURRENCY' => Currency::getCodeById($objOrder->currency_id()));
     $arrSubstitution += $customer->getSubstitutionArray();
     if ($shipment_id) {
         $arrSubstitution += array('SHIPMENT' => array(0 => array('SHIPMENT_NAME' => sprintf('%-40s', Shipment::getShipperName($shipment_id)), 'SHIPMENT_PRICE' => sprintf('% 9.2f', $objOrder->shipment_amount()))), 'SHIPPING_ADDRESS' => array(0 => array('SHIPPING_COMPANY' => $objOrder->company(), 'SHIPPING_TITLE' => $_ARRAYLANG['TXT_SHOP_' . strtoupper($objOrder->gender())], 'SHIPPING_FIRSTNAME' => $objOrder->firstname(), 'SHIPPING_LASTNAME' => $objOrder->lastname(), 'SHIPPING_ADDRESS' => $objOrder->address(), 'SHIPPING_ZIP' => $objOrder->zip(), 'SHIPPING_CITY' => $objOrder->city(), 'SHIPPING_COUNTRY_ID' => $objOrder->country_id(), 'SHIPPING_COUNTRY' => \Cx\Core\Country\Controller\Country::getNameById($objOrder->country_id()), 'SHIPPING_PHONE' => $objOrder->phone())));
     }
     if ($payment_id) {
         $arrSubstitution += array('PAYMENT' => array(0 => array('PAYMENT_NAME' => sprintf('%-40s', Payment::getNameById($payment_id)), 'PAYMENT_PRICE' => sprintf('% 9.2f', $objOrder->payment_amount()))));
     }
     $arrItems = $objOrder->getItems();
     if (!$arrItems) {
         \Message::warning($_ARRAYLANG['TXT_SHOP_ORDER_WARNING_NO_ITEM']);
     }
     // Deduct Coupon discounts, either from each Product price, or
     // from the items total.  Mind that the Coupon has already been
     // stored with the Order, but not redeemed yet.  This is done
     // in this method, but only if $create_accounts is true.
     $coupon_code = NULL;
     $coupon_amount = 0;
     $objCoupon = Coupon::getByOrderId($order_id);
     if ($objCoupon) {
         $coupon_code = $objCoupon->code();
     }
     $orderItemCount = 0;
     $total_item_price = 0;
     // Suppress Coupon messages (see Coupon::available())
     \Message::save();
     foreach ($arrItems as $item) {
         $product_id = $item['product_id'];
         $objProduct = Product::getById($product_id);
         if (!$objProduct) {
             //die("Product ID $product_id not found");
             continue;
         }
         //DBG::log("Orders::getSubstitutionArray(): Item: Product ID $product_id");
         $product_name = substr($item['name'], 0, 40);
         $item_price = $item['price'];
         $quantity = $item['quantity'];
         // TODO: Add individual VAT rates for Products
         //            $orderItemVatPercent = $objResultItem->fields['vat_percent'];
         // Decrease the Product stock count,
         // applies to "real", shipped goods only
         $objProduct->decreaseStock($quantity);
         $product_code = $objProduct->code();
         // Pick the order items attributes
         $str_options = '';
         // Any attributes?
         if ($item['attributes']) {
             $str_options = '  ';
             // '[';
             $attribute_name_previous = '';
             foreach ($item['attributes'] as $attribute_name => $arrAttribute) {
                 //DBG::log("Attribute /$attribute_name/ => ".var_export($arrAttribute, true));
                 // NOTE: The option price is optional and may be left out
                 foreach ($arrAttribute as $arrOption) {
                     $option_name = $arrOption['name'];
                     $option_price = $arrOption['price'];
                     $item_price += $option_price;
                     // Recognize the names of uploaded files,
                     // verify their presence and use the original name
                     $option_name_stripped = ShopLibrary::stripUniqidFromFilename($option_name);
                     $path = Order::UPLOAD_FOLDER . $option_name;
                     if ($option_name != $option_name_stripped && \File::exists($path)) {
                         $option_name = $option_name_stripped;
                     }
                     if ($attribute_name != $attribute_name_previous) {
                         if ($attribute_name_previous) {
                             $str_options .= '; ';
                         }
                         $str_options .= $attribute_name . ': ' . $option_name;
                         $attribute_name_previous = $attribute_name;
                     } else {
                         $str_options .= ', ' . $option_name;
                     }
                     // TODO: Add proper formatting with sprintf() and language entries
                     if ($option_price != 0) {
                         $str_options .= ' ' . Currency::formatPrice($option_price) . ' ' . Currency::getActiveCurrencyCode();
                     }
                 }
             }
             //                $str_options .= ']';
         }
         // Product details
         $arrProduct = array('PRODUCT_ID' => $product_id, 'PRODUCT_CODE' => $product_code, 'PRODUCT_QUANTITY' => $quantity, 'PRODUCT_TITLE' => $product_name, 'PRODUCT_OPTIONS' => $str_options, 'PRODUCT_ITEM_PRICE' => sprintf('% 9.2f', $item_price), 'PRODUCT_TOTAL_PRICE' => sprintf('% 9.2f', $item_price * $quantity));
         //DBG::log("Orders::getSubstitutionArray($order_id, $create_accounts): Adding article: ".var_export($arrProduct, true));
         $orderItemCount += $quantity;
         $total_item_price += $item_price * $quantity;
         if ($create_accounts) {
             // Add an account for every single instance of every Product
             for ($instance = 1; $instance <= $quantity; ++$instance) {
                 $validity = 0;
                 // Default to unlimited validity
                 // In case there are protected downloads in the cart,
                 // collect the group IDs
                 $arrUsergroupId = array();
                 if ($objProduct->distribution() == 'download') {
                     $usergroupIds = $objProduct->usergroup_ids();
                     if ($usergroupIds != '') {
                         $arrUsergroupId = explode(',', $usergroupIds);
                         $validity = $objProduct->weight();
                     }
                 }
                 // create an account that belongs to all collected
                 // user groups, if any.
                 if (count($arrUsergroupId) > 0) {
                     // The login names are created separately for
                     // each product instance
                     $username = self::usernamePrefix . "_{$order_id}_{$product_id}_{$instance}";
                     $userEmail = $username . '-' . $arrSubstitution['CUSTOMER_EMAIL'];
                     $userpass = \User::make_password();
                     $objUser = new \User();
                     $objUser->setUsername($username);
                     $objUser->setPassword($userpass);
                     $objUser->setEmail($userEmail);
                     $objUser->setAdminStatus(false);
                     $objUser->setActiveStatus(true);
                     $objUser->setGroups($arrUsergroupId);
                     $objUser->setValidityTimePeriod($validity);
                     $objUser->setFrontendLanguage(FRONTEND_LANG_ID);
                     $objUser->setBackendLanguage(FRONTEND_LANG_ID);
                     $objUser->setProfile(array('firstname' => array(0 => $arrSubstitution['CUSTOMER_FIRSTNAME']), 'lastname' => array(0 => $arrSubstitution['CUSTOMER_LASTNAME']), 'company' => array(0 => $arrSubstitution['CUSTOMER_COMPANY']), 'address' => array(0 => $arrSubstitution['CUSTOMER_ADDRESS']), 'zip' => array(0 => $arrSubstitution['CUSTOMER_ZIP']), 'city' => array(0 => $arrSubstitution['CUSTOMER_CITY']), 'country' => array(0 => $arrSubstitution['CUSTOMER_COUNTRY_ID']), 'phone_office' => array(0 => $arrSubstitution['CUSTOMER_PHONE']), 'phone_fax' => array(0 => $arrSubstitution['CUSTOMER_FAX'])));
                     if (!$objUser->store()) {
                         \Message::error(implode('<br />', $objUser->getErrorMsg()));
                         return false;
                     }
                     if (empty($arrProduct['USER_DATA'])) {
                         $arrProduct['USER_DATA'] = array();
                     }
                     $arrProduct['USER_DATA'][] = array('USER_NAME' => $username, 'USER_PASS' => $userpass);
                 }
                 //echo("Instance $instance");
                 if ($objProduct->distribution() == 'coupon') {
                     if (empty($arrProduct['COUPON_DATA'])) {
                         $arrProduct['COUPON_DATA'] = array();
                     }
                     //DBG::log("Orders::getSubstitutionArray(): Getting code");
                     $code = Coupon::getNewCode();
                     //DBG::log("Orders::getSubstitutionArray(): Got code: $code, calling Coupon::addCode($code, 0, 0, 0, $item_price)");
                     Coupon::storeCode($code, 0, 0, 0, $item_price, 0, 0, 10000000000.0, true);
                     $arrProduct['COUPON_DATA'][] = array('COUPON_CODE' => $code);
                 }
             }
             // Redeem the *product* Coupon, if possible for the Product
             if ($coupon_code) {
                 $objCoupon = Coupon::available($coupon_code, $item_price * $quantity, $customer_id, $product_id, $payment_id);
                 if ($objCoupon) {
                     $coupon_code = NULL;
                     $coupon_amount = $objCoupon->getDiscountAmount($item_price, $customer_id);
                     if ($create_accounts) {
                         $objCoupon->redeem($order_id, $customer_id, $item_price * $quantity);
                     }
                 }
                 //\DBG::log("Orders::getSubstitutionArray(): Got Product Coupon $coupon_code");
             }
         }
         if (empty($arrSubstitution['ORDER_ITEM'])) {
             $arrSubstitution['ORDER_ITEM'] = array();
         }
         $arrSubstitution['ORDER_ITEM'][] = $arrProduct;
     }
     $arrSubstitution['ORDER_ITEM_SUM'] = sprintf('% 9.2f', $total_item_price);
     $arrSubstitution['ORDER_ITEM_COUNT'] = sprintf('% 4u', $orderItemCount);
     // Redeem the *global* Coupon, if possible for the Order
     if ($coupon_code) {
         $objCoupon = Coupon::available($coupon_code, $total_item_price, $customer_id, null, $payment_id);
         if ($objCoupon) {
             $coupon_amount = $objCoupon->getDiscountAmount($total_item_price, $customer_id);
             if ($create_accounts) {
                 $objCoupon->redeem($order_id, $customer_id, $total_item_price);
             }
         }
     }
     \Message::restore();
     // Fill in the Coupon block with proper discount and amount
     if ($objCoupon) {
         $coupon_code = $objCoupon->code();
         //\DBG::log("Orders::getSubstitutionArray(): Coupon $coupon_code, amount $coupon_amount");
     }
     if ($coupon_amount) {
         //\DBG::log("Orders::getSubstitutionArray(): Got Order Coupon $coupon_code");
         $arrSubstitution['DISCOUNT_COUPON'][] = array('DISCOUNT_COUPON_CODE' => sprintf('%-40s', $coupon_code), 'DISCOUNT_COUPON_AMOUNT' => sprintf('% 9.2f', -$coupon_amount));
     } else {
         //\DBG::log("Orders::getSubstitutionArray(): No Coupon for Order ID $order_id");
     }
     Products::deactivate_soldout();
     if (Vat::isEnabled()) {
         //DBG::log("Orders::getSubstitutionArray(): VAT amount: ".$objOrder->vat_amount());
         $arrSubstitution['VAT'] = array(0 => array('VAT_TEXT' => sprintf('%-40s', Vat::isIncluded() ? $_ARRAYLANG['TXT_SHOP_VAT_PREFIX_INCL'] : $_ARRAYLANG['TXT_SHOP_VAT_PREFIX_EXCL']), 'VAT_PRICE' => $objOrder->vat_amount()));
     }
     return $arrSubstitution;
 }
Example #29
0
function insert_comment()
{
    global $link, $db, $current_user, $globals;
    $error = '';
    require_once mnminclude . 'ban.php';
    if (check_ban_proxy()) {
        return _('dirección IP no permitida');
    }
    // Check if is a POST of a comment
    if ($link->votes > 0 && $link->date > $globals['now'] - $globals['time_enabled_comments'] && $link->comments < $globals['max_comments'] && intval($_POST['link_id']) == $link->id && $current_user->authenticated && intval($_POST['user_id']) == $current_user->user_id && ($current_user->user_karma > $globals['min_karma_for_comments'] || $current_user->user_id == $link->author) && intval($_POST['randkey']) > 0 && mb_strlen(trim($_POST['comment_content'])) > 2) {
        require_once mnminclude . 'comment.php';
        $comment = new Comment();
        $comment->link = $link->id;
        $comment->randkey = intval($_POST['randkey']);
        $comment->author = intval($_POST['user_id']);
        $comment->karma = round($current_user->user_karma);
        $comment->content = clean_text($_POST['comment_content'], 0, false, 10000);
        // Check if is an admin comment
        if ($current_user->user_level == 'god' && $_POST['type'] == 'admin') {
            $comment->karma = 20;
            $comment->type = 'admin';
        }
        if (mb_strlen($comment->content) > 0 && preg_match('/[a-zA-Z:-]/', $_POST['comment_content'])) {
            // Check there are at least a valid char
            $already_stored = intval($db->get_var("select count(*) from comments where comment_link_id = {$comment->link} and comment_user_id = {$comment->author} and comment_randkey = {$comment->randkey}"));
            // Check the comment wasn't already stored
            if (!$already_stored) {
                if ($comment->type != 'admin') {
                    // Lower karma to comments' spammers
                    $comment_count = (int) $db->get_var("select count(*) from comments where comment_user_id = {$current_user->user_id} and comment_date > date_sub(now(), interval 3 minute)");
                    // Check the text is not the same
                    $same_count = $comment->same_text_count() + $comment->same_links_count();
                } else {
                    $comment_count = $same_count = 0;
                }
                if ($comment_count > 2 || $same_count > 2) {
                    require_once mnminclude . 'user.php';
                    $reduction = 0;
                    if ($comment_count > 3) {
                        $reduction += ($comment_count - 3) * 0.1;
                    }
                    if ($same_count > 1) {
                        $reduction += $same_count * 0.25;
                    }
                    if ($reduction > 0) {
                        $user = new User();
                        $user->id = $current_user->user_id;
                        $user->read();
                        $user->karma = $user->karma - $reduction;
                        syslog(LOG_NOTICE, "Meneame: story decreasing {$reduction} of karma to {$current_user->user_login} (now {$user->karma})");
                        $user->store();
                        $error .= ' ' . 'penalización de karma por texto repetido o abuso de enlaces';
                    }
                }
                $comment->store();
                $comment->insert_vote();
                $link->update_comments();
                // Re read link data
                $link->read();
            } else {
                $error .= ' ' . 'duplicado';
            }
        } else {
            $error .= ' ' . 'caracteres no válidos';
        }
        // We don't redirect, Firefox show cache data instead of the new data since we send lastmodification time.
        //header('Location: '.$link->get_permalink());
        //die;
    } else {
        $error .= ' ' . 'texto muy breve, karma bajo o usuario incorrecto';
    }
    return $error;
}
Example #30
0
 /** 
  * Processes the request to create a new user (from the admin controls).
  * 
  * Processes the request from the user creation form, checking that:
  * 1. The username and email are not already in use;
  * 2. The logged-in user has the necessary permissions to update the posted field(s);
  * 3. The submitted data is valid.
  * This route requires authentication.
  * Request type: POST
  * @see formUserCreate
  */
 public function createUser()
 {
     $post = $this->_app->request->post();
     // Load the request schema
     $requestSchema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/user-create.json");
     // Get the alert message stream
     $ms = $this->_app->alerts;
     // Access-controlled resource
     if (!$this->_app->user->checkAccess('create_account')) {
         $ms->addMessageTranslated("danger", "ACCESS_DENIED");
         $this->_app->halt(403);
     }
     // Set up Fortress to process the request
     $rf = new \Fortress\HTTPRequestFortress($ms, $requestSchema, $post);
     // Sanitize data
     $rf->sanitize();
     // Validate, and halt on validation errors.
     $error = !$rf->validate(true);
     // Get the filtered data
     $data = $rf->data();
     // Remove csrf_token, password confirmation from object data
     $rf->removeFields(['csrf_token, passwordc']);
     // Perform desired data transformations on required fields.  Is this a feature we could add to Fortress?
     $data['user_name'] = strtolower(trim($data['user_name']));
     $data['display_name'] = trim($data['display_name']);
     $data['email'] = strtolower(trim($data['email']));
     $data['active'] = 1;
     // Check if username or email already exists
     if (UserLoader::exists($data['user_name'], 'user_name')) {
         $ms->addMessageTranslated("danger", "ACCOUNT_USERNAME_IN_USE", $data);
         $error = true;
     }
     if (UserLoader::exists($data['email'], 'email')) {
         $ms->addMessageTranslated("danger", "ACCOUNT_EMAIL_IN_USE", $data);
         $error = true;
     }
     // Halt on any validation errors
     if ($error) {
         $this->_app->halt(400);
     }
     // Get default primary group (is_default = GROUP_DEFAULT_PRIMARY)
     $primaryGroup = GroupLoader::fetch(GROUP_DEFAULT_PRIMARY, "is_default");
     // Set default values if not specified or not authorized
     if (!isset($data['locale']) || !$this->_app->user->checkAccess("update_account_setting", ["property" => "locale"])) {
         $data['locale'] = $this->_app->site->default_locale;
     }
     if (!isset($data['title']) || !$this->_app->user->checkAccess("update_account_setting", ["property" => "title"])) {
         // Set default title for new users
         $data['title'] = $primaryGroup->new_user_title;
     }
     if (!isset($data['primary_group_id']) || !$this->_app->user->checkAccess("update_account_setting", ["property" => "primary_group_id"])) {
         $data['primary_group_id'] = $primaryGroup->id;
     }
     // Set groups to default groups if not specified or not authorized to set groups
     if (!isset($data['groups']) || !$this->_app->user->checkAccess("update_account_setting", ["property" => "groups"])) {
         $default_groups = GroupLoader::fetchAll(GROUP_DEFAULT, "is_default");
         $data['groups'] = [];
         foreach ($default_groups as $group_id => $group) {
             $data['groups'][$group_id] = "1";
         }
     }
     // Hash password
     $data['password'] = Authentication::hashPassword($data['password']);
     // Create the user
     $user = new User($data);
     // Add user to groups, including selected primary group
     $user->addGroup($data['primary_group_id']);
     foreach ($data['groups'] as $group_id => $is_member) {
         if ($is_member == "1") {
             $user->addGroup($group_id);
         }
     }
     // Store new user to database
     $user->store();
     // Success message
     $ms->addMessageTranslated("success", "ACCOUNT_CREATION_COMPLETE", $data);
 }