MyBB Community Forums

Full Version: Locate IP on page
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
I know many of you like to monitor who is online at your site and the most irritating part is bunch of guests look alike surfing different locations of your site. You are curious who they are, where they are from, and you start hopping between your site and some online IP locator service copy-pasting IP strings. Happened with you? Well then, read ahead.

This is the basic tutorial, so in this we are gonna get Country, City and Region for each IP we encounter in Who’s online page, inline, on page. Yes, with minimal template edits we can do that.

Jump in the modifications:
We are gonna edit 3 templates:online, ‘online_row_ip’ & ‘online_row_ip_lookup’.

1. Open template: ‘online_row_ip’, change this code:
 {$user['ip']}
To
 <span class="ip">{$user['ip']}</span> 

2. Open template: ‘online_row_ip_lookup’, keep existing code, add at the beginning:
 &nbsp;<a href="#" class="iplocate">[Locate]</a>&nbsp;
 
3. Open template: ‘online’, locate variable {$footer}, add after that:
<script type="text/javascript">
$(function () {
    $('.iplocate').on('click', function (e) {
        e.preventDefault();
        var ref = $(this);
        ajaxCall($.trim(ref.prev('.ip').text()), function (result) {
            ref.before('[' + result + ']').remove();
        });
    });

    function ajaxCall(ipdata, callback) {
        $.ajax({
            url: "http://ip-api.com/json/" + ipdata + "?fields=country,regionName,city",
            dataType: "json",
            cache: false,
            success: function (msg) {
                var result = (typeof msg == 'object') ? (msg.country + ', ' + msg.regionName + ', ' + msg.city) : "Unable to locate";
                callback(result);
            }
        });
    }
});
</script>


Save all templates. Result:

[attachment=41349]

Note
  • If your server restricting CROB, you can get Cross-Origin Read Blocking warning in console, you can ignore the warning and the code will still work.
  • If you are using SSL (https://) this code will not work because in this tutorial we are using FREE ‘ip-api’ and secured XMLHttpRequest is a PAID service. You can purchase pro to make SSL access to API or ………… or there are few workarounds, but that’s another tutorial Toungue
So, that’s all for now. Happy coding …



Part 2: For those who uses SSL (https://).

Clearly you can't request to that API using SSL, so you need a proxy.
And the proxy is ...... our own xmlhttp.php Big Grin

Yes, we are gonna core edit (don't be sad, read on...)

First, replace the above code in template with:
&nbsp;<a href="#" class="iplocate" style="display: none;">[Locate]</a>&nbsp;

Now, you need to use this js code in place of previous:

/**
 * IP Locator for MyBB 1.8
 * @author effone <[email protected]>
 * @group MyBB Group (Unofficial)
 * @version 1.0.0
 * @copyright 2018 MyBB Group / Demonate
 *
 * Website: https://github.com/mybbgroup / https://demonate.club
 * 
 */

$(function () {
    var data = {
        "error": "Unable to locate.",
        "ajax": parseInt(use_xmlhttprequest),
        "secure": location.protocol == "https:" ? true : false,
        "fields": "country,regionName,city"
    };

    if (!data.secure || (data.secure && data.ajax)) {
        $('.iplocate').show();

        $('.iplocate').on('click', function (e) {
            e.preventDefault();
            var target = $(this);
            var ip = $.trim(target.prev('.ip').text());
            var bank = data.secure ? rootpath + "/xmlhttp.php?action=get_iplocation&ip=" + ip + "&my_post_key=" + my_post_key + "&fields=" + data.fields : "http://ip-api.com/json/" + ip + "?fields=" + data.fields;

            ajaxCall(bank, function (result) {
                if (typeof result.errors === 'undefined') {
                    var message = (typeof result == 'object') ? (result.country + ', ' + result.regionName + ', ' + result.city) : data.error;
                    target.before('[' + message + ']').remove();
                } else {
                    $.each(result.errors, function (i, message) {
                        $.jGrowl("Error" + ' ' + message, {
                            theme: 'jgrowl_error'
                        });
                    });
                    //console.log(JSON.stringify(result));
                }
            });
        });

        function ajaxCall(bank, callback) {
            $.ajax({
                url: bank,
                dataType: "json",
                cache: true,
                success: function (result) {
                    callback(result);
                }
            });
        }
    }
});

Next, open xmlhttp.php, go to about line number 1110 (where the action blocks end, before xmlhttp_error() function) and add the following:

else if($mybb->input['action'] == 'get_iplocation')
{
        if (!verify_post_check($mybb->get_input('my_post_key'), true)) {
            xmlhttp_error($lang->invalid_post_code);
        }
        
        if(!$mybb->usergroup['canuseipsearch'])
        {
            xmlhttp_error($lang->permission_error);
        }

        $response = file_get_contents("http://ip-api.com/json/" . $mybb->get_input('ip') . "?fields=" . $mybb->get_input('fields'));

        json_decode($response);
        if(!json_last_error()  == 0)
        {
            xmlhttp_error($lang->ipapi_invalid_response);
        }

        header("Content-type: application/json; charset={$charset}");
        die($response);
}
and finally, open global.lang.php and add these two at the very end:
$l['ipapi_invalid_response'] = 'Invalid response received from IP-API.';
$l['permission_error'] = 'You are not allowed to perform this action.';
Save all. Done.

Note:
- For those who don't wanna core edit, Part 3 is coming up.
- A plugin with advanced features (like map, custom cache, advanced validations etc) is also under development. Keep an eye on Demonate & repo list of MyBB Group (unofficial):
https://github.com/mybbgroup

More advanced & detailed tutorials @ Demonate.
(2018-12-19, 06:56 PM)effone Wrote: [ -> ]I know many of you like to monitor who is online at your site and the most irritating part is bunch of guests look alike surfing different locations of your site. You are curious who they are, where they are from, and you start hopping between your site and some online IP locator service copy-pasting IP strings. Happened with you? Well then, read ahead.

This is the basic tutorial, so in this we are gonna get Country, City and Region for each IP we encounter in Who’s online page, inline, on page. Yes, with minimal template edits we can do that.

Jump in the modifications:
We are gonna edit 3 templates:online, ‘online_row_ip’ & ‘online_row_ip_lookup’.

1. Open template: ‘online_row_ip’, change this code:
 {$user['ip']}
To
 <span class="ip">{$user['ip']}</span> 

2. Open template: ‘online_row_ip_lookup’, keep existing code, add at the beginning:
 &nbsp;<a href="#" class="iplocate">[Locate]</a>&nbsp;
 
3. Open template: ‘online’, locate variable {$footer}, add after that:
<script type="text/javascript">
$(function () {
    $('.iplocate').on('click', function (e) {
        e.preventDefault();
        var ref = $(this);
        ajaxCall($.trim(ref.prev('.ip').text()), function (result) {
            ref.before('[' + result + ']').remove();
        });
    });

    function ajaxCall(ipdata, callback) {
        $.ajax({
            url: "http://ip-api.com/json/" + ipdata + "?fields=country,regionName,city",
            dataType: "json",
            cache: false,
            success: function (msg) {
                var result = (typeof msg == 'object') ? (msg.country + ', ' + msg.regionName + ', ' + msg.city) : "Unable to locate";
                callback(result);
            }
        });
    }
});
</script>


Save all templates. Result:



Note
  • If your server restricting CROB, you can get Cross-Origin Read Blocking warning in console, you can ignore the warning and the code will still work.
  • If you are using SSL (https://) this code will not work because in this tutorial we are using FREE ‘ip-api’ and secured XMLHttpRequest is a PAID service. You can purchase pro to make SSL access to API or ………… or there are few workarounds, but that’s another tutorial Toungue
So, that’s all for now. Happy coding …

I love this concept! But...

I do use SSL for my website and I am sure that many others do as well.

Can you do another tutorial that provides those workarounds?

Thanks!

ADDENDUM:

I just visited that website IP-API.com and saw the Pro pricing... ouch...

Based on that info... I'm certain now that you will get more requests for those workarounds.
[Image: 3448810d6b31dc9fdfaee41e53d14304.png]
Sure thing. Let me have some time.

By that time you can still use this. When you click on locate from https:// site a little shield will appear at the right side of your address bar (chrome). Clicking on it will turn your site insecured temporarily and the tutorial will work.
(2018-12-19, 08:06 PM)effone Wrote: [ -> ]Sure thing. Let me have some time.

By that time you can still use this. When you click on locate from https:// site a little shield will appear at the right side of your address bar (chrome). Clicking on it will turn your site insecured temporarily and the tutorial will work.

It's OK... I can wait for your new tutorial.
It is interesting effone, I might try it once I create my forum Smile
Nice effone, but do not use SSL is not recommended and alot of browsers (maybe all of them) displays notice about nonsexure connection Smile so thats why a majority of boards use https. Can you provide a tutorial for ssl anytime in a future? This seems to be really useful. Thank you!
Yes Eldenroot, probably tomorrow, will be able to manage some times, I hope ...
What about this one?

http://ip-api.com/
(2018-12-23, 04:44 PM)Eldenroot Wrote: [ -> ]What about this one?

http://ip-api.com/

That is the one we are using Eldenroot.
Okay I am writing the extended part (coding done, as you know). Will post shortly.
Yes, no rush, if anything let me know and we can discuss Smile
Pages: 1 2