Posts tagged ‘PHP’

Postie (for WordPress) [can] rock multiple image styles

Forget some of those nice things I said about the iPhone WordPress App. Version 2.6.3 is still causing me headaches.

What I really wanted was the ability to quickly post photos front and center. The problem is that more often, I am writing blog posts and all I want is for the image to float on the right side of the text and let the reader see a larger version of the image when clicking on it. From something like Windows Live Writer, that would be easy to choose which style to use but from the iPhone that has been less than easy. Since most of my mobile blogging is thru the Postie plugin for WordPress, I figured there had to be a way to support different image styles.

I started by hacking the Postie code and soon decided that was unwise. Then I thought about the postie_post filter function. Eureka! (the realization not the TV show). So I set out to write a function that would post process after Postie had done its thing. Here is how it all folds together …

I set Postie to use customer markup (on the image tab) which generates both the markup for a medium sized image floating on the right as well as the large markup of the image centered in the post. I then wrap the entire customer template field with a HEAD and TAIL markers. Finally, I add a marker for the first style and another marker for the second. The filter code just keys off how long the post is to decide if it should use one style or there other. In truth, it should be smarter than that but I was lazy. I’ll fix it after the first time it does what I say, not what I want.

Here is what my template looks like …

<!--POSTIEIMG1-->
<div style="margin:2px 4px 2px 8px;float:right">
<a href="{IMAGE}" target="_blank" ><img src="{MEDIUM}" alt="{CAPTION}" title="{CAPTION}"/></a>
<div style="padding:.4em;text-align:center; font-style: italic">{CAPTION}</div></div>
<!--POSTIEIMG2-->
<center>
<div style="margin:2px 2px 2px 2px;">
<a href="{IMAGE}" target="_blank" ><img src="{LARGE}" alt="{CAPTION}" title="{CAPTION}"/></a>
<div style="padding:.4em;text-align:center; font-style: italic">{CAPTION}</div></div>
</center>
<!--POSTIEIMGTAIL-->

For the curious or bored, here is the plugin filter code !

Using WordPress with WPTouch and WP-HashCash

If you use WordPress you should definitely install the WPTouch plugin and give your readers a great experience for their mobile device (iPhone, Blackberry, Android, etc.) Additionally, I am fond of the WP-Hashcash anti-spam plugin since it works well and does not require posters to read one of those CAPTHA images.

Unfortunately, out of the box, things do not play well together. The symptom is that comments that come through the WPTouch experience, will be flagged by WP-Hashcash as potential spam because it did not get a value generated key. There are a lot of background that is not important. There are two ways to make things play well. One has minimal changes but does not support AJAX comments. The other is more invasive but retains all the functions of both plugins.

 

Minimalist Solution:

WP_Hashcash requires two things in the theme – some JavaScript to be inserted in the header and a hidden field inserted into the comment form. The plugin uses hooks for each of these so the theme only needs to conform to the following.

WP Hashcash relies on the presence of two hooks in your theme, wp_head and comment_form. If your theme doesn’t include these actions, you will need to add them immediately before the </head> and </form> tags respectively.

source: Elliot Back, author of WP-Hashcash

Things are a bit spread out. If you have already enabled your normal theme for WP-Hashcash, then the wp_head() change is already done since WPTouch adds to your normal header. However, WPTouch provides its own comments page so you will need to edit that. It’s location is:

  /public_html/wp-content/plugins/wptouch/themes/default/comments.php 

Just add the following before the closing </form> tag:

  <?php do_action('comment_form', $post->ID); ?> 

There is one more thing. In the plugin settings page for WPTouch, you will need to turn off AJAX comments.

 

Full Function Solution:

You make the changes described above but you do not need to turn off AJAX comments. You then need to make some code changes to both WPTouch and WP-Hashcash.

Back in the same directory as WPTouch’s "comments.php" there is the partner file called "comments-ajax.php". Edit this file in two places – adding one line (seen below in bold green) and appending to another (seen below in bold blue).

  $comment_author = trim($_GET['author']); 
  $comment_author_email = trim($_GET['email']);  
  $comment_author_url = trim($_GET['url']); 
  $comment_content = trim($_GET['comment']); 
  $wphc_value = trim($_GET['wphc_value']); 
  ... 
  $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'user_ID', 'wphc_value'); 

Now edit the "wp-hashcash.php" file which should be in the root of your plugins directory. Near the very bottom of the file, there is a comment, "Check the wphc values against the last five keys". There are actually two instances of this comment and you will make changes for the one in the "wphc_check_hidden_tag()" function. The code only looks for the "wphc_value" field in the _POSTS data. If you are using WPTouch AJAX comments, the changes above have added this field to the compacted "comment data". Now you need to check both locations as follows:</P?

  $hash_value = $_POST["wphc_value"]; 
  if (!$hash_value) 
    $hash_value = $comment['wphc_value']; 
  $spam = !in_array($hash_value, $options['key']); 
   
  if($options['logging'] && $spam) 
    $comment['comment_content'] .= "\n\n[WORDPRESS HASHCASH] The poster sent us '".($hash_value)."' which is not a hashcash value."; 

Automating parts of a multi-user blog

I manage a "topic blog" for work. For the uninitiated, a "topic blog" has posts from a community of interest on a given topic. Often, topic blogs have lots of contributors. That’s the case for Communicat.us. Managing lots of users requires some tools and some automation.

Today’s tasks included adding 15 new users, sending out the "getting started" guide to everyone, and updating the "authors" page. To make the least work of it all, I added a Dragon Design’s Import Users plug-in for WordPress. That made shore order of adding the 15 new users. But, before I did the upload, I found out how to modify the email that get’s sent for each new user.

WordPress supports "pluggable functions". Fortunately for me, the wp_new_user_notification() function is one of those. Steve Taylor got me started with his basic code for extending the email that gets sent out. Here is what I ended up with …

<?php
/*
Plugin Name: Custom New User Email
Description: Changes the copy in the email sent out to new users
*/

// Redefine user notification function
if ( !function_exists(‘wp_new_user_notification’) ) {
    function wp_new_user_notification( $user_id, $plaintext_pass = ” ) {
        $user = new WP_User($user_id);

        $user_login = stripslashes($user->user_login);
        $user_email = stripslashes($user->user_email);

        $message  = "New user registration for " . get_option(‘blogname’) . ":\r\n\r\n";
        $message .= "Username: " . $user_login . "\r\n";
        $message .= "E-mail:   " . $user_email . "\r\n";

        @wp_mail(get_option(‘admin_email’), get_option(‘blogname’)." – New User Registration", $message);

        if ( empty($plaintext_pass) )
            return;

        $message .= "\r\n\r\n";
        $message .= "To log in:\r\n";
        $message .= wp_login_url() . "\r\n";
        $message .= "Username: " . $user_login . "\r\n";
        $message .= "Password: " . $plaintext_pass . "\r\n\r\n";

        $message .= "You will find the \"getting started\" guide at: ".get_option(‘upload_url_path’)."/getting_started.pdf"."\r\n";

        wp_mail($user_email, "You have been added to " .  get_option(‘blogname’), $message);

    }
}

?>

… Feel free to copy this into a file called "new_user_email.php", upload it to your plugins directory and activate it. Don’t forget to also upload your getting_started.pdf to your upload directory and double check you have set the upload path under Administration >> Settings >> Miscellaneous

Everything was working well but then I noticed the automated "Authors" page was full of the new users with no photos, "nice names" or biographies. The page is generated using an "authors.php" file added to the theme. The problem is that is shows all registered authors. What would be better is if it only showed authors who had actually contributed to the blog. So, I set about to some good ol’ trial and error with "SELECT", "COUNT", "WHERE", "GROUP BY", and "ORDER BY" … aka SQL code. Here is a snippet of the final results …

<table border=0>
<?php
    // Get the authors from the database ordered by user nicename, but only include those with posts
    global $wpdb;
    $query = "SELECT wusers.ID as ID, wusers.user_nicename as user_nicename, COUNT(wposts.post_author) as thecount ";
    $query .= "FROM $wpdb->users wusers, $wpdb->posts wposts ";
    $query .= "WHERE wposts.post_status = ‘publish’ AND wposts.post_type = ‘post’ AND wposts.post_author = wusers.ID ";
    $query .= "GROUP BY wusers.ID ORDER BY wusers.user_nicename";
    $author_ids = $wpdb->get_results($query);

    // Loop through each author
    foreach($author_ids as $author) :
        // Get user data
        $curauth = get_userdata($author->ID);
        // If user level is above 0 or login name is not called "admin", display profile
        if($curauth->user_level > 0 || $curauth->user_login != ‘admin’) :
?>
        <tr><td>
            // show the user profile
            <?php echo (profilepic_internal_profile($author->ID)); ?>
            // show how many posts they have and give a link to posts
            <a href="/index.php?author=<?php echo $author->ID; ?>"><i><?php echo "View " . $curauth->first_name . "’s " . $author->thecount . " post(s)"; ?></i></a>
        </td></tr>
<?php
        endif;
    endforeach;
?>
</table>

So, now I can add new users quickly. New users get the same information to start blogging (both some guides on what is a good blog post as well as the tools they can use to write their posts. Once a users starts to contribute, they will automatically appear on the page of authors.

It was all pretty easy. If you manage a multi-user blog, feel free to use these techniques and take the above code.

Popcorn Hour – iPod Touch Controller

PopcornHourController-remote Over at the NetworkMediaTank forum I discovered Niels Leenheer had created a great Adobe AIR controller for the Popcorn Hour appropriately named “MediaController“. He also created a lesser well known web based controller for the iPhone (but that he did not have an iPhone, he has not promoted it much).

I downloaded the controller and and one I found the installation instructions* I had it up and running and working with my iPhone Touch. However, it was not very rich so I decided to start working on it. There were two pet peeves – very few actual controls were implemented and the lists of content were by “create date” and not alphabetical.

So, first I set out to find graphics to simulate a remote control. I did not find anything I liked so I used GIMP to create a full set. Next, I had to add a lot of command controls to the and get the layout of all the buttons I wanted. The layout was a bit of trial and error and the command controls was a combination of reading the NMT Wiki and a lot of cut/copy/paste and batch editing.

The image is what I ended up with for the control buttons. Along the way, I also fixed the sorting bug. I’m not 100% happy with the button layout but it’s close. I also do not know enough to do the right things to the button layout when the device is rotated. I’ll eventually dig into that.

If you are curious why I went through this exercise, it’s because there is a good change the Popcorn Hour will be buried in a cabinet in my home office far from the TV and thus the IR remote will not work.

BTW: the trick to the install is to ?

  1. copy the “controller” directory to the root of the Popcorn Hour’s internal HDD
  2. you will need tenlet support enabled (I think)
  3. insure the myiHome Server is running on the Popcorn Hour
  4. point your iPhone / iPod Touch browser to:

    http://YourPopcornHour_IP:8088/stream/file=/opt/sybhttpd/localhost.drives/HARD_DISK/controller/index.php

If you are interested, here is the resulting code

Improving image compression for Windows Live Writer

zendibs2 I did a bit of PHP coding this weekend (cue screams by programmers and a development managers everywhere). I liked Windows Live Writer the first time I ran it through it’s paces and now I like it even more. There is one serious caveat. The images that WLW creates and uploads are a bit “rich”. What I mean by that is they are bigger than they really need to be.

When I use GIMP and even Postie, I use a JPEG quality setting of 75. This seems to make reasonable small thumbnails for my blogs and even does a good job when the image is 575 px. On average, the 240px thumbnails are between 10kb and 20kb while the larger images are 50kb to 70kb. These sizes make it possible for readers using telephone modems and dial-up service to still have a chance to read the blog without falling asleep waiting for the page to load. I would like the pages to be even smaller but I use images in nearly every post so a typical page size is between 400kb and 500kb.

What I liked about WLW was that it took my basic images and create both a nice thumbnail with drop shadow effect and created all the necessary linking to the full size image. Postie did this too. The difference was I had to add the drop shadow to the big image and exaggerate it so that the thumbnail would have it when Postie scaled it down. Also, Postie make all thumbnails the same size and there was now way to control it on a post-by-post basis.

So, to get the control that I wanted I switched back to WLW but then I needed to find a fix for the larger that desirable image results. This is where that PHP comes in. I have created a crude but effective WordPress plug-in that detects JPEG files in uploaded posts and re-compresses them automatically. I even gave it a crude name “jpeg-quality75″.

You can download jpeg-quality75 here if you are interested. The install is very simple – unzip then upload jpeg-quality75.php to your WordPress plug-ins directory and activate it. It has not admin or settings.

The plug-in works by hooking the wp_handle_upload function in WordPress. This function is called for every file uploaded, the plug-in checks if the file type is a JPEG image and if so, locates the image, opens and re-compresses it using a quality setting of 75, and then stores the result back in the original location, overwriting the original. It leaves PNG and GIF files alone.

I’ll be checking it’s results for a few days but it seems to be doing a good job without corrupting my photos and graphics.

Logo-of-the-Day goes hi-tech

A few days ago, I announced I’d be trying to update my blog logo to reflect events, holidays, etc. Thus far, the idea is working (at least for me). The problem is one of timing. I got the St. Patrick’s Day logo up (a few hours late) and took it down (many hours late). While the logo was ready days in advance, I still had to upload it; switch it in; then remember to switch it out. That has all changed.

I can now upload logos hours, day, weeks, or even months in advance. A simple cronos job runs at the start of every day and looks for a logo file with today’s date in the name. If it finds one, it makes it the “logo of the day”. If it does not find one, it reverts to the default logo.

I started with some PHP code over at DZone Snippets that made finding the files a snap. I use …

$pattern = date(‘Ymd’) . ‘.*jpg’;

… to find JPEG files with the current date. If I find one, I simply copy it over the default logo. The nice side effect is I retain all my old logos for reference and posterity.

Now I can start to go wild with logos … provided I can find good events to highlight. What are you favorite or most memorable events ?