Place ads between two text-only paragraphs - php

I am using the following code to place ads between text-only paragraphs. However, the problem is it inserts only 2 ads in the content even if the post is lengthy.
So, I want to display the ad in every nth paragraph (keeping the first ad). So, if n=4, the ad will display after the 4th paragraph but only if the 5th paragraph have text.
add_filter( 'the_content', 'so_25888630_ad_between_paragraphs' );
function so_25888630_ad_between_paragraphs($content){
if( in_the_loop() ){
$closing_p = '</p>';
$paragraphs = explode( $closing_p, wptexturize($content) );
$count = count( $paragraphs );
if( 4 >= $count ) {
$totals = array( $paragraphs );
}else{
$midpoint = floor($count / 2);
$first = array_slice($paragraphs, 0, $midpoint );
if( $count%2 == 1 ) {
$second = array_slice( $paragraphs, $midpoint, $midpoint, true );
}else{
$second = array_slice( $paragraphs, $midpoint, $midpoint-1, true );
}
$totals = array( $first, $second );
}
$new_paras = array();
foreach ( $totals as $key_total=>$total ) {
$p = array();
foreach ( $total as $key_paras=>$paragraph ) {
$word_count = count(explode(' ', $paragraph));
if( preg_match( '~<(?:img|ul|li)[ >]~', $paragraph ) || $word_count < 10 ) {
$p[$key_paras] = 0;
}else{
$p[$key_paras] = 1;
}
}
$m = array();
foreach ( $p as $key=>$value ) {
if( 1 === $value && array_key_exists( $key-1, $p ) && $p[$key] === $p[$key-1] && !$m){
$m[] = $key;
}elseif( !array_key_exists( $key+1, $p ) && !$m ) {
$m[] = 'no-ad';
}
}
if( $key_total == 0 ){
$ad = array( 'ad1' => '<p>PLACE YOUR ADD NO 1 HERE</p>' );
}else{
$ad = array( 'ad2' => '<p>PLACE YOUR ADD NO 2 HERE</p>' );
}
foreach ( $total as $key_para=>$para ) {
if( !in_array( 'no_ad', $m ) && $key_para === $m[0] ){
$new_paras[key($ad)] = $ad[key($ad)];
$new_paras[$key_para] = $para;
}else{
$new_paras[$key_para] = $para;
}
}
}
$content = implode( ' ', $new_paras );
}
return $content;
}

Related

Woocommerce Upsell and cross-sell on product page

Hi I got this plugin from WordPress https://wordpress.org/plugins/c4d-woo-boost-sales/
now the plugin works fine, I would just like to change the order of the upsell and cross-sell but for some reason can not get it to work. upsell is first the cross-sell I would like to change it to cross-sell then upsell. DUE TO CHARACTER LIMIT I could not also include the original. but I can say that I only changed these two around
function c4d_woo_bs_get_up_sell_from_cart($products = array())
function c4d_woo_bs_get_cross_sell($products = array())
I have changed it like this see where it reads NEEDS TO BE FIRST AND NEEDS TO BE LAST but changing it this way did noting to the order see sections
function c4d_woo_bs_get_up_sell_from_cart($products = array())
function c4d_woo_bs_get_cross_sell($products = array())
<?php
//// INIT
add_action( 'woocommerce_init', 'c4d_woo_bs_init' );
function c4d_woo_bs_init() {
global $c4d_plugin_manager;
// show in single page
if (isset($c4d_plugin_manager['c4d-woo-bs-page-single-product']) && $c4d_plugin_manager['c4d-woo-bs-page-single-product'] == 1) {
add_action( 'woocommerce_after_single_product_summary', 'c4d_woo_bs_list_product', 99 );
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );
}
// show in mini cart
if (isset($c4d_plugin_manager['c4d-woo-bs-global-mini-cart']) && $c4d_plugin_manager['c4d-woo-bs-global-mini-cart'] == 1) {
add_action( 'woocommerce_after_mini_cart', 'c4d_woo_bs_mini_cart', 0 );
}
// show in cart page
if (isset($c4d_plugin_manager['c4d-woo-bs-global-cart-page']) && $c4d_plugin_manager['c4d-woo-bs-global-cart-page'] == 1) {
add_action( 'woocommerce_after_cart', 'c4d_woo_bs_list_product' );
}
// show in thankyou page
add_action( 'woocommerce_thankyou', 'c4d_woo_bs_thankyou_page', 10);
// show in email: process || complete order
add_action( 'woocommerce_email_header', 'c4d_woo_bs_email_header', 10, 2 );
add_action( 'woocommerce_email_customer_details', 'c4d_woo_bs_email_customer_details', 10, 4 );
//// CART PAGE
remove_action( 'woocommerce_cart_collaterals', 'woocommerce_cross_sell_display');
//// UP SELL HOOK
add_filter( 'woocommerce_upsell_display_args', 'c4d_woo_bs_upsell_display_args' );
/// CROSS SELL HOOK
add_filter( 'woocommerce_cross_sells_total', 'c4d_woo_bs_cross_sells_total' );
add_filter( 'woocommerce_cross_sells_orderby', 'c4d_woo_bs_cross_sells_orderby' );
add_filter( 'woocommerce_cross_sells_columns', 'c4d_woo_bs_cross_sells_columns' );
}
/////// FUNCTIONS
function c4d_woo_bs_mini_cart($orderId) {
echo '<div class="c4d_woo_bs_mini_cart">';
c4d_woo_bs_list_product($orderId);
echo '</div>';
}
function c4d_woo_bs_replace_title_for_page_email() {
global $c4d_plugin_manager;
$c4d_plugin_manager['c4d-woo-bs-cross-title'] = $c4d_plugin_manager['c4d-woo-bs-email-cross-title'];
$c4d_plugin_manager['c4d-woo-bs-cross-hide-title'] = $c4d_plugin_manager['c4d-woo-bs-email-cross-hide-title'];
$c4d_plugin_manager['c4d-woo-bs-cross-desc'] = $c4d_plugin_manager['c4d-woo-bs-email-cross-desc'];
$c4d_plugin_manager['c4d-woo-bs-cross-hide-desc'] = $c4d_plugin_manager['c4d-woo-bs-email-cross-hide-desc'];
$c4d_plugin_manager['c4d-woo-bs-up-title'] = $c4d_plugin_manager['c4d-woo-bs-email-up-title'];
$c4d_plugin_manager['c4d-woo-bs-up-hide-title'] = $c4d_plugin_manager['c4d-woo-bs-email-up-hide-title'];
$c4d_plugin_manager['c4d-woo-bs-up-desc'] = $c4d_plugin_manager['c4d-woo-bs-email-up-desc'];
$c4d_plugin_manager['c4d-woo-bs-up-hide-desc'] = $c4d_plugin_manager['c4d-woo-bs-email-up-hide-desc'];
}
function c4d_woo_bs_thankyou_page($orderId) {
global $c4d_plugin_manager;
if (isset($c4d_plugin_manager['c4d-woo-bs-global-thankyou-page']) && $c4d_plugin_manager['c4d-woo-bs-global-thankyou-page'] == 1) {
c4d_woo_bs_replace_title_for_page_email();
c4d_woo_bs_list_product($orderId);
}
}
function c4d_woo_bs_email_header($email_heading, $email) {
if (c4d_woo_bs_is_email_pages($email)){
$file = dirname(plugin_dir_path( __FILE__) ) . '/assets/default.css';
if (file_exists($file)) {
$css = file_get_contents($file);
if ($css) {
echo '<style class="c4d-woo-bs">'.$css.'</style>';
}
}
}
}
function c4d_woo_bs_is_email_pages($email) {
$pages = array(
'WC_Email_Customer_Completed_Order',
'WC_Email_Customer_Processing_Order',
'WC_Email_Customer_Note',
);
if (in_array(get_class($email), $pages)) {
return true;
}
return false;
}
function c4d_woo_bs_email_customer_details($order, $sent_to_admin, $plain_text, $email) {
if (c4d_woo_bs_is_email_pages($email)) {
// replace title/desc for email page
c4d_woo_bs_replace_title_for_page_email();
echo '<div class="c4d_woo_bs_email_wrap">';
c4d_woo_bs_list_product($order->get_id());
echo '</div>';
}
}
function c4d_woo_bs_cross_sells_total($params) {
global $c4d_plugin_manager;
if (isset($c4d_plugin_manager['c4d-woo-bs-cross-limit'])) {
return $c4d_plugin_manager['c4d-woo-bs-cross-limit'];
}
return $params;
}
function c4d_woo_bs_cross_sells_orderby($params) {
global $c4d_plugin_manager;
if (isset($c4d_plugin_manager['c4d-woo-bs-cross-order'])) {
return $c4d_plugin_manager['c4d-woo-bs-cross-order'];
}
return $params;
}
function c4d_woo_bs_cross_sells_columns($params) {
global $c4d_plugin_manager;
if (isset($c4d_plugin_manager['c4d-woo-bs-cross-column'])) {
return $c4d_plugin_manager['c4d-woo-bs-cross-column'];
}
return $params;
}
function c4d_woo_bs_upsell_display_args($params) {
global $c4d_plugin_manager;
if (isset($c4d_plugin_manager['c4d-woo-bs-up-limit'])) {
$params['posts_per_page'] = $c4d_plugin_manager['c4d-woo-bs-up-limit'];
}
if (isset($c4d_plugin_manager['c4d-woo-bs-up-column'])) {
$params['columns'] = $c4d_plugin_manager['c4d-woo-bs-up-column'];
}
if (isset($c4d_plugin_manager['c4d-woo-bs-up-order'])) {
$params['orderby'] = $c4d_plugin_manager['c4d-woo-bs-up-order'];
}
return $params;
}
function c4d_woo_bs_list_product($orderId = false) {
global $c4d_plugin_manager;
$c4d_plugin_manager['c4d_woo_bs_category_tag_one_time'] = false;
$type = isset($c4d_plugin_manager['c4d-woo-bs-global-show-type']) ? $c4d_plugin_manager['c4d-woo-bs-global-show-type'] : 0;
if ($type == 0) {
echo '<div class="c4d_woo_bs_wrap">';
if (in_array($type, array('crosssell', 'upsell&crosssell'))) {
$products = c4d_woo_bs_cross_get_srouces($orderId);
c4d_woo_bs_get_cross_sell($products);
}
// if product is not set the up/cross sell, plugin will get the product in same category,
// so it will be duplicate so only display one time.
if ($c4d_plugin_manager['c4d_woo_bs_category_tag_one_time'] == false) {
if (in_array($type, array('upsell', 'upsell&crosssell'))) {
$products = c4d_woo_bs_up_get_srouces($orderId);
c4d_woo_bs_get_up_sell_from_cart($products);
}
}
echo '</div>';
}
}
function c4d_woo_bs_get_product_from_order($orderId, $type = 'upsell'){
$order = wc_get_order($orderId);
$items = $order->get_items();
$ids = array();
foreach ($items as $key => $item) {
if ($type == 'upsell') {
$ids = array_merge( $item->get_product()->get_upsell_ids(), $ids );
} else {
$ids = array_merge( $item->get_product()->get_cross_sell_ids(), $ids );
}
}
return $ids;
}
function c4d_woo_bs_get_product_from_category($orderId = null, $type = 'upsell'){
global $c4d_plugin_manager, $product;
$products = array();
$category_ids = array();
$category_slugs = array();
$excludes = array();
if (is_product()) {
$pid = method_exists('get_parent_id', $product) ? $product->get_parent_id() : 0;
$pid = $pid ? $pid : $product->get_id();
$data = c4d_woo_bs_get_data($pid, 'category');
if (isset($data[$type]) && $data[$type] !== '') {
$category_slugs = array_merge(array_map('trim', explode(',', $data[$type])), $category_slugs);
}
if (count($category_slugs) < 1) {
$category_ids = array_merge($product->get_category_ids(), $category_ids);
$excludes[] = $product->get_id();
}
} else if (!WC()->cart->is_empty()) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
if ( $values['quantity'] > 0 ) {
// check category of products first
$pid = method_exists('get_parent_id', $values['data']) ? $values['data']->get_parent_id() : 0;
$pid = $pid ? $pid : $values['data']->get_id();
// get up/cross sell for category/tag in product
$data = c4d_woo_bs_get_data($pid, 'category');
if (isset($data[$type]) && $data[$type] !== '') {
$category_slugs = array_merge(array_map('trim', explode(',', $data[$type])), $category_slugs);
}
// if product is not set category/tag for up/cross sell, then check the product's categories
if (count($category_slugs) < 1) {
// get product has sampe product's category for cross/up sell
$product = wc_get_product($pid);
$category_ids = array_merge($product->get_category_ids(), $category_ids);
$excludes[] = $product->get_id();
}
}
}
} else {
$order = wc_get_order($orderId);
if ($order) {
$items = $order->get_items();
$ids = array();
foreach ($items as $key => $item) {
$product = $item->get_product();
if ($product) {
$pid = $product->get_parent_id();
$pid = $pid ? $pid : $product->get_id();
$data = c4d_woo_bs_get_data($pid, 'category');
if (isset($data[$type]) && $data[$type] !== '') {
$category_slugs = array_merge(array_map('trim', explode(',', $data[$type])), $category_slugs);
}
if (count($category_slugs) < 1) {
$category_ids = array_merge($product->get_category_ids(), $category_ids);
$excludes[] = $product->get_id();
}
}
}
}
}
// get up/cross sell for category/tag when create category/tag
if (count($category_ids) > 0) {
$c4d_plugin_manager['c4d_woo_bs_category_tag_one_time'] = true;
foreach($category_ids as $id) {
$category_is_set = get_term_meta( $id, $type, true );
if ($category_is_set) {
$category_slugs = array_merge(array_map('trim', explode(',', $category_is_set)), $category_slugs);
$c4d_plugin_manager['c4d_woo_bs_category_tag_one_time'] = false;
}
}
}
$args = array(
'exclude' => $excludes,
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => $type == 'upsell' ? $c4d_plugin_manager['c4d-woo-bs-up-limit'] : $c4d_plugin_manager['c4d-woo-bs-cross-limit'],
);
if (count($category_slugs) > 0) {
$args['category'] = $category_slugs;
} else if (count($category_ids) > 0) {
$args['tax_query'] = array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $category_ids,
'operator' => 'IN',
)
);
}
if (count($category_slugs) > 0 || count($category_ids) > 0 ) {
$products = wc_get_products($args);
}
return $products;
}
function c4d_woo_bs_get_product_from_tags($orderId = null, $type = 'upsell'){
global $c4d_plugin_manager, $product;
$products = array();
$tag_ids = array();
$tag_slugs = array();
$excludes = array();
if (is_product()) {
$pid = method_exists('get_parent_id', $product) ? $product->get_parent_id() : 0;
$pid = $pid ? $pid : $product->get_id();
$data = c4d_woo_bs_get_data($pid, 'tags');
if (isset($data[$type]) && $data[$type] !== '') {
$tag_slugs = array_merge(array_map('trim', explode(',', $data[$type])), $tag_slugs);
}
if (count($tag_slugs) < 1) {
$product = wc_get_product($pid);
if ($product) {
$tag_ids = array_merge($product->get_tag_ids(), $tag_ids);
$excludes[] = $product->get_id();
}
}
} else if (!WC()->cart->is_empty()) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
if ( $values['quantity'] > 0 ) {
$pid = method_exists('get_parent_id', $values['data']) ? $values['data']->get_parent_id() : 0;
$pid = $pid ? $pid : $values['data']->get_id();
$data = c4d_woo_bs_get_data($pid, 'tags');
if (isset($data[$type]) && $data[$type] !== '') {
$tag_slugs = array_merge(array_map('trim', explode(',', $data[$type])), $tag_slugs);
}
if (count($tag_slugs) < 1) {
$product = wc_get_product($pid);
if ($product) {
$tag_ids = array_merge($product->get_tag_ids(), $tag_ids);
$excludes[] = $product->get_id();
}
}
}
}
} else {
$order = wc_get_order($orderId);
if ($order) {
$items = $order->get_items();
$ids = array();
foreach ($items as $key => $item) {
$product = $item->get_product();
if ($product) {
$pid = $product->get_parent_id();
$pid = $pid ? $pid : $product->get_id();
$data = c4d_woo_bs_get_data($pid, 'tags');
if (isset($data[$type]) && $data[$type] !== '') {
$tag_slugs = array_merge(array_map('trim', explode(',', $data[$type])), $tag_slugs);
}
if (count($tag_slugs) < 1) {
$tag_ids = array_merge($product->get_tag_ids(), $tag_ids);
$excludes[] = $product->get_id();
}
}
}
}
}
// get up/cross sell for category/tag when create tag
if (count($tag_ids) > 0) {
$c4d_plugin_manager['c4d_woo_bs_category_tag_one_time'] = true;
foreach($tag_ids as $id) {
$tag_is_set = get_term_meta( $id, $type, true );
if ($tag_is_set) {
$tag_slugs = array_merge(array_map('trim', explode(',', $tag_is_set)), $tag_slugs);
$c4d_plugin_manager['c4d_woo_bs_category_tag_one_time'] = false;
}
}
}
$args = array(
'exclude' => $excludes,
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => $type == 'upsell' ? $c4d_plugin_manager['c4d-woo-bs-up-limit'] : $c4d_plugin_manager['c4d-woo-bs-cross-limit'],
);
if (count($tag_slugs) > 0) {
$args['tag'] = $tag_slugs;
} else if (count($tag_ids) > 0) {
$args['tax_query'] = array(
array(
'taxonomy' => 'product_tag',
'field' => 'id',
'terms' => $tag_ids,
'operator' => 'IN',
)
);
}
if (count($tag_slugs) > 0 || count($tag_ids)) {
$products = wc_get_products($args);
}
return $products;
}
function c4d_woo_bs_cross_get_srouces($orderId) {
global $c4d_plugin_manager, $product;
$ids = array();
$products = array();
// product setting , up sell, cross sell,
if (is_product()) {
$ids = array_merge( $product->get_cross_sell_ids(), $ids );
} else if (!WC()->cart->is_empty()) {
$ids = WC()->cart->get_cross_sells();
} else {
$ids = c4d_woo_bs_get_product_from_order($orderId, 'crosssell');
}
if (count($ids) > 0) {
$products = array_filter( array_map( 'wc_get_product', $ids ), 'wc_products_array_filter_visible' );
}
if (count($ids) < 1) {
$products = c4d_woo_bs_get_product_from_category_tags($orderId, 'crosssell');
}
return $products;
}
function c4d_woo_bs_get_product_from_category_tags($orderId, $type = 'upsell') {
global $c4d_plugin_manager;
$products = array();
// if product does not set crosssell/upsell, then get from tags
if (isset($c4d_plugin_manager['c4d-woo-bs-global-source-tags']) && isset($c4d_plugin_manager['c4d-woo-bs-global-source-tags']) == 1) {
$ptags = c4d_woo_bs_get_product_from_tags($orderId, $type);
if (count($ptags) > 0) {
return $ptags;
}
}
// if product does not set crosssell/upsell, then get from category
if (isset($c4d_plugin_manager['c4d-woo-bs-global-source-category']) && isset($c4d_plugin_manager['c4d-woo-bs-global-source-category']) == 1) {
$pcategory = c4d_woo_bs_get_product_from_category($orderId, $type);
if (count($pcategory) > 0) {
return $pcategory;
}
}
return $products;
}
function c4d_woo_bs_up_get_srouces($orderId) {
global $c4d_plugin_manager, $product;
$ids = array();
$products = array();
$cart = WC()->cart;
if (is_product()) {
$ids = array_merge( $product->get_upsell_ids(), $ids );
} else if ( !$cart->is_empty() ) {
$in_cart = array();
foreach ( $cart->get_cart() as $cart_item_key => $values ) {
if ( $values['quantity'] > 0 ) {
$ids = array_merge( $values['data']->get_upsell_ids(), $ids );
$in_cart[] = $values['product_id'];
}
}
$ids = array_diff( $ids, $in_cart );
} else {
$ids = c4d_woo_bs_get_product_from_order($orderId, 'upsell');
}
if (count($ids) > 0) {
$products = array_filter( array_map( 'wc_get_product', $ids ), 'wc_products_array_filter_visible' );
}
if (count($ids) < 1) {
$products = c4d_woo_bs_get_product_from_category_tags($orderId, 'upsell');
}
return $products;
}
function c4d_woo_bs_get_up_sell_from_cart($products = array()) {
global $c4d_plugin_manager;
if (count($products) > 0 ){
$title = isset($c4d_plugin_manager['c4d-woo-bs-up-title']) && $c4d_plugin_manager['c4d-woo-bs-up-title'] != '' ? $c4d_plugin_manager['c4d-woo-bs-up-title'] : esc_html__('Up Sell', 'c4d-woo-bs');
if (isset($c4d_plugin_manager['c4d-woo-bs-up-hide-title']) && $c4d_plugin_manager['c4d-woo-bs-up-hide-title'] == 1) {
$title = '';
}
$desc = isset($c4d_plugin_manager['c4d-woo-bs-up-desc']) && $c4d_plugin_manager['c4d-woo-bs-up-desc'] != '' ? $c4d_plugin_manager['c4d-woo-bs-up-desc'] : '';
if (isset($c4d_plugin_manager['c4d-woo-bs-up-hide-desc']) && $c4d_plugin_manager['c4d-woo-bs-up-hide-desc'] == 1) {
$desc = '';
}
echo '<div class="c4d_woo_bs_up_sell"> NEEDS TOP BE FIRST ';
if ($title) {
echo '<h3 class="block_title">'.$title.'</h3>';
}
if ($desc) {
echo '<div class="block_desc">'.$desc.'</div>';
}
// default params
$limit = '-1'; $columns = 4; $orderby = 'rand'; $order = 'desc';
// Handle the legacy filter which controlled posts per page etc.
$args = apply_filters(
'woocommerce_upsell_display_args',
array(
'posts_per_page' => $limit,
'orderby' => $orderby,
'columns' => $columns,
)
);
wc_set_loop_prop( 'name', 'up-sells' );
wc_set_loop_prop( 'columns', apply_filters( 'woocommerce_upsells_columns', isset( $args['columns'] ) ? $args['columns'] : $columns ) );
$orderby = apply_filters( 'woocommerce_upsells_orderby', isset( $args['orderby'] ) ? $args['orderby'] : $orderby );
$limit = apply_filters( 'woocommerce_upsells_total', isset( $args['posts_per_page'] ) ? $args['posts_per_page'] : $limit );
// Get visible upsells then sort them, then limit result set.
$products = wc_products_array_orderby( $products, $orderby, $order );
$products = $limit > 0 ? array_slice( $products, 0, $limit ) : $products;
wc_get_template(
'single-product/up-sells.php',
array(
'upsells' => $products,
// Not used now, but used in previous version of up-sells.php.
'posts_per_page' => $limit,
'orderby' => $orderby,
'columns' => $columns,
)
);
echo '</div>';
}
}
function c4d_woo_bs_get_cross_sell($products = array()) {
global $c4d_plugin_manager;
if (count($products) > 0) {
$title = isset($c4d_plugin_manager['c4d-woo-bs-cross-title']) && $c4d_plugin_manager['c4d-woo-bs-cross-title'] != '' ? $c4d_plugin_manager['c4d-woo-bs-cross-title'] : esc_html__('Cross Sell', 'c4d-woo-bs');
if (isset($c4d_plugin_manager['c4d-woo-bs-cross-hide-title']) && $c4d_plugin_manager['c4d-woo-bs-cross-hide-title'] == 1) {
$title = '';
}
$desc = isset($c4d_plugin_manager['c4d-woo-bs-cross-desc']) ? $c4d_plugin_manager['c4d-woo-bs-cross-desc'] : '';
if (isset($c4d_plugin_manager['c4d-woo-bs-cross-hide-desc']) && $c4d_plugin_manager['c4d-woo-bs-cross-hide-desc'] == 1) {
$desc = '';
}
echo '<div class="c4d_woo_bs_cross_sell"> NEEDS TOP BE LAST';
if ($title) {
echo '<h3 class="block_title">'.$title.'</h3>';
}
if ($desc) {
echo '<div class="block_desc">'.$desc.'</div>';
}
// Get visible cross sells then sort them at random.
$limit = -1 /*4*/; $columns = 4; $orderby = 'rand'; $order = 'desc';
wc_set_loop_prop( 'name', 'cross-sells' );
wc_set_loop_prop( 'columns', apply_filters( 'woocommerce_cross_sells_columns', $columns ) );
// Handle orderby and limit results.
$orderby = apply_filters( 'woocommerce_cross_sells_orderby', $orderby );
$order = apply_filters( 'woocommerce_cross_sells_order', $order );
$products = wc_products_array_orderby( $products, $orderby, $order );
$limit = apply_filters( 'woocommerce_cross_sells_total', $limit );
$products = $limit > 0 ? array_slice( $products, 0, $limit ) : $products;
wc_get_template(
'cart/cross-sells.php',
array(
'cross_sells' => $products,
// Not used now, but used in previous version of up-sells.php.
'posts_per_page' => $limit,
'orderby' => $orderby,
'columns' => $columns,
)
);
echo '</div>';
}
}
I have tried to getting contact with the author of the plugin but no luck, they do not respond to emails, contact forms, support requests at all.
ok as no one had an answer for me, I got one its not perfect but at least it works
/*Change order around on product page for related and cross-sell*/
.c4d_woo_bs_wrap {// this is the main div
display: flex;
flex-direction: column;
}
.c4d_woo_bs_wrap > .c4d_woo_bs_cross_sell {order: 2; } /* Will be displayed second */
.c4d_woo_bs_wrape > .cross-sells {order: 1; } /* Will be displayed first */

script that denies access to an ip after they have filled a form on my site

I have an existing php script written which checks if an ip has been written to a .dat, and redirects the user to in this case google if the ip is in the file. If not, it lets them continue on with signing up to my site.
The code below checks if the control is switched on. I placed it in the index.php
if($One_time_access==1)
{
$fp = fopen("blacklist.dat", "a");
fputs($fp, "\r\n$ip\r\n");
fclose($fp);
}
Then the code below does all the work to figure out the ip, what to ban, etc
<?php
class IpList {
private $iplist = array();
private $ipfile = "";
public function __construct( $list ) {
$contents = array();
$this->ipfile = $list;
$lines = $this->read( $list );
foreach( $lines as $line ) {
$line = trim( $line );
# remove comment and blank lines
if ( empty($line ) ) {
continue;
}
if ( $line[0] == '#' ) {
continue;
}
# remove on line comments
$temp = explode( "#", $line );
$line = trim( $temp[0] );
# create content array
$contents[] = $this->normal($line);
}
$this->iplist = $contents;
}
public function __destruct() {
}
public function __toString() {
return implode(' ',$this->iplist);
}
public function is_inlist( $ip ) {
$retval = false;
foreach( $this->iplist as $ipf ) {
$retval = $this->ip_in_range( $ip, $ipf );
if ($retval === true ) {
$this->range = $ipf;
break;
}
}
return $retval;
}
/*
** public function that returns the ip list array
*/
public function iplist() {
return $this->iplist;
}
/*
*/
public function message() {
return $this->range;
}
public function append( $ip, $comment ) {
return file_put_contents( $this->ipfile, $ip, $comment );
}
public function listname() {
return $this->ipfile;
}
/*
** private function that reads the file into array
*/
private function read( $fname ) {
try {
$file = file( $fname, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
}
catch( Exception $e ) {
throw new Exception( $fname.': '.$e->getmessage() . '\n');
}
return $file;
}
private function ip_in_range( $ip, $range ) {
// return ip_in_range( $ip, $range );
if ( strpos($range, '/') !== false ) {
// IP/NETMASK format
list( $range, $netmask ) = explode( '/', $range, 2 );
if ( strpos( $netmask, '.' ) !== false ) {
// 255.255.255.0 format w/ wildcards
$netmask = str_replace('*', '0', $netmask );
$dnetmask = ip2long( $netmask );
return ((ip2long( $ip ) & $dnetmask) == (ip2long($range) & $dnetmask ));
}
else {
// IP/CIDR format
// insure $range format 0.0.0.0
$r = explode( '.', $range );
while( count( $r ) < 4 ) {
$r[] = '0';
}
for($i = 0; $i < 4; $i++) {
$r[$i] = empty($r[$i]) ? '0': $r[$i];
}
$range = implode( '.', $r );
// build netmask
$dnetmask = ~(pow( 2, ( 32 - $netmask)) - 1);
return ((ip2long($ip) & $dnetmask)==(ip2long($range) & $dnetmask));
}
}
else {
if ( strpos( $range, '*' ) !== false ) {
// 255.255.*.* format
$low = str_replace( '*', '0', $range );
$high = str_replace( '*', '255', $range );
$range = $low.'-'.$high;
}
if ( strpos( $range, '-') !== false ) {
// 128.255.255.0-128.255.255.255 format
list( $low, $high ) = explode( '-', $range, 2 );
$dlow = $this->toLongs( $low );
$dhigh = $this->toLongs( $high );
$dip = $this->toLongs( $ip );
return (($this->compare($dip,$dlow) != -1) && ($this->compare($dip,$dhigh) != 1));
}
}
return ( $ip == $range );
}
private function normal( $range ) {
if ( strpbrk( "*-/", $range ) === False ) {
$range .= "/32";
}
return str_replace( ' ', '', $range );
}
private function toLongs( $ip ) {
# $Ip = $this->expand();
# $Parts = explode(':', $Ip);
$Parts = explode('.', $ip );
$Ip = array('', '');
# for ($i = 0; $i < 4; $i++) {
for ($i = 0; $i < 2; $i++){
$Ip[0] .= str_pad(base_convert($Parts[$i], 16, 2), 16, 0, STR_PAD_LEFT);
}
# for ($i = 4; $i < 8; $i++) {
for ($i = 2; $i < 4; $i++) {
$Ip[1] .= str_pad(base_convert($Parts[$i], 16, 2), 16, 0, STR_PAD_LEFT);
}
return array(base_convert($Ip[0], 2, 10), base_convert($Ip[1], 2, 10));
}
private function compare( $ipdec1, $ipdec2 ) {
if( $ipdec1[0] < $ipdec2[0] ) {
return -1;
}
elseif ( $ipdec1[0] > $ipdec2[0] ) {
return 1;
}
elseif ( $ipdec1[1] < $ipdec2[1] ) {
return -1;
}
elseif ( $ipdec1[1] > $ipdec2[1] ) {
return 1;
}
return 0;
}
}
class IpBlockList {
private $statusid = array( 'negative' => -1, 'neutral' => 0, 'positive' => 1 );
private $whitelist = array();
private $blacklist = array();
private $message = NULL;
private $status = NULL;
public function __construct(
$whitelistfile = 'assets/includes/whitelist.dat',
$blacklistfile = 'assets/includes/blacklist.dat' ) {
$this->whitelistfile = $whitelistfile;
$this->blacklistfile = $blacklistfile;
$this->whitelist = new IpList( $whitelistfile );
$this->blacklist = new IpList( $blacklistfile );
}
public function __destruct() {
}
public function ipPass( $ip ) {
$retval = False;
if ( !filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
throw new Exception( 'Requires valid IPv4 address' );
}
if ( $this->whitelist->is_inlist( $ip ) ) {
// Ip is white listed, so it passes
$retval = True;
$this->message = $ip . " is whitelisted by ".$this->whitelist->message().".";
$this->status = $this->statusid['positive'];
}
else if ( $this->blacklist->is_inlist( $ip ) ) {
$retval = False;
$this->message = $ip . " is blacklisted by ".$this->blacklist->message().".";
$this->status = $this->statusid['negative'];
}
else {
$retval = True;
$this->message = $ip . " is unlisted.";
$this->status = $this->statusid['neutral'];
}
return $retval;
}
public function message() {
return $this->message;
}
public function status() {
return $this->status;
}
public function append( $type, $ip, $comment = "" ) {
if ($type == 'WHITELIST' ) {
$retval = $this->whitelistfile->append( $ip, $comment );
}
elseif( $type == 'BLACKLIST' ) {
$retval = $this->blacklistfile->append( $ip, $comment );
}
else {
$retval = false;
}
}
public function filename( $type, $ip, $comment = "" ) {
if ($type == 'WHITELIST' ) {
$retval = $this->whitelistfile->filename( $ip, $comment );
}
elseif( $type == 'BLACKLIST' ) {
$retval = $this->blacklistfile->filename( $ip, $comment );
}
else {
$retval = false;
}
}
}
$ips = array( $_SERVER['REMOTE_ADDR'],
);
$checklist = new IpBlockList( );
foreach ($ips as $ip ) {
$result = $checklist->ipPass( $ip );
if ( $result ) {
// Continue with page
}
else {
header("Location: https://www.google.co.uk/");
die();
}
}
?>
I want to know:
1. can i write the ips to a text file instead of .dat?
2. is there an easier way to do this?/shorter script?
All help will be appreciated :)

Class & Object Scope for Variable Variables in PHP

Question 1) Why is the Variable/variable $this->$template not visible to parse_and_return(), lines 42-50, but visible to $this->fetch, lines 456-472. I thought parse_and_return and $this->fetch belong to the same object, therefore $this->$template should be visible to both functions.
Question 2) Where is $this->$template initialized?
bar.tpl & foo.tpl are separate files
<!-- bar.tpl -->
<HTML>
<HEAD><TITLE>Feature world - {PAGETITLE}</TITLE></HEAD>
<BODY BGCOLOR=BLACK TEXT=WHITE>
<H1>{PAGETITLE}</H1>
{PAGECONTENT}
</BODY>
</HTML>
-->
<!--
foo.tpl
This does not do anything obvious. Please look at {NAME}.
demo.php3
-->
index.php file
<?php
include "FastTemplate.php";
$tpl = new FastTemplate(".");
$tpl->define(array(foo => "foo.tpl", bar => "bar.tpl"));
$tpl->assign(NAME, "me");
$tpl->assign(PAGETITLE, "Welcome!");
$tpl->parse(PAGECONTENT, "foo");
echo $tpl->parse_and_return("bar");
?>
The FastTemplate Class / FastTemplate.php file
<?php
class FastTemplate {
var $start;
var $ERROR = "";
var $LAST = "";
var $ROOT = "";
var $FILELIST = array ( );
var $PARSEVARS = array ( );
var $LOADED = array ( );
var $HANDLE = array ( );
var $UPDT_TIME = '60';
var $COMMENTS_START = "{*";
var $COMMENTS_END = "*}";
var $PATTERN_VARS_VARIABLE = array ( );
var $PATTERN_VARS_DEFINE = array ( );
FUNCTION FastTemplate($pathToTemplates = "") {
if (! empty ( $pathToTemplates )) {
$this->set_root ( $pathToTemplates );
}
$this->start = $this->utime ();
}
FUNCTION parse_and_return($tpl_name) {
$HREF = 'TPL';
$this->parse ( $HREF, $tpl_name );
$result = trim ( $this->fetch ( $HREF ) );
$this->clear_href ( $HREF );
RETURN $result;
}
FUNCTION set_root($root) {
$trailer = substr ( $root, - 1 );
if ((ord ( $trailer )) != 47) {
$root = "$root" . chr ( 47 );
}
if (is_dir ( $root )) {
$this->ROOT = $root;
} else {
$this->ROOT = "";
$this->error ( "dir [$root] is not a directory" );
}
}
FUNCTION get_root() {
RETURN $this->ROOT;
}
FUNCTION utime() {
$time = explode ( " ", microtime () );
$usec = ( double ) $time [0];
$sec = ( double ) $time [1];
RETURN $sec + $usec;
}
FUNCTION get_template($template) {
if (empty ( $this->ROOT )) {
$this->error ( "Root not valid.", 1 );
RETURN FALSE;
}
if (empty ( $template )) {
$this->error ( "Template name is empty.", 1 );
RETURN FALSE;
};
$filename = "$this->ROOT" . "$template";
$contents = ((function_exists ( 'file_get_contents' ))) ? file_get_contents ( $filename ) : implode ( "\n", file ( $filename ) );
RETURN trim ( $contents );
}
FUNCTION parseParamString($string) {
$matches=array();
if (preg_match_all ( '/\{([a-z0-9_]+)\}/i', $string, $matches )) {
FOR($i = 0; $i < count ( $matches [0] ); $i ++) {
$string = str_replace ( $matches [0] [$i], $this->PARSEVARS [$matches [1] [$i]], $string );
}
}
RETURN $string;
}
FUNCTION value_defined($value, $field = '', $params = '') {
$var = $this->PARSEVARS [$value];
if ($field {0} == '.') {
$field = substr ( $field, 1 );
}
# echo "$value, $field, $params <BR>";
if (is_object ( $var )) {
if (method_exists ( $var, $field )) {
eval ( '$return = $var->' . $field . '(' . $this->parseParamString ( $params ) . ');' );
RETURN ((! empty ( $return )) || ($return === TRUE));
} ELSEif ((strcasecmp ( $field, 'id' ) != 0) && method_exists ( $var, 'get' )) {
$result = $var->get ( $field );
RETURN (! empty ( $result ) || $result === TRUE);
} ELSEif ((strcasecmp ( $field, 'id' ) == 0) && method_exists ( $var, 'getId' )) {
$result = $var->getId ();
RETURN (! empty ( $result ) || $result === TRUE);
}
} else {
RETURN (! empty ( $var ) || $var === TRUE);
}
}
FUNCTION parse_defined($template) {
$lines = split ( "\n", $template );
$newTemplate = "";
$ifdefs = FALSE;
$depth = 0;
$needparsedef [$depth] ["defs"] = FALSE;
$needparsedef [$depth] ["parse"] = TRUE;
WHILE ( list ( $num, $line ) = each ( $lines ) ) {
if (((! $needparsedef [$depth] ["defs"]) || ($needparsedef [$depth] ["parse"])) && (strpos ( $line, "IFDEF:" ) === FALSE) && (strpos ( $line, "IFNDEF:" ) === FALSE) && (strpos ( $line, "ELSE" ) === FALSE) && (strpos ( $line, "ENDIF" ) === FALSE)) {
$newTemplate .= trim ( $line ) . "\n";
}
if (preg_match ( "/<!--\s*IFDEF:\s*([a-zA-Z_][a-zA-Z0-9_]+)(\.|\-\>)?([a-zA-Z_][a-zA-Z0-9_]+)?\(?(\s*\,?\".*\"\s*\,?|\s*\,?[a-z0-9\_]*\s*\,?)\)?\s*-->/i", $line, $regs )) {
$depth ++;
$needparsedef [$depth] ["defs"] = TRUE;
if ($this->value_defined ( $regs [1], $regs [3], $regs [4] )){
$needparsedef [$depth] ["parse"] = $needparsedef [$depth - 1] ["parse"];
}else{
$needparsedef [$depth] ["parse"] = FALSE;
}
}
if (preg_match ( "/<!--\s*IFNDEF:\s*([a-zA-Z_][a-zA-Z0-9_]+)(\.|\-\>)?([a-zA-Z_][a-zA-Z0-9_]+)?\(?(\s*\,?\".*\"\s*\,?|\s*\,?[a-z0-9\_]*\s*\,?)\)?\s*-->/i", $line, $regs )) {
$depth ++;
$needparsedef [$depth] ["defs"] = TRUE;
}
if (! $this->value_defined ( $regs [1], $regs [3], $regs [4] )){
$needparsedef [$depth] ["parse"] = $needparsedef [$depth - 1] ["parse"];
}else{
$needparsedef [$depth] ["parse"] = FALSE;}
}
// ELSE block
if (preg_match ( "/<!--\s*ELSE\s*-->/i", $line )) {
if ($needparsedef [$depth] ["defs"]){
$needparsedef [$depth] ["parse"] = (! ($needparsedef [$depth] ["parse"]) & $needparsedef [$depth - 1] ["parse"]);
}
if (preg_match ( "/<!--\s*ENDIF\s*-->/i", $line )) {
$needparsedef [$depth] ["defs"] = FALSE;
$depth --;
}
}
if ($depth){
$this->error ( 'Some nonclosed IDEFS blocks', 0 );
}
RETURN $newTemplate;
}
FUNCTION parse_template($template, $ft_array) {
$matches=array();
if (preg_match_all ( '/\{([a-zA-Z_][a-zA-Z0-9_]+)(\.|\-\>)([a-zA-Z_][a-zA-Z0-9_]+)\(?(\s*\,?\".*?\"\s*\,?|\s*\,?[a-z0-9\_]*\s*\,?)\)?\}/i', $template, $matches )) {
FOR($i = 0; $i < count ( $matches [0] ); ++ $i) {
$obj = $ft_array [$matches [1] [$i]];
if ((is_object ( $obj ) && method_exists ( $obj, $matches [3] [$i] ))) {
eval ( '$return = $obj->' . $matches [3] [$i] . '(' . $this->parseParamString ( $matches [4] [$i] ) . ');' );
$template = str_replace ( $matches [0] [$i], $return, $template );
} else if (is_object ( $obj ) && ($matches [3] [$i] == 'id') && method_exists ( $obj, 'getId' )){
$template = str_replace ( $matches [0] [$i], $obj->getId (), $template );
}else if (is_object ( $obj ) && method_exists ( $obj, 'get' )){
$template = str_replace ( $matches [0] [$i], $obj->get ( $matches [3] [$i] ), $template ); }else if (! is_object ( $obj )){
$template = str_replace ( $matches [0] [$i], '', $template );
}
} //end for loop
} //end if
if (preg_match_all ( '/<\!\-\-\s*#include\s+file="([\{\}a-zA-Z0-9_\.\-\/]+)"\s*\\-\->/i', $template, $matches )) {
FOR($i = 0; $i < count ( $matches [0] ); $i ++) {
$file_path = $matches [1] [$i];
FOREACH ( $ft_array as $key => $value ) {
if (! empty ( $key )) {
$key = '{' . "$key" . '}';
$file_path = str_replace ( "$key", "$value", "$file_path" );
}
} //foreach
$content = '';
if (! isset ( $ft_array [$file_path] )) {
if (! file_exists ( $file_path )){
$file_path = $this->ROOT . $file_path;
}
if (! file_exists ( $file_path )){
$file_path = $this->ROOT . basename ( $file_path );
}
if (file_exists ( $file_path )) {
$content = ((function_exists ( 'file_get_contents' ))) ? file_get_contents ( $file_path ) : implode ( "\n", file ( $file_path ) );
} else {
$content = '';
}
} else {
$content = $ft_array [$file_path];
$template = str_replace ( $matches [0] [$i], $content, $template );
}
} //for
} //end preg_match_all
reset ( $ft_array );
WHILE ( list ( $key, $val ) = each ( $ft_array ) ) {
if (! (empty ( $key ))) {
if (gettype ( $val ) != "string") {
settype ( $val, "string" );
}
$key = '{' . "$key" . '}';
$template = str_replace ( "$key", "$val", "$template" );
}
}
$template = ereg_replace ( "{([A-Za-z0-9_\.]+)}", "", $template );
$template = preg_replace ( "/(<!--\s*IFDEF:\s*([a-zA-Z_][a-zA-Z0-9_]+)(\.|\-\>)?([a-zA-Z_][a-zA-Z0-9_]+)?\(?(\s*\,?\".*?\"\s*\,?|\s*\,?[a-z0-9\_]*\s*\,?)\)?\s*-->)/i", "\n$0\n", $template );
$template = preg_replace ( "/(<!--\s*IFNDEF:\s*([a-zA-Z_][a-zA-Z0-9_]+)(\.|\-\>)?([a-zA-Z_][a-zA-Z0-9_]+)?\(?(\s*\,?\".*?\"\s*\,?|\s*\,?[a-z0-9\_]*\s*\,?)\)?\s*-->)/i", "\n$0\n", $template );
$template = preg_replace ( "/(<!--\s*ELSE\s*-->)/i", "\n\\0\n", $template );
$template = preg_replace ( "/(<!--\s*ENDIF\s*-->)/i", "\n\\0\n", $template );
WHILE ( list ( $num, $line ) = each ( $lines ) ) {
if (! $inside_block) {
$template .= "$line\n";
}
}
$template = $this->parse_defined ( $template );
RETURN $template;
}
FUNCTION parse($ReturnVar, $FileTags) {
FOREACH ( $this->PATTERN_VARS_DEFINE as $value ){
$this->multiple_assign_define ( "$value" );
}
FOREACH ( $this->PATTERN_VARS_VARIABLE as $value ){
$this->multiple_assign ( "$value" );
}
$append = FALSE;
$this->LAST = $ReturnVar;
$this->HANDLE [$ReturnVar] = 1;
if (gettype ( $FileTags ) == "array") {
unset ( $this->$ReturnVar );
WHILE ( list ( $key, $val ) = each ( $FileTags ) ) {
if ((! isset ( $this->$val )) || (empty ( $this->$val ))) {
$this->LOADED ["$val"] = 1;
$fileName = $this->FILELIST ["$val"];
$this->$val = $this->get_template ( $fileName );
}
$this->$ReturnVar = $this->parse_template ( $this->$val, $this->PARSEVARS );
// For recursive calls.
$this->assign ( array ($ReturnVar => $this->$ReturnVar ) );
}
} else {
$val = $FileTags;
if ((substr ( $val, 0, 1 )) == '.') {
$append = TRUE;
$val = substr ( $val, 1 );
}
if ((! isset ( $this->$val )) || (empty ( $this->$val ))) {
$this->LOADED ["$val"] = 1;
$fileName = $this->FILELIST ["$val"];
$this->$val = $this->get_template ( $fileName );
}
if ($append) {
if (isset ( $this->$ReturnVar )) {
$this->$ReturnVar .= $this->parse_template ( $this->$val, $this->PARSEVARS );
} else {
$this->$ReturnVar = $this->parse_template ( $this->$val, $this->PARSEVARS );
}
} else {
$this->$ReturnVar = $this->parse_template ( $this->$val, $this->PARSEVARS );
}
$this->assign ( array ($ReturnVar => $this->$ReturnVar ) );
}
RETURN;
}
FUNCTION getfast($template = "") {
if (empty ( $template )) {
$template = $this->LAST;
}
// "$this->$template" not initialize here!
if ((! (isset ( $this->$template ))) || (empty ( $this->$template ))) {
$this->error ( "Nothing parsed, nothing printed", 0 );
RETURN;
} else {
if (! get_magic_quotes_gpc ()){
$this->$template = stripslashes ( $this->$template );
}
RETURN $this->$template;
}
}
FUNCTION fetch($template = "") {
if (empty ( $template )) {
$template = $this->LAST;
}
if ((! (isset ( $this->$template ))) || (empty ( $this->$template ))) {
$this->error ( "Nothing parsed, nothing printed", 0 );
RETURN "";
}
RETURN ($this->$template);
}
FUNCTION define($fileList, $value = null) {
if ((gettype ( $fileList ) != "array") && ! is_null ( $value )){
$fileList = array ($fileList => $value );
}
WHILE ( list ( $FileTag, $FileName ) = each ( $fileList ) ) {
$this->FILELIST ["$FileTag"] = $FileName;
}
RETURN TRUE;
}
FUNCTION clear_href($href) {
if (! empty ( $href )) {
if ((gettype ( $href )) != "array") {
unset ( $this->PARSEVARS [$href] );
RETURN;
} else {
FOREACH ( $href as $value ){
unset ( $this->PARSEVARS [$value] );
RETURN;
}
}
} else {
// Empty - clear them all
$this->clear_assign ();
}
RETURN;
}
FUNCTION clear_assign() {
if (! (empty ( $this->PARSEVARS ))) {
WHILE ( list ( $Ref, $Val ) = each ( $this->PARSEVARS ) ) {
unset ( $this->PARSEVARS ["$Ref"] );
}
}
}
FUNCTION assign_from_array($Arr, $Keys) {
if (gettype ( $Arr ) == "array") {
foreach ( $Keys as $k ){
if (! empty ( $k )){
$this->PARSEVARS [strtoupper ( $k )] = str_replace ( '&#', '&#', $Arr [$k] );
}
}
}
}
FUNCTION assign($ft_array, $trailer = "") {
if (gettype ( $ft_array ) == "array") {
WHILE ( list ( $key, $val ) = each ( $ft_array ) ) {
if (! (empty ( $key ))) {
if (! is_object ( $val )){
$this->PARSEVARS ["$key"] = str_replace ( '&#', '&#', $val );
} else{
$this->PARSEVARS ["$key"] = $val;
}
}
}
} else {
if (! empty ( $ft_array )) {
if (! is_object ( $trailer )){
$this->PARSEVARS ["$ft_array"] = str_replace ( '&#', '&#', $trailer );
}else{
$this->PARSEVARS ["$ft_array"] = $trailer;
}
}
}
}
FUNCTION get_assigned($ft_name = "") {
if (empty ( $ft_name )) {
RETURN FALSE;
}
if (isset ( $this->PARSEVARS ["$ft_name"] )) {
RETURN ($this->PARSEVARS ["$ft_name"]);
} else {
RETURN FALSE;
}
}
FUNCTION error($errorMsg, $die = 0) {
$this->ERROR = $errorMsg;
echo "ERROR: $this->ERROR <BR> \n";
if ($die == 1) {
exit ();
}
RETURN;
}
FUNCTION multiple_assign($pattern) {
WHILE ( list ( $key, $value ) = each ( $GLOBALS ) ) {
if (substr ( $key, 0, strlen ( $pattern ) ) == $pattern) {
$this->assign ( strtoupper ( $key ), $value );
}
}
reset ( $GLOBALS );
}
FUNCTION multiple_assign_define($pattern) {
$ar = get_defined_constants ();
FOREACH ( $ar as $key => $def ){
if (substr ( $key, 0, strlen ( $pattern ) ) == $pattern){
$this->assign ( strtoupper ( $key ), $def );
}
}
}
} // End Class
?>
Answer to my first question:
There are two reasons why the variable “$this->$template” is not visible to the parse_and_return();
Reason 1: The “$this->$template” variable points to an instance variable $TPL of the FastTemplate class that does not exist until parse() is called. The parse() function parses the bar.tpl file and resolves this file's FastTemplate {VARS}. An instance variable $TPL is created in a FastTemplate object and assigned the bar.tpl file’s contents. The $TPL variable will not be visible to any member function until it is created.
Reason 2: $template is a local variable and $this->$template is a local variable variable; local only to the fetch() function. Because the scope of these variables are local they will generate and error if you try to use them in other member functions. However, once the $TPL instance variable is created you can access its data value from any member function by simply using $this->TPL.
Answer to my second question:
As stated above, “$this->$template” is a local variable variable and refers to the instance variable $TPL that is initialized with the value of the bar.tpl file’s contents. This $TPL variable is initialized near or on lines 382-388, inside the parse() function. The following expression was used to initialize $TPL: “$this->$ReturnVar = $this->parse_template ($this->$val, $this->PARSEVARS )”.
The $ReturnVar variable was the first parameter in parse() function's definition, e.g. FUNCTION parse($ReturnVar, $FileTags). The $ReturnVar variable was passed an argument with a string value of “TPL”. You can now use a variable variable to access a variable’s address, in this case the address of the string “TPL” by using $$ReturnVar. Because “TPL” is an instance variable of a FastTemplate object you must use the pseudo variable “$this->” to access it. Therefore the variable variable is structured as $this->$ReturnVar. This will create the $TPL variable and access its address and assign the address the contents of the bar.tpl file.
Coincidentally in this this example the object is named $tpl but any name could have been used.
Closing comment - It will be my objective to simplify this code by excluding all the variable variables and using a more direct coding approach. It is my opinion that the over use of variable variables (pointers) makes your code convoluted and hard to follow.

index.php returning a blank web page on openshift host

I have a website I am trying to maintain for a project:
http://uomtwittersearch-jbon0041.rhcloud.com/
The user connects to Twitter through the application and authenticates by using the twitteroauth library (by abraham). The process works fine up until it lands on index.php (calling index.inc as the respective HTML page) where it gives me a blank page. On localhost it works perfectly fine so I am not sure what could be causing this. Other pages such as connect.php initialize as required.
Visiting the website as it is will give an error and I am assuming that is because it cannot find index.php directly and it lies in the folder twitteroauth-master. I will fix this when I manage to at least make the contents of index.php appear but for now I am visiting:
http://uomtwittersearch-jbon0041.rhcloud.com/twitteroauth-master/connect.php
first, and this also goes to anyone who would like to visit it. If you have twitter log on with your details, this will move you to index.php which will be blank. Other than that one can simply replace 'connect' with 'index'.
What could be causing the blank page for index.php?
This is only my first ever web development project so I am not sure if this is something obvious. Moreover, I am using OpenShift for hosting.
EDIT --------------------
This is my index.php script. Again the script works fine without any problems on localhost.
<?php
//session_save_path(home/users/web/b2940/ipg.uomtwittersearchnet/cgi-bin/tmp);
ini_set('display_errors',1);
error_reporting(E_ALL);
session_start ();
require_once ('twitteroauth/twitteroauth.php');
require_once ('config.php');
include ('nlp/stop_words.php');
include ('nlp/acronyms.php');
set_time_limit ( 300 );
//////////////////////// TWITTEROAUTH /////////////////////////////////////
/* If access tokens are not available redirect to connect page. */
if (empty ( $_SESSION ['access_token'] ) || empty ( $_SESSION ['access_token'] ['oauth_token'] ) || empty ( $_SESSION ['access_token'] ['oauth_token_secret'] )) {
header ( 'Location: ./clearsessions.php' );
}
/* Get user access tokens out of the session. */
$access_token = $_SESSION ['access_token'];
/* Create a TwitterOauth object with consumer/user tokens. */
$connection = new TwitterOAuth ( CONSUMER_KEY, CONSUMER_SECRET, $access_token ['oauth_token'], $access_token ['oauth_token_secret'] );
///////////////////////////////////////////////////////////////////////////
///// UNCOMMENT BELOW TO AUTOMATICALLY SPECIFY CURRENTLY LOGGED IN USER
//$user = $connection->get('account/verify_credentials');
//$user_handle = $user->screen_name;
$user_handle = 'AngeloDalli';
$timeline = getContent ( $connection, $user_handle, 1 );
$latest_id = $timeline [0]->id_str;
$most_recent = getMostRecentTweet ();
if ($latest_id > $most_recent) {
$t_start = microtime(true); // start indexing
$timeline = getContent ( $connection, $user_handle, 200 );
$json_index = decodeIndex ();
$json_index = updateIndex ( $timeline, $connection, $user_handle, $json_index, $most_recent );
$json_index = sortIndex ( $json_index );
$json = encodeIndex ( $json_index );
updateMostRecentTweet ( $latest_id );
$_SESSION ['index_size'] = countIndex ( $json_index );
$t_end = microtime(true); // finish indexing
$content = 'New tweets indexed! Number of tweets in index: ' . $_SESSION ['index_size'];
// total indexing time
$time = 'Total time of indexing: ' . ($t_end - $t_start)/60 . ' seconds';
} else {
$content = 'No new tweets indexed!';
$time = '';
}
/////////////////////// FUNCTIONS //////////////////////////////////////////////
function getContent($connection, $user_handle, $n) {
$content = $connection->get ( 'statuses/user_timeline', array (
'screen_name' => $user_handle,
'count' => $n
) );
return $content;
}
function decodeIndex() {
$string = file_get_contents ( INDEX_PATH );
if ($string) {
$json_index = json_decode ( $string, true );
} else {
$json_index = [ ];
}
return $json_index;
}
function updateIndex($timeline, $connection, $user_handle, $json_index, $most_recent) {
// URL arrays for uClassify API calls
$urls = [ ];
$urls_id = [ ];
// halt if no more new tweets are found
$halt = false;
// set to 1 to skip first tweet after 1st batch
$j = 0;
// count number of new tweets indexed
$count = 0;
while ( (count ( $timeline ) != 1 || $j == 0) && $halt == false ) {
$no_of_tweets_in_batch = 0;
$n = $j;
while ( ($n < count ( $timeline )) && $halt == false ) {
$tweet_id = $timeline [$n]->id_str;
if ($tweet_id > $most_recent) {
$text = $timeline [$n]->text;
$tokens = parseTweet ( $text );
$coord = extractLocation ( $timeline, $n );
addSentimentURL ( $text, $tweet_id, $urls, $urls_id );
$keywords = makeEntry ( $tokens, $tweet_id, $coord, $text );
foreach ( $keywords as $type ) {
$json_index [] = $type;
}
$n ++;
$no_of_tweets_in_batch ++;
} else {
$halt = true;
}
}
if ($halt == false) {
$tweet_id = $timeline [$n - 1]->id_str;
$timeline = $connection->get ( 'statuses/user_timeline', array (
'screen_name' => $user_handle,
'count' => 200,
'max_id' => $tweet_id
) );
// skip 1st tweet after 1st batch
$j = 1;
}
$count += $no_of_tweets_in_batch;
}
$json_index = extractSentiments ( $urls, $urls_id, $json_index );
echo 'Number of tweets indexed: ' . ($count);
return $json_index;
}
function parseTweet($tweet) {
// find urls in tweet and remove (HTTP ONLY CURRENTLY)
$tweet = preg_replace ( '/(http:\/\/[^\s]+)/', "", $tweet );
// split tweet into tokens and clean
$words = preg_split ( "/[^A-Za-z0-9]+/", $tweet );
// /[\s,:.##?!()-$%&^*;+=]+/ ------ Alternative regex
$expansion = expandAcronyms ( $words );
$tokens = removeStopWords ( $expansion );
// convert to type-frequency array
$tokens = array_filter ( $tokens );
$tokens = array_count_values ( $tokens );
return $tokens;
}
function expandAcronyms($terms) {
$words = [ ];
$acrok = array_keys ( $GLOBALS ['acronyms'] );
$acrov = array_values ( $GLOBALS ['acronyms'] );
for($i = 0; $i < count ( $terms ); $i ++) {
$j = 0;
$is_acronym = false;
while ( $is_acronym == false && $j != count ( $acrok ) ) {
if (strcasecmp ( $terms [$i], $acrok [$j] ) == 0) {
$is_acronym = true;
$expansion = $acrov [$j];
}
$j ++;
}
if ($is_acronym) {
$expansion = preg_split ( "/[^A-Za-z0-9]+/", $expansion );
foreach ( $expansion as $term ) {
$words [] = $term;
}
} else {
$words [] = $terms [$i];
}
}
return $words;
}
function removeStopWords($words) {
$tokens = [ ];
for($i = 0; $i < count ( $words ); $i ++) {
$is_stopword = false;
$j = 0;
while ( $is_stopword == false && $j != count ( $GLOBALS ['stop_words'] ) ) {
if (strcasecmp ( $words [$i], $GLOBALS ['stop_words'] [$j] ) == 0) {
$is_stopword = true;
} else
$j ++;
}
if (! $is_stopword) {
$tokens [] = $words [$i];
}
}
return $tokens;
}
function extractLocation($timeline, $n) {
$geo = $timeline [$n]->place;
if (! empty ( $geo )) {
$place = $geo->full_name;
$long = $geo->bounding_box->coordinates [0] [1] [0];
$lat = $geo->bounding_box->coordinates [0] [1] [1];
$coord = array (
'place' => $place,
'latitude' => $lat,
'longitude' => $long
);
} else {
$coord = [ ];
}
return $coord;
}
function addSentimentURL($text, $tweet_id, &$urls, &$urls_id) {
$urls_id [] = $tweet_id;
$url = makeURLForAPICall ( $text );
$urls [] = $url;
}
function makeURLForAPICall($tweet) {
$tweet = str_replace ( ' ', '+', $tweet );
$prefix = 'http://uclassify.com/browse/uClassify/Sentiment/ClassifyText?';
$key = 'readkey=' . CLASSIFY_KEY . '&';
$text = 'text=' . $tweet . '&';
$version = 'version=1.01';
$url = $prefix . $key . $text . $version;
return $url;
}
function makeEntry($tokens, $tweet_id, $coord, $text) {
$types = array ();
while ( current ( $tokens ) ) {
$key = key ( $tokens );
array_push ( $types, array (
'type' => $key,
'frequency' => $tokens [$key],
'tweet_id' => $tweet_id,
'location' => $coord,
'text' => $text
) );
next ( $tokens );
}
return $types;
}
function extractSentiments($urls, $urls_id, &$json_index) {
$responses = multiHandle ( $urls );
// add sentiments to all index entries
foreach ( $json_index as $i => $term ) {
$tweet_id = $term ['tweet_id'];
foreach ( $urls_id as $j => $id ) {
if ($tweet_id == $id) {
$sentiment = parseSentiment ( $responses [$j] );
$json_index [$i] ['sentiment'] = $sentiment;
}
}
}
return $json_index;
}
// - Without sentiment, indexing is performed at reasonable speed
// - With sentiment, very frequent API calls greatly reduce indexing speed
// - filegetcontents() for Sentiment API calls is too slow, therefore considered cURL
// - cURL is still too slow and indexing performance is still not good enough
// - therefore considered using multi cURL which is much faster than by just using cURL
// on its own and significantly improved sentiment extraction which in turn greatly
// improved indexing with sentiment
function multiHandle($urls) {
// curl handles
$curls = array ();
// results returned in xml
$xml = array ();
// init multi handle
$mh = curl_multi_init ();
foreach ( $urls as $i => $d ) {
// init curl handle
$curls [$i] = curl_init ();
$url = (is_array ( $d ) && ! empty ( $d ['url'] )) ? $d ['url'] : $d;
// set url to curl handle
curl_setopt ( $curls [$i], CURLOPT_URL, $url );
// on success, return actual result rather than true
curl_setopt ( $curls [$i], CURLOPT_RETURNTRANSFER, 1 );
// add curl handle to multi handle
curl_multi_add_handle ( $mh, $curls [$i] );
}
// execute the handles
$active = null;
do {
curl_multi_exec ( $mh, $active );
} while ( $active > 0 );
// get xml and flush handles
foreach ( $curls as $i => $ch ) {
$xml [$i] = curl_multi_getcontent ( $ch );
curl_multi_remove_handle ( $mh, $ch );
}
// close multi handle
curl_multi_close ( $mh );
return $xml;
}
// SENTIMENT VALUES ON INDEX.JSON FOR THIS ASSIGNMENT ARE NOT CORRECT SINCE THE
// NUMBER OF API CALLS EXCEEDED 5000 ON THE DAY OF HANDING IN. ONCE THE API CALLS
// ARE ALLOWED AGAIN IT CLASSIFIES AS REQUIRED
function parseSentiment($xml) {
$p = xml_parser_create ();
xml_parse_into_struct ( $p, $xml, $vals, $index );
xml_parser_free ( $p );
$positivity = $vals [8] ['attributes'] ['P'];
$negativity = 1 - $positivity;
$sentiment = array (
'pos' => $positivity,
'neg' => $negativity
);
return $sentiment;
}
function sortIndex($json_index) {
$type = array ();
$freq = array ();
$id = array ();
foreach ( $json_index as $key => $row ) {
$type [$key] = $row ['type'];
$freq [$key] = $row ['frequency'];
$id [$key] = $row ['tweet_id'];
}
array_multisort ( $type, SORT_ASC | SORT_NATURAL | SORT_FLAG_CASE,
$freq, SORT_DESC,
$id, SORT_ASC,
$json_index );
return $json_index;
}
function encodeIndex($json_index) {
$json = json_encode ( $json_index, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT );
$index = fopen ( INDEX_PATH, 'w' );
fwrite ( $index, $json );
fclose ( $index );
return $json;
}
function countIndex($json_index) {
$tweets = [ ];
$count = 0;
for($i = 0; $i < count ( $json_index ); $i ++) {
$id = $json_index [$i] ['tweet_id'];
if (in_array ( $id, $tweets )) {
} else {
$tweets [] = $id;
$count ++;
}
}
return $count;
}
function lookup($array, $key, $val) {
foreach ( $array as $item ) {
if (isset ( $item [$key] ) && $item [$key] == $val) {
return true;
} else {
return false;
}
}
}
function getMostRecentTweet() {
$file = fopen ( 'latest.txt', 'r' );
$most_recent = fgets ( $file );
if (! $most_recent) {
$most_recent = 0;
}
fclose ( $file );
return $most_recent;
}
function updateMostRecentTweet($latest_id) {
$file = fopen ( 'latest.txt', 'w' );
fwrite ( $file, $latest_id . PHP_EOL );
fclose ( $file );
}
include ('index.inc');
?>
I have fixed the problem. When creating my application on OpenShift using the application wizard, I was specifying PHP 5.3 as the cartridge and not PHP 5.4 (note the way I'm specifying certain empty arrays).
The true lesson to take from this is: always be sure about the version of the language you're developing with
Thank you for any help given and I hope this may come of use to someone else in the future!

How to get tag_description in foreach Wordpress template?

I've made this script,
<?php
function top_tags() {
$tags = get_tags();
if (empty($tags))
return;
$counts = $tag_links = array();
foreach ( (array) $tags as $tag ) {
$counts[$tag->name] = $tag->count;
$tag_links[$tag->name] = get_tag_link( $tag->term_id );
}
asort($counts);
$counts = array_reverse( $counts, true );
$i = 0;
foreach ( $counts as $tag => $count ) {
$i++;
$tag_link = clean_url($tag_links[$tag]);
$tag = str_replace(' ', ' ', wp_specialchars( $tag ));
if($i < 11){
print "<li>$tag ($count) </li>";
}
}
}
?>
But I can't seem to get the tag_description per tag. It does not show anything if I use $description = tag_description(); in the foreach function.
How about... this:
<?php
function top_tags() {
$tags = get_tags();
if (empty($tags))
return;
$counts = $tag_links = array();
foreach ( (array) $tags as $tag ) {
$counts[$tag->name] = $tag->count;
$tag_links[$tag->name] = get_tag_link( $tag->term_id );
}
asort($counts);
$counts = array_reverse( $counts, true );
$i = 0;
foreach ( $counts as $tag => $count ) {
$i++;
$tag_link = clean_url($tag_links[$tag]);
$tag_description = tag_description(get_term_by('name', $tag, 'post_tag')->term_id);
$tag = str_replace(' ', ' ', wp_specialchars( $tag ));
if($i < 11){
print "<li>$tag ($count) $tag_description </li>";
}
}
}
?>
A more efficient way of doing this (untested):
<?php
function top_tags() {
$tags = get_tags();
if (empty($tags))
return;
$counts = $tag_links = array();
foreach ( (array) $tags as $tag ) {
$counts[$tag->name] = $tag->count;
$tag_links[$tag->name] = array( 'url' => get_tag_link( $tag->term_id ), 'description' => $tag->description);
}
asort($counts);
$counts = array_reverse( $counts, true );
$i = 0;
foreach ( $counts as $tag => $count ) {
$i++;
$tag_link = clean_url($tag_links[$tag]['url']);
$tag_description = $tag_links[$tag]['description'];
$tag = str_replace(' ', ' ', wp_specialchars( $tag ));
if($i < 11){
print "<li>$tag ($count) $tag_description </li>";
}
}
}
?>
Just to comment on your idea, which should not be used, you can use tag_description inside your foreach loop as follow
$description = tag_description($tag->term_id);
The above method is not wrong, but get_tags already returns the tag description which you can return as follow
$tag->description
EDIT
To see what is returned by get_tags, do the following
$tags = get_tags;
?><pre><?php var_dump($tags); ?></pre><?php

Categories