<?php
/*
Plugin Name: Whoismanu PhotoQ
Version: 1.0.1b
Plugin URI: http://www.whoismanu.com/blog/2007/01/photoq-wordpress-plugin/
Description: Adds queue based photo-upload capability to Wordpress
Author: Manuel Flury
Author URI: http://www.whoismanu.com
*/

/*load text domain for localization*/
load_plugin_textdomain('PhotoQ');


// wimpq_add_admin_pages() is the sink function for the 'admin_menu' hook
function wimpq_add_admin_pages() {
    
// Add a new menu under Options:
    
add_options_page(__('PhotoQ Options','PhotoQ'), 'PhotoQ', 8, basename(__FILE__), 'wimpq_options_page');

    
// Add a new menu under Manage:
    
add_management_page(__('Manage PhotoQ', 'PhotoQ'), 'PhotoQ', 8, basename(__FILE__), 'wimpq_manage_page');

}


// wimpq_options_page() displays the page content for the Options submenu
function wimpq_options_page() {
    
    if (isset(
$_POST['info_update']) || isset($_POST['add_field']))
    {     
            
update_option('wimpq_qdir', $_POST['qdir']);
              
update_option('wimpq_imgdir', $_POST['imgdir']);
              
update_option('wimpq_thumb_constraint', $_POST['thumbsize']);
              switch (
$_POST['thumbsize']){
                  case
'height':
                      
update_option('wimpq_thumb_size', $_POST['thumb_height']);
                    break;
                  case
'width':
                      
update_option('wimpq_thumb_size', $_POST['thumb_width']);
                      break;
                  case
'side':
                      
update_option('wimpq_thumb_size', $_POST['thumb_side']);
                      break;
            }
            
            
update_option('wimpq_image_constraint', $_POST['imagesize']);
              switch (
$_POST['imagesize']){
                  case
'height':
                      
update_option('wimpq_image_size', $_POST['image_height']);
                    break;
                  case
'width':
                      
update_option('wimpq_image_size', $_POST['image_width']);
                      break;
                  case
'side':
                      
update_option('wimpq_image_size', $_POST['image_side']);
                      break;
            }
            
update_option('wimpq_freq', $_POST['cron_freq']);
            
$del_imgs = !isset($_POST["del_imgs"]) ? NULL : $_POST["del_imgs"];
            
update_option('wimpq_delimg', $del_imgs);
            
$noimgresize = !isset($_POST["no_img_resize"]) ? NULL : $_POST["no_img_resize"];
            
update_option('wimpq_no_img_resize', $noimgresize);
            
$add_posted = !isset($_POST["add_posted"]) ? NULL : $_POST["add_posted"];
            
update_option('wimpq_add_posted', $add_posted);
            
$delete_posted = !isset($_POST["delete_posted"]) ? NULL : $_POST["delete_posted"];
            
update_option('wimpq_delete_posted', $delete_posted);
            
$rename_posted = !isset($_POST["rename_posted"]) ? NULL : $_POST["rename_posted"];
            
update_option('wimpq_rename_posted', $rename_posted);
            
            
        
?>
        <div id="message" class="updated fade"><p><strong><?php _e('Options saved.') ?></strong></p></div>

        <?php
    
} ?>
    
    <?php if (isset($_POST['add_field'])) {  ?>
        <div class=wrap>
        <form method="post" action="options-general.php?page=whoismanu-photoq.php">
            <h2>PhotoQ Options</h2>
            
             <fieldset class="options" name="set1">
                <legend><?php _e('Add new Meta Field', 'PhotoQ') ?></legend>
                
                <table width="100%" cellspacing="2" cellpadding="5" class="editform">
                <tr valign="top">
                    <th width="33%" scope="row"><label for="qdir">
                        <?php _e('Field Name:', 'PhotoQ'); ?>
                        </label>
                    </th>
                    <td>
                        <input type="text" name="fieldname" size="50" maxlength="100"/>
                    </td>
                </tr>
                </table>
             </fieldset>
             <p class="submit">
                  <input type="submit" name="insert_field"
                      value="<?php _e('Add field', 'PhotoQ') ?> &raquo;" />
              </p>
          </form>
          </div>
        
    
    
    <?php } else { //we are not adding meta fields
    
        //we are inserting a field into the database
        
if(isset($_POST['insert_field'])){
            
wimpq_insert_field($_POST['fieldname']);
        }
        
        
//we are renaming a field
        
elseif(isset($_POST['rename_field'])){
            
wimpq_rename_field($_POST['field_id'], $_POST['field_name']);
        }
    
        
        
//we are deleting a field from the database
        
elseif ($_GET['action'] == 'delete') {
            
wimpq_remove_field( $_GET['entry']);
        }
    
    
    
?>
    <div class=wrap>
          <form method="post" action="options-general.php?page=whoismanu-photoq.php">
            <h2>PhotoQ Options</h2>
            
             <fieldset class="options" name="set1">
                <legend><?php _e('Directories', 'PhotoQ') ?></legend>
                
                <table width="100%" cellspacing="2" cellpadding="5" class="editform">
                <tr valign="top">
                    <th width="33%" scope="row"><label for="qdir">
                        <?php _e('Queue Directory:', 'PhotoQ'); ?>
                        </label>
                    </th>
                    <td>
                        <input type="text" name="qdir" size="50" maxlength="100"
                        value="<?php if (get_option('wimpq_qdir')) echo get_option('wimpq_qdir');?>" />
                        <br>Default is <code>/wp-content/qdir</code>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row">
                        <label for="imgdir">
                        <?php _e('Image Directory:', 'PhotoQ'); ?>
                        </label>
                    </th>
                    <td>
                        <input type="text" name="imgdir" size="50" maxlength="100"
                        value="<?php if (get_option('wimpq_imgdir')) echo get_option('wimpq_imgdir');?>" />
                        <br>Default is <code>/wp-content</code>
                    </td>
                </tr>
                </table>
             </fieldset>
             <fieldset class="options" name="set2">
                <legend><?php _e('Meta Fields', 'PhotoQ') ?></legend>
                <table width="100%" cellspacing="2" cellpadding="5" class="editform">
                    <tr valign="top">
                        <th width="33%" scope="row">
                            <label for="del_imgs"><?php _e('Upon Add:', 'PhotoQ'); ?></label>
                        </th>
                        <td>
                            <input type="checkbox" name="add_posted" <?php if(get_option('wimpq_add_posted') == 'on'){echo 'checked="checked"';} ?> />
                            <?php _e('Add to already posted as well.', 'PhotoQ'); ?>
                        </td>
                    </tr>
                    <tr valign="top">
                        <th width="33%" scope="row">
                            <label for="del_imgs"><?php _e('Upon Delete:', 'PhotoQ'); ?></label>
                        </th>
                        <td>
                            <input type="checkbox" name="delete_posted" <?php if(get_option('wimpq_delete_posted') == 'on'){echo 'checked="checked"';} ?> />
                            <?php _e('Delete from already posted as well.', 'PhotoQ'); ?>
                        </td>
                    </tr>
                    <tr valign="top">
                        <th width="33%" scope="row">
                            <label for="del_imgs"><?php _e('Upon Rename:', 'PhotoQ'); ?></label>
                        </th>
                        <td>
                            <input type="checkbox" name="rename_posted" <?php if(get_option('wimpq_rename_posted') == 'on'){echo 'checked="checked"';} ?> />
                            <?php _e('Rename already posted as well.', 'PhotoQ'); ?>
                        </td>
                    </tr>
                    
                </table>
                
                <table width="500px" cellspacing="2" cellpadding="5" class="editform">

                <?php     
                        wimpq_list_metafields
('options');
                        
                
?>
                
                <tr valign="top">
                
                    <td >&nbsp;</td>
                    <td width="100px">&nbsp;</td>
                    
                    <td width="100px"><label for="qdir">
                        <div class="submit">
                      <input type="submit" name="add_field"
                      value="<?php _e('Add meta field', 'PhotoQ') ?> &raquo;" />
                  </div>
                        </label>
                    </td>
                </tr>
                </table>
             </fieldset>
             <fieldset class="options" name="set3">
                <legend><?php _e('Image sizes', 'PhotoQ') ?></legend>
                
                <table width="100%" cellspacing="2" cellpadding="5" class="editform">
                    <tr valign="top">
                        <td> <?php _e('Thumbnail size', 'PhotoQ') ?> </td>
                    </tr>
                    <tr valign="top">
                        <th width="33%" scope="row">
                            <label for="thumbsize_height">
                                <input type="radio" name="thumbsize" value="height" id="thumbsize_height" <?php if (get_option('wimpq_thumb_constraint') == 'height') echo "checked";?> />
                                <?php _e('Fixed height:', 'PhotoQ') ?>
                            </label>
                        </th>
                        <td>
                              <input type="text" name="thumb_height" size="4" value="<?php if (get_option('wimpq_thumb_size') && get_option('wimpq_thumb_constraint') == 'height') echo get_option('wimpq_thumb_size');?>" />px
                        </td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">
                            <label for="thumbsize_width">
                                <input type="radio" name="thumbsize" value="width" id="thumbsize_width" <?php if (get_option('wimpq_thumb_constraint') == 'width') echo "checked";?> />
                                <?php _e('Fixed width:', 'PhotoQ') ?>
                            </label>
                        </th>
                        <td>
                              <input type="text" name="thumb_width" size="4" value="<?php if (get_option('wimpq_thumb_size') && get_option('wimpq_thumb_constraint') == 'width') echo get_option('wimpq_thumb_size');?>" />px
                        </td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">
                            <label for="thumbsize_side">
                                <input type="radio" name="thumbsize" value="side" id="thumbsize_side" <?php if (get_option('wimpq_thumb_constraint') == 'side') echo "checked";?> />
                                <?php _e('Largest side:', 'PhotoQ') ?>
                            </label>
                        </th>
                        <td>
                              <input type="text" name="thumb_side" size="4" value="<?php if (get_option('wimpq_thumb_size') && get_option('wimpq_thumb_constraint') == 'side') echo get_option('wimpq_thumb_size');?>" />px
                
                        </td>
                    </tr>
                    
                </table>
        
                        
                <table width="100%" cellspacing="2" cellpadding="5" class="editform">
                    <tr valign="top">
                        <td> <?php _e('Image size', 'PhotoQ') ?> </td>
                    </tr>
                    <tr valign="top">
                        <th width="33%" scope="row">
                            <label for="imagesize_height">
                                <input type="radio" name="imagesize" value="height" id="imagesize_height" <?php if (get_option('wimpq_image_constraint') == 'height') echo "checked";?> />
                                <?php _e('Fixed height:', 'PhotoQ') ?>
                            </label>
                        </th>
                        <td>
                              <input type="text" name="image_height" size="4" value="<?php if (get_option('wimpq_image_size') && get_option('wimpq_image_constraint') == 'height') echo get_option('wimpq_image_size');?>" />px
                        </td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">
                            <label for="imagesize_width">
                                <input type="radio" name="imagesize" value="width" id="imagesize_width" <?php if (get_option('wimpq_image_constraint') == 'width') echo "checked";?> />
                                <?php _e('Fixed width:', 'PhotoQ') ?>
                            </label>
                        </th>
                        <td>
                              <input type="text" name="image_width" size="4" value="<?php if (get_option('wimpq_image_size') && get_option('wimpq_image_constraint') == 'width') echo get_option('wimpq_image_size');?>" />px
                        </td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">
                            <label for="imagesize_side">
                                <input type="radio" name="imagesize" value="side" id="imagesize_side" <?php if (get_option('wimpq_image_constraint') == 'side') echo "checked";?> />
                                <?php _e('Largest side:', 'PhotoQ') ?>
                            </label>
                        </th>
                        <td>
                              <input type="text" name="image_side" size="4" value="<?php if (get_option('wimpq_image_size') && get_option('wimpq_image_constraint') == 'side') echo get_option('wimpq_image_size');?>" />px
                        </td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">
                            &nbsp;
                        </th>
                        <td>
                            <input type="checkbox" name="no_img_resize" <?php if(get_option('wimpq_no_img_resize') == 'on'){echo 'checked="checked"';} ?> />
                            <?php _e("Keep original image size, don't resize.", 'PhotoQ'); ?>
                        </td>
                    </tr>
                </table>    
             </fieldset>
             <fieldset class="options" name="set4">
                <legend><?php _e('Further Options', 'PhotoQ') ?></legend>
                <table width="100%" cellspacing="2" cellpadding="5" class="editform">
                    <tr valign="top">
                        <th width="33%" scope="row">
                            <label for="cron_freq"><?php _e('Cron Job Frequency:', 'PhotoQ'); ?></label>
                        </th>
                        <td>
                            <input type="text" name="cron_freq" size="3" maxlength="100" value="<?php if (get_option('wimpq_freq')) echo get_option('wimpq_freq');?>" />
                            <?php _e('hours', 'PhotoQ'); ?>
                        </td>
                    </tr>
                    <tr valign="top">
                        <th width="33%" scope="row">
                            <label for="del_imgs"><?php _e('Deleting Posts:', 'PhotoQ'); ?></label>
                        </th>
                        <td>
                            <input type="checkbox" name="del_imgs" <?php if(get_option('wimpq_delimg') == 'on'){echo 'checked="checked"';} ?> />
                            <?php _e('Delete image files from server when deleting post.', 'PhotoQ'); ?>
                        </td>
                    </tr>
                </table>
             </fieldset>
             
            <p class="submit">
                  <input type="submit" name="info_update"
                      value="<?php _e('Update options', 'PhotoQ') ?> &raquo;" />
              </p>
          </form>
     </div>
    
     <?php } //end if(edit)
}



// wimpq_manage_page() displays the page content for the Manage submenu
function wimpq_manage_page() {

    
    
    if (isset(
$_POST['add_entry']))
    {
        
/*a photo will be added*/
    
?>
        <div class=wrap>

             <form method="post" enctype="multipart/form-data" action="edit.php?page=whoismanu-photoq.php">
                <h2>Manage PhotoQ - Upload</h2>    
                <div id="poststuff">
                <fieldset id="categorydiv">
                  <legend><a href="http://wordpress.org/docs/reference/post/#category" title="<?php _e('Help on categories') ?>"><?php _e('Categories') ?></a></legend>
                  <div><?php wimpq_dropdown_categories(); ?></div>
                </fieldset>
                
                
                
                <p>
                  <label for="uploadedfile"><?php _e('File:') ?></label>
                  <br />
                <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo get_settings('fileupload_maxk') * 1024 ?>" />
                <input type="file" name="uploadedfile" size="35" class="uploadform" /></p>
                   <?php printf(__('You can upload files as long as they are no larger than %1$s <abbr title="Kilobytes">KB</abbr>. If you&#8217;re an admin you can configure these values under <a href="%2$s">options</a>.'), get_settings('fileupload_maxk'), 'options-misc.php') ?></p>
                <p>
                <label for="img_title"><?php _e('Title:') ?></label><br />
                <input type="text" name="img_title" size="30" class="uploadform" />
                </p>
                <p>
                <label for="img_descr"><?php _e('Description:') ?></label><br />
                <textarea style="font-size:small;" name="img_descr" cols="70" rows="10" class="uploadform"></textarea>
                </p>
                <p>
                <label for="img_slug"><?php _e('Post Slug:') ?></label><br />
                <input type="text" name="img_slug" size="30" class="uploadform" />
                </p>
                
                <?php wimpq_list_metafields('manage'); ?>
                
                <input type="hidden" name="action" value="save" />
                <div class="submit">
                      <input type="submit" name="submit_entry"
                      value="<?php _e('Upload Photo to Queue', 'PhotoQ') ?> &raquo;" />
                  </div>
                  </div>
              </form>
        </div>
    
        
    
    
    <?php
    
}else{
    
    
    
    if (isset(
$_POST['submit_entry'])) {
        
$status = wimpq_upload_photo($_POST['uploadedfile'], $_POST['img_title'], $_POST['img_descr'], $_POST['img_slug']);
    
    }
    
    if (isset(
$_POST['update_queue'])) {
        
wimpq_update_queue($_POST['img_name'], $_POST['img_title'], $_POST['img_descr'], $_POST['img_slug'], $_POST['img_position'], $_POST['img_old_position'], $_POST['q_length']);
    }
    
    if (
$_GET['action'] == 'delete') {
        
$status = wimpq_delete_photo( $_GET['entry'], $_GET['qlen'], $_GET['pos']);
    }
    
    if (isset(
$_POST['post_first'])) {
        
$status = wimpq_post_next();
    }
    
    
/*get the queue*/
    
$queue = wimpq_get_queue();
    
$q_length = sizeof($queue);
    
    
    if (
$status) {
        if(
$status["type"] == 'error'){
        
?>
            <div id="message" class="error"><p><strong><?php echo $status["message"]; ?></strong></p></div>
    <?php } else { ?>
            <div id="message" class="updated fade"><p><strong><?php echo $status["message"]; ?></strong></p></div>
    <?php }} ?>
    
    
    <div class=wrap>
             <form method="post" action="edit.php?page=whoismanu-photoq.php">
                <h2>Manage PhotoQ</h2>        
                <input type="hidden" name="q_length" value="<?php echo $q_length; ?>" />

                <?php if ($_GET['action'] == 'edit') {  ?>
                <div id="poststuff">
                <fieldset id="categorydiv">
                  <legend><a href="http://wordpress.org/docs/reference/post/#category" title="<?php _e('Help on categories') ?>"><?php _e('Categories') ?></a></legend>
                  <div><?php wimpq_dropdown_categories($queue[$_GET['entry']]->q_imgname, $default_post_cat); ?></div>
                </fieldset>
                
        
                
                <?php
                
                    wimpq_list_metafields
('edit_queue',$queue[$_GET['entry']]->q_imgname);
                
                }
                    if(
$queue){
                        echo
"Queue length: ".$q_length;
                        
                        
?>
                        <table width="100%" cellpadding="3" cellspacing="3">
                            <tr>
                        
                            <th scope="col">Position</th>
                            <th scope="col">Thumbnail</th>
                            <th scope="col">Name</th>
                            <th scope="col">Title</th>
                            <th scope="col">Description</th>
                            <!--<th scope="col">Place</th>
                            <th scope="col">Tags</th> -->
                            <th scope="col">Slug</th>
                            
                            
                            </tr>
                        <?php
                        
                        
for ($i = 0; $i < $q_length; $i++){
                            
//get the name of the thumbnail
                            
$thumb_path = wimpq_get_qdir() . basename(wimpq_get_thumbpath($queue[$i]->q_imgname));
                            
                            if (
$_GET['action'] == 'edit' && $_GET['entry'] == $i ) {  ?>
                                
                                <tr class='<?php if(($i+1)%2) echo "alternate"; ?>'>
                        
                                <th scope="row"><input type="text" name="img_position" size="2" value="<?php echo $queue[$i]->q_position; ?>" />
                                    <input type="hidden" name="img_old_position" value="<?php echo $queue[$i]->q_position; ?>" />
                                </th>
                        
                                        <td><?php $path = "../". wimpq_get_rel_url($thumb_path); ?>
                                            <img src='<?php echo $path; ?>' alt='<?php echo $queue[$i]->q_title; ?>' />
                                        </td>
                                        <td><?php echo $queue[$i]->q_imgname; ?><input type="hidden" name="img_name" value="<?php echo $queue[$i]->q_imgname; ?>" /></td>
                                        <td><input type="text" name="img_title" size="30" value="<?php echo $queue[$i]->q_title; ?>" /></td>
                                        <td><textarea style="font-size:small;" name="img_descr" cols="30" rows="3"><?php echo $queue[$i]->q_descr; ?> </textarea></td>
                                        <td><input type="text" name="img_slug" size="12" value="<?php echo $queue[$i]->q_slug; ?>" /></td>
                                        
                                        
                                </tr>
                                
                                
                        <?php        
                            
}else{
                        
?>

                                <tr class='<?php if(($i+1)%2) echo "alternate"; ?>'>
                        
                                <th scope="row"><?php echo $queue[$i]->q_position; ?></th>
                        
                                        <td><?php $path = "../".wimpq_get_rel_url($thumb_path); ?>
                                            <img src='<?php echo $path; ?>' alt='<?php echo $queue[$i]->q_title; ?>' /></td>
                                        <td><?php echo $queue[$i]->q_imgname; ?></td>
                                        <td><?php echo $queue[$i]->q_title; ?></td>
                                        <td><?php echo $queue[$i]->q_descr; ?></td>
                                        <!--<td><?php echo $queue[$i]->q_place; ?></td>
                                        <td><?php echo $queue[$i]->q_tags; ?></td>-->
                                        <td><?php echo $queue[$i]->q_slug; ?></td>
                                        <?php if ($_GET['action'] != 'edit'){ ?>
                                            <td><a href="edit.php?page=whoismanu-photoq.php&action=edit&entry=<?php echo $i; ?>" class="edit">Edit</a></td>
                                            <td><a href="edit.php?page=whoismanu-photoq.php&action=delete&entry=<?php echo $queue[$i]->q_imgname; ?>&qlen=<?php echo $q_length; ?>&pos=<?php echo $queue[$i]->q_position; ?>" class="delete" onClick="return confirm('Delete entry? Correpsonding image will also be deleted from server?');">Delete</a></td>
                                        <?php } ?>
                            </tr>
                        <?php }  }
                        
                        echo
"</table>";
                        
                    }else
                        echo
"Queue empty";
                
                if (
$_GET['action'] == 'edit') {
                
?>
                
                <div class="submit">
                      <input type="submit" name="update_queue"
                      value="<?php _e('Update queue', 'PhotoQ') ?> &raquo;" />
                  </div>
                  
                  <?php }else{?>
                  
                  <div class="submit">
                      <input type="submit" name="add_entry"
                      value="<?php _e('Add Photo to queue', 'PhotoQ') ?> &raquo;" />
                  </div>
                  
                  <div class="submit">
                      <input type="submit" name="post_first"
                      value="<?php _e('Post Top of queue', 'PhotoQ') ?> &raquo;"     onClick="return confirm(
        'Are you sure you want to publish the first entry of the queue?');" />
                  </div>
                  
                  <?php } if ($_GET['action'] == 'edit') {  ?>
                </div>
                
                
                <?php } ?>
              </form>
    </div>
    
    
    
    <?php }
}


/******************************************************/
/******************** options page ********************/
/******************************************************/

/***** functions to handle meta field stuff on options page *****/

/*display the list of currently used metafields*/
function wimpq_list_metafields($page, $q_entry = ''){
    
    global
$wpdb, $table_prefix;
    
$queue_table = $table_prefix."photoqfields";
    
    
$wpdb->hide_errors();

    
$results = $wpdb->get_results("
        SELECT
            *
        FROM
            $queue_table
        WHERE
            1
        ORDER BY q_field_name
        "
);
    
    
//create table at first call
    
if (strpos(mysql_error(), $table_prefix."photoqfields' doesn't exist")) wimpq_install();
    
    if(
$results){
        
$i = 0; //used to alternate styles
        
foreach ($results as $field_entry) {
            if(
$page == 'manage'){ //we are on the manage page
                
echo '<p><label for="'.$field_entry->q_field_name.'">'.$field_entry->q_field_name.':</label><br /><textarea style="font-size:small;" name="'.$field_entry->q_field_name.'" cols="30" rows="3"  class="uploadform"></textarea></p>';
            }elseif(
$page == 'edit_queue'){ //we are editing the queue
                //get the stored values
                
$queuemeta_table = $table_prefix."photoqmeta";
                
                
$field_value = $wpdb->get_var("SELECT
                        q_field_value
                    FROM
                        $queuemeta_table
                    WHERE
                        q_fk_imgname = '$q_entry' && q_fk_field_id = $field_entry->q_field_id"
);
                echo
'<p><label for="'.$field_entry->q_field_name.'">'.$field_entry->q_field_name.':</label><br /><textarea style="font-size:small;" name="'.$field_entry->q_field_name.'" cols="30" rows="3"  class="uploadform">'.$field_value.'</textarea></p>';
            }else{
//we are on the options page
                
echo '<tr valign="top" class=';
                if((
$i+1)%2) {echo '"alternate"';}
                echo
'>';
                if (
$_GET['action'] == 'rename' && $_GET['entry'] == $field_entry->q_field_id ) {
                    echo
'<td><p><input type="text" name="field_name" size="15" value="'.$field_entry->q_field_name.'"/></p></td>';
                    echo
'<td><input type="hidden" name="field_id" size="15" value="'.$field_entry->q_field_id.'"/>&nbsp;</td><td><p class="submit"><input type="submit" name="rename_field" value="Rename field &raquo;" /></p></td>';
                }else{
                    echo
'<td>'.$field_entry->q_field_name.'</td>';
                    echo
'<td><a href="options-general.php?page=whoismanu-photoq.php&action=rename&entry='.$field_entry->q_field_id.'" class="edit">Rename</a></td>';
                    echo
'<td><a href="options-general.php?page=whoismanu-photoq.php&action=delete&entry='.$field_entry->q_field_id.'" class="delete" onClick="return confirm(\'Are you sure?\');">Delete</a></td>';
                }
                echo
'</tr>';
            }
            
$i++;
        }
        
    }else{
        echo
'<tr valign="top"><td>No fields so far. You can add some if you like.</td></tr>';
    }
    
    
}

/*add field to DB*/
function wimpq_insert_field($name){
    global
$wpdb, $table_prefix;
    
    
$queuemeta_table = $table_prefix."photoqmeta";
    
$queue_table = $table_prefix."photoq";
    
$posts_table = $table_prefix."posts";
    
$postmeta_table = $table_prefix."postmeta";
    
    
//remove whitespace as this will also be used as mysql column header
    
$name = preg_replace('/\s+/', '_', $name);
    
$qfields_table = $table_prefix."photoqfields";
    
$wpdb->query("INSERT INTO $qfields_table (q_field_name) VALUES ('$name')");
    
    
//get the id assigned to this entry
    
$field_id = mysql_insert_id();
    
    
//add also to metatable for all entries in the queue
    
$results = $wpdb->get_results("
        SELECT
            q_imgname
        FROM
            $queue_table
        WHERE
            1
        "
);
    
    if(
$results){
        
        foreach (
$results as $queue_entry) {
            
            
$insert_meta_query = "INSERT INTO $queuemeta_table (q_fk_imgname, q_fk_field_id, q_field_value)
                    VALUES ('$queue_entry->q_imgname', $field_id, '')"
;
            
$wpdb->query($insert_meta_query);
        }
        
    }
    
    if(
get_option('wimpq_add_posted') == 'on'){
        
//finally do the same for all posts that have already been posted
        //add also to metatable for all entries in the queue
        
$results = $wpdb->get_results("
            SELECT
                ID
            FROM
                $posts_table
            WHERE
                1
            "
);
        
        if(
$results){
            
            foreach (
$results as $post_entry) {
                
                
$insert_meta_query = "INSERT INTO $postmeta_table (post_id, meta_key, meta_value)
                        VALUES ($post_entry->ID, '$name', '')"
;
                
$wpdb->query($insert_meta_query);
            }
            
        }
    }
    
}


/*remove field from DB*/
function wimpq_remove_field($id){
    global
$wpdb, $table_prefix;
    
    
$qfields_table = $table_prefix."photoqfields";
    
$queuemeta_table = $table_prefix."photoqmeta";
    
    
//get the name before deleting
    
$old_name = $wpdb->get_var("SELECT q_field_name FROM $qfields_table WHERE q_field_id = $id");

    
/*delete DB entry*/
    
$wpdb->query("DELETE FROM $qfields_table WHERE q_field_id = '$id'");
    
    
/*delete also from metatable*/
    
$wpdb->query("DELETE FROM $queuemeta_table WHERE q_fk_field_id = '$id'");
    
    if(
get_option('wimpq_delete_posted') == 'on'){
        
//delete from already posted posts
        
$postmeta_table = $table_prefix."postmeta";
        
$wpdb->query("DELETE FROM $postmeta_table WHERE meta_key = '$old_name'");
    }
    
}

/*rename field*/
function wimpq_rename_field($id, $new_name){
    global
$wpdb, $table_prefix;
    
    
$qfields_table = $table_prefix."photoqfields";

    
//get the old name
    
$old_name = $wpdb->get_var("SELECT q_field_name FROM $qfields_table WHERE q_field_id = $id");
    
    
//remove whitespace as this will also be used as mysql column header
    
$new_name = preg_replace('/\s+/', '_', $new_name);
    
    
//update DB entry
    
$wpdb->query("UPDATE $qfields_table SET q_field_name = '$new_name' WHERE q_field_id = '$id'");
    
    if(
get_option('wimpq_rename_posted') == 'on'){
        
//update already posted posts
        
$postmeta_table = $table_prefix."postmeta";
        
$wpdb->query("UPDATE $postmeta_table SET meta_key = '$new_name' WHERE meta_key = '$old_name'");
    }
    
}


/******************************************************/
/******************** manage page *********************/
/******************************************************/


/***** functions to manage photo queue *****/

//uploads a photo, creates thumbnail and puts it to the end of the queue
function wimpq_upload_photo($uploadedfile, $title, $descr, $slug){
    global
$wpdb, $table_prefix;
    
    
$qcat_table = $table_prefix."photoq2cat";
    
$queue_table = $table_prefix."photoq";
    
$qfields_table = $table_prefix."photoqfields";
    
$queuemeta_table = $table_prefix."photoqmeta";
    
    
/*try to use the functions provided by wordpress, however there is no way to
    specify the upload path other than changing the option, so we do this */
    //save the old value
    
$old_upload_path = get_settings('upload_path');
    
//set to queue directory
    
$qdir = get_option('wimpq_qdir');
    if (
$qdir == '' ) { //the option was empty
        
$qdir = 'wp-content/qdir'; //default directory
    
}
    
update_option('upload_path', $qdir);
    
    
//do the same for yearmonth_folders
    
$old_yearmonth_folders = get_settings('uploads_use_yearmonth_folders');
    
update_option('uploads_use_yearmonth_folders',false); //turn this off
    
    //set the options that we override
    
$overrides = array('action'=>'save');
    
$overrides['mimes'] = apply_filters('upload_mimes', array (
        
'jpg|jpeg|jpe' => 'image/jpeg',
        
'gif' => 'image/gif',
        
'png' => 'image/png',
        
'bmp' => 'image/bmp',
        
'tif|tiff' => 'image/tiff'
    
));
    
        
    
//upload the thing
    
$file = wp_handle_upload($_FILES['uploadedfile'], $overrides);
    
    
//reset upload options to saved ones
    
update_option('upload_path', $old_update_path);
    
update_option('uploads_use_yearmonth_folders',$old_yearmonth_folders);
    
    
//check for errors
    
if ( isset($file['error']) ) return array('type' => 'error', 'message' => $file['error']);
        
    
    
//get return values
    
$url = $file['url'];
    
$type = $file['type'];
    
$file = $file['file'];
    
$filename = basename($file);
        
    
/*create thumbnail*/
    
    /*if option largest side is chosen, we can simply proceed*/
    
if (get_option('wimpq_thumb_constraint') == 'side'){
        
wp_create_thumbnail($file, get_option('wimpq_thumb_size'));
    }else{
        
        
/*we have to calculate the value the largest side should have*/
        
$image_attr = getimagesize($file);
        
$image_width = $image_attr[0];
        
$image_height = $image_attr[1];
        
$ratio = $image_width/$image_height;
        if (
get_option('wimpq_thumb_constraint') == 'width'){
            if(
$image_width >= $image_height)
                
wp_create_thumbnail($file, get_option('wimpq_thumb_size'));
            else{
                
wp_create_thumbnail($file, get_option('wimpq_thumb_size')/$ratio);
            }
        }else{
//it is height
            
if($image_width <= $image_height)
                
wp_create_thumbnail($file, get_option('wimpq_thumb_size'));
            else{
                
wp_create_thumbnail($file, get_option('wimpq_thumb_size')*$ratio);
            }
        }
    
    }
    
    
/*add it to DB*/
    
$wpdb->query('SELECT q_imgname FROM '.$queue_table.'');
    
$q_length = mysql_affected_rows();    
    
$wpdb->query("INSERT INTO $queue_table (q_title, q_imgname, q_position, q_slug, q_descr) VALUES ('$title', '$filename', '".($q_length+1)."', '$slug', '$descr')");
    

    
// Insert categories
    
$post_categories = apply_filters('category_save_pre', $_POST['post_category']);

    
// Check to make sure there is a category, if not just set it to some default
    
if (!$post_categories) $post_categories[] = get_option('default_category');
    foreach (
$post_categories as $post_category) {
        
// Double check it's not there already
        
$exists = $wpdb->get_row("SELECT * FROM $qcat_table WHERE q_imgname = '$filename' AND category_id = $post_category");

         if (!
$exists) {
            
$wpdb->query("
            INSERT INTO $qcat_table
            (q_imgname, category_id)
            VALUES
            ('$filename', $post_category)
            "
);
        }
    }
    
    
//handle the fields
    
$results = $wpdb->get_results("SELECT * FROM $qfields_table WHERE 1");
    
    if(
$results){
        foreach (
$results as $field_entry) {
            
$insert_meta_query = "INSERT INTO $queuemeta_table (q_fk_imgname, q_fk_field_id, q_field_value)
                    VALUES ('$filename', $field_entry->q_field_id, '"
.$_POST["$field_entry->q_field_name"]."')";
            
$wpdb->query($insert_meta_query);
        }    
    }
    
    
//create status object
    
$status_msg = 'Successfully uploaded. \'' . $filename . '\' added to queue at position ' . ($q_length + 1) . '.';
    
$status = array('type' => 'update', 'message' => __($status_msg, 'PhotoQ'));
    
//Successfully uploaded. ' . $filename . ' was added to queue at position ' .$q_length + 1 . '.

    
return $status;

}


//updates a queue entry
function wimpq_update_queue($name, $title, $descr, $slug, $position, $old_position, $q_length){
    global
$wpdb, $table_prefix;
    
$queue_table = $table_prefix."photoq";
    
$qcat_table = $table_prefix."photoq2cat";
    
$qfields_table = $table_prefix."photoqfields";
    
$queuemeta_table = $table_prefix."photoqmeta";

    if(
$position < 1)
        
$position = 1;
    if(
$position > $q_length)
        
$position = $q_length;
    
    if(
$position < $old_position){
            
$wpdb->query("UPDATE  $queue_table SET q_position = q_position+1 WHERE q_position >= '$position' AND q_position < '$old_position'");
    }
    if(
$position > $old_position){
            
$wpdb->query("UPDATE  $queue_table SET q_position = q_position-1 WHERE q_position <= '$position' AND q_position > '$old_position'");
    }
    
    
$wpdb->query("UPDATE  $queue_table SET q_position = '$position', q_title = '$title', q_descr = '$descr', q_slug = '$slug'  WHERE q_imgname = '$name'");

    
/*update categories*/
    
$post_categories = apply_filters('category_save_pre', $_POST['post_category']);
    
    
// Now it's category time!
    // First the old categories
    
$old_categories = $wpdb->get_col("SELECT category_id FROM $qcat_table WHERE q_imgname = '$name'");
    
    
// Delete any?
    
foreach ($old_categories as $old_cat) {
        if (!
in_array($old_cat, $post_categories)) // If a category was there before but isn't now
            
$wpdb->query("DELETE FROM $qcat_table WHERE q_imgname = '$name' AND category_id = $old_cat LIMIT 1");
    }
    
    
// Add any?
    
foreach ($post_categories as $new_cat) {
        if (!
in_array($new_cat, $old_categories))
            
$wpdb->query("INSERT INTO $qcat_table (q_imgname, category_id) VALUES ('$name', $new_cat)");
    }
    
    
//handle the fields
    
    
    
$results = $wpdb->get_results("
        SELECT
            *
        FROM
            $qfields_table
        WHERE 1"
);
    
    if(
$results){
        
        foreach (
$results as $field_entry) {
            
            
$update_meta_query = "UPDATE $queuemeta_table SET q_field_value = '".$_POST["$field_entry->q_field_name"]."'
                    WHERE q_fk_imgname = '$name' && q_fk_field_id = $field_entry->q_field_id"
;
            
$wpdb->query($update_meta_query);
        }
        
    }

}

//removes a photo from the queue and deletes the photo file from the server
function wimpq_delete_photo($name, $q_length, $position){
    global
$wpdb, $table_prefix;
    
$queue_table = $table_prefix."photoq";
    
$qcat_table = $table_prefix."photoq2cat";
    
$qfields_table = $table_prefix."photoqfields";
    
$queuemeta_table = $table_prefix."photoqmeta";
    
    
/*delete DB entry*/
    
$wpdb->query("DELETE FROM $queue_table WHERE q_imgname = '$name'");
    
/*delete cat entries*/
    
$wpdb->query("DELETE FROM $qcat_table WHERE q_imgname = '$name'");
    
/*delete field entries*/
    
$wpdb->query("DELETE FROM $queuemeta_table WHERE q_fk_imgname = '$name'");
    
    
/*delete image file*/
    
$path = wimpq_get_qdir() . $name;
    
$deleted = 1;
    if (
file_exists($path)) {
        
$deleted = unlink($path);
    }
    if(!
$deleted)
            
$status = array('type' => 'error', 'message' => __("Could not delete $name from server. Please delete manually."));
    
    
/*delete thumb*/
    
$thumb_name = basename(wimpq_get_thumbpath($name));
    
$path = wimpq_get_qdir() . $thumb_name;
    if (
file_exists($path)) {
        
$deleted = unlink($path);
    }
    if(!
$deleted)
        
$status = array('type' => 'error', 'message' => $status['message'] . __("<br> Could not delete $thumb_name from server. Please delete manually."));
    
    
/*update queue positions*/
    
$wpdb->query("UPDATE  $queue_table SET q_position = q_position-1 WHERE q_position > '$position'");

    if(isset(
$status))
        return
$status;
    else
        return array(
'type' => 'update', 'message' => __('Entry successfully removed from queue. Corresponding files deleted from server.'));
}

//posts the top of the queue
function wimpq_post_next(){
    global
$wpdb, $table_prefix, $post_default_category;
    
$queue_table = $table_prefix."photoq";
    
$qcat_table = $table_prefix."photoq2cat";
    
$qfields_table = $table_prefix."photoqfields";
    
$queuemeta_table = $table_prefix."photoqmeta";

    
$q_length = 0;
    
/*get queue length*/
    
if (isset($_POST['q_length']))
        
$q_length = $_POST['q_length'];
    else{
        
$queue = wimpq_get_queue();
        
$q_length = sizeof($queue);
    }
    
    if(
$q_length == 0){
        return array(
'type' => 'error', 'message' => __('Queue is empty, nothing to post.'));
    }
    
    
$post_default_category = get_option('default_category');
    
    
$photo_post = $wpdb->get_row("SELECT * FROM $queue_table WHERE q_position = '1'");
    
    
    
/*publish the post*/
    
$post_author = 1; //default author
    
    /*the title*/
    
$post_title = $photo_post->q_title;
    
    
/*the slug*/
    
$post_name =  $photo_post->q_slug;
    
    
    
$filename = $photo_post->q_imgname;
    
    
/*category stuff*/
    
$post_category = $wpdb->get_col("SELECT category_id
    FROM $qcat_table
    WHERE q_imgname = '$filename'
    "
);
    
    
    
$dir_name = mysql2date('Y_m', current_time('mysql')) . "/";
    
$new_path = wimpq_get_imgdir() . $dir_name;
    
$old_path = wimpq_get_qdir();
    
    
$thumb_name = basename(wimpq_get_thumbpath($old_path . $filename));
    if (!
file_exists($new_path)) {
        
$dir_created = mkdir($new_path, 0777);
        if(!
$dir_created)
            return array(
'type' => 'error', 'message' => __("Couldn't create image directory. Check your image directory options or PHP Save Mode."));
    }
    
    
/*move the image files*/
    
if (!file_exists($new_path . $filename)) {
        
$renamed = rename($old_path . $filename, $new_path . $filename);
        if(!
$renamed) return array('type' => 'error', 'message' => __("Unable to move $filename, posting aborted."));
        
$renamed = rename($old_path . $thumb_name, $new_path . $thumb_name);
        if(!
$renamed) {
            
//put image file back
            
rename($new_path . $filename, $old_path . $filename);
            return array(
'type' => 'error', 'message' => __("Unable to move $thumb_name, posting aborted."));
        }
    }else{
        return array(
'type' => 'error', 'message' => __("Image already exists, posting aborted."));
    }
    
    
    
$url = wimpq_get_rel_url($new_path);
    
//remove any trailing slashes from siteurl
    
$site_url = preg_replace('/\/*$/', '', get_option('siteurl'));
    
$url = $site_url . "/". $url;
    
$img_path = $url . $filename;
    
$thumb_path = $url . $thumb_name;
    
    
/*get image sizes for image links*/
    
$image_attr = getimagesize($new_path.$filename);
    
$image_width = $image_attr[0];
    
$image_height = $image_attr[1];
    
$ratio = $image_width/$image_height;
        
    if (
get_option('wimpq_thumb_constraint') == 'side'){
        if(
$image_width >= $image_height){
            
$thumb_width = get_option('wimpq_thumb_size');
            
$thumb_height = round($thumb_width/$ratio);
        }else{
            
$thumb_height = get_option('wimpq_thumb_size');
            
$thumb_width = round($thumb_height*$ratio);
        }
    }else{
        if (
get_option('wimpq_thumb_constraint') == 'width'){
            
$thumb_width = get_option('wimpq_thumb_size');
            
$thumb_height = round($thumb_width/$ratio);
        }else{
//it is height
            
$thumb_height = get_option('wimpq_thumb_size');
            
$thumb_width = round($thumb_height*$ratio);
        }
    
    }
    if(
get_option('wimpq_no_img_resize') != 'on'){
        if (
get_option('wimpq_image_constraint') == 'side'){
            if(
$image_width >= $image_height){
                
$image_width = get_option('wimpq_image_size');
                
$image_height = round($image_width/$ratio);
            }else{
                
$image_height = get_option('wimpq_image_size');
                
$image_width = round($image_height*$ratio);
            }
        }else{
            if (
get_option('wimpq_image_constraint') == 'width'){
                
$image_width = get_option('wimpq_image_size');
                
$image_height = round($image_width/$ratio);
            }else{
//it is height
                
$image_height = get_option('wimpq_image_size');
                
$image_width = round($image_height*$ratio);
            }
        
        }
    }
    
    
$post_content = '<img width="'.$image_width.'" height="'.$image_height.'" alt="'.$post_title.'" src="'.$img_path.'" id="photo_post" />';
    
$post_excerpt = '<img width="'.$thumb_width.'" height="'.$thumb_height.'" alt="'.$post_title.'" src="'.$thumb_path.'"/>';
    
    
    
//publish the post
    
$post_status = 'publish';
    
    
$post_data = compact('post_content','post_category','post_title','post_excerpt','post_name','post_author', 'post_status');
    
//to safely insert values into db
    
$post_data = add_magic_quotes($post_data);


    
$post_ID = wp_insert_post($post_data);

    if (!
$post_ID) { //post did not succeed
        /*clean up, move the files back where they were*/
        
rename($new_path . $filename, $old_path . $filename);
        
rename($new_path . $thumb_name, $old_path . $thumb_name);
        return array(
'type' => 'error', 'message' => __("Post didn't succeed, wp_insert_post not successful."));
    }
    
    
/*insert meta (custom fields)*/
    
$result = $wpdb->query("
                INSERT INTO $wpdb->postmeta
                (post_id,meta_key,meta_value)
                VALUES ('$post_ID','descr','"
.$wpdb->escape($photo_post->q_descr)."'), ('$post_ID','path','".$new_path . $filename."')
            "
);
            
    
//handle the fields
    
$results = $wpdb->get_results("
        SELECT
            *
        FROM
            $qfields_table
        WHERE
            1
        "
);
    
    if(
$results){
        
        foreach (
$results as $field_entry) {
            
//get field value
            
$field_value = $wpdb->escape($wpdb->get_var("SELECT q_field_value FROM $queuemeta_table WHERE
                        q_fk_imgname = '$filename' && q_fk_field_id = $field_entry->q_field_id"
));
            
//construct insert query
            
$insert_meta_query = "INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value)
                VALUES  ('$post_ID', '"
.$wpdb->escape($field_entry->q_field_name)."', '$field_value')";
            
$wpdb->query($insert_meta_query);
        }
        
    }
    
    
/*delete from queue*/
    
wimpq_delete_photo($filename, $q_length, 1);
    
    return array(
'type' => 'update', 'message' => __("Post successful. View it."));

    
}




/*gets the current queue from the database*/
function wimpq_get_queue(){
    global
$wpdb, $table_prefix;
    
    
$queue_table = $table_prefix."photoq";
    
    
$queue = array();
    
//$wpdb->hide_errors();

    
$results = $wpdb->get_results("
        SELECT
            *
        FROM
            $queue_table
        WHERE
            1
        ORDER BY q_position
        "
);
    
//$wpdb->show_errors();
    
    // Install on plugin first-load?
    
if (strpos(mysql_error(), $table_prefix."photoq' doesn't exist")) wimpq_install();
    
    if(
$results){
        
$count = 0;
        foreach (
$results as $q_entry) {
            
$queue[$count]->q_imgname = $q_entry->q_imgname;
            
$queue[$count]->q_position = $q_entry->q_position;
            
$queue[$count]->q_title = $q_entry->q_title;
            
$queue[$count]->q_slug = $q_entry->q_slug;
            
$queue[$count]->q_descr = $q_entry->q_descr;
            
$count++;
        }
    }
    
    return
$queue;
    

}




/** category functions **/
function wimpq_get_nested_categories($q_ID, $default = 0, $parent = 0) {
global
$mode, $wpdb, $table_prefix;

$qcat_table = $table_prefix."photoq2cat";

if (
$q_ID) {
   
$checked_categories = $wpdb->get_col("
     SELECT category_id
     FROM $wpdb->categories, $qcat_table
     WHERE $qcat_table.category_id = cat_ID AND $qcat_table.q_imgname = '$q_ID'
     "
);
     
   if(
count($checked_categories) == 0)
   {
     
// No selected categories, strange
     
$checked_categories[] = $default;
   }

} else {
   
$checked_categories[] = $default;
}

$cats = return_categories_list($parent);
$result = array();

if (
is_array($cats)) {
    foreach(
$cats as $cat)
    {
           
$result[$cat]['children'] = wimpq_get_nested_categories($q_ID, $default, $cat);
           
$result[$cat]['cat_ID'] = $cat;
           
$result[$cat]['checked'] = in_array($cat, $checked_categories);
           
$result[$cat]['cat_name'] = get_the_category_by_ID($cat);
    }
}

usort($result, 'sort_cats');

return
$result;
}

function
wimpq_write_nested_categories($categories) {
foreach(
$categories as $category) {
   echo
'<label for="category-', $category['cat_ID'], '" class="selectit"><input value="', $category['cat_ID'],
     
'" type="checkbox" name="post_category[]" id="category-', $category['cat_ID'], '"',
     (
$category['checked'] ? ' checked="checked"' : ""), '/> ', wp_specialchars($category['cat_name']), "</label>\n";

   if(isset(
$category['children'])) {
     echo
"\n<span class='cat-nest'>\n";
     
wimpq_write_nested_categories($category['children']);
     echo
"</span>\n";
   }
}
}

function
wimpq_dropdown_categories($q_id=0, $default = 0) {
    
wimpq_write_nested_categories(wimpq_get_nested_categories($q_id, $default));
}

/** end category functions **/


function wimpq_image_resize($file, $max_side, $effect = '') {

    
// 1 = GIF, 2 = JPEG, 3 = PNG

    
if(file_exists($file)) {
        
$type = getimagesize($file);
        
        
// if the associated function doesn't exist - then it's not
        // handle. duh. i hope.
        
        
if(!function_exists('imagegif') && $type[2] == 1) {
            
$error = __('Filetype not supported. Thumbnail not created.');
        }elseif(!
function_exists('imagejpeg') && $type[2] == 2) {
            
$error = __('Filetype not supported. Thumbnail not created.');
        }elseif(!
function_exists('imagepng') && $type[2] == 3) {
            
$error = __('Filetype not supported. Thumbnail not created.');
        } else {
        
            
// create the initial copy from the original file
            
if($type[2] == 1) {
                
$image = imagecreatefromgif($file);
            } elseif(
$type[2] == 2) {
                
$image = imagecreatefromjpeg($file);
            } elseif(
$type[2] == 3) {
                
$image = imagecreatefrompng($file);
            }
            
            if (
function_exists('imageantialias'))
                
imageantialias($image, TRUE);
            
            
$image_attr = getimagesize($file);
            
            
// figure out the longest side
            
            
if($image_attr[0] > $image_attr[1]) {
                
$image_width = $image_attr[0];
                
$image_height = $image_attr[1];
                
$image_new_width = $max_side;
                
                
$image_ratio = $image_width/$image_new_width;
                
$image_new_height = $image_height/$image_ratio;
                
//width is > height
            
} else {
                
$image_width = $image_attr[0];
                
$image_height = $image_attr[1];
                
$image_new_height = $max_side;
                
                
$image_ratio = $image_height/$image_new_height;
                
$image_new_width = $image_width/$image_ratio;
                
//height > width
            
}
            
            
$thumbnail = imagecreatetruecolor($image_new_width, $image_new_height);
            @
imagecopyresampled($thumbnail, $image, 0, 0, 0, 0, $image_new_width, $image_new_height, $image_attr[0], $image_attr[1]);
            
            
// move the thumbnail to it's final destination
            
            
$path = explode('/', $file);
            
$thumbpath = substr($file, 0, strrpos($file, '/')) . $path[count($path)-1];
            
            if(
$type[2] == 1) {
                if(!
imagegif($thumbnail, $thumbpath)) {
                    
$error = __("Thumbnail path invalid");
                }
            } elseif(
$type[2] == 2) {
                if(!
imagejpeg($thumbnail, $thumbpath)) {
                    
$error = __("Thumbnail path invalid");
                }
            } elseif(
$type[2] == 3) {
                if(!
imagepng($thumbnail, $thumbpath)) {
                    
$error = __("Thumbnail path invalid");
                }
            }
            
        }
    }
    
    if(!empty(
$error))
    {
        return
$error;
    }
    else
    {
        return
1;
    }
}

//called by cronjob file
function wimpq_cronjob(){
    global
$wpdb;
    
    echo
"Testing Cron Job";
    
    
$freq = get_option('wimpq_freq');
    echo
"Cron frequency: $freq <br>";
    
    
/*calculate time in hours since last post*/
    

    
$last_time = $wpdb->get_var("SELECT post_date FROM `wp_posts` ORDER BY post_date DESC");
    
$last_time = strtotime($last_time);
    
//$last_time = $wpdb->get_var("SELECT UNIX_TIMESTAMP('$last_time')");
    
echo "Last post: $last_time <br>";
    
    
$current_time = time();
    echo
"Current time: $current_time <br>";
    
    
$time_diff_s = $current_time - $last_time;
    
    
    
$time_diff_h = round($time_diff_s / 3600);
    echo
"Diff: $time_diff_h <br>";
    
    if(
$time_diff_h >= $freq)
        
wimpq_post_next();
}




/*creates the necessary tables in the database*/
function wimpq_install() {
    global
$wpdb, $table_prefix;

    
$queue_table = $table_prefix."photoq";
    echo
"creating Table: ".$queue_table;
    
    
$wpdb->query("
        CREATE TABLE `$queue_table` (
          `q_position` int(10) NOT NULL default '0',
          `q_title` varchar(200) default '',
          `q_imgname` varchar(200) NOT NULL default '',
          `q_slug` varchar(200) default '',
          `q_descr` text default '',
          PRIMARY KEY  (`q_imgname`)
          ); "
);
    
    
$qcat_table = $table_prefix."photoq2cat";
    
    echo
"<br>creating Table: ".$qcat_table;
    
    
$wpdb->query("
        CREATE TABLE `$qcat_table` (
          `rel_id` bigint(20) NOT NULL AUTO_INCREMENT,
          `category_id` bigint(20) NOT NULL default '0',
          `q_imgname` varchar(200) NOT NULL default '',
          PRIMARY KEY  (`rel_id`)
          ); "
);
          
    
$qfields_table = $table_prefix."photoqfields";
    
    echo
"<br>creating Table: ".$qfields_table;
    
    
$wpdb->query("
        CREATE TABLE `$qfields_table` (
          `q_field_id` bigint(20) NOT NULL AUTO_INCREMENT,
          `q_field_name` varchar(200) NOT NULL default '',
          PRIMARY KEY  (`q_field_id`)
          ); "
);
    
    
    
    
$photoqmeta_table = $table_prefix."photoqmeta";
    
    echo
"<br>creating Table: ".$photoqmeta_table;
    
    
$wpdb->query("
        CREATE TABLE `$photoqmeta_table` (
            `q_fk_imgname` varchar(200) NOT NULL default '',
              `q_fk_field_id` bigint(20) NOT NULL default '0',
              `q_field_value` text,
              PRIMARY KEY  (`q_fk_imgname`,`q_fk_field_id`)
        ); "
);
}


/*returns the name of the thumbnail path from the image path*/
function wimpq_get_thumbpath($file) {
    
// If no filters change the filename, we'll do a default transformation.
    
if ( basename($file) == $thumb = apply_filters('thumbnail_filename', basename($file)) )
    
$thumb = preg_replace('!(\.[^.]+)?$!', __('.thumbnail').'$1', basename($file), 1);
    
$thumbpath = str_replace(basename($file), $thumb, $file);
    
    return
$thumbpath;
}

/*get queue directory*/
function wimpq_get_qdir(){
    
//prepend ABSPATH to $qdir and $imgdir if it is not already there
    
$qdir_path = str_replace(ABSPATH, '', trim(get_settings('wimpq_qdir')));
    
$qdir = ABSPATH . $qdir_path;
    if (
$qdir == ABSPATH ) //the option was empty
        
$qdir = ABSPATH . 'wp-content/qdir';
    return
$qdir . '/';
}

/*get image directory*/
function wimpq_get_imgdir(){
    
//prepend ABSPATH to $qdir and $imgdir if it is not already there
    
$imgdir_path = str_replace(ABSPATH, '', trim(get_settings('wimpq_imgdir')));
    
$imgdir = ABSPATH . $imgdir_path;
    if (
$imgdir == ABSPATH ) //the option was empty
        
$imgdir = ABSPATH . 'wp-content';
    return
$imgdir . '/';

}

/*convert absolute filepath to relative url*/
function wimpq_get_rel_url($file){
    
//remove ABSPATH
    
$rel_url = str_replace(ABSPATH, '', trim($file));
    
//remove slashes from beginning
    
$rel_url = preg_replace('/^\/*/', '', $rel_url);
    return
$rel_url;
}

/*sink function executed whenever a post is deleted. Takes post id as argument.
Deletes the corresponding image and thumb files from server if post is deleted.*/
function wimpq_clean_up($id){
    
//only do this when specific option is set
    
if(get_option('wimpq_delimg') == 'on'){
        
//get the data of this post
        
$post = get_post($id);
        
//check whether content has the appropriate format and get the url path

        
preg_match('/^<img width=.*height=.*alt=.*src=\"(.*?)\".*\/>$/',$post->post_content, $matches);
        
$urlpath = $matches[1];
                
            
        
$rel_url = preg_replace('#'.get_option('siteurl').'#','', $urlpath);
        
$rel_url = preg_replace('/^\/*/', '', $rel_url);
        
$filepath = ABSPATH . $rel_url;
        
//echo "file: ".$filepath;
        //echo "url: ".$urlpath;
        //echo "abs: ".ABSPATH;
        //delete both file and thumb
        
        
$deleted = unlink($filepath);
        
$deleted = unlink(wimpq_get_thumbpath($filepath));
    }
}

// Insert the wimpq_add_admin_pages() sink into the plugin hook list for 'admin_menu'
add_action('admin_menu', 'wimpq_add_admin_pages');

//function executed when a post is deleted
add_action ( 'delete_post', 'wimpq_clean_up');



?>