<?php

/**
 * Twilio Component
 * 
 * This component allows monitoring contacts to use a Twilio inbound SMS for notifications.
 *
 * Copyright (c) 2011-2018 Nagios Enterprises, LLC. All rights reserved.
 *
 * @category    component
 * @author      Nagios XI
 * @copyright   2011-2024 Nagios Enterprises, LLC
 * @version     1.0.3
 */

require_once(dirname(__FILE__) . '/../componenthelper.inc.php');

// global constants
$twilio_component_name = 'twilio';

// initialize component
init_twilio_component();


/**
 * Initializes and registers Twilio component
 */
function init_twilio_component()
{
    global $twilio_component_name;

    $desc = _('Provides integration with Twilio SMS.') . '</br>' .
        '<strong>' . _('Requires') . '</strong> ' .
        _('Twilio SMS') . 
        '<a href="https://assets.nagios.com/downloads/nagiosxi/docs/Twilio-SMS-Integration-in-Nagios-XI-2024.pdf" 
        target="_blank" rel="nofollow" title="Documentation" >
        ' . _('setup') . '</a>.';

    $comp_args = array(
        COMPONENT_NAME              => $twilio_component_name,
        COMPONENT_VERSION           => '1.0.4',
        COMPONENT_DATE              => '05/28/2024',
        COMPONENT_AUTHOR            => "Nagios Enterprises, LLC",
        COMPONENT_DESCRIPTION       => $desc,
        COMPONENT_TITLE             => _("Twilio SMS Integration"),
        COMPONENT_CONFIGFUNCTION    => 'configure_twilio_component'
    );

    // Register this component with XI
    register_component($twilio_component_name, $comp_args);
    
    $method_args = array(
        NOTIFICATIONMETHOD_FUNCTION => 'twilio_notificationmethod_func'
    );

    // Register notification method function
    register_notificationmethod($twilio_component_name, $method_args);

    // Register notification method callback to add a tab
    register_callback(CALLBACK_USER_NOTIFICATION_METHODS_TABS_INIT, 
        'add_twilio_notification_tab');
    
    // Register notification message callback to add a tab
    register_callback(CALLBACK_USER_NOTIFICATION_MESSAGES_TABS_INIT,
        'add_twilio_notification_tab');

    // Register event processed callback to send cron notifications
    register_callback(CALLBACK_EVENT_PROCESSED,
        'handle_twilio_event');
}


/**
 * Creates and adds twilio tab using user notification callback
 *
 * @param   string  $cbtype     type of the callback in string
 * @param   array   $cbargs     contains the notification tab array 
 * @return  string  $err_msg    error output
 */
function add_twilio_notification_tab($cbtype, &$cbargs) 
{
    global $twilio_component_name;

    $err_msg = '';

    if (!is_twilio_enabled()) {
        $err_msg = 'Twilio component integration is not enabled';
        return $err_msg;
    }

    // validate callback type
    if (   $cbtype != CALLBACK_USER_NOTIFICATION_METHODS_TABS_INIT
        && $cbtype != CALLBACK_USER_NOTIFICATION_MESSAGES_TABS_INIT) {
        
        $err_msg = "Invalid callback type: $cbtype";
        return $err_msg;
    }

    // validate callback args
    if (empty($cbargs)) {
        $err_msg = "Invalid callback args: $cbargs";
        return $err_msg;
    }

    // create and add a twilio tab
    $cbargs['tabs'][] = array(
        'id'    => $twilio_component_name,
        'title' => _('Twilio Text (SMS)'),
    );
}


/**
 * Manages the configuration of twilio
 */
function configure_twilio_component($mode, $inargs, &$outargs, &$result) 
{
    global $twilio_component_name;
    
    $twilio_component_url = get_component_url_base($twilio_component_name);
    $current_user_id = $_SESSION['user_id'];

    // initialize return code
    $result = 0;
    $output = '';

    switch ( $mode ) {
    
    case COMPONENT_CONFIGMODE_GETSETTINGSHTML:

        // grab the serialized component options
        $settings = get_option('twilio_options');
        
        // validate the component options
        if (empty($settings)) {
            $settings = array();
        } 
        else {
            $settings = unserialize($settings);
        }

        // initial values
        $is_enabled = grab_array_var($settings, 'is_enabled', '');
        $account_sid = grab_array_var($settings, 'sid', '');
        $auth_token = grab_array_var($settings, 'auth_token', '');
        $twilio_phone = grab_array_var($settings, 'twilio_phone', '');
        $twilio_country_code = grab_array_var($settings, 'twilio_country_code', '');

        // saved option values
        $is_enabled = checkbox_binary(grab_array_var($inargs, 'is_enabled', $is_enabled));
        $account_sid = grab_array_var($inargs, 'sid', $account_sid);
        $auth_token = grab_array_var($inargs, 'auth_token', $auth_token);
        $twilio_phone = grab_array_var($inargs, 'twilio_phone', $twilio_phone);
        $twilio_country_code = grab_array_var($inargs, 'twilio_country_code', $twilio_country_code);

        // sanitize user input
        $account_sid = preg_replace("/[^a-zA-Z0-9]+/", "", $account_sid);
        $auth_token = preg_replace("/[^a-zA-Z0-9]+/", "", $auth_token);
        $twilio_phone = preg_replace('/\D/', '', $twilio_phone);
        $twilio_country_code = preg_replace('/\D/', '', $twilio_country_code);

        // add twilio number dropdown
        $twilio_country_dropdown = generate_dropdown('twilio_country_code', $twilio_country_code);

        // add test number dropdown. Default to 1.
        $twilio_test_country_dropdown = generate_dropdown('twilio_test_country_code', 1);

        // output 
        $output .="
 
                <p>" . _("Allows integration between Nagios XI and Twilio SMS API for notifications.") . "</br>
                    <strong>" . _("Requires"). "</strong>" . _(" an existing Twilio account ") . 
                        "<a href='https://assets.nagios.com/downloads/nagiosxi/docs/Setting-Up-SMS-Alerts-in-Nagios-XI-2024.pdf'
                            target='_blank' title='Documentation' >" . 
                        _("setup") . ".</a> </br> 
                <p style='margin-top:5px;'><a href='https://www.twilio.com' target='_blank'>
                    <img src='" . $twilio_component_url . "/twilio.png' alt='Twilio SMS' 
                    height= '50' width = '170'/></a></p>
                

                <h5 class='ul'>" . _("Account Authentication Settings") . "</h5>
                <p>" . _("These settings allow Nagios XI to authenticate against Twilio API 
                    for Twilio SMS notifications setup.") . "</p>
                <table class='table table-condensed table-no-border table-auto-width'>
                    <tr>        
                        <td style='padding-bottom:20px;'>
                            <label>" . _("Account SID")."<span style='color:red;'>*</span>:</label>
                        </td>
                        <td>
                            <input type='password' size='45' name='"."sid"."' id='"."sid"."'
                            value='" . $account_sid . "' class='form-control' autocomplete='off'>
                            <div class='subtext'>" . _("The SID of the account.")."</div>
                        </td>
                        <td style='padding-bottom:22px;padding-left:0px;'>
                            <button type='button' title='Show SID' id='show_sid' name='show_sid' class='btn btn-sm btn-default tt-bind btn-show-password'><i class='fa fa-eye'></i></button> 
                        </td>
                    </tr>
                    <tr>
                        <td style='padding-bottom:20px;'>
                            <label>" . _("Authentication Token")."<span style='color:red;'>*</span>:</label>
                        </td>
                        <td>
                            <input type='password' size='45' name='"."auth_token"."' id='"."auth_token"."'
                            value='" . $auth_token . "' class='form-control' autocomplete='off'>
                            <div class='subtext'>" . _("The authentication token of the account.") .
                        "</td>
                        <td style='padding-bottom:22px;padding-left:0px;'>
                            <button type='button' title='Show Token' id='show_token' name='show_token' class='btn btn-sm btn-default tt-bind btn-show-password'><i class='fa fa-eye'></i></button> 
                        </td>
                        <td style='padding-bottom:22px;'>
                            <button type='button' class='btn btn-sm btn-info' id='".'twilio_config_auth'."' name='".'twilio_config_auth'."' style='display:none;'>
                            "._('Authenticate ')."<i class='fa fa-chevron-right r'></i></button>
                        </td>
                    </tr>               
                    <tr>
                        <td style='padding-bottom:20px;'>
                            <label>" . _("Twilio Phone Number")."<span style='color:red;'>*</span>:</label>
                        </td>
                        <td>
                            <div style='display:inline;'>".$twilio_country_dropdown."</div>
                            <input type='text' size='40' name='"."twilio_phone"."' id='"."twilio_phone"."'
                            value='" . $twilio_phone . "' class='form-control' style='margin-left:-5px; width:213px;'>
                            <div class='subtext'>" . _("Twilio SMS mobile number to send SMS notifications from.") .
                        "</td>
                    </tr>               
                </table>

                <h5 class='ul'>" . _("Test Notification (Optional)") . "</h5>   
                <p>" . _("Specify the phone number to send a test SMS notification to.") . " </p>
                <table class='table table-condensed table-no-border table-auto-width'>
                    <tr>        
                        <td>
                            <label for='test_twilio_phone'>" . _("Phone Number:") . "</label>
                        </td>
                        <td>
                            <div style='display:inline;'>".$twilio_test_country_dropdown."</div>
                            <input type='text' size='40' name='"."test_twilio_phone"."' id='"."test_twilio_phone"."'
                            class='form-control' style='margin-left:-5px; width:213px;'>
                        <td>
                            <button type='button' class='btn btn-sm btn-info' id='".'send_twilio_test_config'."' name='".'send_twilio_test_config'."'>
                            "._('Send Test Notification ')."<i class='fa fa-chevron-right r'></i></button>
                        </td>
                    </tr>
                </table>

                <h5 class='ul'>" . _("Integration Settings") . "</h5>   
                 <p>"._("Once integrated, all monitoring contacts can set up their notification preferences to receive Nagios event notifications
                    via Twilio phone number specified below.") ."</p>  
                <table class='table table-condensed table-no-border table-auto-width'>
                    <tr>        
                        <td class='checkbox'>
                            <label>
                                <input type= 'checkbox' class='checkbox' id='" . "is_enabled" . "' 
                                name='" . "is_enabled" . "' " . is_checked($is_enabled, 1) . "><span style='font-weight:700;'>" . 
                                _("Enable Integration") . 
                            "</span></label>
                        </td>
                    </tr>
                </table>


                <p style='font-size: 7pt;'>" . _("Twilio, Twiml and Twilio logo are registered trademarks of Twilio and/or its affiliates. Other names may be trademarks of their respective owners") . 
                " <a href='https://www.twilio.com' target='_blank'>Twilio, Inc.</a></p>
               
                <script>
               
                    $(document).ready(function() { 

                        //////////////////
                        // show sid button
                        //////////////////
                        $('#show_sid').click( function() {
                            var sid = document.getElementById('sid');
                            var icon = document.getElementById('show_sid');

                            if (sid.type == 'password') {
                                sid.type = 'text';
                                icon.innerHTML = '<i class=".'"fa fa-eye-slash"'."></i>';
                                $('#show_sid').attr('data-original-title', 'Hide SID');
                            }
                            else {
                                sid.type = 'password';
                                icon.innerHTML = '<i class=".'"fa fa-eye"'."></i>';

                                $('#show_sid').attr('data-original-title', 'Show SID');
                            }
                        });



                        //////////////////
                        // show token button
                        //////////////////
                        $('#show_token').click( function() {
                            var token = document.getElementById('auth_token');
                            var icon = document.getElementById('show_token');

                            if (token.type == 'password') {
                                token.type = 'text';
                                icon.innerHTML = '<i class=".'"fa fa-eye-slash"'."></i>';
                                $('#show_token').attr('data-original-title', 'Hide Token');
                            }
                            else {
                                token.type = 'password';
                                icon.innerHTML = '<i class=".'"fa fa-eye"'."></i>';

                                $('#show_token').attr('data-original-title', 'Show Token');
                            }
                        });


                        //////////////////
                        // authenticate
                        //////////////////
                        $('#twilio_config_auth').click( function() {
                            var sid = document.getElementById('sid').value;
                            var token = document.getElementById('auth_token').value;

                            if (sid === '' || token === '') {
                                alert('You must provide both the SID and the token to authenticate!');
                                return;
                            } 

                            $.ajax({
                                url: '".$twilio_component_url."/twilio_ajax_handler.php',
                                type: 'POST',
                                data: { mode: 'config_authentication',
                                        user_id: '".$current_user_id."',
                                        sid: sid,
                                        token, token},
                                success: function(data) {
                                    if (data == 'Success!') {
                                        document.getElementById('twilio_config_auth').innerHTML = 'Authenticated';
                                        document.getElementById('twilio_config_auth').disabled = true;

                                        document.getElementById('sid').readOnly = true;
                                        document.getElementById('auth_token').readOnly = true;
                                    } else {
                                        alert(data);
                                    }
                                },
                                failure: function(xhr, error_string, error_thrown) {
                                    alert(error_string);
                                },
                            });
                        });




                        //////////////////
                        // test notification
                        //////////////////
                        $('#send_twilio_test_config').click( function() {
    
                            var sid = document.getElementById('sid').value;
                            var token = document.getElementById('auth_token').value;
                            var twilio_country_code_options = document.getElementById('twilio_country_code');
                            var twilio_country_code = twilio_country_code_options.options[twilio_country_code_options.selectedIndex].value;
                            var twilio_phone_number = document.getElementById('twilio_phone').value;
                            var twilio_test_country_code_options = document.getElementById('twilio_test_country_code');
                            var twilio_test_country_code = twilio_test_country_code_options.options[twilio_test_country_code_options.selectedIndex].value;
                            var test_twilio_phone = document.getElementById('test_twilio_phone').value;

                            // check if any values are empty
                            if (sid === '' || token === '' || twilio_phone_number === '') {
                                alert('Please complete the authentication settings.');
                                return;
                            }
                            if (test_twilio_phone === '') {
                                alert('Please specify the test phone number.');
                                return;
                            }    

                            $.ajax({
                                url: '".$twilio_component_url."/twilio_ajax_handler.php',
                                type: 'POST',
                                data: { mode: 'send_twilio_test_config',
                                        user_id: '".$current_user_id."', 
                                        sid: sid,
                                        token: token,
                                        twilio_country_code: twilio_country_code,
                                        twilio_phone_number: twilio_phone_number,
                                        twilio_test_country_code: twilio_test_country_code,
                                        test_twilio_phone: test_twilio_phone},
                                success: function(data) {
                                    if (data == 'Success!') {
                                        document.getElementById('send_twilio_test_config').innerHTML = 'Successfully Sent!';
                                        document.getElementById('send_twilio_test_config').disabled = true;
                                    } 
                                    else {
                                        alert(data);
                                    }
                                },
                                failure: function(xhr, error_string, error_thrown) {
                                    alert('Error sending test notification');
                                },
                            });
                        });
                    });

                </script> 
        ";
        break;


    case COMPONENT_CONFIGMODE_SAVESETTINGS:

        // grab values
        $is_enabled = checkbox_binary(grab_array_var($inargs, 'is_enabled', ''));
        $account_sid = grab_array_var($inargs, 'sid', '');
        $auth_token = grab_array_var($inargs, 'auth_token', '');
        $twilio_country_code = grab_array_var($inargs, 'twilio_country_code', '');
        $twilio_phone = grab_array_var($inargs, 'twilio_phone', '');

        // sanitize user input 
        $account_sid = preg_replace("/[^a-zA-Z0-9]+/", "", $account_sid);
        $auth_token = preg_replace("/[^a-zA-Z0-9]+/", "", $auth_token);
        $twilio_phone = preg_replace('/\D/', '', $twilio_phone);
        $twilio_country_code = preg_replace('/\D/', '', $twilio_country_code);

        // validate values
        $errors = 0;
        $errmsg = array();
        $okmsg = array();
        if ($is_enabled) {
            if (!have_value($account_sid)) {
                $errmsg[$errors++] = _('Please specify the SID.');
            }
            if (!have_value($auth_token)) {
                $errmsg[$errors++] = _('Please specify the authentication token.');
            }
            if (!have_value($twilio_country_code)) {
                $errmsg[$errors++] = _('Please specify the country code.');
            }
            if (!have_value($twilio_phone)) {
                $errmsg[$errors++] = _('Please specify the Twilio phone number to send SMS from.');
            }
            if ($twilio_phone && strlen($twilio_phone) <= 4) {
                $errmsg[$errors++] = _('Please specify a valid phone number');
            }
        }
        // handle errors
        if ($errors > 0) {
            $outargs[COMPONENT_ERROR_MESSAGES] = $errmsg;
            $result = 1;
            return;
        }

        // save options
        $settings = array(
            'is_enabled'                => $is_enabled,
            'sid'                       => $account_sid,
            'auth_token'                => $auth_token,
            'twilio_phone'              => $twilio_phone,
            'twilio_country_code'       => $twilio_country_code,
        );
        set_option('twilio_options', serialize($settings));

        // info messages
        $okmsg[] = _('Twilio SMS settings updated.');
        $outargs[COMPONENT_INFO_MESSAGES] = $okmsg;
        break;  
    }   

    return $output; 
}


/**
 * Creates and adds twilio tab content using user notification method callback
 */
function twilio_notificationmethod_func($mode, $inargs, &$outargs, &$result) 
{
    global $twilio_component_name;

    // session is not tracked in notifymethods.php
    $current_user_id = $_SESSION["user_id"];    

    $twilio_component_url = get_component_url_base($twilio_component_name);

    // initialize return values
    $result = 0;
    $outargs = array();
    $output = '';

    if (!is_twilio_enabled()) {
        return $output;
    }

    switch ($mode) {
    
    case NOTIFICATIONMETHOD_MODE_GETCONFIGOPTIONS:

        // default values
        $is_twilio_sms_enabled = get_user_meta($current_user_id, 'is_twilio_sms_enabled'); 
        $mobile_number = get_user_meta($current_user_id, 'mobile_number');
        $is_twilio_sms_trimmed = get_user_meta($current_user_id, 'is_twilio_sms_trimmed');
        $starting_vtag = get_user_twilio_phone_starting_vtag($current_user_id);
        $mobile_country_code = get_user_meta($current_user_id, 'mobile_country_code');

        // create dropdown
        $mobile_country_dropdown = generate_dropdown("mobile_country_code", $mobile_country_code);

        // sanitize user input
        $mobile_number = preg_replace('/\D/', '', $mobile_number);

        // check if the numbers are specified for verification
        $is_mobile_specified = !empty($mobile_number);
        $is_user_phone_verified = is_user_phone_verified();
        $is_sms_checkbox_disabled = $is_user_phone_verified ? '' : 'disabled'; 

        // if checkbox is disabled, disable the sms
        if ($is_sms_checkbox_disabled) {
            set_user_meta($current_user_id, 'is_twilio_sms_enabled', 0);
            $is_twilio_sms_enabled = 0;
        }

        // add verification message if numbers are specified
        $output = "

            <p><a href='https://www.twilio.com' target='_blank'>
                <img src='" . $twilio_component_url . "/twilio.png' alt='Twilio SMS' 
                height= '50' width = '170'/></a></p>
            
            <table class='table table-condensed table-no-border table-auto-width' style='margin-bottom:10px;margin-top:5px;'>
            </table>
            
            <table class='table table-condensed table-no-border table-auto-width' style='margin-bottom:0px;margin-top:5px;'>
                <tr>
                    <td>
                        <label for='mobile_number_input'>"._('User Mobile Number')."
                        <span style='color:red;'>*</span>:</label>
                    </td>
                    <td>
                        <div>".$mobile_country_dropdown."</div>
                    </td>
                    <td>
                        <div class='input-group' style='margin-left:-10px;'>
                        <input type='text' size='20' id='".'mobile_number_input'."' class='textfield form-control'
                        placeholder='"._('Phone Number')."' readonly='".'readonly'."' name='".'mobile_number_input'."' 
                        value='".$mobile_number."' title='"._('To change the mobile phone number, please go to mobile text or user settings.')."'>
                        <label id='vtag' class='input-group-addon' style='padding: 6px 8px;'>".$starting_vtag."</label>
                        </div>
                    </td>
                    <td>
                        <button type='button' class='btn btn-sm btn-info' id='".'send_twilio_test'."' name='".'send_twilio_test'."'>
                        "._('Send Test Notification ')."<i class='fa fa-chevron-right r'></i></button>
                    </td>
                </tr>
            </table>

            <table class='table table-condensed table-no-border table-auto-width' style='margin-bottom:5px;margin-top:-10px;margin-left:285px;'>
                <tr>
                    <td>
                        <div>
                        "._('Go to ')."<a id='reroute_to_tabsms'>mobile settings</a>"._(' to change.')."
                        </div>
                    </td>
                </tr>
            </table>


            <div class='alert alert-info' id='twilio_send_vkey_info' style='margin-bottom:0px;visibility:hidden;padding:0px;display:inline-block;'>
            </div>

            <br>

            <div class='alert alert-danger' id='twilio_problem_alert' style='margin-bottom:0px;visibility:hidden;padding:0px;display:inline-block;'>
            </div>

            <table class='table table-condensed table-no-border table-auto-width' style='margin-top:5px;'>
                <tr>
                    <td>
                        <input type='checkbox' class='checkbox' id='".'is_twilio_sms_enabled'."' style='".'margin-bottom: 18px;'."'
                        name='".'is_twilio_sms_enabled'."' ".is_checked($is_twilio_sms_enabled, 1)."
                        ".$is_sms_checkbox_disabled.">
                    </td>
                    <td>
                        <label for='".'is_twilio_sms_enabled'."' style='".'font-weight: 700'."'>
                        "._('Receive Alerts via Twilio SMS')."
                        </label> <br>
                        <label for='".'is_twilio_sms_enabled'."' style='".'font-weight: 100;'."' class='".'subtext'."'>
                        "._(" Receive Nagios XI event notifications via Twilio SMS to the <span style='color:red;'>*</span>verified mobile phone number.")." 
                        </label>
                    </td>
                </tr>
                <tr>
                    <td>
                        <input type='checkbox' class='checkbox' id='".'is_twilio_sms_trimmed'."' style='".'margin-bottom: 18px;'."'
                        name='".'is_twilio_sms_trimmed'."' ".is_checked($is_twilio_sms_trimmed, 1).">
                    </td>
                    <td>
                        <label for='".'is_twilio_sms_trimmed'."' style='".'font-weight: 700'."'>
                        "._('Receive Alerts Trimmed')."
                        </label> <br>
                        <label for='".'is_twilio_sms_trimmed'."' style='".'font-weight: 100'."' class='".'subtext'."'>
                        "._("Receive SMS messages trimmed to a single text segment of 160 characters.")."
                        </label>
                    </td>
                </tr>
            </table>

            <script>
                var interval = 1000;
                

                // this function uses ajax to grab the 
                // most up to date status of the phone verification
                // to display the accurate verification tag
                function update_vtag()
                {
                    $.ajax({
                        url: '".$twilio_component_url."/twilio_ajax_handler.php',
                        type: 'POST',
                        data: { mode: 'update_user_vtag', user_id: '".$current_user_id."'},
                        success: function(data) {
                            document.getElementById('vtag').innerHTML = data;    
                        },
                        failure: function(xhr, error_string, error_thrown) {
                            alert('Error getting user vtag');
                        },
                    });
                }

                // this function uses ajax to grab the 
                // accurate time remaining for the verification
                // process
                function countdown()
                {
                    $.ajax({
                        url: '".$twilio_component_url."/twilio_ajax_handler.php',
                        type: 'POST',
                        data: { mode: 'countdown', user_id: '".$current_user_id."'},
                        success: function(data) {
                            var info = document.getElementById('countdown');
                            if (data != null && info != null) {
                                info.innerHTML = data;    
                            }
                        },
                        complete: function (data) {
                            setTimeout(countdown, interval);
                        },
                        failure: function(xhr, error_string, error_thrown) {
                            alert('Error getting countdown');
                        },
                    });
                }

                function get_selected_country_code()
                {
                    var country_code = document.getElementById('mobile_country_code');
                    if (country_code.selectedIndex == -1) {
                        return 1;
                    } 
    
                    return country_code.options[country_code.selectedIndex].value;
                }

                // this function sends the test twilio sms 
                function send_twilio_test()
                {
                    $('#send_twilio_test').click( function() {
                        var country_code = get_selected_country_code();
                        $.ajax({
                            url: '".$twilio_component_url."/twilio_ajax_handler.php',
                            type: 'POST',
                            data: { mode: 'send_twilio_test', user_id: '".$current_user_id."', mobile_country_code: country_code},
                            success: function(data) {
                                if (data == 'Success!') {
                                    document.getElementById('send_twilio_test').innerHTML = 'Successfully Sent!';
                                    document.getElementById('send_twilio_test').disabled = true;
                                } 
                                else {
                                    alert(data);
                                }
                            },
                            failure: function(xhr, error_string, error_thrown) {
                                alert('Error sending test notification');
                            },
                        });
                    });
                }

                $(document).ready(function () {

                    var is_mobile_specified = '".$is_mobile_specified."';
                    var is_user_phone_verified = '".$is_user_phone_verified."';
                    var is_verification_in_progress = '".((get_user_phone_vkey_expire($current_user_id)) > 0)."';
                    var info = document.getElementById('twilio_send_vkey_info');

                    // mobile settings link under mobile number input
                    // redirects the user to mobile text sms tab 
                    $('#reroute_to_tabsms').click( function() {
                        $('#ui-id-2').click();
                    });


                    // when the page is reloaded, if the mobile is specified but not verified
                    // then create the info box for users to either initiate verification or finish verification
                    if (is_mobile_specified && !is_user_phone_verified) {
                        if (is_verification_in_progress) {
                            info.innerHTML = 
                            '<table class=".'"table-condensed table-no-border table-auto-width"'."><tr><td style=".'"margin-bottom:8px;"'."><label for=".'"vkey"'.">"._('Enter Verification Key:')."</label></td><td><div class=".'"input-group mb-3"'."><input type=".'"text"'." size=".'"10"'." id=".'"vkey_input"'." class=".'"input-group-text form-control"'." name=".'"vkey_input"'." style=".'"height:29px;width:auto;"'."></input><input type=".'"button"'."id=".'"check_vkey"'." name=".'"check_vkey"'." class=".'"btn btn-sm btn-default input-group-append"'." style=".'"vertical-align:top;"'." value="._('Verify')."></input></div></td><td id=".'"countdown"'.">"._('Key expires in ')." <b>".get_user_phone_vkey_expire($current_user_id)."</b></td></tr></table><div style=".'"margin-left:317px;"'." id=".'"resend"'."><a id=".'"resend_link"'.">"._('Resend verification key')."</a></div>';
                            info.style.marginBottom = '10px';
                            info.style.padding = '15px';
                            info.style.visibility = 'visible';

                            setTimeout(countdown, interval);
                        }
                        else {
                            info.innerHTML = '<label style=".'"margin-top:5px;"'.">"._('You must verify the mobile phone number before enabling notifications.')."</label><a id=".'"send_verification_key"'." name=".'"send_verification_key"'."class=".'"btn btn-xs btn-default"'."style=".'"margin-left: 10px;vertical-align: top; color: #000;"'.">"._('Send a verification key')."</a>';
                            info.style.marginBottom = '10px';
                            info.style.padding = '15px';
                            info.style.visibility = 'visible';
                        }
                    }
                    else {
                        info.style.marginBottom = '0px';
                        info.style.visibility = 'hidden';
                        info.style.padding = '0px';
                    }


                    // when the user clicks the verify the user verification code
                    $('#check_vkey').click(function() {

                        var user_input_key = document.getElementById('vkey_input').value;

                        $.ajax({
                            url: '".$twilio_component_url."/twilio_ajax_handler.php',
                            type: 'POST',
                            data: { mode: 'verify_vkey', user_id: '".$current_user_id."', user_twilio_key: user_input_key},
                            success: function(data) {
                                if (data == 'Verification successful!') {
                                    document.getElementById('twilio_send_vkey_info').innerHTML = '<label>"._('Verification successful! You can now use your mobile phone number to to receive event notifications.')."</label>';
                                    update_vtag();
                                    document.getElementById('twilio_problem_alert').remove();
                                    document.getElementById('is_twilio_sms_enabled').disabled = false;
                                } 
                                else {
                                    $('twilio_send_vkey_info').attr('class', 'alert alert-danger');
                                    var twilio_alert = document.getElementById('twilio_problem_alert');
                                    twilio_alert.innerHTML =  
                                    '<table class=".'"table-condensed table-no-border table-auto-width"'."><tr><td><label>"._('Key is invalid. Please enter your key again.')."</label></td></tr></table>';
                                    twilio_alert.style.visibility = 'visible';
                                    twilio_alert.style.marginBottom = '10px';
                                    twilio_alert.style.padding = '15px';
                                }
                            },
                            failure: function(xhr, error_string, error_thrown) {
                                alert('failed to verify the key');
                            }
                        });
                        update_vtag();
                    });

                    $('#resend_link').click(function() {
                        var country_code = get_selected_country_code();
                        $.ajax({
                            url: '".$twilio_component_url."/twilio_ajax_handler.php',
                            type: 'POST',
                            data: { mode: 'resend', user_id: '".$current_user_id."', mobile_country_code: country_code},
                            success: function(data) {
                                if (data == 'Success!') {
                                    document.getElementById('resend').innerHTML = '"._('Verification resent successfully!')."';
                                }
                                else {
                                    document.getElementById('resend').innerHTML = '"._('Verification failed to resend!')."';
                                }    
                            },
                            failure: function(xhr, error_string, error_thrown) {
                                alert('failed to resend!');
                            },
                        });
                    });

                    update_vtag();
                    send_twilio_test();

                    // when the user first clicks the send verification code
                    $('#send_verification_key').click(function() {
                        var country_code = get_selected_country_code();
                        $.ajax({
                            url: '".$twilio_component_url."/twilio_ajax_handler.php',
                            type: 'POST',
                            data: { mode: 'send_twilio_user_phone_vkey', user_id: '".$current_user_id."', mobile_country_code: country_code},
                            success: function(data) {
                                if (data == 'Success!') {
                                    document.getElementById('twilio_problem_alert').innerHTML = '';
                                    document.getElementById('twilio_problem_alert').style.visibility = 'hidden';

                                    document.getElementById('twilio_send_vkey_info').innerHTML = 
                                    '<table class=".'"table-condensed table-no-border table-auto-width"'."><tr><td style=".'"margin-bottom:8px;"'."><label for=".'"vkey"'.">"._('Enter Verification Key:')."</label></td><td><div class=".'"input-group mb-3"'."><input type=".'"text"'." size=".'"10"'." id=".'"vkey_input"'." class=".'"input-group-text form-control"'." name=".'"vkey_input"'." style=".'"height:29px;width:auto;"'."></input><input type=".'"button"'."id=".'"check_vkey"'." name=".'"check_vkey"'." class=".'"btn btn-sm btn-default input-group-append"'." style=".'"vertical-align:top;"'." value="._('Verify')."></input></div></td><td><span id=".'"countdown"'.">Key expires in <b>10m</b></span></td></tr></table><div style=".'"margin-left:317px;"'." id=".'"resend"'."><a id=".'"resend_link"'.">"._('Resend verification key')."</a></div>';

                                    update_vtag();
                                    setTimeout(countdown, interval);

                                    $('#check_vkey').click(function() {

                                        var user_input_key = document.getElementById('vkey_input').value;

                                        $.ajax({
                                            url: '".$twilio_component_url."/twilio_ajax_handler.php',
                                            type: 'POST',
                                            data: { mode: 'verify_vkey', user_id: '".$current_user_id."', user_twilio_key: user_input_key},
                                            success: function(data) {

                                                if (data == 'Verification successful!') {
                                                    document.getElementById('twilio_send_vkey_info').innerHTML = '<label>"._('Verification successful! You can now use your mobile phone number to to receive event notifications.')."</label>';
                                                    update_vtag();
                                                    document.getElementById('twilio_problem_alert').remove();
                                                    document.getElementById('is_twilio_sms_enabled').disabled = false;
                                                } else {
                                                    $('twilio_send_vkey_info').attr('class', 'alert alert-danger');
                                                    var twilio_alert = document.getElementById('twilio_problem_alert');
                                                    twilio_alert.innerHTML =  
                                                    '<table class=".'"table-condensed table-no-border table-auto-width"'."><tr><td><label>"._('Key is invalid. Please enter your key again.')."</label></td></tr></table>';
                                                    twilio_alert.style.visibility = 'visible';
                                                    twilio_alert.style.marginBottom = '10px';
                                                    twilio_alert.style.padding = '15px';
                                                }
                                            },
                                            failure: function(xhr, error_string, error_thrown) {
                                                alert('failed to verify the key');
                                            }
                                        });
                                        update_vtag();
                                    });

                                    $('#resend_link').click(function() {
                                        var country_code = get_selected_country_code();
                                        $.ajax({
                                            url: '".$twilio_component_url."/twilio_ajax_handler.php',
                                            type: 'POST',
                                            data: { mode: 'resend', user_id: '".$current_user_id."', mobile_country_code: country_code},
                                            success: function(data) {
                                                if (data == 'Success!') {
                                                    document.getElementById('resend').innerHTML = '"._('Verification resent successfully!')."';
                                                }
                                                else {
                                                    document.getElementById('resend').innerHTML = '"._('Verification failed to resend!')."';
                                                }    
                                            },
                                            failure: function(xhr, error_string, error_thrown) {
                                                alert('failed to resend!');
                                            },
                                        });
                                    });
                                }
                                else {
                                    var twilio_alert = document.getElementById('twilio_problem_alert');
                                    var alert_content = '<table class=".'"table-condensed table-no-border table-auto-width"'."><tr><td><label>"._('Failed to send the verification key. ')."';
                                    alert_content += data;
                                    alert_content += '</label></td></tr></table>';
                                    twilio_alert.innerHTML = alert_content; 
                                    twilio_alert.style.visibility = 'visible';
                                    twilio_alert.style.marginBottom = '10px';
                                    twilio_alert.style.padding = '15px';
                                }
                            },
                            failure: function(xhr, error_string, error_thrown) {
                                alert('failed to send verification');
                            }
                        }); 
                    });
                });
                </script>";
    
        break;

    case NOTIFICATIONMETHOD_MODE_SETCONFIGOPTIONS:

        // grab values
        $current_user_id = $_SESSION['user_id'];
        $is_twilio_sms_enabled = grab_array_var($inargs, 'is_twilio_sms_enabled', '');
        $is_twilio_sms_enabled = checkbox_binary($is_twilio_sms_enabled);
        $twilio_mobile_number = grab_array_var($inargs, 'mobile_number', '');
        $is_twilio_sms_trimmed = grab_array_var($inargs, 'is_twilio_sms_trimmed', '');
        $is_twilio_sms_trimmed = checkbox_binary($is_twilio_sms_trimmed);
        $is_user_phone_verified = is_user_phone_verified($current_user_id);
        $mobile_country_code = grab_array_var($inargs, 'mobile_country_code', '');
 
        // sanitize user input
        $twilio_mobile_number = preg_replace('/\D/', '', $twilio_mobile_number);
        $old_twilio_mobile_number = get_user_meta($current_user_id, 'mobile_number');
        $is_mobile_specified = !empty($twilio_mobile_number);

        if ( !$is_mobile_specified || ($twilio_mobile_number != $old_twilio_mobile_number) ) {
            set_user_meta($current_user_id, 'phone_verified', 0);
            $is_user_phone_verified = 0;
            set_user_meta($current_user_id, 'phone_key', '');
            set_user_meta($current_user_id, 'phone_key_expires', '');
            set_user_meta($current_user_id, 'is_twilio_sms_enabled', 0);
            $is_twilio_sms_enabled = 0;
        }

        // validate values
        $errors = 0;
        $errmsg = array();
        $okmsg = array();
        if ($is_mobile_specified) {
            if (strlen($twilio_mobile_number) <= 3) {
                $errmsg[$errors++] = _('Please specify the mobile phone number with the country code.');
            }       
        }

        set_user_meta($current_user_id, 'is_twilio_sms_enabled', $is_twilio_sms_enabled);
        // disable sms event notification if the mobile phone is specified incorrectly 
        if ( $is_twilio_sms_enabled && !$is_mobile_specified ) {
            $is_twilio_sms_enabled = 0;
            set_user_meta($current_user_id, 'is_twilio_sms_enabled', 0);
            $errmsg[$errors++] = _('Please make sure that mobile phone number is specified correctly.');
        }
        if ( $is_twilio_sms_enabled && !$is_user_phone_verified ) {
            $is_twilio_sms_enabled = 0;
            set_user_meta($current_user_id, 'is_twilio_sms_enabled', 0);
            $errmsg[$errors++] = _('Please verify your mobile phone number to enable event notifications.');
        }
        if ( $is_twilio_sms_enabled && !$mobile_country_code ) {
            $is_twilio_sms_enabled = 0;
            set_user_meta($current_user_id, 'is_twilio_sms_enabled', 0);
            $errmsg[$errors++] = _('Please make sure that mobile phone country code is specified correctly.');
        }

        // handle errors
        if ($errors > 0) {
            $outargs[NOTIFICATIONMETHOD_ERROR_MESSAGES] = $errmsg;
            $result = 1;
        } 

        // info messages
        $outargs[NOTIFICATIONMETHOD_INFO_MESSAGES] = $okmsg;

        // save values to the current user
        set_user_meta($current_user_id, 'is_twilio_sms_trimmed', $is_twilio_sms_trimmed);
        set_user_meta($current_user_id, 'mobile_country_code', $mobile_country_code);

        break;

    case NOTIFICATIONMETHOD_MODE_GETMESSAGEFORMAT:

        // default values
        $twilio_host_message = get_twilio_host_messages(0);
        $twilio_service_message = get_twilio_service_messages(0);

        // grab values
        $twilio_host_message = grab_array_var($inargs, 'twilio_host_message', $twilio_host_message);
        $twilio_service_message = grab_array_var($inargs, 'twilio_service_message', $twilio_service_message);

        // warn uesr if disabled
        $is_twilio_sms_enabled = get_user_meta($current_user_id, 'is_twilio_sms_enabled');
        if (!$is_twilio_sms_enabled) {
            $warning_msg = _('Note: You currently have Twilio SMS notification disabled.') .  
                '<a href="notifymethods.php#tab-custom-'. _($twilio_component_name) .'">' . 
                _('Change settings') . '</a>';
            $output .= get_message_text(true, false, $warning_msg);
        }

        $output .= '

            <p><a href="https://www.twilio.com" target="_blank">
                <img src="' . $twilio_component_url . '/twilio.png" alt="Twilio SMS" 
                height= "50" width = "170"/></a></p>

            <p style="margin-top:10px;margin-bottom:10px;">' . _('Specify the format of the SMS messages you want to receive.') . 
            '</p>
            
            <table class="table table-condensed table-no-border table-auto-width">
                <tr>
                    <td>
                        <label>' . _('Host Alert Message') . '</label>
                    </td>
                    <td>
                        <textarea style="width: 400px; height: 100px;" class="form-control"
                        id="'.'twilio_host_message'.'" name="'.'twilio_host_message'.'">' .
                        ($twilio_host_message) . '</textarea>
                    </td>
                </tr>
                <tr>
                    <td>
                        <label>' . _('Service Alert Message') . '</label>
                    </td>
                    <td>
                        <textarea style="width: 400px; height: 100px;" class="form-control"
                        id="'.'twilio_service_message'.'" name="'.'twilio_service_message'.'">' .
                        ($twilio_service_message) . '</textarea>
                    </td>
                </tr>
                <tr>
                    <td>
                    </td>
                    <td>
                        <button type="button" class="btn btn-xs btn-info" id="resettwiliotext" name="resettwiliotext"><i class="fa fa-file-o l"></i> Reset to default messages</button>
                    </td>
                </tr>
            </table>            

            <script>
                // activate the reset button
                $("#resettwiliotext").click(function() {
                    var host_message = "%host% %type% (%hoststate%) %hostoutput% Addr: %hostaddress% Time: %datetime% Nagios URL: %xiserverurl%";
                    var service_message= "%service% %type% (%servicestate%) %serviceoutput% Addr: %hostaddress% Time: %datetime% Nagios URL: %xiserverurl%";

                    $("#twilio_host_message").val(host_message);
                    $("#twilio_service_message").val(service_message);        
                });
            </script>
        ';

        break;

    case NOTIFICATIONMETHOD_MODE_SETMESSAGEFORMAT:

        // grab values
        $twilio_host_message = grab_array_var($inargs, 'twilio_host_message', "");
        $twilio_service_message = grab_array_var($inargs, 'twilio_service_message', "");

        // save values to the currnet user
        set_user_meta($current_user_id, 'twilio_host_message', $twilio_host_message);
        set_user_meta($current_user_id, 'twilio_service_message', $twilio_service_message);

        break;
    }

    return $output;

}


/**
* Gets the host message from the user meta
*/
function get_twilio_host_messages($user_id)
{
    $host_message_content = get_user_meta($user_id, 'twilio_host_message');
    
    if (empty($host_message_content)) {
        $host_message_content = "%host% %type% (%hoststate%) %hostoutput% Addr: %hostaddress% Time: %datetime% Nagios URL: %xiserverurl%";
    }
    return $host_message_content;
}


/**
* Gets the service message from the user meta
*/
function get_twilio_service_messages($user_id)
{
    $service_message_content = get_user_meta($user_id, 'twilio_service_message');
    
    if (empty($service_message_content)) {
        $service_message_content = "%service% %type% (%servicestate%) %serviceoutput% Addr: %hostaddress% Time: %datetime% Nagios URL: %xiserverurl%";
    }
    return $service_message_content;
}


/**
* Checks to see if the component is enabled
*/
function is_twilio_enabled()
{
    // confirm options
    $settings = get_option('twilio_options');
    
    // validate options
    if (empty($settings)) {
        $settings = array();
    } 
    else {
        $settings = unserialize($settings);
    }
    
    $is_enabled = grab_array_var($settings, 'is_enabled', 0);
    
    return $is_enabled;
}


/**
* Registered function at CALLBACK_EVENT_PROCESSED that calls notification event function 
* whenever eventman processes a notification event
*/
function handle_twilio_event($cbtype, $args)
{
    if ( !is_twilio_enabled() ) {
        return;
    }

    if ($args['event_type'] == EVENTTYPE_NOTIFICATION) {
        handle_twilio_notification_event($args);
    }
}


/**
* Gets all the data regarding notifications filtered by user settings
* Once the message is fully compiled and processed, the message is sent using Twilio SMS
* Log goes to /usr/local/nagiosxi/var/eventman.log
*/
function handle_twilio_notification_event($args)
{
    $event_meta = $args["event_meta"];
    $contact = $event_meta["contact"];
    $notification_type = $event_meta["notification-type"];

    // find the XI user
    $user_id = get_user_id($contact);
    if ($user_id <= 0) {
        return;
    }
    echo "\n==== " . _("Twilio Notification Handler") .  " ====\n";

    // check for support for sms notification options
    if (get_product_release() <= 407) {
        echo _("This version of Nagios XI does not support SMS notifications.") . "\n";
        return 1;
    }
    // set user id session variable - used later in date/time, preference, etc. functions
    if (!defined("NAGIOSXI_USER_ID")) {
        define("NAGIOSXI_USER_ID", $user_id);
    }

    echo _("Twilio: CONTACT=$contact, USERID=$user_id") . "\n";

    // get settings
    $is_twilio_sms_enabled = get_user_meta($user_id, 'is_twilio_sms_enabled');
    $mobile_number = get_user_meta($user_id, 'mobile_number');
    $is_mobile_phone_verified = get_user_meta($user_id, 'phone_verified');
    $is_twilio_sms_trimmed = get_user_meta($user_id, 'is_twilio_sms_trimmed');


    // check to make sure twilio is enabled and values are correct
    if (!$is_twilio_sms_enabled) {
        echo _("Twilio: SMS disabled - not sending Twilio SMS.") . "\n";
        return 1;
    }
    if (empty($mobile_number)) {
        echo _("Twilio: Mobile number is unspecified!") . "\n";
        return 1;
    }
    if (!$is_mobile_phone_verified) {
        echo _("Twilio: Mobile phone is not verified!") . "\n";
        return 1;
    }

    // get notification options for user
    $notify_host_recovery = get_user_meta($user_id, 'notify_host_recovery');
    $notify_host_down = get_user_meta($user_id, 'notify_host_down');
    $notify_host_unreachable = get_user_meta($user_id, 'notify_host_unreachable');
    $notify_host_flapping = get_user_meta($user_id, 'notify_host_flapping');
    $notify_host_downtime = get_user_meta($user_id, 'notify_host_downtime');

    $notify_service_recovery = get_user_meta($user_id, 'notify_service_recovery');
    $notify_service_warning = get_user_meta($user_id, 'notify_service_warning');
    $notify_service_unknown = get_user_meta($user_id, 'notify_service_unknown');
    $notify_service_critical = get_user_meta($user_id, 'notify_service_critical');
    $notify_service_flapping = get_user_meta($user_id, 'notify_service_flapping');
    $notify_service_downtime = get_user_meta($user_id, 'notify_service_downtime');

    // Get SMS notification options for user 
    $notify_sms_host_recovery = get_user_meta($user_id, 'notify_sms_host_recovery', $notify_host_recovery);
    $notify_sms_host_down = get_user_meta($user_id, 'notify_sms_host_down', $notify_host_down);
    $notify_sms_host_unreachable = get_user_meta($user_id, 'notify_sms_host_unreachable', $notify_host_unreachable);
    $notify_sms_host_flapping = get_user_meta($user_id, 'notify_sms_host_flapping', $notify_host_flapping);
    $notify_sms_host_downtime = get_user_meta($user_id, 'notify_sms_host_downtime', $notify_host_downtime);

    $notify_sms_service_recovery = get_user_meta($user_id, 'notify_sms_service_recovery', $notify_service_recovery);
    $notify_sms_service_warning = get_user_meta($user_id, 'notify_sms_service_warning', $notify_service_warning);
    $notify_sms_service_unknown = get_user_meta($user_id, 'notify_sms_service_unknown', $notify_service_unknown);
    $notify_sms_service_critical = get_user_meta($user_id, 'notify_sms_service_critical', $notify_service_critical);
    $notify_sms_service_flapping = get_user_meta($user_id, 'notify_sms_service_flapping', $notify_service_flapping);
    $notify_sms_service_downtime = get_user_meta($user_id, 'notify_sms_service_downtime', $notify_service_downtime);

    // service notification return cases
    if ($notification_type == "service") {

        switch ($event_meta['type']) {

        case "PROBLEM":
            if (   ($notify_sms_service_warning != 1) 
                && ($event_meta['servicestateid'] == 1)) {

                return 1;
            }
            else if (   ($notify_sms_service_critical != 1) 
                     && ($event_meta['servicestateid'] == 2)) {

                return 1;
            }
            else if (   ($notify_sms_service_unknown != 1) 
                     && ($event_meta['servicestateid'] == 3)) {

                return 1;
            }
            break;

        case "RECOVERY":
            if ($notify_sms_service_recovery != 1) {
                return 1;
            }
            break;

        case "FLAPPINGSTART":
            // proceed to FLAPPINGSTOP

        case "FLAPPINGSTOP":
            if ($notify_sms_service_flapping != 1) {
                return 1;
            }
            break;

        case "DOWNTIMESTART":
            // proceed to DOWNTIMECANCELLED

        case "DOWNTIMECANCELLED":
            // proceed to DOWNTIMEEND

        case "DOWNTIMEEND":
            if ($notify_sms_service_downtime != 1) {
                return 1;
            }
            break;
        }    
    } 

    // host notification return cases 
    else {

        switch ($event_meta['type']) {

        case "PROBLEM":
            if (   ($notify_sms_host_down != 1) 
                && ($event_meta['hoststateid'] == 1)) {

                return 1;
            }
            else if (   ($notify_sms_host_unreachable != 1) 
                     && ($event_meta['hoststateid'] == 2)) {

                return 1;
            }
            break;

        case "RECOVERY":
            if ($notify_sms_host_recovery != 1) {
                return 1;
            }
            break;

        case "FLAPPINGSTART":
            // proceed to FLAPPINGSTOP

        case "FLAPPINGSTOP":
            if ($notify_sms_host_flapping != 1) {
                return 1;
            }
            break;

        case "DOWNTIMESTART":
            // proceed to DOWNTIMECANCELLED

        case "DOWNTIMECANCELLED":
            // proceed to DOWNTIMEEND

        case "DOWNTIMEEND":
            if ($notify_sms_host_downtime != 1) {
                return 1;
            }
            break;
        }    
    }
    
    // get the SMS message
    if ($event_meta["notification-type"] == "service") {
        $message = get_twilio_service_messages($user_id);
    } 
    else {
        $message = get_twilio_host_messages($user_id);
    }

    // log raw message
    echo _("Twilio: RAW MESSAGE='" . $message . "'\n");

    // replace macros
    $message = process_notification_text($message, $event_meta);

    // trim the message
    if ($is_twilio_sms_trimmed) {
        $message = substr($message, 0, 160);
    }

    // log the message before sending
    echo _("Twilio: SMS MESSAGE='" . $message . "'\n");

    // send the message
    $result = send_twilio_sms($message, $user_id);

    // if the message is not sent due to an error
    if ($result) {
        echo $result;
        return 1;
    }
    else {
        echo _("Twilio: SMS message successfully sent! \n");
    }
    return 0;
}


/**
* Sends Twilio SMS message via Twilio API 
* @param    message and to-phone
* @return   err_string
*/
function send_twilio_sms($message ="", 
                         $user_id = 0, 
                         $mobile_number = 0, 
                         $mobile_country_code = 0, 
                         $account_sid = 0, 
                         $auth_token = 0,
                         $twilio_phone = 0,
                         $twilio_country_code = 0) 
{
    require_once(__DIR__ . '/Twilio/autoload.php');
    //use Twilio\Rest\Client;

    // get options
    $settings = get_option('twilio_options');    
    if (empty($settings)) {
        return "Could not load the user options.";
    } 
    else {
        $settings = unserialize($settings);
    }

    // if function args are unspecifed, use values from options
    if (empty($account_sid)) {
        $account_sid = grab_array_var($settings, 'sid', '');
    }
    if (empty($auth_token)) {
        $auth_token = grab_array_var($settings, 'auth_token', '');
    } 
    if (empty($twilio_country_code)) {
        $twilio_country_code = grab_array_var($settings, 'twilio_country_code', '');
    }
    if (empty($twilio_phone)) {
        $twilio_phone = grab_array_var($settings, 'twilio_phone', '');
    }
    if (empty($mobile_number)) {
        $mobile_number = get_user_meta($user_id, 'mobile_number');
    }
    if (empty($mobile_country_code)) {
        $mobile_country_code = get_user_meta($user_id, 'mobile_country_code');
    }
    try {
        $client = new Twilio\Rest\Client($account_sid, $auth_token);    
    }
    catch (Exception $e) {
        return $e;
    }

    // sanitize user input
    $twilio_country_code = preg_replace('/\D/', '', $twilio_country_code);
    $twilio_phone = preg_replace('/\D/', '', $twilio_phone);
    $mobile_country_code = preg_replace('/\D/', '', $mobile_country_code);
    $mobile_number = preg_replace('/\D/', '', $mobile_number);
    
    // validate user input
    if (empty($twilio_country_code)) {
        return "Country code is required for Twilio phone number.";
    } 
    if (empty($twilio_phone)) {
        return "Twilio phone number is required.";
    } 
    if (strlen($twilio_phone) <= 4) {
        return "Twilio phone number must be valid.";
    }
    if (empty($mobile_country_code)) {
        return "Country code for mobile phone number is required.";
    } 
    if (empty($mobile_number)) {
        return "Mobile phone number is required.";
    } 
    if (strlen($mobile_number) <= 4) {
        return "Mobile phone number must be valid.";
    }

    // format phone numbers
    $twilio_phone = "+" . $twilio_country_code . $twilio_phone;
    $mobile_number = "+" . $mobile_country_code . $mobile_number;
    
    // send message
    try {
        $client->messages->create(
            $mobile_number, // to-phone
            array(
                'from' => $twilio_phone,
                'body' => $message
            )
        );
    }
    catch (Exception $e) {
        return $e;
    }

    return 0;
}

/**
 * Generate the dropdown option string with selected value
 * If nothing is selected, then $selected is ''
 * selected is the value of the dropdown 
 */
function generate_dropdown($id, $selected)
{
    global $twilio_component_name;
 
    // raw options object
    $mobile_country_options = file_get_contents("/usr/local/nagiosxi/html/includes/components/twilio/country_options.html");

    // generate the opening tag of the options 
    $dropdown = "<select name='".$id."' id='".$id."' class='form-control' style='width:135px;'>";

    // add the options object to the opening and add selected attribute to the specified value
    $dropdown .= $mobile_country_options;
    if ($selected == '') {
        $selected = 1;
    }

    $dropdown = str_replace("'$selected'", "'$selected' Selected", $dropdown);

    return $dropdown;

}



/**
 * Returns the starting phone tag
 */
function get_user_twilio_phone_starting_vtag($user_id=1) 
{
    // default values
    $fa = 'fa-question';
    $text = _('Phone Number Unspecified');

    // retrieve user values
    $phone = get_user_meta($user_id, 'mobile_number', '');
    $vkey = get_user_meta($user_id, 'phone_key', '');
    $expires = get_user_meta($user_id, 'phone_key_expires', '');

    // if already verified
    if (is_user_phone_verified($user_id)) {
        $fa = 'fa-check';
        $text = _("Verified Number");
    }
    // if unverified
    else if (!empty($vkey)) {
        if (!empty($expires) && $expires < time()) {
            $fa = 'fa-exclamation';
            $text = _("Phone Number Unverified");
        }
        // if being verified 
        else {
            $fa = 'fa-spinner';
            $text = _("Verification in Progress");
        }
    // if unverified
    } else if (!empty($phone)) {
            $fa = 'fa-exclamation';
            $text = _("Phone Number Unverified");
    }

    // create the icon
    $output = '<i title="'.$text.'" class="fa tt-bind fa-fw fa-14 '.$fa.'"></i>';

    return $output;
}
