Esempio n. 1
0
function addLanguage()
{
    require_once '/home1/typograf/php/Net/vendor/autoload.php';
    $reader = new Reader('/home1/typograf/php/Net/GeoLite2-Country.mmdb');
    $ip_addr = $_SERVER['REMOTE_ADDR'];
    //$ip_addr = '157.7.205.139';
    $langJa = '';
    $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : NULL;
    $httpQuery = $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
    if (!strstr($httpQuery, "lang")) {
        if (!strstr($httpQuery, "?")) {
            $langJa = "?lang=ja";
        } else {
            $langJa = getUrlquery(array("lang" => "ja"));
            $langJa = htmlspecialchars_decode($langJa);
        }
    }
    $record = $reader->country($ip_addr);
    $country = $record->country->name;
    //Japan or Germany
    // if access from Japan and the refere isn't typograffit and no language parameter //
    if ($country == "Japan" && !strstr($referer, "typograffit") && !strstr($httpQuery, "lang")) {
        header('Location: ' . $langJa);
        exit;
    }
}
Esempio n. 2
0
function wp_statistics_populate_geoip_info()
{
    global $wpdb;
    // Find all rows in the table that currently don't have GeoIP info or have an unknown ('000') location.
    $result = $wpdb->get_results("SELECT id,ip FROM `{$wpdb->prefix}statistics_visitor` WHERE location = '' or location = '000' or location IS NULL");
    // Try create a new reader instance.
    try {
        $upload_dir = wp_upload_dir();
        $reader = new Reader($upload_dir['basedir'] . '/wp-statistics/GeoLite2-Country.mmdb');
    } catch (Exception $e) {
        return "<div class='updated settings-error'><p><strong>" . __('Unable to load the GeoIP database, make sure you have downloaded it in the settings page.', 'wp_statistics') . "</strong></p></div>";
    }
    $count = 0;
    // Loop through all the missing rows and update them if we find a locaiton for them.
    foreach ($result as $item) {
        $count++;
        // If the IP address is only a hash, don't bother updating the record.
        if (substr($item->ip, 0, 6) != '#hash#') {
            try {
                $record = $reader->country($item->ip);
                $location = $record->country->isoCode;
                if ($location == "") {
                    $location = "000";
                }
            } catch (Exception $e) {
                $location = "000";
            }
            // Update the row in the database.
            $wpdb->update($wpdb->prefix . "statistics_visitor", array('location' => $location), array('id' => $item->id));
        }
    }
    return "<div class='updated settings-error'><p><strong>" . sprintf(__('Updated %s GeoIP records in the visitors database.', 'wp_statistics'), $count) . "</strong></p></div>";
}
 /**
  * Perform command.
  */
 public function perform()
 {
     try {
         $entry = [];
         $parser = new \Kassner\LogParser\LogParser();
         $parser->setFormat('%h %l %u %t "%r" %>s %O "%{Referer}i" \\"%{User-Agent}i"');
         $lines = file('/var/log/apache2/access.log', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
         foreach ($lines as &$line) {
             $userSpec = $parser->parse($line);
             $userSpec->device = parse_user_agent($userSpec->HeaderUserAgent);
             $city = new Reader(__DIR__ . '/../Database/GeoLite2-City.mmdb');
             $country = new Reader(__DIR__ . '/../Database/GeoLite2-Country.mmdb');
             $userSpec->location = ['city' => $city->city($userSpec->host)->city->name, 'country' => $country->country($userSpec->host)->country->name];
             $entry[] = $userSpec;
         }
         file_put_contents('/var/log/apache2/access.log', '');
     } catch (\Exception $e) {
         file_put_contents('/var/log/apache2/access.log', '');
     }
     if (count($entry) > 0) {
         AccessReport::odmCollection()->batchInsert($entry);
         print "wrote " . count($entry) . " records";
     } else {
         print 0;
     }
 }
Esempio n. 4
0
 /**
  * Get country thanks to the IP Address
  *
  * @param string $format (optional) - possible values : isoCode, name, names
  *
  * @return string|array String with iso code / name of the country or an array of name in different languages
  */
 public function getCountryByIpAddress($format = "isoCode")
 {
     try {
         $reader = new Reader($_SERVER['DOCUMENT_ROOT'] . '/GeoLite2-Country.mmdb');
         $record = $reader->country($this->ipAddress);
         return $record->country->{$format};
     } catch (\Exception $e) {
         return $e->getMessage();
     }
 }
 function get_country_from_ip($ip)
 {
     $isoCode = '';
     try {
         $reader = new Reader(TFLS_GEOIP_DB);
         $record = $reader->country($ip);
         $isoCode = $record->country->isoCode;
     } catch (Exception $e) {
         error_log($e->getMessage());
     }
     return $isoCode;
 }
Esempio n. 6
0
 public function __construct()
 {
     // Call the parent constructor (WP_Statistics::__constructor).
     parent::__construct();
     // We may have set the location based on a private IP address in the hits class, if so, don't bother looking it up again.
     if ($this->location == '000') {
         // Now get the location information from the MaxMind database.
         try {
             // Get the WordPress upload directory information, which is where we have stored the MaxMind database.
             $upload_dir = wp_upload_dir();
             // Create a new Reader and point it to the database.
             $reader = new Reader($upload_dir['basedir'] . '/wp-statistics/GeoLite2-Country.mmdb');
             // Look up the IP address
             $record = $reader->country($this->ip);
             // Get the location.
             $location = $record->country->isoCode;
             // MaxMind returns a blank for location if it can't find it, but we want to use 000 so replace it.
             if ($location == "") {
                 $location = "000";
             }
         } catch (Exception $e) {
             $location = "000";
         }
         // Store the location in the protected $location variable from the parent class.
         $this->location = $location;
     }
     // Check to see if we are excluded by the GeoIP rules.
     if (!$this->exclusion_match) {
         // Grab the excluded/included countries lists, force the country codes to be in upper case to match what the GeoIP code uses.
         $excluded_countries = explode("\n", strtoupper($this->get_option('excluded_countries')));
         $included_countries_string = trim(strtoupper($this->get_option('included_countries')));
         // We need to be really sure this isn't an empty string or explode will return an array with one entry instead of none.
         if ($included_countries_string == '') {
             $included_countries = array();
         } else {
             $included_countries = explode("\n", $included_countries_string);
         }
         // Check to see if the current location is in the excluded countries list.
         if (in_array($this->location, $excluded_countries)) {
             $this->exclusion_match = TRUE;
             $this->exclusion_reason = "geoip";
         } else {
             if (!in_array($this->location, $included_countries) && count($included_countries) > 0) {
                 $this->exclusion_match = TRUE;
                 $this->exclusion_reason = "geoip";
             }
         }
     }
 }
Esempio n. 7
0
 public function index()
 {
     $period = Period::current()->select('id', 'start_at', 'finish_at')->first();
     try {
         $reader = new Reader(storage_path('app/GeoLite2-Country.mmdb'));
         $record = $reader->country($request->ip());
         $country = $record->country->isoCode;
     } catch (Exception $e) {
         $country = 'OM';
     }
     if ($country == 'OM' && $period && app()->environment() !== 'local' && !in_array(app()->ip(), ['188.135.49.50'])) {
         $period = new StdClass();
     }
     return response()->json($period, 200, [], JSON_NUMERIC_CHECK);
 }
Esempio n. 8
0
 public static function getCountryCodeByIP()
 {
     $country['code'] = '';
     $country['name'] = '';
     $country['id'] = '';
     $ip = \Request::getClientIp();
     if (!empty($ip)) {
         $reader = new Reader(app_path() . '/storage/external/GeoLite2-Country.mmdb');
         $record = $reader->country('103.7.80.62');
         $country = array();
         $country['code'] = $record->country->isoCode;
         $country['name'] = $record->country->name;
         $dbCountry = CountryQuery::create()->findOneByCountryCode($country['code']);
         $country['id'] = $dbCountry->getId();
     }
     return $country;
 }
Esempio n. 9
0
 public function blockCountryComment(Result $result)
 {
     /** @var Comment $obj */
     $obj = $result->getObject();
     // globally allowed and disallowed
     $allow = $this->preferences->get('foolfuuka.plugins.geoip_region_lock.allow_comment');
     $disallow = $this->preferences->get('foolfuuka.plugins.geoip_region_lock.disallow_comment');
     $board_allow = trim($obj->radix->getValue('plugin_geo_ip_region_lock_allow_comment'), " ,");
     $board_disallow = trim($obj->radix->getValue('plugin_geo_ip_region_lock_disallow_comment'), " ,");
     // allow board settings to override global
     if ($board_allow || $board_disallow) {
         $allow = $board_allow;
         $disallow = $board_disallow;
     }
     if ($allow || $disallow) {
         $ip = Inet::dtop($obj->comment->poster_ip);
         $reader = new Reader($this->preferences->get('foolframe.maxmind.geoip2_db_path'));
         $country = null;
         try {
             $record = $reader->country($ip);
             $country = strtolower($record->country->isoCode);
         } catch (AddressNotFoundException $e) {
             $country = 'xx';
         }
         if ($allow) {
             $allow = array_filter(explode(',', $allow));
             foreach ($allow as $al) {
                 if (strtolower(trim($al)) === $country) {
                     return;
                 }
             }
             throw new CommentSendingException(_i('Your nation has been blocked from posting.') . '<br/><br/>This product includes GeoLite2 data created by MaxMind, available from http://www.maxmind.com/');
         }
         if ($disallow) {
             $disallow = array_filter(explode(',', $disallow));
             foreach ($disallow as $disal) {
                 if (strtolower(trim($disal)) == $country) {
                     throw new CommentSendingException(_i('Your nation has been blocked from posting.') . '<br/><br/>This product includes GeoLite2 data created by MaxMind, available from http://www.maxmind.com/');
                 }
             }
         }
     }
 }
Esempio n. 10
0
 /**
  * Method checks country code by native php function or search in db file if native function doesn't exist
  * @author Dmitry Fedorov <*****@*****.**>
  * @version 1.0.2 on 2015-08-05
  * @return string|null
  */
 public static function getCountryCode()
 {
     $country = null;
     if (function_exists('geoip_country_code_by_name')) {
         // trick for local using (@author Constantine <*****@*****.**>)
         $userIp = \Yii::$app->getRequest()->getUserIP();
         if ($userIp == '127.0.0.1' || $userIp == '::1') {
             $userIp = self::DEFAULT_USER_IP;
         }
         $country = geoip_country_code_by_name($userIp);
     } else {
         $geoReader = new Reader(\Yii::getAlias('@geolocation/data/GeoLite2-Country.mmdb'));
         try {
             $country = $geoReader->country(\Yii::$app->getRequest()->getUserIP());
             $country = $country->country->isoCode;
         } catch (AddressNotFoundException $e) {
             \Yii::getLogger()->log($e->getMessage(), Logger::LEVEL_WARNING);
         }
     }
     return $country;
 }
Esempio n. 11
0
 /**
  * Returns the 2-digit Country Code matching a given IP address.
  *
  * @param string ip_address The IP address for which to retrieve the Country Code.
  * @return string|bool A Country Code on success, or False on failure.
  */
 public function get_country_code($ip_address)
 {
     //$ip_address = @gethostbyname($host);
     $country_code = '';
     // IP address must be either an IPv4 or an IPv6
     if (filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false && filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) {
         $this->errors[] = sprintf(__('Method IP2Location::get_country_code() expects a valid IPv4 or IPv6 ' . 'address (it will not work with host names). "%s" was passed, which is ' . 'not a valid address.', $this->text_domain), $ip_address);
         $country_code = false;
     }
     if ($country_code !== false) {
         try {
             // Create the Reader object, which should be reused across lookups.
             $reader = new Reader(self::geoip_db_file());
             $record = $reader->country($ip_address);
             $country_code = $record->country->isoCode;
         } catch (\Exception $e) {
             $this->errors[] = sprintf(__('Error(s) occurred while retrieving Geolocation information ' . 'for IP Address "%s". Error: %s.', $this->text_domain), $ip_address, $e->getMessage());
             $country_code = false;
         }
     }
     return apply_filters('wc_aelia_ip2location_country_code', $country_code, $ip_address);
 }
Esempio n. 12
0
 /**
  * Send the comment and attached media to database
  *
  * @param Media $media
  * @param array $data extra data
  * @throws CommentSendingDatabaseException
  * @throws CommentSendingBannedException
  * @throws CommentSendingThreadWithoutMediaException
  * @throws CommentSendingSpamException
  * @throws CommentSendingImageInGhostException
  * @throws CommentSendingNoDelPassException
  * @throws CommentSendingThreadClosedException
  * @throws CommentSendingRequestCaptchaException
  * @throws CommentSendingTimeLimitException
  * @throws CommentSendingException
  * @throws CommentSendingTooManyCharactersException
  * @throws \RuntimeException
  * @throws CommentSendingDisplaysEmptyException
  * @throws CommentSendingTooManyLinesException
  * @throws CommentSendingSameCommentException
  * @throws CommentSendingWrongCaptchaException
  * @throws CommentSendingUnallowedCapcodeException
  * @return array error key with explanation to show to user, or success and post row
  */
 public function p_insert(Media $media = null, $data = [])
 {
     if (isset($data['recaptcha_challenge'])) {
         $this->recaptcha_challenge = $data['recaptcha_challenge'];
         $this->recaptcha_response = $data['recaptcha_response'];
     }
     $this->ghost = false;
     $this->ghost_exist = false;
     $this->allow_media = true;
     // some users don't need to be limited, in here go all the ban and posting limitators
     if (!$this->getAuth()->hasAccess('comment.limitless_comment')) {
         // check if the user is banned
         if ($ban = $this->ban_factory->isBanned($this->comment->poster_ip, $this->radix)) {
             if ($ban->board_id == 0) {
                 $banned_string = _i('It looks like you were banned on all boards.');
             } else {
                 $banned_string = _i('It looks like you were banned on /' . $this->radix->shortname . '/.');
             }
             if ($ban->length) {
                 $banned_string .= ' ' . _i('This ban will last until:') . ' ' . date(DATE_COOKIE, $ban->start + $ban->length) . '.';
             } else {
                 $banned_string .= ' ' . _i('This ban will last forever.');
             }
             if ($ban->reason) {
                 $banned_string .= ' ' . _i('The reason for this ban is:') . ' «' . $ban->reason . '».';
             }
             if ($ban->appeal_status == Ban::APPEAL_NONE) {
                 $banned_string .= ' ' . _i('If you\'d like to appeal to your ban, go to the %s page.', '<a href="' . $this->uri->create($this->radix->shortname . '/appeal') . '">' . _i('Appeal') . '</a>');
             } elseif ($ban->appeal_status == Ban::APPEAL_PENDING) {
                 $banned_string .= ' ' . _i('Your appeal is pending.');
             }
             throw new CommentSendingBannedException($banned_string);
         }
     }
     // check if it's a thread and its status
     if ($this->comment->thread_num > 0) {
         try {
             $thread = Board::forge($this->getContext())->getThread($this->comment->thread_num)->setRadix($this->radix);
             $status = $thread->getThreadStatus();
         } catch (BoardException $e) {
             throw new CommentSendingException($e->getMessage());
         }
         if ($status['closed']) {
             throw new CommentSendingThreadClosedException(_i('The thread is closed.'));
         }
         $this->ghost = $status['dead'];
         $this->ghost_exist = $status['ghost_exist'];
         $this->allow_media = !$status['disable_image_upload'];
     }
     foreach (['name', 'email', 'title', 'comment', 'capcode'] as $key) {
         $this->comment->{$key} = trim((string) $this->comment->{$key});
     }
     $this->comment->setDelpass(trim((string) $this->comment->getDelPass()));
     // some users don't need to be limited, in here go all the ban and posting limitators
     if (!$this->getAuth()->hasAccess('comment.limitless_comment')) {
         if ($this->comment->thread_num < 1) {
             // one can create a new thread only once every 5 minutes
             $check_op = $this->dc->qb()->select('*')->from($this->radix->getTable(), 'r')->where('r.poster_ip = :poster_ip')->andWhere('r.timestamp > :timestamp')->andWhere('r.op = :op')->setParameters([':poster_ip' => $this->comment->poster_ip, ':timestamp' => time() - $this->radix->getValue('cooldown_new_thread'), ':op' => true])->setMaxResults(1)->execute()->fetch();
             if ($check_op) {
                 throw new CommentSendingTimeLimitException(_i('You must wait up to %d minutes to make another new thread.', ceil($this->radix->getValue('cooldown_new_thread') / 60)));
             }
         }
         // check the latest posts by the user to see if he's posting the same message or if he's posting too fast
         $check = $this->dc->qb()->select('*')->from($this->radix->getTable(), 'r')->where('poster_ip = :poster_ip')->orderBy('timestamp', 'DESC')->setMaxResults(1)->setParameter(':poster_ip', $this->comment->poster_ip)->execute()->fetch();
         if ($check) {
             if ($this->comment->comment !== null && $check['comment'] === $this->comment->comment) {
                 throw new CommentSendingSameCommentException(_i('You\'re sending the same comment as the last time'));
             }
             $check_time = $this->getRadixTime();
             if ($check_time - $check['timestamp'] < $this->radix->getValue('cooldown_new_comment') && $check_time - $check['timestamp'] > 0) {
                 throw new CommentSendingTimeLimitException(_i('You must wait up to %d seconds to post again.', $this->radix->getValue('cooldown_new_comment')));
             }
         }
         // we want to know if the comment will display empty, and in case we won't let it pass
         $comment_parsed = $this->processComment();
         if ($this->comment->comment !== '' && $comment_parsed === '') {
             throw new CommentSendingDisplaysEmptyException(_i('This comment would display empty.'));
         }
         // clean up to reset eventual auto-built entries
         $this->comment->clean();
         if ($this->recaptcha_challenge && $this->recaptcha_response && $this->preferences->get('foolframe.auth.recaptcha_public', false)) {
             $recaptcha = ReCaptcha::create($this->preferences->get('foolframe.auth.recaptcha_public'), $this->preferences->get('foolframe.auth.recaptcha_private'));
             $recaptcha_result = $recaptcha->checkAnswer(Inet::dtop($this->comment->poster_ip), $this->recaptcha_challenge, $this->recaptcha_response);
             if (!$recaptcha_result->isValid()) {
                 throw new CommentSendingWrongCaptchaException(_i('Incorrect CAPTCHA solution.'));
             }
         } elseif ($this->preferences->get('foolframe.auth.recaptcha_public')) {
             // if there wasn't a recaptcha input, let's go with heavier checks
             if (substr_count($this->comment->comment, 'http') >= $this->radix->getValue('captcha_comment_link_limit')) {
                 throw new CommentSendingRequestCaptchaException();
             }
             // bots usually fill all the fields
             if ($this->comment->comment && $this->comment->title && $this->comment->email) {
                 throw new CommentSendingRequestCaptchaException();
             }
             // bots usually try various BBC, this checks if there's unparsed BBC after parsing it
             if ($comment_parsed !== '' && substr_count($comment_parsed, '[') + substr_count($comment_parsed, ']') > 4) {
                 throw new CommentSendingRequestCaptchaException();
             }
         }
         // load the spam list and check comment, name, title and email
         $spam = array_filter(preg_split('/\\r\\n|\\r|\\n/', file_get_contents(ASSETSPATH . 'packages/anti-spam/databases/urls.dat')));
         foreach ($spam as $s) {
             if (strpos($this->comment->comment, $s) !== false || strpos($this->comment->name, $s) !== false || strpos($this->comment->title, $s) !== false || strpos($this->comment->email, $s) !== false) {
                 throw new CommentSendingSpamException(_i('Your post has undesidered content.'));
             }
         }
         // check entire length of comment
         if (mb_strlen($this->comment->comment, 'utf-8') > $this->radix->getValue('max_comment_characters_allowed')) {
             throw new CommentSendingTooManyCharactersException(_i('Your comment has too many characters'));
         }
         // check total numbers of lines in comment
         if (count(explode("\n", $this->comment->comment)) > $this->radix->getValue('max_comment_lines_allowed')) {
             throw new CommentSendingTooManyLinesException(_i('Your comment has too many lines.'));
         }
     }
     \Foolz\Plugin\Hook::forge('Foolz\\Foolslide\\Model\\CommentInsert::insert.call.after.input_checks')->setObject($this)->execute();
     // process comment name+trip
     if ($this->comment->name === '') {
         $this->comment->name = $this->radix->getValue('anonymous_default_name');
         $this->comment->trip = null;
     } else {
         $this->processName();
         if ($this->comment->trip === '') {
             $this->comment->trip = null;
         }
     }
     foreach (['email', 'title', 'comment'] as $key) {
         if ($this->comment->{$key} === '') {
             $this->comment->{$key} = null;
         }
     }
     // process comment password
     if ($this->comment->getDelpass() === '') {
         throw new CommentSendingNoDelPassException(_i('You must submit a deletion password.'));
     }
     $pass = password_hash($this->comment->getDelpass(), PASSWORD_BCRYPT, ['cost' => 10]);
     if ($this->comment->getDelpass() === false) {
         throw new \RuntimeException('Password hashing failed');
     }
     $this->comment->setDelpass($pass);
     if ($this->comment->capcode != '') {
         $allowed_capcodes = ['N'];
         if ($this->getAuth()->hasAccess('comment.mod_capcode')) {
             $allowed_capcodes[] = 'M';
         }
         if ($this->getAuth()->hasAccess('comment.admin_capcode')) {
             $allowed_capcodes[] = 'A';
         }
         if ($this->getAuth()->hasAccess('comment.dev_capcode')) {
             $allowed_capcodes[] = 'D';
         }
         if (!in_array($this->comment->capcode, $allowed_capcodes)) {
             throw new CommentSendingUnallowedCapcodeException(_i('You\'re not allowed to use this capcode.'));
         }
     } else {
         $this->comment->capcode = 'N';
     }
     $microtime = str_replace('.', '', (string) microtime(true));
     $this->comment->timestamp = substr($microtime, 0, 10);
     $this->comment->op = (bool) (!$this->comment->thread_num);
     if ($this->radix->getValue('enable_flags')) {
         $reader = new Reader($this->preferences->get('foolframe.maxmind.geoip2_db_path'));
         try {
             $record = $reader->country(Inet::dtop($this->comment->poster_ip));
             $this->comment->poster_country = strtolower($record->country->isoCode);
         } catch (AddressNotFoundException $e) {
             $this->comment->poster_country = 'xx';
         }
     }
     // process comment media
     if ($media !== null) {
         // if uploading an image with OP is prohibited
         if (!$this->comment->thread_num && $this->radix->getValue('op_image_upload_necessity') === 'never') {
             throw new CommentSendingException(_i('You can\'t start a new thread with an image.'));
         }
         if (!$this->allow_media) {
             if ($this->ghost) {
                 throw new CommentSendingImageInGhostException(_i('You can\'t post images when the thread is in ghost mode.'));
             } else {
                 throw new CommentSendingException(_i('This thread has reached its image limit.'));
             }
         }
         try {
             $media->insert($microtime, $this->comment->op);
             $this->media = $media->media;
         } catch (MediaInsertException $e) {
             throw new CommentSendingException($e->getMessage());
         }
     } else {
         // if the user is forced to upload an image when making a new thread
         if (!$this->comment->thread_num && $this->radix->getValue('op_image_upload_necessity') === 'always') {
             throw new CommentSendingThreadWithoutMediaException(_i('You can\'t start a new thread without an image.'));
         }
         // in case of no media, check comment field again for null
         if ($this->comment->comment === null) {
             throw new CommentSendingDisplaysEmptyException(_i('This comment would display empty.'));
         }
         $this->media = $this->bulk->media = new MediaData();
     }
     // 2ch-style codes, only if enabled
     if ($this->comment->thread_num && $this->radix->getValue('enable_poster_hash')) {
         $this->comment->poster_hash = substr(substr(crypt(md5($this->comment->poster_ip . 'id' . $this->comment->thread_num), 'id'), +3), 0, 8);
     }
     $this->comment->timestamp = $this->getRadixTime($this->comment->timestamp);
     \Foolz\Plugin\Hook::forge('Foolz\\Foolslide\\Model\\CommentInsert::insert.call.before.sql')->setObject($this)->execute();
     // being processing insert...
     if ($this->ghost) {
         $num = '
         (
             SELECT MAX(num) AS num
             FROM (
                 (
                     SELECT num
                     FROM ' . $this->radix->getTable() . ' xr
                     WHERE thread_num = ' . $this->dc->getConnection()->quote($this->comment->thread_num) . '
                 )
                 UNION
                 (
                     SELECT num
                     FROM ' . $this->radix->getTable('_deleted') . ' xrd
                     WHERE thread_num = ' . $this->dc->getConnection()->quote($this->comment->thread_num) . '
                 )
             ) x
         )';
         $subnum = '
         (
             SELECT MAX(subnum) + 1 AS subnum
             FROM (
                 (
                     SELECT subnum
                     FROM ' . $this->radix->getTable() . ' xxr
                     WHERE num = (
                         SELECT MAX(num)
                         FROM (
                             (
                                 SELECT num
                                 FROM ' . $this->radix->getTable() . ' xxxr
                                 WHERE thread_num = ' . $this->dc->getConnection()->quote($this->comment->thread_num) . '
                             )
                             UNION
                             (
                                 SELECT num
                                 FROM ' . $this->radix->getTable('_deleted') . ' xxxrd
                                 WHERE thread_num = ' . $this->dc->getConnection()->quote($this->comment->thread_num) . '
                             )
                         ) xxx
                     )
                 )
                 UNION
                 (
                     SELECT subnum
                     FROM ' . $this->radix->getTable('_deleted') . ' xxdr
                     WHERE num = (
                         SELECT MAX(num)
                         FROM (
                             (
                                 SELECT num
                                 FROM ' . $this->radix->getTable() . ' xxxr
                                 WHERE thread_num = ' . $this->dc->getConnection()->quote($this->comment->thread_num) . '
                             )
                             UNION
                             (
                                 SELECT num
                                 FROM ' . $this->radix->getTable('_deleted') . ' xxxdrd
                                 WHERE thread_num = ' . $this->dc->getConnection()->quote($this->comment->thread_num) . '
                             )
                         ) xxxd
                     )
                 )
             ) xx
         )';
         $thread_num = $this->comment->thread_num;
     } else {
         $num = '
         (
             SELECT MAX(num) + 1 AS num
             FROM (
                 (
                     SELECT COALESCE(MAX(num), 0) AS num
                     FROM ' . $this->radix->getTable() . ' xr
                 )
                 UNION
                 (
                     SELECT COALESCE(MAX(num), 0) AS num
                     FROM ' . $this->radix->getTable('_deleted') . ' xdr
                 )
             ) x
         )';
         $subnum = 0;
         if ($this->comment->thread_num > 0) {
             $thread_num = $this->dc->getConnection()->quote($this->comment->thread_num);
         } else {
             $thread_num = '
             (
                 SELECT MAX(thread_num) + 1 AS thread_num
                 FROM (
                     (
                         SELECT COALESCE(MAX(num), 0) as thread_num
                         FROM ' . $this->radix->getTable() . ' xxr
                     )
                     UNION
                     (
                         SELECT COALESCE(MAX(num), 0) as thread_num
                         FROM ' . $this->radix->getTable('_deleted') . ' xxdr
                     )
                 ) xx
             )';
         }
     }
     try {
         $query_fields = ['num' => $num, 'subnum' => $subnum, 'thread_num' => $thread_num];
         $fields = ['media_id' => $this->media->media_id ? $this->media->media_id : 0, 'op' => (int) $this->op, 'timestamp' => $this->comment->timestamp, 'capcode' => $this->comment->capcode, 'email' => $this->comment->email, 'name' => $this->comment->name, 'trip' => $this->comment->trip, 'title' => $this->comment->title, 'comment' => $this->comment->comment, 'delpass' => $this->comment->getDelpass(), 'spoiler' => (int) $this->media->spoiler, 'poster_ip' => $this->comment->poster_ip, 'poster_hash' => $this->comment->poster_hash, 'poster_country' => $this->comment->poster_country, 'preview_orig' => $this->media->preview_orig, 'preview_w' => $this->media->preview_w, 'preview_h' => $this->media->preview_h, 'media_filename' => $this->media->media_filename, 'media_w' => $this->media->media_w, 'media_h' => $this->media->media_h, 'media_size' => $this->media->media_size, 'media_hash' => $this->media->media_hash, 'media_orig' => $this->media->media_orig, 'exif' => $this->media->exif !== null ? @json_encode($this->media->exif) : null, 'timestamp_expired' => 0];
         foreach ($fields as $key => $item) {
             if ($item === null) {
                 $fields[$key] = 'null';
             } else {
                 $fields[$key] = $this->dc->getConnection()->quote($item);
             }
         }
         $fields = $query_fields + $fields;
         $this->dc->getConnection()->beginTransaction();
         $this->dc->getConnection()->executeUpdate('INSERT INTO ' . $this->radix->getTable() . ' (' . implode(', ', array_keys($fields)) . ') VALUES (' . implode(', ', array_values($fields)) . ')');
         $last_id = $this->dc->getConnection()->lastInsertId($this->radix->getTable('_doc_id_seq'));
         $comment = $this->dc->qb()->select('*')->from($this->radix->getTable(), 'r')->where('doc_id = :doc_id')->setParameter(':doc_id', $last_id)->execute()->fetchAll();
         $this->bulk->import($comment[0], $this->radix);
         if (!$this->radix->archive) {
             $this->insertTriggerThreads();
             $this->insertTriggerDaily();
             $this->insertTriggerUsers();
         }
         // update poster_hash for op posts
         if ($this->comment->op && $this->radix->getValue('enable_poster_hash')) {
             $this->comment->poster_hash = substr(substr(crypt(md5($this->comment->poster_ip . 'id' . $this->comment->thread_num), 'id'), 3), 0, 8);
             $this->dc->qb()->update($this->radix->getTable(), 'ph')->set('poster_hash', $this->dc->getConnection()->quote($this->comment->poster_hash))->where('doc_id = :doc_id')->setParameter(':doc_id', $this->comment->doc_id)->execute();
         }
         $this->dc->getConnection()->commit();
         // clean up some caches
         Cache::item('foolslide.model.board.getThreadComments.thread.' . md5(serialize([$this->radix->shortname, $this->comment->thread_num])))->delete();
         // clean up the 10 first pages of index and gallery that are cached
         for ($i = 1; $i <= 10; $i++) {
             Cache::item('foolslide.model.board.getLatestComments.query.' . $this->radix->shortname . '.by_post.' . $i)->delete();
             Cache::item('foolslide.model.board.getLatestComments.query.' . $this->radix->shortname . '.by_thread.' . $i)->delete();
             Cache::item('foolslide.model.board.getThreadsComments.query.' . $this->radix->shortname . '.' . $i)->delete();
         }
     } catch (\Doctrine\DBAL\DBALException $e) {
         $this->logger->error('\\Foolz\\Foolslide\\Model\\CommentInsert: ' . $e->getMessage());
         $this->dc->getConnection()->rollBack();
         throw new CommentSendingDatabaseException(_i('Something went wrong when inserting the post in the database. Try again.'));
     }
     return $this;
 }
 /**
  * @expectedException BadMethodCallException
  * @expectedExceptionMessage The country method cannot be used to open a GeoIP2-City database
  */
 public function testIncorrectDatabase()
 {
     $reader = new Reader('maxmind-db/test-data/GeoIP2-City-Test.mmdb');
     $reader->country('10.10.10.10');
     $reader->close();
 }
<?php

require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
$reader = new Reader("GeoLite2-Country.mmdb");
$all_ip4 = explode(PHP_EOL, file_get_contents('../output/ip4_list.txt'));
$all_ip6 = explode(PHP_EOL, file_get_contents('../output/ip6_list.txt'));
$ip4location_ip = array();
$ip4location_servers = array();
$ip4errors = 0;
$ip6errors = 0;
$ipwitherrors = array();
foreach ($all_ip4 as $ip) {
    $land = 'UNKNOWN';
    try {
        $record = $reader->country($ip);
        $land = $record->country->isoCode;
    } catch (Exception $e) {
        echo 'Error [' . $ip . ']: ' . $e->getMessage() . PHP_EOL;
        $land = 'Invalid / Not in DB';
        $ip4errors++;
        $ipwitherrors[] = $ip;
    }
    echo '[' . $ip . '] ' . $land . PHP_EOL;
    if (!array_key_exists($land, $ip4location_ip)) {
        $ip4location_ip[$land] = 0;
        $ip4location_servers[$land] = 0;
    }
    $ip4location_ip[$land]++;
    $ip4location_servers[$land] += shell_exec('grep "' . $ip . '" ../output/orphans.txt | wc -l');
}
Esempio n. 15
0
 /**
  * @param $ip
  *
  * @return mixed
  */
 public function country($ip)
 {
     return $this->readerCountry->country($ip);
 }
Esempio n. 16
0
 /**
  * Read the location from the
  *
  * @param array $profile            
  */
 public function retriveLocationFromIp()
 {
     $ip = $this->get_ip_address();
     $this->logger->debug('retriveLocationFromIp ' . $ip);
     if ($ip != 'unknown') {
         try {
             $reader = new Reader('./GeoLite2-Country.mmdb');
             $location = $reader->country($ip);
             return $location;
         } catch (\Exception $ex) {
             //
         }
     } else {
         $this->logger->debug('unable to retrive user IP');
     }
     return null;
 }
Esempio n. 17
0
 public function country($ip)
 {
     // This creates the Reader object, which should be reused across
     // lookups.
     $reader = new Reader(maxmind_db_path);
     // Replace "city" with the appropriate method for your database, e.g.,
     // "country".
     $record = $reader->country($ip);
     return $record->country->isoCode;
 }