<?php
/*
Plugin Name: Yet Another Daily Delicious 
Plugin URI: http://jawe.net/wiki/dev/wordpress/yadd
Description: Daily posts the del.icio.us links added the day before.
Version: 0.0.6
Author: Jan Wessely
Author URI: http://jawe.net/
*/

/*  Copyright 2007  Jan Wessely  (email: info@jawe.net)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

/*
History:
1.0: * Converted from original yadd.php (see below).
     * Current del.icio.us API
     * WP 2.3.1 API instead of direct SQL 
*/
#
# From the original yadd.php:
#
# This is yadd.php V1.0 by Marc Nozell (marc@nozell.com) based on
# Stephen Eyre's dailydelicious
# (http://www.dot-totally.co.uk/dailydelicious.txt)
#
# See http://www.nozell.com/blog/ for the latest version of
# 'yet another daily delicious' (yadd.php)
#
# Enjoy,

# -marc

$yadd_content '';
$yadd_empty false;
$yadd_tags = array();

define('YADD_PATH''/wp-content/plugins/yadd/');

function 
yadd_admin_menu() {
    
add_options_page('YADD Options''YADD'8basename(__FILE__), 'yadd_options_page');
}

function 
yadd_notice() {
    global 
$plugin_page;
    if (
$plugin_page == basename(__FILE__)) {
        if (
$_GET['updated'] == 'true') {
            if (
get_option('yadd_task_active') == 'true') {
                
wp_clear_scheduled_hook('yadd_task');
                
$tomorrow time() + 24 60 60;
                
$tasktime mktime(000date('n'$tomorrow), date('d'$tomorrow), date('Y'$tomorrow));
                
wp_schedule_event($tasktime'daily''yadd_task');
?>
    <div id='yadd-message' class='updated fade'>YADD task scheduled at <?php echo date('r'$tasktime); ?></div>
<?php
            
} else {
                
wp_clear_scheduled_hook('yadd_task');
?>
    <div id='yadd-message' class='updated fade'>YADD task stopped</div>
<?php
            
}
        } else {
            
$nexttime wp_next_scheduled('yadd_task');
            if (
$nexttime) {
?>
    <div id='yadd-message' class='updated fade'>Next YADD run at <?php echo date('r'$nexttime?></div>
<?php
            
} else {
?>
    <div id'yadd-message' class='updated fade'>YADD task inactive</div>
<?php
            
}
        }
    }
}

function 
yadd_options_page() {
    if (
$_GET['yadd_manual_run'] == 'true') {
        
yadd_post();
        echo 
'<div id="yadd-message" class="updated fade">YADD invoked manually</div>';
    }
?>
<div class="wrap">
<h2>YADD Plugin Options</h2>
<form method="post" action="options.php">

        <?php wp_nonce_field('update-options'?>
        <input type="hidden" name="action" id="action" value="update" />
        <input type="hidden" name="page_options" id="page_options" value="yadd_del_user,yadd_del_password,yadd_wp_user,yadd_wp_category,yadd_allowcomments,yadd_allowpings,yadd_title_timeformat,yadd_titleformat,yadd_slug,yadd_add_tags,yadd_tag_prefix,yadd_delete_settings,yadd_task_active" />

        <p class="submit">
            <input type="submit" name="Submit" id="Submit-top" value="Update Options &raquo;" />
        </p>
        
        <table class="optiontable">
        <tr>
            <th scope="row"><label for="yadd_del_user">del.icio.us User</label></th>
            <td><input type="text" name="yadd_del_user" id="yadd_del_user" value="<?php echo get_option('yadd_del_user'); ?>" /></td>
        </tr><tr>
            <th scope="row"><label for="yadd_del_password">del.icio.us Password</label></th>
            <td><input type="password" name="yadd_del_password" id="yadd_del_password" value="<?php echo get_option('yadd_del_password'); ?>" /></td>
        </tr><tr>
            <th scope="row"><label for="yadd_wp_user">WordPress User</label></th>
            <td>
                <select name="yadd_wp_user" id="yadd_wp_user">
 <?php
    $users 
get_users_of_blog();
    
$userid get_option('yadd_wp_user');
    foreach (
$users as $user) {
        echo 
'                    <option value="' $user->user_id '"' . ($userid == $user->user_id ' selected="selected"' '') . '>' $user->display_name "</option>\n";
    }
?>
                </select>
            </td>
        </tr><tr>
            <th scope="row"><label for="yadd_wp_category">WordPress Category</label></th>
            <td>
                <select name="yadd_wp_category" id="yadd_wp_category">
                    <option value="">-- None --</option>
<?php
    $categories 
get_categories(); 
    
$catid get_option('yadd_wp_category');
    foreach (
$categories as $cat) {
        echo 
'                    <option value="' $cat->cat_ID '"' . ($catid == $cat->cat_ID ' selected="selected"' '') . '>' $cat->cat_name "</option>\n";
    }
?>
                </select>
            </td>
        </tr><tr>
            <th scope="row"><label for="yadd_allowcomments">Allow comments?</label></th>
            <td><input type="checkbox" name="yadd_allowcomments" id="yadd_allowcomments" <?php if (get_option('yadd_allowcomments') == 'open') echo 'checked="checked"'?> value="open" /></td>
        </tr><tr>
            <th scope="row"><label for="yadd_allowpings">Allow Trackback Pings?</label></th>
            <td><input type="checkbox" name="yadd_allowpings" id="yadd_allowpings" <?php if (get_option('yadd_allowpings') == 'open') echo 'checked="checked"'?> value="open" /></td>
        </tr><tr>
            <th scope="row"><label for="yadd_title_timeformat">Title time format</label></th>
            <td><input type="text" name="yadd_title_timeformat" id="yadd_title_timeformat" value="<?php echo get_option('yadd_title_timeformat'); ?>" /></td>
        </tr><tr>
            <th scope="row"><label for="yadd_titleformat">Title format</label></th>
            <td><input type="text" name="yadd_titleformat" id="yadd_titleformat" value="<?php echo get_option('yadd_titleformat'); ?>" /></td>
        </tr><tr>
            <th scope="row"><label for="yadd_slug">Slug</label></th>
            <td><input type="text" name="yadd_slug" id="yadd_slug" value="<?php echo get_option('yadd_slug'); ?>" /></td>
        </tr><tr>
            <th scope="row"><label for="yadd_tag_prefix">Tags link to</label></th>
            <td>
                <select name="yadd_tag_prefix" id="yadd_tag_prefix">
                    <option value="user" <?php if (get_option('yadd_tag_prefix') == 'user') echo 'selected="selected"'?>>User's tags</option>
                    <option value="all" <?php if (get_option('yadd_tag_prefix') == 'all') echo 'selected="selected"'?>>All tags</option>
                </select>
            </td>
        </tr><tr>
            <th scope="row"><label for="yadd_add_tags">Add del.icio.us tags as WP tags?</label></th>
            <td><input type="checkbox" name="yadd_add_tags" id="yadd_add_tags" <?php if (get_option('yadd_add_tags') == 'true') echo             'checked="checked"'?> value="true" /></td>
        </tr><tr>
            <th scope="row"><label for="yadd_delete_settings">Delete YADD settings on deactivation</label></th>
            <td><input type="checkbox" name="yadd_delete_settings" id="yadd_delete_settings" <?php if (get_option('yadd_delete_settings') == 'true') echo 'checked="checked"'?> value="true" /></td>
        </tr><tr>
            <th scope="row">Activate Daily Posting Task</th>
            <td>
                <input type="radio" name="yadd_task_active" id="yadd_task_active_yes" value="true" <?php if (get_option('yadd_task_active') == 'true') echo 'checked="checked"'?>/> <label for="yadd_task_active_yes">Yes</label><br />
                <input type="radio" name="yadd_task_active" id="yadd_task_active_no" value="false" <?php if (get_option('yadd_task_active') != 'true') echo 'checked="checked"'?>/> <label for="yadd_task_active_no">No</label>
            </td>
        </tr>
        </table>

        <p class="submit">
            <input type="submit" name="Submit" id="Submit-bottom" value="Update Options &raquo;" />
        </p>

        <p>
            Run <a href="<?php echo $_SERVER['PHP_SELF'] . '?page=' basename(__FILE__) . '&amp;yadd_manual_run=true' ?>">manually</a>
        </p>
</form>
</div>
<?php
}

function 
yadd_head() {
    if (!(
is_page() || is_404())) : ?>
<link rel="stylesheet" type="text/css" href="<?php echo htmlspecialchars(get_option('home') . YADD_PATH); ?>yadd.css" media="screen" />
<?php endif;
}

function 
yadd_start_element($parser$name$attrs)
{
    global 
$yadd_content;

    if (
$name == "POSTS") {
        
$yadd_content .= "<div class='yadd'><ul class='yadd-links'>";
    }
    else {
        global 
$yadd_empty;
        
$yadd_empty false;
        global 
$yadd_tags;
        
$tagsarray explode(' 'htmlspecialchars($attrs['TAG']));
        
$tags '';
        
$prefix get_option('yadd_tag_prefix') == 'user' get_option('yadd_del_user') : 'tag';
        foreach(
$tagsarray as $tag) {
            
$tags .= '<a href="http://del.icio.us/' $prefix '/' $tag '">' $tag '</a> ';
            
$yadd_tags[] = $tag;
        }
        
$yadd_content .= "<li class='yadd-link'><a href='"
                 
htmlspecialchars($attrs['HREF'])
                 . 
"' title='"
                 
htmlspecialchars($attrs['HREF']) 
                 . 
"' class='yadd-description'>"
                 
htmlspecialchars($attrs['DESCRIPTION'])
                 . 
"</a>"
                 
. (!empty($attrs['EXTENDED']) ? 
                        
"<div class=\"yadd-extended\">" htmlspecialchars($attrs['EXTENDED']) . "</div>" "")
                 . 
"<div class='yadd-tags'>Tags: $tags</div></li>";
    }
}


function 
yadd_end_element($parser$name)
{
    global 
$yadd_content;

    if (
$name == "POSTS") {
        
$del_url "http://del.icio.us/" get_option('yadd_del_user');
        
$yadd_content .= "</ul>";
        
$yadd_content .= "<p><a href='$del_url'>Alle Links &raquo;</a></p></div>";
    }
}

function 
yadd_post() {
    global 
$yadd_content;
    global 
$yadd_tags;
    global 
$yadd_empty;

    
$yadd_tags = array();
    
$yadd_empty true;
    
$yesterday time() - 24 60 60;
    
$dt date("Y-m-d"$yesterday);
    
$del_user get_option('yadd_del_user');
    
$del_password get_option('yadd_del_password');

    
//echo("Fetching del.icio.us links for $dt\n");

    
$fp fopen("https://$del_user:$del_password@api.del.icio.us/v1/posts/get?dt=$dt""r");

    
$yadd_content "";

    
//echo("Parsing XML\n");

    
$xml_parser xml_parser_create();
    
xml_set_element_handler($xml_parser"yadd_start_element""yadd_end_element");

    while (
$data fread($fp4096)) {
       if (!
xml_parse($xml_parser$datafeof($fp))) {
           die(
sprintf("XML error: %s at line %d",
                       
xml_error_string(xml_get_error_code($xml_parser)),
                       
xml_get_current_line_number($xml_parser)));
       }
    }
    
xml_parser_free($xml_parser);

    if(
$yadd_empty) {
        
//echo("\nNo links for $dt\n");
        
return;
    }

    
setlocale(LC_ALLWPLANG);
    
$wp_postttitle sprintf(get_option('yadd_titleformat'), utf8_encode(strftime(get_option('yadd_title_timeformat'), $yesterday)));
    
$guid $wp_url "/" date("Y/m/d/") . get_option('yadd_slug') . "/";

    
$postargs = array(
            
'post_author' => get_option('yadd_wp_user'),
            
'post_content' => addslashes($yadd_content),
            
'post_title' => addslashes($wp_postttitle),
            
'post_status' => 'publish',
            
'comment_status' => (get_option('yadd_allowcomments') == 'open' 'open' 'closed'),
            
'ping_status' => (get_option('yadd_allowpings') == 'open' 'open' 'closed'),
            
'post_name' => get_option('yadd_slug'),
            
'guid' => $guid,
            
'post_category' => array(intval(get_option('yadd_wp_category'))), 
    );
    if (
get_option('yadd_add_tags') == 'true')
        
$postargs['tags_input'] = $yadd_tags;

    
// no auto formatting please
    
remove_filter ('the_content',  'wpautop');
    
wp_insert_post($postargs);

    
//echo ("\nDone\n");
}

function 
yadd_activate() {
    
add_option('yadd_del_user',         '',                 'Del.icio.us user name');
    
add_option('yadd_del_password',     '',                 'Del.icio.us password');
    
add_option('yadd_wp_user',          '',                 'WordPress User');
    
add_option('yadd_wp_category',      '',                 'WordPress category ID');
    
add_option('yadd_allowcomments',    get_option('default_comment_status'),             'Allow comments?');
    
add_option('yadd_allowpings',       get_option('default_ping_status'),             'Allow trackback pings?');
    
add_option('yadd_title_timeformat''%A, %d. %B %Y',    'Timeformat in title, see strftime');
    
add_option('yadd_titleformat',      'Links vom %s',     'Title format');
    
add_option('yadd_slug',             'links',            'Post Slug');
    
add_option('yadd_tag_prefix',       'user',             'Tags link to all or user\'s tags?');
    
add_option('yadd_add_tags',         'true',             'Add del.icio.us tags as WP tags?');
    
add_option('yadd_delete_settings',  'false',            'Delete all settings on deactivation?');
    
add_option('yadd_task_active',      'false',            'Activate YADD task?');
}

function 
yadd_deactivate() {
    if (
get_option('yadd_delete_settings') == 'true') {
        
delete_option('yadd_del_user');
        
delete_option('yadd_del_password');
        
delete_option('yadd_wp_user');
        
delete_option('yadd_wp_category');
        
delete_option('yadd_allowcomments');
        
delete_option('yadd_allowpings');
        
delete_option('yadd_title_timeformat');
        
delete_option('yadd_titleformat');
        
delete_option('yadd_slug');
        
delete_option('yadd_tag_prefix');
        
delete_option('yadd_add_tags');
        
delete_option('yadd_delete_settings');
        
delete_option('yadd_task_active');
    }
}

// init

register_activation_hook(__FILE__'yadd_activate');
register_deactivation_hook(__FILE__'yadd_deactivate');
add_action('admin_menu''yadd_admin_menu');
add_action('yadd_task''yadd_post');
add_action('admin_notices''yadd_notice');
add_action('wp_head''yadd_head');

//Setup VIM: ex: et ts=4 sw=4 enc=utf-8 :
?>