Esempio n. 1
1
 public function actionAuto()
 {
     $this->stdout("Install:\n\n", Console::FG_YELLOW);
     \humhub\modules\installer\libs\InitialData::bootstrap();
     Yii::$app->settings->set('name', "HumHub Test");
     Yii::$app->settings->set('mailer.systemEmailName', "*****@*****.**");
     Yii::$app->settings->set('mailer.systemEmailName', "*****@*****.**");
     Yii::$app->settings->set('secret', \humhub\libs\UUID::v4());
     $user = new User();
     //$user->group_id = 1;
     $user->username = "******";
     $user->email = '*****@*****.**';
     $user->status = User::STATUS_ENABLED;
     $user->language = '';
     $user->last_activity_email = new \yii\db\Expression('NOW()');
     if (!$user->save()) {
         throw new \yii\base\Exception("Could not save user");
     }
     $user->profile->title = "System Administration";
     $user->profile->firstname = "John";
     $user->profile->lastname = "Doe";
     $user->profile->save();
     $password = new Password();
     $password->user_id = $user->id;
     $password->setPassword('test');
     $password->save();
     // Assign to system admin group
     Group::getAdminGroup()->addUser($user);
     return self::EXIT_CODE_NORMAL;
 }
Esempio n. 2
0
 /**
  * @inheritdoc
  */
 public function run()
 {
     if ($this->user->isCurrentUser() || \Yii::$app->user->isGuest) {
         return;
     }
     if (Yii::$app->getModule('friendship')->getIsEnabled()) {
         // Don't show follow button, when friends
         if (Friendship::getFriendsQuery($this->user)->one() !== null) {
             return;
         }
     }
     // Add class for javascript handling
     $this->followOptions['class'] .= ' followButton';
     $this->unfollowOptions['class'] .= ' unfollowButton';
     // Hide inactive button
     if ($this->user->isFollowedByUser()) {
         $this->followOptions['style'] .= ' display:none;';
     } else {
         $this->unfollowOptions['style'] .= ' display:none;';
     }
     // Add UserId Buttons
     $this->followOptions['data-userid'] = $this->user->id;
     $this->unfollowOptions['data-userid'] = $this->user->id;
     $this->view->registerJsFile('@web/resources/user/followButton.js');
     return Html::a($this->unfollowLabel, $this->user->createUrl('/user/profile/unfollow'), $this->unfollowOptions) . Html::a($this->followLabel, $this->user->createUrl('/user/profile/follow'), $this->followOptions);
 }
Esempio n. 3
0
 public function getMailUpdate(User $user, $interval)
 {
     $output = "";
     foreach (Session::find()->where(['<', 'expire', time()])->all() as $session) {
         $session->delete();
     }
     $receive_email_notifications = $user->getSetting("receive_email_notifications", 'core', Setting::Get('receive_email_notifications', 'mailing'));
     // Never receive notifications
     if ($receive_email_notifications == User::RECEIVE_EMAIL_NEVER) {
         return "";
     }
     // We are in hourly mode and user wants daily
     if ($interval == CronController::EVENT_ON_HOURLY_RUN && $receive_email_notifications == User::RECEIVE_EMAIL_DAILY_SUMMARY) {
         return "";
     }
     // We are in daily mode and user dont wants daily reports
     if ($interval == CronController::EVENT_ON_DAILY_RUN && $receive_email_notifications != User::RECEIVE_EMAIL_DAILY_SUMMARY) {
         return "";
     }
     // User wants only when offline and is online
     if ($interval == CronController::EVENT_ON_HOURLY_RUN) {
         $isOnline = count($user->httpSessions) > 0;
         if ($receive_email_notifications == User::RECEIVE_EMAIL_WHEN_OFFLINE && $isOnline) {
             return "";
         }
     }
     $query = Notification::find()->where(['user_id' => $user->id])->andWhere(['!=', 'seen', 1])->andWhere(['!=', 'emailed', 1]);
     foreach ($query->all() as $notification) {
         $output .= $notification->getClass()->render(BaseNotification::OUTPUT_MAIL);
         $notification->emailed = 1;
         $notification->save();
     }
     return $output;
 }
Esempio n. 4
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     $this->addItemGroup(array('id' => 'profile', 'label' => Yii::t('UserModule.widgets_ProfileMenuWidget', '<strong>Profile</strong> menu'), 'sortOrder' => 100));
     $this->addItem(array('label' => Yii::t('UserModule.widgets_ProfileMenuWidget', 'Stream'), 'group' => 'profile', 'url' => $this->user->createUrl('//user/profile/home'), 'sortOrder' => 200, 'isActive' => Yii::$app->controller->id == "profile" && (Yii::$app->controller->action->id == "index" || Yii::$app->controller->action->id == "home")));
     if ($this->user->permissionManager->can(new \humhub\modules\user\permissions\ViewAboutPage())) {
         $this->addItem(array('label' => Yii::t('UserModule.widgets_ProfileMenuWidget', 'About'), 'group' => 'profile', 'url' => $this->user->createUrl('//user/profile/about'), 'sortOrder' => 300, 'isActive' => Yii::$app->controller->id == "profile" && Yii::$app->controller->action->id == "about"));
     }
     parent::init();
 }
Esempio n. 5
0
 public function testAutoWallCreation()
 {
     $user = new User();
     $user->username = "******";
     $user->email = "*****@*****.**";
     $this->assertTrue($user->save());
     $this->assertNotNull($user->wall_id);
     $wall = Wall::findOne(['id' => $user->wall_id]);
     $this->assertNotNull($wall);
 }
Esempio n. 6
0
 /**
  * @inheritdoc
  */
 public function run()
 {
     $friendshipsEnabled = Yii::$app->getModule('friendship')->getIsEnabled();
     $countFriends = 0;
     if ($friendshipsEnabled) {
         $countFriends = Friendship::getFriendsQuery($this->user)->count();
     }
     $countFollowing = $this->user->getFollowingCount(User::className()) + $this->user->getFollowingCount(Space::className());
     $countUserSpaces = Membership::getUserSpaceQuery($this->user)->andWhere(['!=', 'space.visibility', Space::VISIBILITY_NONE])->andWhere(['space.status' => Space::STATUS_ENABLED])->count();
     return $this->render('profileHeader', array('user' => $this->user, 'isProfileOwner' => $this->isProfileOwner, 'friendshipsEnabled' => $friendshipsEnabled, 'countFriends' => $countFriends, 'countFollowers' => $this->user->getFollowerCount(), 'countFollowing' => $countFollowing, 'countSpaces' => $countUserSpaces));
 }
 public function up()
 {
     $spaces = Space::find()->all();
     $users = User::find()->all();
     $containers = array_merge($users == null ? [] : $users, $spaces == null ? [] : $spaces);
     foreach ($containers as $container) {
         $created_by = $container instanceof User ? $container->id : $container instanceof Space ? $container->created_by : 1;
         $created_by = $created_by == null ? 1 : $created_by;
         if ($container->isModuleEnabled('cfiles')) {
             $this->insert('cfiles_folder', ['title' => Module::ROOT_TITLE, 'description' => Module::ROOT_DESCRIPTION, 'parent_folder_id' => 0, 'has_wall_entry' => false, 'type' => Folder::TYPE_FOLDER_ROOT]);
             $root_id = Yii::$app->db->getLastInsertID();
             $this->insert('content', ['guid' => \humhub\libs\UUID::v4(), 'object_model' => Folder::className(), 'object_id' => $root_id, 'visibility' => 0, 'sticked' => 0, 'archived' => 0, 'created_at' => new \yii\db\Expression('NOW()'), 'created_by' => $created_by, 'updated_at' => new \yii\db\Expression('NOW()'), 'updated_by' => $created_by, 'contentcontainer_id' => $container->contentcontainer_id]);
             $this->insert('cfiles_folder', ['title' => Module::ALL_POSTED_FILES_TITLE, 'description' => Module::ALL_POSTED_FILES_DESCRIPTION, 'parent_folder_id' => $root_id, 'has_wall_entry' => false, 'type' => Folder::TYPE_FOLDER_POSTED]);
             $allpostedfiles_id = Yii::$app->db->getLastInsertID();
             $this->insert('content', ['guid' => \humhub\libs\UUID::v4(), 'object_model' => Folder::className(), 'object_id' => $allpostedfiles_id, 'visibility' => 0, 'sticked' => 0, 'archived' => 0, 'created_at' => new \yii\db\Expression('NOW()'), 'created_by' => $created_by, 'updated_at' => new \yii\db\Expression('NOW()'), 'updated_by' => $created_by, 'contentcontainer_id' => $container->contentcontainer_id]);
             $posted_content_id = Yii::$app->db->getLastInsertID();
             $filesQuery = File::find()->joinWith('baseFile')->contentContainer($container);
             $foldersQuery = Folder::find()->contentContainer($container);
             $filesQuery->andWhere(['cfiles_file.parent_folder_id' => 0]);
             // user maintained folders
             $foldersQuery->andWhere(['cfiles_folder.parent_folder_id' => 0]);
             // do not return any folders here that are root or allpostedfiles
             $foldersQuery->andWhere(['cfiles_folder.type' => null]);
             $rootsubfiles = $filesQuery->all();
             $rootsubfolders = $foldersQuery->all();
             foreach ($rootsubfiles as $file) {
                 $this->update('cfiles_file', ['cfiles_file.parent_folder_id' => $root_id], ['id' => $file->id]);
             }
             foreach ($rootsubfolders as $folder) {
                 $this->update('cfiles_folder', ['parent_folder_id' => $root_id], ['id' => $folder->id]);
             }
         }
     }
 }
Esempio n. 8
0
 /**
  * JSON Search for Users
  *
  * Returns an array of users with fields:
  *  - guid
  *  - displayName
  *  - image
  *  - profile link
  */
 public function actionJson()
 {
     Yii::$app->response->format = 'json';
     $maxResults = 10;
     $keyword = Yii::$app->request->get('keyword');
     $query = User::find()->limit($maxResults)->joinWith('profile');
     foreach (explode(" ", $keyword) as $part) {
         $query->orFilterWhere(['like', 'user.email', $part]);
         $query->orFilterWhere(['like', 'user.username', $part]);
         $query->orFilterWhere(['like', 'profile.firstname', $part]);
         $query->orFilterWhere(['like', 'profile.lastname', $part]);
         $query->orFilterWhere(['like', 'profile.title', $part]);
     }
     $query->active();
     $results = [];
     foreach ($query->all() as $user) {
         if ($user != null) {
             $userInfo = array();
             $userInfo['guid'] = $user->guid;
             $userInfo['displayName'] = Html::encode($user->displayName);
             $userInfo['image'] = $user->getProfileImage()->getUrl();
             $userInfo['link'] = $user->getUrl();
             $results[] = $userInfo;
         }
     }
     return $results;
 }
Esempio n. 9
0
 /**
  * Check if there is a new Humhub Version available and sends a notification
  * to super admins
  *
  * @param \yii\base\Event $event
  */
 public static function onCronDailyRun($event)
 {
     $controller = $event->sender;
     if (!Yii::$app->getModule('admin')->dailyCheckForNewVersion) {
         return;
     }
     if (!Yii::$app->params['humhub']['apiEnabled']) {
         return;
     }
     $controller->stdout("Checking for new HumHub version... ");
     $latestVersion = libs\HumHubAPI::getLatestHumHubVersion();
     if ($latestVersion != "") {
         $adminUserQuery = User::find()->where(['super_admin' => 1]);
         $latestNotifiedVersion = Setting::Get('lastVersionNotify', 'admin');
         $adminsNotified = !($latestNotifiedVersion == "" || version_compare($latestVersion, $latestNotifiedVersion, ">"));
         $newVersionAvailable = version_compare($latestVersion, Yii::$app->version, ">");
         $updateNotification = new notifications\NewVersionAvailable();
         // Cleanup existing notifications
         if (!$newVersionAvailable || $newVersionAvailable && !$adminsNotified) {
             foreach ($adminUserQuery->all() as $admin) {
                 $updateNotification->delete($admin);
             }
         }
         // Create new notification
         if ($newVersionAvailable && !$adminsNotified) {
             $updateNotification->sendBulk($adminUserQuery);
             Setting::Set('lastVersionNotify', $latestVersion, 'admin');
         }
     }
     $controller->stdout('done. ' . PHP_EOL, \yii\helpers\Console::FG_GREEN);
 }
Esempio n. 10
0
 /**
  * Returns all current logged in users.
  * 
  * @return ActiveQueryUser
  */
 public static function getOnlineUsers()
 {
     $query = \humhub\modules\user\models\User::find();
     $query->leftJoin('user_http_session', 'user_http_session.user_id=user.id');
     $query->andWhere(['IS NOT', 'user_http_session.user_id', new Expression('NULL')]);
     return $query;
 }
Esempio n. 11
0
 /**
  * Processes update e-mails for all users
  */
 public static function processCron($controller)
 {
     // Detect the mailing interval we're in
     $interval = 0;
     if (Yii::$app->controller->action->id == 'hourly') {
         $interval = self::INTERVAL_HOURY;
     } elseif (Yii::$app->controller->action->id == 'daily') {
         $interval = self::INTERVAL_DAILY;
     } else {
         throw new \yii\console\Exception('Invalid mail update interval!');
     }
     // Get users
     $users = User::find()->distinct()->joinWith(['httpSessions', 'profile'])->where(['user.status' => User::STATUS_ENABLED]);
     $totalUsers = $users->count();
     $processed = 0;
     Console::startProgress($processed, $totalUsers, 'Sending update e-mails to users... ', false);
     $mailsSent = 0;
     foreach ($users->each() as $user) {
         $mailSender = new self();
         $mailSender->user = $user;
         $mailSender->interval = $interval;
         if ($mailSender->send()) {
             $mailsSent++;
         }
         Console::updateProgress(++$processed, $totalUsers);
     }
     Console::endProgress(true);
     $controller->stdout('done - ' . $mailsSent . ' email(s) sent.' . PHP_EOL, Console::FG_GREEN);
     // Switch back to system language
     self::switchLanguage();
 }
 /** 
  * Edit a karma record
  */
 public function actionEdit()
 {
     $id = (int) Yii::$app->request->get('id');
     $user = User::findOne(['id' => $id]);
     $karma = Karma::findOne(['id' => $id]);
     if ($karma == null) {
         throw new \yii\web\HttpException(404, "Karma record not found!");
     }
     // Build Form Definition
     $definition = array();
     $definition['elements'] = array();
     // Define Form Eleements
     $definition['elements']['Karma'] = array('type' => 'form', 'title' => 'Karma', 'elements' => array('name' => array('type' => 'text', 'class' => 'form-control', 'maxlength' => 25), 'points' => array('type' => 'text', 'class' => 'form-control', 'maxlength' => 10), 'description' => array('type' => 'text', 'class' => 'form-control', 'maxlength' => 1000)));
     // Get Form Definition
     $definition['buttons'] = array('save' => array('type' => 'submit', 'label' => 'Save', 'class' => 'btn btn-primary'), 'delete' => array('type' => 'submit', 'label' => 'Delete', 'class' => 'btn btn-danger'));
     $form = new HForm($definition);
     $form->models['Karma'] = $karma;
     if ($form->submitted('save') && $form->validate()) {
         if ($form->save()) {
             return $this->redirect(Url::toRoute(['edit', 'id' => $karma->id]));
         }
     }
     if ($form->submitted('delete')) {
         return $this->redirect(Url::toRoute(['delete', 'id' => $karma->id]));
     }
     return $this->render('edit', array('hForm' => $form));
 }
Esempio n. 13
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params = [])
 {
     $query = User::find()->joinWith(['profile', 'group']);
     $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => 50]]);
     $dataProvider->setSort(['attributes' => ['group.id', 'username', 'email', 'super_admin', 'profile.firstname', 'profile.lastname', 'created_at']]);
     $this->load($params);
     if (!$this->validate()) {
         $query->where('0=1');
         return $dataProvider;
     }
     /**
      * Limit Groups
      */
     $groups = $this->getGroups();
     $groupIds = [];
     foreach ($groups as $group) {
         $groupIds[] = $group->id;
     }
     $query->andWhere(['IN', 'group_id', $groupIds]);
     $query->andWhere(['status' => User::STATUS_NEED_APPROVAL]);
     $query->andFilterWhere(['id' => $this->id]);
     $query->andFilterWhere(['group.id' => $this->getAttribute('group.id')]);
     $query->andFilterWhere(['super_admin' => $this->super_admin]);
     $query->andFilterWhere(['like', 'id', $this->id]);
     $query->andFilterWhere(['like', 'username', $this->username]);
     $query->andFilterWhere(['like', 'email', $this->email]);
     $query->andFilterWhere(['like', 'profile.firstname', $this->getAttribute('profile.firstname')]);
     $query->andFilterWhere(['like', 'profile.lastname', $this->getAttribute('profile.lastname')]);
     return $dataProvider;
 }
Esempio n. 14
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = User::find()->joinWith('profile');
     $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => 50]]);
     $dataProvider->setSort(['attributes' => ['id', 'username', 'email', 'super_admin', 'last_login', 'profile.firstname', 'profile.lastname', 'created_at']]);
     $this->load($params);
     if (!$this->validate()) {
         $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id]);
     $query->andFilterWhere(['super_admin' => $this->super_admin]);
     $query->andFilterWhere(['like', 'id', $this->id]);
     $query->andFilterWhere(['like', 'username', $this->username]);
     $query->andFilterWhere(['like', 'email', $this->email]);
     $query->andFilterWhere(['like', 'profile.firstname', $this->getAttribute('profile.firstname')]);
     $query->andFilterWhere(['like', 'profile.lastname', $this->getAttribute('profile.lastname')]);
     if ($this->getAttribute('last_login') != "") {
         try {
             $last_login = Yii::$app->formatter->asDate($this->getAttribute('last_login'), 'php:Y-m-d');
             $query->andWhere(['=', new \yii\db\Expression("DATE(last_login)"), new \yii\db\Expression("DATE(:last_login)", [':last_login' => $last_login])]);
         } catch (InvalidParamException $e) {
             // do not change the query if the date is wrong formatted
         }
     }
     return $dataProvider;
 }
Esempio n. 15
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = User::find()->joinWith('profile');
     $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => 50]]);
     $dataProvider->setSort(['attributes' => ['id', 'username', 'email', 'super_admin', 'last_login', 'profile.firstname', 'profile.lastname', 'created_at']]);
     $this->load($params);
     if (!$this->validate()) {
         $query->where('0=1');
         return $dataProvider;
     }
     if (strtolower($this->last_login) == 'yes') {
         $query->andWhere(['not', ['last_login' => null]]);
     } else {
         if (strtolower($this->last_login) == 'no') {
             $query->andWhere(['last_login' => null]);
         }
     }
     $query->andFilterWhere(['id' => $this->id]);
     $query->andFilterWhere(['super_admin' => $this->super_admin]);
     $query->andFilterWhere(['like', 'id', $this->id]);
     $query->andFilterWhere(['like', 'username', $this->username]);
     $query->andFilterWhere(['like', 'email', $this->email]);
     $query->andFilterWhere(['like', 'profile.firstname', $this->getAttribute('profile.firstname')]);
     $query->andFilterWhere(['like', 'profile.lastname', $this->getAttribute('profile.lastname')]);
     return $dataProvider;
 }
Esempio n. 16
0
 /**
  * @inheritdoc
  */
 public function afterSave($insert, $changedAttributes)
 {
     if ($this->scenario == self::SCENARIO_EDIT) {
         $managerGuids = explode(",", $this->managerGuids);
         foreach ($managerGuids as $managerGuid) {
             // Ensure guids valid characters
             $managerGuid = preg_replace("/[^A-Za-z0-9\\-]/", '', $managerGuid);
             // Try to load user and get/create the GroupUser relation with isManager
             $user = \humhub\modules\user\models\User::findOne(['guid' => $managerGuid]);
             if ($user != null) {
                 $groupUser = GroupUser::findOne(['group_id' => $this->id, 'user_id' => $user->id]);
                 if ($groupUser != null && !$groupUser->is_group_manager) {
                     $groupUser->is_group_manager = true;
                     $groupUser->save();
                 } else {
                     $this->addUser($user, true);
                 }
             }
         }
         //Remove admins not contained in the selection
         foreach ($this->getManager()->all() as $admin) {
             if (!in_array($admin->guid, $managerGuids)) {
                 $groupUser = GroupUser::findOne(['group_id' => $this->id, 'user_id' => $admin->id]);
                 if ($groupUser != null) {
                     $groupUser->is_group_manager = false;
                     $groupUser->save();
                 }
             }
         }
     }
     parent::afterSave($insert, $changedAttributes);
 }
Esempio n. 17
0
 /**
  * Broadcast a message to all users
  */
 public function run()
 {
     //Send GCM notifications
     $model = new $this->modelClass();
     $records = $model->findBySql("SELECT * FROM gcm_relation")->all();
     $params = Yii::$app->getRequest()->getBodyParams();
     $data = array('message' => $params['message'], 'url' => $params['url']);
     $results = array();
     foreach ($records as $record) {
         if ($record->register_key) {
             //Enviar missatge
             $gcm = new GoogleCloudMessage();
             $gcm->apiKey = Setting::Get('gcmAPIKey', 'gcm');
             $gcm->url = Setting::Get('gcmURL', 'gcm');
             $result = $gcm->send($data, array($record->register_key));
             $results[$record->register_key] = $result;
         }
     }
     //Send mail notificacion
     $users = User::find()->distinct()->joinWith(['httpSessions', 'profile'])->where(['status' => User::STATUS_ENABLED]);
     Yii::setAlias('@gcmmodule', Yii::$app->getModule('gcm')->getBasePath());
     foreach ($users->each() as $user) {
         $mail = Yii::$app->mailer->compose(['html' => '@gcmmodule/views/emails/NewMessage'], ['message' => $params['message'], 'url' => $params['url']]);
         $mail->setFrom([Setting::Get('systemEmailAddress', 'mailing') => Setting::Get('systemEmailName', 'mailing')]);
         $mail->setTo($user->email);
         $mail->setSubject('Nova notícia al web: ' . $params['message']);
         $mail->send();
     }
     return true;
 }
Esempio n. 18
0
 /**
  * Provides a searchable user list of all workspace members in json.
  *
  */
 public function actionSearch()
 {
     Yii::$app->response->format = 'json';
     $space = $this->getSpace();
     if (!$space->isMember()) {
         throw new HttpException(404, Yii::t('SpaceModule.controllers_SpaceController', 'This action is only available for workspace members!'));
     }
     $results = array();
     $keyword = Yii::$app->request->get('keyword');
     $query = User::find();
     $query->leftJoin('space_membership', 'space_membership.user_id=user.id AND space_membership.space_id=:space_id AND space_membership.status=:member', ['space_id' => $space->id, 'member' => Membership::STATUS_MEMBER]);
     $query->andWhere('space_membership.space_id IS NOT NULL');
     $query->joinWith('profile');
     $query->limit(10);
     // Build Search Condition
     $parts = explode(" ", $keyword);
     $i = 0;
     foreach ($parts as $part) {
         $i++;
         $query->andWhere("(user.email LIKE :match OR " . "user.username LIKE :match OR " . "profile.firstname LIKE :match OR " . "profile.lastname LIKE :match OR " . "profile.title LIKE :match)", ['match' => '%' . $part . '%']);
     }
     foreach ($query->all() as $user) {
         $userInfo['guid'] = $user->guid;
         $userInfo['displayName'] = \yii\helpers\Html::encode($user->displayName);
         $userInfo['email'] = $user->email;
         $userInfo['image'] = $user->getProfileImage()->getUrl();
         $userInfo['link'] = $user->getUrl();
         $results[] = $userInfo;
     }
     return $results;
 }
Esempio n. 19
0
 public function getMailUpdate(User $user, $interval)
 {
     $output = ['html' => '', 'plaintext' => ''];
     $receive_email_activities = $user->getSetting("receive_email_activities", 'core', Setting::Get('receive_email_activities', 'mailing'));
     // User never wants activity content
     if ($receive_email_activities == User::RECEIVE_EMAIL_NEVER) {
         return "";
     }
     // We are in hourly mode and user wants receive a daily summary
     if ($interval == CronController::EVENT_ON_HOURLY_RUN && $receive_email_activities == User::RECEIVE_EMAIL_DAILY_SUMMARY) {
         return "";
     }
     // We are in daily mode and user wants receive not daily
     if ($interval == CronController::EVENT_ON_DAILY_RUN && $receive_email_activities != User::RECEIVE_EMAIL_DAILY_SUMMARY) {
         return "";
     }
     // User is online and want only receive when offline
     if ($interval == CronController::EVENT_ON_HOURLY_RUN) {
         $isOnline = count($user->httpSessions) > 0;
         if ($receive_email_activities == User::RECEIVE_EMAIL_WHEN_OFFLINE && $isOnline) {
             return "";
         }
     }
     $lastMailDate = $user->last_activity_email;
     if ($lastMailDate == "" || $lastMailDate == "0000-00-00 00:00:00") {
         $lastMailDate = new \yii\db\Expression('NOW() - INTERVAL 24 HOUR');
     }
     $stream = new \humhub\modules\dashboard\components\actions\DashboardStream('stream', Yii::$app->controller);
     $stream->limit = 50;
     $stream->mode = \humhub\modules\content\components\actions\Stream::MODE_ACTIVITY;
     $stream->user = $user;
     $stream->init();
     $stream->activeQuery->andWhere(['>', 'content.created_at', $lastMailDate]);
     foreach ($stream->getWallEntries() as $wallEntry) {
         try {
             $activity = $wallEntry->content->getPolymorphicRelation();
             $output['html'] .= $activity->getActivityBaseClass()->render(BaseActivity::OUTPUT_MAIL);
             $output['plaintext'] .= $activity->getActivityBaseClass()->render(BaseActivity::OUTPUT_MAIL_PLAINTEXT);
         } catch (\yii\base\Exception $ex) {
             \Yii::error($ex->getMessage());
         }
     }
     $user->last_activity_email = new \yii\db\Expression('NOW()');
     $user->save();
     return $output;
 }
Esempio n. 20
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     $friendshipEnabled = Yii::$app->getModule('friendship')->getIsEnabled();
     if ($this->user == null) {
         /**
          * For guests collect all wall_ids of "guest" public spaces / user profiles.
          * Generally show only public content
          */
         $publicSpacesSql = (new \yii\db\Query())->select(["si.wall_id"])->from('space si')->where('si.visibility=' . \humhub\modules\space\models\Space::VISIBILITY_ALL);
         $union = Yii::$app->db->getQueryBuilder()->build($publicSpacesSql)[0];
         $publicProfilesSql = (new \yii\db\Query())->select("pi.wall_id")->from('user pi')->where('pi.status=1 AND  pi.visibility = ' . \humhub\modules\user\models\User::VISIBILITY_ALL);
         $union .= " UNION " . Yii::$app->db->getQueryBuilder()->build($publicProfilesSql)[0];
         $this->activeQuery->andWhere('wall_entry.wall_id IN (' . $union . ')');
         $this->activeQuery->andWhere(['content.visibility' => \humhub\modules\content\models\Content::VISIBILITY_PUBLIC]);
     } else {
         /**
          * Collect all wall_ids we need to include into dashboard stream
          */
         // User to user follows
         $userFollow = (new \yii\db\Query())->select(["uf.wall_id"])->from('user_follow')->leftJoin('user uf', 'uf.id=user_follow.object_id AND user_follow.object_model=:userClass')->where('user_follow.user_id=' . $this->user->id . ' AND uf.wall_id IS NOT NULL');
         $union = Yii::$app->db->getQueryBuilder()->build($userFollow)[0];
         // User to space follows
         $spaceFollow = (new \yii\db\Query())->select("sf.wall_id")->from('user_follow')->leftJoin('space sf', 'sf.id=user_follow.object_id AND user_follow.object_model=:spaceClass')->where('user_follow.user_id=' . $this->user->id . ' AND sf.wall_id IS NOT NULL');
         $union .= " UNION " . Yii::$app->db->getQueryBuilder()->build($spaceFollow)[0];
         // User to space memberships
         $spaceMemberships = (new \yii\db\Query())->select("sm.wall_id")->from('space_membership')->leftJoin('space sm', 'sm.id=space_membership.space_id')->where('space_membership.user_id=' . $this->user->id . ' AND sm.wall_id IS NOT NULL AND space_membership.show_at_dashboard = 1');
         $union .= " UNION " . Yii::$app->db->getQueryBuilder()->build($spaceMemberships)[0];
         if ($friendshipEnabled) {
             // User to user follows
             $usersFriends = (new \yii\db\Query())->select(["ufr.wall_id"])->from('user ufr')->leftJoin('user_friendship recv', 'ufr.id=recv.friend_user_id AND recv.user_id=' . (int) $this->user->id)->leftJoin('user_friendship snd', 'ufr.id=snd.user_id AND snd.friend_user_id=' . (int) $this->user->id)->where('recv.id IS NOT NULL AND snd.id IS NOT NULL AND ufr.wall_id IS NOT NULL');
             $union .= " UNION " . Yii::$app->db->getQueryBuilder()->build($usersFriends)[0];
         }
         // Glue together also with current users wall
         $wallIdsSql = (new \yii\db\Query())->select('wall_id')->from('user uw')->where('uw.id=' . $this->user->id);
         $union .= " UNION " . Yii::$app->db->getQueryBuilder()->build($wallIdsSql)[0];
         // Manual Union (https://github.com/yiisoft/yii2/issues/7992)
         // Double union query - to avoid MySQL performance problems
         $this->activeQuery->andWhere('wall_entry.wall_id IN (select subselect.wall_id from (' . $union . ') subselect)', [':spaceClass' => \humhub\modules\space\models\Space::className(), ':userClass' => \humhub\modules\user\models\User::className()]);
         /**
          * Begin visibility checks regarding the content container
          */
         $this->activeQuery->leftJoin('wall', 'wall_entry.wall_id=wall.id');
         $this->activeQuery->leftJoin('space_membership', 'wall.object_id=space_membership.space_id AND space_membership.user_id=:userId AND space_membership.status=:status', ['userId' => $this->user->id, ':status' => \humhub\modules\space\models\Membership::STATUS_MEMBER]);
         if ($friendshipEnabled) {
             $this->activeQuery->leftJoin('user_friendship', 'wall.object_id=user_friendship.user_id AND user_friendship.friend_user_id=:userId', ['userId' => $this->user->id]);
         }
         $condition = ' (wall.object_model=:userModel AND content.visibility=0 AND content.created_by = :userId) OR ';
         if ($friendshipEnabled) {
             // In case of friendship we can also display private content
             $condition .= ' (wall.object_model=:userModel AND content.visibility=0 AND user_friendship.id IS NOT NULL) OR ';
         }
         // In case of an space entry, we need to join the space membership to verify the user can see private space content
         $condition .= ' (wall.object_model=:spaceModel AND content.visibility = 0 AND space_membership.status = ' . \humhub\modules\space\models\Membership::STATUS_MEMBER . ') OR ';
         $condition .= ' (content.visibility = 1 OR content.visibility IS NULL) ';
         $this->activeQuery->andWhere($condition, [':userId' => $this->user->id, ':spaceModel' => \humhub\modules\space\models\Space::className(), ':userModel' => \humhub\modules\user\models\User::className()]);
     }
 }
Esempio n. 21
0
 /**
  * @inheritdoc
  */
 public function rules()
 {
     $rules = [['newEmail', 'required'], ['newEmail', 'email'], ['newEmail', 'unique', 'targetAttribute' => 'email', 'targetClass' => User::className(), 'message' => '{attribute} "{value}" is already in use!']];
     if (CheckPasswordValidator::hasPassword()) {
         $rules[] = ['currentPassword', CheckPasswordValidator::className()];
         $rules[] = ['currentPassword', 'required'];
     }
     return $rules;
 }
Esempio n. 22
0
 /**
  * Executes the widgets
  */
 public function run()
 {
     $groups = Group::find()->count();
     $users = User::find()->count();
     $statsAvgMembers = $users / $groups;
     $statsTopGroup = Group::find()->where('id = (SELECT group_id  FROM user GROUP BY group_id ORDER BY count(*) DESC LIMIT 1)')->one();
     // Render widgets view
     return $this->render('groupStats', array('statsTotalGroups' => $groups, 'statsAvgMembers' => round($statsAvgMembers, 1), 'statsTopGroup' => $statsTopGroup, 'statsTotalUsers' => $users));
 }
Esempio n. 23
0
 /**
  * Gets a user setting
  * 
  * @see \humhub\modules\content\components\ContentContainerSettingsManager::get
  * @param int $userId
  * @param string $name
  * @param string $moduleId
  * @param string $defaultValue
  * @return string the value
  */
 public static function Get($userId, $name, $moduleId = "", $defaultValue = "")
 {
     $user = User::findOne(['id' => $userId]);
     $value = self::getModule($moduleId)->settings->contentContainer($user)->get($name);
     if ($value === null) {
         return $defaultValue;
     }
     return $value;
 }
Esempio n. 24
0
 /**
  * Executes the widgets
  */
 public function run()
 {
     // Some member stats
     $statsTotalUsers = User::find()->active()->count();
     $statsUserOnline = \humhub\modules\user\components\Session::getOnlineUsers()->count();
     $statsUserFollow = Follow::find()->where(['object_model' => User::className()])->count();
     // Render widgets view
     return $this->render('memberStats', array('statsTotalUsers' => $statsTotalUsers, 'statsUserOnline' => $statsUserOnline, 'statsUserFollow' => $statsUserFollow));
 }
Esempio n. 25
0
 /**
  * @inheritdoc
  */
 public function auth()
 {
     $user = User::find()->where(['username' => $this->login->username])->orWhere(['email' => $this->login->username])->one();
     if ($user !== null && $user->currentPassword !== null && $user->currentPassword->validatePassword($this->login->password)) {
         $this->setUserAttributes(['id' => $user->id]);
         return true;
     }
     return false;
 }
Esempio n. 26
0
 /**
  * Returns a user list which contains all users who likes it
  */
 public function actionUserList()
 {
     $query = \humhub\modules\user\models\User::find();
     $query->leftJoin('like', 'like.created_by=user.id');
     $query->where(['like.object_id' => $this->contentId, 'like.object_model' => $this->contentModel]);
     $query->orderBy('like.created_at DESC');
     $title = Yii::t('LikeModule.controllers_LikeController', "<strong>Users</strong> who like this");
     return $this->renderAjaxContent(UserListBox::widget(['query' => $query, 'title' => $title]));
 }
Esempio n. 27
0
 /**
  * Declines or Deletes Friendship
  */
 public function actionDelete()
 {
     $this->forcePostRequest();
     $friend = User::findOne(['id' => Yii::$app->request->get('userId')]);
     if ($friend === null) {
         throw new \yii\web\HttpException(404, 'User not found!');
     }
     Friendship::cancel(Yii::$app->user->getIdentity(), $friend);
     return $this->redirect($friend->getUrl());
 }
 public function run()
 {
     $range = (int) Setting::Get('shownDays', 'birthday');
     $birthdayCondition = "DATE_ADD(profile.birthday, \n                INTERVAL YEAR(CURDATE())-YEAR(profile.birthday)\n                         + IF(DAYOFYEAR(CURDATE()) > DAYOFYEAR(profile.birthday),1,0)\n                YEAR)  \n            BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL " . $range . " DAY);";
     $users = User::find()->joinWith('profile')->where($birthdayCondition)->limit(10)->all();
     if (count($users) == 0) {
         return;
     }
     return $this->render('birthdayPanel', array('users' => $users));
 }
Esempio n. 29
0
 /**
  * Returns an list of all friends of a user
  */
 public function actionPopup()
 {
     $user = User::findOne(['id' => Yii::$app->request->get('userId')]);
     if ($user === null) {
         throw new \yii\web\HttpException(404, 'Could not find user!');
     }
     $query = Friendship::getFriendsQuery($user);
     $title = '<strong>' . Yii::t('FriendshipModule.base', "Friends") . '</strong>';
     return $this->renderAjaxContent(UserListBox::widget(['query' => $query, 'title' => $title]));
 }
 /**
  * Automatically loads the underlying contentContainer (User/Space) by using
  * the uguid/sguid request parameter
  *
  * @return boolean
  */
 public function init()
 {
     $spaceGuid = Yii::$app->request->get('sguid', '');
     $userGuid = Yii::$app->request->get('uguid', '');
     if ($spaceGuid != "") {
         $this->contentContainer = Space::findOne(['guid' => $spaceGuid]);
         if ($this->contentContainer == null) {
             throw new \yii\web\HttpException(404, Yii::t('base', 'Space not found!'));
         }
         $this->attachBehavior('SpaceControllerBehavior', array('class' => \humhub\modules\space\behaviors\SpaceController::className(), 'space' => $this->contentContainer));
         $this->subLayout = "@humhub/modules/space/views/space/_layout";
     } elseif ($userGuid != "") {
         $this->contentContainer = User::findOne(['guid' => $userGuid]);
         if ($this->contentContainer == null) {
             throw new \yii\web\HttpException(404, Yii::t('base', 'User not found!'));
         }
         $this->attachBehavior('ProfileControllerBehavior', ['class' => \humhub\modules\user\behaviors\ProfileController::className(), 'user' => $this->contentContainer]);
         $this->subLayout = "@humhub/modules/user/views/profile/_layout";
     } else {
         throw new \yii\web\HttpException(500, Yii::t('base', 'Could not determine content container!'));
     }
     /**
      * Auto check access rights to this container
      */
     if ($this->contentContainer != null) {
         if ($this->autoCheckContainerAccess) {
             $this->checkContainerAccess();
         }
     }
     if (!$this->checkModuleIsEnabled()) {
         throw new HttpException(405, Yii::t('base', 'Module is not enabled on this content container!'));
     }
     return parent::init();
 }