function wiziapp_publish_post($post)
{
    $post_id = $post->ID;
    // @todo Get this from the saved options
    $tabId = WiziappConfig::getInstance()->main_tab_index;
    if (!WiziappConfig::getInstance()->notify_on_new_post) {
        $GLOBALS['WiziappLog']->write('info', "We are set not to notify on new post...", "notifications_events.wiziapp_publish_post");
        return;
    }
    $GLOBALS['WiziappLog']->write('info', "Notifying on new post", "notifications_events.wiziapp_publish_post");
    $request = null;
    if (WiziappConfig::getInstance()->aggregate_notifications) {
        $GLOBALS['WiziappLog']->write('info', "We need to aggregate the messages", "notifications_events.wiziapp_publish_post");
        // We might need to send this later...
        // let's check
        if (!isset(WiziappConfig::getInstance()->counters)) {
            WiziappConfig::getInstance()->counters = array('posts' => 0);
        }
        // Increase the posts count
        WiziappConfig::getInstance()->counters['posts'] += 1;
        // If the sum is set and not 0 we need to aggragate by posts count
        if (WiziappConfig::getInstance()->aggregate_sum) {
            // Have we reached or passed our trashhold
            if (WiziappConfig::getInstance()->counters['posts'] >= WiziappConfig::getInstance()->aggregate_sum) {
                // We need to notify on all the new posts
                $sound = WiziappConfig::getInstance()->trigger_sound;
                $badge = WiziappConfig::getInstance()->show_badge_number ? WiziappConfig::getInstance()->counters['posts'] : 0;
                $users = 'all';
                $request = array('type' => 1, 'sound' => $sound, 'badge' => $badge, 'users' => $users);
                if (WiziappConfig::getInstance()->show_notification_text) {
                    $request['content'] = urlencode(stripslashes(WiziappConfig::getInstance()->counters['posts'] . ' new posts published'));
                    $request['params'] = "{\"tab\": \"{$tabId}\"}";
                }
                // reset the counter
                WiziappConfig::getInstance()->counters['posts'] = 0;
            }
        }
    } else {
        // We are not aggragating the message
        $sound = WiziappConfig::getInstance()->trigger_sound;
        $badge = WiziappConfig::getInstance()->show_badge_number;
        $users = 'all';
        $request = array('type' => 1, 'sound' => $sound, 'badge' => $badge, 'users' => $users);
        if (WiziappConfig::getInstance()->show_notification_text) {
            $request['content'] = urlencode(stripslashes(__('New Post Published', 'wiziapp')));
            //$request['params'] = "{tab: \"{$tabId}\"}";
            $request['params'] = "{\"tab\": \"{$tabId}\"}";
        }
    }
    // Done setting up what to send, now send it..
    // Make sure we have a reason to even send this message
    if ($request == null || !$request['sound'] && !$request['badge'] && !$request['content']) {
        return;
    }
    // We have something to send
    $GLOBALS['WiziappLog']->write('info', "About to send a single notification event...", "notifications_events.wiziapp_publish_post");
    $response = wiziapp_http_request($request, '/push', 'POST');
}
/**
* Checks the user login information 
* 
* This webservice checks the sent user login information and can return either 
* true/false or the user basic information to the calling application
* 
* @package WiziappWordpressPlugin
* @subpackage AppWebServices
* @author comobix.com plugins@comobix.com
* 
* @param boolean $only_validate a flag indicating if the function should return a full response or just true/false
* @return boolean|array if $only_validate the function will return true/false but if not, 
*                       the websrvice will return the user information: (id, name, package, next_billing, direction)
*                       along with the usual information
* 
* @todo Calculate the next billing date according to the membership plugin
* @todo Get this from the user/blog
*/
function wiziapp_check_login($only_validate = FALSE)
{
    @header('Content-Type: application/json');
    $username = $_REQUEST['username'];
    $password = $_REQUEST['password'];
    $deviceToken = $_REQUEST['device_token'];
    $appToken = $_SERVER['HTTP_APPLICATION'];
    $udid = $_SERVER['HTTP_UDID'];
    // if the request doesn't contain all that we need - leave
    if (!empty($username) && !empty($password) && !empty($appToken) && !empty($udid)) {
        $user = wp_authenticate($username, $password);
        if (is_wp_error($user)) {
            $status = FALSE;
        } else {
            /* 
             * Notify the global admin of the CMS user id that is connected 
             * to the device token
             */
            if (!empty($deviceToken)) {
                $params = array('device_token' => $deviceToken);
                $headers = array('udid' => $udid);
                $response = wiziapp_http_request($params, '/push/user/' . $user->ID, $method = 'POST', $headers);
                // Mark the user so we will know he has a device token
                update_usermeta($user->ID, 'wiziapp_got_valid_mobile_token', $deviceToken);
            }
            $status = TRUE;
        }
        if ($only_validate) {
            return $status ? $user : FALSE;
        } else {
            // id, name, package, next_billing
            $result = array();
            if ($status) {
                $result = array("id" => $user->ID, "name" => $user->display_name, "package" => $user->user_level, "next_billing" => null, "direction" => "LTR");
            }
            $header = array('action' => 'login', 'status' => $status, 'code' => $status ? 200 : 4004, 'message' => $status ? '' : __('Incorrect username or password', 'wiziapp'));
            echo json_encode(array_merge(array('header' => $header), $result));
            exit;
        }
    } else {
        $GLOBALS['WiziappLog']->write('error', "Something in the request was missing: !empty({$username}) && !empty({$deviceToken}) && !empty({$appToken}) && !empty({$udid})", "remote");
    }
}
 /**
  * Check for the ability to issue outgoing requests
  * and accept requests from the api server.
  *
  * Covers the publicly accessible and out going requests tests
  *
  * @return bool|WiziappError can return true if everything is ok or an error object
  */
 public function testConnection()
 {
     $this->testedConnection = TRUE;
     // Get the blog address
     $blogUrl = get_bloginfo('url');
     /**
      * Send a request to the admin to check access to this address
      * it's POST since we need a more restrictive method, there is way
      * to allow Wordpress to send GET request but not POST
      *
      * The post request must have a value to avoid issues with Content-Length  invalid and
      * 413 Request Entity Too Large as a result...
      */
     $response = wiziapp_http_request(array('param' => 1), '/cms/checkUrl?url=' . urlencode($blogUrl), 'POST');
     if (is_wp_error($response)) {
         // If we couldn't connect to the host, outbound connections might be blocked
         if ("couldn't connect to host" == $response->get_error_message()) {
             $this->critical = TRUE;
             $this->hadConnectionError = TRUE;
             return new WiziappError('testing_connection_failed', __('It seems that your server is blocked from issuing outgoing requests to our server. Please make sure your firewall and any other security measures enable outgoing connections.', 'wiziapp'));
         } else {
             return new WiziappError($response->get_error_code(), $response->get_error_message());
         }
     } else {
         // The request worked, but was our server able to contact our url?
         $checkResult = json_decode($response['body']);
         if (empty($checkResult)) {
             if (isset($response['response']) && isset($response['response']['code']) && $response['response']['code'] === FALSE) {
                 $this->critical = TRUE;
                 $this->hadConnectionError = TRUE;
                 return new WiziappError('testing_connection_failed', __('Your host does not allow any kind of outgoing requests. WiziApp requires either HTTP Extension, cURL, Streams, or Fsockopen to be installed and enabled. Please contact your hosting provider to address this issue.', 'wiziapp'));
             } else {
                 // The response wasn't in a json format
                 return new WiziappError('testing_connection_failed', 'The WiziApp plugin has encountered a problem. Please contact us at support@wiziapp.com to see how we can help you resolve this issue');
             }
         } else {
             // The response is ok, let's check when our server is saying
             if (!$checkResult->header->status) {
                 return new WiziappError('testing_connection_failed', $checkResult->header->message);
             }
         }
     }
     // If we made it this far, all is good
     return TRUE;
 }
/**
* @package WiziappWordpressPlugin
* @subpackage AdminDisplay
* @author comobix.com plugins@comobix.com
*/
function wiziapp_generator_display()
{
    // Before opening this display get a one time usage token
    $response = wiziapp_http_request(array(), '/generator/getToken?app_id=' . WiziappConfig::getInstance()->app_id, 'GET');
    $tokenResponse = json_decode($response['body'], TRUE);
    $iframeId = 'wiziapp_generator' . time();
    if (!$tokenResponse['header']['status']) {
        // There was a problem with the token
        echo '<div class="error">' . $tokenResponse['header']['message'] . '</div>';
    } else {
        $token = $tokenResponse['token'];
        $httpProtocol = 'https';
        ?>
        <script src="http://cdn.jquerytools.org/1.2.5/all/jquery.tools.min.js"></script>
        <style>
        .overlay_close {
            background-image:url(<?php 
        echo WiziappConfig::getInstance()->getCdnServer();
        ?>
/images/generator/close.png);
            position:absolute; right:-17px; top:-17px;
            cursor:pointer;
            height:35px;
            width:35px;
        }
        #wiziappBoxWrapper{
            width: 390px;
            height: 760px;
            margin: 0px auto;
            padding: 0px;
            background: url(<?php 
        echo WiziappConfig::getInstance()->getCdnServer();
        ?>
/images/simulator/phone.png) no-repeat scroll 8px 8px;
        }
        #wiziappBoxWrapper.sim_loaded{
            background-image: none;
        }
        #wiziappBoxWrapper #loading_placeholder{
            position: absolute;
            color:#E0E0E0;
            font-weight:bold;
            height:60px;
            top: 260px;
            left: 170px;
            width:75px;
            z-index: 0;
        }
        #wiziappBoxWrapper.sim_loaded #loading_placeholder{
            display: none;
        }
        #wiziappBoxWrapper iframe{
            visibility: hidden;
        }
        #wiziappBoxWrapper.sim_loaded iframe{
            visibility: visible;
        }
        #wiziapp_generator_container{
            background: #fff;
        }
        .processing_modal{
            background: url(<?php 
        echo WiziappConfig::getInstance()->getCdnServer();
        ?>
/images/generator/Pament_Prossing_Lightbox.png) no-repeat top left;
            display:none;
            height: 70px;
            padding: 25px 35px;
            width: 426px;
        }
        #publish_modal .processing_message{
            font-size: 17px;
        }
        #publish_modal .loading_indicator{
            margin: 8px auto 2px;
        }
        #create_account_modal_close{
            display: none;
            clear: both;
            float: none;
        }
        .processing_modal .error{
            margin: 0px;
            width: 407px;
        }
        
        .processing_message{
            color: #000000;
            font-size: 18px;
            font-family: arial;
            margin: 2px 0;
            padding-left: 20px;
        }
        
        .processing_modal .loading_indicator{
            background: url(<?php 
        echo WiziappConfig::getInstance()->getCdnServer();
        ?>
/images/generator/lightgrey_counter.gif) no-repeat;
            width: 35px;
            height: 35px;
            margin: 2px auto;
        }
        #general_error_modal{
            z-index: 999;
        }

        </style>
        <div id="wiziapp_generator_container">
            <?php 
        //$iframeSrc = 'http://'.wiziapp_getApiServer().'/generator?t='.$token;
        //$iframeSrc = $httpProtocol.'://'.wiziapp_getServicesServer().'/generator?t='.$token;
        $iframeSrc = $httpProtocol . '://' . WiziappConfig::getInstance()->api_server . '/generator/index/' . $token . '?v=' . WIZIAPP_P_VERSION;
        ?>
            <script type="text/javascript">
                var WIZIAPP_HANDLER = (function(){
                    jQuery(document).ready(function(){
                        jQuery('.report_issue').click(reportIssue);
                        jQuery('.retry_processing').click(retryProcessing);

                        jQuery('#general_error_modal').bind('closingReportForm', function(){
                            jQuery(this).addClass('s_container');
                        });
                    });

                    function wiziappReceiveMessage(event){
                        // Just wrap our handleRequest 
                        if ( event.origin == '<?php 
        echo "{$httpProtocol}://" . WiziappConfig::getInstance()->api_server;
        ?>
' ){
                            WIZIAPP_HANDLER.handleRequest(event.data);   
                        }
                    };
                    
                    if ( window.addEventListener ){ 
                        window.addEventListener("message", wiziappReceiveMessage, false);
                    }

                    var actions = {
                        informErrorProcessing: function(params){
                            var $box = jQuery('#'+params.el);
                            $box
                                .find('.processing_message').hide().end()
                                .find('.loading_indicator').hide().end()
                                .find('.error').text(params.message).show().end()
                                .find('.close').show().end();
                            
                            $box = null;   
                        },
                        closeProcessing: function(params){
                            jQuery('#'+params.el).data("overlay").close();                             
                            if (typeof(params.reload) != 'undefined'){
                                if (params.reload == 1){
                                    if (typeof(params.qs) != 'undefined'){
                                        var href = top.location.href;
                                        var seperator = '?';
                                        if (href.indexOf('?')) {
                                            seperator = '&';
                                        }
                                        href += seperator + unescape(params.qs);    
                                        top.location.replace(href);    
                                    } else {
                                        top.location.reload(true);
                                    }
                                }
                            }
                            
                            if ( typeof(params.resizeTo) != 'undefined' ){
                                actions.resizeGeneratorIframe({height: params.resizeTo});
                            }
                        },
                        informGeneralError: function(params){
                             var $box = jQuery('#'+params.el);
                            $box
                                .find('.wiziapp_error').text(params.message).end();

                            if ( parseInt(params.retry) == 0 ){
                                $box.find('.retry_processing').hide();
                            } else {
                                $box.find('.retry_processing').show();
                            }

                            if ( parseInt(params.report) == 0 ){
                                $box.find('.report_issue').hide();
                            } else {
                                $box.find('.report_issue').show();
                            }

                            if (!$box.data("overlay")){
                                $box.overlay({
                                    fixed: true,
                                    top: 200,
                                    left: (screen.width / 2) - ($box.outerWidth() / 2),
                                    /**mask: {
                                        color: '#444444',
                                        loadSpeed: 200,
                                        opacity: 0.9
                                    },*/
                                    // disable this for modal dialog-type of overlays
                                    closeOnClick: false,
                                    closeOnEsc: false,
                                    // load it immediately after the construction
                                    load: true,
                                    onBeforeLoad: function(){
                                        var $toCover = jQuery('#wpbody');
                                        var $mask = jQuery('#wiziapp_error_mask');
                                        if ( $mask.length == 0 ){
                                            $mask = jQuery('<div></div>').attr("id", "wiziapp_error_mask");
				                            jQuery("body").append($mask);
                                        }

                                        $mask.css({
                                            position:'absolute',
                                            top: $toCover.offset().top,
                                            left: $toCover.offset().left,
                                            width: $toCover.outerWidth(),
                                            height: $toCover.outerHeight(),
                                            display: 'block',
                                            opacity: 0.9,
                                            backgroundColor: '#444444'
                                        });

                                        $mask = $toCover = null;
                                    }
                                });
                            }
                            else {
                                $box.show();
                                $box.data("overlay").load();
                            }
                            $box = null;
                        },
                        showProcessing: function(params){
                            var $box = jQuery('#'+params.el);
                            $box
                                .find('.error').hide().end()
                                .find('.loading_indicator').show().end()
                                .find('.close').hide().end()
                                .find('.processing_message').show().end();
                                
                            if (!$box.data("overlay")){
                                $box.overlay({
                                    fixed: true,
                                    top: 200,
                                    left: (screen.width / 2) - ($box.outerWidth() / 2),
                                    mask: {
                                        color: '#444444',
                                        loadSpeed: 200,
                                        opacity: 0.9
                                    },

                                    // disable this for modal dialog-type of overlays
                                    closeOnClick: false,
                                    // load it immediately after the construction
                                    load: true
                                });
                            }
                            else {
                                $box.show();
                                $box.data("overlay").load();
                            }
                            
                            $box = null;    
                        },
                        showSim: function(params){
                            var url = decodeURIComponent(params.url);
                            url = url + '&rnd=' + Math.floor(Math.random()*999999);
                            var $box = jQuery("#wiziappBoxWrapper");
                            if ($box.length == 0){
                                $box = jQuery("<div id='wiziappBoxWrapper'><div class='close overlay_close'></div><div id='loading_placeholder'>Loading...</div><iframe id='wiziappBox'></iframe>");
                                $box.find("iframe").attr('src', url+"&preview=1").unbind('load').bind('load', function(){
                                    jQuery("#wiziappBoxWrapper").addClass('sim_loaded');
                                });
                                
                                $box.appendTo(document.body);
                                
                                $box.find("iframe").css({
                                    'border': '0px none',
                                    'height': '760px',
                                    'width': '390px'
                                });
                                
                                $box.overlay({
                                    top: 20,
                                    fixed: false,
                                    mask: {
                                        color: '#444',
                                        loadSpeed: 200,
                                        opacity: 0.8
                                    },
                                    closeOnClick: true,
                                    onClose: function(){
                                        jQuery("#wiziappBoxWrapper").remove();
                                    },
                                    load: true
                                });
                            }
                            else {
                                $box.show();
                                $box.data("overlay").load();
                            }
                            
                            $box = null;
                        },
                        resizeGeneratorIframe: function(params){
                            jQuery("#<?php 
        echo $iframeId;
        ?>
").css({
                                'height': (parseInt(params.height) + 50) + 'px'
                            });
                        }                                                      
                    };

                    function retryProcessing(event){
                        event.preventDefault();
                        document.location.reload(true);
                        return false;
                    };

                    function reportIssue(event){
                        // Change the current box style so it will enable containing the report form
                        event.preventDefault();
                        var $box = jQuery('#general_error_modal');                        
                        var $el = $box.find('.report_container');

                        var params = {
                            action: 'wiziapp_report_issue',
                            data: $box.find('.wiziapp_error').text()
                        };

                        $el.load(ajaxurl, params, function(){
                            var $mainEl = jQuery('#general_error_modal');
                            $mainEl
                                    .removeClass('s_container')
                                    .find(".errors_container").hide().end()
                                    .find(".report_container").show().end();
                            $mainEl = null;
                        });

                        var $el = null;
                        return false;
                    };
                    
                    return {
                        handleRequest: function(q){
                            var paramsArray = q.split('&');
                            var params = {};
                            for (var i = 0; i < paramsArray.length; ++i) {
                                var parts = paramsArray[i].split('=');
                                params[parts[0]] = decodeURIComponent(parts[1]);
                            }
                            if (typeof(actions[params.action]) == "function"){
                                actions[params.action](params);
                            }
                            params = q = paramsArray = null;
                        }
                    };                    
                })();
                
                jQuery(document).ready(function($){
                    var $iframe = $("<iframe frameborder='0'>");
                    $("#wiziapp_generator_container").prepend($iframe);
                    $iframe.css({
                        'overflow': 'hidden',
                        'width': '100%',
                        'height': '1000px', 
                        'border': '0px none'
                    }).attr({
                        'src': "<?php 
        echo $iframeSrc;
        ?>
",
                        'frameborder': '0',
                        'id': '<?php 
        echo $iframeId;
        ?>
'
                    });
                });
            </script>
        </div>

        <div class="hidden wiziapp_errors_container s_container" id="general_error_modal">
            <div class="errors_container">
                <div class="errors">
                    <div class="wiziapp_error"></div>
                </div>
                <div class="buttons">
                    <a href="javascript:void(0);" class="report_issue">Report a Problem</a>
                    <a class="retry_processing close" href="javascript:void(0);">Retry</a>
                </div>
            </div>
            <div class="report_container hidden">

            </div>
        </div>

        <div class="processing_modal" id="create_account_modal">
            <p class="processing_message">Please wait while we place your order...</p>
            <div class="loading_indicator"></div>
            <p class="error" class="errorMessage hidden"></p>
            <a class="close hidden" href="javascript:void(0);">Go back</a>
        </div>
        
        <div class="processing_modal" id="publish_modal">
            <p class="processing_message">Please wait while we are processing your request...</p>
            <div class="loading_indicator"></div>
            <p class="error" class="errorMessage hidden"></p>
            <a class="close hidden" href="javascript:void(0);">Go back</a>
        </div>
        
        <div class="processing_modal" id="reload_modal">
            <p class="processing_message">It seems your session has timed out.</p> 
            <p>please <a href="javascript:top.document.location.reload(true);">refresh</a> this page to try again</p>
            <p class="error" class="errorMessage hidden"></p>
            <a class="close hidden" href="javascript:void(0);">Go back</a>
        </div>
        <?php 
    }
}
 public function deactivate()
 {
     // Inform the system control
     $blogUrl = get_bloginfo('url');
     $urlData = explode('://', $blogUrl);
     $response = wiziapp_http_request(array(), '/cms/deactivate?app_id=' . WiziappConfig::getInstance()->app_id . '&url=' . urlencode($urlData[1]), 'POST');
     $this->deleteUser();
 }
function wiziapp_version_check()
{
    $needCheck = TRUE;
    $needShow = TRUE;
    // Check only if we didn't check in the last 12 hours
    if (isset(WiziappConfig::getInstance()->last_version_checked_at)) {
        // We checked for the version already, but was it in the last 12 hours?
        if (time() - WiziappConfig::getInstance()->last_version_checked_at <= 60 * 60 * 12) {
            // We need to check again
            $needCheck = FALSE;
        }
    }
    if ($needCheck) {
        // Get the current version
        if (empty(WiziappConfig::getInstance()->wiziapp_avail_version)) {
            WiziappConfig::getInstance()->wiziapp_avail_version = WIZIAPP_P_VERSION;
        }
        $response = wiziapp_http_request(array(), '/cms/version', 'GET');
        if (!is_wp_error($response)) {
            $vResponse = json_decode($response['body'], TRUE);
            if (!empty($vResponse)) {
                WiziappConfig::getInstance()->wiziapp_avail_version = $vResponse['version'];
                WiziappConfig::getInstance()->last_version_checked_at = time();
                //update_option('wiziapp_settings', $options);
            }
        }
    }
    if (WiziappConfig::getInstance()->wiziapp_avail_version != WIZIAPP_P_VERSION) {
        if (isset(WiziappConfig::getInstance()->show_need_upgrade_msg) && WiziappConfig::getInstance()->show_need_upgrade_msg === FALSE) {
            // The user choose to hide the version alert, but was the version alert for the version he saw?
            if (WiziappConfig::getInstance()->last_version_shown === WiziappConfig::getInstance()->wiziapp_avail_version) {
                $needShow = FALSE;
            }
        }
        if ($needShow) {
            ?>
            <div id="wiziapp_upgrade_needed_message" class="updated fade">
                <p style="line-height: 150%">
                    An important update is available for the WiziApp WordPress plugin.
                    <br />
                    Make sure to update as soon as possible, to enjoy the security, bug fixes and new features contained in this update.
                </p>
                <p>
                    <input id="wiziappHideUpgrade" type="button" class="button" value="Hide this message" />
                </p>
                <script type="text/javascript">
                jQuery(document).ready(function(){
                    jQuery("#wiziappHideUpgrade").click(function(){
                        var params = {
                            action: 'wiziapp_hide_upgrade_msg'
                        };
                        jQuery.post(ajaxurl, params, function(data){
                            jQuery("#wiziapp_upgrade_needed_message").remove();
                        });     
                    });    
                });
                </script>
            </div>    
        <?php 
        }
    }
}
/**
* @package WiziappWordpressPlugin
* @subpackage PushNotifications
* @author comobix.com plugins@comobix.com
*/
function wiziapp_notifications_display()
{
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $sound = isset($_POST['sound']) ? 1 : 0;
        $badge = isset($_POST['badge']) ? 1 : 0;
        $users = array();
        $choose_all = FALSE;
        if (is_array($_POST['users'])) {
            foreach ($_POST['users'] as $user) {
                // If the user has choosen all users, no need to enter indeviduals entries
                if (!$choose_all) {
                    $users[] = $user;
                }
                // If the user choose all mark it so we will know
                if ($user == 'all') {
                    $choose_all = TRUE;
                }
            }
        }
        $users_of_blog = get_users_of_blog();
        $avail_roles = array();
        $avail_roles['all'] = array();
        if (!$choose_all) {
            foreach ((array) $users_of_blog as $b_user) {
                if (get_usermeta($b_user->ID, 'wiziapp_got_valid_mobile_token') == '1') {
                    $b_roles = unserialize($b_user->meta_value);
                    foreach ((array) $b_roles as $b_role => $val) {
                        if (!isset($avail_roles[$b_role])) {
                            $avail_roles[$b_role] = array();
                        }
                        $avail_roles[$b_role][] = $b_user->ID;
                        $avail_roles['all'] = $b_user->ID;
                    }
                }
            }
        }
        unset($users_of_blog);
        if (is_array($_POST['roles'])) {
            foreach ($_POST['roles'] as $role) {
                // Merge all the users that have this role
                if (isset($avail_roles[$role]) && is_array($avail_roles[$role])) {
                    array_merge($avail_roles[$role], $users);
                }
            }
        }
        unset($users_of_blog);
        unset($avail_roles);
        // Avoid sending the same user twice so if the user was selected
        // already don't readd it
        $users = array_unique($users);
        $request = array('content' => urlencode(stripslashes($_POST['message'])), 'type' => 2, 'sound' => $sound, 'badge' => $badge, 'users' => implode(",", $users));
        $response = wiziapp_http_request($request, '/push', 'POST');
        if (!is_wp_error($response)) {
            print_r($response);
        } else {
            echo $response['body'];
        }
    }
    ?>
	<div class="wrap">
		<h2>Send notifications</h2>
		<form name="fmrCustomNotifications" action="<?php 
    echo $_SERVER["REQUEST_URI"];
    ?>
" method="POST">
			<p>
				<input name="message" size="50" maxsize="50" type="text" value="" /><input type="submit" class="button-primary" value="Send" />
				<br />
				<label>
					<input type="checkbox" name="sound" checked="checked" />
					<span>Sound?</span>
				</label>
				<label>
					<input type="checkbox" name="badge" checked="checked" />
					<span>Badge?</span>
				</label>
			</p>
			<p>
				<label>Choose Users: </label>
				<br />
				<select name="users[]" multiple="multiple" size="5" style="height:auto;">
					<option value="all">All the users that have a token</option>
					<?php 
    $users_of_blog = get_users_of_blog();
    $total_users = count($users_of_blog);
    $avail_roles = array();
    $html = '';
    foreach ((array) $users_of_blog as $b_user) {
        if (get_usermeta($b_user->ID, 'wiziapp_got_valid_mobile_token')) {
            $html .= "<option value='{$b_user->ID}'>{$b_user->display_name}</option>";
            $b_roles = unserialize($b_user->meta_value);
            foreach ((array) $b_roles as $b_role => $val) {
                if (!isset($avail_roles[$b_role])) {
                    $avail_roles[$b_role] = 0;
                }
                $avail_roles[$b_role]++;
            }
        }
    }
    unset($users_of_blog);
    echo $html;
    ?>
				</select>
				
			</p>
			<p>
				<label>Send to users with roles: </label>
				<br />
				<small>Only roles that have users with device tokens connected to them will be listed here</small>
				<br />
				<select name="roles[]" multiple="multiple" size="5" style="height:auto;">
					<option value="all">All</option>
					<?php 
    $html = '';
    foreach ((array) $avail_roles as $role_name => $count) {
        $html .= "<option value='{$role_name}'>{$role_name}</option>";
    }
    echo $html;
    ?>
				</select>
				
			</p>
		</form>
	</div>
	<?php 
}