Example #1
0
    /**
     *
     * @see XenForo_Model_Ip::getSharedIpUsers()
     */
    public function getSharedIpUsers($userId, $logDays)
    {
        $users = parent::getSharedIpUsers($userId, $logDays);
        $db = $this->_getDb();
        $ipLogs = $db->fetchCol($db->limit('
				SELECT DISTINCT ip_address
				FROM xf_moderator_log
				WHERE content_type IN (\'thread\', \'post\')
                    AND action = \'post_as_user\'
                    AND log_date > ?
			', 500), XenForo_Application::$time - $logDays * 86400);
        foreach ($ipLogs as $key => $ipLog) {
            $ipLogs[$key] = XenForo_Helper_Ip::convertIpBinaryToString($ipLog);
        }
        foreach ($users as $userId => $user) {
            foreach ($user['ipLogs'] as $key => $ipLog) {
                if (in_array($ipLog['ip_address'], $ipLogs)) {
                    unset($user['ipLogs'][$key]);
                }
            }
            if (empty($user['ipLogs'])) {
                unset($users[$userId]);
            }
        }
        return $users;
    }
Example #2
0
 public static function getRequestUrl(array $provider, $redirectUri, array $extraParams = array())
 {
     $url = call_user_func_array('sprintf', array('%s/index.php?oauth/authorize/&client_id=%s&redirect_uri=%s&response_type=code&scope=%s', rtrim($provider['root'], '/'), rawurlencode($provider['client_id']), rawurlencode($redirectUri), rawurlencode(self::SCOPE)));
     if (XenForo_Application::getConfig()->get(bdApiConsumer_Option::CONFIG_TRACK_AUTHORIZE_URL_STATE) && !isset($extraParams['state'])) {
         $extraParams['state'] = base64_encode(json_encode(array('time' => XenForo_Application::$time, 'ip' => XenForo_Helper_Ip::convertIpBinaryToString(XenForo_Application::getSession()->get('ip')))));
     }
     foreach ($extraParams as $key => $value) {
         $url .= sprintf('&%s=%s', $key, rawurlencode($value));
     }
     return $url;
 }
Example #3
0
    public function getLastIp($userId)
    {
        $lastIp = $this->_getDb()->fetchOne('
			SELECT ip
			FROM xf_ip
			WHERE user_id = ?
			ORDER BY log_date DESC
			LIMIT 1
		', $userId);
        return XenForo_Helper_Ip::convertIpBinaryToString($lastIp);
    }
Example #4
0
 public final function prepareEntry(array $entry)
 {
     $entry['content_title'] = XenForo_Helper_String::censorString($entry['content_title']);
     $entry['ipAddress'] = $entry['ip_address'] ? XenForo_Helper_Ip::convertIpBinaryToString($entry['ip_address']) : '';
     $entry = $this->_prepareEntry($entry);
     if (!isset($entry['actionText'])) {
         $entry['actionText'] = new XenForo_Phrase('moderator_log_' . $entry['content_type'] . '_' . $entry['action'], json_decode($entry['action_params'], true));
     }
     if (!isset($entry['contentUser'])) {
         $entry['contentUser'] = array('user_id' => $entry['content_user_id'], 'username' => $entry['content_username']);
     }
     return $entry;
 }
Example #5
0
 /**
  * Fetches the current IP for the specified online guest
  *
  * @return XenForo_ControllerResponse_Abstract
  */
 public function actionGuestIp()
 {
     if (!$this->_getUserModel()->canViewIps($errorPhraseKey)) {
         throw $this->getErrorOrNoPermissionResponseException($errorPhraseKey);
     }
     $ip = preg_replace('#[^0-9a-f]#', '', $this->_input->filterSingle('ip', XenForo_Input::STRING));
     try {
         $ip = XenForo_Helper_Ip::convertIpBinaryToString(XenForo_Helper_Ip::convertHexToBin($ip));
     } catch (Exception $e) {
         $ip = false;
     }
     if (!$ip) {
         // likely given an invalid IP
         return $this->responseError(new XenForo_Phrase('unexpected_error_occurred'));
     }
     $viewParams = array('ip' => $ip, 'host' => XenForo_Model_Ip::getHost($ip));
     return $this->responseView('XenForo_ViewPublic_Online_GuestIp', 'online_guest_ip', $viewParams);
 }
Example #6
0
 /**
  * Determines if the existing session matches the given IP address. Looks
  * for the session's IP in the ip key. If not found, check passes.
  *
  * @param array $session
  * @param string|false $ipAddress IP address as binary or false to prevent IP check
  *
  * @return boolean
  */
 public function sessionMatchesIp(array $session, $ipAddress)
 {
     if (!isset($session['ip']) || empty($session['ip']) || empty($ipAddress)) {
         return true;
         // no IP to check against
     }
     if (strlen($ipAddress) == 4) {
         $cidr = intval($this->_config['ipv4CidrMatch']);
     } else {
         $cidr = intval($this->_config['ipv6CidrMatch']);
     }
     if ($cidr <= 0) {
         return true;
         // IP check disabled
     }
     return XenForo_Helper_Ip::ipMatchesCidrRange($ipAddress, $session['ip'], $cidr);
 }
Example #7
0
    public function stepVisitorMessages($start, array $options)
    {
        $options = array_merge(array('limit' => 200, 'max' => false), $options);
        $sDb = $this->_sourceDb;
        $prefix = $this->_prefix;
        /* @var $model XenForo_Model_Import */
        $model = $this->_importModel;
        if ($options['max'] === false) {
            $options['max'] = $sDb->fetchOne('
				SELECT MAX(vmid)
				FROM ' . $prefix . 'visitormessage
			');
        }
        $vms = $sDb->fetchAll($sDb->limit('
				SELECT vm.*,
						IF(user.username IS NULL, vm.postusername, user.username) AS username
				FROM ' . $prefix . 'visitormessage AS vm
				LEFT JOIN ' . $prefix . 'user AS user ON (vm.postuserid = user.userid)
				WHERE vm.vmid > ' . $sDb->quote($start) . '
				ORDER BY vm.vmid
			', $options['limit']));
        if (!$vms) {
            return true;
        }
        $next = 0;
        $total = 0;
        $userIds = array();
        foreach ($vms as $vm) {
            $userIds[] = $vm['userid'];
            $userIds[] = $vm['postuserid'];
        }
        $userIdMap = $model->getImportContentMap('user', $userIds);
        XenForo_Db::beginTransaction();
        $formatter = XenForo_BbCode_Formatter_Base::create('XenForo_BbCode_Formatter_Text');
        $parser = XenForo_BbCode_Parser::create($formatter);
        foreach ($vms as $vm) {
            $next = $vm['vmid'];
            if (trim($vm['postusername']) === '') {
                continue;
            }
            $profileUserId = $this->_mapLookUp($userIdMap, $vm['userid']);
            if (!$profileUserId) {
                continue;
            }
            $postUserId = $this->_mapLookUp($userIdMap, $vm['postuserid'], 0);
            $import = array('profile_user_id' => $profileUserId, 'user_id' => $postUserId, 'username' => $this->_convertToUtf8($vm['postusername'], true), 'post_date' => $vm['dateline'], 'message' => $parser->render($this->_convertToUtf8($vm['pagetext'])), 'ip' => XenForo_Helper_Ip::convertIpBinaryToString($vm['ipaddress']));
            switch ($vm['state']) {
                case 'deleted':
                    $import['message_state'] = 'deleted';
                    break;
                case 'moderation':
                    $import['message_state'] = 'moderated';
                    break;
                default:
                    $import['message_state'] = 'visible';
            }
            if ($model->importProfilePost($vm['vmid'], $import)) {
                $total++;
            }
        }
        XenForo_Db::commit();
        $this->_session->incrementStepImportTotal($total);
        return array($next, $options, $this->_getProgressOutput($next, $options['max']));
    }
 public function logSpamTrigger($contentType, $contentId, $result = null, array $details = null, $userId = null, $ipAddress = null)
 {
     if ($result === null) {
         $result = $this->getLastCheckResult();
     }
     $hax = FALSE;
     if ($result == self::RESULT_ALLOWED) {
         $result = self::RESULT_MODERATED;
         $hax = TRUE;
     }
     $return = parent::logSpamTrigger($contentType, $contentId, $result, $details, $userId, $ipAddress);
     if ($hax) {
         $this->_getDb()->query('UPDATE xf_spam_trigger_log SET result="allowed" WHERE log_date=? AND result=? AND ip_address=?', array(XenForo_Application::$time, self::RESULT_MODERATED, XenForo_Helper_Ip::getBinaryIp(null, $ipAddress)));
     }
     return $return;
 }
Example #9
0
 /**
  * Logs that the spam handler was triggered, if the result was not allowed.
  *
  * @param string $contentType
  * @param integer $contentId
  * @param string|null $result
  * @param array|null $details
  * @param null|integer $userId
  * @param null|string $ipAddress
  *
  * @return bool|int True if updated, false if no change, int ID if inserted
  */
 public function logSpamTrigger($contentType, $contentId, $result = null, array $details = null, $userId = null, $ipAddress = null)
 {
     if ($result === null) {
         $result = $this->getLastCheckResult();
     }
     switch ($result) {
         case self::RESULT_DENIED:
         case self::RESULT_MODERATED:
             break;
         default:
             return false;
     }
     $ipAddress = XenForo_Helper_Ip::getBinaryIp(null, $ipAddress);
     if ($userId === null) {
         $userId = XenForo_Visitor::getUserId();
     }
     if (!$contentId) {
         $contentId = null;
     }
     if ($contentType == 'user') {
         $userId = $contentId ? $contentId : 0;
     }
     if ($details === null) {
         $details = $this->getLastCheckDetails();
     }
     $requestPaths = XenForo_Application::get('requestPaths');
     $request = array('url' => $requestPaths['fullUri'], 'referrer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '', '_GET' => $_GET, '_POST' => $_POST);
     // don't log passwords
     foreach ($request['_POST'] as $key => &$value) {
         if (strpos($key, 'password') !== false || $key == '_xfToken') {
             $value = '********';
         }
     }
     $query = $this->_getDb()->query("\n\t\t\tINSERT INTO xf_spam_trigger_log\n\t\t\t\t(content_type, content_id, log_date, user_id, ip_address, result, details, request_state)\n\t\t\tVALUES\n\t\t\t\t(?, ?, ?, ?, ?, ?, ?, ?)\n\t\t\tON DUPLICATE KEY UPDATE\n\t\t\t\tlog_date = VALUES(log_date),\n\t\t\t\tuser_id = VALUES(user_id),\n\t\t\t\tip_address = VALUES(ip_address),\n\t\t\t\tresult = VALUES(result),\n\t\t\t\tdetails = VALUES(details),\n\t\t\t\trequest_state = VALUES(request_state)\n\t\t", array($contentType, $contentId, XenForo_Application::$time, $userId, $ipAddress, $result, serialize($details), serialize($request)));
     return $query->rowCount() == 1 ? $this->_getDb()->lastInsertId() : true;
 }
Example #10
0
 protected function _verifyIpAddress(&$ipAddress)
 {
     $ipAddress = (string) XenForo_Helper_Ip::convertIpStringToBinary($ipAddress);
     return true;
 }
Example #11
0
 public function prepareAdminLogEntry(array $entry)
 {
     $entry['ipAddress'] = $entry['ip_address'] ? XenForo_Helper_Ip::convertIpBinaryToString($entry['ip_address']) : '';
     return $entry;
 }
Example #12
0
    public function getUsersByIp($ip, $daysLimit = null)
    {
        if (!$ip) {
            return array();
        }
        $ip = XenForo_Helper_Ip::convertIpStringToBinary($ip);
        if (!$ip) {
            return array();
        }
        return $this->fetchAllKeyed('
			SELECT user.*, ip.ip, MAX(ip.log_date) AS log_date
			FROM xf_ip AS ip
			INNER JOIN xf_user AS user ON
				(user.user_id = ip.user_id)
			WHERE ip.ip = ?
				' . ($daysLimit ? ' AND ip.log_date > ' . (XenForo_Application::$time - $daysLimit * 86400) : '') . '
			GROUP BY ip.user_id
			ORDER BY user.username
		', 'user_id', $ip);
    }
Example #13
0
 /**
  * Converts a string based IP (v4 or v6) to a 4 or 16 byte string.
  * This tries to identify not only 192.168.1.1 and 2001::1:2:3:4 style IPs,
  * but integer encoded IPv4 and already binary encoded IPs. IPv4
  * embedded in IPv6 via things like ::ffff:192.168.1.1 is also detected.
  *
  * @param string|int $ip
  *
  * @return bool|string False on failure, binary data otherwise
  */
 public static function convertIpStringToBinary($ip)
 {
     $originalIp = $ip;
     $ip = trim($ip);
     if (strpos($ip, ':') !== false) {
         // IPv6
         if (preg_match('#:(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})$#', $ip, $match)) {
             // embedded IPv4
             $long = ip2long($match[1]);
             if (!$long) {
                 return false;
             }
             $hex = str_pad(dechex($long), 8, '0', STR_PAD_LEFT);
             $v4chunks = str_split($hex, 4);
             $ip = str_replace($match[0], ":{$v4chunks['0']}:{$v4chunks['1']}", $ip);
         }
         if (strpos($ip, '::') !== false) {
             if (substr_count($ip, '::') > 1) {
                 // ambiguous
                 return false;
             }
             $delims = substr_count($ip, ':');
             if ($delims > 7) {
                 return false;
             }
             $ip = str_replace('::', str_repeat(':0', 8 - $delims) . ':', $ip);
             if ($ip[0] == ':') {
                 $ip = '0' . $ip;
             }
         }
         $ip = strtolower($ip);
         $parts = explode(':', $ip);
         if (count($parts) != 8) {
             return false;
         }
         foreach ($parts as &$part) {
             $len = strlen($part);
             if ($len > 4 || preg_match('/[^0-9a-f]/', $part)) {
                 return false;
             }
             if ($len < 4) {
                 $part = str_repeat('0', 4 - $len) . $part;
             }
         }
         $hex = implode('', $parts);
         if (strlen($hex) != 32) {
             return false;
         }
         return XenForo_Helper_Ip::convertHexToBin($hex);
     } else {
         if (strpos($ip, '.')) {
             // IPv4
             if (!preg_match('#(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})#', $ip, $match)) {
                 return false;
             }
             $long = ip2long($match[1]);
             if (!$long) {
                 return false;
             }
             return XenForo_Helper_Ip::convertHexToBin(str_pad(dechex($long), 8, '0', STR_PAD_LEFT));
         } else {
             if (strlen($ip) == 4 || strlen($ip) == 16) {
                 // already binary encoded
                 return $ip;
             } else {
                 if (is_numeric($originalIp) && $originalIp < pow(2, 32)) {
                     // IPv4 as integer
                     return XenForo_Helper_Ip::convertHexToBin(str_pad(dechex($originalIp), 8, '0', STR_PAD_LEFT));
                 } else {
                     return false;
                 }
             }
         }
     }
 }
Example #14
0
 protected function _getIpRecord($ip)
 {
     $results = XenForo_Helper_Ip::parseIpRangeString($ip);
     if (!$results) {
         throw new XenForo_Exception(new XenForo_Phrase('please_enter_valid_ip_or_ip_range'), true);
     }
     return array($results['printable'], $results['binary'][0], $results['startRange'], $results['endRange']);
 }
Example #15
0
 public function clearLoginAttempts($usernameOrEmail, $ipAddress = null)
 {
     $ipAddress = XenForo_Helper_Ip::getBinaryIp(null, $ipAddress);
     $db = $this->_getDb();
     $db->delete('xf_login_attempt', 'login = '******' AND ip_address = ' . $db->quote($ipAddress));
 }
Example #16
0
 /**
  * Deletes the session activity record for the specified user / IP address
  *
  * @param integer $userId
  * @param string $ip
  */
 public function deleteSessionActivity($userId, $ip)
 {
     $userId = intval($userId);
     $ipNum = XenForo_Helper_Ip::convertIpStringToBinary($ip);
     $uniqueKey = $userId ? $userId : $ipNum;
     $db = $this->_getDb();
     $db->delete('xf_session_activity', 'user_id = ' . $db->quote($userId) . ' AND unique_key = ' . $db->quote($uniqueKey));
 }
Example #17
0
 public static function helperIp($ip)
 {
     $res = XenForo_Helper_Ip::convertIpBinaryToString($ip);
     return htmlspecialchars($res ? $res : $ip, ENT_COMPAT, 'utf-8');
 }
Example #18
0
    /**
     * Does not currently handle redirects
     *
     * @param integer $start
     * @param array $options
     */
    public function stepThreads($start, array $options)
    {
        $options = array_merge(array('limit' => 100, 'postDateStart' => 0, 'postLimit' => 800, 'max' => false), $options);
        $sDb = $this->_sourceDb;
        /* @var $model XenForo_Model_Import */
        $model = $this->_importModel;
        if ($options['max'] === false) {
            $options['max'] = $sDb->fetchOne('
				SELECT MAX(thread_id)
				FROM xf_thread
			');
        }
        $threads = $sDb->fetchAll($sDb->limit("\r\r\n\t\t\t\tSELECT thread.*,\r\r\n\t\t\t\t\tIF (user.username IS NULL, thread.username, user.username) AS username\r\r\n\t\t\t\tFROM xf_thread AS thread\r\r\n\t\t\t\tLEFT JOIN xf_user AS user ON (user.user_id = thread.user_id)\r\r\n\t\t\t\tWHERE thread.thread_id >= " . $sDb->quote($start) . "\r\r\n\t\t\t\t\tAND thread.discussion_type <> 'redirect'\r\r\n\t\t\t", $options['limit']));
        if (!$threads) {
            return true;
        }
        $next = 0;
        $total = 0;
        $totalPosts = 0;
        $nodeMap = $model->getImportContentMap('node');
        $threadPrefixMap = $model->getImportContentMap('threadPrefix');
        XenForo_Db::beginTransaction();
        foreach ($threads as $thread) {
            $postDateStart = $options['postDateStart'];
            $next = $thread['thread_id'] + 1;
            $options['postDateStart'] = 0;
            $maxPosts = $options['postLimit'] - $totalPosts;
            $posts = $sDb->fetchAll($sDb->limit("\r\r\n\t\t\t\t\tSELECT post.*,\r\r\n\t\t\t\t\t\tIF (user.username IS NULL, post.username, user.username) AS username,\r\r\n\t\t\t\t\t\txf_ip.ip\r\r\n\t\t\t\t\tFROM xf_post AS post\r\r\n\t\t\t\t\tLEFT JOIN xf_user AS user ON (user.user_id = post.user_id)\r\r\n\t\t\t\t\tLEFT JOIN xf_ip ON (xf_ip.ip_id = post.ip_id)\r\r\n\t\t\t\t\tWHERE post.thread_id = " . $sDb->quote($thread['thread_id']) . "\r\r\n\t\t\t\t\t\tAND post.post_date > " . $sDb->quote($postDateStart) . "\r\r\n\t\t\t\t\tORDER BY post.post_date\r\r\n\t\t\t\t", $maxPosts));
            if (!$posts) {
                if ($postDateStart) {
                    // continuing thread but no remaining threads
                    $total++;
                }
                continue;
            }
            if ($postDateStart) {
                // continuing already-imported thread
                $threadId = $model->mapThreadId($thread['thread_id']);
                $position = $this->_db->fetchOne('
					SELECT MAX(position)
					FROM xf_post
					WHERE thread_id = ?
				', $threadId);
            } else {
                $forumId = $this->_mapLookUp($nodeMap, $thread['node_id']);
                if (!$forumId) {
                    continue;
                }
                $import = $this->_quickAssembleData($thread, array('node_id' => $forumId, 'title', 'reply_count', 'view_count', 'user_id' => $model->mapUserId($thread['user_id'], 0), 'username', 'post_date', 'sticky', 'discussion_state', 'discussion_open', 'discussion_type', 'prefix_id' => $this->_mapLookUp($threadPrefixMap, $thread['prefix_id'], 0)));
                $threadId = $model->importThread($thread['thread_id'], $import);
                if (!$threadId) {
                    continue;
                }
                $subscriptions = $sDb->fetchPairs('
					SELECT user_id, email_subscribe
					FROM xf_thread_watch
					WHERE thread_id = ?
					', $thread['thread_id']);
                if ($subscriptions) {
                    $userIdMap = $model->getImportContentMap('user', array_keys($subscriptions));
                    foreach ($subscriptions as $userId => $emailSubscribe) {
                        if ($newUserId = $this->_mapLookUp($userIdMap, $userId)) {
                            $model->importThreadWatch($newUserId, $threadId, $emailSubscribe);
                        }
                    }
                }
            }
            if ($threadId) {
                $quotedPostIds = array();
                $quotedUserIds = array();
                $userIdMap = $model->getUserIdsMapFromArray($posts, 'user_id');
                foreach ($posts as $i => $post) {
                    $import = $this->_quickAssembleData($post, array('thread_id' => $threadId, 'user_id' => $this->_mapLookUp($userIdMap, $post['user_id'], 0), 'username', 'post_date', 'message', 'ip' => XenForo_Helper_Ip::convertIpBinaryToString($post['ip']), 'message_state', 'attach_count', 'position', 'likes', 'last_edit_date', 'edit_count'));
                    $post['new_post_id'] = $model->importPost($post['post_id'], $import);
                    $options['postDateStart'] = $post['post_date'];
                    $totalPosts++;
                    // quotes
                    if (stripos($post['message'], '[quote=') !== false) {
                        if (preg_match_all('/\\[quote=("|\'|)(?P<username>[^,]*),post:\\s*(?P<post_id>\\d+)\\s*,\\s*member:\\s*(?P<user_id>\\d+)\\s*\\1\\]/siU', $post['message'], $quotes, PREG_SET_ORDER)) {
                            $post['quotes'] = array();
                            foreach ($quotes as $quote) {
                                $quotedPostId = intval($quote['post_id']);
                                $quotedPostIds[] = $quotedPostId;
                                $quotedUserId = intval($quote['user_id']);
                                $quotedUserIds[] = $quotedUserId;
                                $post['quotes'][$quote[0]] = array($quote['username'], $quotedPostId, $quotedUserId);
                            }
                        }
                    }
                    $posts[$i] = $post;
                }
                $postIdMap = empty($quotedPostIds) ? array() : $model->getImportContentMap('post', $quotedPostIds);
                $userIdMap = array_merge($userIdMap, empty($quotedUserIds) ? array() : $model->getImportContentMap('user', $quotedUserIds));
                $db = XenForo_Application::getDb();
                foreach ($posts as $post) {
                    if (!empty($post['quotes'])) {
                        $postQuotesRewrite = $this->_rewritePostQuotes($post['message'], $post['quotes'], $postIdMap, $userIdMap);
                        if ($post['message'] != $postQuotesRewrite) {
                            $db->update('xf_post', array('message' => $postQuotesRewrite), 'post_id = ' . $db->quote($post['new_post_id']));
                        }
                    }
                }
            }
            if (count($posts) < $maxPosts) {
                // this thread completed
                $total++;
                $options['postDateStart'] = 0;
            } else {
                // pick up the thread on the next go-around
                break;
            }
        }
        if ($options['postDateStart']) {
            // thread not yet completed
            $next--;
        }
        XenForo_Db::commit();
        $this->_session->incrementStepImportTotal($total);
        return array($next, $options, $this->_getProgressOutput($next - 1, $options['max']));
    }
Example #19
0
 /**
  * Lists all users logged from the specified IP
  *
  * @return XenForo_ControllerResponse_Abstract
  */
 public function actionIpUsers()
 {
     $ip = $this->_input->filterSingle('ip', XenForo_Input::STRING);
     $fetchOptions = array('join' => XenForo_Model_User::FETCH_USER_PROFILE);
     $ipDetails = XenForo_Helper_Ip::parseIpRangeString($ip);
     if (!$ipDetails) {
         return $this->responseMessage(new XenForo_Phrase('please_enter_valid_ip_or_ip_range'));
     } else {
         if ($ipDetails['isRange']) {
             $users = $this->_getUserModel()->getUsersByIpRange($ipDetails['startRange'], $ipDetails['endRange'], $fetchOptions);
         } else {
             $users = $this->_getUserModel()->getUsersByIp($ip, $fetchOptions);
         }
     }
     if ($users) {
         $viewParams = array('users' => $users, 'ip' => $ip, 'ipPrintable' => $ipDetails['printable']);
         return $this->responseView('XenForo_ViewAdmin_Users_IpUsers', 'ip_users', $viewParams);
     } else {
         return $this->responseMessage(new XenForo_Phrase('no_users_logged_at_ip'));
     }
 }
Example #20
0
 public static function logException($e, $rollbackTransactions = true, $messagePrefix = '')
 {
     $isValidArg = $e instanceof Exception || $e instanceof Throwable;
     if (!$isValidArg) {
         throw new Exception("logException requires an Exception or a Throwable");
     }
     try {
         $db = XenForo_Application::getDb();
         if ($db->getConnection()) {
             if ($rollbackTransactions) {
                 @XenForo_Db::rollbackAll($db);
             }
             $dbVersionId = @$db->fetchOne("SELECT option_value FROM xf_option WHERE option_id = 'currentVersionId'");
             if ($dbVersionId && $dbVersionId != XenForo_Application::$versionId) {
                 // do not log errors when an upgrade is pending
                 return;
             }
             if (!file_exists(XenForo_Helper_File::getInternalDataPath() . '/install-lock.php')) {
                 // install hasn't finished yet, don't write
                 return;
             }
             $rootDir = XenForo_Application::getInstance()->getRootDir();
             $file = $e->getFile();
             if (strpos($file, $rootDir) === 0) {
                 $file = substr($file, strlen($rootDir));
                 if (strlen($file) && ($file[0] == '/' || $file[0] == '\\')) {
                     $file = substr($file, 1);
                 }
             }
             $requestPaths = XenForo_Application::get('requestPaths');
             $request = array('url' => $requestPaths['fullUri'], '_GET' => $_GET, '_POST' => $_POST);
             // don't log passwords
             foreach ($request['_POST'] as $key => &$value) {
                 if (strpos($key, 'password') !== false || $key == '_xfToken') {
                     $value = '********';
                 }
             }
             $db->insert('xf_error_log', array('exception_date' => XenForo_Application::$time, 'user_id' => XenForo_Visitor::hasInstance() ? XenForo_Visitor::getUserId() : null, 'ip_address' => XenForo_Helper_Ip::getBinaryIp(), 'exception_type' => get_class($e), 'message' => $messagePrefix . $e->getMessage(), 'filename' => $file, 'line' => $e->getLine(), 'trace_string' => $e->getTraceAsString(), 'request_state' => serialize($request)));
         }
     } catch (Exception $e) {
     }
 }
Example #21
0
 /**
  * Checks for a match of one or more IPs against a list of IP and IP fragments
  *
  * @param string|array IP address(es)
  * @param array List of IP addresses
  *
  * @return boolean
  */
 public function ipMatch($checkIps, array $ipList)
 {
     if (!is_array($checkIps)) {
         $checkIps = array($checkIps);
     }
     foreach ($checkIps as $ip) {
         $binary = XenForo_Helper_Ip::convertIpStringToBinary($ip);
         if (!$binary) {
             continue;
         }
         $firstByte = $binary[0];
         if (!empty($ipList[$firstByte])) {
             foreach ($ipList[$firstByte] as $range) {
                 if (XenForo_Helper_Ip::ipMatchesRange($binary, $range[0], $range[1])) {
                     return true;
                 }
             }
         }
     }
     return false;
 }
Example #22
0
 public function login($user_id, $username, $ip_address)
 {
     $session = XenForo_Session::startPublicSession();
     $session->set('user_id', $user_id);
     $session->set('username', $username);
     $session->set('ip', XenForo_Helper_Ip::convertIpStringToBinary($ip_address));
     //$session->set('userAgent', $user_agent);
     $session->saveSessionToSource($session->getSessionId(), false);
     return $session;
 }
Example #23
0
 public function actionUsermap()
 {
     if (!function_exists('geoip_record_by_name')) {
         throw $this->responseException($this->responseError(new XenForo_Phrase('geoip_not_installed'), 503));
     } elseif (!geoip_db_avail(GEOIP_CITY_EDITION_REV0)) {
         throw $this->responseException($this->responseError(str_replace('{geoip_city_path}', geoip_db_filename(GEOIP_CITY_EDITION_REV0), new XenForo_Phrase('geoip_missing_database')), 503));
     }
     $sessionModel = $this->_getSessionModel();
     $bypassUserPrivacy = $this->_getUserModel()->canBypassUserPrivacy();
     $conditions = array('cutOff' => array('>', $sessionModel->getOnlineStatusTimeout()), 'getInvisible' => $bypassUserPrivacy, 'getUnconfirmed' => $bypassUserPrivacy, 'forceInclude' => $bypassUserPrivacy ? false : XenForo_Visitor::getUserId());
     $onlineUsers = $sessionModel->getSessionActivityRecords($conditions, array('perPage' => 5000, 'page' => 1, 'join' => XenForo_Model_Session::FETCH_USER, 'order' => 'view_date'));
     $users = $used_ip = $users_new = $users_added = $duplicate_location = array();
     $users_newest = array(0 => array(), 1 => array(), 3 => array());
     if (count($onlineUsers)) {
         foreach ($onlineUsers as $key => $user) {
             $user['ip'] = XenForo_Helper_Ip::convertIpBinaryToString($user['ip']);
             $onlineUsers[$key]['user_id'] = $user['user_id'] = intval($onlineUsers[$key]['user_id']);
             $users["{$user['user_id']}-{$user['ip']}"] = $user;
         }
     }
     $dataRegistryModel = $this->_getDataRegistryModel();
     $users_cached = $dataRegistryModel->get('userMap');
     if (count($users)) {
         foreach ($users as $key => $user) {
             if (isset($users_cached[$key])) {
                 // Read from cache
                 $type = substr($users_cached[$key], -1);
                 if ($type < 3) {
                     // Prioritize admins/mods and registered users
                     if ($user['is_staff']) {
                         $type = 3;
                     } elseif ($user['user_id']) {
                         $type = 0;
                     }
                 }
                 $users_new[$key] = substr($users_cached[$key], 0, -1) . $type;
             } else {
                 $user_location = @geoip_record_by_name($user['ip']);
                 if (!($user_location['longitude'] == 0 && $user_location['latitude'] == 0)) {
                     $type = $user['is_staff'] ? 3 : ($user['user_id'] ? 0 : ($user['robot_key'] ? 2 : 1));
                     if (!isset($used_ip[$user_location['longitude'] . ',' . $user_location['latitude']])) {
                         $string = $user_location['longitude'] . ',' . $user_location['latitude'] . ',' . $type;
                         if ($type < 2) {
                             $users_new = @array_merge(array($key => $string), $users_new);
                         } else {
                             $users_new[$key] = $string;
                         }
                         $used_ip[$user_location['longitude'] . ',' . $user_location['latitude']] = true;
                     } else {
                         $duplicate_location = @array_merge(array($key => $string), $users_new);
                     }
                 } else {
                     $duplicate_location = @array_merge(array($key => $string), $users_new);
                 }
             }
         }
     }
     $dataRegistryModel->set('userMap', @array_merge((array) $users_new, (array) $duplicate_location));
     foreach ($users_new as $key => $plot) {
         $type = substr($plot, -1);
         $users_newest[$type][] = substr($plot, 0, -2);
     }
     foreach ($users_newest as $key => $group) {
         $users_newest[$key] = @array_flip(@array_flip($users_newest[$key]));
     }
     $users_new = array();
     foreach (array(3, 0, 2, 1) as $type) {
         if (!empty($users_newest[$type])) {
             foreach ($users_newest[$type] as $plot) {
                 if (!isset($users_added[$plot])) {
                     $users_new[] = $plot . ',' . $type;
                     $users_added[$plot] = true;
                 }
             }
         }
     }
     $js_array = 'DigitalPointUserMap._UserMap.allPoints = new Array (';
     if (count($users_new)) {
         foreach ($users_new as $user) {
             $js_array .= "[{$user}],";
         }
         $js_array = substr($js_array, 0, -1) . ')';
     } else {
         $js_array .= ')';
     }
     $viewParams = array('js_array' => $js_array, 'user_location' => @geoip_record_by_name($_SERVER['REMOTE_ADDR']));
     return $this->responseView('DigitalPointUserMap_ViewPubic_UserMap_Index', 'usermap_index', $viewParams);
 }