Guest User

framework-widgets

a guest
Jun 12th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 116.16 KB | None | 0 0
  1. <?php  if ( ! defined('AVIA_FW')) exit('No direct script access allowed');
  2. /**
  3.  * This file holds several widgets exclusive to the framework
  4.  *
  5.  * @author      Christian "Kriesi" Budschedl
  6.  * @copyright   Copyright (c) Christian Budschedl
  7.  * @link        http://Kriesi.at
  8.  * @link        http://aviathemes.com
  9.  * @since       Version 1.0
  10.  * @package     AviaFramework
  11.  */
  12.  
  13.  
  14. if ( ! class_exists( 'Avia_Widget' ) )
  15. {
  16.     abstract class Avia_Widget extends WP_Widget
  17.     {
  18.        
  19.         /**
  20.          *
  21.          * @since 4.3.2
  22.          * @var array
  23.          */
  24.         protected $field_names;
  25.        
  26.         public function __construct( $id_base, $name, $widget_options = array(), $control_options = array() )
  27.         {
  28.             parent::__construct( $id_base, $name, $widget_options, $control_options );
  29.            
  30.             $this->field_names = array();
  31.         }
  32.        
  33.                
  34.         /**
  35.          * @since 4.3.2
  36.          */
  37.         public function __destruct()
  38.         {
  39.             if( method_exists( $this, 'parent::__destruct' ) )
  40.             {
  41.                 parent::__destruct();
  42.             }
  43.            
  44.             unset( $this->field_names );
  45.         }
  46.        
  47.         /**
  48.          * Returns an array that contains all default instance members filled with default values
  49.          *
  50.          * @since 4.3.2
  51.          * @param array $instance
  52.          * @return array
  53.          */
  54.         abstract protected function parse_args_instance( array $instance );
  55.        
  56.        
  57.         /**
  58.          * Returns an array of all default fields
  59.          *
  60.          * @since 4.3.2
  61.          * @return array
  62.          */
  63.         protected function get_field_names()
  64.         {
  65.             if( empty( $this->field_names ) )
  66.             {
  67.                 $fields = $this->parse_args_instance( array() );
  68.                 $this->field_names = array_keys( $fields );
  69.             }
  70.            
  71.             return $this->field_names;
  72.         }
  73.        
  74.     }
  75.    
  76. }
  77.  
  78.  
  79.  
  80.  
  81. /**
  82.  * AVIA FACEBOOK WIDGET
  83.  */
  84.  
  85. if ( ! class_exists( 'avia_fb_likebox' ) )
  86. {
  87.     class avia_fb_likebox extends Avia_Widget
  88.     {
  89.         const AJAX_NONCE = 'avia_fb_likebox_nonce';
  90.         const FB_SCRIPT_ID = 'facebook-jssdk';
  91.        
  92.         /**
  93.          *
  94.          * @var int
  95.          */
  96.         static protected $script_loaded = 0;
  97.    
  98.        
  99.  
  100.  
  101.  
  102.         /**
  103.          *
  104.          */
  105.         public function __construct()
  106.         {
  107.             //Constructor
  108.             $widget_ops = array(
  109.                         'classname'     => 'avia_fb_likebox',
  110.                         'description'   => __( 'A widget that displays a facebook Likebox to a facebook page of your choice', 'avia_framework' )
  111.                         );
  112.            
  113.             parent::__construct( 'avia_fb_likebox', THEMENAME.' Facebook Likebox', $widget_ops );
  114.            
  115.             add_action( 'init', array( $this, 'handler_wp_register_scripts' ), 500 );
  116.             add_action( 'wp_enqueue_scripts', array( $this, 'handler_wp_enqueue_scripts' ), 500 );
  117.            
  118.         }
  119.        
  120.        
  121.         /**
  122.          * @since 4.3.2
  123.          */
  124.         public function __destruct()
  125.         {
  126.             parent::__destruct();
  127.         }
  128.        
  129.         /**
  130.          *
  131.          * @since 4.3.2
  132.          */
  133.         public function handler_wp_register_scripts()
  134.         {
  135.             $vn = avia_get_theme_version();
  136.            
  137.             wp_register_script( 'avia_facebook_front_script' , AVIA_JS_URL . 'conditional_load/avia_facebook_front.js', array( 'jquery' ), $vn, true );
  138.         }
  139.  
  140.         /**
  141.          * @since 4.3.2
  142.          */
  143.         public function handler_wp_enqueue_scripts()
  144.         {
  145.             $instances = $this->get_settings();
  146.             if( count( $instances ) > 0 )
  147.             {
  148.                 $need_js = array( 'confirm_link' );
  149.                
  150.                 foreach( $instances as $instance )
  151.                 {
  152.                     if( isset( $instance['fb_link'] ) && in_array( $instance['fb_link'], $need_js ) )
  153.                     {
  154.                         wp_enqueue_script( 'avia_facebook_front_script' );
  155.                         break;
  156.                     }
  157.                 }
  158.             }
  159.         }
  160.  
  161.         /**
  162.          *
  163.          * @since 4.3.2
  164.          * @param array $instance
  165.          * @return array
  166.          */
  167.         protected function parse_args_instance( array $instance )
  168.         {
  169.             $new_instance = wp_parse_args( $instance, array(
  170.                                                 'url'               => 'https://www.facebook.com/kriesi.at',
  171.                                                 'title'             => __( 'Follow us on Facebook', 'avia_framework' ),
  172.                                                 'fb_link'           => '',
  173.                                                 'fb_banner'         => '',
  174.                                                 'page_title'        => '',
  175.                                                 'fb_logo'           => '',
  176.                                                 'content'           => '',
  177.                                                 'add_info'          => __( 'Join our Facebook community', 'avia_framework' ),
  178.                                                 'confirm_button'    => __( 'Click to load facebook widget', 'avia_framework' ),
  179.                                                 'page_link_text'    => __( 'Open facebook page now', 'avia_framework' )
  180.                                             ) );
  181.            
  182.             return $new_instance;
  183.         }
  184.        
  185.  
  186.         /**
  187.          * Outputs the widget
  188.          *
  189.          * @param array $args
  190.          * @param array $instance
  191.          */
  192.         public function widget( $args, $instance )
  193.         {
  194.             $instance = $this->parse_args_instance( $instance );
  195.  
  196.             extract( $args, EXTR_SKIP );
  197.             extract( $instance, EXTR_SKIP );
  198.            
  199.             if( empty( $url ) )
  200.             {
  201.                 return;
  202.             }
  203.            
  204.             /**
  205.              * Allow to change the conditional display setting - e.g. if user is opt in and allows to connect directly
  206.              *
  207.              * @since 4.4
  208.              * @param string $google_link           '' | 'confirm_link' | 'page_only'
  209.              * @param string $context
  210.              * @param mixed $object
  211.              * @param array $args
  212.              * @param array $instance
  213.              * @return string
  214.              */
  215.              
  216.             $original_fb_link = $fb_link;
  217.             $fb_link = apply_filters( 'avf_conditional_setting_external_links', $fb_link, __CLASS__, $this, $args, $instance );
  218.             if( ! in_array( $fb_link, array( '', 'confirm_link', 'page_only' ) ) )
  219.             {
  220.                $fb_link = $original_fb_link;
  221.             }
  222.            
  223.             $title = apply_filters( 'widget_title', $title );
  224.        
  225.             echo $before_widget;
  226.            
  227.             if ( ! empty( $title ) )
  228.             {
  229.                 echo $before_title . $title . $after_title;
  230.             };
  231.            
  232.             $banner_bg = "";
  233.            
  234.             if( ! empty( $fb_link ) )
  235.             {
  236.                 if( ! empty( $fb_banner ) && ! empty( $fb_link ) )
  237.                 {  
  238.                     $banner_bg = 'style="background-image:url(' . $fb_banner . ');"';
  239.                 }
  240.                
  241.                 echo '<div class="av_facebook_widget_main_wrap" ' . $banner_bg . '>';
  242.            
  243.                 echo    '<div class="av_facebook_widget_page_title_container">';
  244.                 echo        '<span class="av_facebook_widget_title">';
  245.                 echo            '<a href="'.$url.'" target="_blank" title="' . esc_html( $page_title ) . '">' . esc_html( $page_title )."</a>";
  246.                 echo        '</span>';
  247.                 echo        '<span class="av_facebook_widget_content">';
  248.                 echo            esc_html( $content );
  249.                 echo        '</span>';
  250.                 echo    '</div>';
  251.            
  252.            
  253.                 $html_logo = '';
  254.            
  255.                 if( ! empty( $fb_logo ) )
  256.                 {
  257.                     $html_logo .=       '<div class="av_facebook_widget_logo_image">';
  258.                     $html_logo .=           '<img src="' . $fb_logo . '" alt="' . __( 'Logo image', 'avia_framework' ) . '">';
  259.                     $html_logo .=       '</div>';
  260.                 }
  261.                
  262.                 echo '<div class="av_facebook_widget_main_wrap_shadow"></div>';
  263.                 echo    '<div class="av_facebook_widget_logo av_widget_img_text_confirm">';
  264.                
  265.                 echo $html_logo;
  266.                
  267.                 echo    '</div>';
  268.            
  269.                 $data = "";
  270.                 if( 'confirm_link' == $fb_link )
  271.                 {
  272.                     $data  = ' data-fbhtml="' . htmlentities( $this->html_facebook_page( $url ), ENT_QUOTES, get_bloginfo( 'charset' ) ) . '"';
  273.                     $data .= ' data-fbscript="' . htmlentities( $this->get_fb_page_js_src(), ENT_QUOTES, get_bloginfo( 'charset' ) ) . '"';
  274.                     $data .= ' data-fbscript_id="' . avia_fb_likebox::FB_SCRIPT_ID . '"';
  275.                 }
  276.                
  277.                 $btn_text = ( 'confirm_link' == $fb_link ) ? $confirm_button : $page_link_text;
  278.                 $icon = "<span class='av_facebook_widget_icon' " . av_icon_string('facebook') . "></span>";
  279.                 echo    '<a href="'.$url.'" target="_blank" class="av_facebook_widget_button av_facebook_widget_' . $fb_link . '"' . $data . '>' .$icon . esc_html( $btn_text ) . '</a>';
  280.                
  281.                 if( ! empty( $fb_link ) )
  282.                 {
  283.                     echo    '<div class="av_facebook_widget_add_info">';
  284.                     echo        '<div class="av_facebook_widget_add_info_inner">';
  285.                     echo            '<span class="av_facebook_widget_add_info_inner_wrap">';
  286.                     echo                esc_html( $add_info );
  287.                     echo            '</span>';
  288.                     echo            '<div class="av_facebook_widget_imagebar">';
  289.                     echo            '</div>';
  290.                     echo        '</div>';
  291.                     echo    '</div>';
  292.                 }
  293.                
  294.                 echo '</div>';      //  class="av_facebook_widget_main_wrap"
  295.             }
  296.            
  297.             if( empty( $fb_link ) )
  298.             {
  299.                     echo $this->html_facebook_page( $url );
  300.                     add_action( 'wp_footer', array( $this,'handler_output_fb_page_script' ), 10 );
  301.             }
  302.            
  303.             echo $after_widget;
  304.         }
  305.        
  306.         /**
  307.          * Create the HTML for the facebook page widget
  308.          *
  309.          * @since 4.3.2
  310.          * @param string $url
  311.          * @return string
  312.          */
  313.         protected function html_facebook_page( $url )
  314.         {
  315.             $extraClass = '';
  316.             $style = '';
  317.            
  318. //          $height     = 151;                      //  remainings from original widget ?????
  319. //          $faces      = "true";
  320. //          $extraClass = "";
  321. //          $style      = "";
  322. //         
  323. //         
  324. //          if( strpos( $height, "%" ) !== false )
  325. //          {
  326. //              $extraClass = "av_facebook_widget_wrap_positioner";
  327. //              $style      = "style='padding-bottom:{$height}%'";
  328. //              $height     = "100%";
  329. //          }
  330.                    
  331.             $html = '';
  332.             $html .=    "<div class='av_facebook_widget_wrap {$extraClass}' {$style}>";
  333.             $html .=        '<div class="fb-page" data-width="500" data-href="' . $url . '" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true" data-show-posts="false">';
  334.             $html .=            '<div class="fb-xfbml-parse-ignore"></div>';
  335.             $html .=        '</div>';
  336.             $html .=    "</div>";
  337.            
  338.             return $html;
  339.         }
  340.  
  341.         /**
  342.          *
  343.          * @since 4.3.2
  344.          */
  345.         public function handler_output_fb_page_script()
  346.         {
  347.             if( self::$script_loaded >= 1 )
  348.             {
  349.                 return;
  350.             }
  351.            
  352.             self::$script_loaded = 1;
  353.            
  354.             $script = '
  355. <script>(function(d, s, id) {
  356.  var js, fjs = d.getElementsByTagName(s)[0];
  357.  if (d.getElementById(id)) return;
  358.  js = d.createElement(s); js.id = id;
  359.  js.src = "' . $this->get_fb_page_js_src() . '";
  360.  fjs.parentNode.insertBefore(js, fjs);
  361. }(document, "script", "' . avia_fb_likebox::FB_SCRIPT_ID . '"));</script>';
  362.            
  363.             echo $script;
  364.         }
  365.  
  366.        
  367.         /**
  368.          * Return the js function
  369.          * @since 4.3.2
  370.          * @return string
  371.          */
  372.         protected function get_fb_page_js_src()
  373.         {
  374.             $langcode = get_locale();
  375.            
  376.             /**
  377.              * Change language code for facebook page widget
  378.              *
  379.              * @used_by     enfold\config-wpml\config.php               10
  380.              * @since 4.3.2
  381.              */
  382.             $langcode = apply_filters( 'avf_fb_widget_lang_code', $langcode, 'fb-page' );
  383.            
  384.             $src = '//connect.facebook.net/'. $langcode .'/sdk.js#xfbml=1&version=v2.7';
  385.  
  386.             return $src;
  387.         }
  388.  
  389.  
  390.         /**
  391.          *
  392.          * @param array $new_instance
  393.          * @param array $old_instance
  394.          * @return array
  395.          */
  396.         public function update( $new_instance, $old_instance )
  397.         {
  398.             $instance = $this->parse_args_instance( $old_instance );
  399.             $fields = $this->get_field_names();
  400.            
  401.             foreach( $new_instance as $key => $value )
  402.             {
  403.                 if( in_array( $key, $fields ) )
  404.                 {
  405.                     $instance[ $key ] = strip_tags( $value );
  406.                 }
  407.             }
  408.            
  409.             return $instance;
  410.         }
  411.  
  412.        
  413.         /**
  414.          * Outputs Widgetform in backend
  415.          *
  416.          * @param array $instance
  417.          */
  418.         public function form( $instance )
  419.         {
  420.             $instance = $this->parse_args_instance( $instance );
  421.             $fields = $this->get_field_names();
  422.            
  423.             foreach( $instance as $key => $value )
  424.             {
  425.                 if( in_array( $key, $fields ) )
  426.                 {
  427.                     $instance[ $key ] = esc_attr( $value );
  428.                 }
  429.             }
  430.            
  431.             extract( $instance );
  432.            
  433.             $html = new avia_htmlhelper();
  434.            
  435.             $banner_element = array(
  436.                                 'name'      => __( 'Banner image', 'avia_framework' ),
  437.                                 'desc'      => __( 'Upload a banner image or enter the URL', 'avia_framework' ),
  438.                                 'id'        => $this->get_field_id( 'fb_banner'),
  439.                                 'id_name'   => $this->get_field_name( 'fb_banner' ),
  440.                                 'std'       => $fb_banner,
  441.                                 'type'      => 'upload',
  442.                                 'label'     => __('Use image as banner', 'avia_framework')
  443.                             );
  444.  
  445.             $logo_element = array(
  446.                                 'name'      => __( 'Logo', 'avia_framework' ),
  447.                                 'desc'      => __( 'Upload a logo or enter the URL', 'avia_framework' ),
  448.                                 'id'        => $this->get_field_id( 'fb_logo'),
  449.                                 'id_name'   => $this->get_field_name( 'fb_logo' ),
  450.                                 'std'       => $fb_logo,
  451.                                 'type'      => 'upload',
  452.                                 'label'     => __('Use image as logo', 'avia_framework')
  453.                             );
  454.            
  455.     ?>
  456.         <div class="avia_widget_form avia_widget_conditional_form avia_fb_likebox_form <?php echo $fb_link;?>">
  457.             <p>
  458.                 <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:', 'avia_framework'); ?>
  459.                 <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></label>
  460.             </p>
  461.            
  462.             <p>
  463.                 <label for="<?php echo $this->get_field_id('url'); ?>"><?php _e('Enter the url to the Page. Please note that it needs to be a link to a <strong>facebook fanpage</strong>. Personal profiles are not allowed!', 'avia_framework'); ?>
  464.                 <input class="widefat" id="<?php echo $this->get_field_id('url'); ?>" name="<?php echo $this->get_field_name('url'); ?>" type="text" value="<?php echo $url; ?>" /></label>
  465.             </p>
  466.            
  467.             <p>
  468.                 <label for="<?php echo $this->get_field_id( 'fb_link' ); ?>"><?php _e( 'Link to facebook', 'avia_framework' ); ?>:</label>
  469.                 <select id="<?php echo $this->get_field_id( 'fb_link' ); ?>" name="<?php echo $this->get_field_name( 'fb_link' ); ?>" class="widefat avia-coditional-widget-select">
  470.                     <option value="" <?php selected( '', $fb_link ) ?>><?php _e( 'Show facebook page widget &quot;Share/Like&quot; directly', 'avia_framework' ); ?></option>
  471.                     <option value="confirm_link" <?php selected( 'confirm_link', $fb_link ) ?>><?php _e( 'User must accept to show facebook page widget &quot;Share/Like&quot;', 'avia_framework' ); ?></option>
  472.                     <option value="page_only" <?php selected( 'page_only', $fb_link ) ?>><?php _e( 'Only open the facebook page - no data are sent', 'avia_framework' ); ?></option>
  473.                 </select>
  474.             </p>
  475.            
  476.             <p class="av-confirm_link">
  477.                 <label for="<?php echo $this->get_field_id('confirm_button'); ?>"><?php _e('Button text confirm link to facebook:', 'avia_framework'); ?>
  478.                 <input class="widefat" id="<?php echo $this->get_field_id('confirm_button'); ?>" name="<?php echo $this->get_field_name('confirm_button'); ?>" type="text" value="<?php echo $confirm_button; ?>" /></label>
  479.             </p>
  480.            
  481.             <p class="av-page_only">
  482.                 <label for="<?php echo $this->get_field_id('page_link_text'); ?>"><?php _e('Direct link to FB-page text:', 'avia_framework'); ?>
  483.                 <input class="widefat" id="<?php echo $this->get_field_id('page_link_text'); ?>" name="<?php echo $this->get_field_name('page_link_text'); ?>" type="text" value="<?php echo $page_link_text; ?>" /></label>
  484.             </p>
  485.  
  486.             <div class="avia_fb_likebox_upload avia-fb-banner av-widgets-upload">
  487.                 <?php echo $html->render_single_element( $banner_element );?>
  488.             </div>
  489.                
  490.             <p  class="av-page-title">
  491.                 <label for="<?php echo $this->get_field_id('page_title'); ?>"><?php _e('Facebook Page Title:', 'avia_framework'); ?>
  492.                 <input class="widefat" id="<?php echo $this->get_field_id('page_title'); ?>" name="<?php echo $this->get_field_name('page_title'); ?>" type="text" value="<?php echo $page_title; ?>" placeholder="<?php _e('Enter some info to the page', 'avia_framework'); ?>" /></label>
  493.             </p>
  494.            
  495.             <div class="avia_fb_likebox_upload avia-fb-logo av-widgets-upload">
  496.                 <?php echo $html->render_single_element( $logo_element );?>
  497.             </div>
  498.            
  499.             <p class="av-content">
  500.                 <label for="<?php echo $this->get_field_id('content'); ?>"><?php _e('Static like count:', 'avia_framework'); ?>
  501.                     <input class="widefat" id="<?php echo $this->get_field_id('content'); ?>" name="<?php echo $this->get_field_name('content'); ?>" rows="5" placeholder="<?php _e('2k+ likes', 'avia_framework'); ?>" value='<?php echo $content; ?>' />
  502.                 </label>
  503.             </p>
  504.            
  505.             <p class="av-add_info">
  506.                 <label for="<?php echo $this->get_field_id('add_info'); ?>"><?php _e('Additional Information:', 'avia_framework'); ?>
  507.                     <input class="widefat" id="<?php echo $this->get_field_id('add_info'); ?>" name="<?php echo $this->get_field_name('add_info'); ?>" rows="5" placeholder="<?php _e('Info displayed above the fake user profiles', 'avia_framework'); ?>" value='<?php echo $add_info; ?>' />
  508.                 </label>
  509.             </p>
  510.         </div>
  511.     <?php
  512.            
  513.         }
  514.     }
  515. }
  516.  
  517.  
  518.  
  519.  
  520.  
  521.  
  522.  
  523.  
  524.  
  525.  
  526. /**
  527.  * AVIA TWEETBOX
  528.  *
  529.  * Widget that creates a list of latest tweets
  530.  *
  531.  * @package AviaFramework
  532.  * @todo replace the widget system with a dynamic one, based on config files for easier widget creation
  533.  */
  534.  
  535.  
  536.  
  537. /*
  538. Twitter widget only for compatibility reasons with older themes present. no onger used since API will be shut down by twitter
  539. */
  540. if (!class_exists('avia_tweetbox'))
  541. {
  542.     class avia_tweetbox extends WP_Widget {
  543.  
  544.         function __construct() {
  545.             //Constructor
  546.             $widget_ops = array('classname' => 'tweetbox', 'description' => 'A widget to display your latest twitter messages' );
  547.             parent::__construct( 'tweetbox', THEMENAME.' Twitter Widget', $widget_ops );
  548.         }
  549.  
  550.         function widget($args, $instance) {
  551.             // prints the widget
  552.  
  553.             extract($args, EXTR_SKIP);
  554.             echo $before_widget;
  555.  
  556.             $title = empty($instance['title']) ? '' : apply_filters('widget_title', $instance['title']);
  557.             $count = empty($instance['count']) ? '' : $instance['count'];
  558.             $username = empty($instance['username']) ? '' : $instance['username'];
  559.             $exclude_replies = empty($instance['exclude_replies']) ? '' : $instance['exclude_replies'];
  560.             $time = empty($instance['time']) ? 'no' : $instance['time'];
  561.             $display_image = empty($instance['display_image']) ? 'no' : $instance['display_image'];
  562.  
  563.             if ( !empty( $title ) ) { echo $before_title . "<a href='http://twitter.com/$username/' title='".strip_tags($title)."'>".$title ."</a>". $after_title; };
  564.  
  565.             $messages = tweetbox_get_tweet($count, $username, $widget_id, $time, $exclude_replies, $display_image);
  566.             echo $messages;
  567.  
  568.             echo $after_widget;
  569.  
  570.  
  571.         }
  572.  
  573.         function update($new_instance, $old_instance) {
  574.             //save the widget
  575.             $instance = $old_instance;
  576.             foreach($new_instance as $key=>$value)
  577.             {
  578.                 $instance[$key] = strip_tags($new_instance[$key]);
  579.             }
  580.  
  581.             delete_transient(THEMENAME.'_tweetcache_id_'.$instance['username'].'_'.$this->id_base."-".$this->number);
  582.             return $instance;
  583.         }
  584.  
  585.         function form($instance) {
  586.             //widgetform in backend
  587.  
  588.             $instance = wp_parse_args( (array) $instance, array( 'title' => 'Latest Tweets', 'count' => '3', 'username' => avia_get_option('twitter') ) );
  589.             $title =            isset($instance['title']) ? strip_tags($instance['title']): "";
  590.             $count =            isset($instance['count']) ? strip_tags($instance['count']): "";
  591.             $username =         isset($instance['username']) ? strip_tags($instance['username']): "";
  592.             $exclude_replies =  isset($instance['exclude_replies']) ? strip_tags($instance['exclude_replies']): "";
  593.             $time =             isset($instance['time']) ? strip_tags($instance['time']): "";
  594.             $display_image =    isset($instance['display_image']) ? strip_tags($instance['display_image']): "";
  595.     ?>
  596.             <p>
  597.             <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:', 'avia_framework'); ?>
  598.             <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></label></p>
  599.  
  600.             <p><label for="<?php echo $this->get_field_id('username'); ?>">Enter your twitter username:
  601.             <input class="widefat" id="<?php echo $this->get_field_id('username'); ?>" name="<?php echo $this->get_field_name('username'); ?>" type="text" value="<?php echo esc_attr($username); ?>" /></label></p>
  602.  
  603.             <p>
  604.                 <label for="<?php echo $this->get_field_id('count'); ?>">How many entries do you want to display: </label>
  605.                 <select class="widefat" id="<?php echo $this->get_field_id('count'); ?>" name="<?php echo $this->get_field_name('count'); ?>">
  606.                     <?php
  607.                     $list = "";
  608.                     for ($i = 1; $i <= 20; $i++ )
  609.                     {
  610.                         $selected = "";
  611.                         if($count == $i) $selected = 'selected="selected"';
  612.  
  613.                         $list .= "<option $selected value='$i'>$i</option>";
  614.                     }
  615.                     $list .= "</select>";
  616.                     echo $list;
  617.                     ?>
  618.  
  619.  
  620.             </p>
  621.  
  622.             <p>
  623.                 <label for="<?php echo $this->get_field_id('exclude_replies'); ?>">Exclude @replies: </label>
  624.                 <select class="widefat" id="<?php echo $this->get_field_id('exclude_replies'); ?>" name="<?php echo $this->get_field_name('exclude_replies'); ?>">
  625.                     <?php
  626.                     $list = "";
  627.                     $answers = array('yes','no');
  628.                     foreach ($answers as $answer)
  629.                     {
  630.                         $selected = "";
  631.                         if($answer == $exclude_replies) $selected = 'selected="selected"';
  632.  
  633.                         $list .= "<option $selected value='$answer'>$answer</option>";
  634.                     }
  635.                     $list .= "</select>";
  636.                     echo $list;
  637.                     ?>
  638.  
  639.  
  640.             </p>
  641.  
  642.             <p>
  643.                 <label for="<?php echo $this->get_field_id('time'); ?>">Display time of tweet</label>
  644.                 <select class="widefat" id="<?php echo $this->get_field_id('time'); ?>" name="<?php echo $this->get_field_name('time'); ?>">
  645.                     <?php
  646.                     $list = "";
  647.                     $answers = array('yes','no');
  648.                     foreach ($answers as $answer)
  649.                     {
  650.                         $selected = "";
  651.                         if($answer == $time) $selected = 'selected="selected"';
  652.  
  653.                         $list .= "<option $selected value='$answer'>$answer</option>";
  654.                     }
  655.                     $list .= "</select>";
  656.                     echo $list;
  657.                     ?>
  658.  
  659.  
  660.             </p>
  661.  
  662.             <p>
  663.                 <label for="<?php echo $this->get_field_id('display_image'); ?>">Display Twitter User Avatar</label>
  664.                 <select class="widefat" id="<?php echo $this->get_field_id('display_image'); ?>" name="<?php echo $this->get_field_name('display_image'); ?>">
  665.                     <?php
  666.                     $list = "";
  667.                     $answers = array('yes','no');
  668.                     foreach ($answers as $answer)
  669.                     {
  670.                         $selected = "";
  671.                         if($answer == $display_image) $selected = 'selected="selected"';
  672.  
  673.                         $list .= "<option $selected value='$answer'>$answer</option>";
  674.                     }
  675.                     $list .= "</select>";
  676.                     echo $list;
  677.                     ?>
  678.             </p>
  679.  
  680.  
  681.  
  682.         <?php
  683.         }
  684.     }
  685. }
  686.  
  687. if(!function_exists('tweetbox_get_tweet'))
  688. {
  689.     function tweetbox_get_tweet($count, $username, $widget_id, $time='yes', $exclude_replies='yes', $avatar = 'yes')
  690.     {
  691.             $filtered_message = "";
  692.             $output = "";
  693.             $iterations = 0;
  694.  
  695.             $cache = get_transient(THEMENAME.'_tweetcache_id_'.$username.'_'.$widget_id);
  696.  
  697.             if($cache)
  698.             {
  699.                 $tweets = get_option(THEMENAME.'_tweetcache_'.$username.'_'.$widget_id);
  700.             }
  701.             else
  702.             {
  703.                 //$response = wp_remote_get( 'http://api.twitter.com/1/statuses/user_timeline.xml?screen_name='.$username );
  704.                 $response = wp_remote_get( 'http://api.twitter.com/1/statuses/user_timeline.xml?include_rts=true&screen_name='.$username );
  705.                 if (!is_wp_error($response))
  706.                 {
  707.                     $xml = @simplexml_load_string($response['body']);
  708.                     //follower: (int) $xml->status->user->followers_count
  709.  
  710.                     if( empty( $xml->error ) )
  711.                     {
  712.                         if ( isset($xml->status[0]))
  713.                         {
  714.  
  715.                             $tweets = array();
  716.                             foreach ($xml->status as $tweet)
  717.                             {
  718.                                 if($iterations == $count) break;
  719.  
  720.                                 $text = (string) $tweet->text;
  721.                                 if($exclude_replies == 'no' || ($exclude_replies == 'yes' && $text[0] != "@"))
  722.                                 {
  723.                                     $iterations++;
  724.                                     $tweets[] = array(
  725.                                         'text' => tweetbox_filter( $text ),
  726.                                         'created' =>  strtotime( $tweet->created_at ),
  727.                                         'user' => array(
  728.                                             'name' => (string)$tweet->user->name,
  729.                                             'screen_name' => (string)$tweet->user->screen_name,
  730.                                             'image' => (string)$tweet->user->profile_image_url,
  731.                                             'utc_offset' => (int) $tweet->user->utc_offset[0],
  732.                                             'follower' => (int) $tweet->user->followers_count
  733.  
  734.                                         ));
  735.                                 }
  736.                             }
  737.  
  738.                             set_transient(THEMENAME.'_tweetcache_id_'.$username.'_'.$widget_id, 'true', 60*30);
  739.                             update_option(THEMENAME.'_tweetcache_'.$username.'_'.$widget_id, $tweets);
  740.                         }
  741.                     }
  742.                 }
  743.             }
  744.  
  745.  
  746.  
  747.             if(!isset($tweets[0]))
  748.             {
  749.                 $tweets = get_option(THEMENAME.'_tweetcache_'.$username.'_'.$widget_id);
  750.             }
  751.  
  752.             if(isset($tweets[0]))
  753.             {
  754.                 $time_format = apply_filters( 'avia_widget_time', get_option('date_format')." - ".get_option('time_format'), 'tweetbox' );
  755.  
  756.                 foreach ($tweets as $message)
  757.                 {
  758.                     $output .= '<li class="tweet">';
  759.                     if($avatar == "yes") $output .= '<div class="tweet-thumb"><a href="http://twitter.com/'.$username.'" title=""><img src="'.$message['user']['image'].'" alt="" /></a></div>';
  760.                     $output .= '<div class="tweet-text avatar_'.$avatar.'">'.$message['text'];
  761.                     if($time == "yes") $output .= '<div class="tweet-time">'.date_i18n( $time_format, $message['created'] + $message['user']['utc_offset']).'</div>';
  762.                     $output .= '</div></li>';
  763.                 }
  764.             }
  765.  
  766.  
  767.             if($output != "")
  768.             {
  769.                 $filtered_message = "<ul class='tweets'>$output</ul>";
  770.             }
  771.             else
  772.             {
  773.                 $filtered_message = "<ul class='tweets'><li>No public Tweets found</li></ul>";
  774.             }
  775.  
  776.             return $filtered_message;
  777.     }
  778. }
  779.  
  780. if(!function_exists('tweetbox_filter'))
  781. {
  782.     function tweetbox_filter($text) {
  783.         // Props to Allen Shaw & webmancers.com & Michael Voigt
  784.         $text = preg_replace('/\b([a-zA-Z]+:\/\/[\w_.\-]+\.[a-zA-Z]{2,6}[\/\w\-~.?=&%#+$*!]*)\b/i',"<a href=\"$1\" class=\"twitter-link\">$1</a>", $text);
  785.         $text = preg_replace('/\b(?<!:\/\/)(www\.[\w_.\-]+\.[a-zA-Z]{2,6}[\/\w\-~.?=&%#+$*!]*)\b/i',"<a href=\"http://$1\" class=\"twitter-link\">$1</a>", $text);
  786.         $text = preg_replace("/\b([a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]*\@[a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]{2,6})\b/i","<a href=\"mailto://$1\" class=\"twitter-link\">$1</a>", $text);
  787.         $text = preg_replace("/#([\p{L}\p{Mn}]+)/u", "<a class=\"twitter-link\" href=\"http://search.twitter.com/search?q=\\1\">#\\1</a>", $text);
  788.         $text = preg_replace("/@([\p{L}\p{Mn}]+)/u", "<a class=\"twitter-link\" href=\"http://twitter.com/\\1\">@\\1</a>", $text);
  789.  
  790.         return $text;
  791.     }
  792. }
  793.  
  794.  
  795.  
  796.  
  797.  
  798.  
  799.  
  800.  
  801.  
  802. /**
  803.  * AVIA NEWSBOX
  804.  *
  805.  * Widget that creates a list of latest news entries
  806.  *
  807.  * @package AviaFramework
  808.  * @todo replace the widget system with a dynamic one, based on config files for easier widget creation
  809.  */
  810.  
  811. if (!class_exists('avia_newsbox'))
  812. {
  813.     class avia_newsbox extends WP_Widget {
  814.  
  815.         var $avia_term = '';
  816.         var $avia_post_type = '';
  817.         var $avia_new_query = '';
  818.  
  819.         function __construct()
  820.         {
  821.             $widget_ops = array('classname' => 'newsbox', 'description' => __('A Sidebar widget to display latest post entries in your sidebar', 'avia_framework') );
  822.  
  823.             parent::__construct( 'newsbox', THEMENAME.' Latest News', $widget_ops );
  824.         }
  825.  
  826.         function widget($args, $instance)
  827.         {
  828.             global $avia_config;
  829.  
  830.             extract($args, EXTR_SKIP);
  831.             echo $before_widget;
  832.  
  833.             $title = empty($instance['title']) ? '' : apply_filters('widget_title', $instance['title']);
  834.             $count = empty($instance['count']) ? '' : $instance['count'];
  835.             $cat = empty($instance['cat']) ? '' : $instance['cat'];
  836.             $excerpt = empty($instance['excerpt']) ? '' : $instance['excerpt'];
  837.             $image_size = isset($avia_config['widget_image_size']) ? $avia_config['widget_image_size'] : 'widget';
  838.  
  839.             if ( !empty( $title ) ) { echo $before_title . $title . $after_title; };
  840.  
  841.  
  842.             if(empty($this->avia_term))
  843.             {
  844.                 $additional_loop = new WP_Query("cat=".$cat."&posts_per_page=".$count);
  845.             }
  846.             else
  847.             {
  848.                 $catarray = explode(',', $cat);
  849.  
  850.  
  851.                 if(empty($catarray[0]))
  852.                 {
  853.                     $new_query = array("posts_per_page"=>$count,"post_type"=>$this->avia_post_type);
  854.                 }
  855.                 else
  856.                 {
  857.                     if($this->avia_new_query)
  858.                     {
  859.                         $new_query = $this->avia_new_query;
  860.                     }
  861.                     else
  862.                     {
  863.                         $new_query = array( "posts_per_page"=>$count, 'tax_query' => array(
  864.                                                         array( 'taxonomy' => $this->avia_term,
  865.                                                                'field' => 'id',
  866.                                                                'terms' => explode(',', $cat),
  867.                                                                'operator' => 'IN')
  868.                                                               )
  869.                                                         );
  870.                     }
  871.                 }
  872.  
  873.                 $additional_loop = new WP_Query($new_query);
  874.             }
  875.  
  876.             if($additional_loop->have_posts()) :
  877.  
  878.  
  879.  
  880.             echo '<ul class="news-wrap image_size_'.$image_size.'">';
  881.             while ($additional_loop->have_posts()) : $additional_loop->the_post();
  882.  
  883.             $format = "";
  884.             if(empty($this->avia_post_type))    $format = $this->avia_post_type;
  885.             if(empty($format))                  $format = get_post_format();
  886.             if(empty($format))                  $format = 'standard';
  887.            
  888.             $the_id = get_the_ID();
  889.             $link = get_post_meta( $the_id  ,'_portfolio_custom_link', true) != "" ? get_post_meta( $the_id ,'_portfolio_custom_link_url', true) : get_permalink();
  890.            
  891.            
  892.             echo '<li class="news-content post-format-'.$format.'">';
  893.  
  894.             //check for preview images:
  895.             $image = "";
  896.  
  897.             if(!current_theme_supports('force-post-thumbnails-in-widget'))
  898.             {
  899.                 $slides = avia_post_meta(get_the_ID(), 'slideshow', true);
  900.  
  901.                 if( $slides != "" && !empty( $slides[0]['slideshow_image'] ) )
  902.                 {
  903.                     $image = avia_image_by_id($slides[0]['slideshow_image'], $image_size, 'image');
  904.                 }
  905.             }
  906.  
  907.             if(current_theme_supports( 'post-thumbnails' ) && !$image )
  908.             {
  909.                 $image = get_the_post_thumbnail( $the_id, $image_size );
  910.             }
  911.  
  912.             $time_format = apply_filters( 'avia_widget_time', get_option('date_format')." - ".get_option('time_format'), 'avia_newsbox' );
  913.  
  914.  
  915.             echo "<a class='news-link' title='".get_the_title()."' href='".$link."'>";
  916.  
  917.             $nothumb = (!$image) ? 'no-news-thumb' : '';
  918.  
  919.             echo "<span class='news-thumb $nothumb'>";
  920.             echo $image;
  921.             echo "</span>";
  922.             if(empty($avia_config['widget_image_size']) || 'display title and excerpt' != $excerpt)
  923.             {
  924.                 echo "<strong class='news-headline'>".get_the_title();
  925.                
  926.                 if($time_format)
  927.                 {
  928.                     echo "<span class='news-time'>".get_the_time($time_format)."</span>";  
  929.                 }
  930.                
  931.                 echo "</strong>";
  932.             }
  933.             echo "</a>";
  934.  
  935.             if( 'display title and excerpt' == $excerpt )
  936.             {
  937.                 echo "<div class='news-excerpt'>";
  938.  
  939.                 if(!empty($avia_config['widget_image_size']))
  940.                 {
  941.                     echo "<a class='news-link-inner' title='".get_the_title()."' href='".$link."'>";
  942.                     echo "<strong class='news-headline'>".get_the_title()."</strong>";
  943.                     echo "</a>";
  944.                     if($time_format)
  945.                     {
  946.                         echo "<span class='news-time'>".get_the_time($time_format)."</span>";  
  947.                     }
  948.  
  949.                 }
  950.                 the_excerpt();
  951.                 echo "</div>";
  952.             }
  953.  
  954.             echo '</li>';
  955.  
  956.  
  957.             endwhile;
  958.             echo "</ul>";
  959.             wp_reset_postdata();
  960.             endif;
  961.  
  962.  
  963.             echo $after_widget;
  964.  
  965.         }
  966.  
  967.  
  968.         function update($new_instance, $old_instance)
  969.         {
  970.             $instance = $old_instance;
  971.             $instance['title'] = strip_tags($new_instance['title']);
  972.             $instance['count'] = strip_tags($new_instance['count']);
  973.             $instance['excerpt'] = strip_tags($new_instance['excerpt']);
  974.             $instance['cat'] = implode(',',$new_instance['cat']);
  975.             return $instance;
  976.         }
  977.  
  978.  
  979.  
  980.         function form($instance)
  981.         {
  982.             $instance = wp_parse_args( (array) $instance, array( 'title' => '', 'count' => '', 'cat' => '', 'excerpt'=>'' ) );
  983.             $title = strip_tags($instance['title']);
  984.             $count = strip_tags($instance['count']);
  985.             $excerpt = strip_tags($instance['excerpt']);
  986.  
  987.  
  988.             $elementCat = array("name"  => __("Which categories should be used for the portfolio?", 'avia_framework'),
  989.                                 "desc"  => __("You can select multiple categories here", 'avia_framework'),
  990.                                 "id"    => $this->get_field_name('cat')."[]",
  991.                                 "type"  => "select",
  992.                                 "std"   => strip_tags($instance['cat']),
  993.                                 "class" => "",
  994.                                 "multiple"=>6,
  995.                                 "subtype" => "cat");
  996.             //check if a different taxonomy than the default is set
  997.             if(!empty($this->avia_term))
  998.             {
  999.                 $elementCat['taxonomy'] = $this->avia_term;
  1000.             }
  1001.  
  1002.  
  1003.  
  1004.  
  1005.             $html = new avia_htmlhelper();
  1006.  
  1007.     ?>
  1008.             <p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:', 'avia_framework'); ?>
  1009.             <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></label></p>
  1010.  
  1011.             <p>
  1012.                 <label for="<?php echo $this->get_field_id('count'); ?>"><?php _e('How many entries do you want to display: ', 'avia_framework'); ?></label>
  1013.                 <select class="widefat" id="<?php echo $this->get_field_id('count'); ?>" name="<?php echo $this->get_field_name('count'); ?>">
  1014.                     <?php
  1015.                     $list = "";
  1016.                     for ($i = 1; $i <= 20; $i++ )
  1017.                     {
  1018.                         $selected = "";
  1019.                         if($count == $i) $selected = 'selected="selected"';
  1020.  
  1021.                         $list .= "<option $selected value='$i'>$i</option>";
  1022.                     }
  1023.                     $list .= "</select>";
  1024.                     echo $list;
  1025.                     ?>
  1026.  
  1027.  
  1028.             </p>
  1029.  
  1030.             <p><label for="<?php echo $this->get_field_id('cat'); ?>"><?php _e('Choose the categories you want to display (multiple selection possible):', 'avia_framework'); ?>
  1031.             <?php echo $html->select($elementCat); ?>
  1032.             </label></p>
  1033.  
  1034.             <p>
  1035.                 <label for="<?php echo $this->get_field_id('excerpt'); ?>"><?php _e('Display title only or title &amp; excerpt', 'avia_framework'); ?></label>
  1036.                 <select class="widefat" id="<?php echo $this->get_field_id('excerpt'); ?>" name="<?php echo $this->get_field_name('excerpt'); ?>">
  1037.                     <?php
  1038.                     $list = "";
  1039.                     $answers = array(
  1040.                                 'show title only'           =>  __( 'show title only', 'avia_framework' ),
  1041.                                 'display title and excerpt' =>  __('display title and excerpt', 'avia_framework')
  1042.                                 );
  1043.                    
  1044.                     foreach ( $answers as $key => $answer )
  1045.                     {
  1046.                         $selected = "";
  1047.                         if( $key == $excerpt ) $selected = 'selected="selected"';
  1048.  
  1049.                         $list .= "<option $selected value='$key'>$answer</option>";
  1050.                     }
  1051.                     $list .= "</select>";
  1052.                     echo $list;
  1053.                     ?>
  1054.  
  1055.  
  1056.             </p>
  1057.  
  1058.  
  1059.     <?php
  1060.         }
  1061.     }
  1062. }
  1063.  
  1064.  
  1065. /**
  1066.  * AVIA PORTFOLIOBOX
  1067.  *
  1068.  * Widget that creates a list of latest portfolio entries. Basically the same widget as the newsbox with some minor modifications, therefore it just extends the Newsbox
  1069.  *
  1070.  * @package AviaFramework
  1071.  * @todo replace the widget system with a dynamic one, based on config files for easier widget creation
  1072.  */
  1073.  
  1074. if (!class_exists('avia_portfoliobox'))
  1075. {
  1076.     class avia_portfoliobox extends avia_newsbox
  1077.     {
  1078.         function __construct()
  1079.         {
  1080.             $this->avia_term = 'portfolio_entries';
  1081.             $this->avia_post_type = 'portfolio';
  1082.             $this->avia_new_query = ''; //set a custom query here
  1083.  
  1084.  
  1085.             $widget_ops = array('classname' => 'newsbox', 'description' => __('A Sidebar widget to display latest portfolio entries in your sidebar', 'avia_framework') );
  1086.  
  1087.             WP_Widget::__construct( 'portfoliobox', THEMENAME.' Latest Portfolio', $widget_ops );
  1088.         }
  1089.     }
  1090. }
  1091.  
  1092.  
  1093.  
  1094. /**
  1095.  * AVIA SOCIALCOUNT
  1096.  *
  1097.  * Widget that retrieves, stores and displays the number of twitter and rss followers
  1098.  *
  1099.  * @package AviaFramework
  1100.  * @todo replace the widget system with a dynamic one, based on config files for easier widget creation
  1101.  */
  1102.  
  1103. if (!class_exists('avia_socialcount'))
  1104. {
  1105.     class avia_socialcount extends WP_Widget {
  1106.  
  1107.         function __construct() {
  1108.             //Constructor
  1109.             $widget_ops = array('classname' => 'avia_socialcount', 'description' => __('A widget to display a link to your twitter profile and rss feed', 'avia_framework') );
  1110.             parent::__construct( 'avia_socialcount', THEMENAME.' RSS Link and Twitter Account', $widget_ops );
  1111.         }
  1112.  
  1113.         function widget($args, $instance) {
  1114.             // prints the widget
  1115.  
  1116.             extract($args, EXTR_SKIP);
  1117.             $twitter = empty($instance['twitter']) ? '' : $instance['twitter'];
  1118.             $rss     = empty($instance['rss'])     ? '' : $instance['rss'];
  1119.             $rss = preg_replace('!https?:\/\/feeds.feedburner.com\/!','',$rss);
  1120.  
  1121.  
  1122.             if(!empty($twitter) || !empty($rss))
  1123.             {
  1124.                 $addClass = "asc_multi_count";
  1125.                 if(!isset($twitter) || !isset($rss)) $addClass = 'asc_single_count';
  1126.  
  1127.                 echo $before_widget;
  1128.                 $output = "";
  1129.                 if(!empty($twitter))
  1130.                 {
  1131.                     $link = 'http://twitter.com/'.$twitter.'/';
  1132.                     $before = apply_filters('avf_social_widget', "", 'twitter');
  1133.                     $output .= "<a href='$link' class='asc_twitter $addClass'>{$before}<strong class='asc_count'>".__('Follow','avia_framework')."</strong><span>".__('on Twitter','avia_framework')."</span></a>";
  1134.                    
  1135.                 }
  1136.  
  1137.                 if($rss)
  1138.                 {
  1139.                     $output .= "<a href='$rss' class='asc_rss $addClass'>".apply_filters('avf_social_widget',"", 'rss')."<strong class='asc_count'>".__('Subscribe','avia_framework')."</strong><span>".__('to RSS Feed','avia_framework')."</span></a>";
  1140.                 }
  1141.  
  1142.                 echo $output;
  1143.                 echo $after_widget;
  1144.             }
  1145.         }
  1146.  
  1147.  
  1148.  
  1149.         function update($new_instance, $old_instance) {
  1150.             //save the widget
  1151.             $instance = $old_instance;
  1152.             foreach($new_instance as $key=>$value)
  1153.             {
  1154.                 $instance[$key] = strip_tags($new_instance[$key]);
  1155.             }
  1156.  
  1157.             return $instance;
  1158.         }
  1159.  
  1160.         function form($instance) {
  1161.             //widgetform in backend
  1162.  
  1163.             $instance = wp_parse_args( (array) $instance, array('rss' => avia_get_option('feedburner'), 'twitter' => avia_get_option('twitter') ) );
  1164.             $twitter = empty($instance['twitter']) ? '' :  strip_tags($instance['twitter']);
  1165.             $rss     = empty($instance['rss'])     ? '' :  strip_tags($instance['rss']);
  1166.     ?>
  1167.             <p>
  1168.             <label for="<?php echo $this->get_field_id('twitter'); ?>"><?php _e('Twitter Username:', 'avia_framework'); ?>
  1169.             <input class="widefat" id="<?php echo $this->get_field_id('twitter'); ?>" name="<?php echo $this->get_field_name('twitter'); ?>" type="text" value="<?php echo esc_attr($twitter); ?>" /></label></p>
  1170.  
  1171.             <p><label for="<?php echo $this->get_field_id('rss'); ?>"><?php _e('Enter your feed url:', 'avia_framework'); ?>
  1172.             <input class="widefat" id="<?php echo $this->get_field_id('rss'); ?>" name="<?php echo $this->get_field_name('rss'); ?>" type="text" value="<?php echo esc_attr($rss); ?>" /></label></p>
  1173.  
  1174.  
  1175.  
  1176.         <?php
  1177.         }
  1178.     }
  1179. }
  1180.  
  1181.  
  1182.  
  1183.  
  1184. /**
  1185.  * AVIA ADVERTISING WIDGET
  1186.  *
  1187.  * Widget that retrieves, stores and displays the number of twitter and rss followers
  1188.  *
  1189.  * @package AviaFramework
  1190.  * @todo replace the widget system with a dynamic one, based on config files for easier widget creation
  1191.  */
  1192.  
  1193.  
  1194. //multiple images
  1195. if (!class_exists('avia_partner_widget'))
  1196. {
  1197.     class avia_partner_widget extends WP_Widget {
  1198.  
  1199.         function __construct() {
  1200.  
  1201.             $this->add_cont = 2;
  1202.             //Constructor
  1203.             $widget_ops = array('classname' => 'avia_partner_widget', 'description' => __('An advertising widget that displays 2 images with 125 x 125 px in size', 'avia_framework') );
  1204.             parent::__construct( 'avia_partner_widget', THEMENAME.' Advertising Area', $widget_ops );
  1205.         }
  1206.  
  1207.         function widget($args, $instance)
  1208.         {
  1209.             extract($args, EXTR_SKIP);
  1210.             echo $before_widget;
  1211.  
  1212.             global $kriesiaddwidget, $firsttitle;
  1213.             $kriesiaddwidget ++;
  1214.  
  1215.             $title = empty($instance['title']) ? '' : apply_filters('widget_title', $instance['title']);
  1216.             $image_url = empty($instance['image_url']) ? '<span class="avia_parnter_empty"><span>'.__('Advertise here','avia_framework').'</span></span>' : '<img class="rounded" src="'.$instance['image_url'].'" title="'.$title.'" alt="'.$title.'"/>';
  1217.             $ref_url = empty($instance['ref_url']) ? '#' : apply_filters('widget_comments_title', $instance['ref_url']);
  1218.             $image_url2 = empty($instance['image_url2']) ? '<span class="avia_parnter_empty"><span>'.__('Advertise here','avia_framework').'</span></span>' : '<img class="rounded" src="'.$instance['image_url2'].'" title="'.$title.'" alt="'.$title.'"/>';
  1219.             $ref_url2 = empty($instance['ref_url2']) ? '#' : apply_filters('widget_comments_title', $instance['ref_url2']);
  1220.  
  1221.             if ( !empty( $title ) ) { echo $before_title . $title . $after_title; };
  1222.             echo '<a target="_blank" href="'.$ref_url.'" class="preloading_background  avia_partner1 link_list_item'.$kriesiaddwidget.' '.$firsttitle.'" >'.$image_url.'</a>';
  1223.             if($this->add_cont == 2) echo '<a target="_blank" href="'.$ref_url2.'" class="preloading_background avia_partner2 link_list_item'.$kriesiaddwidget.' '.$firsttitle.'" >'.$image_url2.'</a>';
  1224.             echo $after_widget;
  1225.  
  1226.             if($title == '')
  1227.             {
  1228.                 $firsttitle = 'no_top_margin';
  1229.             }
  1230.  
  1231.         }
  1232.  
  1233.  
  1234.         function update($new_instance, $old_instance) {
  1235.             //save the widget
  1236.             $instance = $old_instance;
  1237.             foreach($new_instance as $key=>$value)
  1238.             {
  1239.                 $instance[$key] = strip_tags($new_instance[$key]);
  1240.             }
  1241.             return $instance;
  1242.         }
  1243.  
  1244.  
  1245.  
  1246.         function form($instance)
  1247.         {
  1248.             $instance = wp_parse_args( (array) $instance, array( 'title' => '', 'image_url' => '', 'ref_url' => '', 'image_url2' => '', 'ref_url2' => '' ) );
  1249.             $title = strip_tags($instance['title']);
  1250.             $image_url = strip_tags($instance['image_url']);
  1251.             $ref_url = strip_tags($instance['ref_url']);
  1252.             $image_url2 = strip_tags($instance['image_url2']);
  1253.             $ref_url2 = strip_tags($instance['ref_url2']);
  1254.     ?>
  1255.             <p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:', 'avia_framework'); ?>
  1256.             <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></label></p>
  1257.  
  1258.             <p><label for="<?php echo $this->get_field_id('image_url'); ?>"><?php _e('Image URL:', 'avia_framework'); ?> <?php if($this->add_cont == 2) echo "(125px * 125px):"; ?>
  1259.             <input class="widefat" id="<?php echo $this->get_field_id('image_url'); ?>" name="<?php echo $this->get_field_name('image_url'); ?>" type="text" value="<?php echo esc_attr($image_url); ?>" /></label></p>
  1260.  
  1261.             <p><label for="<?php echo $this->get_field_id('ref_url'); ?>"><?php _e('Referal URL:', 'avia_framework'); ?>
  1262.             <input class="widefat" id="<?php echo $this->get_field_id('ref_url'); ?>" name="<?php echo $this->get_field_name('ref_url'); ?>" type="text" value="<?php echo esc_attr($ref_url); ?>" /></label></p>
  1263.  
  1264.             <?php if($this->add_cont == 2)
  1265.             { ?>
  1266.  
  1267.                     <p><label for="<?php echo $this->get_field_id('image_url2'); ?>"><?php _e('Image URL 2: (125px * 125px):', 'avia_framework'); ?>
  1268.             <input class="widefat" id="<?php echo $this->get_field_id('image_url2'); ?>" name="<?php echo $this->get_field_name('image_url2'); ?>" type="text" value="<?php echo esc_attr($image_url2); ?>" /></label></p>
  1269.  
  1270.             <p><label for="<?php echo $this->get_field_id('ref_url2'); ?>"><?php _e('Referal URL 2:', 'avia_framework'); ?>
  1271.             <input class="widefat" id="<?php echo $this->get_field_id('ref_url2'); ?>" name="<?php echo $this->get_field_name('ref_url2'); ?>" type="text" value="<?php echo esc_attr($ref_url2); ?>" /></label></p>
  1272.  
  1273.             <?php }?>
  1274.  
  1275.     <?php
  1276.         }
  1277.     }
  1278. }
  1279.  
  1280.  
  1281. if (!class_exists('avia_one_partner_widget'))
  1282. {
  1283.     //one image
  1284.     class avia_one_partner_widget extends avia_partner_widget
  1285.     {
  1286.         function __construct()
  1287.         {
  1288.  
  1289.             $this->add_cont = 1;
  1290.  
  1291.             $widget_ops = array('classname' => 'avia_one_partner_widget', 'description' => __('An advertising widget that displays 1 big image', 'avia_framework') );
  1292.  
  1293.             parent::__construct( 'avia_one_partner_widget', THEMENAME.' Big Advertising Area', $widget_ops );
  1294.         }
  1295.     }
  1296. }
  1297.  
  1298.  
  1299.  
  1300. /**
  1301.  * AVIA COMBO WIDGET
  1302.  *
  1303.  * Widget that retrieves, stores and displays the number of twitter and rss followers
  1304.  *
  1305.  * @package AviaFramework
  1306.  * @todo replace the widget system with a dynamic one, based on config files for easier widget creation
  1307.  */
  1308.  
  1309. if (!class_exists('avia_combo_widget'))
  1310. {
  1311.     class avia_combo_widget extends WP_Widget {
  1312.  
  1313.         function __construct() {
  1314.             //Constructor
  1315.             $widget_ops = array('classname' => 'avia_combo_widget', 'description' => __('A widget that displays your popular posts, recent posts, recent comments and a tagcloud', 'avia_framework') );
  1316.             parent::__construct( 'avia_combo_widget', THEMENAME.' Combo Widget', $widget_ops );
  1317.         }
  1318.  
  1319.         function widget($args, $instance)
  1320.         {
  1321.             // prints the widget
  1322.  
  1323.             extract($args, EXTR_SKIP);
  1324.             $posts = empty($instance['count']) ? 4 : $instance['count'];
  1325.  
  1326.             echo $before_widget;
  1327.             echo "<div class='tabcontainer border_tabs top_tab tab_initial_open tab_initial_open__1'>";
  1328.  
  1329.             echo '<div class="tab first_tab active_tab widget_tab_popular"><span>'.__('Popular', 'avia_framework').'</span></div>';
  1330.             echo "<div class='tab_content active_tab_content'>";
  1331.             avia_get_post_list('cat=&orderby=comment_count&posts_per_page='.$posts);
  1332.             echo "</div>";
  1333.  
  1334.             echo '<div class="tab widget_tab_recent"><span>'.__('Recent', 'avia_framework').'</span></div>';
  1335.             echo "<div class='tab_content'>";
  1336.             avia_get_post_list('showposts='. $posts .'&orderby=post_date&order=desc');
  1337.             echo "</div>";
  1338.  
  1339.             echo '<div class="tab widget_tab_comments"><span>'.__('Comments', 'avia_framework').'</span></div>';
  1340.             echo "<div class='tab_content'>";
  1341.             avia_get_comment_list( array('number' => $posts, 'status' => 'approve', 'order' => 'DESC') );
  1342.             echo "</div>";
  1343.  
  1344.             echo '<div class="tab last_tab widget_tab_tags"><span>'.__('Tags', 'avia_framework').'</span></div>';
  1345.             echo "<div class='tab_content tagcloud'>";
  1346.             wp_tag_cloud('smallest=12&largest=12&unit=px');
  1347.             echo "</div>";
  1348.  
  1349.             echo "</div>";
  1350.             echo $after_widget;
  1351.         }
  1352.  
  1353.  
  1354.         function update($new_instance, $old_instance)
  1355.         {
  1356.             $instance = $old_instance;
  1357.             foreach($new_instance as $key=>$value)
  1358.             {
  1359.                 $instance[$key] = strip_tags($new_instance[$key]);
  1360.             }
  1361.  
  1362.             return $instance;
  1363.         }
  1364.  
  1365.         function form($instance) {
  1366.             //widgetform in backend
  1367.  
  1368.             $instance = wp_parse_args( (array) $instance, array('count' => 4) );
  1369.             if(!is_numeric($instance['count'])) $instance['count'] = 4;
  1370.  
  1371.     ?>
  1372.             <p>
  1373.             <label for="<?php echo $this->get_field_id('count'); ?>"><?php _e('Number of posts you want to display:', 'avia_framework'); ?>
  1374.             <input class="widefat" id="<?php echo $this->get_field_id('count'); ?>" name="<?php echo $this->get_field_name('count'); ?>" type="text" value="<?php echo esc_attr($instance['count']); ?>" /></label></p>
  1375.  
  1376.  
  1377.         <?php
  1378.         }
  1379.     }
  1380. }
  1381.  
  1382. /*-----------------------------------------------------------------------------------
  1383. get posts posts
  1384. -----------------------------------------------------------------------------------*/
  1385. if (!function_exists('avia_get_post_list'))
  1386. {
  1387.     function avia_get_post_list( $avia_new_query , $excerpt = false)
  1388.     {
  1389.         global $avia_config;
  1390.         $image_size = isset($avia_config['widget_image_size']) ? $avia_config['widget_image_size'] : 'widget';
  1391.         $additional_loop = new WP_Query($avia_new_query);
  1392.  
  1393.         if($additional_loop->have_posts()) :
  1394.         echo '<ul class="news-wrap">';
  1395.         while ($additional_loop->have_posts()) : $additional_loop->the_post();
  1396.  
  1397.         $format = "";
  1398.         if(get_post_type() != 'post')       $format = get_post_type();
  1399.         if(empty($format))                  $format = get_post_format();
  1400.         if(empty($format))                  $format = 'standard';
  1401.  
  1402.         echo '<li class="news-content post-format-'.$format.'">';
  1403.  
  1404.         //check for preview images:
  1405.         $image = "";
  1406.  
  1407.         if(!current_theme_supports('force-post-thumbnails-in-widget'))
  1408.             {
  1409.             $slides = avia_post_meta(get_the_ID(), 'slideshow');
  1410.  
  1411.             if( $slides != "" && !empty( $slides[0]['slideshow_image'] ) )
  1412.             {
  1413.                 $image = avia_image_by_id($slides[0]['slideshow_image'], 'widget', 'image');
  1414.             }
  1415.         }
  1416.  
  1417.         if(!$image && current_theme_supports( 'post-thumbnails' ))
  1418.         {
  1419.             $image = get_the_post_thumbnail( get_the_ID(), $image_size );
  1420.         }
  1421.  
  1422.         $time_format = apply_filters( 'avia_widget_time', get_option('date_format')." - ".get_option('time_format'), 'avia_get_post_list' );
  1423.  
  1424.         $nothumb = (!$image) ? 'no-news-thumb' : '';
  1425.  
  1426.         echo "<a class='news-link' title='".get_the_title()."' href='".get_permalink()."'>";
  1427.         echo "<span class='news-thumb $nothumb'>";
  1428.         echo $image;
  1429.         echo "</span>";
  1430.         echo "<strong class='news-headline'>".avia_backend_truncate(get_the_title(), 55," ");
  1431.         echo "<span class='news-time'>".get_the_time($time_format)."</span>";
  1432.         echo "</strong>";
  1433.         echo "</a>";
  1434.  
  1435.         if('display title and excerpt' == $excerpt)
  1436.         {
  1437.             echo "<div class='news-excerpt'>";
  1438.             the_excerpt();
  1439.             echo "</div>";
  1440.         }
  1441.  
  1442.         echo '</li>';
  1443.  
  1444.  
  1445.         endwhile;
  1446.         echo "</ul>";
  1447.         wp_reset_postdata();
  1448.         endif;
  1449.     }
  1450. }
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456. if (!function_exists('avia_get_comment_list'))
  1457. {
  1458.  
  1459.     function avia_get_comment_list($avia_new_query)
  1460.     {
  1461.         $time_format = apply_filters( 'avia_widget_time', get_option('date_format')." - ".get_option('time_format'), 'avia_get_comment_list' );
  1462.  
  1463.         global $avia_config;
  1464.        
  1465.        
  1466.         $comments = get_comments($avia_new_query);
  1467.  
  1468.         if(!empty($comments)) :
  1469.         echo '<ul class="news-wrap">';
  1470.         foreach($comments as $comment)
  1471.         {
  1472.             if ($comment->comment_author != 'ActionScheduler')
  1473.             {
  1474.             $gravatar_alt = esc_html($comment->comment_author);
  1475.             echo '<li class="news-content">';
  1476.             echo "<a class='news-link' title='".get_the_title($comment->comment_post_ID)."' href='".get_comment_link($comment)."'>";
  1477.             echo "<span class='news-thumb'>";
  1478.             echo get_avatar($comment,'48', '', $gravatar_alt);
  1479.             echo "</span>";
  1480.             echo "<strong class='news-headline'>".avia_backend_truncate($comment->comment_content, 55," ");
  1481.            
  1482.             if($time_format)
  1483.             {
  1484.                 echo "<span class='news-time'>".get_comment_date($time_format, $comment->comment_ID)." ".__('by','avia_framework')." ".$comment->comment_author."</span>";
  1485.             }
  1486.             echo "</strong>";
  1487.             echo "</a>";
  1488.             echo '</li>';
  1489.             }
  1490.         }
  1491.         echo "</ul>";
  1492.         wp_reset_postdata();
  1493.         endif;
  1494.     }
  1495. }
  1496.  
  1497.  
  1498.  
  1499. /*
  1500.     Google Maps Widget
  1501.  
  1502.     Copyright 2009  Clark Nikdel Powell  (email : [email protected])
  1503.  
  1504.     This program is free software; you can redistribute it and/or modify
  1505.     it under the terms of the GNU General Public License as published by
  1506.     the Free Software Foundation; either version 2 of the License, or
  1507.     (at your option) any later version.
  1508.  
  1509.     This program is distributed in the hope that it will be useful,
  1510.     but WITHOUT ANY WARRANTY; without even the implied warranty of
  1511.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  1512.     GNU General Public License for more details.
  1513.  
  1514.     You should have received a copy of the GNU General Public License
  1515.     along with this program; if not, write to the Free Software
  1516.     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  1517. */
  1518.  
  1519. if( ! class_exists('avia_google_maps') )
  1520. {
  1521.     class avia_google_maps extends Avia_Widget
  1522.     {
  1523.  
  1524.         /**
  1525.          *
  1526.          */
  1527.         public function __construct()
  1528.         {
  1529.             $widget_ops = array(
  1530.                                 'classname'     => 'avia_google_maps',
  1531.                                 'description'   => __( 'Add a google map to your blog or site', 'avia_framework' )
  1532.                             );
  1533.            
  1534.             parent::__construct( 'avia_google_maps', THEMENAME.' Google Maps Widget', $widget_ops );
  1535.            
  1536. //            add_action( 'admin_enqueue_scripts', array( $this,'handler_print_google_maps_scripts' ) );
  1537.         }
  1538.        
  1539.        
  1540.         /**
  1541.          * @since 4.3.2
  1542.          */
  1543.         public function __destruct()
  1544.         {
  1545.             parent::__destruct();
  1546.         }
  1547.        
  1548.         /**
  1549.          *
  1550.          * @since 4.3.2
  1551.          * @param array $instance
  1552.          * @return array
  1553.          */
  1554.         protected function parse_args_instance( array $instance )
  1555.         {
  1556.             $SGMoptions = get_option( 'SGMoptions', array() ); // get options defined in admin page ????
  1557.             $SGMoptions =  wp_parse_args( $SGMoptions, array(
  1558.                                             'zoom'              =>  '15',           // 1 - 19
  1559.                                             'type'              =>  'ROADMAP',      // ROADMAP, SATELLITE, HYBRID, TERRAIN
  1560.                                             'content'           =>  '',
  1561.                                         ) );
  1562.            
  1563.             $new_instance = wp_parse_args( $instance, array(
  1564.                                             'title'             =>  '',
  1565.                                             'lat'               =>  '0',
  1566.                                             'lng'               =>  '0',
  1567.                                             'zoom'              =>  $SGMoptions['zoom'],
  1568.                                             'type'              =>  $SGMoptions['type'],
  1569.                                             'directionsto'      =>  '',
  1570.                                             'content'           =>  $SGMoptions['content'],
  1571.                                             'width'             =>  '',
  1572.                                             'height'            =>  '',
  1573.                                             'street-address'    =>  '',
  1574.                                             'city'              =>  '',
  1575.                                             'state'             =>  '',
  1576.                                             'postcode'          =>  '',
  1577.                                             'country'           =>  '',
  1578.                                             'icon'              =>  '',
  1579.                                             'google_link'       =>  '',
  1580.                                             'confirm_button'    =>  __( 'Click to load Google Maps', 'avia_framework' ),
  1581.                                             'page_link_text'    =>  __( 'Open Google Maps in a new window', 'avia_framework' ),
  1582.                                             'google_fallback'   =>  ''
  1583.                                         ) );
  1584.            
  1585.             return $new_instance;
  1586.         }
  1587.        
  1588.  
  1589.         /**
  1590.          * Output the content of the widget
  1591.          * @param array $args
  1592.          * @param array $instance
  1593.          */
  1594.         public function widget( $args, $instance )
  1595.         {
  1596.             $instance = $this->parse_args_instance( $instance );
  1597.             $fields = $this->get_field_names();
  1598.            
  1599.             foreach( $instance as $key => $value )
  1600.             {
  1601.                 if( in_array( $key, $fields ) )
  1602.                 {
  1603.                     $instance[ $key ] = esc_attr( $value );
  1604.                 }
  1605.             }
  1606.            
  1607.             extract( $args );
  1608.             extract( $instance );
  1609.  
  1610.             $street_address = $instance['street-address'];
  1611.            
  1612.             if( empty( $lat ) || empty( $lng ) )
  1613.             {
  1614.                 return;
  1615.             }
  1616.            
  1617.             /**
  1618.              * Allow to change the conditional display setting - e.g. if user is opt in and allows to connect directly
  1619.              *
  1620.              * @since 4.4
  1621.              * @param string $google_link           '' | 'confirm_link' | 'page_only'
  1622.              * @param string $context
  1623.              * @param mixed $object
  1624.              * @param array $args
  1625.              * @param array $instance
  1626.              * @return string
  1627.              */
  1628.             $original_google_link = $google_link;
  1629.             $google_link = apply_filters( 'avf_conditional_setting_external_links', $google_link, __CLASS__, $this, $args, $instance );
  1630.             if( ! in_array( $google_link, array( '', 'confirm_link', 'page_only' ) ) )
  1631.             {
  1632.                 $google_link = $original_google_link;
  1633.             }
  1634.            
  1635.             $title = apply_filters('widget_title', $title );
  1636.  
  1637.             echo $before_widget;
  1638.            
  1639.             if( ! empty( $title ) )
  1640.             {
  1641.                 echo $before_title . $title . $after_title;
  1642.             }
  1643.            
  1644.  
  1645.             $html_fallback_url = '';   
  1646.             if( ! empty( $google_fallback ) )
  1647.             {
  1648.                 $html_fallback_url .= 'background-image:url(' . $google_fallback . ');';
  1649.             }
  1650.            
  1651.             $html_overlay = '';
  1652.             if( ( 'confirm_link' == $google_link ) || ( 'page_only' == $google_link ) )
  1653.             {
  1654.                 $button_class = empty( $html_fallback_url ) ? ' av_text_confirm_link_visible' : '';
  1655.                
  1656.                 $text_overlay = '';
  1657.                 if( 'confirm_link' == $google_link )
  1658.                 {
  1659.                     $html_overlay = '<a href="#" class="av_gmaps_confirm_link av_text_confirm_link' . $button_class . '">';
  1660.                     $text_overlay = esc_html( $confirm_button );
  1661.                 }
  1662.                 else
  1663.                 {
  1664.                     if( empty( $street_address ) )
  1665.                     {
  1666.                         $adress1 = $lat;
  1667.                         $adress2 = $lng;
  1668.                     }
  1669.                     else
  1670.                     {
  1671.                         $adress1 = $street_address . ' ' . $postcode . ' ' . $city . ' ' . $state . ' ' . $country;
  1672.                         $adress2 = '';
  1673.                     }
  1674.                      
  1675.                     $url = av_google_maps::api_destination_url( $adress1, $adress2 );
  1676.                     $html_overlay = '<a class="av_gmaps_page_only av_text_confirm_link' . $button_class . '" href="' . $url . '" target="_blank">';
  1677.                     $text_overlay = esc_html( $page_link_text );
  1678.                 }
  1679.                
  1680.                 $html_overlay .= '<span>' . $text_overlay . '</span></a>';
  1681.             }
  1682.            
  1683.             $map_id = '';
  1684.             if( 'page_only' != $google_link )
  1685.             {
  1686.                 /**
  1687.                  * Add map data to js
  1688.                  */
  1689.                 $content = htmlspecialchars( $content, ENT_QUOTES );
  1690.                 $content = str_replace( '&lt;', '<', $content );
  1691.                 $content = str_replace( '&gt;', '>', $content );
  1692.                 $content = str_replace( '&quot;', '"', $content );
  1693.                 $content = str_replace( '&#039;', '"', $content );
  1694. //              $content = json_encode( $content );
  1695.                 $content = wpautop( $content );
  1696.                
  1697.                 $data = array(
  1698.                             'hue'                   => '',
  1699.                             'zoom'                  => $zoom,
  1700.                             'saturation'            => '',
  1701.                             'zoom_control'          => true,
  1702. //                          'pan_control'           => true,                not needed in > 4.3.2
  1703.                             'streetview_control'    => false,
  1704.                             'mobile_drag_control'   => true,
  1705.                             'maptype_control'       => 'dropdown',
  1706.                             'maptype_id'            => $type
  1707.                 );
  1708.                
  1709.                 $data['marker'] = array();
  1710.                
  1711.                 $data['marker'][0] = array(
  1712.                             'address'           => $postcode . '  ' . $street_address,
  1713.                             'city'              => $city,
  1714.                             'country'           => $country,
  1715.                             'state'             => $state,
  1716.                             'long'              => $lng,
  1717.                             'lat'               => $lat,
  1718.                             'icon'              => $icon,
  1719.                             'imagesize'         => 40,
  1720.                             'content'           => $content,
  1721.                     );
  1722.            
  1723.                 /**
  1724.                  * Does not work since 4.4
  1725.                  */
  1726.                 if( ! empty( $directionsto ) )
  1727.                 {
  1728.                     $data['marker'][0]['directionsto'] = $directionsto;
  1729.                 }
  1730.                
  1731.                 $add = empty( $google_link ) ? 'unconditionally' : 'delayed';
  1732.                
  1733.                 /**
  1734.                  * Allow to filter Google Maps data array
  1735.                  *
  1736.                  * @since 4.4
  1737.                  * @param array $data
  1738.                  * @param string context
  1739.                  * @param object
  1740.                  * @param array additional args
  1741.                  * @return array
  1742.                  */
  1743.                 $data = apply_filters( 'avf_google_maps_data', $data, __CLASS__, $this, array( $args, $instance ) );
  1744.                
  1745.                 $map_id = Av_Google_Maps()->add_map( $data, $add );
  1746.             }
  1747.                
  1748.             switch( $google_link )
  1749.             {
  1750.                 case 'confirm_link':
  1751.                     $show_class = 'av_gmaps_show_delayed';
  1752.                     break;
  1753.                 case 'page_only':
  1754.                     $show_class = 'av_gmaps_show_page_only';
  1755.                     break;
  1756.                 case '':
  1757.                 default:
  1758.                     $show_class = 'av_gmaps_show_unconditionally';
  1759.                     break;
  1760.             }
  1761.            
  1762.             if( empty( $html_fallback_url ) )
  1763.             {
  1764.                 $show_class .= ' av-no-fallback-img';
  1765.             }
  1766.            
  1767.             $style = '';        // $this->define_height($height)
  1768.             if( ! empty( $height ) )
  1769.             {
  1770.                 $height = str_replace( ';', '', $height );
  1771.                 $style .= " height: {$height};";
  1772.             }
  1773.             if( ! empty( $width ) )
  1774.             {
  1775.                 $width = str_replace( ';', '', $width );
  1776.                 $style .= " width: {$width};";
  1777.             }
  1778.             if( ! empty( $html_fallback_url ) )
  1779.             {
  1780.                 $html_fallback_url = str_replace( ';', '', $html_fallback_url );
  1781.                 $style .= " {$html_fallback_url};";
  1782.             }
  1783.  
  1784.             if( ! empty( $style ) )
  1785.             {
  1786.                 $style = "style='{$style}'";
  1787.             }
  1788.                
  1789.             echo '<div class="av_gmaps_widget_main_wrap av_gmaps_main_wrap">';
  1790.            
  1791.             if( empty( $map_id ) )
  1792.             {
  1793.                 echo    "<div class='avia-google-map-container avia-google-map-widget {$show_class}' {$style}>";
  1794.             }
  1795.             else
  1796.             {
  1797.                 echo    "<div id='{$map_id}' class='avia-google-map-container avia-google-map-widget {$show_class}' data-mapid='{$map_id}' {$style}>";
  1798.             }
  1799.            
  1800.             echo            $html_overlay;
  1801.             echo        '</div>';
  1802.            
  1803.            
  1804.             echo '</div>';
  1805.            
  1806.             echo $after_widget;
  1807.         }
  1808.  
  1809.         /**
  1810.          * Process widget options to be saved
  1811.          *
  1812.          * @param array $new_instance
  1813.          * @param array $old_instance
  1814.          * @return array
  1815.          */
  1816.         public function update( $new_instance, $old_instance )
  1817.         {
  1818.             $instance = $this->parse_args_instance( $old_instance );
  1819.            
  1820.             $fields = $this->get_field_names();
  1821.            
  1822.             foreach( $new_instance as $key => $value )
  1823.             {
  1824.                 if( in_array( $key, $fields ) )
  1825.                 {
  1826.                     $instance[ $key ] = strip_tags( $value );
  1827.                 }
  1828.             }
  1829.            
  1830.             return $instance;
  1831.         }
  1832.  
  1833.  
  1834.         /**
  1835.          * output the options form on admin
  1836.          *
  1837.          * @param array $instance
  1838.          */
  1839.         public function form( $instance )
  1840.         {
  1841.             $instance = $this->parse_args_instance( $instance );
  1842.             $fields = $this->get_field_names();
  1843.            
  1844.             foreach( $instance as $key => $value )
  1845.             {
  1846.                 if( in_array( $key, $fields ) )
  1847.                 {
  1848.                     $instance[ $key ] = esc_attr( $value );
  1849.                 }
  1850.             }
  1851.            
  1852.             extract( $instance );
  1853.            
  1854.             $street_address = $instance['street-address'];
  1855.            
  1856.             $html = new avia_htmlhelper();
  1857.            
  1858.             $marker_icon_element = array(
  1859.                                 'name'      => __( 'Custom Marker Icon', 'avia_framework' ),
  1860.                                 'desc'      => __( 'Upload a custom marker icon or enter the URL', 'avia_framework' ),
  1861.                                 'id'        => $this->get_field_id( 'icon'),
  1862.                                 'id_name'   => $this->get_field_name( 'icon' ),
  1863.                                 'std'       => $icon,
  1864.                                 'type'      => 'upload',
  1865.                                 'label'     => __('Use image as custom marker icon', 'avia_framework')
  1866.                             );
  1867.                
  1868.             $fallback_element = array(
  1869.                                 'name'      => __( 'Fallback image to replace Google Maps', 'avia_framework' ),
  1870.                                 'desc'      => __( 'Upload a fallback image or enter the URL to an image to replace Google Maps or until Google Maps is loaded', 'avia_framework' ),
  1871.                                 'id'        => $this->get_field_id( 'google_fallback'),
  1872.                                 'id_name'   => $this->get_field_name( 'google_fallback' ),
  1873.                                 'std'       => $google_fallback,
  1874.                                 'type'      => 'upload',
  1875.                                 'label'     => __('Use image as Google Maps fallback image', 'avia_framework')
  1876.                             );
  1877.  
  1878.             ?>
  1879.             <div class="avia_widget_form avia_widget_conditional_form avia_google_maps_form <?php echo $google_link;?>">
  1880.                 <p>
  1881.                     <label for="<?php print $this->get_field_id('title'); ?>"><?php _e('Title:','avia_framework'); ?></label>
  1882.                     <input class="widefat" id="<?php print $this->get_field_id('title'); ?>" name="<?php print $this->get_field_name('title'); ?>" type="text" value="<?php print $title; ?>" />
  1883.                 </p>
  1884.                 <p>
  1885.                 <?php _e('Enter the latitude and longitude of the location you want to display. Need help finding the latitude and longitude?', 'avia_framework'); ?> <a href="#" class="avia-coordinates-help-link button"><?php _e('Click here to enter an address.','avia_framework'); ?></a>
  1886.                 </p>
  1887.                 <div class="avia-find-coordinates-wrapper">
  1888.                     <p>
  1889.                         <label for="<?php print $this->get_field_id('street-address'); ?>"><?php _e('Street Address:','avia_framework'); ?></label>
  1890.                         <input class='widefat avia-map-street-address' id="<?php print $this->get_field_id('street-address'); ?>" name="<?php print $this->get_field_name('street-address'); ?>" type="text" value="<?php print $street_address; ?>" />
  1891.                     </p>
  1892.                     <p>
  1893.                         <label for="<?php print $this->get_field_id('city'); ?>"><?php _e('City:','avia_framework'); ?></label>
  1894.                         <input class='widefat avia-map-city' id="<?php print $this->get_field_id('city'); ?>" name="<?php print $this->get_field_name('city'); ?>" type="text" value="<?php print $city; ?>" />
  1895.                     </p>
  1896.                     <p>
  1897.                         <label for="<?php print $this->get_field_id('state'); ?>"><?php _e('State:','avia_framework'); ?></label>
  1898.                         <input class='widefat avia-map-state' id="<?php print $this->get_field_id('state'); ?>" name="<?php print $this->get_field_name('state'); ?>" type="text" value="<?php print $state; ?>" />
  1899.                     </p>
  1900.                     <p>
  1901.                         <label for="<?php print $this->get_field_id('postcode'); ?>"><?php _e('Postcode:','avia_framework'); ?></label>
  1902.                         <input class='widefat avia-map-postcode' id="<?php print $this->get_field_id('postcode'); ?>" name="<?php print $this->get_field_name('postcode'); ?>" type="text" value="<?php print $postcode; ?>" />
  1903.                     </p>
  1904.                     <p>
  1905.                         <label for="<?php print $this->get_field_id('country'); ?>"><?php _e('Country:','avia_framework'); ?></label>
  1906.                         <input class='widefat avia-map-country' id="<?php print $this->get_field_id('country'); ?>" name="<?php print $this->get_field_name('country'); ?>" type="text" value="<?php print $country; ?>" />
  1907.                     </p>
  1908.                     <p>
  1909.                         <a class="button avia-populate-coordinates"><?php _e('Fetch coordinates!','avia_framework'); ?></a>
  1910.                         <div class='avia-loading-coordinates'><?php _e('Fetching the coordinates. Please wait...','avia_framework'); ?></div>
  1911.                     </p>
  1912.                 </div>
  1913.                 <div class="avia-coordinates-wrapper">
  1914.                     <p>
  1915.                         <label for="<?php print $this->get_field_id('lat'); ?>"><?php _e('Latitude:','avia_framework'); ?></label>
  1916.                         <input class='widefat avia-map-lat' id="<?php print $this->get_field_id('lat'); ?>" name="<?php print $this->get_field_name('lat'); ?>" type="text" value="<?php print $lat; ?>" />
  1917.                     </p>
  1918.                     <p>
  1919.                         <label for="<?php print $this->get_field_id('lng'); ?>"><?php _e('Longitude:','avia_framework'); ?></label>
  1920.                         <input class='widefat avia-map-lng' id="<?php print $this->get_field_id('lng'); ?>" name="<?php print $this->get_field_name('lng'); ?>" type="text" value="<?php print $lng; ?>" />
  1921.                     </p>
  1922.                 </div>
  1923.                 <p>
  1924.                 <label for="<?php print $this->get_field_id('zoom'); ?>"><?php echo __('Zoom Level:','avia_framework').' <small>'.__('(1-19)','avia_framework').'</small>'; ?></label>
  1925.                 <select class="widefat" id="<?php echo $this->get_field_id('zoom'); ?>" name="<?php echo $this->get_field_name('zoom'); ?>">
  1926.                     <?php
  1927.                     $answers = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19);
  1928.                     foreach( $answers as $answer )
  1929.                     {
  1930.                         ?><option value="<?php echo $answer;?>" <?php selected( $answer, $zoom ); ?>><?php echo $answer;?></option><?php
  1931.                     }?>
  1932.                 </select>
  1933.                 </p>
  1934.                 <p>
  1935.                 <label for="<?php print $this->get_field_id('type'); ?>"><?php _e('Map Type:','avia_framework'); ?></label>
  1936.                 <select class="widefat" id="<?php echo $this->get_field_id('type'); ?>" name="<?php echo $this->get_field_name('type'); ?>">
  1937.                     <?php
  1938.                     $answers = array('ROADMAP', 'SATELLITE', 'HYBRID', 'TERRAIN');
  1939.                     foreach( $answers as $answer )
  1940.                     {
  1941.                         ?><option value="<?php echo $answer;?>" <?php selected( $answer, $type ); ?>><?php echo $answer;?></option><?php
  1942.                     }?>
  1943.                 </select>
  1944.                 </p>
  1945.                 <p style="display:none;">
  1946.                     <label for="<?php print $this->get_field_id('directionsto'); ?>"><?php _e('Display a Route by entering a address here. (If address is added Zoom will be ignored)','avia_framework'); ?>:</label>
  1947.                     <input class="widefat" id="<?php print $this->get_field_id('directionsto'); ?>" name="<?php print $this->get_field_name('directionsto'); ?>" type="text" value="<?php print $directionsto; ?>" />
  1948.                 </p>
  1949.                 <p>
  1950.                     <label for="<?php print $this->get_field_id('content'); ?>"><?php _e('Info Bubble Content:','avia_framework'); ?></label>
  1951.                     <textarea rows="7" class="widefat" id="<?php print $this->get_field_id('content'); ?>" name="<?php print $this->get_field_name('content'); ?>"><?php print $content; ?></textarea>
  1952.                 </p>
  1953.                
  1954.                 <div class="avia_gm_marker_icon_upload avia_google_marker_icon av-widgets-upload">
  1955.                     <?php echo $html->render_single_element( $marker_icon_element );?>
  1956.                 </div>
  1957.                 <p>
  1958.                     <label for="<?php print $this->get_field_id('width'); ?>"><?php _e('Enter the width in px or &percnt; (100&percnt; width will be used if you leave this field empty)','avia_framework'); ?>:</label>
  1959.                     <input class="widefat" id="<?php print $this->get_field_id('width'); ?>" name="<?php print $this->get_field_name('width'); ?>" type="text" value="<?php print $width; ?>" />
  1960.                 </p>
  1961.                 <p>
  1962.                     <label for="<?php print $this->get_field_id('height'); ?>"><?php _e('Enter the height in px or &percnt;','avia_framework'); ?>:</label>
  1963.                     <input class="widefat" id="<?php print $this->get_field_id('height'); ?>" name="<?php print $this->get_field_name('height'); ?>" type="text" value="<?php print $height; ?>" />
  1964.                 </p>
  1965.                 <p>
  1966.                     <label for="<?php echo $this->get_field_id( 'google_link' ); ?>"><?php _e( 'Link to Google Maps', 'avia_framework' ); ?>:</label>
  1967.                     <select id="<?php echo $this->get_field_id( 'google_link' ); ?>" name="<?php echo $this->get_field_name( 'google_link' ); ?>" class="widefat avia-coditional-widget-select">
  1968.                         <option value="" <?php selected( '', $google_link ) ?>><?php _e( 'Show Google Maps immediatly', 'avia_framework' ); ?></option>
  1969.                         <option value="confirm_link" <?php selected( 'confirm_link', $google_link ) ?>><?php _e( 'User must accept to show Google Maps', 'avia_framework' ); ?></option>
  1970.                         <option value="page_only" <?php selected( 'page_only', $google_link ) ?>><?php _e( 'Only open Google Maps in new window', 'avia_framework' ); ?></option>
  1971.                     </select>
  1972.                 </p>
  1973.                
  1974.                 <p class="av-confirm_link">
  1975.                     <label for="<?php echo $this->get_field_id('confirm_button'); ?>"><?php _e('Button text confirm to load Google Maps:', 'avia_framework'); ?>
  1976.                     <input class="widefat" id="<?php echo $this->get_field_id('confirm_button'); ?>" name="<?php echo $this->get_field_name('confirm_button'); ?>" type="text" value="<?php echo $confirm_button; ?>" /></label>
  1977.                 </p>
  1978.            
  1979.                 <p class="av-page_only">
  1980.                     <label for="<?php echo $this->get_field_id('page_link_text'); ?>"><?php _e('Direct link to Google Maps page:', 'avia_framework'); ?>
  1981.                     <input class="widefat" id="<?php echo $this->get_field_id('page_link_text'); ?>" name="<?php echo $this->get_field_name('page_link_text'); ?>" type="text" value="<?php echo $page_link_text; ?>" /></label>
  1982.                 </p>
  1983.  
  1984.                 <div class="avia_gm_fallback_upload avia_google_fallback av-widgets-upload">
  1985.                     <?php echo $html->render_single_element( $fallback_element );?>
  1986.                 </div>
  1987.                
  1988.             </div>
  1989.             <?php
  1990.         }
  1991.  
  1992.         /**
  1993.          * Output scripts in backend
  1994.          */
  1995.         public function handler_print_google_maps_scripts()
  1996.         {
  1997.             return;
  1998.            
  1999.             $api_key = avia_get_option( 'gmap_api' );
  2000.             $api_url = av_google_maps::api_url( $api_key );
  2001.            
  2002.             wp_register_script( 'avia-google-maps-api', $api_url, array('jquery'), NULL, true );
  2003.            
  2004.             $load_google_map_api = apply_filters( 'avf_load_google_map_api', true, 'avia_google_map_widget' );
  2005.            
  2006.             if( $load_google_map_api )
  2007.             {
  2008.                 wp_enqueue_script( 'avia-google-maps-api' );
  2009.             }
  2010.  
  2011.             $is_widget_edit_page = in_array( basename( $_SERVER['PHP_SELF'] ), array( 'widgets.php' ) );
  2012.             if( $is_widget_edit_page )
  2013.             {
  2014.                 wp_register_script( 'avia-google-maps-widget', AVIA_JS_URL . 'conditional_load/avia_google_maps_widget_admin.js', array( 'jquery','media-upload','media-views' ), '1.0.0', true);
  2015.                 wp_enqueue_script( 'avia-google-maps-widget' );
  2016.  
  2017.                 $args = array(
  2018.                     'toomanyrequests'   => __( "Too many requests at once, please refresh the page to complete geocoding", 'avia_framework' ),
  2019.                     'latitude'          => __( "Latitude and longitude for", 'avia_framework' ),
  2020.                     'notfound'          => __( "couldn't be found by Google, please add them manually", 'avia_framework' ),
  2021.                     'insertaddress'     => __( "Please insert a valid address in the fields above", 'avia_framework' )
  2022.                 );
  2023.  
  2024.                 if( $load_google_map_api )
  2025.                 {
  2026.                     wp_localize_script( 'avia-google-maps-api', 'AviaMapTranslation', $args );
  2027.                 }
  2028.             }
  2029.         }
  2030.  
  2031.         /**
  2032.          * Returns the js script
  2033.          *
  2034.          * @param string $lat
  2035.          * @param string $lng
  2036.          * @param string $zoom
  2037.          * @param string $type
  2038.          * @param string $content
  2039.          * @param string $directionsto
  2040.          * @param string $width
  2041.          * @param string $height
  2042.          * @param string $icon
  2043.          * @return string
  2044.          *
  2045.          * @deprecated since version 4.4    no longer needed
  2046.          */
  2047.         protected function print_map( $lat, $lng, $zoom, $type, $content, $directionsto, $width, $height, $icon )
  2048.         {
  2049.             global $avia_config;
  2050.            
  2051.             _deprecated_function( 'print_map', '4.4', 'see class av_google_maps' );
  2052.            
  2053.             $output = "";
  2054.             $unique = uniqid();
  2055.  
  2056.             $prefix = isset($_SERVER['HTTPS'] ) ? "https" : "http";
  2057.             $width = ! empty( $width ) ? 'width:'.$width.';' : 'width:100%;';
  2058.             $height = ! empty( $height ) ? 'height:'.$height.';' : '';
  2059.  
  2060.             $content = htmlspecialchars( $content, ENT_QUOTES );
  2061.             $content = str_replace( '&lt;', '<', $content );
  2062.             $content = str_replace( '&gt;', '>', $content );
  2063.             $content = str_replace( '&quot;', '"', $content );
  2064.             $content = str_replace( '&#039;', '"', $content );
  2065.             $content = json_encode( $content );
  2066.  
  2067.  
  2068.             $directionsForm = "";
  2069.             if( empty( $avia_config['g_maps_widget_active'] ) )
  2070.             {
  2071.                 $avia_config['g_maps_widget_active'] = 0;
  2072.             }
  2073.  
  2074.             if( apply_filters( 'avia_google_maps_widget_load_api', true, $avia_config[ 'g_maps_widget_active'] ) )
  2075.             {  
  2076.                 $api_key = avia_get_option('gmap_api');
  2077.                 $api_url = av_google_maps::api_url( $api_key );
  2078.  
  2079.                 wp_register_script( 'avia-google-maps-api', $api_url, array( 'jquery' ), NULL, true );
  2080.                 wp_enqueue_script( 'avia-google-maps-api' );
  2081.             }
  2082.  
  2083.             $avia_config['g_maps_widget_active'] ++;
  2084.  
  2085.             $output .= "<script type='text/javascript'>
  2086.                 function makeMap_" . $avia_config['g_maps_widget_active'] . "() {\n";
  2087.  
  2088.             $avia_maps_config = "
  2089.                 var directionsDisplay;
  2090.                 directionsDisplay = new google.maps.DirectionsRenderer;
  2091.                 var directionsService = new google.maps.DirectionsService;
  2092.                 var map;
  2093.                 var latlng = new google.maps.LatLng(" . $lat . ", " . $lng . ");
  2094.                 var directionsto = '" . $directionsto . "';
  2095.                 var myOptions = {
  2096.                   zoom:" . $zoom . ",
  2097.                   mapTypeControl:true,
  2098.                   mapTypeId:google.maps.MapTypeId." . $type . ",
  2099.                   mapTypeControlOptions:{style:google.maps.MapTypeControlStyle.DROPDOWN_MENU},
  2100.                   navigationControl:true,
  2101.                   navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL},
  2102.                   center:latlng
  2103.                 };
  2104.                 var map = new google.maps.Map(document.getElementById('avia_google_maps_$unique'), myOptions);
  2105.  
  2106.                 if(directionsto.length > 5)
  2107.                 {
  2108.                   directionsDisplay.setMap(map);
  2109.                   var request = {
  2110.                      origin:directionsto,
  2111.                      destination:latlng,
  2112.                      travelMode:google.maps.DirectionsTravelMode.DRIVING
  2113.                 };
  2114.                   directionsService.route(request, function(response, status) {
  2115.                      if(status == google.maps.DirectionsStatus.OK) {
  2116.                         directionsDisplay.setDirections(response)
  2117.                      }
  2118.                   })
  2119.                 }
  2120.                 else
  2121.                 {
  2122.                   var contentString = " . $content . ";
  2123.                   var infowindow = new google.maps.InfoWindow({
  2124.                      content: contentString
  2125.                   });
  2126.                   var marker = new google.maps.Marker({
  2127.                      position: latlng,
  2128.                      map: map,
  2129.                      icon: '" . $icon . "',
  2130.                      title: ''
  2131.                   });
  2132.  
  2133.                   google.maps.event.addListener(marker, 'click', function() {
  2134.                       infowindow.open(map,marker);
  2135.                   });
  2136.                 }";
  2137.  
  2138.             $output .= apply_filters( 'avia_google_maps_widget_config', $avia_maps_config, $lat, $lng, $directionsto, $zoom, $type, $unique, $content, $icon );
  2139.  
  2140.             $output .= "\n}\n\n
  2141.                     jQuery(document).ready(function() {
  2142.                         makeMap_" . $avia_config['g_maps_widget_active'] . "()
  2143.                     });
  2144.                 </script>
  2145.                 <div id='avia_google_maps_$unique' style='$height $width' class='avia_google_map_container'></div>";
  2146.  
  2147.            return $output;
  2148.         }
  2149.  
  2150.  
  2151.     } // SGMwidget widget
  2152. }
  2153.  
  2154.  
  2155. if( ! class_exists('avia_instagram_widget') )
  2156. {
  2157.     /**
  2158.      * Extended and improved version.
  2159.      * Adds a background caching of images on own server to avoid to access instagram to display the images
  2160.      *
  2161.      * @since 4.3.1
  2162.      * @by Günter
  2163.      */
  2164.     class avia_instagram_widget extends Avia_Widget
  2165.     {
  2166.  
  2167.         /**
  2168.          *
  2169.          * @since 4.3.1
  2170.          * @var array
  2171.          */
  2172.         protected $upload_folders;
  2173.  
  2174.         /**
  2175.          * Stores the expire time for cached images in seconds.
  2176.          * Do not make intervall too short to avoid unnecessary requests.
  2177.          * Also make it large enough to allow a complete update of all instances in that period.
  2178.          *
  2179.          * @since 4.3.1
  2180.          * @var int
  2181.          */
  2182.         protected $expire_time;
  2183.  
  2184.         /**
  2185.          *
  2186.          * @since 4.3.1
  2187.          * @var boolean
  2188.          */
  2189.         protected $activate_cron;
  2190.  
  2191.  
  2192.         /**
  2193.          * Holds all caching info for each widget instance.
  2194.          *
  2195.          * @since 4.3.1
  2196.          * @var array
  2197.          */
  2198.         protected $cache;
  2199.  
  2200.  
  2201.         /**
  2202.          *
  2203.          * @since 4.3.1
  2204.          * @var array
  2205.          */
  2206.         protected $cached_file_sizes;
  2207.  
  2208.  
  2209.         /**
  2210.          *
  2211.          */
  2212.         public function __construct()
  2213.         {
  2214.             parent::__construct(
  2215.                                 'avia-instagram-feed',
  2216.                                 THEMENAME ." ". __( 'Instagram', 'avia_framework' ),
  2217.                                 array( 'classname' => 'avia-instagram-feed', 'description' => __( 'Displays your latest Instagram photos', 'avia_framework' ) )
  2218.                             );
  2219.  
  2220.             $this->upload_folders = wp_upload_dir();
  2221.  
  2222.             if( is_ssl() )
  2223.             {
  2224.                 $this->upload_folders['baseurl'] = str_replace( 'http://', 'https://', $this->upload_folders['baseurl'] );
  2225.             }
  2226.  
  2227.             $folder = apply_filters( 'avf_instagram_cache_folder_name', 'avia_instagram_cache' );
  2228.  
  2229.             $this->upload_folders['instagram_dir'] = trailingslashit( trailingslashit( $this->upload_folders['basedir'] ) . $folder );
  2230.             $this->upload_folders['instagram_url'] = trailingslashit( trailingslashit( $this->upload_folders['baseurl'] ) . $folder );
  2231.  
  2232.             $this->expire_time = HOUR_IN_SECONDS * 2;
  2233.  
  2234.             $this->expire_time = apply_filters_deprecated( 'null_instagram_cache_time', array( $this->expire_time ), '4.3.1', 'avf_instagram_file_cache_time', __( 'Adding possible file caching on server might need a longer period of time to invalidate cache.', 'avia_framework' ) );
  2235.             $this->expire_time = apply_filters( 'avf_instagram_file_cache_time', $this->expire_time );
  2236.  
  2237.             $this->activate_cron =  ! ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON );
  2238.             $this->activate_cron = apply_filters( 'avf_instagram_activate_cron', $this->activate_cron );
  2239.  
  2240.             $this->cache = $this->get_cache();
  2241.  
  2242.             $this->cached_file_sizes = array( 'thumbnail', 'small', 'large', 'original' );
  2243.  
  2244.             /**
  2245.              * WP Cron job events
  2246.              */
  2247.             if( $this->activate_cron )
  2248.             {
  2249.                 add_action( 'av_instagram_scheduled_filecheck', array( $this, 'handler_scheduled_filecheck' ), 10 );
  2250.             }
  2251.  
  2252.             /**
  2253.              * Makes sure to keep cron job alive as fallback
  2254.              */
  2255.             if( is_admin() )
  2256.             {
  2257.                 add_action( 'admin_init', array( $this, 'handler_init_filecheck' ), 99999 );
  2258.                 add_action( 'delete_widget', array( $this, 'handler_delete_widget' ), 10, 3 );     
  2259.             }
  2260.             else
  2261.             {
  2262.                 add_action( 'init', array( $this, 'handler_init_filecheck' ), 99999 );
  2263.             }
  2264.  
  2265.         }
  2266.  
  2267.         /**
  2268.          *
  2269.          * @since 4.3.1
  2270.          */
  2271.         public function __destruct()
  2272.         {
  2273.             parent::__destruct();
  2274.            
  2275.             unset( $this->upload_folders );
  2276.             unset( $this->cache );
  2277.             unset( $this->cached_file_sizes );
  2278.         }
  2279.  
  2280.  
  2281.         /**
  2282.          * Returns the cache info array
  2283.          *
  2284.          * @since 4.3.1
  2285.          * @return array
  2286.          */
  2287.         public function get_cache()
  2288.         {
  2289.             if( is_null( $this->cache ) )
  2290.             {
  2291.                 $this->cache = get_option( 'avia_instagram_widgets_cache', array() );
  2292.  
  2293.                 if( empty( $this->cache ) )
  2294.                 {
  2295.                     $this->cache = array(
  2296.                             'last_updated'      => 0,           //  time() when last complete check has run
  2297.                             'instances'         => array()
  2298.                         );
  2299.                 }
  2300.             }
  2301.  
  2302.             return $this->cache;
  2303.         }
  2304.  
  2305.  
  2306.         /**
  2307.          * Update the cache array in DB
  2308.          *
  2309.          * @since 4.3.1
  2310.          * @param array|null $cache
  2311.          */
  2312.         public function update_cache( array $cache = null )
  2313.         {
  2314.             if( ! is_null( $cache) )
  2315.             {
  2316.                 $this->cache = $cache;
  2317.             }
  2318.  
  2319.             update_option( 'avia_instagram_widgets_cache', $this->cache );
  2320.         }
  2321.  
  2322.  
  2323.         /**
  2324.          * Ensure a valid instance array filled with defaults
  2325.          *
  2326.          * @since 4.3.1
  2327.          * @param array $instance
  2328.          * @return array
  2329.          */
  2330.         protected function parse_args_instance( array $instance )
  2331.         {
  2332.             $instance = wp_parse_args( $instance, array(
  2333.                                     'title'         => __( 'Instagram', 'avia_framework' ),
  2334.                                     'username'      => '',
  2335.                                     'cache'         => apply_filters( 'avf_instagram_default_cache_location', '' ),     //  '' | 'server'
  2336.                                     'number'        => 9,
  2337.                                     'columns'       => 3,
  2338.                                     'size'          => 'thumbnail',
  2339.                                     'target'        => 'lightbox' ,
  2340.                                     'link'          => __( 'Follow Me!', 'avia_framework' ),
  2341.                                     'avia_key'      => ''
  2342.                                 )
  2343.                             );
  2344.  
  2345.             return $instance;
  2346.         }
  2347.  
  2348.         /**
  2349.          * Ensure a valid instance array filled with defaults
  2350.          *
  2351.          * @since 4.3.1
  2352.          * @param array $instance_cache
  2353.          * @return array
  2354.          */
  2355.         protected function parse_args_instance_cache( array $instance_cache )
  2356.         {
  2357.             $instance_cache = wp_parse_args( (array) $instance_cache, array(
  2358.                                             'upload_folder'     => '',              //  not the complete path, only the last folder name
  2359.                                             'path_error'        => '',              //  Error message if upload_folder could not be created
  2360.                                             'instagram_error'   => '',             
  2361.                                             'upload_errors'     => false,           //  number of errors found when caching files to show
  2362.                                             'last_update'       => 0,               //  time() of last update
  2363.                                             'cached_list'       => array(),         //  in the order how to display the files and file info on server
  2364.                                             'instagram_list'    => array()          //  returned info from instagramm
  2365.                                         ));
  2366.  
  2367.             return $instance_cache;
  2368.         }
  2369.  
  2370.  
  2371.         /**
  2372.          * Creates a unique key for the given instance for our cache array
  2373.          *
  2374.          * @since 4.3.1
  2375.          * @param array $instance
  2376.          * @param string $id_widget
  2377.          * @return string
  2378.          */
  2379.         protected function create_avia_key( array $instance, $id_widget )
  2380.         {
  2381.             $k = 0;
  2382.             $key = str_replace( $this->id_base . '-', '', $id_widget ) . '-' . AviaHelper::save_string( $instance['title'], '-' );
  2383.  
  2384.             $orig_key = $key;
  2385.             while( array_key_exists( $key, $this->cache['instances'] ) )
  2386.             {
  2387.                 $key = $orig_key . "-{$k}";
  2388.                 $k++;
  2389.             }
  2390.  
  2391.             return $key;
  2392.         }
  2393.  
  2394.  
  2395.         /**
  2396.          * Output the widget in frontend
  2397.          *
  2398.          * @param array $args
  2399.          * @param array $instance
  2400.          */
  2401.         public function widget( $args, $instance )
  2402.         {
  2403.             $instance = $this->parse_args_instance( $instance );
  2404.  
  2405.             $fields = $this->get_field_names();
  2406.  
  2407.                 foreach( $instance as $key => $value )
  2408.                 {
  2409.                     if( in_array( $key, $fields ) )
  2410.                     {
  2411.                         $instance[ $key ] = esc_attr( $value );
  2412.                     }
  2413.                 }
  2414.  
  2415.             extract( $args, EXTR_SKIP );
  2416.             extract( $instance, EXTR_SKIP );
  2417.            
  2418.             /**
  2419.              * Allow to change the conditional display setting - e.g. if user is opt in and allows to connect directly
  2420.              *
  2421.              * @since 4.4
  2422.              * @param string $google_link           '' | 'server'
  2423.              * @param string $context
  2424.              * @param mixed $object
  2425.              * @param array $args
  2426.              * @param array $instance
  2427.              * @return string
  2428.              */
  2429.             $original_cache = $cache;
  2430.             $cache = apply_filters( 'avf_conditional_setting_external_links', $cache, __CLASS__, $this, $args, $instance );
  2431.             if( ! in_array( $cache, array( '', 'server' ) ) )
  2432.             {
  2433.                $cache = $original_cache;
  2434.             }
  2435.  
  2436.             $title = apply_filters( 'widget_title', $title, $args );
  2437.  
  2438.             /**
  2439.              * Skip for non logged in users in frontend
  2440.              */
  2441.             if( ( trim( $username ) == '' ) && ! is_user_logged_in() && ! current_user_can( 'edit_posts' ) )
  2442.             {
  2443.                 return;
  2444.             }
  2445.  
  2446.             echo $before_widget;
  2447.  
  2448.             if ( ! empty( $title ) )
  2449.             {
  2450.                 echo $before_title . $title . $after_title;
  2451.             }
  2452.  
  2453.             do_action( 'aviw_before_widget', $instance );
  2454.  
  2455.             if( $username != '' )
  2456.             {
  2457.                 $errors = array();
  2458.                 $media_array = array();
  2459.  
  2460.                 $instance_cache = isset( $this->cache['instances'][ $instance['avia_key'] ] ) ? $this->cache['instances'][ $instance['avia_key'] ] : null;
  2461.  
  2462.                 if( ! is_null( $instance_cache ) )
  2463.                 {
  2464.                     if( ! empty( $instance_cache['instagram_error'] ) )
  2465.                     {
  2466.                         $errors =  array( $instance_cache['instagram_error'] );
  2467.                     }
  2468.                     if( ! empty( $instance_cache['upload_errors'] ) && ( 'server' == $instance['cache'] ) )
  2469.                     {
  2470.                         foreach( $instance_cache['cached_list'] as $img )
  2471.                         {
  2472.                             if( ! empty( $img['errors'] ) )
  2473.                             {
  2474.                                 $errors = array_merge( $errors, $img['errors'] );
  2475.                             }
  2476.                         }
  2477.                     }
  2478.  
  2479.                     if( 'server' == $instance['cache'] )
  2480.                     {
  2481.                         $media_array = $instance_cache['cached_list'];
  2482.  
  2483.                         $url = trailingslashit( trailingslashit( $this->upload_folders['instagram_url'] ) . $instance_cache['upload_folder'] );
  2484.  
  2485.                         foreach( $media_array as $key => $media )
  2486.                         {
  2487.                             if( ! empty( $media['errors'] ) )
  2488.                             {
  2489.                                 $errors = array_merge( $errors, $media['errors'] );
  2490.                             }
  2491.  
  2492.                             if( ! empty( $media[ $size ] ) )
  2493.                             {
  2494.                                 $media_array[ $key ][ $size ] = $url . $media[ $size ];
  2495.                             }
  2496.                             if( ! empty( $media[ 'original' ] ) )
  2497.                             {
  2498.                                 $media_array[ $key ]['original'] = $url . $media['original'];
  2499.                             }
  2500.                         }
  2501.                     }
  2502.                     else
  2503.                     {
  2504.                         $media_array = $instance_cache['instagram_list'];
  2505.                     }
  2506.                 }
  2507.  
  2508.                 /**
  2509.                  * Only show error messages to admins and authors
  2510.                  */
  2511.                 if( ! empty( $errors ) && is_user_logged_in() && current_user_can( 'edit_posts' ) )
  2512.                 {
  2513.                     $errors = array_map( 'esc_html__', $errors );
  2514.  
  2515.                     $out = '';
  2516.                     $out .= '<div class="av-instagram-errors">';
  2517.  
  2518.                     $out .=     '<p class="av-instagram-errors-msg av-instagram-admin">' . esc_html__( 'Only visisble for Admins:', 'avia_framework' ) . '</p>';
  2519.  
  2520.                     $out .=     '<p class="av-instagram-errors-msg av-instagram-admin">';
  2521.                     $out .=         implode( '<br />', $errors );
  2522.                     $out .=     '</p>';
  2523.  
  2524.                     $out .= '</div>';
  2525.  
  2526.                     echo $out;
  2527.                 }
  2528.  
  2529.                 if( count( $media_array ) > 0 )
  2530.                 {
  2531.                     // filters for custom classes
  2532.                     $ulclass    = esc_attr( apply_filters( 'aviw_list_class', 'av-instagram-pics av-instagram-size-' . $size ) );
  2533.                     $rowclass   = esc_attr( apply_filters( 'aviw_row_class', 'av-instagram-row' ) );
  2534.                     $liclass    = esc_attr( apply_filters( 'aviw_item_class', 'av-instagram-item' ) );
  2535.                     $aclass     = esc_attr( apply_filters( 'aviw_a_class', '' ) );
  2536.                     $imgclass   = esc_attr( apply_filters( 'aviw_img_class', '' ) );
  2537.  
  2538.                     ?><div class="<?php echo esc_attr( $ulclass ); ?>"><?php
  2539.  
  2540.                     $last_id  = end( $media_array );
  2541.                     $last_id  = $last_id['id'];
  2542.  
  2543.                     $rowcount = 0; 
  2544.                     $itemcount = 0;
  2545.                     foreach ( $media_array as $item )
  2546.                     {
  2547.                         if( empty( $item[ $size ] ) )
  2548.                         {
  2549.                             continue;
  2550.                         }
  2551.  
  2552.                         if( $rowcount == 0 )
  2553.                         {
  2554.                             echo "<div class='{$rowclass}'>";
  2555.                         }
  2556.  
  2557.                         $rowcount ++;
  2558.                         $itemcount ++;
  2559.  
  2560.                         $targeting = $target;
  2561.                         if( $target == "lightbox" )
  2562.                         {
  2563.                             $targeting = "";
  2564.                             $item['link'] = ! empty( $item['original'] ) ? $item['original'] : $item[ $size ];
  2565.                         }
  2566.  
  2567.                         echo '<div class="' . $liclass . '">';
  2568.                         echo '<a href="' . esc_url( $item['link'] ) . '" target="' . esc_attr( $targeting ) . '"  class="' . $aclass . ' ' . $imgclass . '" title="' . esc_attr( $item['description'] ) . '" style="background-image:url(' . esc_url( $item[ $size ] ) . ');">';
  2569.                         echo '</a></div>';
  2570.  
  2571.                         if( $rowcount % $columns == 0 || $last_id == $item['id'] || ( $itemcount >= $number ) )
  2572.                         {
  2573.                             echo '</div>';
  2574.                             $rowcount = 0;
  2575.  
  2576.                             if( $itemcount >= $number )
  2577.                             {
  2578.                                 break;
  2579.                             }
  2580.                         }
  2581.                     }
  2582.                     echo '</div>';
  2583.                 }
  2584.                 else
  2585.                 {
  2586.                     echo '<p class="av-instagram-errors-msg">' . esc_html__( 'No images available at the moment', 'avia_framework' ) . '</p>';
  2587.                 }
  2588.             }
  2589.             else
  2590.             {
  2591.                 echo '<p class="av-instagram-errors-msg av-instagram-admin">' . esc_html__( 'For admins only: Missing intagram user name !!', 'avia_framework' ) . '</p>';
  2592.             }
  2593.  
  2594.             if ( $link != '' )
  2595.             {
  2596.                 ?>
  2597.                 <a class="av-instagram-follow avia-button" href="//instagram.com/<?php echo esc_attr( trim( $username ) ); ?>" rel="me" target="<?php echo esc_attr( $target ); ?>"><?php echo $link; ?></a><?php
  2598.             }
  2599.  
  2600.             do_action( 'aviw_after_widget', $instance );
  2601.  
  2602.             echo $after_widget;
  2603.         }
  2604.  
  2605.  
  2606.         /**
  2607.          * Output the form in backend
  2608.          *
  2609.          * @param array $instance
  2610.          */
  2611.         public function form( $instance )
  2612.         {
  2613.             $instance = $this->parse_args_instance( $instance );
  2614.             $fields = $this->get_field_names();
  2615.            
  2616.             foreach( $instance as $key => $value )
  2617.             {
  2618.                 if( in_array( $key, $fields ) )
  2619.                 {
  2620.                     switch( $key )
  2621.                     {
  2622.                         case 'number':
  2623.                         case 'columns':
  2624.                             $instance[ $key ] = absint( $value );
  2625.                             break;
  2626.                         default:
  2627.                             $instance[ $key ] = esc_attr( $value );
  2628.                             break;
  2629.                     }
  2630.                 }
  2631.             }
  2632.            
  2633.             extract( $instance );
  2634.  
  2635.             ?>
  2636.             <p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title', 'avia_framework' ); ?>: <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" /></label></p>
  2637.             <p><label for="<?php echo $this->get_field_id( 'username' ); ?>"><?php _e( 'Username', 'avia_framework' ); ?>: <input class="widefat" id="<?php echo $this->get_field_id( 'username' ); ?>" name="<?php echo $this->get_field_name( 'username' ); ?>" type="text" value="<?php echo $username; ?>" /></label></p>          
  2638.             <p><label for="<?php echo $this->get_field_id( 'cache' ); ?>"><?php _e( 'Location of your photos or videos', 'avia_framework' ); ?>:</label>
  2639.                 <select id="<?php echo $this->get_field_id( 'cache' ); ?>" name="<?php echo $this->get_field_name( 'cache' ); ?>" class="widefat">
  2640.                     <option value="" <?php selected( '', $cache ) ?>><?php _e( 'Get from your instagram account (instagram server connection needed)', 'avia_framework' ); ?></option>
  2641.                     <option value="server" <?php selected( 'server', $cache ) ?>><?php _e( 'Cache on your server - no instagram connection needed on pageload', 'avia_framework' ); ?></option>
  2642.                 </select>
  2643.             </p>
  2644.             <p><label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e( 'Number of photos', 'avia_framework' ); ?>:</label>
  2645.                 <select id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" class="widefat">
  2646.                     <option value="1" <?php selected( 1, $number ) ?>>1</option>
  2647.                     <option value="2" <?php selected( 2, $number ) ?>>2</option>
  2648.                     <option value="3" <?php selected( 3, $number ) ?>>3</option>
  2649.                     <option value="4" <?php selected( 4, $number ) ?>>4</option>
  2650.                     <option value="5" <?php selected( 5, $number ) ?>>5</option>
  2651.                     <option value="6" <?php selected( 6, $number ) ?>>6</option>
  2652.                     <option value="7" <?php selected( 7, $number ) ?>>7</option>
  2653.                     <option value="8" <?php selected( 8, $number ) ?>>8</option>
  2654.                     <option value="9" <?php selected( 9, $number ) ?>>9</option>
  2655.                     <option value="10" <?php selected( 10, $number ) ?>>10</option>
  2656.                     <option value="11" <?php selected( 11, $number ) ?>>11</option>
  2657.                     <option value="12" <?php selected( 12, $number ) ?>>12</option>
  2658.                 </select>
  2659.             </p>
  2660.             <p><label for="<?php echo $this->get_field_id( 'columns' ); ?>"><?php _e( 'Number of columns', 'avia_framework' ); ?>:</label>
  2661.                 <select id="<?php echo $this->get_field_id( 'columns' ); ?>" name="<?php echo $this->get_field_name( 'columns' ); ?>" class="widefat">
  2662.                     <option value="1" <?php selected( 1, $columns ) ?>>1</option>
  2663.                     <option value="2" <?php selected( 2, $columns ) ?>>2</option>
  2664.                     <option value="3" <?php selected( 3, $columns ) ?>>3</option>
  2665.                     <option value="4" <?php selected( 4, $columns ) ?>>4</option>
  2666.                     <option value="5" <?php selected( 5, $columns ) ?>>5</option>
  2667.                     <option value="6" <?php selected( 6, $columns ) ?>>6</option>
  2668.                 </select>
  2669.             </p>
  2670.             <p><label for="<?php echo $this->get_field_id( 'size' ); ?>"><?php _e( 'Thumbnail size', 'avia_framework' ); ?>:</label>
  2671.                 <select id="<?php echo $this->get_field_id( 'size' ); ?>" name="<?php echo $this->get_field_name( 'size' ); ?>" class="widefat">
  2672.                     <option value="thumbnail" <?php selected( 'thumbnail', $size ) ?>><?php _e( 'Thumbnail', 'avia_framework' ); ?></option>
  2673.                     <option value="small" <?php selected( 'small', $size ) ?>><?php _e( 'Small', 'avia_framework' ); ?></option>
  2674.                     <option value="large" <?php selected( 'large', $size ) ?>><?php _e( 'Large', 'avia_framework' ); ?></option>
  2675.                     <option value="original" <?php selected( 'original', $size ) ?>><?php _e( 'Original', 'avia_framework' ); ?></option>
  2676.                 </select>
  2677.             </p>
  2678.             <p><label for="<?php echo $this->get_field_id( 'target' ); ?>"><?php _e( 'Open links in', 'avia_framework' ); ?>:</label>
  2679.                 <select id="<?php echo $this->get_field_id( 'target' ); ?>" name="<?php echo $this->get_field_name( 'target' ); ?>" class="widefat">
  2680.                     <option value="lightbox" <?php selected( 'lightbox', $target ) ?>><?php _e( 'Lightbox', 'avia_framework' ); ?></option>
  2681.                     <option value="_self" <?php selected( '_self', $target ) ?>><?php _e( 'Current window (_self)', 'avia_framework' ); ?></option>
  2682.                     <option value="_blank" <?php selected( '_blank', $target ) ?>><?php _e( 'New window (_blank)', 'avia_framework' ); ?></option>
  2683.                 </select>
  2684.             </p>
  2685.             <p><label for="<?php echo $this->get_field_id( 'link' ); ?>"><?php _e( 'Link text', 'avia_framework' ); ?>: <input class="widefat" id="<?php echo $this->get_field_id( 'link' ); ?>" name="<?php echo $this->get_field_name( 'link' ); ?>" type="text" value="<?php echo $link; ?>" /></label></p>
  2686.  
  2687.             <?php
  2688.  
  2689.             if( ! $this->activate_cron )
  2690.             {
  2691.                 echo '<p class="av-instagram-no-cron">';
  2692.                 echo    __( 'WP Cron jobs are disabled. To assure a regular update of cached data and an optimal pageload in frontend and backend we recommend to activate this.', 'avia_framework' );
  2693.                 echo '</p>';
  2694.  
  2695.                 $timestamp = ( $this->cache['last_updated'] != 0 ) ? $this->cache['last_updated'] + $this->expire_time : false;
  2696.                 $time = ( false !== $timestamp ) ? date( 'Y/m/d H:i a', $timestamp ) . ' UTC' : __( 'No time available', 'avia_framework' );
  2697.  
  2698.                 echo '<p class="av-instagram-next-update">';
  2699.                 echo    __( 'The widget preloads and caches Instagram data for better performance.', 'avia_framework' )." ";
  2700.                 echo    sprintf( __( 'Next update: %s', 'avia_framework' ), $time );
  2701.                 echo '</p>';
  2702.             }
  2703.             else
  2704.             {
  2705.                 $timestamp = wp_next_scheduled( 'av_instagram_scheduled_filecheck' );
  2706.                 $time = ( false !== $timestamp ) ? date( "Y/m/d H:i", $timestamp ) . ' UTC' : __( '', 'avia_framework' );
  2707.  
  2708.                 echo '<p class="av-instagram-next-update">';
  2709.                 echo    __( 'The widget preloads and caches Instagram data for better performance.', 'avia_framework' )." ";
  2710.                 echo    sprintf( __( 'Next update: %s', 'avia_framework' ), $time );
  2711.                 echo '</p>';
  2712.             }
  2713.  
  2714.             if( empty( $instance['avia_key'] ) )
  2715.             {
  2716.                 return;
  2717.             }
  2718.  
  2719.             if( empty( $this->cache['instances'][ $instance['avia_key'] ] ) )
  2720.             {
  2721.                 return;
  2722.             }
  2723.  
  2724.             $instance_cache = $this->cache['instances'][ $instance['avia_key'] ];
  2725.             $errors = array();
  2726.  
  2727.             if( ! empty( $instance_cache['instagram_error'] ) )
  2728.             {
  2729.                 $errors = (array) $instance_cache['instagram_error'];
  2730.             }
  2731.  
  2732.             if( 'server' == $instance['cache'] )
  2733.             {
  2734.                 foreach( $instance_cache['cached_list'] as $image )
  2735.                 {
  2736.                     if( ! empty( $image['errors'] ) )
  2737.                     {
  2738.                         $errors = array_merge( $errors, $image['errors'] );
  2739.                     }
  2740.                 }
  2741.             }
  2742.  
  2743.             if( ! empty( $errors ) )
  2744.             {
  2745.                 $errors = array_map( 'esc_html__', $errors );
  2746.  
  2747.                 $out  = '<div class="av-instagram-errors">';
  2748.  
  2749.                 $out .=     '<p class="av-instagram-errors-msg av-instagram-error-headline">' . esc_html__( 'Errors found:', 'avia_framework' ) . '</p>';
  2750.  
  2751.                 $out .=     '<p class="av-instagram-errors-msg">';
  2752.                 $out .=         implode( '<br />', $errors );
  2753.                 $out .=     '</p>';
  2754.  
  2755.                 $out .= '</div>';
  2756.  
  2757.                 echo $out;
  2758.             }
  2759.  
  2760.         }
  2761.  
  2762.         /**
  2763.          * Update the form data
  2764.          *
  2765.          * @param array $new_instance
  2766.          * @param array $old_instance
  2767.          * @return array
  2768.          */
  2769.         public function update( $new_instance, $old_instance )
  2770.         {
  2771.             $instance = $this->parse_args_instance( $old_instance );
  2772.            
  2773.             $instance['title'] = strip_tags( $new_instance['title'] );
  2774.             $instance['username'] = trim( strip_tags( $new_instance['username'] ) );
  2775.             $instance['cache'] = ( $new_instance['cache'] == 'server' || $new_instance['cache'] == '' ) ? $new_instance['cache'] : apply_filters( 'avf_instagram_default_cache_location', 'server' );
  2776.             $instance['number'] = ! absint( $new_instance['number'] ) ? 9 : $new_instance['number'];
  2777.             $instance['columns'] = ! absint( $new_instance['columns'] ) ? 3 : $new_instance['columns'];
  2778.             $instance['size'] = ( $new_instance['size'] == 'thumbnail' || $new_instance['size'] == 'large' || $new_instance['size'] == 'small' || $new_instance['size'] == 'original' ) ? $new_instance['size'] : 'large';
  2779.             $instance['target'] = ( $new_instance['target'] == '_self' || $new_instance['target'] == '_blank'|| $new_instance['target'] == 'lightbox' ) ? $new_instance['target'] : '_self';
  2780.             $instance['link'] = strip_tags( $new_instance['link'] );
  2781.  
  2782.  
  2783.             /**
  2784.              * We have a new widget (or an existing from an older theme version)
  2785.              */
  2786.             if( empty( $instance['avia_key'] ) )
  2787.             {
  2788.                 $key = $this->create_avia_key( $instance, $this->id );
  2789.                 $instance['avia_key'] = $key;
  2790.                 $this->cache['instances'][ $key ] = array();
  2791.                 $this->update_cache();
  2792.             }
  2793.  
  2794.             $this->update_single_instance( $instance, $this->id );
  2795.  
  2796.             if( $this->activate_cron )
  2797.             {
  2798.                 $this->restart_cron_job();
  2799.             }
  2800.  
  2801.             return $instance;
  2802.         }
  2803.  
  2804.  
  2805.         /**
  2806.          * Get info from instagram
  2807.          * based on https://gist.github.com/cosmocatalano/4544576
  2808.          *
  2809.          * @param string $username
  2810.          *
  2811.          * @return array|\WP_Error
  2812.          */
  2813.         protected function scrape_instagram( $username )
  2814.         {
  2815.             $username = strtolower( $username );
  2816.             $username = str_replace( '@', '', $username );
  2817.  
  2818.             $remote = wp_remote_get( 'https://www.instagram.com/' . trim( $username ), array( 'sslverify' => false, 'timeout' => 60 ) );
  2819.  
  2820.             if ( is_wp_error( $remote ) )
  2821.             {
  2822.                 return new WP_Error( 'site_down', __( 'Unable to communicate with Instagram.', 'avia_framework' ) );
  2823.             }
  2824.  
  2825.             if ( 200 != wp_remote_retrieve_response_code( $remote ) )
  2826.             {
  2827.                 return new WP_Error( 'invalid_response', __( 'Instagram did not return a 200.', 'avia_framework' ) );
  2828.             }
  2829.  
  2830.             $shards = explode( 'window._sharedData = ', $remote['body'] );
  2831.             $insta_json = explode( ';</script>', $shards[1] );
  2832.             $insta_array = json_decode( $insta_json[0], true );
  2833.  
  2834.             if ( ! $insta_array )
  2835.             {
  2836.                 return new WP_Error( 'bad_json', __( 'Instagram has returned invalid data.', 'avia_framework' ) );
  2837.             }
  2838.  
  2839.             if ( isset( $insta_array['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges'] ) )
  2840.             {
  2841.                 $images = $insta_array['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges'];
  2842.             }
  2843.             else
  2844.             {
  2845.                 return new WP_Error( 'bad_json_2', __( 'Instagram has returned invalid data.', 'avia_framework' ) );
  2846.             }
  2847.  
  2848.             if ( ! is_array( $images ) )
  2849.             {
  2850.                 return new WP_Error( 'bad_array', __( 'Instagram has returned invalid data.', 'avia_framework' ) );
  2851.             }
  2852.  
  2853.             $instagram = array();
  2854.  
  2855.             foreach ( $images as $image )
  2856.             {
  2857.                 // see https://github.com/stevenschobert/instafeed.js/issues/549
  2858.                 if ( $image['node']['is_video'] == true )
  2859.                 {
  2860.                     $type = 'video';
  2861.                 }
  2862.                 else
  2863.                 {
  2864.                     $type = 'image';
  2865.                 }
  2866.  
  2867.                 $caption = __( 'Instagram Image', 'avia_framework' );
  2868.  
  2869.                 if ( ! empty( $image['node']['edge_media_to_caption']['edges'][0]['node']['text'] ) )
  2870.                 {
  2871.                     $caption = wp_kses( $image['node']['edge_media_to_caption']['edges'][0]['node']['text'], array() );
  2872.                 }
  2873.  
  2874.                 $instagram[] = array(
  2875.                         'description'   => $caption,
  2876.                         'link'          => trailingslashit( '//instagram.com/p/' . $image['node']['shortcode'] ),
  2877.                         'time'          => $image['node']['taken_at_timestamp'],
  2878.                         'comments'      => $image['node']['edge_media_to_comment']['count'],
  2879.                         'likes'         => $image['node']['edge_liked_by']['count'],
  2880.                         'thumbnail'     => preg_replace( '/^https?\:/i', '', $image['node']['thumbnail_resources'][0]['src'] ),
  2881.                         'small'         => preg_replace( '/^https?\:/i', '', $image['node']['thumbnail_resources'][2]['src'] ),
  2882.                         'large'         => preg_replace( '/^https?\:/i', '', $image['node']['thumbnail_resources'][4]['src'] ),
  2883.                         'original'      => preg_replace( '/^https?\:/i', '', $image['node']['display_url'] ),
  2884.                         'type'          => $type,
  2885.                         'id'            => $image['node']['id']
  2886.                     );
  2887.             }
  2888.  
  2889.             $aviw_images_only = false;
  2890.             $aviw_images_only = apply_filters_deprecated( 'aviw_images_only', array( $aviw_images_only ), '4.3.1', 'avf_instagram_filter_files', __( 'Filter extended to filter images or videos', 'avia_framework' ) );
  2891.  
  2892.             /**
  2893.              * Filter which type of elements will be displayed.
  2894.              * Return an empty array to show all files.
  2895.              *
  2896.              * Possible values:   'video' | 'image'
  2897.              *
  2898.              * @since 4.3.1
  2899.              * @return array
  2900.              */
  2901.             $show = $aviw_images_only ? array( 'image' ) : array();
  2902.             $show = apply_filters( 'avf_instagram_filter_files', $show, $username );
  2903.  
  2904.             if( ! empty( $show ) )
  2905.             {
  2906.                 foreach( $instagram as $key => $media_item )
  2907.                 {
  2908.                     if( ! in_array( $media_item['type'], $show ) )
  2909.                     {
  2910.                         unset( $instagram[ $key ] );
  2911.                     }
  2912.                 }
  2913.  
  2914.                 $instagram = array_merge( $instagram );
  2915.             }
  2916.  
  2917.             if ( empty( $instagram ) )
  2918.             {
  2919.                 return new WP_Error( 'no_images', __( 'Instagram did not return any images.', 'avia_framework' ) );
  2920.             }
  2921.  
  2922.             return $instagram;
  2923.         }
  2924.  
  2925.  
  2926.         /**
  2927.          * WP Cron handler for background uploads
  2928.          *
  2929.          * @since 4.3.1
  2930.          */
  2931.         public function handler_scheduled_filecheck()
  2932.         {
  2933.             if( defined( 'WP_DEBUG ') && WP_DEBUG )
  2934.             {
  2935.                 error_log( '******************  In avia_instagram_widget::handler_scheduled_filecheck started' );
  2936.             }
  2937.  
  2938.             /**
  2939.              * Create a scheduled event to prevent double checks running on parallel pageloads
  2940.              */
  2941.             $this->schedule_cron_job( $this->expire_time * 2 );
  2942.  
  2943.             $settings = $this->get_settings();
  2944.             if( ! empty( $settings ) )
  2945.             {
  2946.                 $this->check_all_instances();
  2947.             }
  2948.  
  2949.             $this->schedule_cron_job( $this->expire_time * 2 );
  2950.  
  2951.             $this->sync_data();
  2952.  
  2953.             $this->schedule_cron_job( $this->expire_time );
  2954.  
  2955.             if( defined( 'WP_DEBUG ') && WP_DEBUG )
  2956.             {
  2957.                 error_log( '******************  In avia_instagram_widget::handler_scheduled_filecheck ended' );
  2958.             }
  2959.         }
  2960.  
  2961.  
  2962.         /**
  2963.          * Synchronises directory and cache data structure.
  2964.          * It might happen, that the update cronjob is running and user removes the last widget.
  2965.          * This leads to an inconsistent cache and directory structure.
  2966.          *
  2967.          * As user might have added new widgets again we have to sync cache with latest settings
  2968.          *
  2969.          * @since 4.3.1
  2970.          */
  2971.         public function sync_data()
  2972.         {
  2973.             if( defined( 'WP_DEBUG ') && WP_DEBUG )
  2974.             {
  2975.                 error_log( '******************  In avia_instagram_widget::sync_data started' );
  2976.             }
  2977.  
  2978.             $settings = $this->get_settings();
  2979.  
  2980.             if( empty( $settings ) && empty( $this->cache['instances'] ) )
  2981.             {
  2982.                 if( is_dir( $this->upload_folders['instagram_dir'] ) )
  2983.                 {
  2984.                     avia_backend_delete_folder( $this->upload_folders['instagram_dir'] );
  2985.                     $this->cache['last_updated'] = time();
  2986.                     $this->update_cache();
  2987.                 }
  2988.                 else {
  2989.                     write_log('No cache folder');
  2990.                 }
  2991.                 return;
  2992.             }
  2993.  
  2994.             $instance_infos = (array) $this->cache['instances'];
  2995.  
  2996.             /**
  2997.              * Remove all entries from cache that have no more entry in settings
  2998.              */
  2999.             $keys = array_keys( $instance_infos );
  3000.             $keys_to_keep = array();
  3001.  
  3002.             foreach ( $settings as $index => $setting )
  3003.             {
  3004.                 if( in_array( $setting['avia_key'], $keys ) )
  3005.                 {
  3006.                     $keys_to_keep[] = $setting['avia_key'];
  3007.                 }
  3008.             }
  3009.  
  3010.             $keys_to_remove = array_diff( $keys, $keys_to_keep );
  3011.  
  3012.             foreach( $keys_to_remove as $key )
  3013.             {
  3014.                 $folder = $this->upload_folders['instagram_dir'] . $instance_infos[ $key ]['upload_folder'];
  3015.                 avia_backend_delete_folder( $folder );
  3016.                 unset( $this->cache['instances'][ $key ] );
  3017.             }
  3018.  
  3019.             /**
  3020.              * Now we check that all directories belong to a cache entry
  3021.              */
  3022.             $cache_dirs = scandir( $this->upload_folders['instagram_dir'] );
  3023.             if( ! is_array( $cache_dirs ) )
  3024.             {
  3025.                 /**
  3026.                  * Something went wrong reading directory - folder does not exist, access denied, .....
  3027.                  * There is nothing we can do.
  3028.                  */
  3029.                 return;
  3030.             }
  3031.            
  3032.             $cache_dirs = array_diff( $cache_dirs, array( '.', '..' ) );
  3033.  
  3034.             $ref_dirs = array();
  3035.             foreach( $this->cache['instances'] as $key => $instance_info )
  3036.             {
  3037.                 $ref_dirs[] = $instance_info['upload_folder'];
  3038.             }
  3039.  
  3040.             $remove_dirs = array_diff( $cache_dirs, $ref_dirs );
  3041.  
  3042.             foreach( $remove_dirs as $remove_dir )
  3043.             {
  3044.                 avia_backend_delete_folder( $this->upload_folders['instagram_dir'] . $remove_dir );
  3045.             }
  3046.  
  3047.  
  3048.             if( empty( $this->cache['instances'] ) )
  3049.             {
  3050.                 avia_backend_delete_folder( $this->upload_folders['instagram_dir'] );
  3051.             }
  3052.  
  3053.             $this->cache['last_updated'] = time();
  3054.             $this->update_cache();
  3055.         }
  3056.  
  3057.         /**
  3058.          * WP Cron is disabled - we have to load files during pageload in admin area
  3059.          *
  3060.          * @since 4.3.1
  3061.          */
  3062.         public function handler_init_filecheck()
  3063.         {
  3064.             $settings = $this->get_settings();
  3065.             if( empty( $settings ) )
  3066.             {
  3067.                 /**
  3068.                  * Keep alive to allow to clean up in case when deleting a widget and check_all_instances() have run at same time.
  3069.                  * Due to internal WP caching this might have lead to inconsistent data structure.
  3070.                  */
  3071.                 if( $this->activate_cron  )
  3072.                 {
  3073.                     $this->restart_cron_job();
  3074.                 }
  3075.                 return;
  3076.             }
  3077.  
  3078.             /**
  3079.              * Fallback on version update - we need to switch to new data structure
  3080.              * Can be removed in very very future versions.
  3081.              *
  3082.              * @since 4.3.1
  3083.              */
  3084.             $instance = array_shift( $settings );
  3085.             if( ! isset( $instance['avia_key'] ) || empty( $instance['avia_key'] ) )
  3086.             {
  3087.                 $instances = $this->get_settings();
  3088.                 foreach( $instances as $key => &$instance )
  3089.                 {
  3090.                     $key = $this->create_avia_key( $instance, $this->id_base . "-{$key}" );
  3091.                     $instance['avia_key'] = $key;
  3092.                     $this->cache['instances'][ $key ] = array();
  3093.                 }
  3094.                 unset( $instance );
  3095.                 $this->save_settings( $instances );
  3096.  
  3097.                 $this->cache['last_updated'] = 0;
  3098.                 $this->update_cache();
  3099.  
  3100.                 $this->check_all_instances();
  3101.             }
  3102.  
  3103.             if( $this->activate_cron  )
  3104.             {
  3105.                 $this->restart_cron_job();
  3106.                 return;
  3107.             }
  3108.  
  3109.             /**
  3110.              * Check if we need to run an update
  3111.              */
  3112.             if( $this->cache['last_updated'] + $this->expire_time > time() )
  3113.             {
  3114.                 return;
  3115.             }
  3116.  
  3117.             /**
  3118.              * Only run update in backend
  3119.              */
  3120.             if( is_admin() )
  3121.             {
  3122.                 $this->check_all_instances();
  3123.             }
  3124.         }
  3125.  
  3126.  
  3127.         /**
  3128.          * Is called, when an instance of a widget is deleted - Both from active sidebars or inactive widget area.
  3129.          *
  3130.          * @since 4.3.1
  3131.          * @param string $widget_id
  3132.          * @param string $sidebar_id
  3133.          * @param string $id_base
  3134.          */    
  3135.         public function handler_delete_widget( $widget_id, $sidebar_id, $id_base )
  3136.         {
  3137.             $id = str_replace( $id_base . '-', '', $widget_id );
  3138.  
  3139.             $settings = $this->get_settings();
  3140.             if( empty( $settings ) || empty( $settings[ $id ] ) )
  3141.             {
  3142.                 return;
  3143.             }
  3144.  
  3145.             $instance = $settings[ $id ];
  3146.  
  3147.             $instance_info = isset( $this->cache['instances'][ $instance['avia_key'] ] ) ? $this->cache['instances'][ $instance['avia_key'] ] : array();
  3148.             if( empty( $instance_info ) )
  3149.             {
  3150.                 return;
  3151.             }
  3152.  
  3153.             $instance = $this->parse_args_instance( $instance );
  3154.             $instance_info = $this->parse_args_instance_cache( $instance_info );
  3155.  
  3156.             if( count( $settings ) <= 1 )
  3157.             {
  3158.                 avia_backend_delete_folder( $this->upload_folders['instagram_dir'] );
  3159.                 $this->cache['instances'] = array();
  3160.             }
  3161.             else
  3162.             {
  3163.                 $folder = $this->upload_folders['instagram_dir'] . $instance_info['upload_folder'];
  3164.                 avia_backend_delete_folder( $folder );
  3165.                 unset( $this->cache['instances'][ $instance['avia_key'] ] );
  3166.             }
  3167.  
  3168.             $this->update_cache();
  3169.         }
  3170.  
  3171.  
  3172.         /**
  3173.          * This is a fallback function to ensure that the cron job is running
  3174.          *
  3175.          * @since 4.3.1
  3176.          */
  3177.         protected function restart_cron_job()
  3178.         {
  3179.            $timestamp = wp_next_scheduled( 'av_instagram_scheduled_filecheck' );
  3180.            if( false === $timestamp )
  3181.            {
  3182.                $this->schedule_cron_job( $this->expire_time );
  3183.                return;
  3184.            }
  3185.  
  3186.            /**
  3187.             * This is a fallback to prevent a blocking of updates
  3188.             */
  3189.            if( $timestamp > ( time() + $this->expire_time * 2 ) )
  3190.            {
  3191.                $this->schedule_cron_job( $this->expire_time * 2 );
  3192.            }
  3193.         }
  3194.  
  3195.         /**
  3196.          * Removes an existing cron job and creates a new one
  3197.          *
  3198.          * @since 4.3.1
  3199.          * @param int $delay_seconds
  3200.          * @return boolean
  3201.          */
  3202.         protected function schedule_cron_job( $delay_seconds = 0 )
  3203.         {  
  3204.             $timestamp = wp_next_scheduled( 'av_instagram_scheduled_filecheck' );
  3205.             if( false !== $timestamp )
  3206.             {
  3207.                 wp_unschedule_hook( 'av_instagram_scheduled_filecheck' );
  3208.             }
  3209.  
  3210.             $timestamp = time() + $delay_seconds;
  3211.  
  3212.             $scheduled = wp_schedule_single_event( $timestamp, 'av_instagram_scheduled_filecheck' );
  3213.  
  3214.             return false !== $scheduled;
  3215.         }
  3216.  
  3217.  
  3218.         /**
  3219.          * Scan all instances of this widget and update cache data
  3220.          *
  3221.          * @since 4.3.1
  3222.          */
  3223.         protected function check_all_instances()
  3224.         {
  3225.             $settings = $this->get_settings();
  3226.  
  3227.             foreach ( $settings as $key => $instance )
  3228.             {
  3229.                 $id_widget = $this->id_base . "-{$key}";
  3230.  
  3231.                 if( false === is_active_widget( false, $id_widget, $this->id_base, false ) )
  3232.                 {
  3233.                     continue;
  3234.                 }
  3235.  
  3236.                 $this->update_single_instance( $instance, $id_widget );
  3237.             }
  3238.  
  3239.             $this->cache['last_updated'] = time();
  3240.             $this->update_cache();
  3241.         }
  3242.  
  3243.  
  3244.         /**
  3245.          * Updates the cache for the given instance.
  3246.          * As a fallback for older versions the instance is updated and returned.
  3247.          *
  3248.          * @since 4.3.1
  3249.          * @param array $instance
  3250.          * @param string $id_widget
  3251.          * @return array
  3252.          */
  3253.         protected function update_single_instance( array $instance, $id_widget )
  3254.         {
  3255.             set_time_limit( 0 );
  3256.  
  3257.             $instance = $this->parse_args_instance( $instance );
  3258.  
  3259.             /**
  3260.              * Fallback for old versions - update to new datastructure
  3261.              */
  3262.             if( empty( $instance['avia_key'] ) )
  3263.             {
  3264.                 $key = $this->create_avia_key( $instance, $id_widget );
  3265.                 $instance['avia_key'] = $key;
  3266.                 $this->cache['instances'][ $key ] = array();
  3267.             }
  3268.  
  3269.             $instance_cache = isset( $this->cache['instances'][ $instance['avia_key'] ] ) ? $this->cache['instances'][ $instance['avia_key'] ] : array();
  3270.             $instance_cache = $this->parse_args_instance_cache( $instance_cache );
  3271.  
  3272.             /**
  3273.              * Create upload directory if not exist. Upload directory will be deleted when widget instance is removed.
  3274.              */
  3275.             if( ( 'server' == $instance['cache'] ) && empty( $instance_cache['upload_folder'] ) && ! empty( $instance['username'] ) )
  3276.             {
  3277.                 $id = str_replace( $this->id_base . '-', '', $id_widget );
  3278.                 $f = empty( $instance['title'] ) ? $instance['username'] : $instance['title'];
  3279.                 $folder_name = substr( AviaHelper::save_string( $id . '-' . $f, '-' ), 0, 30 );
  3280.                 $folder = $this->upload_folders['instagram_dir'] . $folder_name;
  3281.  
  3282.                 $created = avia_backend_create_folder( $folder, false, 'unique' );
  3283.                 if( $created )
  3284.                 {
  3285.                     $split = pathinfo( $folder );
  3286.                     $instance_cache['upload_folder'] = $split['filename'];
  3287.                     $instance_cache['path_error'] = '';
  3288.                     $instance_cache['cached_list'] = array();
  3289.                 }
  3290.                 else
  3291.                 {
  3292.                     $instance_cache['path_error'] = sprintf( __( 'Unable to create cache folder "%s". Files will be loaded directly from instagram', 'avia_framework' ), $folder );
  3293.                 }
  3294.             }
  3295.  
  3296.             $username = $instance['username'];
  3297.             $number = $instance['number'];
  3298.  
  3299.             if( ! empty( $username) )
  3300.             {
  3301.                 $media_array = $this->scrape_instagram( $username );
  3302.  
  3303.                 if ( ! is_wp_error( $media_array ) )
  3304.                 {
  3305.                     $instance_cache['instagram_error'] = '';
  3306.                     $instance_cache['instagram_list'] = array_slice( $media_array, 0, $number );
  3307.  
  3308.                     if( 'server' == $instance['cache'] )
  3309.                     {
  3310.                         $instance_cache = $this->cache_files_in_upload_directory( $media_array, $instance, $instance_cache );
  3311.                     }
  3312.                 }
  3313.                 else
  3314.                 {
  3315.                     /**
  3316.                      * We only store error message but keep existing files for fallback so we do not break widget
  3317.                      */
  3318.                     $instance_cache['instagram_error'] = $media_array->get_error_message();
  3319.                 }
  3320.             }
  3321.             else
  3322.             {
  3323.                 $instance_cache['instagram_error'] = __( 'You need to specify an instgram username.', 'avia_framework' );
  3324.                 $instance_cache['instagram_list'] = array();
  3325.                 $instance_cache['cached_list'] = array();
  3326.             }
  3327.  
  3328.             $instance_cache['last_update'] = time();
  3329.  
  3330.             $this->cache['instances'][ $instance['avia_key'] ] = $instance_cache;
  3331.             $this->update_cache();
  3332.  
  3333.             return $instance;
  3334.         }
  3335.  
  3336.  
  3337.         /**
  3338.          * Updates the local stored files in upload directory
  3339.          * Already downloaded files are not updated.
  3340.          * If an error occurs, we try to download more files as fallback to provide requested number of files
  3341.          * in frontend.
  3342.          *
  3343.          * No longer needed files are removed from cache.
  3344.          *
  3345.          * @since 4.3.1
  3346.          * @param array $instagram_files
  3347.          * @param array $instance
  3348.          * @param array $instance_cache
  3349.          * @return array
  3350.          */
  3351.         protected function cache_files_in_upload_directory( array $instagram_files, array $instance, array $instance_cache )
  3352.         {
  3353.             set_time_limit( 0 );
  3354.  
  3355.             $cached_files = $instance_cache['cached_list'];
  3356.  
  3357.             $new_cached_files = array();
  3358.             $no_errors = 0;
  3359.  
  3360.             foreach( $instagram_files as $instagram_file )
  3361.             {
  3362.                 $id = $instagram_file['id'];
  3363.  
  3364.                 $found = false;
  3365.                 foreach( $cached_files as $key_cache => $cached_file )
  3366.                 {
  3367.                     if( $id == $cached_file['id'] )
  3368.                     {
  3369.                         /**
  3370.                          * If an error occured in a previous file load we try to reload all files again
  3371.                          */
  3372.                         if( ! empty( $cached_file['errors'] ) )
  3373.                         {
  3374.                             $this->remove_single_cached_files( $cached_file, $instance_cache );
  3375.                             unset( $cached_files[ $key_cache ] );
  3376.                             break;
  3377.                         }
  3378.  
  3379.                         /**
  3380.                          * As a fallback (or if other sizes were added later) we check if the cached files exist
  3381.                          */
  3382.                         $path = trailingslashit( $this->upload_folders['instagram_dir'] . $instance_cache['upload_folder'] );
  3383.                         foreach( $this->cached_file_sizes as $size )
  3384.                         {
  3385.                             if( empty( $cached_file[ $size ] ) || ! file_exists( $path . $cached_file[ $size ] ) )
  3386.                             {
  3387.                                 $this->remove_single_cached_files( $cached_file, $instance_cache );
  3388.                                 unset( $cached_files[ $key_cache ] );
  3389.                                 break;
  3390.                             }
  3391.                         }
  3392.  
  3393.                         if( ! isset( $cached_files[ $key_cache ] ) )
  3394.                         {
  3395.                             break;
  3396.                         }
  3397.  
  3398.                         $ncf = $cached_file;
  3399.  
  3400.                         $ncf['description'] = $instagram_file['description'];
  3401.                         $ncf['link'] = $instagram_file['link'];
  3402.                         $ncf['time'] = $instagram_file['time'];
  3403.                         $ncf['comments'] = $instagram_file['comments'];
  3404.                         $ncf['likes'] = $instagram_file['likes'];
  3405.                         $ncf['type'] = $instagram_file['type'];
  3406.  
  3407.                         $new_cached_files[] = $ncf;
  3408.  
  3409.                         unset( $cached_files[ $key_cache ] );
  3410.                         $found = true;
  3411.                         break;
  3412.                     }
  3413.                 }
  3414.  
  3415.                 if( ! $found )
  3416.                 {
  3417.                     $new_cached_files[] = $this->download_from_instagram( $instagram_file, $instance, $instance_cache );
  3418.                 }
  3419.  
  3420.                 $last = $new_cached_files[ count( $new_cached_files ) - 1 ];
  3421.  
  3422.                 /**
  3423.                  * Check if we could cache the file in requested size - we might have got a warning from chmod
  3424.                  */
  3425.                 if( empty( $last['errors'] ) || ! empty( $last[ $instance['size'] ] ) )
  3426.                 {
  3427.                     $no_errors++;
  3428.                 }
  3429.  
  3430.                 /**
  3431.                  * Also break if we get too many errors
  3432.                  */
  3433.                 if( $no_errors >= $instance['number'] || count( $new_cached_files ) > ( $instance['number'] * 2 ) )
  3434.                 {
  3435.                     break;
  3436.                 }
  3437.             }
  3438.  
  3439.             /**
  3440.              * Now we add all remaining cached files to fill up requested number of files
  3441.              */
  3442.             if( $no_errors < $instance['number'] )
  3443.             {
  3444.                 foreach( $cached_files as $key_cache => $cached_file )
  3445.                 {
  3446.                     $new_cached_files[] = $cached_file;
  3447.                     if( empty( $cached_file['errors'] ) )
  3448.                     {
  3449.                         $no_errors++;
  3450.                     }
  3451.  
  3452.                     unset( $cached_files[ $key_cache ] );
  3453.  
  3454.                     if( $no_errors >= $instance['number'] )
  3455.                     {
  3456.                         break;
  3457.                     }
  3458.                 }
  3459.             }
  3460.  
  3461.             /**
  3462.              * Now we delete no longer needed files
  3463.              */
  3464.             foreach( $cached_files as $key_cache => $cached_file )
  3465.             {
  3466.                 $this->remove_single_cached_files( $cached_file, $instance_cache );
  3467.                 unset( $cached_files[ $key_cache ] );
  3468.             }
  3469.  
  3470.             /**
  3471.              * Save results and count errors
  3472.              */
  3473.             $err_cnt = 0;
  3474.             $count = 1;
  3475.  
  3476.             foreach( $new_cached_files as $new_file )
  3477.             {
  3478.                 if( ! empty( $new_file['errors'] ) )
  3479.                 {
  3480.                     $err_cnt++;
  3481.                 }
  3482.                 $count++;
  3483.  
  3484.                 if( $count > $instance['number'] )
  3485.                 {
  3486.                     break;
  3487.                 }
  3488.             }
  3489.  
  3490.             $instance_cache['upload_errors'] = ( 0 == $err_cnt ) ? false : $err_cnt;
  3491.             $instance_cache['cached_list'] = $new_cached_files;
  3492.  
  3493.             return $instance_cache;
  3494.         }
  3495.  
  3496.         /**
  3497.          * Downloads the files from instagram and stores them in local cache
  3498.          *
  3499.          * @since 4.3.1
  3500.          * @param array $instagram_file
  3501.          * @param array $instance
  3502.          * @param array $instance_cache
  3503.          * @return array
  3504.          */
  3505.         protected function download_from_instagram( array $instagram_file, array $instance, array $instance_cache )
  3506.         {
  3507.             $new_cached_file = $instagram_file;
  3508.             $new_cached_file['errors'] = array();
  3509.             $instagram_schema = 'https:';
  3510.  
  3511.             $cache_path = trailingslashit( $this->upload_folders['instagram_dir'] . $instance_cache['upload_folder'] );
  3512.  
  3513.             foreach( $this->cached_file_sizes as $size )
  3514.             {
  3515.                 $file_array = array();
  3516.                 $file_array['name'] = basename( $instagram_file[ $size ] );
  3517.  
  3518.                 // Download file to temp location - include file if called from frontend.
  3519.                 if( ! function_exists( 'download_url' ) )
  3520.                 {
  3521.                     $s = trailingslashit( ABSPATH ) . 'wp-admin/includes/file.php';
  3522.                     require_once $s;
  3523.                 }
  3524.  
  3525.                 $file_array['tmp_name'] = download_url( $instagram_schema . $instagram_file[ $size ] );
  3526.  
  3527.                 // If error storing temporarily, return the error.
  3528.                 if( is_wp_error( $file_array['tmp_name'] ) )
  3529.                 {
  3530.                     $new_cached_file[ $size ] = '';
  3531.                     $new_cached_file['errors'] = array_merge( $new_cached_file['errors'], $file_array['tmp_name']->get_error_messages() );
  3532.                     continue;
  3533.                 }
  3534.  
  3535.                 $new_file_name = $size . '_' . $file_array['name'];
  3536.                 $new_name = $cache_path . $new_file_name;
  3537.  
  3538.                 $moved = avia_backend_rename_file( $file_array['tmp_name'], $new_name );
  3539.                 if( is_wp_error( $moved ) )
  3540.                 {
  3541.                     $new_cached_file[ $size ] = '';
  3542.                     $new_cached_file['errors'] = array_merge( $new_cached_file['errors'], $moved->get_error_messages() );
  3543.                     continue;
  3544.                 }
  3545.  
  3546.                 /**
  3547.                  * Try to change accessability of file
  3548.                  */
  3549.                 if( ! chmod( $new_name, 0777 ) )
  3550.                 {
  3551.                     $new_cached_file['errors'][] = sprintf( __( 'Could not change user rights of file %s to 777 - file might not be visible in frontend.', 'avia_framework' ), $new_name );
  3552.                 }
  3553.  
  3554.                 $new_cached_file[ $size ] = $new_file_name;
  3555.             }
  3556.  
  3557.             return $new_cached_file;
  3558.         }
  3559.  
  3560.  
  3561.         /**
  3562.          * Removes all cashed files from $cached_file_info
  3563.          *
  3564.          * @since 4.3.1
  3565.          * @param array $cached_file_info
  3566.          * @param array $instance_cache
  3567.          * @return array
  3568.          */
  3569.         protected function remove_single_cached_files( array $cached_file_info, array $instance_cache )
  3570.         {
  3571.             $cache_path = trailingslashit( $this->upload_folders['instagram_dir'] . $instance_cache['upload_folder'] );
  3572.  
  3573.             foreach( $this->cached_file_sizes as $size )
  3574.             {
  3575.                 if( ! empty( $cached_file_info[ $size ] ) )
  3576.                 {
  3577.                     $file = $cache_path . $cached_file_info[ $size ];
  3578.  
  3579.                     if( file_exists( $file ) )
  3580.                     {
  3581.                         unlink( $file );
  3582.                     }
  3583.                     $cached_file_info[ $size ] = '';
  3584.                 }
  3585.             }
  3586.  
  3587.             return $cached_file_info;
  3588.         }
  3589.     }
  3590. }
Advertisement
Add Comment
Please, Sign In to add comment