The followings are the available columns in table 'user':
Inheritance: extends YumActiveRecord
 public function actionprojectdetails()
 {
     if (!empty(Yii::app()->user->_data)) {
         $projectModel = new YumUserProject();
         // get project id
         $id = Yii::app()->request->getParam('project_id');
         // here define the userdocumentsprojects as relation
         $projectObj = $projectModel->with('projectresources')->findByPk($id);
         $projectArr = [];
         $projectArr['project'] = $projectObj;
         //get project tasks
         $projModel = new YumUserProject();
         $projectTasks = $projModel->findAll('parent_id=:parent_id', array('parent_id' => $id));
         if (!empty($projectTasks)) {
             $projectArr['task'] = $projectTasks;
         } else {
             $projectArr['task'] = [];
         }
         $allUsersModel = new YumUser();
         $allUsersObjs = $allUsersModel->findAll();
         $this->render('projectdetails', array('projectdetails' => $projectArr, 'allUsers' => $allUsersObjs));
     } else {
         $this->redirect(array('//user/auth/login'));
     }
 }
 public function actionCreate()
 {
     // if some data has been entered before or the user is already logged in,
     // take the already existing data and prefill the input form
     if ($model = Shop::getCustomer()) {
         $address = $model->address;
     } else {
         $model = new Customer();
     }
     if (isset($_POST['Customer'])) {
         $model->attributes = $_POST['Customer'];
         if (isset($_POST['Address'])) {
             $address = new Address();
             $address->attributes = $_POST['Address'];
             if ($address->save()) {
                 $model->address_id = $address->id;
             }
         }
         if (!Yii::app()->user->isGuest) {
             $model->user_id = Yii::app()->user->id;
         }
         $model->validate();
         if (Shop::module()->useWithYum && isset($_POST['register']) && ($_POST['register'] = true)) {
             if (isset($_POST['Customer']['password']) && isset($_POST['Customer']['passwordRepeat'])) {
                 if ($_POST['Customer']['password'] != $_POST['Customer']['passwordRepeat']) {
                     $model->addError('password', Shop::t('Passwords do not match'));
                 } else {
                     if ($_POST['Customer']['password'] == '') {
                         $model->addError('password', Shop::t('Password is empty'));
                     } else {
                         $user = new YumUser();
                         $profile = new YumProfile();
                         $profile->attributes = $_POST['Customer'];
                         $profile->attributes = $_POST['Address'];
                         if ($user->register(strtr($model->email, array('@' => '_', '.' => '_')), $_POST['Customer']['password'], $profile)) {
                             $user->status = YumUser::STATUS_ACTIVE;
                             $user->save(false, array('status'));
                             $model->user_id = $user->id;
                             Shop::setFlash(Shop::t('Successfully registered user'));
                         } else {
                             $model->addErrors($user->getErrors());
                             $model->addErrors($profile->getErrors());
                             Shop::setFlash(Shop::t('Error while registering user'));
                         }
                     }
                 }
             }
         }
         if (!$model->hasErrors()) {
             if ($model->save()) {
                 Yii::app()->user->setState('customer_id', $model->customer_id);
                 $this->redirect(array('//shop/order/create', 'customer' => $model->customer_id));
             }
         }
     }
     $this->render('create', array('customer' => $model, 'address' => isset($address) ? $address : new Address()));
 }
 public function listDocuments()
 {
     $model = new YumUserdocuments();
     $allDocuments = $model->findAll();
     Yii::import('user.models.*');
     $userModel = new YumUser();
     $allUsers = $userModel->findAll();
     if (!empty($allDocuments)) {
         $this->render('index', array('model' => $model, 'documents' => $allDocuments, 'allUsers' => $allUsers));
         return;
     } else {
         $this->render('index', array('model' => $model, 'documents' => $allDocuments, 'allUsers' => $allUsers));
     }
 }
 public function actionEditAvatar()
 {
     $model = YumUser::model()->findByPk(Yii::app()->user->id);
     if (isset($_POST['YumUser'])) {
         $model->attributes = $_POST['YumUser'];
         $model->setScenario('avatarUpload');
         if (Yum::module('avatar')->avatarMaxWidth != 0) {
             $model->setScenario('avatarSizeCheck');
         }
         $model->avatar = CUploadedFile::getInstanceByName('YumUser[avatar]');
         if ($model->validate()) {
             if ($model->avatar instanceof CUploadedFile) {
                 // Prepend the id of the user to avoid filename conflicts
                 $filename = Yum::module('avatar')->avatarPath . '/' . $model->id . '_' . $_FILES['YumUser']['name']['avatar'];
                 $model->avatar->saveAs($filename);
                 $model->avatar = $filename;
                 if ($model->save()) {
                     Yum::setFlash(Yum::t('The image was uploaded successfully'));
                     Yum::log(Yum::t('User {username} uploaded avatar image {filename}', array('{username}' => $model->username, '{filename}' => $model->avatar)));
                     $this->redirect(array('//profile/profile/view'));
                 }
             }
         }
     }
     $this->render('edit_avatar', array('model' => $model));
 }
	public function rules() 
	{
		$rules = parent::rules();

		/* FIXME: As soon as i grasp how i can dynamically add variables to a 
			 class in PHP, i will enable this code snippet for flexibility:

			 $profile = new YumProfile;
			 $profile_rules = $profile->rules();
			 foreach($profile_rules as $rule) 
			 if(isset($rule[0]) && is_string($rule[0]))
			 $this->${$rule[0]} = ''; 

			 $rules = array_merge($rules, $profile->rules());	 */

		$rules[] = array('username', 'required');
		$rules[] = array('password, verifyPassword', 'required');
		$rules[] = array('password', 'compare',
				'compareAttribute'=>'verifyPassword',
				'message' => Yum::t("Retype password is incorrect."));
		if(Yum::module('registration')->enableCaptcha)
			$rules[] = array('verifyCode', 'captcha',
					'allowEmpty'=>CCaptcha::checkRequirements()); 

		return $rules;
	}
 public function actionRegistration()
 {
     Yii::import('application.modules.profile.models.*');
     $profile = new YumProfile();
     if (isset($_POST['Profile'])) {
         $profile->attributes = $_POST['YumProfile'];
         if ($profile->save()) {
             $user = new YumUser();
         }
         $password = YumUser::generatePassword();
         // we generate a dummy username here, since yum requires one
         $user->register(md5($profile->email), $password, $profile);
         $this->sendRegistrationEmail($user, $password);
         Yum::setFlash('Thank you for your registration. Please check your email.');
         $this->redirect(Yum::module()->loginUrl);
     }
     $this->render('/registration/registration', array('profile' => $profile));
 }
 protected function renderContent()
 {
     parent::renderContent();
     if (Yii::app()->user->isGuest) {
         return false;
     }
     $user = YumUser::model()->findByPk(Yii::app()->user->id);
     $this->render('profile_comments', array('comments' => Yii::app()->user->data()->profile->recentComments()));
 }
 public function checkexists($attribute, $params)
 {
     $user = null;
     // we only want to authenticate when there are no input errors so far
     if (!$this->hasErrors()) {
         if (strpos($this->login_or_email, "@")) {
             $profile = YumProfile::model()->findByAttributes(array('email' => $this->login_or_email));
             $this->user = $profile && $profile->user && $profile->user instanceof YumUser ? $profile->user : null;
         } else {
             $this->user = YumUser::model()->findByAttributes(array('username' => $this->login_or_email));
         }
     }
 }
 public function loadModel($id = null)
 {
     if (!$id) {
         $id = Yii::app()->user->id;
     }
     if (is_numeric($id)) {
         return $this->_model = YumUser::model()->findByPk($id);
     } else {
         if (is_string($id)) {
             return $this->_model = YumUser::model()->find("username = '******'");
         }
     }
 }
	public function isPublic($user = null) {
		if($user == null)
			$user = Yii::app()->user->id;

		if(!$this->visible)
			return false;

		if($privacy = YumUser::model()->findByPk($user)->privacy) {
			if($privacy->public_profile_fields & pow(2, $this->id))
				return true;
		}

		return false;
	}
 public function rules()
 {
     $rules = parent::rules();
     if (!(Yum::hasModule('registration') && Yum::module('registration')->registration_by_email)) {
         $rules[] = array('username', 'required');
     }
     $rules[] = array('newsletter, terms,type_id', 'safe');
     // password requirement is already checked in YumUser model, its sufficient
     // to check for verifyPassword here
     $rules[] = array('verifyPassword', 'required');
     $rules[] = array('password', 'compare', 'compareAttribute' => 'verifyPassword', 'message' => Yum::t("Retype password is incorrect."));
     if (Yum::module('registration')->enableCaptcha && !Yum::module()->debug) {
         $rules[] = array('verifyCode', 'captcha', 'allowEmpty' => CCaptcha::checkRequirements());
     }
     return $rules;
 }
 public function actionCreate()
 {
     $this->layout = Yum::module()->adminLayout;
     $model = new YumRole();
     $this->performAjaxValidation($model, 'yum-role-form');
     if (isset($_POST['YumRole'])) {
         $model->attributes = $_POST['YumRole'];
         if ($model->save()) {
             if (Yum::module()->enableLogging == true) {
                 $user = YumUser::model()->findbyPK(Yii::app()->user->id);
                 Yum::log(Yum::t('The role {role} has been created by {username}', array('{role}' => $model->title, '{username}' => Yii::app()->user->data()->username)));
             }
             $this->redirect(array('admin'));
         }
     }
     $this->render('create', array('model' => $model));
 }
 public function getPublicFields()
 {
     if (!Yum::module('profile')->enablePrivacySetting) {
         return false;
     }
     $fields = array();
     if ($privacy = @YumUser::model()->cache(500)->with('privacy')->findByPk($this->user_id)->privacy->public_profile_fields) {
         $i = 1;
         foreach (YumProfileField::model()->cache(500)->findAll() as $field) {
             if ($i & $privacy && $field->visible != 0) {
                 $fields[] = $field;
             }
             $i *= 2;
         }
     }
     return $fields;
 }
 public function actionCompose($to_user_id = null, $answer_to = 0)
 {
     $model = new YumMessage();
     $this->performAjaxValidation('YumMessage', 'yum-message-form');
     if (isset($_POST['YumMessage'])) {
         $model->attributes = $_POST['YumMessage'];
         $model->from_user_id = Yii::app()->user->id;
         $model->validate();
         if (!$model->hasErrors()) {
             $model->save();
             Yum::setFlash(Yum::t('Message "{message}" has been sent to {to}', array('{message}' => $model->title, '{to}' => YumUser::model()->findByPk($model->to_user_id)->username)));
             $this->redirect(Yum::module('message')->inboxRoute);
         }
     }
     $fct = 'render';
     if (Yii::app()->request->isAjaxRequest) {
         $fct = 'renderPartial';
     }
     $this->{$fct}('compose', array('model' => $model, 'to_user_id' => $to_user_id, 'answer_to' => $answer_to));
 }
 public function authenticate($without_password = false)
 {
     $user = YumUser::model()->find('username = :username', array(':username' => $this->username));
     // try to authenticate via email
     if (Yum::hasModule('profile') && Yum::module()->loginType & UserModule::LOGIN_BY_EMAIL && !$user) {
         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 ($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 {
                 if ($without_password) {
                     $this->credentialsConfirmed($user);
                 } else {
                     if (!CPasswordHelper::verifyPassword($this->password, $user->password)) {
                         $this->errorCode = self::ERROR_PASSWORD_INVALID;
                     } else {
                         $this->credentialsConfirmed($user);
                     }
                 }
             }
         }
     }
     return !$this->errorCode;
 }
 public static function write($to, $from, $subject, $body, $mail = true)
 {
     $message = new YumMessage();
     if (!$mail) {
         $message->omit_mail = true;
     }
     if (is_object($from)) {
         $message->from_user_id = (int) $from->id;
     } else {
         if (is_numeric($from)) {
             $message->from_user_id = $from;
         } else {
             if (is_string($from) && ($user = YumUser::model()->find("username = '******'"))) {
                 $message->from_user_id = $user->id;
             } else {
                 return false;
             }
         }
     }
     if (is_object($to)) {
         $message->to_user_id = (int) $to->id;
     } else {
         if (is_numeric($to)) {
             $message->to_user_id = $to;
         } else {
             if (is_string($to) && ($user = YumUser::model()->find("username = '******'"))) {
                 $message->to_user_id = $user->id;
             } else {
                 return false;
             }
         }
     }
     $message->title = $subject;
     $message->message = $body;
     return $message->save();
 }
 public function beforeSave()
 {
     $this->updatetime = time();
     // If the user has activated email receiving, send a email
     if ($this->isNewRecord) {
         if ($user = YumUser::model()->findByPk($this->friend_id)) {
             if (Yum::hasModule('messages') && $user->privacy && $user->privacy->message_new_friendship) {
                 Yii::import('application.modules.messages.models.YumMessage');
                 YumMessage::write($user, $this->inviter, Yum::t('New friendship request from {username}', array('{username}' => $this->inviter->username)), YumTextSettings::getText('text_friendship_new', array('{username}' => $this->inviter->username, '{link_friends}' => Yii::app()->controller->createUrl('//friendship/friendship/index'), '{link_profile}' => Yii::app()->controller->createUrl('//profile/profile/view'), '{message}' => $this->message)));
             }
         }
     }
     return parent::beforeSave();
 }
?>
    </div>

    <div style="float: right; margin: 10px;">
        <div class="row">
            <?php 
echo $form->labelEx($model, 'superuser');
echo $form->dropDownList($model, 'superuser', YumUser::itemAlias('AdminStatus'));
echo $form->error($model, 'superuser');
?>
        </div>

        <div class="row">
            <?php 
echo $form->labelEx($model, 'status');
echo $form->dropDownList($model, 'status', YumUser::itemAlias('UserStatus'));
echo $form->error($model, 'status');
?>
        </div>
<?php 
if (Yum::hasModule('role')) {
    Yii::import('application.modules.role.models.*');
    ?>
            <div class="row roles">
                <p> <?php 
    echo Yum::t('User belongs to these roles');
    ?>
 </p>

                <?php 
    $this->widget('application.modules.user.components.Relation', array('model' => $model, 'relation' => 'roles', 'style' => 'dropdownlist', 'fields' => 'title', 'showAddButton' => false));
 /**
  * Activation of an user account. The Email and the Activation key send
  * by email needs to correct in order to continue. The Status will
  * be initially set to 1 (active - first Visit) so the administrator
  * can see, which accounts have been activated, but not yet logged in 
  * (more than once)
  */
 public function actionActivation($email, $key)
 {
     // If already logged in, we dont activate anymore
     if (!Yii::app()->user->isGuest) {
         Yum::setFlash('You are already logged in, please log out to activate your account');
         $this->redirect(Yii::app()->user->returnUrl);
     }
     // If everything is set properly, let the model handle the Validation
     // and do the Activation
     $status = YumUser::activate($email, $key);
     if ($status instanceof YumUser) {
         if (Yum::module('registration')->loginAfterSuccessfulActivation) {
             $login = new YumUserIdentity($status->username, false);
             $login->authenticate(true);
             Yii::app()->user->login($login);
         }
         $this->render(Yum::module('registration')->activationSuccessView);
     } else {
         $this->render(Yum::module('registration')->activationFailureView, array('error' => $status));
     }
 }
 public function actionLogout()
 {
     // If the user is already logged out send them to returnLogoutUrl
     if (Yii::app()->user->isGuest) {
         $this->redirect(Yum::module()->returnLogoutUrl);
     }
     //let's delete the login_type cookie
     $cookie = Yii::app()->request->cookies['login_type'];
     if ($cookie) {
         $cookie->expire = time() - 3600 * 72;
         Yii::app()->request->cookies['login_type'] = $cookie;
     }
     if ($user = YumUser::model()->findByPk(Yii::app()->user->id)) {
         $username = $user->username;
         $user->logout();
         if (Yii::app()->user->name == 'facebook') {
             if (!Yum::module()->loginType & UserModule::LOGIN_BY_FACEBOOK) {
                 throw new Exception('actionLogout for Facebook was called, but is not activated in main.php');
             }
             Yii::import('application.modules.user.vendors.facebook.*');
             require_once 'Facebook.php';
             $facebook = new Facebook(Yum::module()->facebookConfig);
             $fb_cookie = 'fbs_' . Yum::module()->facebookConfig['appId'];
             $cookie = Yii::app()->request->cookies[$fb_cookie];
             if ($cookie) {
                 $cookie->expire = time() - 1 * (3600 * 72);
                 Yii::app()->request->cookies[$cookie->name] = $cookie;
                 $servername = '.' . Yii::app()->request->serverName;
                 setcookie("{$fb_cookie}", "", time() - 3600);
                 setcookie("{$fb_cookie}", "", time() - 3600, "/", "{$servername}", 1);
             }
             $session = $facebook->getSession();
             Yum::log('Facebook logout from user ' . $username);
             Yii::app()->user->logout();
             $this->redirect($facebook->getLogoutUrl(array('next' => $this->createAbsoluteUrl(Yum::module()->returnLogoutUrl), 'session_key' => $session['session_key'])));
         } else {
             Yum::log(Yum::t('User {username} logged off', array('{username}' => $username)));
             Yii::app()->user->logout();
         }
     }
     $this->redirect(Yum::module()->returnLogoutUrl);
 }
	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(YumUser::encrypt($this->password)!==$user->password)
			$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;

	}
	<th class="label"><?php 
echo CHtml::encode($model->getAttributeLabel('lastvisit'));
?>
</th>
    <td><?php 
echo date(UserModule::$dateFormat, $model->lastvisit);
?>
</td>
</tr>
<tr>
	<th class="label"><?php 
echo CHtml::encode($model->getAttributeLabel('status'));
?>
</th>
    <td><?php 
echo CHtml::encode(YumUser::itemAlias("UserStatus", $model->status));
?>
</td>
</tr>
</table>

<div id="friends">
<h2> <?php 
echo Yum::t('My friends');
?>
 </h2>
<?php 
if (Yum::hasModule('friendship') && $model->friends) {
    foreach ($friends as $friend) {
        ?>
<div id="friend">
 public static function invitationLink($inviter, $invited)
 {
     if ($inviter === $invited) {
         return false;
     }
     if (!is_object($inviter)) {
         $inviter = YumUser::model()->findByPk($inviter);
     }
     if (!is_object($invited)) {
         $invited = YumUser::model()->findByPk($invited);
     }
     $friends = $inviter->getFriends(true);
     if ($friends && $friends[0] != NULL) {
         foreach ($friends as $friend) {
             if ($friend->id == $invited->id) {
                 return false;
             }
         }
     }
     // already friends, rejected or request pending
     return CHtml::link(Yum::t('Add as a friend'), array('//friendship/friendship/invite', 'user_id' => $invited->id));
 }
Exemple #24
0
	/**
	 * Loads the User Object instance
	 * @return YumUser
	 */
	public function loadUser($uid = 0)
	{
		if($this->_model === null)
		{
			if($uid != 0)
				$this->_model = YumUser::model()->findByPk($uid);
			elseif(isset($_GET['id']))
				$this->_model = YumUser::model()->findByPk($_GET['id']);
			if($this->_model === null)
				throw new CHttpException(404,'The requested User does not exist.');
		}
		return $this->_model;
	}
} else {
    $this->title = Yum::t('View user "{username}"', array('{username}' => $model->username));
}
$this->breadcrumbs = array(Yum::t('Users') => array('index'), $model->username);
echo Yum::renderFlash();
if (Yii::app()->user->isAdmin()) {
    $attributes = array('id');
    if (!Yum::module()->loginType & UserModule::LOGIN_BY_EMAIL) {
        $attributes[] = 'username';
    }
    if ($profiles && $model->profile) {
        foreach (YumProfile::getProfileFields() as $field) {
            array_push($attributes, array('label' => Yum::t($field), 'type' => 'raw', 'value' => $model->profile->getAttribute($field)));
        }
    }
    array_push($attributes, array('name' => 'createtime', 'value' => date(UserModule::$dateFormat, $model->createtime)), array('name' => 'lastvisit', 'value' => date(UserModule::$dateFormat, $model->lastvisit)), array('name' => 'lastpasswordchange', 'value' => date(UserModule::$dateFormat, $model->lastpasswordchange)), array('name' => 'superuser', 'value' => YumUser::itemAlias("AdminStatus", $model->superuser)), array('name' => Yum::t('Activation link'), 'value' => $model->getActivationUrl()), array('name' => 'status', 'value' => YumUser::itemAlias("UserStatus", $model->status)));
    $this->widget('zii.widgets.CDetailView', array('data' => $model, 'attributes' => $attributes));
} else {
    // For all users
    $attributes = array('username');
    if ($profiles) {
        $profileFields = YumProfile::getProfileFields();
        if ($profileFields) {
            foreach ($profileFields as $field) {
                array_push($attributes, array('label' => Yum::t($field), 'name' => $field, 'value' => $model->profile->getAttribute($field)));
            }
        }
    }
    array_push($attributes, array('name' => 'createtime', 'value' => date(UserModule::$dateFormat, $model->createtime)), array('name' => 'lastvisit', 'value' => date(UserModule::$dateFormat, $model->lastvisit)));
    $this->widget('zii.widgets.CDetailView', array('data' => $model, 'attributes' => $attributes));
}
 private function _checkAuth()
 {
     foreach (array('HTTP_X_USERNAME', 'PHP_AUTH_USER') as $var) {
         if (isset($_SERVER[$var]) && $_SERVER[$var] != '') {
             $username = $_SERVER[$var];
         }
     }
     foreach (array('HTTP_X_PASSWORD', 'PHP_AUTH_PW') as $var) {
         if (isset($_SERVER[$var]) && $_SERVER[$var] != '') {
             $password = $_SERVER[$var];
         }
     }
     if ($username && $password) {
         $user = YumUser::model()->find('LOWER(username)=?', array(strtolower($username)));
         if (Yum::module()->RESTfulCleartextPasswords && $user !== null && $user->superuser && md5($password) == $user->password) {
             return true;
         }
         if (!Yum::module()->RESTfulCleartextPasswords && $user !== null && $user->superuser && $password == $user->password) {
             return true;
         }
     }
     $this->_sendResponse(401, 'Error: Username or password is invalid');
 }
	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',
						'usergroupMessagesTable',
						'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,
						`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 `" . $usergroupMessagesTable . "` (
							`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']['usergroupMessagesTable'] = $usergroupMessagesTable;
					}

					// Install Membership Management submodule
					if (isset($_POST['installMembership'])) {
						$sql = "CREATE TABLE IF NOT EXISTS `{$membershipTable}` (
							`id` int(11) 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
								) 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,
							`is_membership_possible` tinyint(1) NOT NULL DEFAULT 0,
							`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

					$sql = "INSERT INTO `" . $userTable
					   ."` (`id`, `username`, `password`, `activationKey`, `createtime`, `lastvisit`, `superuser`, `status`) VALUES "
					   ."(1, 'admin', '" . YumUser::encrypt('admin') . "', '', " . time() . ", 0, 1, 1),"
					   ."(2, 'demo', '" . YumUser::encrypt('demo') . "', '', " . 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`, `price`, `duration`) VALUES "
							."('UserManager', 'This users can manage Users', 0, 0),"
							."('Demo', 'Users having the demo role', 0, 0),"
							."('Business', 'Example Business account', 9.99, 7),"
							."('Premium', 'Example Premium account', 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 {
				$this->render('start', array(
					//FIXME: We should normalize table names either in singular or plural.
					'userTable' => Yum::resolveTableName($this->module->userTable, Yii::app()->db),
					'privacySettingTable' => Yum::resolveTableName($this->module->privacySettingTable, Yii::app()->db),
					'translationTable' => Yum::resolveTableName($this->module->translationTable, Yii::app()->db),
					'roleTable' => Yum::resolveTableName($this->module->roleTable, Yii::app()->db),
					'membershipTable' => Yum::resolveTableName($this->module->membershipTable, Yii::app()->db),
					'paymentTable' => Yum::resolveTableName($this->module->paymentTable, Yii::app()->db),
					'messageTable' => Yum::resolveTableName($this->module->messageTable, Yii::app()->db),
					'profileTable' => Yum::resolveTableName($this->module->profileTable, Yii::app()->db),
					'profileCommentTable' => Yum::resolveTableName($this->module->profileCommentTable, Yii::app()->db),
					'profileVisitTable' => Yum::resolveTableName($this->module->profileVisitTable, Yii::app()->db),
					'profileFieldTable' => Yum::resolveTableName($this->module->profileFieldTable, Yii::app()->db),
					'userRoleTable' => Yum::resolveTableName($this->module->userRoleTable, Yii::app()->db),
					'usergroupTable' => Yum::resolveTableName($this->module->usergroupTable, Yii::app()->db),
					'usergroupMessagesTable' => Yum::resolveTableName($this->module->usergroupMessagesTable, Yii::app()->db),
					'permissionTable' => Yum::resolveTableName($this->module->permissionTable, Yii::app()->db),
					'friendshipTable' => Yum::resolveTableName($this->module->friendshipTable, Yii::app()->db),
					'actionTable' => Yum::resolveTableName($this->module->actionTable, Yii::app()->db),
				));
			}
		} else {
			throw new CException(Yum::t('User management module is not in Debug Mode'));
		}
	}
 public function loginsToday()
 {
     $day = $this->getStartOfDay(time());
     return YumUser::model()->count('lastvisit > :begin and lastvisit < :end', array(':begin' => $day, ':end' => $day + 86400));
 }
 /**
  * Return admins.
  * @return array syperusers names
  */
 public static function getAdmins()
 {
     $admins = YumUser::model()->active()->superuser()->findAll();
     $returnarray = array();
     foreach ($admins as $admin) {
         array_push($returnarray, $admin->username);
     }
     return $returnarray;
 }
<?php

if (isset($actions)) {
    foreach ($actions as $action) {
        printf('<h2>%s</h2>', $action->title);
        echo Yum::t('The following users have permission to perform the action {action}:', array('{action}' => $action->title));
        if ($action->permissions) {
            foreach ($action->permissions as $permission) {
                echo '<ul>';
                if ($permission->type == 'user') {
                    $user = YumUser::model()->findByPk($permission->principal_id);
                    printf('<li>%s</li>', CHtml::link($user->username, array('/user/view', 'id' => $user->id)));
                }
                if ($permission->type == 'role') {
                    $role = YumRole::model()->findByPk($permission->principal_id);
                    printf('<li>role %s</li>', CHtml::link($role->title, array('/role/view', 'id' => $role->id)));
                }
                echo '</ul>';
            }
        }
    }
} else {
    echo Yum::t('No user has permission');
}
?>