public function loginByFacebook() {
		if (!Yum::module()->loginType & UserModule::LOGIN_BY_FACEBOOK)
			throw new Exception('actionFacebook was called, but is not activated in application configuration');

		Yii::app()->user->logout();
		Yii::import('application.modules.user.vendors.facebook.*');
		$facebook = new Facebook(Yum::module()->facebookConfig);
		$fb_uid = $facebook->getUser();
		if ($fb_uid) {
			$profile = YumProfile::model()->findByAttributes(array('facebook_id' => $fb_uid));
			$user = ($profile) ? YumUser::model()->findByPk($profile->user_id) : null;
			try {
				$fb_user = $facebook->api('/me');
				if (isset($fb_user['email']))
					$profile = YumProfile::model()->findByAttributes(array('email' => $fb_user['email']));
				else
					return false;
				if ($user === null && $profile === null) {
					// New account
					$user = new YumUser;
					$user->username = '******'.YumRegistrationForm::genRandomString(Yum::module()->usernameRequirements['maxLen'] - 3);
					$user->password = YumEncrypt::encrypt(YumUserChangePassword::createRandomPassword());
					$user->activationKey = YumEncrypt::encrypt(microtime().$user->password, $user->salt);
					$user->createtime = time();
					$user->superuser = 0;
					if ($user->save()) {
						$profile = new YumProfile;
						$profile->user_id = $user->id;
						$profile->facebook_id = $fb_user['id'];
						$profile->email = $fb_user['email'];
						$profile->save(false);
					}
				} else {
					//No superuser account can log in using Facebook
					$user = $profile->user;
					if ($user->superuser) {
						Yum::log('A superuser tried to login by facebook', 'error');
						return false;
					}
					//Current account and FB account blending
					$profile->facebook_id = $fb_uid;
					$profile->save(false);
					$user->username = '******'.YumRegistrationForm::genRandomString(Yum::module()->usernameRequirements['maxLen'] - 3);

					$user->superuser = 0;
					$user->save();
				}

				$identity = new YumUserIdentity($fb_uid, $user->id);
				$identity->authenticateFacebook(true);

				switch ($identity->errorCode) {
					case YumUserIdentity::ERROR_NONE:
						$duration = 3600*24*30; //30 days
						Yii::app()->user->login($identity, $duration);
						Yum::log('User ' . $user->username .' logged in via facebook');
						return $user;
						break;
					case YumUserIdentity::ERROR_STATUS_INACTIVE:
						$user->addError('status', Yum::t('Your account is not activated.'));
						break;
					case YumUserIdentity::ERROR_STATUS_BANNED:
						$user->addError('status', Yum::t('Your account is blocked.'));
						break;
					case YumUserIdentity::ERROR_PASSWORD_INVALID:
						Yum::log(Yum::t('Failed login attempt for {username} via facebook', array(
										'{username}' => $user->username)), 'error');
						$user->addError('status', Yum::t('Password incorrect.'));
						break;
				}
				return false;
			} catch (FacebookApiException $e) {
				/* FIXME: Workaround for avoiding the 'Error validating access token.'
				 * inmediatly after a user logs out. This is nasty. Any other
				 * approach to solve this issue is more than welcomed.
				 */

				Yum::log('Failed login attempt for ' . $user->username . ' via facebook', 'error');
				return false;
			}
		}
		else
			return false;
	}
 public function authenticate($without_password = false)
 {
     $user = YumUser::model()->find('username = :username', array(':username' => $this->username));
     // try to authenticate via email
     if (!$user && Yum::module()->loginType & 2 && Yum::hasModule('profile')) {
         if ($profile = YumProfile::model()->find('email = :email', array(':email' => $this->username))) {
             if ($profile->user) {
                 $user = $profile->user;
             }
         }
     }
     if (!$user) {
         return self::ERROR_STATUS_USER_DOES_NOT_EXIST;
     }
     if ($without_password) {
         $this->credentialsConfirmed($user);
     } else {
         if (!YumEncrypt::validate_password($this->password, $user->password, $user->salt)) {
             $this->errorCode = self::ERROR_PASSWORD_INVALID;
         } else {
             if ($user->status == YumUser::STATUS_INACTIVE) {
                 $this->errorCode = self::ERROR_STATUS_INACTIVE;
             } else {
                 if ($user->status == YumUser::STATUS_BANNED) {
                     $this->errorCode = self::ERROR_STATUS_BANNED;
                 } else {
                     if ($user->status == YumUser::STATUS_REMOVED) {
                         $this->errorCode = self::ERROR_STATUS_REMOVED;
                     } else {
                         $this->credentialsConfirmed($user);
                     }
                 }
             }
         }
     }
     return !$this->errorCode;
 }
 /**
  * @params boolean $activate Whether to generate activation key when user is
  * registering first time (false)
  * or when it is activating (true)
  * @params string $password password entered by user
  * @param array $params, optional, to allow passing values outside class in inherited classes
  * By default it uses password and microtime combination to generated activation key
  * When user is activating, activation key becomes micortime()
  * @return string
  */
 public function generateActivationKey($activate = false)
 {
     if ($activate) {
         $this->activationKey = $activate;
         $this->save(false, array('activationKey'));
     } else {
         $this->activationKey = YumEncrypt::encrypt(microtime() . $this->password, $this->salt);
     }
     if (!$this->isNewRecord) {
         $this->save(false, array('activationKey'));
     }
     return $this->activationKey;
 }
	public function actionUpdate() {
		$model = $this->loadUser();
		$passwordform = new YumUserChangePassword();

		if(isset($_POST['YumUser'])) {
			if(!isset($model->salt) || empty($model->salt))
				$model->salt = YumEncrypt::generateSalt();
			
			$model->attributes = $_POST['YumUser'];
			if(Yum::hasModule('role')) {
				Yii::import('application.modules.role.models.*');
				// Assign the roles and belonging Users to the model
				$model->roles = Relation::retrieveValues($_POST);
			}

			if(Yum::hasModule('profile')) {
				$profile = $model->profile;

				if(isset($_POST['YumProfile']) )
					$profile->attributes = $_POST['YumProfile'];
			}

			// Password change is requested ?
			if(isset($_POST['YumUserChangePassword'])
					&& $_POST['YumUserChangePassword']['password'] != '') {
				$passwordform->attributes = $_POST['YumUserChangePassword'];
				if($passwordform->validate())
					$model->setPassword($_POST['YumUserChangePassword']['password'], $model->salt);
			}

			if(!$passwordform->hasErrors() && $model->save()) {
				if(isset($profile)) 
					$profile->save();

				$this->redirect(array('//user/user/view', 'id' => $model->id));
			}
		}

		$this->render('update', array(
					'model'=>$model,
					'passwordform' =>$passwordform,
					'profile' => isset($profile) ? $profile : false,
					));
	}
 /**
  * Password recovery routine. The User will receive an email with an
  * activation link. If clicked, he will be prompted to enter his new
  * password.
  */
 public function actionRecovery($email = null, $key = null)
 {
     $form = new YumPasswordRecoveryForm();
     if ($email != null && $key != null) {
         if ($profile = YumProfile::model()->find('email = :email', array('email' => $email))) {
             $user = $profile->user;
             if ($user->activationKey == $key) {
                 $passwordform = new YumUserChangePassword();
                 if (isset($_POST['YumUserChangePassword'])) {
                     $passwordform->attributes = $_POST['YumUserChangePassword'];
                     if ($passwordform->validate()) {
                         $user->password = YumEncrypt::encrypt($passwordform->password, $user->salt);
                         $user->activationKey = YumEncrypt::encrypt(microtime() . $passwordform->password, $user->salt);
                         $user->save();
                         Yum::setFlash('Your new password has been saved.');
                         $this->redirect(Yum::module()->loginUrl);
                     }
                 }
                 $this->render(Yum::module('registration')->changePasswordView, array('form' => $passwordform));
                 Yii::app()->end();
             } else {
                 $form->addError('login_or_email', Yum::t('Invalid recovery key'));
                 Yum::log(Yum::t('Someone tried to recover a password, but entered a wrong recovery key. Email is {email}, associated user is {username} (id: {uid})', array('{email}' => $email, '{uid}' => $user->id, '{username}' => $user->username)));
             }
         }
     } else {
         if (isset($_POST['YumPasswordRecoveryForm'])) {
             $form->attributes = $_POST['YumPasswordRecoveryForm'];
             if ($form->validate()) {
                 Yum::setFlash('Instructions have been sent to you. Please check your email.');
                 if ($form->user instanceof YumUser) {
                     $form->user->generateActivationKey();
                     $recovery_url = $this->createAbsoluteUrl(Yum::module('registration')->recoveryUrl[0], array('key' => $form->user->activationKey, 'email' => $form->user->profile->email));
                     Yum::log(Yum::t('{username} successfully requested a new password in the password recovery form. A email with the password recovery url {recovery_url} has been sent to {email}', array('{email}' => $form->user->profile->email, '{recovery_url}' => $recovery_url, '{username}' => $form->user->username)));
                     $mail = array('from' => Yii::app()->params['adminEmail'], 'to' => $form->user->profile->email, 'subject' => 'You requested a new password', 'body' => strtr('You have requested a new password. Please use this URL to continue: {recovery_url}', array('{recovery_url}' => $recovery_url)));
                     $sent = YumMailer::send($mail);
                 } else {
                     Yum::log(Yum::t('A password has been requested, but no associated user was found in the database. Requested user/email is: {username}', array('{username}' => $form->login_or_email)));
                 }
                 $this->redirect(Yum::module()->loginUrl);
             }
         }
     }
     $this->render(Yum::module('registration')->recoverPasswordView, array('form' => $form));
 }
 /**
  * This function is used for generating the salt.
  * @return hash string.
  */
 public static function validate_password($password, $good_hash, $salt)
 {
     $enc_pwd = YumEncrypt::encrypt($password, $salt);
     return YumEncrypt::slow_equals($enc_pwd, $good_hash);
 }
 /**
  * Deletes a user by setting the status to 'deleted'
  */
 public function actionDelete($id = null)
 {
     if (!$id) {
         $id = Yii::app()->user->id;
     }
     $user = YumUser::model()->findByPk($id);
     if (Yii::app()->user->isAdmin()) {
         //This is necesary for handling human stupidity.
         if ($user && $user->id == Yii::app()->user->id) {
             Yum::setFlash('You can not delete your own admin account');
             $this->redirect(array('//user/user/admin'));
         }
         if ($user->delete()) {
             Yum::setFlash('The User has been deleted');
             if (!Yii::app()->request->isAjaxRequest) {
                 $this->redirect('//user/user/admin');
             }
         }
     } else {
         if (isset($_POST['confirmPassword'])) {
             if (YumEncrypt::validate_password($_POST['confirmPassword'], $user->password, $user->salt)) {
                 if ($user->delete()) {
                     $this->actionLogout();
                 } else {
                     Yum::setFlash('Error while deleting Account. Account was not deleted');
                 }
             } else {
                 Yum::setFlash('Wrong password confirmation! Account was not deleted');
             }
             $this->redirect(Yum::module()->deleteUrl);
         }
     }
     $this->render('confirmDeletion', array('model' => $user));
 }
	public function actionInstall()
	{
		if ($this->module->debug === true) {
			if (Yii::app()->request->isPostRequest) {
				// A associative array containing the tables to be created.
				$createdTables = array();
				if ($db = Yii::app()->db) {
					$sql = 'set FOREIGN_KEY_CHECKS = 0;';
					$db->createCommand($sql)->execute();

					$transaction = $db->beginTransaction();

					$tables = array(
						'userTable',
						'privacySettingTable',
						'profileFieldTable',
						'profileFieldsGroupTable',
						'profileTable',
						'profileCommentTable',
						'profileVisitTable',
						'membershipTable',
						'paymentTable',
						'messageTable',
						'roleTable',
						'userRoleTable',
						'permissionTable',
						'friendshipTable',
						'actionTable',
						'usergroupTable',
						'usergroupMessageTable',
						'translationTable');

					/*
					 * Hey, we're dropping your tables. Did anyone said 'backups'?
					 */
					foreach ($tables as $table) {
						if (isset($_POST[$table])) {
							${$table} = $_POST[$table];

							// Clean up existing Installation table-by-table
							$db->createCommand(sprintf('DROP TABLE IF EXISTS %s',
							                           ${$table}))->execute();

						}
					}

					// Create User Table
					$sql = "CREATE TABLE IF NOT EXISTS `" . $userTable . "` (
						`id` int unsigned NOT NULL auto_increment,
						`username` varchar(20) NOT NULL,
						`password` varchar(128) NOT NULL,
						`salt` varchar(128) NOT NULL,
						`activationKey` varchar(128) NOT NULL default '',
						`createtime` int(10) NOT NULL default '0',
						`lastvisit` int(10) NOT NULL default '0',
						`lastaction` int(10) NOT NULL default '0',
						`lastpasswordchange` int(10) NOT NULL default '0',
						`superuser` int(1) NOT NULL default '0',
						`status` int(1) NOT NULL default '0',
						`avatar` varchar(255) default NULL,
						`notifyType` enum('None', 'Digest', 'Instant', 'Threshold') default 'Instant',
						PRIMARY KEY  (`id`),
						UNIQUE KEY `username` (`username`),
						KEY `status` (`status`),
						KEY `superuser` (`superuser`)
							) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;";

					$db->createCommand($sql)->execute();
					$createdTables['user']['userTable'] = $userTable;

					// Create messages translation table
					$sql = "CREATE TABLE IF NOT EXISTS `{$translationTable}` (
						`message` varbinary(255) NOT NULL,
						`translation` varchar(255) NOT NULL,
						`language` varchar(5) NOT NULL,
						`category` varchar(255) NOT NULL,
						PRIMARY KEY (`message`,`language`,`category`)
							) ENGINE=InnoDB DEFAULT CHARSET=utf8;";

					$db->createCommand($sql)->execute();
					$createdTables['user']['translationTable'] = $translationTable;

					// Insert the translation strings that come with yum
					$sql = file_get_contents(Yii::getPathOfAlias(
								'application.modules.user.docs') . '/yum_translation.sql');

					$db->createCommand($sql)->execute();

					// Install Usergroups submodule
					if (isset($_POST['installUsergroup'])) {
						$sql = "CREATE TABLE IF NOT EXISTS `" . $usergroupTable . "` (
							`id` int(11) NOT NULL AUTO_INCREMENT,
							`owner_id` int(11) NOT NULL,
							`participants` text NULL,
							`title` varchar(255) NOT NULL,
							`description` text NOT NULL,
							PRIMARY KEY (`id`)
								) ENGINE=InnoDB DEFAULT CHARSET=utf8;";

						$db->createCommand($sql)->execute();
						$createdTables['usergroup']['usergroupTable'] = $usergroupTable;

						$sql = "CREATE TABLE IF NOT EXISTS `" . $usergroupMessageTable . "` (
							`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
							`author_id` int(11) unsigned NOT NULL,
							`group_id` int(11) unsigned NOT NULL,
							`createtime` int(11) unsigned NOT NULL,
							`title` varchar(255) NOT NULL,
							`message` text NOT NULL,
							PRIMARY KEY (`id`)
								) ENGINE=InnoDB DEFAULT CHARSET=utf8;";

						$db->createCommand($sql)->execute();
						$createdTables['usergroup']['usergroupMessageTable'] = $usergroupMessageTable;
					}

					// Install Membership Management submodule
					if (isset($_POST['installMembership'])) {
						$sql = "CREATE TABLE IF NOT EXISTS `{$membershipTable}` (
							`id` int(11) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
							`membership_id` int(11) NOT NULL,
							`user_id` int(11) NOT NULL,
							`payment_id` int(11) NOT NULL,
							`order_date` int(11) NOT NULL,
							`end_date` int(11) DEFAULT NULL,
							`name` varchar(255) DEFAULT NULL,
							`street` varchar(255) DEFAULT NULL,
							`zipcode` varchar(255) DEFAULT NULL,
							`city` varchar(255) DEFAULT NULL,
							`payment_date` int(11) NULL,
							`subscribed` tinyint(1) NOT NULL 
								) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=10000;";

						$db->createCommand($sql)->execute();
						$createdTables['membership']['membershipTable'] = $membershipTable;

						$sql = " CREATE TABLE IF NOT EXISTS `{$paymentTable}` (
							`id` int(11) NOT NULL AUTO_INCREMENT,
							`title` varchar(255) NOT NULL,
							`text` text,
							PRIMARY KEY (`id`)
								) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; ";
						$db->createCommand($sql)->execute();
						$createdTables['membership']['paymentTable'] = $paymentTable;
					}

					// Install Friendship submodule
					if (isset($_POST['installFriendship'])) {
						$sql = "CREATE TABLE  `" . $friendshipTable . "` (
							`inviter_id` int(11) NOT NULL,
							`friend_id` int(11) NOT NULL,
							`status` int(11) NOT NULL,
							`acknowledgetime` int(11) DEFAULT NULL,
							`requesttime` int(11) DEFAULT NULL,
							`updatetime` int(11) DEFAULT NULL,
							`message` varchar(255) NOT NULL,
							PRIMARY KEY (`inviter_id`, `friend_id`)
						) ENGINE = INNODB;";

						$db->createCommand($sql)->execute();
						$createdTables['friendship']['friendshipTable'] = $friendshipTable;
					}

					// Install Profiles submodule
					if (isset($_POST['installProfiles'])) {
						$sql = "CREATE TABLE IF NOT EXISTS `" . $privacySettingTable . "` (
							`user_id` int unsigned NOT NULL,
							`message_new_friendship` tinyint(1) NOT NULL DEFAULT 1,
							`message_new_message` tinyint(1) NOT NULL DEFAULT 1,
							`message_new_profilecomment` tinyint(1) NOT NULL DEFAULT 1,
							`appear_in_search` tinyint(1) NOT NULL DEFAULT 1,
							`show_online_status` tinyint(1) NOT NULL DEFAULT 1,
							`log_profile_visits` tinyint(1) NOT NULL DEFAULT 1,
							`ignore_users` varchar(255),
							`public_profile_fields` bigint(15) unsigned,
							PRIMARY KEY (`user_id`)
						) ENGINE=InnoDB DEFAULT CHARSET=utf8;";

						$db->createCommand($sql)->execute();
						$createdTables['profile']['privacySettingTable'] = $privacySettingTable;

						// Create Profile Fields Table
						$sql = "CREATE TABLE IF NOT EXISTS `" . $profileFieldTable . "` (
							`id` int unsigned NOT NULL auto_increment,
							`varname` varchar(50) NOT NULL DEFAULT '',
							`title` varchar(255) NOT NULL DEFAULT '',
							`hint` text NOT NULL,
							`field_type` varchar(50) NOT NULL DEFAULT '',
							`field_size` int(3) NOT NULL default '0',
							`field_size_min` int(3) NOT NULL default '0',
							`required` int(1) NOT NULL default '0',
							`match` varchar(255) NOT NULL DEFAULT '',
							`range` varchar(255) NOT NULL DEFAULT '',
							`error_message` varchar(255) NOT NULL DEFAULT '',
							`other_validator` varchar(255) NOT NULL DEFAULT '',
							`default` varchar(255) NOT NULL DEFAULT '',
							`position` int(3) NOT NULL default '0',
							`visible` int(1) NOT NULL default '0',
							`related_field_name` varchar(255) NOT NULL DEFAULT '',
							PRIMARY KEY  (`id`),
							KEY `varname` (`varname`,`visible`)
						) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; ";

						$db->createCommand($sql)->execute();
						$createdTables['profile']['profileFieldTable'] = $profileFieldTable;

						// Create Profiles Table
						$sql = "CREATE TABLE IF NOT EXISTS `" . $profileTable . "` (
							`id` int unsigned NOT NULL auto_increment,
							`user_id` int unsigned NOT NULL,
							`timestamp` timestamp NOT NULL,
							`privacy` ENUM('protected', 'private', 'public') NOT NULL,
							`lastname` varchar(50) NOT NULL default '',
							`firstname` varchar(50) NOT NULL default '',
							`show_friends` tinyint(1) DEFAULT 1,
							`allow_comments` tinyint(1) DEFAULT 1,
							`email` varchar(255) NOT NULL default '',
							`street` varchar(255),
							`city` varchar(255),
							`about` text,
							PRIMARY KEY  (`id`)
						) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;";

						$db->createCommand($sql)->execute();
						$createdTables['profile']['profileTable'] = $profileTable;

						$sql = "CREATE TABLE IF NOT EXISTS `" . $profileCommentTable . "` (
							`id` int(11) NOT NULL AUTO_INCREMENT,
							`user_id` int(11) NOT NULL,
							`profile_id` int(11) NOT NULL,
							`comment` text NOT NULL,
							`createtime` int(11) NOT NULL,
							PRIMARY KEY (`id`)
						) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;";

						$db->createCommand($sql)->execute();
						$createdTables['profile']['profileCommentTable'] = $profileCommentTable;

						$sql = "CREATE TABLE IF NOT EXISTS `" . $profileVisitTable . "` (
							`visitor_id` int(11) NOT NULL,
							`visited_id` int(11) NOT NULL,
							`timestamp_first_visit` int(11) NOT NULL,
							`timestamp_last_visit` int(11) NOT NULL,
							`num_of_visits` int(11) NOT NULL,
							PRIMARY KEY (`visitor_id`,`visited_id`)
						) ENGINE=InnoDB;";

						$db->createCommand($sql)->execute();
						$createdTables['profile']['profileVisitTable'] = $profileVisitTable;
					}

					// Install Role Management submodule
					if (isset($_POST['installRole'])) {
						// Create Roles Table
						$sql = "CREATE TABLE IF NOT EXISTS `" . $roleTable . "` (
							`id` INT unsigned NOT NULL AUTO_INCREMENT ,
							`title` VARCHAR(255) NOT NULL ,
							`description` VARCHAR(255) NULL,
							`membership_priority` int(11) NULL DEFAULT NULL,
							`price` double COMMENT 'Price (when using membership module)',
							`duration` int COMMENT 'How long a membership is valid',
							PRIMARY KEY (`id`)
						) ENGINE = InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; ";

						$db->createCommand($sql)->execute();
						$createdTables['role']['roleTable'] = $roleTable;

						// Create User_has_role Table
						$sql = "CREATE TABLE IF NOT EXISTS `" . $userRoleTable . "` (
							`user_id` int unsigned NOT NULL,
							`role_id` int unsigned NOT NULL,
							PRIMARY KEY (`user_id`, `role_id`)
						) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;";

						$db->createCommand($sql)->execute();
						$createdTables['role']['userRoleTable'] = $userRoleTable;

						// Install permission support (at the end will it be a submodule?)
						if (isset($_POST['installPermission'])) {
							$sql = "CREATE TABLE IF NOT EXISTS `" . $actionTable . "` (
							`id` int(11) NOT NULL AUTO_INCREMENT,
							`title` varchar(255) NOT NULL,
							`comment` text,
							`subject` varchar(255) DEFAULT NULL,
							PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; ";

							$db->createCommand($sql)->execute();
							$createdTables['role']['actionTable'] = $actionTable;

							$sql = "CREATE TABLE IF NOT EXISTS `" . $permissionTable . "` (
							`principal_id` int(11) NOT NULL,
							`subordinate_id` int(11) NULL,
							`type` enum('user','role') NOT NULL,
							`action` int(11) NOT NULL,
							`template` tinyint(1) NOT NULL,
							`comment` text,
							PRIMARY KEY (`principal_id`,`subordinate_id`,`type`,`action`)
						) ENGINE=InnoDB DEFAULT CHARSET=utf8; ";

							$db->createCommand($sql)->execute();
							$createdTables['role']['permissionTable'] = $permissionTable;
						}
					}

					// Install Messages submodule
					if (isset($_POST['installMessages'])) {
						// Create Messages Table
						$sql = "CREATE TABLE IF NOT EXISTS `" . $messageTable . "` (
							`id` int unsigned NOT NULL auto_increment,
							`timestamp` int unsigned NOT NULL,
							`from_user_id` int unsigned NOT NULL,
							`to_user_id` int unsigned NOT NULL,
							`title` varchar(255) NOT NULL,
							`message` text,
							`message_read` tinyint(1) NOT NULL,
							`answered` tinyint(1),
							`draft` tinyint(1) default NULL,
							PRIMARY KEY  (`id`)
						) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;";

						$db->createCommand($sql)->execute();
						$createdTables['message']['messageTable'] = $messageTable;
					}

					// Generate demo data
					$salt1 = YumEncrypt::generateSalt();
					$salt2 = YumEncrypt::generateSalt();
					$sql = "INSERT INTO `" . $userTable
					   ."` (`id`, `username`, `password`, `salt`, `activationKey`, `createtime`, `lastvisit`, `superuser`, `status`) VALUES "
					   ."(1, 'admin', '" . YumEncrypt::encrypt('admin', $salt1) . "', '" . $salt1 . "', '', " . time() . ", 0, 1, 1),"
					   ."(2, 'demo', '" . YumEncrypt::encrypt('demo', $salt2) . "', '" . $salt2 . "', '', " . time() . ", 0, 0, 1)";
					$db->createCommand($sql)->execute();

					if (isset($_POST['installMembership'])) {
						$sql = "INSERT INTO `{$paymentTable}` (`title`) VALUES ('Prepayment'), ('Paypal')";

						$db->createCommand($sql)->execute();
					}

					if (isset($_POST['installRole']) && isset($_POST['installPermission'])) {
						$sql = "INSERT INTO `" . $actionTable . "` (`title`) VALUES "
							."('message_write'),"
							."('message_receive'),"
							."('user_create'),"
							."('user_update'),"
							."('user_remove'),"
							."('user_admin')";

						$db->createCommand($sql)->execute();

						$sql = "INSERT INTO `{$permissionTable}` (`principal_id`, `subordinate_id`, `type`, `action`, `template`, `comment`) VALUES "
							."(2, 0, 'role', 1, 0, 'Users can write messages'),"
							."(2, 0, 'role', 2, 0, 'Users can receive messages'),"
							."(2, 0, 'role', 3, 0, 'Users are able to view visits of his profile'),"
							."(1, 0, 'role', 4, 0, ''),"
							."(1, 0, 'role', 5, 0, ''),"
							."(1, 0, 'role', 6, 0, ''),"
							."(1, 0, 'role', 7, 0, '');";

						$db->createCommand($sql)->execute();

						$sql = "INSERT INTO `" . $roleTable . "` (`title`,`description`, `membership_priority`, `price`, `duration`) VALUES "
							."('UserManager', 'These users can manage Users', 0, 0, 0),"
							."('Demo', 'Users having the demo role', 0, 0, 0),"
							."('Business', 'Example Business account', 1, 9.99, 7),"
							."('Premium', 'Example Premium account', 2, 19.99, 28) ";
						$db->createCommand($sql)->execute();

						$sql = "INSERT INTO `" . $userRoleTable . "` (`user_id`, `role_id`) VALUES (2, 3)";

						$db->createCommand($sql)->execute();
					}

					if (isset($_POST['installProfiles'])) {
						$sql = "INSERT INTO `" . $privacySettingTable . "` (`user_id`) values (2)";
						$db->createCommand($sql)->execute();

						$sql = "INSERT INTO `" . $profileTable . "` (`id`, `user_id`, `lastname`, `firstname`, `email`) VALUES "
							."(1, 1, 'admin','admin','*****@*****.**'),"
							."(2, 2, 'demo','demo','*****@*****.**')";
						$db->createCommand($sql)->execute();

						$sql = "INSERT INTO `" . $profileFieldTable . "` "
							."(`varname`, `title`, `field_type`, `field_size`, `required`, `visible`, `other_validator`) VALUES "
							."('email', 'E-Mail', 'VARCHAR', 255, 1, 3, 'CEmailValidator'),"
							."('firstname', 'First name', 'VARCHAR', 255, 1, 3, ''),"
							."('lastname', 'Last name', 'VARCHAR', 255, 1, 3, ''),"
							."('street','Street', 'VARCHAR', 255, 0, 3, ''),"
							."('city','City', 'VARCHAR', 255, 0, 3, ''),"
							."('about', 'About', 'TEXT', 255, 0, 3, '')";
						$db->createCommand($sql)->execute();

					}

					// Do it
					$transaction->commit();

					// Victory
					$this->render('success', array('modules' => $createdTables));
				}
				else
				{
					throw new CException(Yum::t('Database connection is not working'));
				}
			}
			else {
				if(Yii::app()->db->getSchema()->getTable('user'))
					throw new CHttpException(403, Yum::t(
								'Yii-user-management is already installed. Please remove it manually to continue'));

				$this->render('start', array(
					'userTable' => 'user',
					'roleTable' => 'role',
					'privacySettingTable' => 'privacysetting',
					'translationTable' => 'translation',
					'membershipTable' => 'membership',
					'paymentTable' => 'payment',
					'messageTable' => 'message',
					'profileTable' => 'profile',
					'profileCommentTable' => 'profile_comment',
					'profileVisitTable' => 'profile_visit',
					'profileFieldTable' => 'profile_field',
					'userRoleTable' => 'user_role',
					'usergroupTable' => 'usergroup',
					'usergroupMessageTable' => 'user_group_message',
					'permissionTable' => 'permission',
					'friendshipTable' => 'friendship',
					'actionTable' => 'action',
				));
			}
		} else {
			throw new CException(Yum::t('User management module is not in Debug Mode'));
		}
	}