Please accept my apology in advance if my question is long.
I am using a payment gateway of woocommerce.
When click on checkout it goes to an external link. Then there We have button to click and Then It goes to another link which make it enable to pay via cards.
Now What I want to do is that.
I want to minimize some step.
1- If possible I want to bypass detail page which appears after click on Checkout button.
2- Is this possible to hide amount on detail page. As my website currecny is different and this payment gateway the show in different.
3- If above 1,2 not possible. Can simply put external pages in a iframe.
So if user click on check out. It should show a ifram on new page current page with redirected link.
Below code is from gateway plugin.
<?php
add_action( 'plugins_loaded', 'init_pp_woo_gateway');
function mib_ppbycp_settings( $links ) {
$settings_link = 'Setup';
array_push( $links, $settings_link );
return $links;
}
$plugin = plugin_basename( __FILE__ );
add_filter( "plugin_action_links_$plugin", 'mib_ppbycp_settings' );
function init_pp_woo_gateway(){
if ( ! class_exists( 'WC_Payment_Gateway' ) ) return;
class WC_Gateway_MIB_PayPro extends WC_Payment_Gateway {
// Logging
public static $log_enabled = false;
public static $log = false;
var $merchant_id;
var $merchant_password;
var $test_mode;
var $plugin_url;
var $timeout;
var $checkout_url;
var $api_url;
var $timeout_in_days;
public function __construct(){
global $woocommerce;
$this -> plugin_url = WP_PLUGIN_URL . DIRECTORY_SEPARATOR . 'woocommerce-paypro-payment';
$this->id = 'mibwoo_pp';
$this->has_fields = false;
$this->checkout_url = 'https://marketplace.paypro.com.pk/';
$this->icon = 'https://thebalmainworld.com/wp-content/uploads/2020/10/Credit-Card-Icons-copy-1.png';
$this->method_title = 'Paypro';
$this->method_description = 'Pay via Debit/Credit card.';
$this->title = "Paypro";
$this->description = "Pay via Debit/Credit card.";
$this->merchant_id = $this->get_option( 'merchant_id' );
$this->merchant_password = trim($this->get_option( 'merchant_password' ));
$this->merchant_secret = $this->get_option( 'merchant_secret' );
$this->test_mode = $this->get_option('test_mode');
$this->timeout_in_days = $this->get_option('timeout_in_days');
$this->debug = $this->get_option('debug');
$this->pay_method = "Paypro";
if($this->timeout_in_days==='yes'){
$this->timeout = trim($this->get_option( 'merchant_timeout_days' ));
}
else{
$this->timeout = trim($this->get_option( 'merchant_timeout_minutes' ));
}
if($this->test_mode==='yes'){
$this->api_url = 'https://demoapi.paypro.com.pk';
}
else{
$this->api_url = 'https://api.paypro.com.pk';
}
$this->init_form_fields();
$this->init_settings();
self::$log_enabled = $this->debug;
// Save options
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
// Payment listener/API hook
add_action( 'woocommerce_api_wc_gateway_mib_paypro', array( $this, 'paypro_response' ) );
}
function init_form_fields(){
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Yes', 'woocommerce' ),
'default' => 'yes'
),
'merchant_id' => array(
'title' => __( 'Merchant Username', 'woocommerce' ),
'type' => 'text',
'description' => __( 'This Merchant Username Provided by PayPro', 'woocommerce' ),
'default' => '',
'desc_tip' => true,
),
'test_mode' => array(
'title' => __( 'Enable Test Mode', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Yes', 'woocommerce' ),
'default' => 'yes'
),
'merchant_password' => array(
'title' => __( 'Merchant Password', 'woocommerce' ),
'type' => 'password',
'description' => __( 'Merchant Password Provided by PayPro', 'woocommerce' ),
'default' => __( '', 'woocommerce' ),
'desc_tip' => true,
),
'merchant_secret' => array(
'title' => __( 'Secret Key', 'woocommerce' ),
'type' => 'password',
'description' => __( 'Any Secret Key Or Word with No Spaces', 'woocommerce' ),
'default' => __( rand(), 'woocommerce' ),
'desc_tip' => true,
),
'merchant_timeout_minutes' => array(
'title' => __( 'Timeout (In Minutes)', 'woocommerce' ),
'type' => 'number',
'description' => __( 'Timeout Before order expires it can be between 5 to 30 minutes', 'woocommerce' ),
'default' => __( 5, 'woocommerce' ),
'desc_tip' => true,
'custom_attributes' => array(
'min' => 5,
'max' => 30
)
),
'timeout_in_days' => array(
'title' => __( 'Enable Timeout in days', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Yes', 'woocommerce' ),
'default' => 'no'
),
'merchant_timeout_days' => array(
'title' => __( 'Timeout (In Days)', 'woocommerce' ),
'type' => 'number',
'description' => __( 'Minimum 1 day Max 3 Days. Remember, It works as due date you\'ve selected 1 day the expiration date of the PayPro id will be set as the day after today.', 'woocommerce' ),
'default' => __( 1, 'woocommerce' ),
'desc_tip' => true,
'custom_attributes' => array(
'min' => 1,
'max' => 3
)
),
'debug' => array(
'title' => __( 'Debug Log', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Enable logging', 'woocommerce' ),
'default' => 'no',
'description' => sprintf( __( 'Debug Information <em>%s</em>', 'woocommerce' ), wc_get_log_file_path( 'paypro' ) )
),
);
}
/**
* Logging method
* #param string $message
*/
public static function log( $message ) {
if ( self::$log_enabled ) {
if ( empty( self::$log ) ) {
self::$log = new WC_Logger();
}
$message = is_array($message) ? json_encode($message) : $message;
self::$log->add( 'paypro', $message );
}
}
/**
* Process the payment and return the result
*
* #access public
* #param int $order_id
* #return array
*/
function process_payment( $order_id ) {
$order = new WC_Order( $order_id );
$paypro_args = $this->get_paypro_args( $order );
$paypro_args = http_build_query( $paypro_args, '', '&' );
$this->log("========== Payment Processing Started: args =========");
$this->log($paypro_args);
//if demo is enabled
$checkout_url = $this->checkout_url;;
return array(
'result' => 'success',
// 'redirect' => 'http://localhost:8000/secureform?'.$paypro_args
'redirect' => 'https://marketplace.paypro.com.pk/secureform?'.$paypro_args
);
}
/**
* Get PayPro Args for passing to PP
*
* #access public
* #param mixed $order
* #return array
*/
function get_paypro_args( $order ) {
global $woocommerce;
$order_id = $order->get_id();
//Encrypting the username and password
$token1 = $this->merchant_id;
$token2 = $this->merchant_password;
$cipher_method = 'aes-128-ctr';
$secret_word = md5($this->merchant_secret);
$enc_key = openssl_digest($secret_word.date('d/m/y'), 'SHA256', TRUE);
$enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_method));
$crypted_token1 = openssl_encrypt($token1, $cipher_method, $enc_key, 0, $enc_iv) . "::" . bin2hex($enc_iv);
$crypted_token2 = openssl_encrypt($token2, $cipher_method, $enc_key, 0, $enc_iv) . "::" . bin2hex($enc_iv);
unset($token, $cipher_method, $enc_key, $enc_iv);
// PayPro Args
$paypro_args = array(
'mid' => $crypted_token1,
'mpw' => $crypted_token2,
'secret_public' => base64_encode($this->merchant_secret),
'is_encrypted' => 1,
'mode' => $this->test_mode,
'timeout_in_days' => $this->timeout_in_days,
'merchant_order_id' => $order_id,
'merchant_name' => get_bloginfo( 'name' ),
'request_is_valid' => 'true',
'request_from' => 'woocommerce',
// Billing Address info
'first_name' => $order->get_billing_first_name(),
'last_name' => $order->get_billing_last_name(),
'street_address' => $order->get_billing_address_1(),
'street_address2' => $order->get_billing_address_2(),
'city' => $order->get_billing_city(),
'state' => $order->get_billing_state(),
'zip' => $order->get_billing_postcode(),
'country' => $order->get_billing_country(),
'email' => $order->get_billing_email(),
'phone' => $order->get_billing_phone(),
);
if (!function_exists('is_plugin_active')) {
include_once(ABSPATH . 'wp-admin/includes/plugin.php');
}
if(is_plugin_active( 'custom-order-numbers-for-woocommerce/custom-order-numbers-for-woocommerce.php' )){
$paypro_args['paypro_order_id'] = time().'-'.get_option( 'alg_wc_custom_order_numbers_counter', 1 );
}
else{
$paypro_args['paypro_order_id'] = time().'-'.$order_id;
}
// Shipping
if ($order->needs_shipping_address()) {
$paypro_args['ship_name'] = $order->get_shipping_first_name().' '.$order->get_shipping_last_name();
$paypro_args['company'] = $order->get_shipping_company();
$paypro_args['ship_street_address'] = $order->get_shipping_address_1();
$paypro_args['ship_street_address2'] = $order->get_shipping_address_2();
$paypro_args['ship_city'] = $order->get_shipping_city();
$paypro_args['ship_state'] = $order->get_shipping_state();
$paypro_args['ship_zip'] = $order->get_shipping_postcode();
$paypro_args['ship_country'] = $order->get_shipping_country();
}
$paypro_args['x_receipt_link_url'] = $this->get_return_url( $order );
$paypro_args['request_site_url'] = get_site_url();
$paypro_args['request_site_checkout_url'] = wc_get_checkout_url();
$paypro_args['return_url'] = $order->get_cancel_order_url();
$paypro_args['issueDate'] = date('d/m/Y');
$paypro_args['cartTotal'] = $order->get_total();
$paypro_args['store_currency'] = get_woocommerce_currency();
$paypro_args['store_currency_symbol'] = get_woocommerce_currency_symbol();
//Getting Cart Items
$billDetails= array();
$flag = 0;
foreach ($order->get_items() as $item => $values){
// Get the product name
$product_name = $values['name'];
// Get the item quantity
$item_quantity = $order->get_item_meta($item, '_qty', true);
// Get the item line total
$item_total = $order->get_item_meta($item, '_line_total', true);
$price = $item_total/$item_quantity;
$billDetails[$flag]['LineItem'] = esc_html($product_name);
$billDetails[$flag]['Quantity'] = $item_quantity;
$billDetails[$flag]['UnitPrice'] = $price;
$billDetails[$flag++]['SubTotal'] = $item_total;
}
$paypro_args['cartItemList'] = urlencode(json_encode($billDetails));
////
//setting payment method
if ($this->pay_method)
$paypro_args['pay_method'] = $this->pay_method;
//if test_mode is enabled
if ($this -> test_mode == 'yes'){
$paypro_args['test_mode'] = 'Y';
}
//if timeout_in_days is enabled
if ($this -> timeout_in_days == 'yes'){
$paypro_args['timeout'] = $this->timeout;
}
else{
$paypro_args['timeout'] = $this->timeout*60;
}
$paypro_args = apply_filters( 'woocommerce_paypro_args', $paypro_args );
return $paypro_args;
}
/**
* this function is return product object for two
* different version of WC
*/
function get_product_object(){
return $product;
}
/**
* Check for PayPro IPN Response
*
* #access public
* #return void
*/
function paypro_response() {
global $woocommerce;
// woocommerce_log($_REQUEST);
$this->log(__("== INS Response Received == ", "PayPro") );
$this->log( $_REQUEST );
$wc_order_id = '';
if( !isset($_REQUEST['merchant_order_id']) ) {
if( !isset($_REQUEST['vendor_order_id']) ) {
$this->log( '===== NO ORDER NUMBER FOUND =====' );
exit;
} else {
$wc_order_id = $_REQUEST['vendor_order_id'];
}
} else {
$wc_order_id = $_REQUEST['merchant_order_id'];
}
$this->log(" ==== ORDER -> {$wc_order_id} ====");
// echo $wc_order_id;
$wc_order_id = apply_filters('woocommerce_order_no_received', $wc_order_id, $_REQUEST);
$this->log( "Order Received ==> {$wc_order_id}" );
// exit;
$wc_order = new WC_Order( absint( $wc_order_id ) );
$this->log("Order ID {$wc_order_id}");
$this->log("WC API ==> ".$_GET['wc-api']);
// If redirect after payment
if( isset($_GET['key']) && (isset($_GET['wc-api']) && strtolower($_GET['wc-api']) == 'wc_gateway_mib_paypro') ) {
$this->verify_order_by_hash($wc_order_id);
exit;
}
$message_type = isset($_REQUEST['message_type']) ? $_REQUEST['message_type'] : '';
$sale_id = isset($_REQUEST['sale_id']) ? $_REQUEST['sale_id'] : '';
$invoice_id = isset($_REQUEST['invoice_id']) ? $_REQUEST['invoice_id'] : '';
$fraud_status = isset($_REQUEST['fraud_status']) ? $_REQUEST['fraud_status'] : '';
$this->log( "Message Type/Fraud Status: {$message_type}/{$fraud_status}" );
switch( $message_type ) {
case 'ORDER_CREATED':
$wc_order->add_order_note( sprintf(__('ORDER_CREATED with Sale ID: %d', 'woocommerce'), $sale_id) );
$this->log(sprintf(__('ORDER_CREATED with Sale ID: %d', 'woocommerce'), $sale_id));
break;
case 'FRAUD_STATUS_CHANGED':
if( $fraud_status == 'pass' ) {
// Mark order complete
$wc_order->payment_complete();
$wc_order->add_order_note( sprintf(__('Payment Status Clear with Invoice ID: %d', 'woocommerce'), $invoice_id) );
$this->log(sprintf(__('Payment Status Clear with Invoice ID: %d', 'woocommerce'), $invoice_id));
add_action('woocommerce_order_completed', $order, $sale_id, $invoice_id);
} elseif( $fraud_status == 'fail' ) {
$wc_order->update_status('failed');
$wc_order->add_order_note( __("Payment Declined", 'woocommerce') );
$this->log( __("Payment Declined", 'woocommerce') );
}
break;
}
exit;
}
function verify_order_by_hash($wc_order_id) {
global $woocommerce;
#ob_clean();
$paypro_id = $_REQUEST['paypro_id'];
$tpaycode = $_REQUEST['tpaycode'];
$order_id = $_REQUEST['merchant_order_id'];
$wc_order = wc_get_order( $wc_order_id );
// $order_total = isset($_REQUEST['total']) ? $_REQUEST['total'] : '';
$order_total = $wc_order->get_total();
$compare_string = $this->merchant_id . $paypro_id . $order_total;
$compare_hash1 = strtoupper(md5($compare_string));
$this->log("Compare String ===>" .$compare_string);
$compare_hash2 = $_REQUEST['key'];
if ($compare_hash1 != $compare_hash2) {
$this->log("Hash_1 ==> {$compare_hash1}");
$this->log("Hash_2 ==> {$compare_hash2}");
wp_die( "PayPro Hash Mismatch... check your secret word." );
} else {
//Curl Request
$url = $this->api_url.'/cpay/gos?userName=' . $this->merchant_id . '&password=' . $this->merchant_password . '&cpayId=' . $tpaycode;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
// Submit the GET request
$result = curl_exec($ch);
if (curl_errno($ch)) //catch if curl error exists and show it
echo 'Curl error: ' . curl_error($ch);
else {
//Check if the order ID passed is the same or fake
$res = json_decode($result, true);
$returnedOrderID = explode('-',$res[1]['OrderNumber']);
if ($returnedOrderID[1]===$order_id) {
if (strtoupper($res[1]['OrderStatus']) == "PAID") {
$wc_order->add_order_note( sprintf(__('Payment completed via PayPro Order Number %d', 'paypro'), $tpaycode) );
// Mark order complete
$wc_order->payment_complete();
// Empty cart and clear session
$woocommerce->cart->empty_cart();
$order_redirect = add_query_arg('paypro','processed', $this->get_return_url( $wc_order ));
// Close cURL session handle
curl_close($ch);
wp_redirect( $order_redirect );
exit;
} elseif (strtoupper($res[1]['OrderStatus']) == "BLOCKED") {
$wc_order->add_order_note( sprintf(__('Error processing the payment of Order Number %d', 'paypro'), $tpaycode) );
$order_redirect = add_query_arg('paypro','canceled', $wc_order->get_cancel_order_url());
// Close cURL session handle
curl_close($ch);
wp_redirect( $order_redirect );
exit;
}
elseif (strtoupper($res[1]['OrderStatus']) == "UNPAID") {
$wc_order->add_order_note( sprintf(__('Error processing the payment of Order Number %d', 'paypro'), $tpaycode) );
$order_redirect = add_query_arg('paypro','pending', $wc_order->get_cancel_order_url());
// Close cURL session handle
curl_close($ch);
wp_redirect( $order_redirect );
exit;
}
}
}
}
}
function get_price($price){
$price = wc_format_decimal($price, 2);
return apply_filters('mib_get_price', $price);
}
}
}
function add_mib_payment_gateway( $methods ) {
$methods[] = 'WC_Gateway_MIB_PayPro';
return $methods;
}
add_filter( 'woocommerce_payment_gateways', 'add_mib_payment_gateway' );
function payproco_log( $log ) {
if ( true === WP_DEBUG ) {
if ( is_array( $log ) || is_object( $log ) ) {
$resp = error_log( print_r( $log, true ), 3, plugin_dir_path(__FILE__).'payproco.log' );
} else {
$resp = error_log( $log, 3, plugin_dir_path(__FILE__).'payproco.log' );
}
var_dump($resp);
}
}
Related
I am really stuck and have tried every email hook under the sun. I used an outdated PHP code developed by someone else and revised it for new woocommerce hooks (as the code is 4years old). Everything works perfectly but i need the customer field "billing_vat" to appear in the new order admin email. I will share my code and any help will be greatly appreciated please!!
Thanks
//create vat number billing field
add_filter('woocommerce_billing_fields' , 'display_billing_vat_fields');
function display_billing_vat_fields($billing_fields){
$billing_fields['billing_vat'] = array(
'type' => 'text',
'label' => __('VAT number', 'woocommerce' ),
'class' => array('form-row-wide'),
'required' => false,
'clear' => true,
'priority' => 30, // To change the field location increase or decrease this value
);
return $billing_fields;
}
// Printing the Billing Address on My Account
add_filter( 'woocommerce_my_account_my_address_formatted_address',
'custom_my_account_my_address_formatted_address', 10, 3 );
function custom_my_account_my_address_formatted_address( $fields, $customer_id, $type ) {
if ( $type == 'billing' ) {
$fields['vat'] = get_user_meta( $customer_id, 'billing_vat', true );
}
return $fields;
}
// Checkout -- Order Received (printed after having completed checkout)
add_filter( 'woocommerce_order_formatted_billing_address',
'custom_add_vat_formatted_billing_address', 10, 2 );
function custom_add_vat_formatted_billing_address( $fields, $order ) {
$fields['vat'] = $order->get_meta('billing_vat');
return $fields;
}
// Creating merger VAT variables for printing formatting
add_filter( 'woocommerce_formatted_address_replacements',
'custom_formatted_address_replacements', 10, 2 );
function custom_formatted_address_replacements( $replacements, $args ) {
$replacements['{vat}'] = ! empty($args['vat']) ? $args['vat'] : '';
$replacements['{vat_upper}'] = ! empty($args['vat']) ? strtoupper($args['vat']) : '';
return $replacements;
}
//Defining the Spanish formatting to print the address, including VAT.
add_filter( 'woocommerce_localisation_address_formats', 'custom_localisation_address_format' );
function custom_localisation_address_format( $formats ) {
foreach($formats as $country => $string_address ) {
$formats[$country] = str_replace('{company}\n', '{company}\n{vat_upper}\n', $string_address);
}
return $formats;
}
add_filter( 'woocommerce_customer_meta_fields', 'custom_customer_meta_fields' );
function custom_customer_meta_fields( $fields ) {
$fields['billing']['fields']['billing_vat'] = array(
'label' => __( 'VAT number', 'woocommerce' )
);
return $fields;
}
add_filter( 'woocommerce_admin_billing_fields', 'custom_admin_billing_fields' );
function custom_admin_billing_fields( $fields ) {
$fields['vat'] = array(
'label' => __( 'VAT number', 'woocommerce' ),
'show' => true
);
return $fields;
}
add_filter( 'woocommerce_found_customer_details', 'custom_found_customer_details' );
function custom_found_customer_details( $customer_data ) {
$customer_data['billing_vat'] = get_user_meta( $_POST['user_id'], 'billing_vat', true );
return $customer_data;
}
add_filter('woocommerce_email_order_meta_fields', 'supine_add_email_order_meta_fields', 10, 3 );
function supine_add_email_order_meta_fields( $fields, $sent_to_admin, $order_obj ) {
$billing = get_post_meta( $order_obj->get_order_number(), 'billing_vat', true );
return $fields;
}
Shortly after posting this, i found a fix for it. I had to define the new key "billing_vat" so that it posted with other user information. All the code above is correct except the last add_filter hook. Replace that with the following code, and you have added an optional vat_number field to your checkout, admin backend as well as order emails. Here's the code snippet to replace last "add_filter" hook:
// VAT Number in emails
add_filter( 'woocommerce_email_order_meta_keys',
'supine_vat_number_display_email' );
function supine_vat_number_display_email( $keys ) {
$keys['VAT Number'] = '_billing_vat';
return $keys;
}
code goes in functions.php of your active child theme. Tested and working.
I have 2 PHP scripts, each have their own register and login forms. I want to be able to take the user information from one and use it on the other so that my members do not have to register or login on the second PHP script. Below is the login, register and logout functions for both scripts
This is PHP script #1 where I already have members:
#check login from login form
public function login()
{
$this->form_validation->set_rules('useremail','Email','required|xss_clean');
$this->form_validation->set_rules('password','Password','required|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->trylogin();
}
else
{
$this->load->model('auth_model');
$query = $this->auth_model->check_login($this->input->post('useremail'),$this->input->post('password'),'result');
if($query->num_rows()>0)
{
$row = $query->row();
if($row->banned==1)
{
$msg = '<div class="alert alert-danger">'.
'<button data-dismiss="alert" class="close" type="button">×</button>'.
'<strong>'.lang_key('user_banned').'</strong>'.
'</div>';
$this->session->set_flashdata('msg', $msg);
redirect(site_url('account/trylogin'));
}
else if($row->confirmed!=1)
{
$msg = '<div class="alert alert-danger">'.
'<button data-dismiss="alert" class="close" type="button">×</button>'.
'<strong>'.lang_key('account_not_confirmed').'</strong>'.
'</div>';
$this->session->set_flashdata('msg', $msg);
redirect(site_url('account/trylogin'));
}
else
{
if(is_admin($row->user_name,$row->user_type))
create_log($row->user_name);
$this->session->set_userdata('user_id',$row->id);
$this->session->set_userdata('user_name',$row->user_name);
$this->session->set_userdata('user_type',$row->user_type);
$this->session->set_userdata('user_email',$this->input->post('useremail'));
if($this->session->userdata('req_url')!='')
{
$req_url = $this->session->userdata('req_url');
$this->session->set_userdata('req_url','');
redirect($req_url);
}
redirect(site_url());
}
}
else
{
$msg = '<div class="alert alert-danger">'.
'<button data-dismiss="alert" class="close" type="button">×</button>'.
'<strong>'.lang_key('email_or_password_not_mathed').'</strong>'.
'</div>';
$this->session->set_flashdata('msg', $msg);
redirect(site_url('account/trylogin'));
}
}
}
#logout a user
public function logout()
{
$this->session->sess_destroy();
redirect(site_url());
}
#loads signup view
public function signup()
{
if(is_loggedin())
{
redirect(base_url());
}
if(get_settings('business_settings','enable_signup','Yes')=='No')
{
redirect(site_url());
}
$data['content'] = load_view('register_view','',TRUE);
$data['alias'] = 'signup';
load_template($data,$this->active_theme);
}
public function takepackage()
{
if(get_settings('business_settings','enable_signup','Yes')=='No')
{
redirect(site_url());
}
$this->form_validation->set_rules('package_id', 'Package id', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->signup();
}
else
{
$package_id = $this->input->post('package_id');
$this->session->set_userdata('package_id',$package_id);
if($this->session->userdata('from')=='facebook')
{
$this->session->set_userdata('from','signup');
redirect(site_url('account/fbauth'));
}
else
redirect(site_url('account/signupform'));
}
}
public function signupform()
{
if(is_loggedin())
{
redirect(base_url());
}
if(get_settings('business_settings','enable_signup','Yes')=='No')
{
redirect(site_url());
}
if($this->session->userdata('package_id')=='')
{
if(get_settings('business_settings','enable_pricing','Yes')=='Yes')
redirect(site_url('account/signup'));
else
$value = array();
}
else
{
$this->load->model('admin/package_model');
$value['package'] = $this->package_model->get_package_by_id($this->session->userdata('package_id'));
}
$data['content'] = load_view('register_view',$value,TRUE);
$data['alias'] = 'signup';
load_template($data,$this->active_theme);
}
#controls different signup method routing
function newaccount($type='',$user_type='business')
{
if(is_loggedin())
{
redirect(base_url());
}
if(get_settings('business_settings','enable_signup','Yes')=='No')
{
redirect(site_url());
}
if($user_type=='business')
$this->session->set_userdata('signup_user_type',2);
else
$this->session->set_userdata('signup_user_type',3);
if($type=='fb')
redirect(site_url('account/fbauth'));
else if($type=='google_plus')
{
redirect(site_url('account/google_plus_auth'));
}
}
#signup form submits to this function
function register()
{
if(is_loggedin())
{
redirect(base_url());
}
if(get_settings('business_settings','enable_signup','Yes')=='No')
{
redirect(site_url());
}
$user_type = $this->input->post('user_type');
$this->form_validation->set_rules('first_name', lang_key('first_name'), 'required|xss_clean');
$this->form_validation->set_rules('last_name', lang_key('last_name'), 'required|xss_clean');
$this->form_validation->set_rules('gender', lang_key('gender'), 'required|xss_clean');
$this->form_validation->set_rules('username', lang_key('username'), 'required|callback_username_check|xss_clean');
$this->form_validation->set_rules('company_name',lang_key('company_name'), 'xss_clean');
$this->form_validation->set_rules('phone',lang_key('phone'), 'xss_clean');
$this->form_validation->set_rules('useremail', lang_key('user_email'), 'required|valid_email|xss_clean|callback_useremail_check');
$this->form_validation->set_rules('password', lang_key('password'), 'required|matches[repassword]|min_length[5]|xss_clean');
$this->form_validation->set_rules('repassword', lang_key('confirm_password'), 'required|xss_clean');
$this->form_validation->set_rules('terms_conditon',lang_key('terms_and_condition'),'xss_clean|callback_terms_check');
$enable_pricing = get_settings('business_settings','enable_pricing','Yes');
if ($this->form_validation->run() == FALSE)
{
$this->signup();
}
else
{
$this->load->library('encrypt');
$userdata['user_type'] = 2;//2 = users
$userdata['first_name'] = $this->input->post('first_name');
$userdata['last_name'] = $this->input->post('last_name');
$userdata['gender'] = $this->input->post('gender');
$userdata['user_name'] = $this->input->post('username');
$userdata['user_email'] = $this->input->post('useremail');
$userdata['password'] = $this->encrypt->sha1($this->input->post('password'));
$userdata['confirmation_key'] = uniqid();
$userdata['confirmed'] = 0;
$userdata['status'] = 1;
$this->load->model('user/user_model');
$user_id = $this->user_model->insert_user_data($userdata);
add_user_meta($user_id,'company_name',$this->input->post('company_name'));
add_user_meta($user_id,'phone',$this->input->post('phone'));
$this->send_confirmation_email($userdata);
$this->load->config('business_directory');
if($this->config->item('send_admin_email_user_signup')=='Yes')
$this->send_admin_notification_email();
redirect(site_url('account/success'));
}
}
This is PHP script #2 where I have no members and want to have PHP script #1 members visit without having to register or login:
/* USER LOGIN */
public static function is_logged() {
global $db;
if( !isset( $_COOKIE['user-session'] ) ) {
return false;
} else {
$stmt = $db->stmt_init();
$stmt->prepare( "SELECT user FROM " . DB_TABLE_PREFIX . "sessions WHERE session = ?" );
$stmt->bind_param( "s", $_COOKIE['user-session'] );
$stmt->bind_result( $id );
$stmt->execute();
$stmt->fetch();
if( !empty( $id ) ) {
$stmt->prepare( "SELECT name, email, avatar, points, credits, ipaddr, privileges, erole, subscriber, last_login, (SELECT COUNT(*) FROM " . DB_TABLE_PREFIX . "stores WHERE user = u.id), visits, valid, ban, date FROM " . DB_TABLE_PREFIX . "users u WHERE id = ?" );
$stmt->bind_param( "i", $id );
$stmt->bind_result( $name, $email, $avatar, $points, $credits, $ip, $privileges, $erole, $subscriber, $last_login, $stores, $visits, $valid, $ban, $date );
$stmt->execute();
$stmt->fetch();
// update action
$stmt->prepare( "UPDATE " . DB_TABLE_PREFIX . "users SET points = IF(last_action < DATE(NOW()), points + ?, points), last_action = NOW() WHERE id = ?" );
$daily_points = \query\main::get_option( 'u_points_davisit' );
$stmt->bind_param( "ii", $daily_points, $id );
$stmt->execute();
$stmt->close();
return (object) array( 'ID' => $id, 'Name' => esc_html( $name ), 'Email' => esc_html( $email ), 'Avatar' => esc_html( $avatar ), 'Points' => $points, 'Credits' => $credits, 'IP' => esc_html( $ip ), 'Privileges' => $privileges, 'Erole' => #unserialize( $erole ), 'Last_login' => $last_login, 'Stores' => $stores, 'Visits' => $visits, 'Date' => $date, 'is_subscribed' => $subscriber, 'is_confirmed' => $valid, 'is_banned' => ( strtotime( $ban ) > time() ? true : false ), 'is_subadmin' => ( $privileges >= 1 ? true : false ), 'is_admin' => ( $privileges > 1 ? true : false ) );
} else {
$stmt->close();
return false;
}
}
}
/* BANNED */
public static function banned( $type = '', $IP = '' ) {
global $db;
switch( $type ) {
case 'registration':
$stmt = $db->stmt_init();
$stmt->prepare( "SELECT COUNT(*) FROM " . DB_TABLE_PREFIX . "banned WHERE ipaddr = ? AND registration = 1" );
$userip = empty( $IP ) ? \site\utils::getIP() : $IP;
$stmt->bind_param( "s", $userip );
$stmt->bind_result( $count );
$stmt->execute();
$stmt->fetch();
$stmt->close();
if( $count > 0 ) return true;
return false;
break;
case 'login':
$stmt = $db->stmt_init();
$stmt->prepare( "SELECT COUNT(*) FROM " . DB_TABLE_PREFIX . "banned WHERE ipaddr = ? AND login = 1" );
$userip = empty( $IP ) ? \site\utils::getIP() : $IP;
$stmt->bind_param( "s", $userip );
$stmt->bind_result( $count );
$stmt->execute();
$stmt->fetch();
$stmt->close();
if( $count > 0 ) return true;
return false;
break;
default:
$stmt = $db->stmt_init();
$stmt->prepare( "SELECT id, redirect_to FROM " . DB_TABLE_PREFIX . "banned WHERE ipaddr = ? AND site = 1 AND ( expiration = 0 OR ( expiration = 1 AND expiration_date > NOW() ) )" );
$userip = empty( $IP ) ? \site\utils::getIP() : $IP;
$stmt->bind_param( "s", $userip );
$stmt->bind_result( $id, $new_location );
$stmt->execute();
$stmt->fetch();
$stmt->close();
if( !empty( $id ) ) return $new_location;
return false;
break;
}
return false;
}
/* USER LOGOUT */
public static function logout() {
global $db;
if( !isset( $_COOKIE['user-session'] ) ) {
return false;
} else {
$stmt = $db->stmt_init();
$stmt->prepare( "DELETE FROM " . DB_TABLE_PREFIX . "sessions WHERE session = ?" );
$stmt->bind_param( "s", $_COOKIE['user-session'] );
$execute = $stmt->execute();
$stmt->close();
if( $execute ) {
return true;
}
return false;
}
}
/* USER LOGIN */
public static function login( $post, $privileges = 0 ) {
global $db;
$session = '';
if( self::banned( 'login' ) ) {
throw new \Exception( t( 'msg_banned', "Sorry, but this action isn't permitted for you at this time." ) );
} else {
$stmt = $db->stmt_init();
$stmt->prepare( "SELECT id, password, ban FROM " . DB_TABLE_PREFIX . "users WHERE email = ? AND privileges >= ?" );
$stmt->bind_param( "si", $post['username'], $privileges );
$stmt->bind_result( $id, $password, $ban );
$stmt->execute();
$stmt->fetch();
if( empty( $id ) ) {
// user does not even exist
throw new \Exception( t( 'login_invalid', "Login details are invalid." ) );
} else if( strtotime( $ban ) > time() ) {
// banned user
throw new \Exception( t( 'login_banaccount', "Your account it's banned for security reasons, often for failed login attempts. Please try later." ) );
} else if( (string)$password !== (string) md5( $post['password'] ) ) {
// wrong password
$stmt->prepare( "UPDATE " . DB_TABLE_PREFIX . "users SET fail_attempts = IF(fail_attempts >= " . BAN_AFTER_ATTEMPTS . ", 1, fail_attempts + 1), ban = IF(fail_attempts >= " . BAN_AFTER_ATTEMPTS . ", DATE_ADD(NOW(), INTERVAL " . BAN_AFTER_FAIL . " MINUTE), ban) WHERE email = ?" );
$stmt->bind_param( "s", $post['username'] );
$stmt->execute();
$stmt->close();
throw new \Exception( t( 'login_invalid', "Login details are invalid." ) );
} else {
$session = md5( \site\utils::str_random(15) );
// delete old sessions
$stmt->prepare( "DELETE FROM " . DB_TABLE_PREFIX . "sessions WHERE user = ?" );
$stmt->bind_param( "i", $id );
$stmt->execute();
// insert new session
$stmt->prepare( "INSERT INTO " . DB_TABLE_PREFIX . "sessions SET user = ?, session = ?, expiration = DATE_ADD(NOW(), INTERVAL " . ( isset( $post['keep_logged'] ) ? DEF_USER_SESSION_KL : DEF_USER_SESSION ) . " MINUTE), date = NOW()" );
$stmt->bind_param( "is", $id, $session );
if( !$stmt->execute() ) {
$stmt->close();
throw new \Exception( t( 'msg_error', "Error!" ) );
} else {
$stmt->prepare( "UPDATE " . DB_TABLE_PREFIX . "users SET ipaddr = ?, last_login = NOW(), visits = visits + 1, fail_attempts = 0 WHERE id = ?" );
$userip = \site\utils::getIP();
$stmt->bind_param( "si", $userip, $id );
$stmt->execute();
$stmt->close();
}
}
}
return $session;
}
/* USER REGISTER */
public static function register( $post ) {
global $db;
$session = '';
$max_acc = (int) \query\main::get_option( 'accounts_per_ip' );
if( $max_acc !== 0 && (int) \query\main::users( array( 'ip' => \site\utils::getIP() ) ) >= $max_acc ) {
throw new \Exception( t( 'msg_error', "Error!" ) ); // administrator don't allow that manny accounts
} else if( self::banned( 'registration' ) ) {
throw new \Exception( t( 'msg_banned', "Sorry, but this action isn't permitted for you at this time." ) );
} else if( !isset( $post['email'] ) || !filter_var( $post['email'], FILTER_VALIDATE_EMAIL ) ) {
throw new \Exception( t( 'register_usevalide', "Please use a valid email address." ) );
} else if( !isset( $post['username'] ) ) {
throw new \Exception( t( 'register_complete_name', "Please fill the name." ) );
} else if( !preg_match( '/(^[a-zA-Z0-9 ]{3,25}$)/', $post['username'] ) ) {
throw new \Exception( t( 'register_invalid_name', "The name should not contain special characters, not less than 3 and no more than 25 characters." ) );
} else if( !isset( $post['password'] ) || !isset( $post['password2'] ) ) {
throw new \Exception( t( 'register_paswdreq', "Both passwords are required." ) );
} else if( !preg_match( '/(^[a-zA-Z0-9-_]{5,40}$)/', $post['password'] ) ) {
throw new \Exception( t( 'register_invalid_paswd', "Password should not contain special characters, not less than 5 and no more than 40 characters." ) );
} else if( $post['password'] != $post['password2'] ) {
throw new \Exception( t( 'register_passwdnm', "Passwords do not match!" ) );
} else {
if( !$session = self::insert_user( $post ) ) {
throw new \Exception( t( 'register_accexists', "This email address already exists." ) );
}
return $session;
}
}
/* INSERT USER */
public static function insert_user( $info = array(), $autologin = false, $autovalid = false ) {
/*
** ATTENTION
If $autologin is set to true, login don't require the password !
*/
global $db;
$stmt = $db->stmt_init();
$stmt->prepare( "INSERT INTO " . DB_TABLE_PREFIX . "users (name, email, password, points, ipaddr, last_action, valid, refid, date) VALUES (?, ?, ?, ?, ?, NOW(), ?, ?, NOW())" );
$passwd = isset( $info['password'] ) ? md5( $info['password'] ) : md5( \site\utils::str_random(15) );
$points = (int) \query\main::get_option( 'u_def_points' );
$IPaddr = \site\utils::getIP();
$valid = (int) ( $autovalid ? 1 : (boolean) \query\main::get_option( 'u_confirm_req' ) );
$refid = isset( $_COOKIE['referrer'] ) ? (int) $_COOKIE['referrer'] : 0;
$stmt->bind_param( "sssssii", $info['username'], $info['email'], $passwd, $points, $IPaddr, $valid, $refid );
$execute = $stmt->execute();
if( !$execute && !$autologin ) {
return false;
} else {
$stmt->prepare( "SELECT id FROM " . DB_TABLE_PREFIX . "users WHERE email = ?" );
$stmt->bind_param( "s", $info['email'] );
$stmt->execute();
$stmt->bind_result( $id );
$stmt->fetch();
$session = md5( \site\utils::str_random(15) );
$stmt->prepare( "INSERT INTO " . DB_TABLE_PREFIX . "sessions SET user = ?, session = ?, expiration = DATE_ADD(NOW(), INTERVAL " . DEF_USER_SESSION . " MINUTE), date = NOW()" );
$stmt->bind_param( "is", $id, $session );
$stmt->execute();
$stmt->prepare( "UPDATE " . DB_TABLE_PREFIX . "users SET last_login = NOW(), visits = 1 WHERE id = ?" );
$stmt->bind_param( "i", $id );
$stmt->execute();
if( !$valid ) {
$cofirm_session = md5( \site\utils::str_random(15) );
if( \user\mail_sessions::insert( 'confirmation', array( 'user' => $id, 'session' => $cofirm_session ) ) )
\site\mail::send( $info['email'], t( 'email_acc_title', "Activate account" ) . ' - ' . \query\main::get_option( 'sitename' ), array( 'template' => 'account_confirmation' ), array( 'hello_name' => sprintf( t( 'email_text_hello', "Hello %s" ), $info['username'] ), 'confirmation_main_text' => t( 'email_acc_maintext', "Click on the link bellow to confirm your account." ), 'confirmation_button' => t( 'email_acc_button', "Activate account!" ), 'link' => \site\utils::update_uri( $GLOBALS['siteURL'] . 'verify.php', array( 'user' => $id, 'token' => $cofirm_session ) ) ) );
} else if( $valid && $refid !== 0 ) {
// add points to user who referred the new user
\user\update::add_points( $refid, \query\main::get_option( 'u_points_refer' ) );
}
$stmt->close();
return $session;
}
}
/* USER RECOVERY PASSWORD */
public static function recovery_password( $post, $path = '', $privileges = 0 ) {
global $db;
if( !isset( $post['email'] ) || !filter_var( $post['email'], FILTER_VALIDATE_EMAIL ) ) {
throw new \Exception( t( 'register_usevalide', "Please use a valid email address." ) );
} else {
$stmt = $db->stmt_init();
$stmt->prepare( "SELECT id FROM " . DB_TABLE_PREFIX . "users WHERE email = ? AND privileges >= ?" );
$stmt->bind_param( "si", $post['email'], $privileges );
$stmt->bind_result( $user );
$execute = $stmt->execute();
$stmt->fetch();
$stmt->close();
if( !$execute || empty( $user ) ) {
throw new \Exception( t( 'fp_unkwacc', "Sorry, we couldn't find this account in our database." ) );
} else {
$session = md5( \site\utils::str_random(15) );
if( \user\mail_sessions::insert( 'password_recovery', array( 'user' => $user, 'session' => $session ) ) ) {
// send email
if( \site\mail::send( $post['email'], t( 'email_reset_title', "Reset your password" ) . ' - ' . \query\main::get_option( 'sitename' ), array( 'template' => 'password_reset', 'path' => $path ), array( 'reset_main_text' => t( 'email_reset_maintext', "Click on the link bellow to reset your password." ), 'reset_button' => t( 'email_reset_button', "Reset password!" ), 'link' => \site\utils::update_uri( '', array( 'uid' => $user, 'session' => $session ) ) ) ) )
return true;
}
throw new \Exception( t( 'msg_error', "Error!" ) );
}
}
}
/* RESET PASSWORD */
public static function reset_password( $id, $post ) {
global $db;
if( !isset( $post['password1'] ) || !preg_match( '/(^[a-zA-Z0-9-_]{5,40}$)/', $post['password1'] ) ) {
throw new \Exception( t( 'reset_pwd_wrong_np', "Password should not contain special characters, not less than 5 and no more than 40 characters." ) );
} else if( !isset( $post['password1'] ) || !isset( $post['password2'] ) || $post['password1'] != $post['password2'] ) {
throw new \Exception( t( 'reset_pwd_pwddm', "Passwords do not match!" ) );
} else {
$stmt = $db->stmt_init();
$stmt->prepare( "UPDATE " . DB_TABLE_PREFIX . "users SET password = ? WHERE id = ?" );
$password = md5( $post['password1'] );
$stmt->bind_param( "si", $password, $id );
$execute = $stmt->execute();
$stmt->close();
if( !$execute ) throw new \Exception( t( 'msg_error', "Error!" ) );
}
}
/* CHANGE PASSWORD */
public static function change_password( $id, $post ) {
global $db;
if( !isset( $post['new'] ) || !preg_match( '/(^[a-zA-Z0-9-_]{5,40}$)/', $post['new'] ) ) {
throw new \Exception( t( 'change_pwd_wrong_np', "Password should not contain special characters, not less than 5 and no more than 40 characters." ) );
} else if( !isset( $post['new'] ) || !isset( $post['new2'] ) || $post['new'] != $post['new2'] ) {
throw new \Exception( t( 'change_pwd_pwddm', "Passwords do not match!" ) );
} else {
$stmt = $db->stmt_init();
$stmt->prepare( "SELECT password FROM " . DB_TABLE_PREFIX . "users WHERE id = ?" );
$stmt->bind_param( "i", $id );
$stmt->bind_result( $password );
$stmt->execute();
$stmt->fetch();
if( md5( $post['old'] ) == $password ) {
$stmt->prepare( "UPDATE " . DB_TABLE_PREFIX . "users SET password = ? WHERE id = ?" );
$new = md5( $post['new'] );
$stmt->bind_param( "si", $new, $id );
$execute = $stmt->execute();
$stmt->close();
if( $execute ) {
return true;
} else throw new \Exception( t( 'msg_error', "Error!" ) );
} else {
$stmt->close();
throw new \Exception( t( 'change_pwd_wrongpwd', "Your current password it's wrong!" ) );
}
}
}
/* EDIT PROFILE */
public static function edit_profile( $id, $post ) {
global $db;
if( !isset( $post['username'] ) ) {
throw new \Exception( t( 'profile_complete_name', "Please fill the name." ) );
} else if( !preg_match( '/(^[a-zA-Z0-9 ]{3,25}$)/', $post['username'] ) ) {
throw new \Exception( t( 'profile_invalid_name', "The name should not contain special characters, not less than 3 and no more than 25 characters." ) );
} else {
$avatar = \site\images::upload( $_FILES['edit_profile_form_avatar'], 'avatar_', array( 'max_size' => 1024, 'max_width' => 600, 'max_height' => 600, 'current' => $GLOBALS['me']->Avatar ) );
$stmt = $db->stmt_init();
$stmt->prepare( "UPDATE " . DB_TABLE_PREFIX . "users SET name = ?, avatar = ?, subscriber = ? WHERE id = ?" );
$subscriber = ( isset( $post['subscriber'] ) ? 1 : 0 );
$stmt->bind_param( "ssii", $post['username'], $avatar, $subscriber, $id );
$execute = $stmt->execute();
$stmt->close();
if( $execute ) {
return (object) array( 'avatar' => $avatar );
} else {
throw new \Exception( t( 'msg_error', "Error!" ) );
}
}
}
/* WRITE REVIEW */
public static function write_review( $id, $user, $post ) {
global $db;
if( !( $allow = (int) \query\main::get_option( 'allow_reviews' ) ) || !isset( $post['stars'] ) || !in_array( $post['stars'], array( 1,2,3,4,5 ) ) ) {
throw new \Exception( t( 'msg_error', "Error!" ) ); // this error can appear only when the user try to modify post data OR administrator don't allow new reviews
} else if( $allow === 2 && !$GLOBALS['me']->is_confirmed ) {
throw new \Exception( t( 'review_write_notv', "Your account isn't confirmed, you can't write reviews." ) );
} else if( !isset( $post['text'] ) || trim( $post['text'] ) == '' ) {
throw new \Exception( t( 'review_write_text', "Please fill a message." ) );
} else {
$stmt = $db->stmt_init();
$stmt->prepare( "INSERT INTO " . DB_TABLE_PREFIX . "reviews (user, store, text, stars, valid, lastupdate_by, lastupdate, date) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())" );
$valid = (boolean) \query\main::get_option( 'review_validate' );
$stmt->bind_param( "iisiii", $user, $id, $post['text'], $post['stars'], $valid, $user );
$execute = $stmt->execute();
if( $execute ) {
if( ( $ppr = \query\main::get_option( 'u_points_review' ) ) > 0 ) {
$stmt->prepare( "UPDATE " . DB_TABLE_PREFIX . "users SET points = points + ? WHERE id = ?" );
$stmt->bind_param( "ii", $ppr, $user );
$stmt->execute();
}
$stmt->close();
return true;
} else {
throw new \Exception( t( 'msg_error', "Error!" ) );
}
}
}
Outline-
I am running a Wordpress v4 installation and have installed a chatroom plugin: https://github.com/wp-plugins/chat-room (full code below).
I want to be able to highlight specific words that appear in chat when a user posts a message. For example, every time a user posts a message with the word "Dog" in it, it would have background colour so that it can be highlighted to everyone.
As the HTML output from the plugin is plain HTML, the best solution I have found is the following working example: https://jsfiddle.net/4ny8adpg/2/.
The Problem-
When using the script from the jsfiddle above on the page where the chatroom is placed, it seems that the script either cannot find the words or cannot replace them. I do not understand why, as the HTML that is output from the chatroom scripts is plain HTML (exactly as shown in the jsfiddle). It's also worth noting that the script will find and replace words that are written into the HTML source on the same page.
The Code-
Below is the PHP, Javascript and example HTML output for the chat-room plugin. I did not write this plugin and the original author offers very very limited support.
PHP:
Class Chatroom {
function __construct() {
register_activation_hook( __FILE__, array( $this, 'activation_hook' ) );
register_deactivation_hook( __FILE__, array( $this, 'deactivation_hook' ) );
add_action( 'init', array( $this, 'register_post_types' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_action( 'save_post', array( $this, 'maybe_create_chatroom_log_file' ), 10, 2 );
add_action( 'wp_head', array( $this, 'define_javascript_variables' ) );
add_action( 'wp_ajax_check_updates', array( $this, 'ajax_check_updates_handler' ) );
add_action( 'wp_ajax_send_message', array( $this, 'ajax_send_message_handler' ) );
add_filter( 'the_content', array( $this, 'the_content_filter' ) );
}
function activation_hook() {
$this->register_post_types();
flush_rewrite_rules();
}
function deactivation_hook() {
flush_rewrite_rules();
}
function register_post_types() {
$labels = array(
'name' => _x( 'Chat Rooms', 'post type general name', 'chatroom' ),
'singular_name' => _x( 'Chat Room', 'post type singular name', 'chatroom' ),
'add_new' => _x( 'Add New', 'book', 'chatroom' ),
'add_new_item' => __( 'Add New Chat Room', 'chatroom' ),
'edit_item' => __( 'Edit Chat Room', 'chatroom' ),
'new_item' => __( 'New Chat Room', 'chatroom' ),
'all_items' => __( 'All Chat Rooms', 'chatroom' ),
'view_item' => __( 'View Chat Room', 'chatroom' ),
'search_items' => __( 'Search Chat Rooms', 'chatroom' ),
'not_found' => __( 'No Chat Rooms found', 'chatroom' ),
'not_found_in_trash' => __( 'No Chat Rooms found in Trash', 'chatroom' ),
'parent_item_colon' => '',
'menu_name' => __( 'Chat Rooms', 'chatroom' )
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'show_in_nav_menus' => true,
'supports' => array( 'title' )
);
register_post_type( 'chat-room', $args );
}
function enqueue_scripts() {
global $post;
if ( $post->post_type != 'chat-room' )
return;
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'chat-room', plugins_url( 'chat-room.js', __FILE__ ) );
wp_enqueue_style( 'chat-room-styles', plugins_url( 'chat-room.css', __FILE__ ) );
}
function maybe_create_chatroom_log_file( $post_id, $post ) {
if ( empty( $post->post_type ) || $post->post_type != 'chat-room' )
return;
$upload_dir = wp_upload_dir();
$log_filename = $upload_dir['basedir'] . '/chatter/' . $post->post_name . '-' . date( 'm-d-y', time() );
if ( file_exists( $log_filename ) )
return;
wp_mkdir_p( $upload_dir['basedir'] . '/chatter/' );
$handle = fopen( $log_filename, 'w' );
fwrite( $handle, json_encode( array() ) );
// TODO create warnings if the user can't create a file, and suggest putting FTP creds in wp-config
}
function define_javascript_variables() {
global $post;
if ( empty( $post->post_type ) || $post->post_type != 'chat-room' )
return; ?>
<script>
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
var chatroom_slug = '<?echo $post->post_name; ?>';
</script>
<?php
}
function ajax_check_updates_handler() {
$upload_dir = wp_upload_dir();
$log_filename = $this->get_log_filename( $_POST['chatroom_slug'] );
$contents = $this->parse_messages_log_file( $log_filename );
$messages = json_decode( $contents );
foreach ( $messages as $key => $message ) {
if ( $message->id <= $_POST['last_update_id'] )
unset( $messages[$key] );
}
$messages = array_values( $messages );
echo json_encode( $messages );
die;
}
/**
* AJAX server-side handler for sending a message.
*
* Stores the message in a recent messages file.
*
* Clears out cache of any messages older than 10 seconds.
*/
function ajax_send_message_handler() {
$current_user = wp_get_current_user();
$this->save_message( $_POST['chatroom_slug'], $current_user->id, $_POST['message'] );
die;
}
function save_message( $chatroom_slug, $user_id, $content ) {
$user = get_userdata( $user_id );
if ( ! $user_text_color = get_user_meta( $user_id, 'user_color', true ) ) {
// Set random color for each user
$red = rand( 0, 16 );
$green = 16 - $red;
$blue = rand( 0, 16 );
$user_text_color = '#' . dechex( $red^2 ) . dechex( $green^2 ) . dechex( $blue^2 );
update_user_meta( $user_id, 'user_color', $user_text_color );
}
$content = esc_attr( $content );
// Save the message in recent messages file
$log_filename = $this->get_log_filename( $chatroom_slug );
$contents = $this->parse_messages_log_file( $log_filename );
$messages = json_decode( $contents );
$last_message_id = 0; // Helps determine the new message's ID
foreach ( $messages as $key => $message ) {
if ( time() - $message->time > 10 ) {
$last_message_id = $message->id;
unset( $messages[$key] );
}
else {
break;
}
}
$messages = array_values( $messages );
if ( ! empty( $messages ) )
$last_message_id = end( $messages )->id;
$new_message_id = $last_message_id + 1;
$messages[] = array(
'id' => $new_message_id,
'time' => time(),
'sender' => $user_id,
'contents' => $content,
'html' => '<div class="chat-message-' . $new_message_id . '"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>',
);
$this->write_log_file( $log_filename, json_encode( $messages ) );
// Save the message in the daily log
$log_filename = $this->get_log_filename( $chatroom_slug, date( 'm-d-y', time() ) );
$contents = $this->parse_messages_log_file( $log_filename );
$messages = json_decode( $contents );
$messages[] = array(
'id' => $new_message_id,
'time' => time(),
'sender' => $user_id,
'contents' => $content,
'html' => '<div class="chat-message-' . $new_message_id .'"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>',
);
$this->write_log_file( $log_filename, json_encode( $messages ) );
}
function write_log_file( $log_filename, $content ) {
$handle = fopen( $log_filename, 'w' );
fwrite( $handle, $content );
}
function get_log_filename( $chatroom_slug, $date = 'recent' ) {
$upload_dir = wp_upload_dir();
$log_filename = $upload_dir['basedir'] . '/chatter/' . $chatroom_slug . '-' . $date;
return $log_filename;
}
function parse_messages_log_file( $log_filename ) {
$upload_dir = wp_upload_dir();
$handle = fopen( $log_filename, 'r' );
$contents = fread( $handle, filesize( $log_filename ) );
fclose( $handle );
return $contents;
}
function the_content_filter( $content ) {
global $post;
if ( $post->post_type != 'chat-room' )
return $content;
if ( ! is_user_logged_in() ) {
?>You need to be logged in to participate in the chatroom.<?php
return;
}
?>
<div class="chat-container">
</div>
<textarea class="chat-text-entry"></textarea>
<?php
return '';
}
}
$chatroom = new Chatroom();
Javascript:
var last_update_received = 0;
function chatroom_check_updates() {
jQuery.post(
ajaxurl,
{
action: 'check_updates',
chatroom_slug: chatroom_slug,
last_update_id: last_update_id
},
function (response) {
chats = jQuery.parseJSON( response );
if ( chats !== null ) {
for ( i = 0; i < chats.length; i++ ) {
if ( jQuery('div.chat-container div.chat-message-'+chats[i].id).length )
continue;
jQuery('div.chat-container').html( jQuery('div.chat-container').html() + chatroom_strip_slashes(chats[i].html) );
last_update_id = chats[i].id;
jQuery('div.chat-container').animate({ scrollTop: jQuery('div.chat-container')[0].scrollHeight - jQuery('div.chat-container').height() }, 100);
}
}
}
);
setTimeout( "chatroom_check_updates()", 1000 );
}
function chatroom_strip_slashes(str) {
return (str + '').replace(/\\(.?)/g, function (s, n1) {
switch (n1) {
case '\\':
return '\\';
case '0':
return '\u0000';
case '':
return '';
default:
return n1;
}
});
}
jQuery(document).ready( function() {
last_update_id = 0;
chatroom_check_updates();
jQuery( 'textarea.chat-text-entry' ).keypress( function( event ) {
if ( event.charCode == 13 || event.keyCode == 13 ) {
chatroom_send_message();
return false;
}
});
});
function chatroom_send_message() {
message = jQuery( 'textarea.chat-text-entry' ).val();
jQuery( 'textarea.chat-text-entry' ).val('');
jQuery.post(
ajaxurl,
{
action: 'send_message',
chatroom_slug: chatroom_slug,
message: message
},
function (response) {
}
);
}
HTML Output:
<div class="chat-container">
<div class="chat chat-message-111"><strong style="color: #840;">User 1</strong>: What is your favourite animal?</div>
<div class="chat chat-message-112"><strong style="color: #840;">User 2</strong>: I vote for #dog. </div>
<div class="chat chat-message-113"><strong style="color: #840;">User 3</strong>: I have a #cat!</div>
</div>
My question really is, am I missing something obvious? Any help towards a solution will be greatly appreciated!
EDIT: To provide better explanation.
EDIT 2: Added script output as requested
Var. Chats in chatroom_check_updates() Output:
[{"id":129,"time":1428340673,"sender":1,"contents":"What is your favourite animal?","html":"<div class=\"chat chat-message-129\"><strong style=\"color: #840;\">User 1<\/strong>: What is your favourite animal?<\/div>"},
{"id":130,"time":1428351683,"sender":2,"contents":"I vote for #dog.","html":"<div class=\"chat chat-message-130\"><strong style=\"color: #840;\">User 2<\/strong>: I vote for #dog.<\/div>"},
{"id":131,"time":1428352376,"sender":3,"contents":"I have a #cat!","html":"<div class=\"chat chat-message-131\"><strong style=\"color: #840;\">User 3<\/strong>: I have a #cat!<\/div>"}]
So this is a question following on from the awesome work #Drakes has done on this question previously: Highlighting words with Javascript, what am I missing?.
The solution is to highlight words by finding "#cat" or "#dog" and replacing them with
<span class='cat'>#CAT</span>
or
<span class='dog'>#DOG</span>
Then we can control the background colour of the span tag with CSS.
This works perfectly, however the background colour only remains for a brief moment before disappearing. Upon a closer look, it seems the span tags are applied correctly and then removed again suddenly.
Here is the actual working example for you to have a look at, plus log in details to run any tests and to view the chat.
[Removed, no longer exists]
Below is the updated code from the previous question that is currently running on the working example.
Once again, any further help is hugely appreciated. Please let me know if you require any additional information!
Javascript:
// NOTE: I needed to define these variables to make the demo work
var ajaxurl = "http://ip.jsontest.com/";
var chatroom_slug = "1";
var last_update_id = "1";
var last_update_received = 0;
function chatroom_check_updates() {
jQuery.post(
ajaxurl,
{
action: 'check_updates',
chatroom_slug: chatroom_slug,
last_update_id: last_update_id
},
function (response) {
// NOTE: the response is bad, an exception will be thrown, not NULL
chats = null;
try {
chats = jQuery.parseJSON( response );
} catch(e) {}
// NOTE: In this test, I don't know your URL, so I just commented out the bit below
if (1 || chats !== null ) {
for ( i = 0; i < chats.length; i++ ) {
if ( jQuery('div.chat-container div.chat-message-'+chats[i].id).length )
continue;
jQuery('div.chat-container').html( jQuery('div.chat-container').html() + chatroom_strip_slashes(chats[i].html) );
last_update_id = chats[i].id;
jQuery('div.chat-container').animate({ scrollTop: jQuery('div.chat-container')[0].scrollHeight - jQuery('div.chat-container').height() }, 100);
}
jQuery('.chat').each(function(){
var hashtag = jQuery(this).text()
.replace(/#dog/g, "<span class='dog'>#DOG</span>")
.replace(/#cat/g, "<span class='cat'>#CAT</span>");
jQuery(this).html(hashtag);
});
}
}
)
.error(function(xhr, status, error){
alert(xhr.responseText);
});
// I commented this out just for testing.
setTimeout( chatroom_check_updates, 1000 );
}
function chatroom_strip_slashes(str) {
return (str + '').replace(/\\(.?)/g, function (s, n1) {
switch (n1) {
case '\\':
return '\\';
case '0':
return '\u0000';
case '':
return '';
default:
return n1;
}
});
}
jQuery(document).ready( function() {
last_update_id = 0;
chatroom_check_updates();
jQuery( 'textarea.chat-text-entry' ).keypress( function( event ) {
if ( event.charCode == 13 || event.keyCode == 13 ) {
chatroom_send_message();
return false;
}
});
});
function chatroom_send_message() {
message = jQuery( 'textarea.chat-text-entry' ).val();
jQuery( 'textarea.chat-text-entry' ).val('');
jQuery.post(
ajaxurl,
{
action: 'send_message',
chatroom_slug: chatroom_slug,
message: message
},
function (response) {
}
);
}
PHP:
<?php
/*
Plugin Name: Chat Room
Plugin URI: http://webdevstudios.com/support/wordpress-plugins/
Description: Chat Room for WordPress
Author: WebDevStudios.com
Version: 0.1.2
Author URI: http://webdevstudios.com/
License: GPLv2 or later
*/
Class Chatroom {
function __construct() {
register_activation_hook( __FILE__, array( $this, 'activation_hook' ) );
register_deactivation_hook( __FILE__, array( $this, 'deactivation_hook' ) );
add_action( 'init', array( $this, 'register_post_types' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_action( 'save_post', array( $this, 'maybe_create_chatroom_log_file' ), 10, 2 );
add_action( 'wp_head', array( $this, 'define_javascript_variables' ) );
add_action( 'wp_ajax_check_updates', array( $this, 'ajax_check_updates_handler' ) );
add_action( 'wp_ajax_send_message', array( $this, 'ajax_send_message_handler' ) );
add_filter( 'the_content', array( $this, 'the_content_filter' ) );
}
function activation_hook() {
$this->register_post_types();
flush_rewrite_rules();
}
function deactivation_hook() {
flush_rewrite_rules();
}
function register_post_types() {
$labels = array(
'name' => _x( 'Chat Rooms', 'post type general name', 'chatroom' ),
'singular_name' => _x( 'Chat Room', 'post type singular name', 'chatroom' ),
'add_new' => _x( 'Add New', 'book', 'chatroom' ),
'add_new_item' => __( 'Add New Chat Room', 'chatroom' ),
'edit_item' => __( 'Edit Chat Room', 'chatroom' ),
'new_item' => __( 'New Chat Room', 'chatroom' ),
'all_items' => __( 'All Chat Rooms', 'chatroom' ),
'view_item' => __( 'View Chat Room', 'chatroom' ),
'search_items' => __( 'Search Chat Rooms', 'chatroom' ),
'not_found' => __( 'No Chat Rooms found', 'chatroom' ),
'not_found_in_trash' => __( 'No Chat Rooms found in Trash', 'chatroom' ),
'parent_item_colon' => '',
'menu_name' => __( 'Chat Rooms', 'chatroom' )
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'show_in_nav_menus' => true,
'supports' => array( 'title' )
);
register_post_type( 'chat-room', $args );
}
function enqueue_scripts() {
global $post;
if ( $post->post_type != 'chat-room' )
return;
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'chat-room', plugins_url( 'chat-room.js', __FILE__ ) );
wp_enqueue_style( 'chat-room-styles', plugins_url( 'chat-room.css', __FILE__ ) );
}
function maybe_create_chatroom_log_file( $post_id, $post ) {
if ( empty( $post->post_type ) || $post->post_type != 'chat-room' )
return;
$upload_dir = wp_upload_dir();
$log_filename = $upload_dir['basedir'] . '/chatter/' . $post->post_name . '-' . date( 'm-d-y', time() );
if ( file_exists( $log_filename ) )
return;
wp_mkdir_p( $upload_dir['basedir'] . '/chatter/' );
$handle = fopen( $log_filename, 'w' );
fwrite( $handle, json_encode( array() ) );
// TODO create warnings if the user can't create a file, and suggest putting FTP creds in wp-config
}
function define_javascript_variables() {
global $post;
if ( empty( $post->post_type ) || $post->post_type != 'chat-room' )
return; ?>
<script>
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
var chatroom_slug = '<?echo $post->post_name; ?>';
</script>
<?php
}
function ajax_check_updates_handler() {
$upload_dir = wp_upload_dir();
$log_filename = $this->get_log_filename( $_POST['chatroom_slug'] );
$contents = $this->parse_messages_log_file( $log_filename );
$messages = json_decode( $contents );
foreach ( $messages as $key => $message ) {
if ( $message->id <= $_POST['last_update_id'] )
unset( $messages[$key] );
}
$messages = array_values( $messages );
echo json_encode( $messages );
die;
}
/**
* AJAX server-side handler for sending a message.
*
* Stores the message in a recent messages file.
*
* Clears out cache of any messages older than 10 seconds.
*/
function ajax_send_message_handler() {
$current_user = wp_get_current_user();
$this->save_message( $_POST['chatroom_slug'], $current_user->id, $_POST['message'] );
die;
}
function save_message( $chatroom_slug, $user_id, $content ) {
$user = get_userdata( $user_id );
if ( ! $user_text_color = get_user_meta( $user_id, 'user_color', true ) ) {
// Set random color for each user
$red = rand( 0, 16 );
$green = 16 - $red;
$blue = rand( 0, 16 );
$user_text_color = '#' . dechex( $red^2 ) . dechex( $green^2 ) . dechex( $blue^2 );
update_user_meta( $user_id, 'user_color', $user_text_color );
}
$content = esc_attr( $content );
// Save the message in recent messages file
$log_filename = $this->get_log_filename( $chatroom_slug );
$contents = $this->parse_messages_log_file( $log_filename );
$messages = json_decode( $contents );
$last_message_id = 0; // Helps determine the new message's ID
foreach ( $messages as $key => $message ) {
if ( time() - $message->time > 100 ) {
$last_message_id = $message->id;
unset( $messages[$key] );
}
else {
break;
}
}
$messages = array_values( $messages );
if ( ! empty( $messages ) )
$last_message_id = end( $messages )->id;
$new_message_id = $last_message_id + 1;
$messages[] = array(
'id' => $new_message_id,
'time' => time(),
'sender' => $user_id,
'contents' => $content,
'html' => '<div class="chat chat-message-' . $new_message_id . '"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>',
);
$this->write_log_file( $log_filename, json_encode( $messages ) );
// Save the message in the daily log
$log_filename = $this->get_log_filename( $chatroom_slug, date( 'm-d-y', time() ) );
$contents = $this->parse_messages_log_file( $log_filename );
$messages = json_decode( $contents );
$messages[] = array(
'id' => $new_message_id,
'time' => time(),
'sender' => $user_id,
'contents' => $content,
'html' => '<div class="chat chat-message-' . $new_message_id .'"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>',
);
$this->write_log_file( $log_filename, json_encode( $messages ) );
}
function write_log_file( $log_filename, $content ) {
$handle = fopen( $log_filename, 'w' );
fwrite( $handle, $content );
}
function get_log_filename( $chatroom_slug, $date = 'recent' ) {
$upload_dir = wp_upload_dir();
$log_filename = $upload_dir['basedir'] . '/chatter/' . $chatroom_slug . '-' . $date;
return $log_filename;
}
function parse_messages_log_file( $log_filename ) {
$upload_dir = wp_upload_dir();
$handle = fopen( $log_filename, 'r' );
$contents = fread( $handle, filesize( $log_filename ) );
fclose( $handle );
return $contents;
}
function the_content_filter( $content ) {
global $post;
if ( $post->post_type != 'chat-room' )
return $content;
if ( ! is_user_logged_in() ) {
?>You need to be logged in to participate in the chatroom.<?php
return;
}
?>
<div class="chat-container">
</div>
<textarea class="chat-text-entry"></textarea>
<?php
return '';
}
}
$chatroom = new Chatroom();
Example HTML output:
<div class="chat-container">
<div class="chat chat-message-111"><strong style="color: #840;">User 1</strong>: What is your favourite animal?</div>
<div class="chat chat-message-112"><strong style="color: #840;">User 2</strong>: I vote for #dog. </div>
<div class="chat chat-message-113"><strong style="color: #840;">User 3</strong>: I have a #cat!</div>
</div>
Because you are replacing all the text even if there is not a match. So .text() strips the HTML and than it does not find dog or cat and just puts the text in.
var hashtag = jQuery(this).text()
.replace(/#dog/g, "<span class='dog'>#DOG</span>")
.replace(/#cat/g, "<span class='cat'>#CAT</span>");
jQuery(this).html(hashtag);
since you replace #dog with #DOG it will not match since the search is not case insensitive
either make it case insensitive
/#dog/gi
or only replace the text if there is a change made.
var orgText = jQuery(this).text();
var hashtag = orgText
.replace(/#dog/g, "<span class='dog'>#DOG</span>")
.replace(/#cat/g, "<span class='cat'>#CAT</span>");
if(orgText!==hashtag) {
jQuery(this).html(hashtag);
}
Note: the way you have it currently written, you are going to blow away the User formatting since you are reading the text.
<?php
// Edit this ->
define( 'MQ_SERVER_ADDR', 'XX.XXX.XXX.XXX' );
define( 'MQ_SERVER_PORT', 25565 );
define( 'MQ_TIMEOUT', 1 );
// Edit this <-
// Display everything in browser, because some people can't look in logs for errors
Error_Reporting( E_ALL | E_STRICT );
Ini_Set( 'display_errors', true );
require __DIR__ . '/status/MinecraftQuery.class.php';
$Timer = MicroTime( true );
$Query = new MinecraftQuery( );
try
{
$Query->Connect( MQ_SERVER_ADDR, MQ_SERVER_PORT, MQ_TIMEOUT );
}
catch( MinecraftQueryException $e )
{
$Exception = $e;
}
$Timer = Number_Format( MicroTime( true ) - $Timer, 4, '.', '' );
?>
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
<div class="spanx"><p>
<h1>Login</h1>
Username:<br />
<input type="text" name="username" style="height: 30px; style="width: 220px; value="" />
<br/>
<button>Submit</button>
<?php // Example from PHP.net
$string = '<?php if( ( $Players = $Query->GetPlayers( ) ) !== false ): ?>
<?php foreach( $Players as $Player ): ?>';
if(stristr($string, 'Thisshouldbethestringfromthetextbox') === FALSE) {
echo 'Player is not online';
}
?>
Is my code. Basically what I am trying to do is query my Minecraft server. Check if a player is online by the text form on button click, and if not, deliver a message that says the player is not online, otherwise, keep the person logged in as they browse the site (dunno how to do this either...)
The external query file is:
<?php
class MinecraftQueryException extends Exception
{
// Exception thrown by MinecraftQuery class
}
class MinecraftQuery
{
/*
* Class written by xPaw
*
* Website: http://xpaw.ru
* GitHub: https://github.com/xPaw/PHP-Minecraft-Query
*/
const STATISTIC = 0x00;
const HANDSHAKE = 0x09;
private $Socket;
private $Players;
private $Info;
public function Connect( $Ip, $Port = 25565, $Timeout = 3 )
{
if( !is_int( $Timeout ) || $Timeout < 0 )
{
throw new InvalidArgumentException( 'Timeout must be an integer.' );
}
$this->Socket = #FSockOpen( 'udp://' . $Ip, (int)$Port, $ErrNo, $ErrStr, $Timeout );
if( $ErrNo || $this->Socket === false )
{
throw new MinecraftQueryException( 'Could not create socket: ' . $ErrStr );
}
Stream_Set_Timeout( $this->Socket, $Timeout );
Stream_Set_Blocking( $this->Socket, true );
try
{
$Challenge = $this->GetChallenge( );
$this->GetStatus( $Challenge );
}
// We catch this because we want to close the socket, not very elegant
catch( MinecraftQueryException $e )
{
FClose( $this->Socket );
throw new MinecraftQueryException( $e->getMessage( ) );
}
FClose( $this->Socket );
}
public function GetInfo( )
{
return isset( $this->Info ) ? $this->Info : false;
}
public function GetPlayers( )
{
return isset( $this->Players ) ? $this->Players : false;
}
private function GetChallenge( )
{
$Data = $this->WriteData( self :: HANDSHAKE );
if( $Data === false )
{
throw new MinecraftQueryException( 'Offline' );
}
return Pack( 'N', $Data );
}
private function GetStatus( $Challenge )
{
$Data = $this->WriteData( self :: STATISTIC, $Challenge . Pack( 'c*', 0x00, 0x00, 0x00, 0x00 ) );
if( !$Data )
{
throw new MinecraftQueryException( 'Failed to receive status.' );
}
$Last = '';
$Info = Array( );
$Data = SubStr( $Data, 11 ); // splitnum + 2 int
$Data = Explode( "\x00\x00\x01player_\x00\x00", $Data );
if( Count( $Data ) !== 2 )
{
throw new MinecraftQueryException( 'Failed to parse server\'s response.' );
}
$Players = SubStr( $Data[ 1 ], 0, -2 );
$Data = Explode( "\x00", $Data[ 0 ] );
// Array with known keys in order to validate the result
// It can happen that server sends custom strings containing bad things (who can know!)
$Keys = Array(
'hostname' => 'HostName',
'gametype' => 'GameType',
'version' => 'Version',
'plugins' => 'Plugins',
'map' => 'Map',
'numplayers' => 'Players',
'maxplayers' => 'MaxPlayers',
'hostport' => 'HostPort',
'hostip' => 'HostIp'
);
foreach( $Data as $Key => $Value )
{
if( ~$Key & 1 )
{
if( !Array_Key_Exists( $Value, $Keys ) )
{
$Last = false;
continue;
}
$Last = $Keys[ $Value ];
$Info[ $Last ] = '';
}
else if( $Last != false )
{
$Info[ $Last ] = $Value;
}
}
// Ints
$Info[ 'Players' ] = IntVal( $Info[ 'Players' ] );
$Info[ 'MaxPlayers' ] = IntVal( $Info[ 'MaxPlayers' ] );
$Info[ 'HostPort' ] = IntVal( $Info[ 'HostPort' ] );
// Parse "plugins", if any
if( $Info[ 'Plugins' ] )
{
$Data = Explode( ": ", $Info[ 'Plugins' ], 2 );
$Info[ 'RawPlugins' ] = $Info[ 'Plugins' ];
$Info[ 'Software' ] = $Data[ 0 ];
if( Count( $Data ) == 2 )
{
$Info[ 'Plugins' ] = Explode( "; ", $Data[ 1 ] );
}
}
else
{
$Info[ 'Software' ] = 'Vanilla';
}
$this->Info = $Info;
if( $Players )
{
$this->Players = Explode( "\x00", $Players );
}
}
private function WriteData( $Command, $Append = "" )
{
$Command = Pack( 'c*', 0xFE, 0xFD, $Command, 0x01, 0x02, 0x03, 0x04 ) . $Append;
$Length = StrLen( $Command );
if( $Length !== FWrite( $this->Socket, $Command, $Length ) )
{
throw new MinecraftQueryException( "Failed to write on socket." );
}
$Data = FRead( $this->Socket, 2048 );
if( $Data === false )
{
throw new MinecraftQueryException( "Failed to read from socket." );
}
if( StrLen( $Data ) < 5 || $Data[ 0 ] != $Command[ 2 ] )
{
return false;
}
return SubStr( $Data, 5 );
}
}
I would like to solve this in any way that I can. Thanks in advance and ask any questions you need :D.
You can create a form pointing to the same URL to accomplish that.
<form action="<?= $_SERVER['REQUEST_URI'] ?>" method="post">
Username: <input type="text" name="username" />
<button type="submit">Send</button>
</form>
When the form is sent, you can access your input content by accessing $_POST['username']
if (isset($_POST['username'])) {
// your code here
echo 'Username: ' . $_POST['username'];
}