Advertisement
Guest User

class.jnews-view-counter.php

a guest
Nov 2nd, 2017
314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 23.33 KB | None | 0 0
  1. <?php
  2. /**
  3.  * @author : Jegtheme
  4.  */
  5.  
  6. if ( ! defined( 'ABSPATH' ) ) {
  7.     exit;
  8. }
  9.  
  10. JNews_View_Counter::getInstance();
  11.  
  12. /**
  13.  * Class Theme JNews Option
  14.  */
  15. Class JNews_View_Counter
  16. {
  17.     /**
  18.      * @var JNews_View_Counter
  19.      */
  20.     private static $instance;
  21.  
  22.     /**
  23.      * @var integer
  24.      */
  25.     private $post_id;
  26.  
  27.     /**
  28.      * @return JNews_View_Counter
  29.      */
  30.     public static function getInstance()
  31.     {
  32.         if (null === static::$instance) {
  33.             static::$instance = new static();
  34.         }
  35.         return static::$instance;
  36.     }
  37.  
  38.     /**
  39.      * JNews_View_Counter constructor.
  40.      */
  41.     private function __construct()
  42.     {
  43.         add_action( 'template_redirect', array( $this, 'set_post_id' ) );
  44.         add_action( 'wpmu_new_blog', array( $this, 'new_site_activation' ) );
  45.         add_action( 'wp_head', array(&$this, 'print_ajax') );
  46.         add_action( 'admin_init', array($this, 'delete_post_init') );
  47.  
  48.         // jnews view ajax
  49.         add_action( 'jnews_ajax_views_handler', array($this, 'jnews_views_ajax') );
  50.  
  51.         // Remove post/page prefetching!
  52.         remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head' );
  53.     }
  54.  
  55.     /**
  56.      * Data Table
  57.      *
  58.      * @return string
  59.      */
  60.     public function get_data_table()
  61.     {
  62.         global $wpdb;
  63.  
  64.         return $wpdb->prefix . JNEWS_VIEW_COUNTER_DB_DATA;
  65.     }
  66.  
  67.     /**
  68.      * Summary Table
  69.      *
  70.      * @return string
  71.      */
  72.     public function get_summary_table()
  73.     {
  74.         global $wpdb;
  75.  
  76.         return $wpdb->prefix . JNEWS_VIEW_COUNTER_DB_SUMMARY;
  77.     }
  78.  
  79.     public function new_site_activation( $blog_id ){
  80.  
  81.         if ( 1 !== did_action( 'wpmu_new_blog' ) )
  82.             return;
  83.  
  84.         // run activation for the new blog
  85.         switch_to_blog( $blog_id );
  86.  
  87.         // check required table
  88.         $this->plugin_activation();
  89.  
  90.         // switch back to current blog
  91.         restore_current_blog();
  92.  
  93.     }
  94.  
  95.     /**
  96.      * Execute when Plugin Activated
  97.      */
  98.     public function plugin_activation()
  99.     {
  100.         global $wpdb;
  101.  
  102.         $show_table = "SHOW TABLES LIKE '{$this->get_data_table()}'";
  103.  
  104.         if ( $this->get_data_table() != $wpdb->get_var($show_table) )
  105.         {
  106.             $this->create_table();
  107.         }
  108.     }
  109.  
  110.     /**
  111.      * Create Required Table
  112.      */
  113.     public function create_table()
  114.     {
  115.         global $wpdb;
  116.  
  117.         $charset_collate = "";
  118.  
  119.         if ( !empty($wpdb->charset) )
  120.             $charset_collate = "DEFAULT CHARACTER SET {$wpdb->charset} ";
  121.  
  122.         if ( !empty($wpdb->collate) )
  123.             $charset_collate .= "COLLATE {$wpdb->collate}";
  124.  
  125.         $create_data_table = "CREATE TABLE " . $this->get_data_table() . " (
  126.                postid bigint(20) NOT NULL,
  127.                day datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  128.                last_viewed datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  129.                pageviews bigint(20) DEFAULT 1,
  130.                PRIMARY KEY  (postid)
  131.            ) {$charset_collate} ENGINE=INNODB;";
  132.  
  133.         $create_summary_table = "CREATE TABLE " . $this->get_summary_table() . " (
  134.                ID bigint(20) NOT NULL AUTO_INCREMENT,
  135.                postid bigint(20) NOT NULL,
  136.                pageviews bigint(20) NOT NULL DEFAULT 1,
  137.                view_date date NOT NULL DEFAULT '0000-00-00',
  138.                last_viewed datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  139.                PRIMARY KEY  (ID),
  140.                UNIQUE KEY ID_date (postid,view_date),
  141.                KEY postid (postid),
  142.                KEY view_date (view_date),
  143.                KEY last_viewed (last_viewed)
  144.            ) {$charset_collate} ENGINE=INNODB;";
  145.  
  146.         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
  147.         dbDelta($create_data_table . $create_summary_table);
  148.     }
  149.  
  150.     public function delete_post_init()
  151.     {
  152.         if ( current_user_can( 'delete_posts' ) ) {
  153.             add_action( 'delete_post', array( $this, 'delete_post_action' ), 10 );
  154.         }
  155.     }
  156.  
  157.     public function delete_post_action($post_id)
  158.     {
  159.         global $wpdb;
  160.  
  161.         if ( $wpdb->get_var( $wpdb->prepare( "SELECT postid FROM " . $this->get_data_table() . " WHERE postid = %d", $post_id ) ) )
  162.         {
  163.             $wpdb->query( $wpdb->prepare( "DELETE FROM " . $this->get_data_table() . " WHERE postid = %d", $post_id ) );
  164.  
  165.             $wpdb->query( $wpdb->prepare( "DELETE FROM " . $this->get_summary_table() . " WHERE postid = %d" , $post_id ) );
  166.         }
  167.  
  168.         return true;
  169.     }
  170.  
  171.  
  172.     /**
  173.      * Set Post ID
  174.      */
  175.     public function set_post_id()
  176.     {
  177.         $trackable = array();
  178.         $registered_post_types = get_post_types( array('public' => true), 'names' );
  179.  
  180.         foreach ( $registered_post_types as $post_type ) {
  181.             $trackable[] = $post_type;
  182.         }
  183.  
  184.         $trackable = apply_filters( 'jnews_trackable_post_types', $trackable );
  185.  
  186.         if ( is_singular($trackable) && !is_front_page() && !is_preview() && !is_trackback() && !is_feed() && !is_robots() ) {
  187.             global $post;
  188.             $this->post_id = ( is_object($post) ) ? $post->ID : 0;
  189.         } else {
  190.             $this->post_id = 0;
  191.         }
  192.     }
  193.  
  194.     /**
  195.      * Print Ajax Header
  196.      */
  197.     public function print_ajax()
  198.     {
  199.         if ( 0 != $this->post_id )
  200.         {
  201.             ?>
  202.             <script type="text/javascript">
  203.  
  204.                 /* Create XMLHttpRequest object and set variables */
  205.                 var xhr = ( window.XMLHttpRequest )
  206.                         ? new XMLHttpRequest()
  207.                         : new ActiveXObject( "Microsoft.XMLHTTP" ),
  208.                     url = ajax_url,
  209.                     params = 'action=views_handler&token=<?php echo wp_create_nonce('jnews-view-token') ?>&jnews_id=<?php echo esc_js($this->post_id); ?>';
  210.                 /* Set request method and target URL */
  211.                 xhr.open( "POST", url, true );
  212.                 /* Set request header */
  213.                 xhr.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
  214.                 /* Hook into onreadystatechange */
  215.                 xhr.onreadystatechange = function() {
  216.                     if ( 4 === xhr.readyState && 200 === xhr.status ) {
  217.                         if ( window.console && window.console.log ) {
  218.                             window.console.log( xhr.responseText );
  219.                         }
  220.                     }
  221.                 };
  222.                 /* Send request */
  223.                 xhr.send( params );
  224.  
  225.             </script>
  226.             <?php
  227.         }
  228.     }
  229.  
  230.     /**
  231.      * Ajax View
  232.      */
  233.     public function jnews_views_ajax()
  234.     {
  235.         if ( !wp_verify_nonce($_POST['token'], 'jnews-view-token') || !$this->is_numeric($_POST['jnews_id']) )
  236.             die("JNews View Counter: Oops, invalid request!");
  237.  
  238.         $post_ID = $_POST['jnews_id'];
  239.  
  240.         $exec_time = 0;
  241.  
  242.         $start = $this->microtime_float();
  243.         $result = $this->update_views($post_ID);
  244.         $end = $this->microtime_float();
  245.  
  246.         $exec_time += round($end - $start, 6);
  247.  
  248.         if ( $result ) {
  249.             die( "JNews View Counter: OK. Execution time: " . $exec_time . " seconds" );
  250.         }
  251.  
  252.         die( "JNews View Counter: Oops, could not update the views count!" );
  253.     }
  254.  
  255.     private function update_views($id)
  256.     {
  257.         global $wpdb;
  258.         $wpdb->show_errors();
  259.  
  260.         // WPML support, get original post/page ID
  261.         if ( defined('ICL_LANGUAGE_CODE') && function_exists('icl_object_id') )
  262.         {
  263.             global $sitepress;
  264.             if ( isset( $sitepress )) { // avoids a fatal error with Polylang
  265.                 $id = icl_object_id( $id, get_post_type( $id ), true, $sitepress->get_default_language() );
  266.             }
  267.             else if ( function_exists( 'pll_default_language' ) ) { // adds Polylang support
  268.                 $id = icl_object_id( $id, get_post_type( $id ), true, pll_default_language() );
  269.             }
  270.         }
  271.  
  272.         $now = $this->now();
  273.         $curdate = $this->curdate();
  274.         $views = 1;
  275.  
  276.         // before updating views count
  277.         if ( has_action( 'jnews_pre_update_views' ) )
  278.             do_action( 'jnews_pre_update_views', $id, $views );
  279.  
  280.         // Update all-time table
  281.         $result1 = $wpdb->query( $wpdb->prepare(
  282.             "INSERT INTO " . $this->get_data_table() . "
  283.            (postid, day, last_viewed, pageviews) VALUES (%d, %s, %s, %d)
  284.            ON DUPLICATE KEY UPDATE pageviews = pageviews + %d, last_viewed = '%s';",
  285.             $id, $now, $now, $views, $views, $now
  286.         ));
  287.  
  288.         // Update range (summary) table
  289.         $result2 = $wpdb->query( $wpdb->prepare(
  290.             "INSERT INTO " . $this->get_summary_table() . "
  291.            (postid, pageviews, view_date, last_viewed) VALUES (%d, %d, %s, %s)
  292.            ON DUPLICATE KEY UPDATE pageviews = pageviews + %d, last_viewed = '%s';",
  293.             $id, $views, $curdate, $now, $views, $now
  294.         ));
  295.  
  296.         if ( !$result1 || !$result2 )
  297.             return false;
  298.  
  299.         // after updating views count
  300.         if ( has_action( 'jnews_post_update_views' ) )
  301.             do_action( 'jnews_post_update_views', $id );
  302.  
  303.         return true;
  304.     }
  305.  
  306.     /**
  307.      * @return float
  308.      */
  309.     private function microtime_float()
  310.     {
  311.         list( $msec, $sec ) = explode( ' ', microtime() );
  312.  
  313.         $microtime = (float) $msec + (float) $sec;
  314.         return $microtime;
  315.     }
  316.  
  317.     /**
  318.      * Checks for valid number
  319.      *
  320.      * @param   int number
  321.      * @return  bool
  322.      */
  323.     private function is_numeric($number){
  324.         return !empty($number) && is_numeric($number) && (intval($number) == floatval($number));
  325.     }
  326.  
  327.     /**
  328.      * Returns server datetime
  329.      *
  330.      * @return  string
  331.      */
  332.     private function curdate() {
  333.         return gmdate( 'Y-m-d', ( time() + ( get_site_option( 'gmt_offset' ) * 3600 ) ));
  334.     }
  335.  
  336.     /**
  337.      * Returns mysql datetime
  338.      *
  339.      * @return  string
  340.      */
  341.     private function now() {
  342.         return current_time('mysql');
  343.     }
  344.  
  345.  
  346.     /**
  347.      * Template tag - gets views count.
  348.      *
  349.      * @global  object  wpdb
  350.      * @param   int     id
  351.      * @param   string  range
  352.      * @param   bool    number_format
  353.      * @return  string
  354.      */
  355.     public function get_views($id = NULL, $range = NULL, $number_format = true)
  356.     {
  357.         // have we got an id?
  358.         if ( empty($id) || is_null($id) || !is_numeric($id) ) {
  359.             return "-1";
  360.         } else {
  361.             global $wpdb;
  362.  
  363.             if ( !$range || 'all' == $range ) {
  364.                 $query = "SELECT pageviews FROM " . $this->get_data_table() . " WHERE postid = '{$id}'";
  365.             } else {
  366.                 $interval = "";
  367.  
  368.                 switch( $range ){
  369.                     case "yesterday":
  370.                         $interval = "1 DAY";
  371.                         break;
  372.  
  373.                     case "daily":
  374.                         $interval = "1 DAY";
  375.                         break;
  376.  
  377.                     case "weekly":
  378.                         $interval = "1 WEEK";
  379.                         break;
  380.  
  381.                     case "monthly":
  382.                         $interval = "1 MONTH";
  383.                         break;
  384.  
  385.                     default:
  386.                         $interval = "1 DAY";
  387.                         break;
  388.                 }
  389.  
  390.                 $now = current_time('mysql');
  391.  
  392.                 $query = "SELECT SUM(pageviews) FROM " . $this->get_summary_table() . " WHERE postid = '{$id}' AND last_viewed > DATE_SUB('{$now}', INTERVAL {$interval}) LIMIT 1;";
  393.             }
  394.  
  395.             $result = $wpdb->get_var($query);
  396.  
  397.             if ( !$result ) {
  398.                 return "0";
  399.             }
  400.  
  401.             return ($number_format) ? number_format_i18n( intval($result) ) : $result;
  402.         }
  403.     }
  404.  
  405.  
  406.     /**
  407.      * Custom Query JNews. Add ability to receive Paging Parameter and Tag Parameter
  408.      *
  409.      * @param $instance
  410.      * @return array
  411.      */
  412.     public function query($instance)
  413.     {
  414.         global $wpdb;
  415.         $default = array(
  416.             'limit'             => 10,
  417.             'offset'            => 0,
  418.             'paged'             => 1,
  419.             'range'             => 'all',
  420.             'freshness'         => false,
  421.             'order_by'          => 'views',
  422.             'post_type'         => 'post',
  423.             'include_post'      => '',
  424.             'exclude_post'      => '',
  425.             'include_category'  => '',
  426.             'exclude_category'  => '',
  427.             'include_tag'       => '',
  428.             'exclude_tag'       => '',
  429.             'author'            => '',
  430.         );
  431.  
  432.         // parse instance values
  433.         $instance = $this->merge_array_r(
  434.             $default,
  435.             $instance
  436.         );
  437.  
  438.         $prefix         = $wpdb->prefix . "popularposts";
  439.         $fields         = "p.ID AS 'id', p.post_title AS 'title', p.post_date AS 'date', p.post_author AS 'uid'";
  440.         $where          = "WHERE 1 = 1";
  441.         $orderby        = "";
  442.         $groupby        = "";
  443.  
  444.         $limit = "LIMIT " . (int) $instance['offset'] . ", {$instance['limit']}";
  445.  
  446.         $now = $this->now();
  447.  
  448.         // post filters
  449.         if ( $instance['freshness'] )
  450.         {
  451.             switch( $instance['range'] )
  452.             {
  453.                 case "daily":
  454.                     $where .= " AND p.post_date > DATE_SUB('{$now}', INTERVAL 1 DAY) ";
  455.                     break;
  456.  
  457.                 case "weekly":
  458.                     $where .= " AND p.post_date > DATE_SUB('{$now}', INTERVAL 1 WEEK) ";
  459.                     break;
  460.  
  461.                 case "monthly":
  462.                     $where .= " AND p.post_date > DATE_SUB('{$now}', INTERVAL 1 MONTH) ";
  463.                     break;
  464.  
  465.                 default:
  466.                     $where .= "";
  467.                     break;
  468.             }
  469.         }
  470.  
  471.         // * post type
  472.         $where .= " AND p.post_type = '{$instance['post_type']}'";
  473.  
  474.         // * post include & exclude
  475.         if ( !empty($instance['include_post']) ) {
  476.             $where .= " AND p.ID IN ({$instance['include_post']})";
  477.         }
  478.  
  479.         if ( !empty($instance['exclude_post']) ) {
  480.             $where .= " AND p.ID NOT IN({$instance['exclude_post']})";
  481.         }
  482.  
  483.         // * categories
  484.         if ( $instance['include_category'] !== '' || $instance['exclude_category'] !== '' )
  485.         {
  486.             if ( $instance['include_category'] !== '' && $instance['exclude_category'] == '' ) {
  487.                 $where .= " AND p.ID IN (
  488.                    SELECT object_id
  489.                    FROM {$wpdb->term_relationships} AS r
  490.                         JOIN {$wpdb->term_taxonomy} AS x ON x.term_taxonomy_id = r.term_taxonomy_id
  491.                    WHERE x.taxonomy = 'category' AND x.term_id IN({$instance['include_category']})
  492.                    )";
  493.             } else if ($instance['include_category'] === '' && $instance['exclude_category'] !== '') {
  494.                 $where .= " AND p.ID NOT IN (
  495.                    SELECT object_id
  496.                    FROM {$wpdb->term_relationships} AS r
  497.                         JOIN {$wpdb->term_taxonomy} AS x ON x.term_taxonomy_id = r.term_taxonomy_id
  498.                    WHERE x.taxonomy = 'category' AND x.term_id IN({$instance['exclude_category']})
  499.                    )";
  500.             } else { // mixed
  501.                 $where .= " AND p.ID IN (
  502.                    SELECT object_id
  503.                    FROM {$wpdb->term_relationships} AS r
  504.                         JOIN {$wpdb->term_taxonomy} AS x ON x.term_taxonomy_id = r.term_taxonomy_id
  505.                    WHERE x.taxonomy = 'category' AND x.term_id IN({$instance['include_category']}) AND x.term_id NOT IN({$instance['exclude_category']})
  506.                    ) ";
  507.             }
  508.         }
  509.  
  510.         // * tag
  511.         if ( $instance['include_tag'] !== '' || $instance['exclude_tag'] !== '' )
  512.         {
  513.             if ( $instance['include_tag'] !== '' && $instance['exclude_tag'] == '' ) {
  514.                 $where .= " AND p.ID IN (
  515.                    SELECT object_id
  516.                    FROM {$wpdb->term_relationships} AS r
  517.                         JOIN {$wpdb->term_taxonomy} AS x ON x.term_taxonomy_id = r.term_taxonomy_id
  518.                    WHERE x.taxonomy = 'post_tag' AND x.term_id IN({$instance['include_tag']})
  519.                    )";
  520.             } else if ($instance['include_tag'] === '' && $instance['exclude_tag'] !== '') {
  521.                 $where .= " AND p.ID NOT IN (
  522.                    SELECT object_id
  523.                    FROM {$wpdb->term_relationships} AS r
  524.                         JOIN {$wpdb->term_taxonomy} AS x ON x.term_taxonomy_id = r.term_taxonomy_id
  525.                    WHERE x.taxonomy = 'post_tag' AND x.term_id IN({$instance['exclude_tag']})
  526.                    )";
  527.             } else { // mixed
  528.                 $where .= " AND p.ID IN (
  529.                    SELECT object_id
  530.                    FROM {$wpdb->term_relationships} AS r
  531.                         JOIN {$wpdb->term_taxonomy} AS x ON x.term_taxonomy_id = r.term_taxonomy_id
  532.                    WHERE x.taxonomy = 'post_tag' AND x.term_id IN({$instance['include_tag']}) AND x.term_id NOT IN({$instance['exclude_tag']})
  533.                    ) ";
  534.             }
  535.         }
  536.  
  537.         // * authors
  538.         if ( !empty($instance['author']) )
  539.         {
  540.             $where .= " AND p.post_author IN({$instance['author']})";
  541.         }
  542.  
  543.         // * All-time range
  544.         if ( "all" == $instance['range'] ) {
  545.  
  546.             $fields .= ", p.comment_count AS 'comment_count'";
  547.  
  548.             // order by comments
  549.             if ( "comments" == $instance['order_by'] ) {
  550.  
  551.                 $from = "{$wpdb->posts} p";
  552.                 $where .= " AND p.comment_count > 0 ";
  553.                 $orderby = " ORDER BY p.comment_count DESC";
  554.  
  555.             }
  556.             // order by (avg) views
  557.             else {
  558.  
  559.                 $from = "{$prefix}data v LEFT JOIN {$wpdb->posts} p ON v.postid = p.ID";
  560.  
  561.                 // order by views
  562.                 if ( "views" == $instance['order_by'] ) {
  563.  
  564.                     $fields .= ", v.pageviews AS 'pageviews'";
  565.                     $orderby = "ORDER BY pageviews DESC";
  566.  
  567.                 }
  568.                 // order by avg views
  569.                 elseif ( "avg" == $instance['order_by'] ) {
  570.  
  571.                     $fields .= ", ( v.pageviews/(IF ( DATEDIFF('{$now}', MIN(v.day)) > 0, DATEDIFF('{$now}', MIN(v.day)), 1) ) ) AS 'avg_views'";
  572.                     $groupby = "GROUP BY v.postid";
  573.                     $orderby = "ORDER BY avg_views DESC";
  574.  
  575.                 }
  576.  
  577.             }
  578.  
  579.         } else { // CUSTOM RANGE
  580.  
  581.             switch( $instance['range'] ){
  582.                 case "daily":
  583.                     $interval = "1 DAY";
  584.                     break;
  585.  
  586.                 case "weekly":
  587.                     $interval = "1 WEEK";
  588.                     break;
  589.  
  590.                 case "monthly":
  591.                     $interval = "1 MONTH";
  592.                     break;
  593.  
  594.                 default:
  595.                     $interval = "1 DAY";
  596.                     break;
  597.             }
  598.  
  599.             // order by comments
  600.             if ( "comments" == $instance['order_by'] ) {
  601.  
  602.                 $fields .= ", COUNT(c.comment_post_ID) AS 'comment_count'";
  603.                 $from = "{$wpdb->comments} c LEFT JOIN {$wpdb->posts} p ON c.comment_post_ID = p.ID";
  604.                 $where .= " AND c.comment_date_gmt > DATE_SUB('{$now}', INTERVAL {$interval}) AND c.comment_approved = 1 ";
  605.                 $groupby = "GROUP BY c.comment_post_ID";
  606.                 $orderby = "ORDER BY comment_count DESC";
  607.  
  608.             }
  609.             // ordered by views / avg
  610.             else {
  611.  
  612.                 $from = "{$prefix}summary v LEFT JOIN {$wpdb->posts} p ON v.postid = p.ID";
  613.                 $where .= " AND v.last_viewed > DATE_SUB('{$now}', INTERVAL {$interval}) ";
  614.                 $groupby = "GROUP BY v.postid";
  615.  
  616.                 // ordered by views
  617.                 if ( "views" == $instance['order_by'] ) {
  618.  
  619.                     $fields .= ", SUM(v.pageviews) AS 'pageviews'";
  620.                     $orderby = "ORDER BY pageviews DESC";
  621.  
  622.                 }
  623.                 // ordered by avg views
  624.                 elseif ( "avg" == $instance['order_by'] ) {
  625.  
  626.                     $fields .= ", ( SUM(v.pageviews)/(IF ( DATEDIFF('{$now}', DATE_SUB('{$now}', INTERVAL {$interval})) > 0, DATEDIFF('{$now}', DATE_SUB('{$now}', INTERVAL {$interval})), 1) ) ) AS 'avg_views' ";
  627.                     $orderby = "ORDER BY avg_views DESC";
  628.  
  629.                 }
  630.  
  631.             }
  632.  
  633.         }
  634.  
  635.         // List only published, non password-protected posts
  636.         $where .= " AND p.post_password = '' AND p.post_status = 'publish'";
  637.  
  638.         // Build query
  639.         $query = "SELECT SQL_CALC_FOUND_ROWS {$fields} FROM {$from} {$where} {$groupby} {$orderby} {$limit};";
  640.         $query = $wpdb->get_results($query);
  641.  
  642.         if( isset( $instance['no_found_rows'] ) && ! $instance['no_found_rows'] ) {
  643.             $total_row = $wpdb->get_results("SELECT FOUND_ROWS() as total");
  644.             $total_row = $total_row[0]->total;
  645.         } else {
  646.             $total_row = 0;
  647.         }
  648.  
  649.         $result_ids = array();
  650.  
  651.         foreach($query as $result)
  652.         {
  653.             $result_ids[] = $this->get_translate_id($result->id);
  654.         }
  655.  
  656.         $all_post = get_posts(array(
  657.             'post__in'  => $result_ids,
  658.             'post_type' => 'post',
  659.             'showposts' => empty($result_ids) ? $instance['limit'] : count( $result_ids )
  660.         ));
  661.         $results = $this->arrange_index($all_post, $result_ids);
  662.  
  663.         return array(
  664.             'result'        => $results,
  665.             'total'         => $total_row
  666.         );
  667.     }
  668.  
  669.     public function arrange_index($result, $results_id)
  670.     {
  671.         $new_result = array();
  672.  
  673.         foreach($results_id as $id)
  674.         {
  675.             foreach($result as $post) {
  676.                 if($id == $post->ID) {
  677.                     $new_result[] = $post;
  678.                     break;
  679.                 }
  680.             }
  681.         }
  682.  
  683.         return $new_result;
  684.     }
  685.    
  686.     public function get_translate_id($post_id)
  687.     {
  688.         if(function_exists('pll_get_post'))
  689.         {
  690.             $result_id = pll_get_post($post_id, pll_current_language());
  691.  
  692.             if($result_id) {
  693.                 $post_id = $result_id;
  694.             }
  695.         }
  696.  
  697.         return $post_id;
  698.     }
  699.  
  700.     /**
  701.      * Merges two associative arrays recursively
  702.      */
  703.     private function merge_array_r( array &$array1, array &$array2 ) {
  704.  
  705.         $merged = $array1;
  706.  
  707.         foreach ( $array2 as $key => &$value ) {
  708.  
  709.             if ( is_array( $value ) && isset ( $merged[$key] ) && is_array( $merged[$key] ) ) {
  710.                 $merged[$key] = $this->merge_array_r( $merged[$key], $value );
  711.             } else {
  712.                 $merged[$key] = $value;
  713.             }
  714.         }
  715.  
  716.         return $merged;
  717.  
  718.     }
  719. }
  720.  
  721. /**
  722.  * Get total View
  723.  *
  724.  * @param null $id
  725.  * @param null $range
  726.  * @param bool $number_format
  727.  * @return string
  728.  */
  729. function jnews_get_views($id = NULL, $range = NULL, $number_format = true)
  730. {
  731.     return JNews_View_Counter::getInstance()->get_views($id, $range, $number_format);
  732. }
  733.  
  734. /**
  735.  * @param $instance
  736.  * @return array
  737.  */
  738. function jnews_view_counter_query($instance)
  739. {
  740.     return JNews_View_Counter::getInstance()->query($instance);
  741. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement