コード例 #1
0
ファイル: Session.php プロジェクト: difra-org/difra
 public static function load()
 {
     if (Auth::getInstance()->isAuthorized()) {
         return;
     }
     if (!isset($_COOKIE['resume']) or strlen($_COOKIE['resume']) != 48) {
         return;
     }
     try {
         // find session in db
         $session = DB::getInstance()->fetchRow("SELECT `ip`, `user` FROM `user_session` WHERE `session`=?", [$_COOKIE['resume']]);
         if (empty($session)) {
             throw new Exception('Long session not found in database');
         }
         // check ip
         if ($session['ip'] & ip2long(Users::IP_MASK) != ip2long($_SERVER['REMOTE_ADDR']) & ip2long(Users::IP_MASK)) {
             throw new Exception('Long session IP does not match');
         }
         // find user
         $user = User::getById($session['user']);
         $user->login();
     } catch (Exception $ex) {
         self::remove();
     }
 }
コード例 #2
0
ファイル: post.php プロジェクト: difra-org/difra
 /**
  * Создаёт пост (или несколько) из результатов выборки из базы
  * @static
  * @param array $data
  * @return array|null
  */
 public static function makeList($data)
 {
     // нет данных
     if (empty($data) or !is_array($data)) {
         return null;
     }
     // в $data один пост
     if (isset($data['id'])) {
         $data = [$data];
     }
     $groups = [];
     $Auth = Auth::getInstance();
     if ($userId = $Auth->getEmail()) {
         $groups = Group::getOwnedGroupsIds($userId);
     }
     $posts = [];
     foreach ($data as $row) {
         $post = new self();
         foreach ($row as $k => $v) {
             if (property_exists($post, $k)) {
                 $post->{$k} = $v;
             }
         }
         if ($userId and $post->getUser() == $userId || $Auth->isModerator()) {
             $post->canModify = true;
         } elseif ($userId and $post->groupId and in_array($post->groupId, $groups)) {
             $post->canModify = true;
         } else {
             $post->canModify = false;
         }
         $posts[] = $post;
     }
     return $posts;
 }
コード例 #3
0
ファイル: friends.php プロジェクト: difra-org/difra
 public function addAjaxAction(\Difra\Param\AnyString $blogId)
 {
     if (!\Difra\Auth::getInstance()->getEmail()) {
         $this->ajax->notify(Difra\Locales::getInstance()->getXPath('notify/need_reg'));
         return;
     }
     $blog = \Difra\Plugins\Blogs::getInstance();
     $blog->addFriend($blogId);
     // TODO: вывод ошибок
     $this->ajax->redirect($_SERVER['HTTP_REFERER']);
 }
コード例 #4
0
ファイル: comments.php プロジェクト: difra-org/difra
 public function add($data)
 {
     // module moduleId replyId newComment
     if (empty($data['module']) or !trim($data['module'])) {
         throw new \Difra\Exception('Missing module name for comments');
     }
     if (empty($data['moduleId'])) {
         throw new \Difra\Exception('Comments module id is missing or invalid');
     }
     if (empty($data['replyId'])) {
         $data['replyId'] = 0;
     }
     if (empty($data['text']) or !trim($data['text'])) {
         return false;
     }
     $auth = \Difra\Auth::getInstance();
     $auth->required();
     $data['user'] = $auth->getEmail();
     return Comments\Comment::create($data);
 }
コード例 #5
0
ファイル: Controller.php プロジェクト: difra-org/difra
 /**
  * Choose action
  */
 private function chooseAction()
 {
     $method = null;
     if (Request::isAjax() and Action::$methodAjaxAuth and Auth::getInstance()->isAuthorized()) {
         $this->isAjaxAction = true;
         $method = 'methodAjaxAuth';
     } elseif (Request::isAjax() and Action::$methodAjax) {
         $this->isAjaxAction = true;
         $method = 'methodAjax';
     } elseif (Action::$methodAuth and Auth::getInstance()->isAuthorized()) {
         $method = 'methodAuth';
     } elseif (Action::$method) {
         $method = 'method';
     } elseif (Request::isAjax() and Action::$methodAjaxAuth) {
         self::$parameters = [];
         throw new View\HttpError(401);
     } elseif (Action::$methodAuth) {
         self::$parameters = [];
         throw new View\HttpError(401);
     } else {
         throw new View\HttpError(404);
     }
     $this->method = $method;
 }
コード例 #6
0
ファイル: blogs.php プロジェクト: difra-org/difra
 /**
  * Делает +1 для статистики поста
  * @param      $postId
  * @param null $groupId
  * @param null $userId
  * @return bool
  */
 public function savePostStat($postId, $groupId = null, $userId = null)
 {
     $Cache = \Difra\Cache::getInstance();
     $db = \Difra\MySQL::getInstance();
     if (!$db->fetchRow("SHOW TABLES LIKE 'blogs_stat'")) {
         return false;
     }
     $postsStat = $Cache->get('posts_stat');
     $client = \Difra\Auth::getInstance()->getEmail();
     if (is_null($client)) {
         $client = $_SERVER['REMOTE_ADDR'];
     }
     $groupAdd = $userAdd = '';
     if (!is_null($groupId)) {
         $groupAdd = ", `group_id`='" . intval($groupId) . "' ";
     }
     if (!is_null($userId)) {
         $userAdd = ", `user_id`='" . intval($userId) . "' ";
     }
     $query = "INSERT INTO `blogs_stat` SET `date`='" . date('Y-m-d', time()) . "', `post_id`='" . intval($postId) . "', `count`=1 " . $groupAdd . $userAdd . " ON DUPLICATE KEY UPDATE `count`=`count`+1";
     if (isset($postsStat[$client])) {
         if (!in_array($postId, $postsStat[$client])) {
             if (count($postsStat[$client]) == 3) {
                 array_shift($postsStat[$client]);
             }
             $postsStat[$client][] = $postId;
             $Cache->put('posts_stat', $postsStat);
             $db->query($query);
             return true;
         } else {
             return false;
         }
     }
     $postsStat[$client][] = $postId;
     $Cache->put('posts_stat', $postsStat);
     $db->query($query);
     return true;
 }
コード例 #7
0
ファイル: announcements.php プロジェクト: difra-org/difra
 /**
  * Проверяет является ли пользователь владельцем анонса
  * @param $eventId
  * @param $userId
  * @return bool
  */
 public function checkOnwer($eventId, $userId)
 {
     if (Auth::getInstance()->isModerator()) {
         return true;
     }
     $db = MySQL::getInstance();
     $query = "SELECT `id` FROM `announcements` WHERE `id`='" . intval($eventId) . "' AND `user`='" . intval($userId) . "'";
     $res = $db->fetchOne($query);
     return !empty($res) ? true : false;
 }
コード例 #8
0
ファイル: XML.php プロジェクト: difra-org/difra
 /**
  * Fill output XML with some common data
  * @param \DOMDocument|null $xml
  * @param null $instance
  */
 public static function fillXML(&$xml = null, $instance = null)
 {
     $controller = Controller::getInstance();
     if (is_null($xml)) {
         $xml = $controller->xml;
         $node = $controller->realRoot;
     } else {
         $node = $xml->documentElement;
     }
     Debugger::addLine('Filling XML data for render: Started');
     // TODO: sync this with Envi::getState()
     $node->setAttribute('lang', Envi\Setup::getLocale());
     $node->setAttribute('site', Envi::getSubsite());
     $node->setAttribute('host', $host = Envi::getHost());
     $node->setAttribute('mainhost', $mainhost = Envi::getHost(true));
     $node->setAttribute('protocol', Envi::getProtocol());
     $node->setAttribute('fullhost', Envi::getURLPrefix());
     $node->setAttribute('instance', $instance ? $instance : View::$instance);
     $node->setAttribute('uri', Envi::getUri());
     $node->setAttribute('controllerUri', Action::getControllerUri());
     if ($host != $mainhost) {
         $node->setAttribute('urlprefix', Envi::getURLPrefix(true));
     }
     // get user agent
     Envi\UserAgent::getUserAgentXML($node);
     // ajax flag
     $node->setAttribute('ajax', (Request::isAjax() or isset($_SERVER['HTTP_X_REQUESTED_WITH']) and $_SERVER['HTTP_X_REQUESTED_WITH'] == 'SwitchPage') ? '1' : '0');
     $node->setAttribute('switcher', (!$controller->cache and isset($_SERVER['HTTP_X_REQUESTED_WITH']) and $_SERVER['HTTP_X_REQUESTED_WITH'] == 'SwitchPage') ? '1' : '0');
     // build and version number
     $node->setAttribute('build', Version::getBuild());
     $node->setAttribute('framework', Version::getFrameworkVersion(false));
     $node->setAttribute('frameworkLong', Version::getFrameworkVersion(true));
     // date
     /** @var $dateNode \DOMElement */
     $dateNode = $node->appendChild($xml->createElement('date'));
     $dateKeys = ['d', 'e', 'A', 'a', 'm', 'B', 'b', 'Y', 'y', 'c', 'x', 'H', 'M', 'S'];
     $dateValues = explode('|', strftime('%' . implode('|%', $dateKeys)));
     $dateCombined = array_combine($dateKeys, $dateValues);
     $dateNode->setAttribute('ts', time());
     foreach ($dateCombined as $k => $v) {
         $dateNode->setAttribute($k, $v);
     }
     // debug flag
     $node->setAttribute('debug', Debugger::isEnabled() ? '1' : '0');
     // config values (for js variable)
     $configNode = $node->appendChild($xml->createElement('config'));
     Envi::getStateXML($configNode);
     // menu
     if ($menuResource = Resourcer::getInstance('menu')->compile(View::$instance)) {
         $menuXML = new \DOMDocument();
         $menuXML->loadXML($menuResource);
         $node->appendChild($xml->importNode($menuXML->documentElement, true));
     }
     // auth
     Auth::getInstance()->getAuthXML($node);
     // locale
     Locales::getInstance()->getLocaleXML($node);
     // Add config js object
     $config = Envi::getState();
     $confJS = '';
     foreach ($config as $k => $v) {
         $confJS .= "config.{$k}='" . addslashes($v) . "';";
     }
     $node->setAttribute('jsConfig', $confJS);
     Debugger::addLine('Filling XML data for render: Done');
     Debugger::debugXML($node);
 }
コード例 #9
0
ファイル: post.php プロジェクト: difra-org/difra
 public function deleteAjaxActionAuth(Param\AjaxString $id = null)
 {
     $id = $id ? $id->val() : null;
     if (!($post = Blogs\Post::getById($id))) {
         $this->ajax->display(Difra\Locales::getInstance()->getXPath('blogs/notifies/post_not_found'));
         die;
     }
     $Auth = \Difra\Auth::getInstance();
     if ($post->getUser() != $Auth->getEmail() && !$Auth->isModerator()) {
         $group = $post->getBlog()->getGroup();
         if (!$group or $group->getOwner() != \Difra\Auth::getInstance()->getEmail()) {
             $this->ajax->display(Difra\Locales::getInstance()->getXPath('blogs/notifies/edit_post_denied'));
             die;
         }
     }
     $post::delete($id);
     $this->ajax->setResponse('success', true);
 }
コード例 #10
0
ファイル: Debugger.php プロジェクト: difra-org/difra
    /**
     * If page rendered too long, report to developers
     * @throws Exception
     */
    public static function checkSlow()
    {
        // TODO: merge this method with Exception::sendNotification()
        $time = self::getTimer();
        if (!$time <= 1) {
            return;
        }
        // don't send notifications on development environment
        if (!Envi::isProduction()) {
            return;
        }
        $notificationMail = self::getNotificationMail();
        // no notification mail is set
        if (!$notificationMail) {
            return;
        }
        $output = '<pre>';
        foreach (self::$output as $line) {
            if (!isset($line['type'])) {
                $line['type'] = null;
            }
            $output .= "{$line['timer']}\t{$line['class']}\t{$line['type']}\t{$line['message']}\n";
        }
        $date = date('r');
        $server = print_r($_SERVER, true);
        $post = print_r($_POST, true);
        $cookie = print_r($_COOKIE, true);
        $host = Envi::getHost();
        $uri = Envi::getUri();
        $user = Auth::getInstance()->getEmail();
        $output .= <<<MSG

Page:\t{$uri}
Time:\t{$date}
Host:\t{$host}
User:\t{$user}

\$_SERVER:
{$server}

\$_POST:
{$post}

\$_COOKIE:
{$cookie}
MSG;
        $output .= '</pre>';
        Mailer::getInstance()->sendMail(self::getNotificationMail(), 'Slow script', print_r($output, true));
    }
コード例 #11
0
ファイル: Logger.php プロジェクト: difra-org/difra
 /**
  * Log object
  * @param $message
  * @return array
  */
 protected function getLogObj($message)
 {
     $obj = ['timestamp' => time(), 'date' => date('r'), 'message' => $message, 'pid' => getmypid()];
     if (!empty($_SERVER['REMOTE_ADDR'])) {
         $obj['ip'] = $_SERVER['REMOTE_ADDR'];
     }
     if ($a = Auth::getInstance()->getLogin()) {
         $obj['user'] = $a;
     }
     return $obj;
 }
コード例 #12
0
ファイル: User.php プロジェクト: difra-org/difra
 /**
  * Log out current user
  */
 public static function logout()
 {
     Session::remove();
     Auth::getInstance()->logout();
 }
コード例 #13
0
ファイル: comment.php プロジェクト: difra-org/difra
 public static function checkDeleteRights($id, $module)
 {
     $db = \Difra\MySQL::getInstance();
     $parentOwner = false;
     switch ($module) {
         case 'blogs':
             $query = "SELECT bl.`user`, bl.`group`\n\t\t\t\t\t\tFROM `blogs_posts` bp\n\t\t\t\t\t\tRIGHT JOIN `blogs` AS `bl` ON bl.`id`=bp.`blog`\n\t\t\t\t\t\tWHERE bp.`id`='" . intval($id) . "'";
             break;
         case 'albums':
             $query = "SELECT al.`group_id` as `group`\n\t\t\t\t\t\tFROM `albums` al\n\t\t\t\t\t\tWHERE al.`id` = '" . intval($id) . "'";
             break;
         default:
             $query = false;
     }
     if ($query) {
         $parentOwner = $db->fetchRow($query);
     }
     $groups = [];
     $Auth = \Difra\Auth::getInstance();
     $userId = $Auth->getEmail();
     if ($userId && \Difra\Plugger::getInstance()->isEnabled('blogs')) {
         $groups = \Difra\Plugins\Blogs\Group::getOwnedGroupsIds($userId);
     }
     $commentData = $db->fetchRow("SELECT `user` FROM `{$module}_comments` WHERE `id`='" . intval($id) . "'");
     if ($userId && ($userId == $commentData['user'] || $Auth->isModerator())) {
         return true;
     } elseif ($userId && $parentOwner && in_array($parentOwner['group'], $groups)) {
         return true;
     } elseif ($userId && $parentOwner && isset($parentOwner['user']) && $parentOwner['user'] == $userId) {
         return true;
     }
     return false;
 }
コード例 #14
0
ファイル: index.php プロジェクト: difra-org/difra
 public function indexAction(Param\AnyString $nickname = null, Param\NamedInt $page = null)
 {
     $page = $page ? $page->val() : 1;
     if ($nickname) {
         // получаем $userId по никнейму
         $nickname = rawurldecode($nickname);
         if (!($userId = Difra\Additionals::getAdditionalId('users', 'nickname', $nickname))) {
             $this->view->httpError(404);
             return;
         }
         /** @var \DOMElement $userNode */
         $userNode = $this->root->appendChild($this->xml->createElement('user'));
         $userNode->setAttribute('id', $userId);
         \Difra\Additionals::getAdditionalsXml('users', $userId, $userNode);
         // /user/имя
         if (empty($this->action->parameters)) {
             $auth = \Difra\Auth::getInstance();
             $canModify = ($auth->isAuthorized() and $userId == $auth->getEmail());
             // виджет данных юзера
             /** @var \DOMElement $blogsViewNode */
             $blogsViewNode = $this->root->appendChild($this->xml->createElement('userInfoWidget'));
             $blogsViewNode->setAttribute('left', 1);
             $blogsViewNode = $this->root->appendChild($this->xml->createElement('blogsView'));
             $blogsViewNode->setAttribute('left', 1);
             $blogsViewNode->setAttribute('link', '/blogs/' . rawurlencode($nickname));
             $blogsViewNode->setAttribute('canModify', $canModify ? '1' : '0');
             $blogId = Blogs::getInstance()->getUserBlogXML($blogsViewNode, $userId, $page);
             if ($auth->isAuthorized()) {
                 if ($canModify) {
                     /** @var \DOMElement $blogsControlNode */
                     $blogsControlNode = $this->root->appendChild($this->xml->createElement('blogsControl'));
                     $blogsControlNode->setAttribute('right', 1);
                     $blogsControlNode->setAttribute('addPrefix', 1);
                 }
             }
             // виджет "я в группах"
             /** @var \DOMElement $myGroupsNode */
             $myGroupsNode = $this->root->appendChild($this->xml->createElement('myGroupsWidget'));
             $myGroupsNode->setAttribute('right', 1);
             \Difra\Plugins\Blogs\Group::getUsersGroups($userId, $myGroupsNode);
             // виджет избранных блогов
             /** @var \DOMElement $friendsNode */
             $friendsNode = $this->root->appendChild($this->xml->createElement('friendsWidget'));
             $friendsNode->setAttribute('right', 1);
             \Difra\Plugins\Blogs\Blog::getFriendsPreviewXML($auth->getEmail(), $friendsNode);
             if ($userId != $auth->getEmail()) {
                 $friendsNode->setAttribute('user', $auth->getEmail());
                 $friendsNode->setAttribute('canAdd', $blogId);
             }
             // /user/имя/15/заголовок
         } elseif (sizeof($this->action->parameters) == 2) {
             $postId = $this->action->parameters[0];
             if (!ctype_digit($postId)) {
                 $this->view->httpError(404);
                 return;
             }
             $postLink = rawurldecode($this->action->parameters[1]);
             if (!($post = Blogs::getInstance()->getPost($userId, $postId))) {
                 $this->view->httpError(404);
                 return;
             }
             if ($postLink != $post->getLink()) {
                 $this->view->redirect("/blogs/{$nickname}/{$postId}/" . $post->getLink());
                 return;
             }
             $this->action->parameters = [];
             // виджет "я в группах"
             $myGroupsNode = $this->root->appendChild($this->xml->createElement('myGroupsWidget'));
             $myGroupsNode->setAttribute('right', 1);
             \Difra\Plugins\Blogs\Group::getUsersGroups($userId, $myGroupsNode);
             // виджет данных юзера
             $blogsViewNode = $this->root->appendChild($this->xml->createElement('userInfoWidget'));
             $blogsViewNode->setAttribute('left', 1);
             /** @var \DOMElement $blogsSingle */
             $blogsSingle = $this->root->appendChild($this->xml->createElement('blogsSingle'));
             $blogsSingle->setAttribute('left', 1);
             $post->getXML($blogsSingle, true);
             /** @var \DOMElement $comments */
             $comments = $this->root->appendChild($this->xml->createElement('comments'));
             $comments->setAttribute('left', 1);
             \Difra\Plugins\Comments::getInstance()->getCommentsXML($comments, 'blogs', $postId, $page);
             // виджет избранных блогов
             $friendsNode = $this->root->appendChild($this->xml->createElement('friendsWidget'));
             $friendsNode->setAttribute('right', 1);
             $auth = \Difra\Auth::getInstance();
             \Difra\Plugins\Blogs\Blog::getFriendsPreviewXML($auth->getEmail(), $friendsNode);
             if ($userId != $auth->getEmail()) {
                 $friendsNode->setAttribute('user', $auth->getEmail());
                 $friendsNode->setAttribute('canAdd', $post->getBlogId());
             }
             // статистика для поста
             Blogs::getInstance()->savePostStat($postId, null, $userId);
         } else {
             $this->view->httpError(404);
         }
     } else {
         $blogsViewNode = $this->root->appendChild($this->xml->createElement('blogsAllView'));
         $blogsViewNode->setAttribute('left', 1);
         $blogsViewNode->setAttribute('link', '/blogs');
         Difra\Plugins\Blogs::getInstance()->getAllPostsXML($blogsViewNode, $page);
         if (Difra\Auth::getInstance()->isAuthorized()) {
             /** @var \DOMElement $mypageWidget */
             $mypageWidget = $this->root->appendChild($this->xml->createElement('myPageWidget'));
             $mypageWidget->setAttribute('right', 1);
         }
         /** @var \DOMElement $controlNode */
         $controlNode = $this->root->appendChild($this->xml->createElement('artistControl'));
         $controlNode->setAttribute('right', 1);
         // TODO: вынести работу с тэгами в отдельный диспатчер
         $Tags = Difra\Plugins\Tags::getInstance();
         if ($Tags->getCloudXml('posts', $this->root)) {
             $controlNode = $this->root->appendChild($this->xml->createElement('postsTags'));
             $controlNode->setAttribute('right', 1);
         }
     }
 }