<?php

class kippis_widget_post extends WP_Widget
{
  function kippis_widget_post() {
    $widget_id = 'kippis_widget_post';
    $widget_ops = array('classname' => 'kippis_widget_post','description' => __('Show a post/page/whatever as a widget','kippis'));
    $this->WP_Widget($widget_id,__('Kippis Featured post','kippis'),$widget_ops);
  }

  function widget($args,$instance) {
    extract($args);
    echo $before_widget;
    $title = '';
    if (!empty($instance['title'])) {
      $title = $before_title . apply_filters('widget_title',$instance['title']) . $after_title;
    }
    echo $this->getPost($title,$instance['post_url']);
    echo $after_widget;
  }

  function update($new_instance,$old_instance) {
    $instance = $old_instance;
    $instance['title'   ] = strip_tags($new_instance['title'   ]);
    $instance['post_url'] = strip_tags($new_instance['post_url']);
    return $instance;
  }

  function form($instance) {
    $defaults = array('title'    => __('Featured Post','kippis')
                     ,'post_url' => ''
                     );
    $instance = wp_parse_args((array)$instance,$defaults);
    echo '<p>'
       .   '<label for="' . $this->get_field_id('title') . '">' . __('Title:','kippis') . '</label>'
       .   '<input  id="' . $this->get_field_id('title') . '" name="' . $this->get_field_name('title') . '" value="' . $instance['title'] . '" style="width:100%;" />'
       . '</p>'
       . '<p>'
       .   '<label for="' . $this->get_field_id('post_url') . '">' . __('Post URL:','kippis') . '</label>'
       .   '<input  id="' . $this->get_field_id('post_url') . '" name="' . $this->get_field_name('post_url') . '" value="' . $instance['post_url'] . '" style="width:100%;" />'
       . '</p>'
       ;
  }

  function getPost($title,$url) {
    //  Originally from http://core.trac.wordpress.org/browser/tags/3.3.1/wp-includes/formatting.php - function wp_trim_excerpt($text = '')
    $id = url_to_postid($url);
    if ($id) {
      $post = get_post($id);
      if ($post) {
        $thumbnail = get_the_post_thumbnail($post->ID,'thumbnail',array('class'	=> "attachment-thumbnail alignleft"));
        $excerpt = $post->post_content;
        $excerpt = strip_shortcodes($excerpt);
        //$excerpt = apply_filters('the_content',$excerpt);
        //$excerpt = str_replace(']]>',']]&gt;',$excerpt);
        $excerpt_length = apply_filters('excerpt_length',55);
        $excerpt_more = apply_filters('excerpt_more',' ' . '[...]');
        $excerpt = wp_trim_words($excerpt,$excerpt_length);
        return $title
             . '<h3><a href="' . get_permalink($post->ID) . '">' . $post->post_title . '</a></h3>'
             . $thumbnail
             . apply_filters('wp_trim_excerpt',$excerpt)
             . '<div style="clear:both;"></div>'
             ;
      }
    }
    return $title;
  }
}

