Exemplo n.º 1
0
 /**
  * @SuppressWarnings(PHPMD)
  */
 public function run()
 {
     $options = CMDUtils::getOptionsList();
     if (!($service = $this->getService($options))) {
         return $this->printHelp();
     }
     $service->setup($options);
     if (!$service->canRun() || isset($options['--help'])) {
         return $this->printServiceHelp($service);
     }
     $locker = new LockerInDB();
     $lockName = $this->getLockName($service);
     if (isset($options['--unlock'])) {
         $locker->unlock($lockName);
         $this->msg("Service was unlocked. You can run it now.");
         return;
     }
     try {
         $locker->lock($lockName);
     } catch (AlreadyLockedException $e) {
         if (!isset($options['--hiddenLock'])) {
             $this->msg("Service already locked, " . $e->getMessage());
         }
         return;
     }
     try {
         $service->run();
         $locker->unlock($this->getLockName($service));
     } catch (BaseException $e) {
         $locker->unlock($this->getLockName($service));
         DI::get()->container()->get('logger')->error($e->getMessage());
         exit(1);
     }
 }
 public function run()
 {
     $sessionHandler = new DBSessionHandler();
     $config = DI::get()->getConfig();
     $sessionHandler->clean($config->session->lifetime);
     TmpSessionDAO::create()->dropAll();
 }
Exemplo n.º 3
0
 public function run(User $user, $args)
 {
     $args = explode(' ', $args, 2);
     $userName = $args[0];
     if (!isset($args[1])) {
         RespondError::make($user, ['msg' => 'Вы не ввели сообщения']);
         return;
     }
     $text = $args[1];
     $properties = PropertiesDAO::create()->getByUserName($userName);
     if (!$properties->getId()) {
         RespondError::make($user, ['msg' => "{$userName} не зарегистрирован или имя введено не верно"]);
         return;
     }
     $address = UserDAO::create()->getById($properties->getUserId());
     $permissions = new UserActions($user->getUserDAO());
     $actions = $permissions->getAllowed($address);
     if (!in_array(UserActions::MAIL, $actions)) {
         RespondError::make($user, ['msg' => $user->getLang()->getPhrase('NoPermission')]);
         return;
     }
     //@TODO сделать отправку по крону
     //также надо ограничить частоту отправки
     $config = DI::get()->getConfig();
     $mailerName = 'СоциоЧат';
     $headers = "MIME-Version: 1.0 \n" . "From: " . mb_encode_mimeheader($mailerName) . "<" . $config->adminEmail . "> \n" . "Reply-To: " . mb_encode_mimeheader($mailerName) . "<" . $config->adminEmail . "> \n" . "Content-Type: text/html;charset=UTF-8\n";
     $topic = 'Для вас есть сообщение';
     $msg = "<h2>Вам пришло сообщение от пользователя {$user->getProperties()->getName()}</h2>";
     $msg .= '<p>' . htmlentities(strip_tags($text)) . '</p>';
     $msg .= '<hr>';
     $msg .= 'Вернуться в <a href="' . $config->domain->protocol . $config->domain->web . '">СоциоЧат</a>';
     mb_send_mail($address->getEmail(), $topic, $msg, $headers);
     RespondError::make($user, ['msg' => 'Сообщение отправлено!']);
     return ['Сообщение отправлено!', true];
 }
Exemplo n.º 4
0
 public function send($email, $topic, $msg)
 {
     $config = DI::get()->getConfig()->mail;
     $mailerName = $config->name;
     $headers = "MIME-Version: 1.0 \n" . "From: " . mb_encode_mimeheader($mailerName) . "<" . $config->adminEmail . "> \n" . "Reply-To: " . mb_encode_mimeheader($mailerName) . "<" . $config->adminEmail . "> \n" . "Content-Type: text/html;charset=UTF-8\n";
     mb_send_mail($email, $topic, $msg, $headers);
 }
 public function run()
 {
     $config = DI::get()->getConfig();
     $timeOut = $config->onlineMonitoringTimeout;
     // Let it be simple for a while
     $channelId = 1;
     /** @var PropertiesDAO $props */
     foreach (PropertiesDAO::create()->getRegisteredList() as $props) {
         if (!($limit = $props->getOnlineNotificationLimit())) {
             continue;
         }
         $online = OnlineDAO::create();
         if ($online->isUserOnline($channelId, $props->getUserId())) {
             continue;
         }
         $onlineCount = $online->getOnlineCount($channelId);
         if (time() - $timeOut < strtotime($props->getOnlineNotificationLast())) {
             continue;
         }
         if ($onlineCount >= $limit) {
             $user = UserDAO::create()->getById($props->getUserId());
             $list = '';
             foreach ($online->getOnlineList($channelId) as $userId => $userName) {
                 $list .= "<li>{$userName}</li>";
             }
             $msg = "<h2>Достижение заданного онлайна в SocioChat.Me</h2>\n<p>Вы получили данное письмо, потому что пожелали уведомить вас, когда в чате будет более {$limit} человек.</p>\n<p>Сейчас на основном канале общается {$onlineCount} человек</p>\n<ul>{$list}</ul>\n<p><a href=\"" . $config->domain->protocol . $config->domain->web . "\">Присоединяйтесь</a>!</p>";
             $message = MailQueueDAO::create();
             $message->setEmail($user->getEmail())->setTopic('SocioChat.Me - Заходите к нам!')->setMessage($msg);
             $message->save();
             $props->setOnlineNotificationLast(DbQueryHelper::timestamp2date());
             $props->save(false);
         }
     }
 }
 /**
  * @param User $user
  */
 public function clean(User $user)
 {
     $channelId = $user->getChannelId();
     if (DI::get()->getUsers()->getClientsCount($channelId) == 0 && isset($this->channels[$channelId]) && $this->channels[$channelId]->isPrivate()) {
         unset($this->channels[$channelId]);
     }
 }
Exemplo n.º 7
0
 public function getServiceInstance()
 {
     $service = DI::get()->spawn($this->getName());
     if (!$service instanceof CronService) {
         throw new BaseException("Expects {$this->getName()} implements CronService interface");
     }
     return $service;
 }
 public function handleRequest(ChainContainer $chain)
 {
     $user = $chain->getFrom();
     $users = DI::get()->getUsers();
     $channels = ChannelsCollection::get();
     MainChatDualsHandler::run($user, $users);
     MainChatPrivateHandler::run($user, $users, $channels);
 }
 private function unbanResponse(User $user, UserDAO $unBanUserDAO)
 {
     $response = (new MessageResponse())->setMsg(MsgToken::create('UserIsUnbanned', $unBanUserDAO->getPropeties()->getName()))->setTime(null)->setChannelId($user->getChannelId())->setGuests(DI::get()->getUsers()->getUsersByChatId($user->getChannelId()));
     (new UserCollection())->attach($user)->setResponse($response)->notify(false);
     if ($unBanUser = DI::get()->getUsers()->getClientById($unBanUserDAO->getId())) {
         $response = (new MessageResponse())->setMsg(MsgToken::create('UserUnbannedYou', $user->getProperties()->getName()))->setChannelId($unBanUser->getChannelId())->setTime(null);
         (new UserCollection())->attach($unBanUser)->setResponse($response)->notify(false);
     }
 }
Exemplo n.º 10
0
 /**
  * @param int $timId
  * @param int $sexId
  * @return User|PHPUnit_Framework_MockObject_MockObject
  */
 protected function getMockUser($timId = TimEnum::ILE, $sexId = SexEnum::MALE)
 {
     $user = $this->getMock(User::class, ['getId', 'getChannelId', 'getProperties'], [], '', false);
     $user->expects($this->any())->method('getId')->willReturn($this->userSeq);
     $user->expects($this->any())->method('getProperties')->willReturn($this->getMockProperties($timId, $sexId));
     $this->userSeq++;
     DI::get()->getUsers()->attach($user);
     return $user;
 }
Exemplo n.º 11
0
 public function setChannels(ChannelsCollection $channels)
 {
     $users = DI::get()->getUsers();
     foreach ($channels->getChannels() as $channel) {
         if (!$channel->isPrivate()) {
             $this->channels[$channel->getId()] = ['name' => $channel->getName(), 'usersCount' => $users->getClientsCount($channel->getId())];
         }
     }
     return $this;
 }
Exemplo n.º 12
0
 public function handleRequest(ChainContainer $chain)
 {
     $clients = DI::get()->getUsers();
     $conn = $chain->getFrom()->getConnectionId();
     if (!($user = $clients->getClientByConnectionId($conn))) {
         return false;
     }
     $chain->setFrom($user);
     return true;
 }
Exemplo n.º 13
0
 /**
  * @param User $userInviter
  * @param User $desiredUser
  * @param callable $timoutResponse
  * @return array
  */
 private function createInvitation(User $userInviter, User $desiredUser, callable $timoutResponse)
 {
     $timer = DI::get()->container()->get('eventloop')->addTimer($this->getTTL(), function () use($userInviter, $desiredUser, $timoutResponse) {
         $this->clearRequest($userInviter, $desiredUser);
         $timoutResponse($userInviter, $desiredUser);
     });
     $matchUser = ['inviterUserId' => $userInviter->getId(), 'time' => time(), 'timer' => $timer];
     $token = $this->getToken($userInviter, $desiredUser);
     $this->queue[$token] = $matchUser;
     return $matchUser;
 }
Exemplo n.º 14
0
 /**
  * C-o-R pattern
  * @param Chain $chain input stream
  * @return false|null|true
  */
 public function handleRequest(Chain $chain)
 {
     $request = $chain->getRequest();
     $text = strip_tags(htmlentities(trim($request['msg'])));
     $msgMaxLength = DI::get()->getConfig()->msgMaxLength;
     if (mb_strlen($text) > $msgMaxLength) {
         $text = mb_strcut($text, 0, $msgMaxLength) . self::CUT;
     }
     $request['msg'] = $text;
     $chain->setRequest($request);
 }
Exemplo n.º 15
0
 public function updateKeyOfUserId($oldUserId)
 {
     if (isset($this->users[$oldUserId])) {
         $user = $this->users[$oldUserId];
         if ($user->getId() != $oldUserId) {
             DI::get()->getLogger()->info("UserCollection::updateKey({$oldUserId})");
             $this->users[$user->getId()] = $user;
             unset($this->users[$oldUserId]);
         }
     }
 }
Exemplo n.º 16
0
 public function store($sessionId, $userId)
 {
     $session = SessionDAO::create();
     $session->getBySessionId($sessionId);
     $session->setSessionId($sessionId)->setAccessTime(date(self::TIMESTAMP))->setUserId($userId);
     try {
         $session->save();
     } catch (\PDOException $e) {
         DI::get()->getLogger()->error($e->getMessage() . ': ' . $e->getTraceAsString());
     }
 }
Exemplo n.º 17
0
 public function run(User $user, $args)
 {
     $args = explode(' ', $args);
     $name = $args[0];
     $users = DI::get()->getUsers();
     if (!($targetUser = $users->getClientByName($name))) {
         RespondError::make($user, ['userId' => "{$name} not found"]);
         return;
     }
     return [$targetUser->getProperties()->getName() . ' ip = ' . $targetUser->getIp(), true];
 }
Exemplo n.º 18
0
 public function run(User $user, $args)
 {
     $users = DI::get()->getUsers()->getAll();
     $logger = DI::get()->getLogger();
     /** @var User $user */
     foreach ($users as $user) {
         $user->save(true);
         $logger->info('User data for ' . $user->getId() . ' is saved.');
     }
     return ['User data has flushed to disk!', true];
 }
 private static function sendRenewPositions(array $userIds, UserCollection $users)
 {
     if (empty($userIds)) {
         return;
     }
     $notification = new UserCollection();
     foreach ($userIds as $userId) {
         $user = $users->getClientById($userId);
         $response = (new MessageResponse())->setGuests(DI::get()->getUsers()->getUsersByChatId($user->getChannelId()))->setChannelId($user->getChannelId());
         $notification->attach($user)->setResponse($response);
     }
     $notification->notify(false);
 }
Exemplo n.º 20
0
 public function run(User $user, $args)
 {
     $text = explode(' ', $args, 2);
     $assHoleName = $text[0];
     $users = DI::get()->getUsers();
     if (!($assHole = $users->getClientByName($assHoleName))) {
         return ["{$assHoleName} not found", 1];
     }
     $userDAO = $assHole->getUserDAO()->setBanned(true);
     $userDAO->save(false);
     $assHole->setAsyncDetach(false)->send(['disconnect' => 1, 'msg' => isset($text[1]) ? $text[1] : null]);
     Chat::get()->onClose($assHole->getConnection());
     return ["{$assHoleName} кикнут", false];
 }
Exemplo n.º 21
0
 /**
  * @param array $guests
  * @return $this
  */
 public function setGuests(array $guests = null)
 {
     if ($guests === null) {
         $this->guests = null;
         return $this;
     }
     $avatarDir = DI::get()->getConfig()->uploads->avatars->wwwfolder . DIRECTORY_SEPARATOR;
     foreach ($guests as $user) {
         /* @var $user User */
         $props = $user->getProperties();
         $this->guests[] = [PropertiesDAO::USER_ID => $props->getUserId(), PropertiesDAO::NAME => $props->getName(), PropertiesDAO::TIM => $props->getTim()->getName(), PropertiesDAO::SEX => $props->getSex()->getName(), PropertiesDAO::AVATAR . 'Thumb' => $props->getAvatarThumb() ? $avatarDir . $props->getAvatarThumb() : null, PropertiesDAO::CITY => $props->getCity(), PropertiesDAO::BIRTH => $props->getAge(), PropertiesDAO::KARMA => $props->getKarma()];
     }
     return $this;
 }
Exemplo n.º 22
0
 public function setOnlineList($channelId = 1)
 {
     $key = self::KEY . $channelId;
     $users = DI::get()->getUsers()->getUsersByChatId($channelId);
     if (count($users) == 0) {
         $this->memcache->delete($key);
         return $this;
     }
     $list = [];
     foreach ($users as $user) {
         $list[$user->getId()] = $user->getProperties()->getName();
     }
     $this->memcache->set($key, json_encode($list));
     return $this;
 }
Exemplo n.º 23
0
 public function matchDual(User $user)
 {
     if ($user->isInPrivateChat() || !$this->isCorrectUser($user)) {
         return false;
     }
     $tim = $user->getProperties()->getTim();
     if (!$this->dualExists($user)) {
         $this->register($user);
         return false;
     }
     $queue = $this->getDualQueue($user)[$this->getDualTim($tim)];
     $queue = array_flip($queue);
     $userId = $queue[1];
     $this->deleteByUser(DI::get()->getUsers()->getClientById($userId));
     return $userId;
 }
Exemplo n.º 24
0
 /**
  * @param User $user
  * @param array $timers
  * @return array
  */
 private function setTimer(User $user, array &$timers)
 {
     $container = DI::get()->container();
     $loop = $container->get('eventloop');
     $config = $container->get('config');
     $timeout = $config->flood->timeout;
     $penalty = $config->flood->penalty;
     $timerCallback = function () use($user, &$timers) {
         unset($timers[$user->getId()]);
     };
     if (isset($timers[$user->getId()])) {
         $loop->cancelTimer($timers[$user->getId()]);
         $timeout += $penalty;
     }
     $timer = $loop->addTimer($timeout, $timerCallback);
     $timers[$user->getId()] = $timer;
 }
Exemplo n.º 25
0
 private function searchUser(User $from, $userId)
 {
     if ($userId == '') {
         return null;
     }
     if ($userId == $from->getId()) {
         return $from;
     }
     $form = (new Form())->import([UserDAO::ID => $userId])->addRule(UserDAO::ID, Rules::isUserOnline(), $from->getLang()->getPhrase('UserIsNotOnline'));
     if (!$form->validate()) {
         RespondError::make($from, $form->getErrors());
         DI::get()->getLogger()->warn("Trying to find userId = {$userId} for private message but not found", [__CLASS__]);
         return false;
     }
     $recipient = $form->getResult(UserDAO::ID);
     /* @var $recipient User */
     return $recipient;
 }
Exemplo n.º 26
0
 /**
  * @param User $user
  */
 private function handleHistory(User $user)
 {
     ChannelNotifier::uploadHistory($user);
     $ds = DIRECTORY_SEPARATOR;
     if (file_exists(ROOT . $ds . 'www' . $ds . 'motd.txt') && !$user->getLastMsgId()) {
         $motd = file_get_contents(ROOT . $ds . 'www' . $ds . 'motd.txt');
         $motd .= "<br>Доступны каналы:<br>";
         foreach (ChannelsCollection::get()->getChannels() as $channel) {
             if ($channel->isPrivate()) {
                 continue;
             }
             $motd .= '(' . DI::get()->getUsers()->getClientsCount($channel->getId()) . ') ' . $channel->getName() . '<br>';
         }
         $client = (new UserCollection())->attach($user);
         $response = (new MessageResponse())->setChannelId($user->getChannelId())->setMsg(MsgRaw::create($motd));
         $client->setResponse($response)->notify(false);
     }
 }
Exemplo n.º 27
0
 public function getPhraseByArray(array $args)
 {
     $token = array_shift($args);
     $logger = DI::get()->getLogger();
     if (!$this->lexicon) {
         $logger->warn('No localization was set', [__CLASS__]);
         return $token . '|' . implode('|', $args);
     }
     $scope = $this->lexicon;
     foreach (explode('.', $token) as $part) {
         if (!($newScope = $scope->get($part))) {
             $logger->warn('No localization was matched for ' . $part . ' (lang = ' . $this->lang . ')', [__CLASS__]);
             return $token . '|' . implode('|', $args);
         }
         $scope = $newScope;
     }
     return vsprintf($scope, $args);
 }
 public function run()
 {
     $dir = ROOT . DIRECTORY_SEPARATOR . DI::get()->getConfig()->uploads->avatars->dir . DIRECTORY_SEPARATOR;
     $fileList = glob("{$dir}*.{jpg,png}", GLOB_BRACE);
     $fileList = array_flip($fileList);
     echo "Found images: " . count($fileList) . "\n";
     print_r($fileList);
     /** @var PropertiesDAO $userProp */
     foreach (PropertiesDAO::create()->getListWithAvatars() as $userProp) {
         if (file_exists($dir . $userProp->getAvatarImg())) {
             unset($fileList[$dir . $userProp->getAvatarImg()]);
         } else {
             $userProp->setAvatarImg(null);
         }
         if (file_exists($dir . $userProp->getAvatarThumb())) {
             unset($fileList[$dir . $userProp->getAvatarThumb()]);
         } else {
             $userProp->setAvatarImg(null);
         }
         if (file_exists($dir . $userProp->getAvatarThumb2X())) {
             unset($fileList[$dir . $userProp->getAvatarThumb2X()]);
         } else {
             $userProp->setAvatarImg(null);
         }
         if (file_exists($dir . $userProp->getAvatarImg2X())) {
             unset($fileList[$dir . $userProp->getAvatarImg2X()]);
         } else {
             $userProp->setAvatarImg(null);
         }
         if ($userProp->getAvatarImg() === null) {
             $userProp->save();
             echo "Fixed avatar link to null for " . $userProp->getName() . "\n";
         }
     }
     $fileList = array_keys($fileList);
     echo "Images to delete: " . count($fileList) . "\n";
     foreach ($fileList as $file) {
         unlink($file);
     }
 }
Exemplo n.º 29
0
 private function detacher(User $user, Logger $logger)
 {
     return function () use($user, $logger) {
         $clients = DI::get()->getUsers();
         $clients->detach($user);
         $logger->info("OnClose closure:\n                closed userId = {$user->getId()},\n                connId = {$user->getConnectionId()}\n                Total user count {$clients->getTotalCount()}\n", [__CLASS__]);
         $this->notifyOnClose($user, $clients);
         $this->cleanPendingQueue($user);
         ChannelsCollection::get()->clean($user);
         $props = $user->getProperties();
         $props->setOnlineCount(time() - $user->getLoginTime() + $props->getOnlineCount());
         $online = OnlineDAO::create();
         $online->setOnlineList($user->getChannelId());
         $user->save();
         //update access time
         $sessionHandler = DI::get()->getSession();
         $sessionHandler->store($user->getToken(), $user->getId());
         unset($clients);
         unset($sessionHandler);
         unset($user);
     };
 }
Exemplo n.º 30
0
 private function onResponse(Chain $chain)
 {
     return function (Response $response) use($chain) {
         BufferedSink::createPromise($response)->then(function ($body) use($chain) {
             $logger = DI::get()->getLogger();
             $logger->info('Got http response: ' . $body);
             if (!($json = json_decode($body, 1))) {
                 return;
             }
             $logger->info('JSON decoded');
             $channelId = $chain->getUser()->getChannelId();
             /** @var UserCollection $users */
             $users = DI::get()->getUsers();
             $response = (new MusicResponse())->setInfo($json)->setChannelId($channelId);
             $loop = DI::get()->container()->get('eventloop');
             $loop->addTimer(1, function () use($users, $response, $logger) {
                 $users->setResponse($response)->notify(false);
                 $logger->info('Sent MusicResponse!');
             });
             $channel = ChannelsCollection::get()->getChannelById($channelId);
             $history = $channel->getHistory(0);
             foreach ($history as $k => $part) {
                 /** @var Msg $msgObj */
                 $msgObj = $part['msg'];
                 $string = $msgObj->getMsg($chain->getUser()->getLang());
                 if (!preg_match('~id="music-(' . $json['track_id'] . ')"~u', $string)) {
                     continue;
                 }
                 $logger->info('Replacing corresponding history row');
                 $string = str_replace('id="music-' . $json['track_id'] . '" data-src=""><span class="glyphicon glyphicon-play-circle">' . '</span> <span class="audio-title">...</span>', 'id="music-' . $json['track_id'] . '" data-src="' . $json['url'] . '" bind-play-click="1">' . '<span class="glyphicon glyphicon-play-circle"></span> ' . '<span class="audio-title">' . $json['artist'] . ' - ' . $json['track'] . '</span>', $string);
                 $part['msg'] = MsgRaw::create($string);
                 $channel->setRow($k, $part);
             }
         });
     };
 }