Esempio n. 1
0
function dlm_addnew()
{
    //set globals
    global $wpdb, $wp_dlm_root, $wp_dlm_db, $wp_dlm_db_taxonomies, $wp_dlm_db_relationships, $wp_dlm_db_formats, $wp_dlm_db_meta, $download_taxonomies;
    // turn off magic quotes
    wp_dlm_magic();
    ?>
	
	<div class="download_monitor">
	
	<div class="wrap alternate">
    
    <div class="wrap">

    <div id="downloadadminicon" class="icon32"><br/></div>
    <h2><?php 
    _e('Add New Download', "wp-download_monitor");
    ?>
</h2>
    <?php 
    $errors = '';
    if ($_POST) {
        //get postdata
        $title = htmlspecialchars(trim($_POST['title']));
        $filename = htmlspecialchars(trim($_POST['filename']));
        $dlversion = htmlspecialchars(trim($_POST['dlversion']));
        $dlhits = htmlspecialchars(trim($_POST['dlhits']));
        $postDate = $_POST['postDate'];
        $user = $_POST['user'];
        $members = isset($_POST['memberonly']) ? 1 : 0;
        $forcedownload = isset($_POST['forcedownload']) ? 1 : 0;
        if (isset($_POST['download_cat'])) {
            $download_cat = $_POST['download_cat'];
        } else {
            $download_cat = '';
        }
        $mirrors = htmlspecialchars(trim($_POST['mirrors']));
        $file_description = trim($_POST['file_description']);
    }
    if (isset($_POST['save'])) {
        //validate fields
        if (empty($_POST['title'])) {
            $errors .= __('<div class="error">Required field: <strong>Title</strong> omitted</div>', "wp-download_monitor");
        }
        if (empty($_POST['dlhits'])) {
            $_POST['dlhits'] = 0;
        }
        if (!is_numeric($_POST['dlhits'])) {
            $errors .= __('<div class="error">Invalid <strong>hits</strong> entered</div>', "wp-download_monitor");
        }
        $tags = $_POST['tags'];
        $thumbnail = $_POST['thumbnail'];
        if ($thumbnail) {
            if (!strstr($thumbnail, '://')) {
                $pageURL = "";
                $pageURL = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
                if ($_SERVER["SERVER_PORT"] != "80") {
                    $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"];
                } else {
                    $pageURL .= $_SERVER["SERVER_NAME"];
                }
                if (!strstr(get_bloginfo('url'), 'www.')) {
                    $pageURL = str_replace('www.', '', $pageURL);
                }
                if (!isset($_SERVER['DOCUMENT_ROOT'])) {
                    $_SERVER['DOCUMENT_ROOT'] = str_replace('\\', '/', substr($_SERVER['SCRIPT_FILENAME'], 0, 0 - strlen($_SERVER['PHP_SELF'])));
                }
                $dir_path = $_SERVER['DOCUMENT_ROOT'];
                $thumbnail = str_replace($dir_path, $pageURL, $thumbnail);
            }
        }
        //attempt to upload file
        if (empty($errors)) {
            $time = current_time('mysql');
            $overrides = array('test_form' => false);
            add_filter('upload_dir', 'dlm_upload_dir');
            $file = wp_handle_upload($_FILES['upload'], $overrides, $time);
            remove_filter('upload_dir', 'dlm_upload_dir');
            if (!isset($file['error'])) {
                $full_path = $file['url'];
                $info = $file['url'];
                $filename = $file['url'];
            } else {
                $errors = '<div class="error">' . $file['error'] . '</div>';
            }
            if (!empty($errors)) {
                // No File Was uploaded
                if (empty($_POST['filename']) && !isset($_FILES['upload'])) {
                    $errors = '<div class="error">' . __('No file selected', "wp-download_monitor") . '</div>';
                } elseif (!empty($_POST['filename'])) {
                    $errors = '';
                }
            }
        }
        //attempt to upload thumbnail
        if (empty($errors)) {
            $time = current_time('mysql');
            $overrides = array('test_form' => false);
            add_filter('upload_dir', 'dlm_upload_thumbnail_dir');
            $file = wp_handle_upload($_FILES['thumbnail_upload'], $overrides, $time);
            remove_filter('upload_dir', 'dlm_upload_thumbnail_dir');
            if (!isset($file['error'])) {
                $thumbnail = $file['url'];
            }
        }
        //save to db
        if (empty($errors)) {
            // Add download
            $query_add = sprintf("INSERT INTO %s (`title`, `filename`, `dlversion`, `postDate`, `hits`, `user`, `members`, `mirrors`, `file_description`) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s')", $wpdb->escape($wp_dlm_db), $wpdb->escape($_POST['title']), $wpdb->escape($filename), mysql_real_escape_string($_POST['dlversion']), $wpdb->escape($_POST['postDate']), mysql_real_escape_string($_POST['dlhits']), $wpdb->escape($_POST['user']), $wpdb->escape($members), $wpdb->escape($mirrors), $wpdb->escape($file_description));
            $result = $wpdb->query($query_add);
            if ($result) {
                $download_insert_id = $wpdb->insert_id;
                // Loop Categories
                $cats = $download_taxonomies->categories;
                $values = array();
                if (!empty($cats)) {
                    foreach ($cats as $c) {
                        $this_cat_value = isset($_POST['category_' . $c->id]) ? 1 : 0;
                        if ($this_cat_value) {
                            $values[] = '("' . $wpdb->escape($c->id) . '", ' . $download_insert_id . ')';
                        }
                    }
                }
                if (sizeof($values) > 0) {
                    $wpdb->query("INSERT INTO {$wp_dlm_db_relationships} (taxonomy_id, download_id) VALUES " . implode(',', $values) . "");
                }
                // Tags
                $values = array();
                if ($tags) {
                    // Break 'em up
                    $thetags = explode(',', $tags);
                    $thetags = array_map('trim', $thetags);
                    $thetags = array_map('strtolower', $thetags);
                    if (sizeof($thetags) > 0) {
                        foreach ($thetags as $tag) {
                            if ($tag) {
                                // Exists?
                                $tag_id = $wpdb->get_var("SELECT id FROM {$wp_dlm_db_taxonomies} WHERE taxonomy='tag' AND name='" . $wpdb->escape($tag) . "';");
                                // Insert
                                if (!$tag_id) {
                                    $wpdb->query("INSERT INTO {$wp_dlm_db_taxonomies} (name, parent, taxonomy) VALUES ('" . $wpdb->escape($tag) . "', 0, 'tag');");
                                    $tag_id = $wpdb->insert_id;
                                }
                                if ($tag_id) {
                                    $values[] = '("' . $wpdb->escape($tag_id) . '", ' . $download_insert_id . ')';
                                }
                            }
                        }
                    }
                }
                if (sizeof($values) > 0) {
                    $wpdb->query("INSERT INTO {$wp_dlm_db_relationships} (taxonomy_id, download_id) VALUES " . implode(',', $values) . "");
                }
                // Thumbnail
                if ($thumbnail) {
                    $wpdb->query("INSERT INTO {$wp_dlm_db_meta} (meta_name, meta_value, download_id) VALUES ('thumbnail', '" . $wpdb->escape($thumbnail) . "', '" . $download_insert_id . "')");
                }
                // Force Download
                $wpdb->query("INSERT INTO {$wp_dlm_db_meta} (meta_name, meta_value, download_id) VALUES ('force', '" . $wpdb->escape($forcedownload) . "', '" . $download_insert_id . "')");
                // Process and save meta/custom fields
                $index = 1;
                $values = array();
                if (isset($_POST['meta']) && is_array($_POST['meta'])) {
                    foreach ($_POST['meta'] as $meta) {
                        if (trim($meta['key'])) {
                            $values[] = '("' . $wpdb->escape(strtolower(str_replace(' ', '-', trim(stripslashes($meta['key']))))) . '", "' . $wpdb->escape($meta['value']) . '", ' . $download_insert_id . ')';
                            $index++;
                        }
                    }
                }
                if (sizeof($values) > 0) {
                    $wpdb->query("INSERT INTO {$wp_dlm_db_meta} (meta_name, meta_value, download_id) VALUES " . implode(',', $values) . "");
                }
                if (empty($info)) {
                    echo '<div id="message" class="updated fade"><p><strong>' . __("Download added Successfully", "wp-download_monitor") . '</strong></p></div>';
                } else {
                    echo '<div id="message" class="updated fade"><p><strong>' . __("Download added Successfully", "wp-download_monitor") . ' - ' . $info . '</strong></p></div>';
                }
                do_action('download_added', $download_insert_id);
                // Redirect
                echo '<meta http-equiv="refresh" content="3;url=admin.php?page=dlm_addnew"/>';
                exit;
            } else {
                _e('<div class="error">Error saving to database</div>', "wp-download_monitor");
            }
        } else {
            echo $errors;
        }
    }
    $max_upload_size_text = '';
    if (function_exists('ini_get')) {
        $max_upload_size = min(dlm_let_to_num(ini_get('post_max_size')), dlm_let_to_num(ini_get('upload_max_filesize')));
        $max_upload_size_text = __(' (defined in php.ini)', "wp-download_monitor");
    }
    if (!$max_upload_size || $max_upload_size == 0) {
        $max_upload_size = 8388608;
        $max_upload_size_text = '';
    }
    ?>
		<form enctype="multipart/form-data" action="?page=dlm_addnew&amp;action=add&amp;method=upload" method="post" id="wp_dlm_add" name="add_download" class="form-table"> 
            <input type="hidden" name="MAX_FILE_SIZE" value="<?php 
    echo $max_upload_size;
    ?>
" />
            <table class="optiontable niceblue" cellpadding="0" cellspacing="0"> 
                <tr valign="middle">
                    <th scope="row"><strong><?php 
    _e('Title', "wp-download_monitor");
    ?>
 <?php 
    _e('(required)', "wp-download_monitor");
    ?>
: </strong></th> 
                    <td>
                        <input type="text" style="width:360px;" class="cleardefault" value="<?php 
    if (isset($title)) {
        echo $title;
    }
    ?>
" name="title" id="dltitle" maxlength="200" />												
                    </td> 
                </tr>
                <tr valign="middle">
                    <th scope="row"><strong><?php 
    _e('Version', "wp-download_monitor");
    ?>
: </strong></th> 
                    <td>
                        <input type="text" style="width:360px;" class="cleardefault" value="<?php 
    if (isset($dlversion)) {
        echo $dlversion;
    }
    ?>
" name="dlversion" id="dlversion" />
                    </td> 
                </tr>
                <tr valign="middle">
                    <th scope="row"><strong><?php 
    _e('Description', "wp-download_monitor");
    ?>
: </strong></th> 
                    <td><textarea style="width:360px;" name="file_description" cols="50" rows="6"><?php 
    if (isset($file_description)) {
        echo $file_description;
    }
    ?>
</textarea></td> 
                </tr>
                <tr valign="middle">
                    <th scope="row"><strong><?php 
    _e('Starting hits', "wp-download_monitor");
    ?>
: </strong></th> 
                    <td>
                        <input type="text" style="width:100px;" class="cleardefault" value="<?php 
    if (isset($dlhits) && $dlhits > 0) {
        echo $dlhits;
    } else {
        echo 0;
    }
    ?>
" name="dlhits" id="dlhits" maxlength="50" />
                    </td> 
                </tr>
				<tr valign="top">
						<th scope="row"><strong><?php 
    _e('Select a file...', "wp-download_monitor");
    ?>
 <?php 
    _e('(required)', "wp-download_monitor");
    ?>
</strong></th> 
						<td>
							<div style="width:820px;">
								<div style="float:left; width:362px;">
									<h3 style="margin:0 0 0.5em"><?php 
    _e('Upload File', "wp-download_monitor");
    ?>
</h3>
									<input type="file" name="upload" style="width:354px; margin:1px;" /><br /><span class="setting-description"><?php 
    _e('Max. filesize', "wp-download_monitor");
    echo $max_upload_size_text;
    ?>
 = <?php 
    echo $max_upload_size;
    ?>
 <?php 
    _e('bytes', "wp-download_monitor");
    ?>
. <?php 
    _e('If a file with the same name already exists in the upload directly, this file will be renamed.', "wp-download_monitor");
    ?>
</span>
								</div>
								<div style="float:left; text-align:center; width: 75px; margin: 0 8px; display:inline;">
									<p style="font-weight:bold; font-size:16px; color: #999; line-height: 48px; ">&larr;<?php 
    _e('OR', "wp-download_monitor");
    ?>
&rarr;</p>
								</div>
								<div style="float:left; width:362px;">
									<h3 style="margin:0 0 0.5em"><?php 
    _e('Enter file URL', "wp-download_monitor");
    ?>
</h3>
									<input type="text" style="width:360px;" class="cleardefault" value="<?php 
    if (isset($filename)) {
        echo $filename;
    }
    ?>
" name="filename" id="filename" /><br />
									<?php 
    if (get_option('wp_dlm_enable_file_browser') !== 'no') {
        ?>
									<a class="browsefiles" style="display:none" href="#"><?php 
        _e('Toggle File Browser', "wp-download_monitor");
        ?>
</a>
                        			<div id="file_browser"></div>
                        			<?php 
    }
    ?>
								</div>
								<div style="clear:both"></div>
							</div>
						</td>
                </tr> 
                <tr valign="top">												
                    <th scope="row"><strong><?php 
    _e('Download Mirrors', "wp-download_monitor");
    ?>
</strong></th> 
                    <td><textarea name="mirrors" style="width:360px;" cols="50" rows="2"><?php 
    if (isset($mirrors)) {
        echo $mirrors;
    }
    ?>
</textarea><br /><span class="setting-description"><?php 
    _e('Optionally list the url\'s of any mirrors here (1 per line). Download monitor will randomly pick one of these mirrors when serving the download.', "wp-download_monitor");
    ?>
</span></td>
                </tr>
                <tr valign="top">												
                    <th scope="row"><strong><?php 
    _e('Categories', "wp-download_monitor");
    ?>
</strong></th> 
                    <td><div id="categorydiv"><ul class="categorychecklist" style="background: #fff; border: 1px solid #DFDFDF; height: 200px; margin: 4px 1px; overflow: auto; padding: 3px 6px; width: 346px;">
                    		<?php 
    $cats = $download_taxonomies->get_parent_cats();
    if (!empty($cats)) {
        foreach ($cats as $c) {
            echo '<li><label for="category_' . $c->id . '"><input type="checkbox" name="category_' . $c->id . '" id="category_' . $c->id . '" ';
            if (isset($_POST['category_' . $c->id])) {
                echo 'checked="checked"';
            }
            echo ' /> ' . $c->id . ' - ' . $c->name . '</label>';
            // Do Children
            if (!function_exists('cat_form_output_children')) {
                function cat_form_output_children($child)
                {
                    global $download_taxonomies;
                    if ($child) {
                        echo '<li><label for="category_' . $child->id . '"><input type="checkbox" name="category_' . $child->id . '" id="category_' . $child->id . '" ';
                        if (isset($_POST['category_' . $child->id])) {
                            echo 'checked="checked"';
                        }
                        echo ' /> ' . $child->id . ' - ' . $child->name . '</label>';
                        echo '<ul class="children">';
                        $download_taxonomies->do_something_to_cat_children($child->id, 'cat_form_output_children', 'cat_form_output_no_children');
                        echo '</ul>';
                        echo '</li>';
                    }
                }
                function cat_form_output_no_children()
                {
                    echo '<li></li>';
                }
            }
            echo '<ul class="children">';
            $download_taxonomies->do_something_to_cat_children($c->id, 'cat_form_output_children', 'cat_form_output_no_children');
            echo '</ul>';
            echo '</li>';
        }
    }
    ?>
                    	</ul></div><a href="#" class="add-new-cat-ajax" style="display:none"><?php 
    _e('+ Add New Category', "wp-download_monitor");
    ?>
</a><div id="add_cat_form" style="display:none">
		                    <table class="niceblue small-table" cellpadding="0" cellspacing="0" style="width:362px;">
		                        <tr>
		                            <th scope="col"><?php 
    _e('Name', "wp-download_monitor");
    ?>
:</th>
		                            <td><input type="text" name="cat_name" style="width: 220px" /></td>
		                        </tr>
		                        <tr>
		                            <th scope="col"><?php 
    _e('Parent', "wp-download_monitor");
    ?>
:</th>
		                            <td><select name="cat_parent" style="width: 220px">
		                            	<option value=""><?php 
    _e('None', "wp-download_monitor");
    ?>
</option>
		                                <?php 
    if (!empty($cats)) {
        foreach ($cats as $c) {
            echo '<option value="' . $c->id . '">' . $c->id . ' - ' . $c->name . '</option>';
            echo get_option_children_cats($c->id, "{$c->name} &mdash; ", 0);
        }
    }
    ?>
		                            </select></td>
		                        </tr>
		                    </table>
	                    	<p class="submit" style="padding:0 "><input type="submit" value="<?php 
    _e('Add', "wp-download_monitor");
    ?>
" name="add_cat" id="add_cat" /></p>
                    	</div></td>
                </tr> 
                <tr valign="middle">
                    <th scope="row"><strong><?php 
    _e('Tags', "wp-download_monitor");
    ?>
: </strong></th> 
                    <td>
                        <input type="text" style="width:360px;" class="cleardefault" value="<?php 
    if (isset($tags)) {
        echo $tags;
    }
    ?>
" name="tags" id="dltags" /><br /><span class="setting-description"><?php 
    _e('Separate tags with commas.', "wp-download_monitor");
    ?>
 <a class="browsetags" style="display:none" href="#">Toggle Tags</a></span>
                    	<div id="tag-list" style="display:none;">
                    		<?php 
    $tags = $download_taxonomies->tags;
    echo '<ul>';
    if (!empty($tags)) {
        foreach ($tags as $tag) {
            echo '<li><a href="#" class="ins-tag">' . $tag->name . '</a></li>';
        }
    } else {
        echo '<li>' . __('No Tags Found', "wp-download_monitor") . '</li>';
    }
    echo '</ul>';
    ?>
                    	</div>
                    </td> 
                </tr>
                <tr valign="middle">
                    <th scope="row"><strong><?php 
    _e('Thumbnail', "wp-download_monitor");
    ?>
: </strong></th> 
					<td>
						<div style="width:820px;">
							<div style="float:left; width:362px;">
								<h3 style="margin:0 0 0.5em"><?php 
    _e('Upload thumbnail', "wp-download_monitor");
    ?>
</h3>
								<input type="file" name="thumbnail_upload" style="width:354px; margin:1px;" /><br /><span class="setting-description"><?php 
    _e('This will be displayed on the download page or with {thumbnail} in a custom format (a placeholder will be shown if not set).', "wp-download_monitor");
    ?>
</span>
							</div>
							<div style="float:left; text-align:center; width: 75px; margin: 0 8px; display:inline;">
								<p style="font-weight:bold; font-size:16px; color: #999; line-height: 48px; ">&larr;<?php 
    _e('OR', "wp-download_monitor");
    ?>
&rarr;</p>
							</div>
							<div style="float:left; width:362px;">
								<h3 style="margin:0 0 0.5em"><?php 
    _e('Enter thumbnail URL', "wp-download_monitor");
    ?>
</h3>
								<input type="text" style="width:360px;" class="cleardefault" value="<?php 
    if (isset($thumbnail)) {
        echo $thumbnail;
    }
    ?>
" name="thumbnail" id="thumbnail" /><br />
								<?php 
    if (get_option('wp_dlm_enable_file_browser') !== 'no') {
        ?>
								<a class="browsefilesthumbnail" style="display:none" href="#"><?php 
        _e('Toggle File Browser', "wp-download_monitor");
        ?>
</a>
                    			<div id="file_browser_thumbnail"></div>
                    			<?php 
    }
    ?>
							</div>
							<div style="clear:both;"></div>
						</div>
					</td>
                </tr>
                <tr valign="top">												
                    <th scope="row"><strong><?php 
    _e('Member only file?', "wp-download_monitor");
    ?>
</strong></th> 
                    <td><input type="checkbox" name="memberonly" style="vertical-align:top" <?php 
    if (isset($members) && $members == 1) {
        echo "checked='checked'";
    }
    ?>
 /> <span class="setting-description"><?php 
    _e('If chosen, only logged in users will be able to access the file via a download link. You can also add a custom field called min-level or req-role to set the minimum user level needed to download the file.', "wp-download_monitor");
    ?>
</span></td>
                </tr>
                <tr valign="top">												
                    <th scope="row"><strong><?php 
    _e('Force Download?', "wp-download_monitor");
    ?>
</strong></th> 
                    <td><input type="checkbox" name="forcedownload" style="vertical-align:top" <?php 
    if (isset($forcedownload) && $forcedownload == 1) {
        echo "checked='checked'";
    }
    ?>
 /> <span class="setting-description"><?php 
    _e('If chosen, Download Monitor will attempt to force the download rather than redirect. This setting is not compatible with all servers (so test it), and in most cases will only work on files hosted on the local server.', "wp-download_monitor");
    ?>
</span></td>
                </tr>

            </table>
            <h3><?php 
    _e('Custom fields', "wp-download_monitor");
    ?>
</h3>
            <p><?php 
    _e('Custom fields can be used to add extra metadata to a download. Leave blank to add none. Name should be lower case with no spaces (changed automatically, e.g. <code>Some Name</code> will become <code>some-name</code>.', "wp-download_monitor");
    ?>
</p>
			<table style="width:80%">
				<thead>
					<tr>
						<th class="left"><?php 
    _e('Name', "wp-download_monitor");
    ?>
</th>
						<th><?php 
    _e('Value', "wp-download_monitor");
    ?>
</th>
					</tr>			
				</thead>
				<tbody id="customfield_list">
					<?php 
    $index = 1;
    if ($_POST) {
        if (isset($_POST['meta'])) {
            foreach ($_POST['meta'] as $meta) {
                if (!isset($meta['remove'])) {
                    if (trim($meta['key'])) {
                        echo '<tr class="alternate">
										<td class="left" style="vertical-align:top;">
											<label class="hidden" for="meta[' . $index . '][key]">Key</label><input name="meta[' . $index . '][key]" id="meta[' . $index . '][key]" tabindex="6" size="20" value="' . strtolower(str_replace(' ', '-', trim($meta['key']))) . '" type="text" style="width:95%">
											<input type="submit" name="meta[' . $index . '][remove]" class="button" value="' . __('remove', "wp-download_monitor") . '" />
										</td>
										<td style="vertical-align:top;"><label class="hidden" for="meta[' . $index . '][value]">Value</label><textarea name="meta[' . $index . '][value]" id="meta[' . $index . '][value]" tabindex="6" rows="2" cols="30" style="width:95%">' . $meta['value'] . '</textarea></td>
									</tr>';
                    }
                }
                $index++;
            }
        }
        if (isset($_POST['addmeta'])) {
            echo '<tr class="alternate">
									<td class="left" style="vertical-align:top;">
										<label class="hidden" for="meta[' . $index . '][key]">Key</label><input name="meta[' . $index . '][key]" id="meta[' . $index . '][key]" tabindex="6" size="20" value="" type="text" style="width:95%" /><input type="submit" name="meta[' . $index . '][remove]" class="button" value="' . __('remove', "wp-download_monitor") . '" />
									</td>
									<td style="vertical-align:top;"><label class="hidden" for="meta[' . $index . '][value]">Value</label><textarea name="meta[' . $index . '][value]" id="meta[' . $index . '][value]" tabindex="6" rows="2" cols="30" style="width:95%"></textarea></td>
							</tr>';
        }
    }
    ?>
					<tr id="addmetarow">
						<td colspan="2" class="submit"><input id="addmetasub" name="addmeta" value="<?php 
    _e('Add Custom Field', "wp-download_monitor");
    ?>
" type="submit" style="margin-bottom: 6px !important;" /><br/><a class="seemetafields" style="display:none;" href="#"><?php 
    _e('Toggle Existing Custom Fields', "wp-download_monitor");
    ?>
</a>
						<div id="meta_fields" style="display:none">
							<?php 
    $fields = $wpdb->get_results("SELECT DISTINCT meta_name FROM {$wp_dlm_db_meta} WHERE meta_name NOT IN ('tags', 'thumbnail', 'force') ORDER BY meta_name;");
    if ($fields) {
        echo '<ul>';
        foreach ($fields as $field) {
            echo '<li><strong>' . $field->meta_name . '</strong> <button type="button" class="addmeta_rel" rel="' . $field->meta_name . '">Add</button></li>';
        }
        echo '</ul>';
    } else {
        echo '<p>' . __('None found.', "wp-download_monitor") . '</p>';
    }
    ?>
						</div></td>
					</tr>
				</tbody>
			</table>
			<hr />

            <p class="submit"><input type="submit" class="btn button-primary" name="save" style="padding:5px 30px 5px 30px;" value="<?php 
    _e('Upload &amp; save', "wp-download_monitor");
    ?>
" /></p>
			<input type="hidden" name="postDate" value="<?php 
    echo date_i18n(__('Y-m-d H:i:s', "wp-download_monitor"));
    ?>
" />
			<?php 
    global $userdata;
    get_currentuserinfo();
    echo '<input type="hidden" name="user" value="' . $userdata->user_login . '" />';
    ?>
									
		</form>
	</div>
	<?php 
    echo '</div>';
}
function wp_dlmp_output($base_heading_level = '3', $pop_count = 4, $pop_cat_count = 4, $show_uncategorized = true, $per_page = 20, $format = '', $exclude = '', $exclude_cat = '', $show_tags = 0, $default_order = 'title', $front_order = 'hits')
{
    if (function_exists('get_downloads')) {
        // DEFINE STRINGS (translate these if needed)
        $popular_text = __('Popular Downloads', 'wp-download_monitor');
        $tags_widget_text = __('Tags', 'wp-download_monitor');
        $uncategorized = __('Other', 'wp-download_monitor');
        $search_text = __('Search Downloads:', 'wp-download_monitor');
        $search_submit_text = __('Go', 'wp-download_monitor');
        $search_results_text = __('Results found for ', 'wp-download_monitor');
        $nonefound = __('No downloads were found.', 'wp-download_monitor');
        $notfound = __('No download found matching given ID.', 'wp-download_monitor');
        $main_page_back_text = __('Downloads', 'wp-download_monitor');
        $desc_heading = __('Description', 'wp-download_monitor');
        $version_text = __('Version', 'wp-download_monitor');
        $category_text = __('Categories', 'wp-download_monitor');
        $single_tags_text = __('Tags', 'wp-download_monitor');
        $hits_text = __('Downloaded', 'wp-download_monitor');
        $hits_text2 = __(' time', 'wp-download_monitor');
        $hits_text2_p = __(' times', 'wp-download_monitor');
        $posted_text = __('Date posted', 'wp-download_monitor');
        $posted_text2 = __('F j, Y', 'wp-download_monitor');
        $dbutton_text = __('Download', 'wp-download_monitor');
        $readmore_text = __('Read More', 'wp-download_monitor');
        $subcat_text = __('Sub-Categories:', 'wp-download_monitor');
        $sort_text = __('Sort by:', 'wp-download_monitor');
        $tags_text = __('Downloads tagged:', 'wp-download_monitor');
        // END DEFINE STRINGS
        global $wpdb, $wp_dlm_db, $wp_dlm_db_taxonomies, $wp_dlm_db_relationships, $post, $wp_dlmp_root, $wp_dlm_db_meta, $download_taxonomies;
        // Handle $exclude
        $exclude_array = array();
        if ($exclude) {
            $exclude_unclean = explode(',', $exclude);
            foreach ($exclude_unclean as $e) {
                $e = trim($e);
                if (is_numeric($e)) {
                    $exclude_array[] = $e;
                }
            }
        }
        if (sizeof($exclude_array) > 0) {
            $exclude_query = ' AND ' . $wp_dlm_db . '.id NOT IN (' . implode(',', $exclude_array) . ')';
        } else {
            $exclude_query = "";
            $exclude_array[] = 0;
        }
        // Handle $exclude_cat
        $exclude_cat_array = array();
        if ($exclude_cat) {
            $exclude_cat_unclean = explode(',', $exclude_cat);
            foreach ($exclude_cat_unclean as $e) {
                $e = trim($e);
                if (is_numeric($e)) {
                    $exclude_cat_array[] = $e;
                }
            }
        }
        $category_array = array();
        if (is_object($download_taxonomies) && sizeof($download_taxonomies->categories) > 0) {
            foreach ($download_taxonomies->categories as $category) {
                if (!in_array($category->id, $exclude_cat_array)) {
                    $category_array[$category->id] = $category;
                }
            }
        }
        // Find more IDS to exlude
        if (sizeof($exclude_cat_array) > 0) {
            $results = $wpdb->get_results("\n\t\tSELECT {$wp_dlm_db}.id \n\t\tFROM {$wp_dlm_db} \t\t\n\t\tLEFT JOIN {$wp_dlm_db_relationships} ON( {$wp_dlm_db}.id = {$wp_dlm_db_relationships}.download_id )\n\t\tLEFT JOIN {$wp_dlm_db_taxonomies} ON({$wp_dlm_db_relationships}.taxonomy_id = {$wp_dlm_db_taxonomies}.id)\n\t\tWHERE {$wp_dlm_db_taxonomies}.id IN (" . implode(',', $exclude_cat_array) . ")\n\t\tAND {$wp_dlm_db_taxonomies}.taxonomy = 'category';");
            $new_exclude_array = array();
            foreach ($results as $r) {
                $new_exclude_array[] = $r->id;
            }
            $exclude_array = array_merge($exclude_array, $new_exclude_array);
        }
        if (sizeof($exclude_array) > 0) {
            $exclude_query = ' AND ' . $wp_dlm_db . '.id NOT IN (' . implode(',', $exclude_array) . ')';
        } else {
            $exclude_query = "";
        }
        // Handle Formats
        global $download_formats_names_array, $def_format;
        $format = trim($format);
        if (!$format && $def_format > 0) {
            $format = wp_dlm_get_custom_format($def_format);
        } elseif ($format > 0 && is_numeric($format)) {
            $format = wp_dlm_get_custom_format($format);
        } else {
            if (isset($download_formats_names_array) && is_array($download_formats_names_array) && in_array($format, $download_formats_names_array)) {
                $format = wp_dlm_get_custom_format_by_name($format);
            } else {
                $format = html_entity_decode($format);
            }
        }
        // Default is none set/no defaults
        if (empty($format) || $format == '0') {
            $format = '<a class="downloadlink" href="{url}" title="{version,"' . __("Version", "wp-download_monitor") . '", ""} ' . __("downloaded", "wp-download_monitor") . ' {hits} ' . __("times", "wp-download_monitor") . '" >{title} ({hits})</a>';
        }
        wp_dlm_magic();
        // DOWNLOAD PAGE DATA FUNCTIONS
        if (!function_exists('wp_dlmp_append_url')) {
            function wp_dlmp_append_url($append)
            {
                global $post;
                $querystring = explode('?', get_permalink($post->ID));
                $add = '?';
                if (isset($querystring[1])) {
                    $add .= $querystring[1] . '&amp;';
                }
                $add .= $append;
                return $querystring[0] . $add;
            }
        }
        if (!function_exists('get_chain')) {
            function get_chain($cat, $chain = array())
            {
                global $download_taxonomies;
                $chain[] = '<a href="' . wp_dlmp_append_url('category=' . urlencode(strtolower($cat->id))) . '">&laquo; ' . $cat->name . '</a>';
                if ($cat->parent > 0) {
                    $chain = get_chain($download_taxonomies->categories[$cat->parent], $chain);
                }
                return $chain;
            }
            function no_chain($chain = array())
            {
                return $chain;
            }
        }
        // START PAGE OUTPUT
        $page = '';
        $fields = '';
        // Ensure it works with default permalinks
        global $post;
        if ($post && is_page()) {
            $fields = '<input type="hidden" name="page_id" value="' . $post->ID . '" />';
        }
        if ($post && is_single()) {
            $fields = '<input type="hidden" name="p" value="' . $post->ID . '" />';
        }
        if (isset($_GET['lang'])) {
            $fields .= '<input type="hidden" name="lang" value="' . $_GET['lang'] . '" />';
        }
        $dlsearch = '';
        if (isset($_REQUEST['dlsearch'])) {
            $dlsearch = $_REQUEST['dlsearch'];
        }
        $page .= '<div id="download-page">
		<form id="download-page-search" action="" method="post">
			<p><label for="dlsearch">' . $search_text . '</label> <input type="text" name="dlsearch" id="dlsearch" value="' . $dlsearch . '" /><input class="search_submit" type="submit" value="' . $search_submit_text . '" />' . $fields . '</p></form>';
        if (isset($dlsearch) && !empty($dlsearch)) {
            ##########################################################################################################################################################################################
            ## Search View
            ##########################################################################################################################################################################################
            $page .= '<h' . $base_heading_level . '>' . $search_results_text . '<em>"' . $dlsearch . '"</em> <small><a href="' . get_permalink($post->ID) . '">&laquo;&nbsp;' . $main_page_back_text . '</a></small></h' . $base_heading_level . '>';
            $orderby = '';
            if (!isset($_GET['sortby'])) {
                $_GET['sortby'] = $default_order;
            }
            // Sorting Options
            switch (trim(strtolower($_GET['sortby']))) {
                case 'hits':
                    $sort_hits = 'class="active"';
                    $sort_date = '';
                    $sort_title = '';
                    $orderby = 'ORDER BY ' . $wp_dlm_db . '.hits DESC';
                    break;
                case 'date':
                    $sort_date = 'class="active"';
                    $sort_hits = '';
                    $sort_title = '';
                    $orderby = 'ORDER BY ' . $wp_dlm_db . '.postDate DESC';
                    break;
                default:
                    $sort_title = 'class="active"';
                    $sort_date = '';
                    $sort_hits = '';
                    $orderby = 'ORDER BY ' . $wp_dlm_db . '.title ASC';
                    break;
            }
            $sort_options = array('<a href="' . wp_dlmp_append_url('dlsearch=' . urlencode($dlsearch) . '&sortby=title') . '" ' . $sort_title . '>' . __('Title', 'wp-download_monitor') . '</a>', '<a href="' . wp_dlmp_append_url('dlsearch=' . urlencode($dlsearch) . '&sortby=hits') . '" ' . $sort_hits . '>' . __('Hits', 'wp-download_monitor') . '</a>', '<a href="' . wp_dlmp_append_url('dlsearch=' . urlencode($dlsearch) . '&sortby=date') . '" ' . $sort_date . '>' . __('Date', 'wp-download_monitor') . '</a>');
            $page .= '<p class="sorting"><strong>' . $sort_text . '</strong> ';
            $page .= implode(' | ', $sort_options) . '</p>';
            // End Sorting Options
            // Pagination Calc
            $paged_query = "";
            if (!isset($_GET['dlpage'])) {
                $dlpage = 1;
            } else {
                $dlpage = $_GET['dlpage'];
            }
            $from = $dlpage * $per_page - $per_page;
            $paged_query = 'LIMIT ' . $from . ',' . $per_page . '';
            $total = $wpdb->get_var("SELECT COUNT(DISTINCT {$wp_dlm_db}.id) \n\t\t\t\tFROM {$wp_dlm_db}  \n\t\t\t\tLEFT JOIN {$wp_dlm_db_relationships} ON( {$wp_dlm_db}.id = {$wp_dlm_db_relationships}.download_id )\n\t\t\t\tLEFT JOIN {$wp_dlm_db_taxonomies} ON({$wp_dlm_db_relationships}.taxonomy_id = {$wp_dlm_db_taxonomies}.id)\n\t\t\t\tWHERE \n\t\t\t\t\t(\n\t\t\t\t\ttitle LIKE '%" . $wpdb->escape($_REQUEST['dlsearch']) . "%' \n\t\t\t\t\tOR filename LIKE '%" . $wpdb->escape($_REQUEST['dlsearch']) . "%'\n\t\t\t\t\tOR {$wp_dlm_db_taxonomies}.name LIKE '%" . $wpdb->escape($_REQUEST['dlsearch']) . "%'\n\t\t\t\t\tOR file_description LIKE '%" . $wpdb->escape($_REQUEST['dlsearch']) . "%'\n\t\t\t\t\t)\n\t\t\t\tAND {$wp_dlm_db}.id NOT IN (" . implode(',', $exclude_array) . ")\n\t\t\t;");
            $total_pages = ceil($total / $per_page);
            // End Pagination Calc
            $downloads = $wpdb->get_results("SELECT DISTINCT {$wp_dlm_db}.* \n\t\t\t\tFROM {$wp_dlm_db}  \n\t\t\t\tLEFT JOIN {$wp_dlm_db_relationships} ON( {$wp_dlm_db}.id = {$wp_dlm_db_relationships}.download_id )\n\t\t\t\tLEFT JOIN {$wp_dlm_db_taxonomies} ON({$wp_dlm_db_relationships}.taxonomy_id = {$wp_dlm_db_taxonomies}.id)\n\t\t\t\tWHERE \n\t\t\t\t\t(\n\t\t\t\t\ttitle LIKE '%" . $wpdb->escape($_REQUEST['dlsearch']) . "%' \n\t\t\t\t\tOR filename LIKE '%" . $wpdb->escape($_REQUEST['dlsearch']) . "%'\n\t\t\t\t\tOR {$wp_dlm_db_taxonomies}.name LIKE '%" . $wpdb->escape($_REQUEST['dlsearch']) . "%'\n\t\t\t\t\tOR file_description LIKE '%" . $wpdb->escape($_REQUEST['dlsearch']) . "%'\n\t\t\t\t\t)\n\t\t\t\tAND {$wp_dlm_db}.id NOT IN (" . implode(',', $exclude_array) . ")\n\t\t\t\t{$orderby} {$paged_query};");
            if (!empty($downloads)) {
                $page .= '<ul>';
                foreach ($downloads as $d) {
                    $page .= '<li>' . do_shortcode('[download id="' . $d->id . '" format="' . htmlspecialchars(str_replace('{url}', wp_dlmp_append_url('did=') . '{id}', $format)) . '"]') . '</li>';
                }
                $page .= '</ul>';
                // Show Pagination
                if ($total_pages > 1) {
                    $page .= '<ul class="pagination">';
                    if ($dlpage > 1) {
                        $prev = $dlpage - 1;
                        $page .= "<li><a href=\"" . wp_dlmp_append_url('dlsearch=' . urlencode($dlsearch) . '&sortby=' . strtolower($_GET['sortby']) . '&dlpage=' . $prev . '') . "\">&laquo; " . __('Previous', "wp-download_monitor") . "</a></li>";
                    } else {
                        $page .= "<li><span class='current page-numbers'>&laquo; " . __('Previous', "wp-download_monitor") . "</span></li>";
                    }
                    for ($i = 1; $i <= $total_pages; $i++) {
                        if ($dlpage == $i) {
                            $page .= "<li><span class='page-numbers current'>{$i}</span></li>";
                        } else {
                            $page .= "<li><a href=\"" . wp_dlmp_append_url('dlsearch=' . urlencode($dlsearch) . '&sortby=' . strtolower($_GET['sortby']) . '&dlpage=' . $i . '') . "\">{$i}</a></li>";
                        }
                    }
                    if ($dlpage < $total_pages) {
                        $next = $dlpage + 1;
                        $page .= "<li><a href=\"" . wp_dlmp_append_url('dlsearch=' . urlencode($dlsearch) . '&sortby=' . strtolower($_GET['sortby']) . '&dlpage=' . $next . '') . "\">" . __('Next', "wp-download_monitor") . " &raquo;</a></li>";
                    } else {
                        $page .= "<li><span class='current page-numbers'>" . __('Next', "wp-download_monitor") . " &raquo;</span></li>";
                    }
                    $page .= '</ul>';
                }
                // End show pagination
            } else {
                $page .= '<p>' . $nonefound . '</p>';
            }
        } elseif (isset($_GET['category'])) {
            ##########################################################################################################################################################################################
            ## Single Category view
            ##########################################################################################################################################################################################
            $category = $wpdb->escape(trim(urldecode(strtolower($_GET['category']))));
            $downloads = "";
            $total_pages = "";
            $dlpage = "";
            if (($category == strtolower($uncategorized) || $category == 0) && $show_uncategorized) {
                $count = $wpdb->get_var("\n\t\t\t\tSELECT COUNT(DISTINCT {$wp_dlm_db}.id) \n\t\t\t\tFROM {$wp_dlm_db} \n\t\t\t\tWHERE {$wp_dlm_db}.id NOT IN (\n\t\t\t\t\tSELECT download_id FROM {$wp_dlm_db_relationships}\n\t\t\t\t\tLEFT JOIN {$wp_dlm_db_taxonomies} ON {$wp_dlm_db_relationships}.taxonomy_id = {$wp_dlm_db_taxonomies}.id\n\t\t\t\t\tWHERE {$wp_dlm_db_taxonomies}.taxonomy = 'category'\n\t\t\t\t)\n\t\t\t\t{$exclude_query};\n\t\t\t");
                $page .= '<h' . $base_heading_level . '>' . ucwords($uncategorized) . ' (' . $count . ') <small><a href="' . get_permalink($post->ID) . '">&laquo;&nbsp;' . $main_page_back_text . '</a></small></h' . $base_heading_level . '>';
                $orderby = '';
                if (!isset($_GET['sortby'])) {
                    $_GET['sortby'] = $default_order;
                }
                // Sorting Options
                switch (trim(strtolower($_GET['sortby']))) {
                    case 'hits':
                        $sort_hits = 'class="active"';
                        $orderby = 'hits';
                        $order = 'desc';
                        break;
                    case 'date':
                        $sort_date = 'class="active"';
                        $orderby = 'postdate';
                        $order = 'desc';
                        break;
                    default:
                        $sort_title = 'class="active"';
                        $orderby = 'title';
                        $order = 'asc';
                        break;
                }
                $sort_options = array('<a href="' . wp_dlmp_append_url('category=' . urlencode(strtolower($uncategorized)) . '&sortby=title') . '" ' . $sort_title . '>' . __('Title', 'wp-download_monitor') . '</a>', '<a href="' . wp_dlmp_append_url('category=' . urlencode(strtolower($uncategorized)) . '&sortby=hits') . '" ' . $sort_hits . '>' . __('Hits', 'wp-download_monitor') . '</a>', '<a href="' . wp_dlmp_append_url('category=' . urlencode(strtolower($uncategorized)) . '&sortby=date') . '" ' . $sort_date . '>' . __('Date', 'wp-download_monitor') . '</a>');
                $page .= '<p class="sorting"><strong>' . $sort_text . '</strong> ';
                $page .= implode(' | ', $sort_options) . '</p>';
                // End Sorting Options
                // Pagination Calc
                if (!isset($_GET['dlpage'])) {
                    $dlpage = 1;
                } else {
                    $dlpage = $_GET['dlpage'];
                }
                $from = $dlpage * $per_page - $per_page;
                $total_pages = ceil($count / $per_page);
                // End Pagination Calc
                $page .= do_shortcode('[downloads query="exclude=' . implode(',', $exclude_array) . '&limit=' . $per_page . '&orderby=' . $orderby . '&order=' . $order . '&offset=' . $from . '&category=none" format="' . htmlspecialchars(str_replace('{url}', wp_dlmp_append_url('did=') . '{id}', $format)) . '"]');
            } else {
                if ($category_array[$category]) {
                    $cat = $category_array[$category];
                }
                if ($cat->id > 0) {
                    $chain = $download_taxonomies->do_something_to_cat_parents($cat->id, 'get_chain', 'no_chain');
                    if (is_array($chain) && sizeof($chain) > 0) {
                        $cat_breadcrumb = implode(' ', $chain);
                    }
                    // Count = children too
                    $in_cats = $cat->decendents;
                    $in_cats[] = $cat->id;
                    $count = $wpdb->get_var("\n\t\t\t\t\tSELECT COUNT(DISTINCT {$wp_dlm_db_relationships}.download_id) \n\t\t\t\t\tFROM {$wp_dlm_db_relationships} \n\t\t\t\t\tLEFT JOIN {$wp_dlm_db_taxonomies} ON({$wp_dlm_db_relationships}.taxonomy_id = {$wp_dlm_db_taxonomies}.id)\n\t\t\t\t\tWHERE {$wp_dlm_db_taxonomies}.id IN (" . implode(',', $in_cats) . ")\n\t\t\t\t\tAND {$wp_dlm_db_relationships}.download_id NOT IN (" . implode(',', $exclude_array) . ")\n\t\t\t\t\tAND {$wp_dlm_db_taxonomies}.taxonomy = 'category';\n\t\t\t\t");
                    if (!isset($cat_breadcrumb)) {
                        $cat_breadcrumb = '';
                    }
                    $page .= '<h' . $base_heading_level . '>' . wptexturize($cat->name) . ' (' . $count . ') <small>' . $cat_breadcrumb . ' <a href="' . get_permalink($post->ID) . '">&laquo;&nbsp;' . $main_page_back_text . '</a></small></h' . $base_heading_level . '>';
                    if (sizeof($cat->decendents) > 0) {
                        $subcats = array();
                        foreach ($cat->direct_decendents as $child_cat) {
                            if ($category_array[$child_cat]->name) {
                                $sub_in_cats = $category_array[$child_cat]->decendents;
                                $sub_in_cats[] = $category_array[$child_cat]->id;
                                $scount = $wpdb->get_var("\n\t\t\t\t\t\t\t\tSELECT COUNT(DISTINCT {$wp_dlm_db_relationships}.download_id) \n\t\t\t\t\t\t\t\tFROM {$wp_dlm_db_relationships} \n\t\t\t\t\t\t\t\tLEFT JOIN {$wp_dlm_db_taxonomies} ON({$wp_dlm_db_relationships}.taxonomy_id = {$wp_dlm_db_taxonomies}.id)\n\t\t\t\t\t\t\t\tWHERE {$wp_dlm_db_taxonomies}.id IN (" . implode(',', $sub_in_cats) . ")\n\t\t\t\t\t\t\t\tAND {$wp_dlm_db_relationships}.download_id NOT IN (" . implode(',', $exclude_array) . ")\n\t\t\t\t\t\t\t\tAND {$wp_dlm_db_taxonomies}.taxonomy = 'category';\n\t\t\t\t\t\t\t");
                                if ($scount > 0) {
                                    $subcats[] = wptexturize($category_array[$child_cat]->name) . ' ' . '<a href="' . wp_dlmp_append_url('category=' . urlencode(strtolower($category_array[$child_cat]->id))) . '">(' . $scount . ')</a>';
                                }
                            }
                        }
                        if (sizeof($subcats) > 0) {
                            $page .= '<p class="subcats"><strong>' . $subcat_text . '</strong> ';
                            sort($subcats);
                            $page .= implode(' | ', $subcats) . '</p>';
                        }
                    }
                    $orderby = '';
                    if (!isset($_GET['sortby'])) {
                        $_GET['sortby'] = $default_order;
                    }
                    // Sorting Options
                    switch (trim(strtolower($_GET['sortby']))) {
                        case 'hits':
                            $sort_hits = 'class="active"';
                            $sort_date = '';
                            $sort_title = '';
                            $orderby = 'hits';
                            $order = 'desc';
                            break;
                        case 'date':
                            $sort_date = 'class="active"';
                            $sort_hits = '';
                            $sort_title = '';
                            $orderby = 'postdate';
                            $order = 'desc';
                            break;
                        default:
                            $sort_title = 'class="active"';
                            $sort_hits = '';
                            $sort_date = '';
                            $orderby = 'title';
                            $order = 'asc';
                            break;
                    }
                    $sort_options = array('<a href="' . wp_dlmp_append_url('category=' . urlencode(strtolower($cat->id)) . '&sortby=title') . '" ' . $sort_title . '>' . __('Title', 'wp-download_monitor') . '</a>', '<a href="' . wp_dlmp_append_url('category=' . urlencode(strtolower($cat->id)) . '&sortby=hits') . '" ' . $sort_hits . '>' . __('Hits', 'wp-download_monitor') . '</a>', '<a href="' . wp_dlmp_append_url('category=' . urlencode(strtolower($cat->id)) . '&sortby=date') . '" ' . $sort_date . '>' . __('Date', 'wp-download_monitor') . '</a>');
                    $page .= '<p class="sorting"><strong>' . $sort_text . '</strong> ';
                    $page .= implode(' | ', $sort_options) . '</p>';
                    // End Sorting Options
                    // Pagination Calc
                    if (!isset($_GET['dlpage'])) {
                        $dlpage = 1;
                    } else {
                        $dlpage = $_GET['dlpage'];
                    }
                    $from = $dlpage * $per_page - $per_page;
                    $paged_query = 'LIMIT ' . $from . ',' . $per_page . '';
                    $total_pages = ceil($count / $per_page);
                    // End Pagination Calc
                    $page .= do_shortcode('[downloads query="exclude=' . implode(',', $exclude_array) . '&limit=' . $per_page . '&orderby=' . $orderby . '&order=' . $order . '&offset=' . $from . '&category=' . $cat->id . '" format="' . htmlspecialchars(str_replace('{url}', wp_dlmp_append_url('did=') . '{id}', $format)) . '"]');
                }
            }
            // Show Pagination
            if ($total_pages > 1) {
                $page .= '<ul class="pagination">';
                if ($dlpage > 1) {
                    $prev = $dlpage - 1;
                    $page .= "<li><a href=\"" . wp_dlmp_append_url('category=' . urlencode(strtolower($cat->id)) . '&sortby=' . strtolower($_GET['sortby']) . '&dlpage=' . $prev . '') . "\">&laquo; " . __('Previous', "wp-download_monitor") . "</a></li>";
                } else {
                    $page .= "<li><span class='current page-numbers'>&laquo; " . __('Previous', "wp-download_monitor") . "</span></li>";
                }
                for ($i = 1; $i <= $total_pages; $i++) {
                    if ($dlpage == $i) {
                        $page .= "<li><span class='page-numbers current'>{$i}</span></li>";
                    } else {
                        $page .= "<li><a href=\"" . wp_dlmp_append_url('category=' . urlencode(strtolower($cat->id)) . '&sortby=' . strtolower($_GET['sortby']) . '&dlpage=' . $i . '') . "\">{$i}</a></li>";
                    }
                }
                if ($dlpage < $total_pages) {
                    $next = $dlpage + 1;
                    $page .= "<li><a href=\"" . wp_dlmp_append_url('category=' . urlencode(strtolower($cat->id)) . '&sortby=' . strtolower($_GET['sortby']) . '&dlpage=' . $next . '') . "\">" . __('Next', "wp-download_monitor") . " &raquo;</a></li>";
                } else {
                    $page .= "<li><span class='current page-numbers'>" . __('Next', "wp-download_monitor") . " &raquo;</span></li>";
                }
                $page .= '</ul>';
            }
            // End show pagination
        } elseif (isset($_GET['dltag'])) {
            ##########################################################################################################################################################################################
            ## Tag View
            ##########################################################################################################################################################################################
            $tag = urldecode(strtolower(trim($_GET['dltag'])));
            if ($tag) {
                $page .= '<h' . $base_heading_level . '>' . $tags_text . ' ' . $tag . ' <small><a href="' . get_permalink($post->ID) . '">&laquo;&nbsp;' . $main_page_back_text . '</a></small></h' . $base_heading_level . '>';
                $orderby = '';
                if (!isset($_GET['sortby'])) {
                    $_GET['sortby'] = $default_order;
                }
                // Sorting Options
                switch (trim(strtolower($_GET['sortby']))) {
                    case 'hits':
                        $sort_hits = 'class="active"';
                        $sort_date = '';
                        $sort_title = '';
                        $orderby = 'hits';
                        $order = 'desc';
                        break;
                    case 'date':
                        $sort_date = 'class="active"';
                        $sort_hits = '';
                        $sort_title = '';
                        $orderby = 'postdate';
                        $order = 'desc';
                        break;
                    default:
                        $sort_title = 'class="active"';
                        $sort_date = '';
                        $sort_hits = '';
                        $orderby = 'title';
                        $order = 'asc';
                        break;
                }
                $sort_options = array('<a href="' . wp_dlmp_append_url('dltag=' . urlencode(strtolower($tag)) . '&sortby=title') . '" ' . $sort_title . '>' . __('Title', 'wp-download_monitor') . '</a>', '<a href="' . wp_dlmp_append_url('dltag=' . urlencode(strtolower($tag)) . '&sortby=hits') . '" ' . $sort_hits . '>' . __('Hits', 'wp-download_monitor') . '</a>', '<a href="' . wp_dlmp_append_url('dltag=' . urlencode(strtolower($tag)) . '&sortby=date') . '" ' . $sort_date . '>' . __('Date', 'wp-download_monitor') . '</a>');
                $page .= '<p class="sorting"><strong>' . $sort_text . '</strong> ';
                $page .= implode(' | ', $sort_options) . '</p>';
                // End Sorting Options
                // Pagination Calc
                if (!isset($_GET['dlpage'])) {
                    $dlpage = 1;
                } else {
                    $dlpage = $_GET['dlpage'];
                }
                $from = $dlpage * $per_page - $per_page;
                $count = $wpdb->get_var("\n\t\t\t\t\tSELECT COUNT(DISTINCT {$wp_dlm_db_relationships}.download_id) \n\t\t\t\t\tFROM {$wp_dlm_db_relationships} \n\t\t\t\t\tLEFT JOIN {$wp_dlm_db_taxonomies} ON({$wp_dlm_db_relationships}.taxonomy_id = {$wp_dlm_db_taxonomies}.id)\n\t\t\t\t\tWHERE {$wp_dlm_db_taxonomies}.name = '{$tag}'  \n\t\t\t\t\tAND {$wp_dlm_db_relationships}.download_id NOT IN (" . implode(',', $exclude_array) . ") \n\t\t\t\t\tAND {$wp_dlm_db_taxonomies}.taxonomy = 'tag';\n\t\t\t\t");
                $total_pages = ceil($count / $per_page);
                // End Pagination Calc
                $page .= do_shortcode('[downloads query="exclude=' . implode(',', $exclude_array) . '&limit=' . $per_page . '&orderby=' . $orderby . '&order=' . $order . '&offset=' . $from . '&tags=' . $tag . '" format="' . htmlspecialchars(str_replace('{url}', wp_dlmp_append_url('did=') . '{id}', $format)) . '"]');
                // Show Pagination
                if ($total_pages > 1) {
                    $page .= '<ul class="pagination">';
                    if ($dlpage > 1) {
                        $prev = $dlpage - 1;
                        $page .= "<li><a href=\"" . wp_dlmp_append_url('dltag=' . urlencode(strtolower($tag)) . '&sortby=' . strtolower($_GET['sortby']) . '&dlpage=' . $prev . '') . "\">&laquo; " . __('Previous', "wp-download_monitor") . "</a></li>";
                    } else {
                        $page .= "<li><span class='current page-numbers'>&laquo; " . __('Previous', "wp-download_monitor") . "</span></li>";
                    }
                    for ($i = 1; $i <= $total_pages; $i++) {
                        if ($dlpage == $i) {
                            $page .= "<li><span class='page-numbers current'>{$i}</span></li>";
                        } else {
                            $page .= "<li><a href=\"" . wp_dlmp_append_url('dltag=' . urlencode(strtolower($tag)) . '&sortby=' . strtolower($_GET['sortby']) . '&dlpage=' . $i . '') . "\">{$i}</a></li>";
                        }
                    }
                    if ($dlpage < $total_pages) {
                        $next = $dlpage + 1;
                        $page .= "<li><a href=\"" . wp_dlmp_append_url('dltag=' . urlencode(strtolower($tag)) . '&sortby=' . strtolower($_GET['sortby']) . '&dlpage=' . $next . '') . "\">" . __('Next', "wp-download_monitor") . " &raquo;</a></li>";
                    } else {
                        $page .= "<li><span class='current page-numbers'>" . __('Next', "wp-download_monitor") . " &raquo;</span></li>";
                    }
                    $page .= '</ul>';
                }
                // End show pagination
            }
        } elseif (isset($_GET['did']) && is_numeric($_GET['did']) && $_GET['did'] > 0) {
            ##########################################################################################################################################################################################
            ## Single Download View
            ##########################################################################################################################################################################################
            $d = $wpdb->get_row("SELECT * FROM {$wp_dlm_db} WHERE {$wp_dlm_db}.id = " . $wpdb->escape($_GET['did']) . " {$exclude_query} LIMIT 1;");
            if (!empty($d)) {
                $download = new downloadable_file($d);
                if ($download->category) {
                    $catname = trim($download->category);
                } else {
                    $catname = ucwords($uncategorized);
                }
                $date = date("jS M Y", strtotime($download->date));
                if ($download->dlversion) {
                    $version = __('Version', "wp-download_monitor") . ' ' . $download->dlversion;
                } else {
                    $version = '';
                }
                if ($download->file_description) {
                    $desc = apply_filters('download_description', $download->file_description);
                } else {
                    $desc = "";
                }
                $thumbnail_url = $download->thumbnail;
                // Gen category breadcrumb
                if ($download->category_id) {
                    $chain[] = '<a href="' . wp_dlmp_append_url('category=' . urlencode(strtolower($download_taxonomies->categories[$download->category_id]->id))) . '">&laquo; ' . $download_taxonomies->categories[$download->category_id]->name . '</a>';
                    $chain = $download_taxonomies->do_something_to_cat_parents($download->category_id, 'get_chain', 'no_chain', $chain);
                    $cat_breadcrumb = implode(' ', $chain);
                } else {
                    $cat_breadcrumb = '<a href="' . wp_dlmp_append_url('category=' . urlencode(strtolower($uncategorized)) . '') . '">&laquo;&nbsp;' . ucwords($uncategorized) . '</a>';
                }
                $page .= '<div class="download-info single">	        		
	        		
		           	<div class="side-section">
		        		<p><img src="' . $thumbnail_url . '" class="download-image" alt="' . strip_tags($download->title) . '" title="' . strip_tags($download->title) . '" width="112" /></p>';
                if (!isset($download->meta['hide_download_button'])) {
                    $page .= '<p><a href="' . do_shortcode('[download id="' . $download->id . '" format="{url}"]') . '" class="download-button">' . $dbutton_text . '</a></p>';
                }
                // Handle post_id field
                if (isset($download->meta['post_id']) && is_numeric($download->meta['post_id'])) {
                    $page .= '<p><a href="' . get_permalink($download->meta['post_id']) . '" class="more-button">' . $readmore_text . '</a></p>';
                } else {
                    $page .= '<div class="related-projects">' . "\n";
                    // multiple ids
                    $page .= '<h3>' . __('Related', 'wp-download_monitor') . ':</h3><ul>';
                    $post_ids = explode(',', $download->meta['post_id']);
                    // split into array
                    foreach ($post_ids as $dl) {
                        // print link for each array entry
                        $page .= '<li><a href="' . get_permalink(trim($dl)) . '">' . get_the_title(trim($dl)) . '</a></li>';
                    }
                    $page .= '</ul></div> <!-- /.related-projects -->' . "\n";
                }
                // Special additional content meta field
                if (isset($download->meta['side_content'])) {
                    $extra = $download->meta['side_content'];
                    if ($extra) {
                        $page .= '<div class="extra">' . $extra . '</div>';
                    }
                }
                $page .= '
		        	</div>
		        	<div class="main-section">
		        		<h' . $base_heading_level . ' class="download-info-heading">' . $download->title . ' <small>' . $cat_breadcrumb . ' <small><a href="' . get_permalink($post->ID) . '">&laquo;&nbsp;' . $main_page_back_text . '</a></small></small></h' . $base_heading_level . '>
	        	';
                // Show Meta Fields + download data
                $custom_field_data = array();
                if ($download->dlversion) {
                    $custom_field_data[] = array($version_text, $download->dlversion);
                }
                $custom_field_data[] = array($posted_text, date($posted_text2, strtotime($download->postDate)));
                if (!isset($download->meta['hide_hits'])) {
                    if ($download->hits == 1) {
                        $custom_field_data[] = array($hits_text, $download->hits . $hits_text2);
                    } else {
                        $custom_field_data[] = array($hits_text, $download->hits . $hits_text2_p);
                    }
                }
                if ($download->categories) {
                    $names = array();
                    foreach ($download->categories as $cat) {
                        $names[] = '<a href="' . wp_dlmp_append_url('category=' . urlencode(strtolower($cat['id']))) . '">' . $cat['name'] . '</a>';
                    }
                    $custom_field_data[] = array($category_text, implode(', ', $names));
                }
                if ($download->tags) {
                    $names = array();
                    foreach ($download->tags as $tag) {
                        $names[] = '<a href="' . wp_dlmp_append_url('dltag=' . urlencode(strtolower($tag['name']))) . '">' . $tag['name'] . '</a>';
                    }
                    $custom_field_data[] = array($single_tags_text, implode(', ', $names));
                }
                if (isset($download->meta['include_fields'])) {
                    $show_custom_fields = $download->meta['include_fields'];
                    if ($show_custom_fields) {
                        $show_custom_fields = explode(',', $show_custom_fields);
                    }
                    if (sizeof($show_custom_fields) > 0) {
                        // Get each custom field's value ready to output
                        foreach ($show_custom_fields as $field) {
                            $value = $download->meta[$field];
                            if (!empty($value)) {
                                $custom_field_data[] = array(ucfirst(str_replace('-', ' ', $field)), $value);
                            }
                        }
                    }
                }
                if (sizeof($custom_field_data) > 0) {
                    // Output
                    $page .= '<table class="download-meta" cellspacing="0" style="width:100%"><thead><tr><th scope="col">Attribute</th><th style="text-align:right" scope="col">Value</th></tr></thead><tbody>';
                    foreach ($custom_field_data as $field) {
                        $page .= '<tr><th scope="row">' . $field[0] . '</th><td style="text-align:right">' . do_shortcode($field[1]) . '</td></tr>';
                    }
                    $page .= '</tbody></table>';
                }
                // Show Description
                if ($desc) {
                    $page .= '<div class="download-desc">
		        			<h' . ($base_heading_level + 1) . ' class="download-desc-heading">' . $desc_heading . '</h' . ($base_heading_level + 1) . '>
		        			' . $desc . '
		        		</div>';
                }
                $page .= '</div>';
                /* Close main-section */
                $page .= '</div>';
                /* Close download-info */
            } else {
                $page .= '<p>' . $notfound . '</p>';
            }
        } else {
            ##########################################################################################################################################################################################
            ## Front View
            ##########################################################################################################################################################################################
            if ($pop_count > 0) {
                // Front view
                $page .= '<div id="download-page-featured">
					<h' . $base_heading_level . '>' . $popular_text . '</h' . $base_heading_level . '><ul>';
                // Get top downloads
                $downloads = get_downloads('limit=' . $pop_count . '&orderby=hits&order=desc&exclude=' . implode(',', $exclude_array) . '');
                if (!empty($downloads)) {
                    $alt = -1;
                    foreach ($downloads as $d) {
                        if ($alt == 1) {
                            $alttext = 'alternate';
                        } else {
                            $alttext = '';
                        }
                        $date = date("jS M Y", strtotime($d->date));
                        if ($d->version) {
                            $version = __('Version', "wp-download_monitor") . ' ' . $d->version;
                        } else {
                            $version = '';
                        }
                        if ($d->desc) {
                            $desc = do_shortcode(wptexturize(wpautop(current(explode('<!--more-->', $d->desc)))));
                        } else {
                            $desc = "";
                        }
                        $thumbnail_url = $d->thumbnail;
                        if (!$thumbnail_url) {
                            $thumbnail_url = $wp_dlmp_root . 'thumbnail.gif';
                        }
                        $page .= '<li class="' . $alttext . '"><a href="' . wp_dlmp_append_url('did=' . $d->id) . '" title="' . $version . ' ' . __('Downloaded', "wp-download_monitor") . ' ' . $d->hits . ' ' . __('times', "wp-download_monitor") . '" ><span><img src="' . $thumbnail_url . '" class="download-thumbnail" alt="' . strip_tags($d->title) . '" title="' . strip_tags($d->title) . '"  /></span> <span>' . $d->title . '</span></a></li>';
                        $alt = $alt * -1;
                    }
                }
                $page .= '</ul></div>';
                // End top
            }
            // Tags View
            if ($show_tags > 0) {
                $page .= '<div id="download-page-tags">
					<h' . $base_heading_level . '>' . $tags_widget_text . '</h' . $base_heading_level . '><ul>';
                // Get tags
                $tags = $download_taxonomies->used_tags;
                if (!empty($tags)) {
                    $sized_tags = array();
                    foreach ($tags as $tag) {
                        $sized_tags[$tag->name] = $tag->size;
                    }
                    $max = max($sized_tags);
                    $min = min($sized_tags);
                    $div = $max - $min;
                    if (!$div) {
                        $div = 1;
                    }
                    $multiplier = (200 - 80) / $div;
                    asort($sized_tags);
                    $sized_tags = array_reverse($sized_tags);
                    $sized_tags = array_slice($sized_tags, 0, $show_tags);
                    ksort($sized_tags);
                    foreach ($sized_tags as $tag => $count) {
                        $size = 80 + ($max - ($max - ($count - $min))) * $multiplier;
                        $page .= '<li style="font-size:' . $size . '%"><a href="' . wp_dlmp_append_url('dltag=' . urlencode(strtolower($tag))) . '">' . $tag . '</a></li>';
                    }
                }
                $page .= '</ul></div>';
            }
            // End Tags
            // Begin cats
            $page .= '<div id="download-page-categories">';
            // Show categories
            if (sizeof($category_array) > 0) {
                $alt = -1;
                foreach ($category_array as $cat) {
                    if ($cat->parent > 0) {
                        continue;
                    }
                    // Count = children too
                    $in_cats = $cat->decendents;
                    $in_cats[] = $cat->id;
                    $count = $wpdb->get_var("\n\t\t\t\t\tSELECT COUNT(DISTINCT {$wp_dlm_db_relationships}.download_id) \n\t\t\t\t\tFROM {$wp_dlm_db_relationships} \n\t\t\t\t\tLEFT JOIN {$wp_dlm_db_taxonomies} ON({$wp_dlm_db_relationships}.taxonomy_id = {$wp_dlm_db_taxonomies}.id)\n\t\t\t\t\tWHERE {$wp_dlm_db_taxonomies}.id IN (" . implode(',', $in_cats) . ")\n\t\t\t\t\tAND {$wp_dlm_db_relationships}.download_id NOT IN (" . implode(',', $exclude_array) . ")\n\t\t\t\t\tAND {$wp_dlm_db_taxonomies}.taxonomy = 'category';\n\t\t\t\t");
                    if ($count == 0) {
                        continue;
                    }
                    if ($alt == 1) {
                        $alttext = 'alternate';
                    } else {
                        $alttext = '';
                    }
                    $page .= '<div class="category ' . $alttext . '"><div class="inner">';
                    $page .= '<h' . $base_heading_level . '><a href="' . wp_dlmp_append_url('category=' . urlencode(strtolower($cat->id))) . '">' . wptexturize($cat->name) . ' (' . $count . ') &raquo;</a></h' . $base_heading_level . '>';
                    if ($pop_cat_count > 0) {
                        $page .= '<ol>';
                        $page .= do_shortcode('[downloads query="exclude=' . implode(',', $exclude_array) . '&limit=' . $pop_cat_count . '&orderby=' . $front_order . '&order=desc&category=' . $cat->id . '" wrap="" format="' . htmlspecialchars(str_replace('{url}', wp_dlmp_append_url('did=') . '{id}', $format)) . '"]');
                        $page .= '</ol>';
                    }
                    $page .= '</div></div>';
                    $alt = $alt * -1;
                }
                // $show_uncategorized
                if ($show_uncategorized) {
                    if ($alt == 1) {
                        $alttext = 'alternate';
                    } else {
                        $alttext = '';
                    }
                    $count = $wpdb->get_var("\n\t\t\t\t\tSELECT COUNT(DISTINCT {$wp_dlm_db}.id) \n\t\t\t\t\tFROM {$wp_dlm_db} \n\t\t\t\t\tWHERE {$wp_dlm_db}.id NOT IN (\n\t\t\t\t\t\tSELECT download_id FROM {$wp_dlm_db_relationships}\n\t\t\t\t\t\tLEFT JOIN {$wp_dlm_db_taxonomies} ON {$wp_dlm_db_relationships}.taxonomy_id = {$wp_dlm_db_taxonomies}.id\n\t\t\t\t\t\tWHERE {$wp_dlm_db_taxonomies}.taxonomy = 'category'\n\t\t\t\t\t)\n\t\t\t\t\t{$exclude_query};\n\t\t\t\t");
                    if ($count > 0) {
                        $page .= '<div class="category ' . $alttext . '"><div class="inner">';
                        $page .= '<h' . $base_heading_level . '><a href="' . wp_dlmp_append_url('category=' . urlencode(strtolower($uncategorized)) . '') . '">' . ucwords($uncategorized) . ' (' . $count . ') &raquo;</a></h' . $base_heading_level . '>';
                        if ($pop_cat_count > 0) {
                            $page .= '<ol>';
                            $page .= do_shortcode('[downloads query="exclude=' . implode(',', $exclude_array) . '&limit=' . $pop_cat_count . '&orderby=' . $front_order . '&order=desc&category=none" wrap="" format="' . htmlspecialchars(str_replace('{url}', wp_dlmp_append_url('did=') . '{id}', $format)) . '"]');
                            $page .= '</ol>';
                        }
                        $page .= '</div></div>';
                        $alt = $alt * -1;
                    }
                }
            }
            $page .= '</div>';
            // End cats
        }
        $page .= '</div>';
        $page .= "\n<!-- Download Page powered by WordPress Download Monitor (http://mikejolley.com). Fugue icons by Yusuke Kamiyamane (http://pinvoke.com). -->";
        return $page;
    }
}
Esempio n. 3
0
function wp_dlm_config()
{
    //set globals
    global $wpdb, $wp_dlm_root, $wp_dlm_db, $wp_dlm_db_taxonomies, $wp_dlm_db_formats, $dlm_url, $downloadtype, $wp_dlm_db_relationships;
    // turn off magic quotes
    wp_dlm_magic();
    $ins_format = false;
    $save_url = false;
    $save_opt = false;
    ?>

	<div class="download_monitor">

	<div class="wrap alternate">

    <div id="downloadadminicon" class="icon32"><br/></div>
    <h2><?php 
    _e('Download Monitor Configuration', "wp-download_monitor");
    ?>
</h2>
    <?php 
    if (isset($_GET['action'])) {
        $action = $_GET['action'];
    } else {
        $action = '';
    }
    if (!empty($action)) {
        $nonce = $_REQUEST['_wpnonce'];
        if (!wp_verify_nonce($nonce)) {
            die('Security check');
        }
        switch ($action) {
            case "saveurl":
                $dlm_url = $_POST['url'];
                update_option('wp_dlm_url', trim($dlm_url));
                update_option('wp_dlm_type', $_POST['type']);
                $downloadtype = get_option('wp_dlm_type');
                if (!empty($dlm_url)) {
                    echo '<div id="message"class="updated fade">';
                    _e('<p>Download URL updated - You need to <strong>re-save your permalinks settings</strong> (Options/settings -> Permalinks) for
						the changes to occur in your blog.</p>
						<p>If your .htaccess file cannot be written to by WordPress, add the following to your
					.htaccess file above the "# BEGIN WordPress" line:</p>
						<p>Options +FollowSymLinks<br/>
						RewriteEngine on<br/>
						RewriteRule ^download/([^/]+)$ *your wp-content dir*/plugins/download-monitor/download.php?id=$1 [L]</p>
						<p>replacing "download/" with your custom url and "*your wp-content dir*" with your wp-content directory.</p>', "wp-download_monitor");
                    echo '</div>';
                } else {
                    echo '<div id="message"class="updated fade">';
                    _e('<p>Download URL updated - You need to <strong>re-save your permalinks settings</strong> (Options/settings -> Permalinks) for
						the changes to occur in your blog.</p>
						<p>If your .htaccess file cannot be written to by WordPress, remove the following from your
					.htaccess file if it exists above the "# BEGIN WordPress" line:</p>
						<p>Options +FollowSymLinks<br/>
						RewriteEngine on<br/>
						RewriteRule ^download/([^/]+)$ *your wp-content dir*/plugins/download-monitor/download.php?id=$1 [L]</p>
						<p>replacing "download/" with your previous custom url and "*your wp-content dir*" with your wp-content directory.</p>', "wp-download_monitor");
                    echo '</div>';
                }
                $save_url = true;
                $show = true;
                break;
            case "saveoptions":
                update_option('wp_dlm_disable_news', $_POST['wp_dlm_disable_news']);
                update_option('wp_dlm_image_url', $_POST['wp_dlm_image_url']);
                update_option('wp_dlm_default_format', $_POST['wp_dlm_default_format']);
                update_option('wp_dlm_does_not_exist', $_POST['wp_dlm_does_not_exist']);
                update_option('wp_dlm_member_only', $_POST['wp_dlm_member_only']);
                update_option('wp_dlm_log_downloads', $_POST['wp_dlm_log_downloads']);
                update_option('wp_dlm_enable_file_browser', $_POST['wp_dlm_enable_file_browser']);
                update_option('wp_dlm_auto_mirror', $_POST['wp_dlm_auto_mirror']);
                update_option('wp_dlm_global_member_only', $_POST['wp_dlm_global_member_only']);
                update_option('wp_dlm_log_timeout', $_POST['wp_dlm_log_timeout']);
                update_option('wp_dlm_ip_blacklist', $_POST['wp_dlm_ip_blacklist']);
                if ($_POST['wp_dlm_file_browser_root']) {
                    update_option('wp_dlm_file_browser_root', $_POST['wp_dlm_file_browser_root']);
                } else {
                    update_option('wp_dlm_file_browser_root', ABSPATH);
                }
                $save_opt = true;
                echo '<div id="message"class="updated fade">';
                _e('<p>Options updated</p>', "wp-download_monitor");
                echo '</div>';
                $show = true;
                break;
            case "upgrade":
                wp_dlm_upgrade();
                $show = true;
                break;
            case "cleanup":
                wp_dlm_cleanup();
                echo '<div id="message" class="updated fade"><p><strong>' . __('Database Cleaned', "wp-download_monitor") . '</strong></p></div>';
                $show = true;
                break;
            case "formats":
                wp_cache_flush();
                if (isset($_POST['savef'])) {
                    $loop = 0;
                    if (is_array($_POST['formatfieldid'])) {
                        foreach ($_POST['formatfieldid'] as $formatid) {
                            if ($_POST['formatfield'][$loop]) {
                                $query_update = sprintf("UPDATE %s SET `format`='%s' WHERE id = %s;", $wpdb->escape($wp_dlm_db_formats), $wpdb->escape(stripslashes($_POST['formatfield'][$loop])), $wpdb->escape($formatid));
                                $wpdb->query($query_update);
                            }
                            //echo htmlspecialchars($wpdb->escape( stripslashes($_POST['formatfield'][$loop]) ));
                            $loop++;
                        }
                        echo '<div id="message" class="updated fade"><p><strong>' . __('Formats updated', "wp-download_monitor") . '</strong></p></div>';
                        $ins_format = true;
                    }
                } else {
                    $name = $_POST['format_name'];
                    $format = $_POST['format'];
                    if (!empty($name) && !empty($format)) {
                        $query_ins = sprintf("INSERT INTO %s (name, format) VALUES ('%s','%s')", $wpdb->escape($wp_dlm_db_formats), $wpdb->escape($name), $wpdb->escape($format));
                        $wpdb->query($query_ins);
                        echo '<div id="message" class="updated fade"><p><strong>' . __('Format added', "wp-download_monitor") . '</strong></p></div>';
                        $ins_format = true;
                    }
                }
                $show = true;
                break;
            case "deleteformat":
                wp_cache_flush();
                $id = $_GET['id'];
                // Delete
                $query_delete = sprintf("DELETE FROM %s WHERE id=%s;", $wpdb->escape($wp_dlm_db_formats), $wpdb->escape($id));
                $wpdb->query($query_delete);
                echo '<div id="message" class="updated fade"><p><strong>' . __('Format deleted Successfully', "wp-download_monitor") . '</strong></p></div>';
                $ins_format = true;
                $show = true;
                break;
        }
    }
    if (!isset($show)) {
        $show = false;
    }
    if ($show == true || empty($action)) {
        ?>
	<br class="" style="clear: both;"/>
    <div id="poststuff" class="dlm meta-box-sortables">
            <div class="postbox <?php 
        if (!$ins_format) {
            echo 'close-me';
        }
        ?>
 dlmbox">
            <h3><?php 
        _e('Custom Output Formats', "wp-download_monitor");
        ?>
</h3>
            <div class="inside" style="padding:8px 16px 16px">
            	<?php 
        _e('<p>This allows you to define formats in which to output your downloads however you want.</p>', "wp-download_monitor");
        ?>
                <form action="<?php 
        echo wp_nonce_url(admin_url('admin.php?page=dlm_config&amp;action=formats'));
        ?>
" method="post">
                    <table class="widefat">
                        <thead>
                            <tr>
                            	<th scope="col"><?php 
        _e('ID', "wp-download_monitor");
        ?>
</th>
                                <th scope="col"><?php 
        _e('Name', "wp-download_monitor");
        ?>
</th>
                                <th scope="col"><?php 
        _e('Format', "wp-download_monitor");
        ?>
</th>
                                <th scope="col" style="text-align:center"><?php 
        _e('Action', "wp-download_monitor");
        ?>
</th>
                            </tr>
                        </thead>
                        <tbody id="the-list">
                        	<?php 
        $query_select_formats = sprintf("SELECT * FROM %s ORDER BY id;", $wpdb->escape($wp_dlm_db_formats));
        $formats = $wpdb->get_results($query_select_formats);
        if (!empty($formats)) {
            foreach ($formats as $f) {
                echo '<tr><td style="vertical-align:middle;">' . $f->id . '</td><td style="vertical-align:middle;">' . $f->name . '</td>
										<td style="vertical-align:middle;"><input type="hidden" value="' . $f->id . '" name="formatfieldid[]" /><textarea name="formatfield[]" style="width:100%;" rows="2">' . htmlspecialchars($f->format) . '</textarea></td>
										<td style="text-align:center;vertical-align:middle;"><a href="' . wp_nonce_url(admin_url('admin.php?page=dlm_config&amp;action=deleteformat&amp;id=' . $f->id)) . '"><img src="' . WP_CONTENT_URL . '/plugins/download-monitor/img/cross.png" alt="' . __('Delete', "wp-download_monitor") . '" title="' . __('Delete', "wp-download_monitor") . '" /></a></td></tr>';
            }
        } else {
            echo '<tr><td colspan="3">' . __('No formats exist', "wp-download_monitor") . '</td></tr>';
        }
        ?>
                        </tbody>
                    </table>
                    <p class="submit" style="margin:0; padding-bottom:0;"><input name="savef" type="submit" value="<?php 
        _e('Save Changes', "wp-download_monitor");
        ?>
" /></p>

                	<h4 style="font-size:1.4em"><?php 
        _e('Add format', "wp-download_monitor");
        ?>
</h4>

                	<table class="niceblue small-table" cellpadding="0" cellspacing="0">
                	    <tr>
                	        <th scope="col"><?php 
        _e('Name', "wp-download_monitor");
        ?>
:</th>
                	        <td><input type="text" name="format_name" /></td>
                	    </tr>
                	    <tr>
                	        <th scope="col"><?php 
        _e('Format', "wp-download_monitor");
        ?>
:</th>
                	        <td><input type="text" name="format" style="width:360px;" /></td>
                	    </tr>
                	</table>
                	<p class="submit"><input type="submit" value="<?php 
        _e('Add', "wp-download_monitor");
        ?>
" /></p>

                	<h5 style="float:left; color: #fff; background: #8A8A8A; padding: 8px; margin: 0;"><?php 
        _e('Available Tags', "wp-download_monitor");
        ?>
</h5>
                	<div style="margin:0 0 12px;height:150px;overflow:auto;border:2px solid #8A8A8A;padding:4px; clear:both;">
	                	<p><?php 
        _e('Use the following tags in your custom formats: <em>note</em> if you use <code>"</code> (quote) characters within the special attributes e.g. <code>"before"</code> you should either escape them or use html entities.', "wp-download_monitor");
        ?>
</p>
	                	<ul>
		                	<li><code>{url}</code> - <?php 
        _e('Url of download (does not include hyperlink)', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{id}</code> - <?php 
        _e('ID of download', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{user}</code> - <?php 
        _e('Username of whoever posted download', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{version}</code> - <?php 
        _e('Version of download', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{version,"before","after"}</code> - <?php 
        _e('Version of download. Not outputted if none set. Replace "before" with preceding text/html and "after" with succeeding text/html.', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{title}</code> - <?php 
        _e('Title of download', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{size}</code> - <?php 
        _e('Filesize of download', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{categories}</code> - <?php 
        _e('Outputs comma separated list of categories.', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{categories, "<em>link</em>"}</code> - <?php 
        _e('Outputs comma separated list of categories contained in a link with the href you define. <code>%</code> replaced with category id. <code>%2</code> replaced with category name. This can be used with the <code>[download_page]</code>.', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{category,"before","after"}</code> <?php 
        _e('or', "wp-download_monitor");
        ?>
 <code>{category}</code> - <?php 
        _e('(Top Level/First) Download Category. Replace "before" with preceding text/html and "after" with succeeding text/html.', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{category_other,"before","after"}</code> <?php 
        _e('or', "wp-download_monitor");
        ?>
 <code>{category_other}</code> - <?php 
        _e('(Top Level/First) Download Category (but if no category is set "other" is returned. Replace "before" with preceding text/html and "after" with succeeding text/html.', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{category_ID}</code> - <?php 
        _e('(Top Level/First) Download Category ID.', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{hits}</code> - <?php 
        _e('Current hit count', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{hits,"No hits","1 Hit","% hits"}</code> - <?php 
        _e('Formatted hit count depending on hits. <code>%</code> replaced with hit count.', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{image_url}</code> - <?php 
        _e('URL of the download image', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{description,"before","after"}</code> <?php 
        _e('or', "wp-download_monitor");
        ?>
 <code>{description}</code> - <?php 
        _e('Description you gave download. Not outputted if none set. Replace "before" with preceding text/html and "after" with succeeding text/html.', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{description-autop,"before","after"}</code> <?php 
        _e('or', "wp-download_monitor");
        ?>
 <code>{description-autop}</code> - <?php 
        _e('Description formatted with autop (converts double line breaks to paragraphs)', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{date,"Y-m-d"}</code> - <?php 
        _e('Date posted. Second argument is for date format.', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{tags}</code> - <?php 
        _e('Outputs comma separated list of tags.', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{tags, "<em>link</em>"}</code> - <?php 
        _e('Outputs comma separated list of tags contained in a link with the href you define. <code>%</code> replaced with tag id. <code>%2</code> replaced with tag name.', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{thumbnail}</code> - <?php 
        _e('Output thumbnail URL (or placeholder)', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{meta-<em>key</em>}</code> - <?php 
        _e('Custom field value', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{meta-autop-<em>key</em>}</code> - <?php 
        _e('Custom field value formatted with autop', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{filetype}</code> - <?php 
        _e('File extension (e.g. "zip")', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{filetype_icon}</code> - <?php 
        _e('File extension icon (16x16)', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{mirror-1-url}</code> - <?php 
        _e('Output a Mirror\'s url', "wp-download_monitor");
        ?>
</li>
		                	<li><code>{content}</code> - <?php 
        _e('Include the styled content that [download]content[/download] wraps', "wp-download_monitor");
        ?>
</li>
		                </ul>
	                </div>
	                <h5 style="float:left; color: #fff; background: #8A8A8A; padding: 8px; margin: 0;"><?php 
        _e('Example Formats', "wp-download_monitor");
        ?>
</h5>
	                <div style="margin:0;height:150px;overflow:auto;border:2px solid #8A8A8A;padding:4px; clear:both;">
	                	<p><?php 
        _e('Here are some example custom formats you can use or modify.', "wp-download_monitor");
        ?>
</p>
	                	<ul>
	                    	<li><?php 
        _e('Link and description of download with hits in title:', "wp-download_monitor");
        ?>
 &ndash; <code>&lt;a href="{url}" title="Downloaded {hits} times"&gt;{title}&lt;/a&gt; - {description}</code></li>
	                    	<li><?php 
        _e('Standard link with no hits:', "wp-download_monitor");
        ?>
 &ndash; <code>&lt;a href="{url}"&gt;{title}&lt;/a&gt;</code></li>
	                    	<li><?php 
        _e('Image link:', "wp-download_monitor");
        ?>
 &ndash; <code>&lt;a href="{url}"&gt;&lt;img src="{image_url}" alt="{title}" /&gt;&lt;/a&gt;</code></li>
	                    </ul>
	                </div>
                </form>
            </div>
        </div>
        <div class="postbox <?php 
        if (!$save_url) {
            echo 'close-me';
        }
        ?>
 dlmbox">
            <h3><?php 
        _e('Custom Download URL', "wp-download_monitor");
        ?>
</h3>
            <div class="inside">
            	<?php 
        _e('<p>Set a custom url for your downloads, e.g. <code>download/</code>. You can also choose how to link to the download in it\'s url, e.g. selecting "filename" would make the link appear as <code>http://yoursite.com/download/filename.zip</code>. This option will only work if using wordpress permalinks (other than default).</p>

                        <p>Leave this option blank to use the default download path (<code>/download-monitor/download.php?id=</code>)</p>
                        <p>If you fill in this option ensure the custom directory does not exist on the server nor does it match a page or post\'s url as this can cause problems redirecting to download.php.</p>', "wp-download_monitor");
        ?>

                 <div style="display:block; width:716px; clear:both; margin:12px auto 4px; border:3px solid #eee; -moz-border-radius: 4px; -webkit-border-radius: 4px;">
                 <p style="background:#eee;padding:4px; margin:0;"><strong><?php 
        _e('Without Custom URL:', "wp-download_monitor");
        ?>
</strong></p>
                 <img style="padding:8px" src="<?php 
        echo $wp_dlm_root;
        ?>
img/explain.gif" alt="Explanation" />
                 </div>

                 <div style="display:block; width:716px; clear:both; margin:12px auto 4px; border:3px solid #eee; -moz-border-radius: 4px; -webkit-border-radius: 4px;">
                 <p style="background:#eee;padding:4px; margin:0;"><strong><?php 
        _e('With Custom URL (downloads/ID):', "wp-download_monitor");
        ?>
</strong></p>
                 <img style="padding:8px" src="<?php 
        echo $wp_dlm_root;
        ?>
img/explain2.gif" alt="Explanation" /></div>

                <form action="<?php 
        echo wp_nonce_url(admin_url('admin.php?page=dlm_config&amp;action=saveurl'));
        ?>
" method="post">
                    <table class="niceblue form-table">
                        <tr>
                            <th scope="col"><strong><?php 
        _e('Custom URL', "wp-download_monitor");
        ?>
:</strong></th>
                            <td><?php 
        echo get_bloginfo('url');
        ?>
/<input type="text" name="url" value="<?php 
        echo $dlm_url;
        ?>
" />
                            <select name="type" style="width:150px;padding:2px !important;cursor:pointer;">
                                    <option<?php 
        if ($downloadtype == "ID") {
            echo ' selected="selected" ';
        }
        ?>
 value="ID"><?php 
        _e('ID', "wp-download_monitor");
        ?>
</option>
                                    <option<?php 
        if ($downloadtype == "Title") {
            echo ' selected="selected" ';
        }
        ?>
 value="Title"><?php 
        _e('Title', "wp-download_monitor");
        ?>
</option>
                                    <option<?php 
        if ($downloadtype == "Filename") {
            echo ' selected="selected" ';
        }
        ?>
 value="Filename"><?php 
        _e('Filename', "wp-download_monitor");
        ?>
</option>
                            </select></td>
                        </tr>
                    </table>
                    <p class="submit"><input type="submit" value="<?php 
        _e('Save Changes', "wp-download_monitor");
        ?>
" /></p>
                </form>
            </div>
        </div>
        <div class="postbox <?php 
        if (!$save_opt) {
            echo 'close-me';
        }
        ?>
 dlmbox">
            <h3><?php 
        _e('General Options', "wp-download_monitor");
        ?>
</h3>
            <div class="inside">
                <form action="<?php 
        echo wp_nonce_url(admin_url('admin.php?page=dlm_config&amp;action=saveoptions'));
        ?>
" method="post">
                    <table class="niceblue form-table">

                        <tr>
                            <th scope="col"><?php 
        _e('Disable the news/links/donate box on the Edit Download Page?', "wp-download_monitor");
        ?>
:</th>
                            <td>
	                            <select name="wp_dlm_disable_news" id="wp_dlm_disable_news">
	                            	<option value="yes" <?php 
        if (get_option('wp_dlm_disable_news') == 'yes') {
            echo 'selected="selected" ';
        }
        ?>
><?php 
        _e('Yes', "wp-download_monitor");
        ?>
</option>
	                        		<option value="no" <?php 
        if (!get_option('wp_dlm_disable_news') || get_option('wp_dlm_disable_news') == 'no') {
            echo 'selected="selected" ';
        }
        ?>
><?php 
        _e('No', "wp-download_monitor");
        ?>
</option>
	                            </select>
                            </td>
                        </tr>
                        <tr>
                            <th scope="col"><?php 
        _e('"Download not found" redirect URL', "wp-download_monitor");
        ?>
:</th>
                            <td><input type="text" value="<?php 
        echo get_option('wp_dlm_does_not_exist');
        ?>
" name="wp_dlm_does_not_exist" /> <span class="setting-description"><?php 
        _e('Leave blank for no redirect.', "wp-download_monitor");
        ?>
</span></td>
                        </tr>
                        <tr>
                            <th scope="col"><?php 
        _e('Member-only files non-member redirect', "wp-download_monitor");
        ?>
:</th>
                            <td><input type="text" value="<?php 
        echo get_option('wp_dlm_member_only');
        ?>
" name="wp_dlm_member_only" /> <span class="setting-description"><?php 
        _e('Leave blank for no redirect.', "wp-download_monitor");
        ?>
 <?php 
        _e('Note: <code>{referrer}</code> will be replaced with current url. Useful if sending user to the login page and then back to the download :) e.g. <code>http://yourdomain.com/wp-login.php?redirect_to={referrer}</code>.', "wp-download_monitor");
        ?>
</span></td>
                        </tr>
                        <tr>
                            <th scope="col"><?php 
        _e('Global member only files', "wp-download_monitor");
        ?>
:</th>
                            <td>
                            	<select name="wp_dlm_global_member_only" id="wp_dlm_global_member_only">
                            		<option value="no" <?php 
        if (get_option('wp_dlm_global_member_only') == 'no') {
            echo 'selected="selected" ';
        }
        ?>
><?php 
        _e('No', "wp-download_monitor");
        ?>
</option>
                            		<option value="yes" <?php 
        if (get_option('wp_dlm_global_member_only') == 'yes') {
            echo 'selected="selected" ';
        }
        ?>
><?php 
        _e('Yes', "wp-download_monitor");
        ?>
</option>
                            	</select> <span class="setting-description"><?php 
        _e('Makes all downloads member only, ignoring the individual download member only setting.', "wp-download_monitor");
        ?>
</span>
                            </td>
                        </tr>
                        <tr>
                            <th scope="col"><?php 
        _e('Download image path', "wp-download_monitor");
        ?>
:</th>
                            <td><input type="text" value="<?php 
        echo get_option('wp_dlm_image_url');
        ?>
" name="wp_dlm_image_url" /> <span class="setting-description"><?php 
        _e('This image is used when using the <code>#image</code> download tag and the <code>{image_url}</code> tag on this page. Please use an absolute url (e.g. <code>http://yoursite.com/image.gif</code>).', "wp-download_monitor");
        ?>
</span></td>
                        </tr>
                        <tr>
                            <th scope="col"><?php 
        _e('Default output format', "wp-download_monitor");
        ?>
:</th>
                            <td><select name="wp_dlm_default_format" id="wp_dlm_default_format">
                            	<option value="0"><?php 
        _e('None', "wp-download_monitor");
        ?>
</option>
                        	<?php 
        $query_select_formats = sprintf("SELECT * FROM %s ORDER BY id;", $wpdb->escape($wp_dlm_db_formats));
        $formats = $wpdb->get_results($query_select_formats);
        if (!empty($formats)) {
            foreach ($formats as $f) {
                echo '<option ';
                if (get_option('wp_dlm_default_format') == $f->id) {
                    echo 'selected="selected" ';
                }
                echo 'value="' . $f->id . '">' . $f->name . '</option>';
            }
        }
        ?>
                            </select></td>
                        </tr>
                        <tr>
	                        <th scope="col"><?php 
        _e('Auto-select mirror', "wp-download_monitor");
        ?>
:</th>
	                        <td>
	                        	<select name="wp_dlm_auto_mirror" id="wp_dlm_auto_mirror">
	                        		<option value="yes" <?php 
        if (get_option('wp_dlm_auto_mirror') == 'yes') {
            echo 'selected="selected" ';
        }
        ?>
><?php 
        _e('Yes', "wp-download_monitor");
        ?>
</option>
	                        		<option value="no" <?php 
        if (get_option('wp_dlm_auto_mirror') == 'no') {
            echo 'selected="selected" ';
        }
        ?>
><?php 
        _e('No', "wp-download_monitor");
        ?>
</option>
	                        	</select> <span class="setting-description"><?php 
        _e('If a download has "mirrors" set should download.php automatically pick one?', "wp-download_monitor");
        ?>
</span>
	                        </td>
	                    </tr>
                        <tr>
                            <th scope="col"><?php 
        _e('Log Downloads', "wp-download_monitor");
        ?>
:</th>
                            <td>
	                            <select name="wp_dlm_log_downloads" id="wp_dlm_log_downloads">
	                            	<option value="yes" <?php 
        if (get_option('wp_dlm_log_downloads') == 'yes') {
            echo 'selected="selected" ';
        }
        ?>
><?php 
        _e('Yes', "wp-download_monitor");
        ?>
</option>
	                        		<option value="no" <?php 
        if (get_option('wp_dlm_log_downloads') == 'no') {
            echo 'selected="selected" ';
        }
        ?>
><?php 
        _e('No', "wp-download_monitor");
        ?>
</option>
	                            </select>
                            </td>
                        </tr>
                        <tr>
                            <th scope="col"><?php 
        _e('Log Timeout', "wp-download_monitor");
        ?>
:</th>
                            <td>
                            	<input type="text" value="<?php 
        echo get_option('wp_dlm_log_timeout');
        ?>
" name="wp_dlm_log_timeout" /> <span class="setting-description"><?php 
        _e('0 means all downloads are logged. Increase to set the timeout in minutes so that downloads by the same person are not logged multiple times.', "wp-download_monitor");
        ?>
</span>
                            </td>
                        </tr>
                        <tr>
                            <th scope="col"><?php 
        _e('Log/Count Blacklist', "wp-download_monitor");
        ?>
:</th>
                            <td>
                            	<textarea cols="15" rows="5" name="wp_dlm_ip_blacklist"><?php 
        echo get_option('wp_dlm_ip_blacklist');
        ?>
</textarea> <span class="setting-description"><?php 
        _e('List IP addresses here that you wish to exclude from the logs/counts - 1 per line.', "wp-download_monitor");
        ?>
</span>
                            </td>
                        </tr>
                        <tr>
                            <th scope="col"><?php 
        _e('Enable File Browser', "wp-download_monitor");
        ?>
:</th>
                            <td>
	                            <select name="wp_dlm_enable_file_browser" id="wp_dlm_enable_file_browser">
	                            	<option value="yes" <?php 
        if (get_option('wp_dlm_enable_file_browser') == 'yes') {
            echo 'selected="selected" ';
        }
        ?>
><?php 
        _e('Yes', "wp-download_monitor");
        ?>
</option>
	                            	<option value="no" <?php 
        if (get_option('wp_dlm_enable_file_browser') == 'no') {
            echo 'selected="selected" ';
        }
        ?>
><?php 
        _e('No', "wp-download_monitor");
        ?>
</option>
	                            </select>
                            </td>
                        </tr>
                        <tr>
                            <th scope="col"><?php 
        _e('File Browser Root', "wp-download_monitor");
        ?>
:</th>
                            <td><input type="text" value="<?php 
        echo get_option('wp_dlm_file_browser_root');
        ?>
" name="wp_dlm_file_browser_root" /> <span class="setting-description"><?php 
        _e('The root directory the file browser can display.', "wp-download_monitor");
        ?>
</span></td>
                        </tr>

                       <?php 
        /* Playing <tr>
                                    <th scope="col"><?php _e('&ldquo;Edit&rdquo; page role requirement',"wp-download_monitor"); ?>:</th>
                                    <td><select name="edit_role">
                                    	<?php
                                    		$rolenames = $wp_roles->get_names();
                                    		foreach ($rolenames as $key=>$role) {
                                    			echo '<option ';
        
                                    			echo ' value="'.$key.'">'.$role.'</option>';
                                    		}
                                    	?>
                                    </select> and above.</td>
                                </tr> */
        ?>

                    </table>
                    <p class="submit"><input type="submit" value="<?php 
        _e('Save Changes', "wp-download_monitor");
        ?>
" /></p>
                </form>
            </div>
        </div>
        <div class="postbox close-me dlmbox">
            <h3><?php 
        _e('Advanced Stuff', "wp-download_monitor");
        ?>
</h3>
            <div class="inside">
            	<h4><?php 
        _e('Upgrade from 3.2.3', "wp-download_monitor");
        ?>
</h4>
            	<?php 
        _e('<p>Download monitor uses new tables from version 3.3 onwards; this was to clean things up and add multiple category support.</p>', "wp-download_monitor");
        ?>
                <?php 
        _e('<p>This update should have been done when you activated the plugin, but if it didn\'t, use this function to create the new tables and import from the old ones.</p>', "wp-download_monitor");
        ?>
                <form action="<?php 
        echo wp_nonce_url(admin_url('admin.php?page=dlm_config&amp;action=upgrade'));
        ?>
" method="post">
                    <p class="submit"><input type="submit" value="<?php 
        _e('Upgrade Database', "wp-download_monitor");
        ?>
" /></p>
                </form>
                <hr/>
                <h4><?php 
        _e('Upgraded Successfully? Cleanup!', "wp-download_monitor");
        ?>
</h4>
            	<?php 
        _e('<p>As stated above, tables were renamed from 3.3 onwards - if the upgrade has been successful (woo) you may use this function to delete the old tables (I left them there as a backup).</p>', "wp-download_monitor");
        ?>
                <?php 
        _e('<p>WARNING: THIS MAY DELETE DOWNLOAD DATA IN THE DATABASE; BACKUP YOUR DATABASE FIRST!</p>', "wp-download_monitor");
        ?>
                <form action="<?php 
        echo wp_nonce_url(admin_url('admin.php?page=dlm_config&amp;action=cleanup'));
        ?>
" method="post">
                    <p class="submit"><input type="submit" value="<?php 
        _e('Clean me up Scotty', "wp-download_monitor");
        ?>
" /></p>
                </form>
            </div>
        </div>
    </div>
    <script type="text/javascript">
		<!--
		<?php 
        global $wp_db_version;
        if ($wp_db_version >= 9872) {
            echo "jQuery('.postbox h3').before('<div class=\"handlediv\" title=\"" . __('Click to toggle', "wp-download_monitor") . "\"><br /></div>');";
        } else {
            echo "jQuery('.postbox h3').prepend('<a class=\"togbox\">+</a> ');";
        }
        ?>

		jQuery('.postbox h3').click( function() { jQuery(jQuery(this).parent().get(0)).toggleClass('closed'); } );
		jQuery('.postbox.close-me').each(function(){
			jQuery(this).addClass("closed");
		});
		//-->
	</script>
	<?php 
    }
    echo '</div></div>';
}
Esempio n. 4
0
function dlm_adddir()
{
    //set globals
    global $wpdb, $wp_dlm_root, $wp_dlm_db, $wp_dlm_db_taxonomies, $wp_dlm_db_formats, $wp_dlm_db_meta, $download_taxonomies, $wp_dlm_db_relationships;
    // turn off magic quotes
    wp_dlm_magic();
    ?>

	<div class="download_monitor">

	<div class="wrap alternate">

    <div class="wrap">

    <div id="downloadadminicon" class="icon32"><br/></div>
    <h2><?php 
    _e('Add From Directory', "wp-download_monitor");
    ?>
</h2>
    <p><?php 
    _e('This feature lets you add downloads in bulk from a directory <strong>on your server</strong>. It will attempt to read sub-directories too. It will do its best to choose relevant titles for each download - if you need to change titles or add extra information you will have to edit the downloads afterwards.', "wp-download_monitor");
    ?>
</p>
    <?php 
    if ($_POST) {
        //get postdata
        $exe = htmlspecialchars(trim($_POST['exe']));
        $filename = htmlspecialchars(trim($_POST['filename']));
        $postDate = $_POST['postDate'];
        $user = $_POST['user'];
        $members = isset($_POST['memberonly']) ? 1 : 0;
        $forcedownload = isset($_POST['forcedownload']) ? 1 : 0;
        if (isset($_POST['download_cat'])) {
            $download_cat = $_POST['download_cat'];
        } else {
            $download_cat = '';
        }
    }
    if (isset($_POST['save'])) {
        //validate fields
        if (empty($_POST['filename'])) {
            $errors .= __('<div class="error">No folder selected</div>', "wp-download_monitor");
        }
        $tags = $_POST['tags'];
        //save to db
        if (empty($errors)) {
            if (!function_exists('php4_scandir') && !function_exists('scandir')) {
                function php4_scandir($dir, $listDirectories = true)
                {
                    $dirArray = array();
                    if ($handle = opendir($dir)) {
                        while (false !== ($file = readdir($handle))) {
                            if ($listDirectories == false) {
                                if (is_dir($file)) {
                                    continue;
                                }
                            }
                            array_push($dirArray, basename($file));
                        }
                        closedir($handle);
                    }
                    return $dirArray;
                }
            }
            global $found_downloads, $extensions;
            $extensions = array();
            if ($exe) {
                $extensions = explode(',', $exe);
            }
            global $found_downloads;
            $found_downloads = array();
            function find_downloads($dir)
            {
                global $found_downloads, $extensions;
                $root_dir = '';
                if (file_exists($root_dir . $dir)) {
                    if (function_exists('scandir')) {
                        $files = scandir($root_dir . $dir);
                    } else {
                        $files = php4_scandir($root_dir . $dir);
                    }
                    if (count($files) > 2) {
                        // All dirs
                        foreach ($files as $file) {
                            if (file_exists($root_dir . $dir . $file) && $file != '.' && $file != '..' && is_dir($root_dir . $dir . $file)) {
                                find_downloads(htmlentities($dir . $file . '/'));
                            }
                        }
                        // All files
                        foreach ($files as $file) {
                            if (file_exists($root_dir . $dir . $file) && $file != '.' && $file != '..' && !is_dir($root_dir . $dir . $file)) {
                                $ext = preg_replace('/^.*\\./', '', $file);
                                if ($ext != 'php' && (in_array($ext, $extensions) || sizeof($extensions) == 0)) {
                                    $info = pathinfo($file);
                                    $found_downloads[] = array('path' => htmlentities($dir . $file), 'title' => trim(ucwords(htmlentities(str_replace('_', ' ', str_replace('.' . $info['extension'], '', $file))))));
                                }
                            }
                        }
                    }
                }
            }
            $dir = urldecode($filename);
            $dir = str_replace(get_bloginfo('wpurl') . '/', ABSPATH, $dir);
            find_downloads($dir);
            if (sizeof($found_downloads) > 0) {
                $count = 0;
                $found_download_ids = array();
                foreach ($found_downloads as $adownload) {
                    $query_add = sprintf("INSERT INTO %s (title, filename, dlversion, postDate, hits, user, members, mirrors, file_description) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s')", $wpdb->escape($wp_dlm_db), $wpdb->escape($adownload['title']), $wpdb->escape($adownload['path']), "", $wpdb->escape($_POST['postDate']), "0", $wpdb->escape($_POST['user']), $wpdb->escape($members), "", "");
                    $result = $wpdb->query($query_add);
                    if ($result) {
                        $download_insert_id = $wpdb->insert_id;
                        $found_download_ids[] = $download_insert_id;
                        // Loop Categories
                        $cats = $download_taxonomies->categories;
                        $values = array();
                        if (!empty($cats)) {
                            foreach ($cats as $c) {
                                $this_cat_value = isset($_POST['category_' . $c->id]) ? 1 : 0;
                                if ($this_cat_value) {
                                    $values[] = '("' . $wpdb->escape($c->id) . '", ' . $download_insert_id . ')';
                                }
                            }
                        }
                        if (sizeof($values) > 0) {
                            $wpdb->query("INSERT INTO {$wp_dlm_db_relationships} (taxonomy_id, download_id) VALUES " . implode(',', $values) . "");
                        }
                        // Tags
                        $values = array();
                        if ($tags) {
                            // Break 'em up
                            $thetags = explode(',', $tags);
                            $thetags = array_map('trim', $thetags);
                            if (sizeof($thetags) > 0) {
                                foreach ($thetags as $tag) {
                                    if ($tag) {
                                        // Exists?
                                        $tag_id = $wpdb->get_var("SELECT id FROM {$wp_dlm_db_taxonomies} WHERE taxonomy='tag' AND name='" . $wpdb->escape($tag) . "';");
                                        // Insert
                                        if (!$tag_id) {
                                            $wpdb->query("INSERT INTO {$wp_dlm_db_taxonomies} (name, parent, taxonomy) VALUES ('" . $wpdb->escape($tag) . "', 0, 'tag');");
                                            $tag_id = $wpdb->insert_id;
                                        }
                                        if ($tag_id) {
                                            $values[] = '("' . $wpdb->escape($tag_id) . '", ' . $download_insert_id . ')';
                                        }
                                    }
                                }
                            }
                        }
                        if (sizeof($values) > 0) {
                            $wpdb->query("INSERT INTO {$wp_dlm_db_relationships} (taxonomy_id, download_id) VALUES " . implode(',', $values) . "");
                        }
                        // Thumbnail
                        if (isset($thumbnail)) {
                            $wpdb->query("INSERT INTO {$wp_dlm_db_meta} (meta_name, meta_value, download_id) VALUES ('thumbnail', '" . $wpdb->escape($thumbnail) . "', '" . $download_insert_id . "')");
                        }
                        // Force Download
                        if (isset($forcedownload)) {
                            $wpdb->query("INSERT INTO {$wp_dlm_db_meta} (meta_name, meta_value, download_id) VALUES ('force', '" . $wpdb->escape($forcedownload) . "', '" . $download_insert_id . "')");
                        }
                        $count++;
                    }
                }
                // Process and save meta/custom fields
                $index = 1;
                $values = array();
                if (isset($_POST['meta'])) {
                    foreach ($_POST['meta'] as $meta) {
                        if (trim($meta['key'])) {
                            if ($found_download_ids) {
                                foreach ($found_download_ids as $download_id) {
                                    $values[] = '("' . $wpdb->escape(strtolower(str_replace(' ', '-', trim(stripslashes($meta['key']))))) . '", "' . $wpdb->escape($meta['value']) . '", ' . $download_id . ')';
                                    $index++;
                                }
                            }
                        }
                    }
                }
                if (sizeof($values) > 0) {
                    $wpdb->query("INSERT INTO {$wp_dlm_db_meta} (meta_name, meta_value, download_id) VALUES " . implode(',', $values) . "");
                }
                wp_dlm_clear_cached_stuff();
                // Message
                echo '<div id="message" class="updated fade"><p><strong>' . $count . ' ' . __("Downloads added Successfully", "wp-download_monitor") . '</strong></p></div>';
                exit;
            } else {
                echo '<div id="message" class="updated fade"><p><strong>' . __("No files found", "wp-download_monitor") . '</strong></p></div>';
            }
        } else {
            echo $errors;
        }
    }
    ?>
		<form action="<?php 
    wp_nonce_url(admin_url('admin.php?page=dlm_adddir&amp;action=add&amp;method=upload'));
    ?>
" method="post" id="wp_dlm_add" name="add_download" class="form-table">
            <table class="optiontable niceblue" cellpadding="0" cellspacing="0">
                <tr valign="top">
                    <th scope="row"><strong><?php 
    _e('Directory (relative paths only)', "wp-download_monitor");
    ?>
:</strong></th>
                    <td>
                        <input type="text" style="width:360px;" class="cleardefault" value="<?php 
    if (isset($filename)) {
        echo $filename;
    }
    ?>
" name="filename" id="filename" /><br/>
                        <?php 
    if (get_option('wp_dlm_enable_file_browser') !== 'no') {
        ?>
                        <a class="browsefiles" style="display:none" href="#"><?php 
        _e('Toggle Folder Browser', "wp-download_monitor");
        ?>
</a>
                        <div id="file_browser2"></div>
                        <?php 
    }
    ?>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><strong><?php 
    _e('Extensions', "wp-download_monitor");
    ?>
:</strong></th>
                    <td>
                        <input type="text" style="width:360px;" class="cleardefault" value="<?php 
    if (isset($exe)) {
        echo $exe;
    }
    ?>
" name="exe" id="exe" /><br /><span class="setting-description"><?php 
    _e('List extensions to look for separated by commas, or leave blank to import all. Example: zip,gif,jpg', "wp-download_monitor");
    ?>
</a>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><strong><?php 
    _e('Categories', "wp-download_monitor");
    ?>
</strong></th>
                    <td><div id="categorydiv"><ul class="categorychecklist" style="background: #fff; border: 1px solid #DFDFDF; height: 200px; margin: 4px 1px; overflow: auto; padding: 3px 6px; width: 346px;">
                    		<?php 
    $cats = $download_taxonomies->get_parent_cats();
    if (!empty($cats)) {
        foreach ($cats as $c) {
            echo '<li><label for="category_' . $c->id . '"><input type="checkbox" name="category_' . $c->id . '" id="category_' . $c->id . '" ';
            if (isset($_POST['category_' . $c->id])) {
                echo 'checked="checked"';
            }
            echo ' /> ' . $c->id . ' - ' . $c->name . '</label>';
            // Do Children
            if (!function_exists('cat_form_output_children')) {
                function cat_form_output_children($child)
                {
                    global $download_taxonomies;
                    if ($child) {
                        echo '<li><label for="category_' . $child->id . '"><input type="checkbox" name="category_' . $child->id . '" id="category_' . $child->id . '" ';
                        if (isset($_POST['category_' . $child->id])) {
                            echo 'checked="checked"';
                        }
                        echo ' /> ' . $child->id . ' - ' . $child->name . '</label>';
                        echo '<ul class="children">';
                        $download_taxonomies->do_something_to_cat_children($child->id, 'cat_form_output_children', 'cat_form_output_no_children');
                        echo '</ul>';
                        echo '</li>';
                    }
                }
                function cat_form_output_no_children()
                {
                    echo '<li></li>';
                }
            }
            echo '<ul class="children">';
            $download_taxonomies->do_something_to_cat_children($c->id, 'cat_form_output_children', 'cat_form_output_no_children');
            echo '</ul>';
            echo '</li>';
        }
    }
    ?>
                    	</ul></div><a href="#" class="add-new-cat-ajax" style="display:none"><?php 
    _e('+ Add New Category', "wp-download_monitor");
    ?>
</a><div id="add_cat_form" style="display:none">
		                    <table class="niceblue small-table" cellpadding="0" cellspacing="0" style="width:362px;">
		                        <tr>
		                            <th scope="col"><?php 
    _e('Name', "wp-download_monitor");
    ?>
:</th>
		                            <td><input type="text" name="cat_name" style="width: 220px" /></td>
		                        </tr>
		                        <tr>
		                            <th scope="col"><?php 
    _e('Parent', "wp-download_monitor");
    ?>
:</th>
		                            <td><select name="cat_parent" style="width: 220px">
		                            	<option value=""><?php 
    _e('None', "wp-download_monitor");
    ?>
</option>
		                                <?php 
    if (!empty($cats)) {
        foreach ($cats as $c) {
            echo '<option value="' . $c->id . '">' . $c->id . ' - ' . $c->name . '</option>';
            echo get_option_children_cats($c->id, "{$c->name} &mdash; ", 0);
        }
    }
    ?>
		                            </select></td>
		                        </tr>
		                    </table>
	                    	<p class="submit" style="padding:0 "><input type="submit" value="<?php 
    _e('Add', "wp-download_monitor");
    ?>
" name="add_cat" id="add_cat" /></p>
                    	</div></td>
                </tr>
                <tr valign="middle">
                    <th scope="row"><strong><?php 
    _e('Tags', "wp-download_monitor");
    ?>
: </strong></th>
                    <td>
                        <input type="text" style="width:360px;" class="cleardefault" value="<?php 
    if (isset($tags)) {
        echo $tags;
    }
    ?>
" name="tags" id="dltags" /><br /><span class="setting-description"><?php 
    _e('Separate tags with commas.', "wp-download_monitor");
    ?>
 <a class="browsetags" style="display:none" href="#"><?php 
    _e('Toggle Tags', "wp-download_monitor");
    ?>
</a></span>
                    	<div id="tag-list" style="display:none;">
                    		<?php 
    $tags = $download_taxonomies->tags;
    echo '<ul>';
    if (!empty($tags)) {
        foreach ($tags as $tag) {
            echo '<li><a href="#" class="ins-tag">' . $tag->name . '</a></li>';
        }
    } else {
        echo '<li>' . __('No Tags Found', "wp-download_monitor") . '</li>';
    }
    echo '</ul>';
    ?>
                    	</div>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><strong><?php 
    _e('Member only file?', "wp-download_monitor");
    ?>
</strong></th>
                    <td><input type="checkbox" name="memberonly" style="vertical-align:top" <?php 
    if (isset($members) && $members == 1) {
        echo "checked='checked'";
    }
    ?>
 /> <span class="setting-description"><?php 
    _e('If chosen, only logged in users will be able to access the file via a download link. You can also add a custom field called min-level or req-role to set the minimum user level needed to download the file.', "wp-download_monitor");
    ?>
</span></td>
                </tr>
                <tr valign="top">
                    <th scope="row"><strong><?php 
    _e('Force Download?', "wp-download_monitor");
    ?>
</strong></th>
                    <td><input type="checkbox" name="forcedownload" style="vertical-align:top" <?php 
    if (isset($forcedownload) && $forcedownload == 1) {
        echo "checked='checked'";
    }
    ?>
 /> <span class="setting-description"><?php 
    _e('If chosen, Download Monitor will attempt to force the download rather than redirect. This setting is not compatible with all servers (so test it), and in most cases will only work on files hosted on the local server.', "wp-download_monitor");
    ?>
</span></td>
                </tr>
            </table>
            <h3><?php 
    _e('Custom fields', "wp-download_monitor");
    ?>
</h3>
            <p><?php 
    _e('Custom fields can be used to add extra metadata to a download. Leave blank to add none. Name should be lower case with no spaces (changed automatically, e.g. <code>Some Name</code> will become <code>some-name</code>.', "wp-download_monitor");
    ?>
</p>
			<table style="width:80%">
				<thead>
					<tr>
						<th class="left"><?php 
    _e('Name', "wp-download_monitor");
    ?>
</th>
						<th><?php 
    _e('Value', "wp-download_monitor");
    ?>
</th>
					</tr>
				</thead>
				<tbody id="customfield_list">
					<?php 
    $index = 1;
    if ($_POST) {
        if ($_POST['meta']) {
            foreach ($_POST['meta'] as $meta) {
                if (!$meta['remove']) {
                    if (trim($meta['key'])) {
                        echo '<tr class="alternate">
										<td class="left" style="vertical-align:top;">
											<label class="hidden" for="meta[' . $index . '][key]">Key</label><input name="meta[' . $index . '][key]" id="meta[' . $index . '][key]" tabindex="6" size="20" value="' . strtolower(str_replace(' ', '-', trim($meta['key']))) . '" type="text" style="width:95%">
											<input type="submit" name="meta[' . $index . '][remove]" class="button" value="' . __('remove', "wp-download_monitor") . '" />
										</td>
										<td style="vertical-align:top;"><label class="hidden" for="meta[' . $index . '][value]">Value</label><textarea name="meta[' . $index . '][value]" id="meta[' . $index . '][value]" tabindex="6" rows="2" cols="30" style="width:95%">' . $meta['value'] . '</textarea></td>
									</tr>';
                    }
                }
                $index++;
            }
        }
        if ($_POST['addmeta']) {
            echo '<tr class="alternate">
									<td class="left" style="vertical-align:top;">
										<label class="hidden" for="meta[' . $index . '][key]">Key</label><input name="meta[' . $index . '][key]" id="meta[' . $index . '][key]" tabindex="6" size="20" value="" type="text" style="width:95%" /><input type="submit" name="meta[' . $index . '][remove]" class="button" value="' . __('remove', "wp-download_monitor") . '" />
									</td>
									<td style="vertical-align:top;"><label class="hidden" for="meta[' . $index . '][value]">Value</label><textarea name="meta[' . $index . '][value]" id="meta[' . $index . '][value]" tabindex="6" rows="2" cols="30" style="width:95%"></textarea></td>
							</tr>';
        }
    }
    ?>
					<tr id="addmetarow">
						<td colspan="2" class="submit"><input id="addmetasub" name="addmeta" value="<?php 
    _e('Add Custom Field', "wp-download_monitor");
    ?>
" type="submit" style="margin-bottom: 6px !important;" /><br/><a class="seemetafields" style="display:none;" href="#"><?php 
    _e('Toggle Existing Custom Fields', "wp-download_monitor");
    ?>
</a>
						<div id="meta_fields" style="display:none">
							<?php 
    $fields = $wpdb->get_results("SELECT DISTINCT meta_name FROM {$wp_dlm_db_meta} WHERE meta_name NOT IN ('tags', 'thumbnail', 'force') ORDER BY meta_name;");
    if ($fields) {
        echo '<ul>';
        foreach ($fields as $field) {
            echo '<li><strong>' . $field->meta_name . '</strong> <button type="button" class="addmeta_rel" rel="' . $field->meta_name . '">' . _e('Add', "wp-download_monitor") . '</button></li>';
        }
        echo '</ul>';
    } else {
        echo '<p>' . __('None found.', "wp-download_monitor") . '</p>';
    }
    ?>
						</div></td>
					</tr>
				</tbody>
			</table>
			<hr />

			<p class="submit"><input type="submit" class="btn button-primary" name="save" style="padding:5px 30px 5px 30px;" value="<?php 
    _e('Scan &amp; Add', "wp-download_monitor");
    ?>
" /></p>
			<input type="hidden" name="postDate" value="<?php 
    echo date_i18n(__('Y-m-d H:i:s', "wp-download_monitor"));
    ?>
" />

			<?php 
    global $userdata;
    get_currentuserinfo();
    echo '<input type="hidden" name="user" value="' . $userdata->user_login . '" />';
    ?>
		</form>
	</div>
	<?php 
    echo '</div>';
}
Esempio n. 5
0
function wp_dlm_admin()
{
    //set globals
    global $wpdb, $wp_dlm_root, $wp_dlm_db, $wp_dlm_db_taxonomies, $wp_dlm_db_formats, $wp_dlm_db_stats, $wp_dlm_db_meta, $wp_dlm_db_log, $wp_dlm_db_relationships, $download_taxonomies;
    // turn off magic quotes
    wp_dlm_magic();
    echo '<div class="download_monitor">';
    // DEFINE QUERIES
    // select all downloads
    if (empty($_POST['dlhits'])) {
        $_POST['dlhits'] = 0;
    }
    // select a downloads
    if (isset($_GET['id'])) {
        $query_select_1 = sprintf("SELECT * FROM %s WHERE id=%s;", $wpdb->escape($wp_dlm_db), $wpdb->escape($_GET['id']));
    }
    if (isset($_GET['action'])) {
        $action = $_GET['action'];
    } else {
        $action = '';
    }
    if (!empty($action)) {
        switch ($action) {
            case "delete":
                wp_dlm_clear_cached_stuff();
                $d = $wpdb->get_row($query_select_1);
                global $wp_db_version;
                $adminpage = 'admin.php';
                ?>
						<div class="wrap">
							<div id="downloadadminicon" class="icon32"><br/></div>
							<h2><?php 
                _e('Sure?', "wp-download_monitor");
                ?>
</h2>
							<p><?php 
                _e('Are you sure you want to delete', "wp-download_monitor");
                ?>
 "<?php 
                echo $d->title;
                ?>
"<?php 
                _e('? (If originally uploaded by this plugin, this will also remove the file from the server)', "wp-download_monitor");
                ?>
 <a href="<?php 
                echo get_bloginfo('wpurl');
                ?>
/wp-admin/<?php 
                echo $adminpage;
                ?>
?page=download-monitor/wp-download_monitor.php&amp;action=confirmed&amp;id=<?php 
                echo $_GET['id'];
                ?>
&amp;sort=<?php 
                echo $_GET['sort'];
                ?>
&amp;p=<?php 
                echo $_GET['p'];
                ?>
"><?php 
                _e('[yes]', "wp-download_monitor");
                ?>
</a> <a href="<?php 
                echo get_bloginfo('wpurl');
                ?>
/wp-admin/<?php 
                echo $adminpage;
                ?>
?page=download-monitor/wp-download_monitor.php&amp;action=cancelled&amp;sort=<?php 
                echo $_GET['sort'];
                ?>
&amp;p=<?php 
                echo $_GET['p'];
                ?>
"><?php 
                _e('[no]', "wp-download_monitor");
                ?>
</a>
						</div>
					<?php 
                break;
            case "edit":
                wp_dlm_clear_cached_stuff();
                if (isset($_POST['sub'])) {
                    $title = $_POST['title'];
                    $dlversion = $_POST['dlversion'];
                    $dlhits = $_POST['dlhits'];
                    $dlfilename = $_POST['dlfilename'];
                    $members = isset($_POST['memberonly']) ? 1 : 0;
                    $removefile = isset($_POST['removefile']) ? 1 : 0;
                    $mirrors = $_POST['mirrors'];
                    $file_description = $_POST['file_description'];
                    if (isset($_POST['meta'])) {
                        $custom_fields = $_POST['meta'];
                    } else {
                        $custom_fields = '';
                    }
                    if (isset($_POST['tags'])) {
                        $download_tags = $_POST['tags'];
                    } else {
                        $download_tags = '';
                    }
                    $thumbnail = $_POST['thumbnail'];
                    /* Get Post Date Fields */
                    $postDate = $_POST['postDate'];
                    $mm = $_POST['mm'];
                    $jj = $_POST['jj'];
                    $aa = $_POST['aa'];
                    $hh = $_POST['hh'];
                    $mn = $_POST['mn'];
                    if ($mm > 0 && $mm < 13 && ($jj > 0 && $jj < 32) && ($aa > 1990 && $jj < 2100) && (isset($hh) && $hh < 25) && (isset($mn) && $mn < 61)) {
                        // Good to go
                        $newPostDate = "{$aa}-{$mm}-{$jj} {$hh}-{$mn}-00";
                    } else {
                        // Bad Date
                        $newPostDate = $postDate;
                    }
                    /* End Date Fields */
                    if ($_POST['save']) {
                        //save and validate
                        if (empty($_POST['title'])) {
                            $errors .= '<div class="error">' . __('Required field: <strong>Title</strong> omitted', "wp-download_monitor") . '</div>';
                        }
                        if (empty($_POST['dlfilename']) && empty($_FILES['upload']['tmp_name'])) {
                            $errors .= '<div class="error">' . __('Required field: <strong>THE FILE</strong> omitted', "wp-download_monitor") . '</div>';
                        }
                        if (empty($_POST['dlhits'])) {
                            $_POST['dlhits'] = 0;
                        }
                        if (!is_numeric($_POST['dlhits'])) {
                            $errors .= '<div class="error">' . __('Invalid <strong>hits</strong> entered', "wp-download_monitor") . '</div>';
                        }
                        $members = isset($_POST['memberonly']) ? 1 : 0;
                        $removefile = isset($_POST['removefile']) ? 1 : 0;
                        $forcedownload = isset($_POST['forcedownload']) ? 1 : 0;
                        if (empty($errors)) {
                            // Remove Old Taxonomies
                            $wpdb->query("DELETE FROM {$wp_dlm_db_relationships} WHERE download_id = " . $wpdb->escape($_GET['id']) . "");
                            // Categories
                            $cats = $download_taxonomies->categories;
                            $values = array();
                            if (!empty($cats)) {
                                foreach ($cats as $c) {
                                    $this_cat_value = isset($_POST['category_' . $c->id]) ? 1 : 0;
                                    if ($this_cat_value) {
                                        $values[] = '("' . $wpdb->escape($c->id) . '", ' . $wpdb->escape($_GET['id']) . ')';
                                    }
                                }
                            }
                            if (sizeof($values) > 0) {
                                $wpdb->query("INSERT INTO {$wp_dlm_db_relationships} (taxonomy_id, download_id) VALUES " . implode(',', $values) . "");
                            }
                            // Tags
                            $values = array();
                            if ($download_tags) {
                                // Break 'em up
                                $thetags = explode(',', $download_tags);
                                $thetags = array_map('trim', $thetags);
                                $thetags = array_map('strtolower', $thetags);
                                if (sizeof($thetags) > 0) {
                                    foreach ($thetags as $tag) {
                                        if ($tag) {
                                            // Exists?
                                            $tag_id = $wpdb->get_var("SELECT id FROM {$wp_dlm_db_taxonomies} WHERE taxonomy='tag' AND name='" . $wpdb->escape($tag) . "';");
                                            // Insert
                                            if (!$tag_id) {
                                                $wpdb->query("INSERT INTO {$wp_dlm_db_taxonomies} (name, parent, taxonomy) VALUES ('" . $wpdb->escape($tag) . "', 0, 'tag');");
                                                $tag_id = $wpdb->insert_id;
                                            }
                                            if ($tag_id) {
                                                $values[] = '("' . $wpdb->escape($tag_id) . '", ' . $wpdb->escape($_GET['id']) . ')';
                                            }
                                        }
                                    }
                                }
                            }
                            if (sizeof($values) > 0) {
                                $wpdb->query("INSERT INTO {$wp_dlm_db_relationships} (taxonomy_id, download_id) VALUES " . implode(',', $values) . "");
                            }
                            // Handle File Uploads
                            $time = current_time('mysql');
                            $overrides = array('test_form' => false);
                            // Remove old file
                            if ($removefile) {
                                $d = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wp_dlm_db} WHERE id=%s;", $_GET['id']));
                                $file = $d->filename;
                                $dirs = wp_upload_dir();
                                $uploadpath = trailingslashit($dirs['baseurl']);
                                $absuploadpath = trailingslashit($dirs['basedir']);
                                if ($uploadpath && (strstr($d->filename, $uploadpath) || strstr($d->filename, $absuploadpath))) {
                                    $file = str_replace($uploadpath, "", $d->filename);
                                    if (is_file($absuploadpath . $file)) {
                                        chmod($absuploadpath . $file, 0777);
                                        unlink($absuploadpath . $file);
                                    }
                                }
                            }
                            add_filter('upload_dir', 'dlm_upload_dir');
                            $file = wp_handle_upload($_FILES['upload'], $overrides, $time);
                            remove_filter('upload_dir', 'dlm_upload_dir');
                            if (!isset($file['error'])) {
                                $dlfilename = $file['url'];
                            } else {
                                $errors = '<div class="error">' . $file['error'] . '</div>';
                            }
                            if (!empty($errors)) {
                                // No File Was uploaded
                                if (empty($_POST['dlfilename'])) {
                                    $errors = __('<div class="error">No file selected</div>', "wp-download_monitor");
                                } else {
                                    $errors = '';
                                }
                            }
                            //attempt to upload thumbnail
                            if (empty($errors)) {
                                add_filter('upload_dir', 'dlm_upload_thumbnail_dir');
                                $file = wp_handle_upload($_FILES['thumbnail_upload'], $overrides, $time);
                                remove_filter('upload_dir', 'dlm_upload_thumbnail_dir');
                                if (!isset($file['error'])) {
                                    $thumbnail = $file['url'];
                                }
                            }
                            //save to db
                            if (empty($errors)) {
                                $query_update_file = sprintf("UPDATE %s SET title='%s', dlversion='%s', hits='%s', filename='%s', postDate='%s', user='******',members='%s',mirrors='%s', file_description='%s' WHERE id=%s;", $wpdb->escape($wp_dlm_db), $wpdb->escape($title), mysql_real_escape_string($dlversion), mysql_real_escape_string($dlhits), $wpdb->escape($dlfilename), $wpdb->escape($newPostDate), $wpdb->escape($_POST['user']), $wpdb->escape($members), $wpdb->escape(trim($mirrors)), $wpdb->escape(trim($file_description)), $wpdb->escape($_GET['id']));
                                $d = $wpdb->get_row($query_update_file);
                                $show = true;
                                // Process and save meta/custom fields
                                $wpdb->query("DELETE FROM {$wp_dlm_db_meta} WHERE download_id = " . $_GET['id'] . "");
                                // Thumbnail
                                if ($thumbnail) {
                                    $wpdb->query("INSERT INTO {$wp_dlm_db_meta} (meta_name, meta_value, download_id) VALUES ('thumbnail', '" . $wpdb->escape($thumbnail) . "', '" . $wpdb->escape($_GET['id']) . "')");
                                }
                                // Force Download
                                $wpdb->query("INSERT INTO {$wp_dlm_db_meta} (meta_name, meta_value, download_id) VALUES ('force', '" . $wpdb->escape($forcedownload) . "', '" . $wpdb->escape($_GET['id']) . "')");
                                // Custom Fields
                                $index = 1;
                                $values = array();
                                if (isset($_POST['meta'])) {
                                    foreach ($_POST['meta'] as $meta) {
                                        if (trim($meta['key'])) {
                                            $values[] = '("' . $wpdb->escape(strtolower(str_replace(' ', '-', trim(stripslashes($meta['key']))))) . '", "' . $wpdb->escape($meta['value']) . '", ' . $_GET['id'] . ')';
                                            $index++;
                                        }
                                    }
                                }
                                if (sizeof($values) > 0) {
                                    $wpdb->query("INSERT INTO {$wp_dlm_db_meta} (meta_name, meta_value, download_id) VALUES " . implode(',', $values) . "");
                                }
                                echo '<div id="message" class="updated fade"><p><strong>' . __('Download edited Successfully', "wp-download_monitor") . '</strong></p></div>';
                            }
                        }
                        if (!empty($errors)) {
                            echo $errors;
                        }
                    }
                } else {
                    //load values
                    $d = $wpdb->get_row($query_select_1);
                    $title = $d->title;
                    $dlversion = $d->dlversion;
                    $dlhits = $d->hits;
                    $dlfilename = $d->filename;
                    if (empty($dlhits)) {
                        $dlhits = 0;
                    }
                    $members = $d->members;
                    global $categories;
                    $categories = array();
                    $categories_taxonomy = get_download_taxonomy($d->id);
                    if (sizeof($categories_taxonomy['ids']) > 0) {
                        $categories = $categories_taxonomy['ids'];
                    }
                    global $download_tags;
                    $download_tags = '';
                    $tags_taxonomy = get_download_taxonomy($d->id, 'tag');
                    if (sizeof($tags_taxonomy['names']) > 0) {
                        $download_tags = implode(', ', $tags_taxonomy['names']);
                    }
                    $mirrors = $d->mirrors;
                    $file_description = $d->file_description;
                    $fields = $wpdb->get_results("SELECT * FROM {$wp_dlm_db_meta} WHERE download_id= " . $d->id . "");
                    $index = 1;
                    $custom_fields = array();
                    $thumbnail = '';
                    if ($fields) {
                        foreach ($fields as $meta) {
                            if ($meta->meta_name == 'thumbnail') {
                                $thumbnail = stripslashes($meta->meta_value);
                            } elseif ($meta->meta_name == 'force') {
                                $forcedownload = stripslashes($meta->meta_value);
                            } elseif ($meta->meta_name == 'filesize') {
                                // Nothing
                            } else {
                                $custom_fields[$index]['key'] = $meta->meta_name;
                                $custom_fields[$index]['value'] = stripslashes($meta->meta_value);
                                $custom_fields[$index]['remove'] = 0;
                                $index++;
                            }
                        }
                    }
                    $postDate = date_i18n('Y-m-d H:i:s', strtotime($d->postDate));
                    $newPostDate = $d->postDate;
                }
                if (!isset($show)) {
                    $show = false;
                }
                if ($show == false) {
                    $max_upload_size_text = '';
                    if (function_exists('ini_get')) {
                        $max_upload_size = min(dlm_let_to_num(ini_get('post_max_size')), dlm_let_to_num(ini_get('upload_max_filesize')));
                        $max_upload_size_text = __(' (defined in php.ini)', "wp-download_monitor");
                    }
                    if (!$max_upload_size || $max_upload_size == 0) {
                        $max_upload_size = 8388608;
                        $max_upload_size_text = '';
                    }
                    ?>
								<div class="wrap">
								<div id="downloadadminicon" class="icon32"><br/></div>
								<h2><?php 
                    _e('Edit Download Information', "wp-download_monitor");
                    ?>
</h2>
								<form enctype="multipart/form-data" action="?page=download-monitor/wp-download_monitor.php&amp;action=edit&amp;id=<?php 
                    echo $_GET['id'];
                    ?>
" method="post" id="wp_dlm_add" name="edit_download" class="form-table" cellpadding="0" cellspacing="0"> 
									<input type="hidden" name="MAX_FILE_SIZE" value="<?php 
                    echo $max_upload_size;
                    ?>
" />

									<table class="optiontable niceblue">                     
										<tr valign="top">
											<th scope="row"><strong><?php 
                    _e('Title (required)', "wp-download_monitor");
                    ?>
: </strong></th> 
											<td>
												<input type="text" style="width:360px;" class="cleardefault" value="<?php 
                    echo $title;
                    ?>
" name="title" id="dlmtitle" maxlength="200" />												
											</td> 
										</tr>
										<tr valign="top">
											<th scope="row"><strong><?php 
                    _e('Version', "wp-download_monitor");
                    ?>
: </strong></th> 
											<td>
												<input type="text" style="width:360px;" class="cleardefault" value="<?php 
                    echo $dlversion;
                    ?>
" name="dlversion" id="dlversion" maxlength="200" />
											</td> 
										</tr>
										<tr valign="middle">
                                            <th scope="row"><strong><?php 
                    _e('Description', "wp-download_monitor");
                    ?>
: </strong></th> 
                                            <td><textarea name="file_description" style="width:360px;" cols="50" rows="6"><?php 
                    echo $file_description;
                    ?>
</textarea></td> 
                                        </tr>
										<tr valign="top">
											<th scope="row"><strong><?php 
                    _e('Change hit count', "wp-download_monitor");
                    ?>
: </strong></th> 
											<td>
												<input type="text" style="width:100px;" class="cleardefault" value="<?php 
                    echo $dlhits;
                    ?>
" name="dlhits" id="dlhits" maxlength="50" />
											</td> 
										</tr>
										<tr valign="top">
											<th scope="row"><strong><?php 
                    _e('Change post date', "wp-download_monitor");
                    ?>
: </strong></th> 
											<td>
												<?php 
                    dlm_touch_time($newPostDate);
                    ?>
												<br/><span class="setting-description"><?php 
                    _e('Change the post date of the download. Was set to:', "wp-download_monitor");
                    ?>
 <?php 
                    echo date_i18n(__('M jS Y @ H:i', "wp-download_monitor"), strtotime($postDate));
                    ?>
</span>
											</td> 
										</tr>
										<tr valign="top">
												<th scope="row"><strong><?php 
                    _e('The File', "wp-download_monitor");
                    ?>
 <?php 
                    _e('(required)', "wp-download_monitor");
                    ?>
</strong></th> 
												<td>
													<div style="width:820px;">
														<div style="float:left; width:362px;">
															<h3 style="margin:0 0 0.5em"><?php 
                    _e('Upload New File', "wp-download_monitor");
                    ?>
</h3>
															<input type="file" name="upload" style="width:354px; margin:1px;" /><br />
															<input type="checkbox" name="removefile" id="removefile" style="vertical-align:middle" <?php 
                    if (isset($removefile) && $removefile == 1) {
                        echo "checked='checked'";
                    }
                    ?>
 /> <label for="removefile"><?php 
                    _e('Remove old file?', "wp-download_monitor");
                    ?>
</label>
															<span class="setting-description"><?php 
                    _e('Max. filesize', "wp-download_monitor");
                    echo $max_upload_size_text;
                    ?>
 = <?php 
                    echo $max_upload_size;
                    ?>
 <?php 
                    _e('bytes', "wp-download_monitor");
                    ?>
. <?php 
                    _e('If a file with the same name already exists in the upload directly, this file will be renamed.', "wp-download_monitor");
                    ?>
</span>															
														</div>
														<div style="float:left; text-align:center; width: 75px; margin: 0 8px; display:inline;">
															<p style="font-weight:bold; font-size:16px; color: #999; line-height: 48px; ">&larr;<?php 
                    _e('OR', "wp-download_monitor");
                    ?>
&rarr;</p>
														</div>
														<div style="float:left; width:362px;">
															<h3 style="margin:0 0 0.5em"><?php 
                    _e('Edit File URL', "wp-download_monitor");
                    ?>
</h3>
															<input type="text" style="width:360px;" class="cleardefault" value="<?php 
                    echo $dlfilename;
                    ?>
" name="dlfilename" id="dlfilename" /><br />
															<?php 
                    if (get_option('wp_dlm_enable_file_browser') !== 'no') {
                        ?>
															<a class="browsefiles" style="display:none" href="#"><?php 
                        _e('Toggle File Browser', "wp-download_monitor");
                        ?>
</a>
						                        			<div id="file_browser"></div>
						                        			<?php 
                    }
                    ?>
														</div>
														<div style="clear:both"></div>
													</div>
												</td>
						                </tr> 
										<tr valign="top">												
											<th scope="row"><strong><?php 
                    _e('Download Mirrors', "wp-download_monitor");
                    ?>
</strong></th> 
											<td><textarea name="mirrors" cols="50" rows="2"><?php 
                    echo $mirrors;
                    ?>
</textarea><br /><span class="setting-description"><?php 
                    _e('Optionally list the url\'s of any mirrors here (1 per line). Download monitor will randomly pick one of these mirrors when serving the download.', "wp-download_monitor");
                    ?>
</span></td>
										</tr>											
						                <tr valign="top">												
						                    <th scope="row"><strong><?php 
                    _e('Categories', "wp-download_monitor");
                    ?>
</strong></th> 
						                    <td><div id="categorydiv"><ul class="categorychecklist" style="background: #fff; border: 1px solid #DFDFDF; height: 200px; margin: 4px 1px; overflow: auto; padding: 3px 6px; width: 346px;">
						                    		<?php 
                    $cats = $download_taxonomies->get_parent_cats();
                    if (!empty($cats)) {
                        foreach ($cats as $c) {
                            echo '<li><label for="category_' . $c->id . '"><input type="checkbox" name="category_' . $c->id . '" id="category_' . $c->id . '" ';
                            if (isset($_POST['category_' . $c->id]) || is_array($categories) && in_array($c->id, $categories)) {
                                echo 'checked="checked"';
                            }
                            echo ' /> ' . $c->id . ' - ' . $c->name . '</label>';
                            // Do Children
                            if (!function_exists('cat_form_output_children')) {
                                function cat_form_output_children($child)
                                {
                                    global $download_taxonomies, $categories;
                                    if ($child) {
                                        echo '<li><label for="category_' . $child->id . '"><input type="checkbox" name="category_' . $child->id . '" id="category_' . $child->id . '" ';
                                        if (isset($_POST['category_' . $child->id]) || is_array($categories) && in_array($child->id, $categories)) {
                                            echo 'checked="checked"';
                                        }
                                        echo ' /> ' . $child->id . ' - ' . $child->name . '</label>';
                                        echo '<ul class="children">';
                                        $download_taxonomies->do_something_to_cat_children($child->id, 'cat_form_output_children', 'cat_form_output_no_children');
                                        echo '</ul>';
                                        echo '</li>';
                                    }
                                }
                                function cat_form_output_no_children()
                                {
                                    echo '<li></li>';
                                }
                            }
                            echo '<ul class="children">';
                            $download_taxonomies->do_something_to_cat_children($c->id, 'cat_form_output_children', 'cat_form_output_no_children');
                            echo '</ul>';
                            echo '</li>';
                        }
                    }
                    ?>
						                    	</ul></div><a href="#" class="add-new-cat-ajax" style="display:none"><?php 
                    _e('+ Add New Category', "wp-download_monitor");
                    ?>
</a><div id="add_cat_form" style="display:none">
								                    <table class="niceblue small-table" cellpadding="0" cellspacing="0" style="width:362px;">
								                        <tr>
								                            <th scope="col"><?php 
                    _e('Name', "wp-download_monitor");
                    ?>
:</th>
								                            <td><input type="text" name="cat_name" style="width: 220px" /></td>
								                        </tr>
								                        <tr>
								                            <th scope="col"><?php 
                    _e('Parent', "wp-download_monitor");
                    ?>
:</th>
								                            <td><select name="cat_parent" style="width: 220px">
								                            	<option value=""><?php 
                    _e('None', "wp-download_monitor");
                    ?>
</option>
								                                <?php 
                    if (!empty($cats)) {
                        foreach ($cats as $c) {
                            echo '<option value="' . $c->id . '">' . $c->id . ' - ' . $c->name . '</option>';
                            echo get_option_children_cats($c->id, "{$c->name} &mdash; ", 0);
                        }
                    }
                    ?>
								                            </select></td>
								                        </tr>
								                    </table>
							                    	<p class="submit" style="padding:0 "><input type="submit" value="<?php 
                    _e('Add', "wp-download_monitor");
                    ?>
" name="add_cat" id="add_cat" /></p>
						                    	</div></td>
						                </tr>
						                <tr valign="middle">
						                    <th scope="row"><strong><?php 
                    _e('Tags', "wp-download_monitor");
                    ?>
: </strong></th> 
						                    <td>
						                        <input type="text" style="width:360px;" class="cleardefault" value="<?php 
                    echo $download_tags;
                    ?>
" name="tags" id="dltags" /><br /><span class="setting-description"><?php 
                    _e('Separate tags with commas.', "wp-download_monitor");
                    ?>
 <a class="browsetags" style="display:none" href="#"><?php 
                    _e('Toggle Tags', "wp-download_monitor");
                    ?>
</a></span>
						                    	<div id="tag-list" style="display:none;">
						                    		<?php 
                    $tags = $download_taxonomies->tags;
                    echo '<ul>';
                    if (!empty($tags)) {
                        foreach ($tags as $tag) {
                            echo '<li><a href="#" class="ins-tag">' . $tag->name . '</a></li>';
                        }
                    } else {
                        echo '<li>' . __('No Tags Found', "wp-download_monitor") . '</li>';
                    }
                    echo '</ul>';
                    ?>
						                    	</div>
						                    </td> 
						                </tr>
						                <tr valign="middle">
						                    <th scope="row"><strong><?php 
                    _e('Thumbnail', "wp-download_monitor");
                    ?>
: </strong></th> 
											<td>
												<div style="width:820px;">
													<div style="float:left; width:362px;">
														<h3 style="margin:0 0 0.5em"><?php 
                    _e('Upload new thumbnail', "wp-download_monitor");
                    ?>
</h3>
														<input type="file" name="thumbnail_upload" style="width:354px; margin:1px;" /><br /><span class="setting-description"><?php 
                    _e('This will be displayed on the download page or with {thumbnail} in a custom format (a placeholder will be shown if not set).', "wp-download_monitor");
                    ?>
</span>
													</div>
													<div style="float:left; text-align:center; width: 75px; margin: 0 8px; display:inline;">
														<p style="font-weight:bold; font-size:16px; color: #999; line-height: 48px; ">&larr;<?php 
                    _e('OR', "wp-download_monitor");
                    ?>
&rarr;</p>
													</div>
													<div style="float:left; width:362px;">
														<h3 style="margin:0 0 0.5em"><?php 
                    _e('Edit thumbnail URL', "wp-download_monitor");
                    ?>
</h3>
														<input type="text" style="width:360px;" class="cleardefault" value="<?php 
                    echo $thumbnail;
                    ?>
" name="thumbnail" id="thumbnail" /><br />
														<?php 
                    if (get_option('wp_dlm_enable_file_browser') !== 'no') {
                        ?>
														<a class="browsefilesthumbnail" style="display:none" href="#"><?php 
                        _e('Toggle File Browser', "wp-download_monitor");
                        ?>
</a>
						                    			<div id="file_browser_thumbnail"></div>
						                    			<?php 
                    }
                    ?>
													</div>
													<div style="clear:both;"></div>
												</div>
											</td>
						                </tr>
						                <tr valign="top">												
						                    <th scope="row"><strong><?php 
                    _e('Member only file?', "wp-download_monitor");
                    ?>
</strong></th> 
						                    <td><input type="checkbox" name="memberonly" style="vertical-align:top" <?php 
                    if ($members == 1) {
                        echo "checked='checked'";
                    }
                    ?>
 /> <span class="setting-description"><?php 
                    _e('If chosen, only logged in users will be able to access the file via a download link. You can also add a custom field called min-level or req-role to set the minimum user level needed to download the file.', "wp-download_monitor");
                    ?>
</span></td>
						                </tr>
						                <tr valign="top">												
						                    <th scope="row"><strong><?php 
                    _e('Force Download?', "wp-download_monitor");
                    ?>
</strong></th> 
						                    <td><input type="checkbox" name="forcedownload" style="vertical-align:top" <?php 
                    if ($forcedownload == 1) {
                        echo "checked='checked'";
                    }
                    ?>
 /> <span class="setting-description"><?php 
                    _e('If chosen, Download Monitor will attempt to force the download rather than redirect. This setting is not compatible with all servers (so test it), and in most cases will only work on files hosted on the local server.', "wp-download_monitor");
                    ?>
</span></td>
						                </tr>
									</table>
									<input type="hidden" name="sort" value="<?php 
                    echo $_REQUEST['sort'];
                    ?>
" />
									<input type="hidden" name="p" value="<?php 
                    echo $_REQUEST['p'];
                    ?>
" />
									<input type="hidden" name="sub" value="1" />
									<input type="hidden" name="postDate" value="<?php 
                    echo $postDate;
                    ?>
" />
									<?php 
                    global $userdata;
                    get_currentuserinfo();
                    echo '<input type="hidden" name="user" value="' . $userdata->user_login . '" />';
                    ?>
									<hr/>
						            <h3><?php 
                    _e('Custom fields', "wp-download_monitor");
                    ?>
</h3>
						            <p><?php 
                    _e('Custom fields can be used to add extra metadata to a download. Leave blank to add none. Name should be lower case with no spaces (changed automatically, e.g. <code>Some Name</code> will become <code>some-name</code>.', "wp-download_monitor");
                    ?>
</p>
									<table style="width:80%">
										<thead>
											<tr>
												<th class="left"><?php 
                    _e('Name', "wp-download_monitor");
                    ?>
</th>
												<th><?php 
                    _e('Value', "wp-download_monitor");
                    ?>
</th>
											</tr>			
										</thead>
										<tbody id="customfield_list">
											<?php 
                    $index = 1;
                    if ($custom_fields) {
                        foreach ($custom_fields as $meta) {
                            if (!$meta['remove']) {
                                if (trim($meta['key'])) {
                                    echo '<tr class="alternate">
															<td class="left" style="vertical-align:top;">
																<label class="hidden" for="meta[' . $index . '][key]">Key</label><input name="meta[' . $index . '][key]" id="meta[' . $index . '][key]" tabindex="6" size="20" value="' . strtolower(str_replace(' ', '-', trim($meta['key']))) . '" type="text" style="width:95%">
																<input type="submit" name="meta[' . $index . '][remove]" class="button" value="' . __('remove', "wp-download_monitor") . '" />
															</td>
															<td style="vertical-align:top;"><label class="hidden" for="meta[' . $index . '][value]">Value</label><textarea name="meta[' . $index . '][value]" id="meta[' . $index . '][value]" tabindex="6" rows="2" cols="30" style="width:95%">' . $meta['value'] . '</textarea></td>
														</tr>';
                                }
                            }
                            $index++;
                        }
                    }
                    if (isset($_POST['addmeta'])) {
                        echo '<tr class="alternate">
														<td class="left" style="vertical-align:top;">
															<label class="hidden" for="meta[' . $index . '][key]">Key</label><input name="meta[' . $index . '][key]" id="meta[' . $index . '][key]" tabindex="6" size="20" value="" type="text" style="width:95%">
															<input type="submit" name="meta[' . $index . '][remove]" class="button" value="' . __('remove', "wp-download_monitor") . '" />
														</td>
														<td style="vertical-align:top;"><label class="hidden" for="meta[' . $index . '][value]">Value</label><textarea name="meta[' . $index . '][value]" id="meta[' . $index . '][value]" tabindex="6" rows="2" cols="30" style="width:95%"></textarea></td>
												</tr>';
                    }
                    ?>
											<tr id="addmetarow">
												<td colspan="2" class="submit"><input id="addmetasub" name="addmeta" value="<?php 
                    _e('Add Custom Field', "wp-download_monitor");
                    ?>
" type="submit" style="margin-bottom: 6px !important;" /><br/><a class="seemetafields" style="display:none;" href="#"><?php 
                    _e('Toggle Existing Custom Fields', "wp-download_monitor");
                    ?>
</a>
												<div id="meta_fields" style="display:none">
													<?php 
                    $fields = $wpdb->get_results("SELECT DISTINCT meta_name FROM {$wp_dlm_db_meta} WHERE meta_name NOT IN ('tags', 'thumbnail', 'force') ORDER BY meta_name;");
                    if ($fields) {
                        echo '<ul>';
                        foreach ($fields as $field) {
                            echo '<li><strong>' . $field->meta_name . '</strong> <button type="button" class="addmeta_rel" rel="' . $field->meta_name . '">Add</button></li>';
                        }
                        echo '</ul>';
                    } else {
                        echo '<p>' . __('None found.', "wp-download_monitor") . '</p>';
                    }
                    ?>
												</div></td>
											</tr>
										</tbody>
									</table>
									<hr />									
									<p class="submit"><input type="submit" class="btn button-primary" name="save" style="padding:5px 30px 5px 30px;" value="<?php 
                    _e('Save Changes', "wp-download_monitor");
                    ?>
" /></p>
								</form>
								</div>													
							<?php 
                }
                break;
            case "confirmed":
                wp_dlm_clear_cached_stuff();
                //load values
                $d = $wpdb->get_row($query_select_1);
                $file = $d->filename;
                $dirs = wp_upload_dir();
                $uploadpath = trailingslashit($dirs['baseurl']);
                $absuploadpath = trailingslashit($dirs['basedir']);
                if ($uploadpath && (strstr($d->filename, $uploadpath) || strstr($d->filename, $absuploadpath))) {
                    $file = str_replace($uploadpath, "", $d->filename);
                    if (is_file($absuploadpath . $file)) {
                        chmod($absuploadpath . $file, 0777);
                        unlink($absuploadpath . $file);
                    }
                }
                $query_delete = "DELETE FROM {$wp_dlm_db} WHERE id=" . $wpdb->escape($_GET['id']) . ";";
                $wpdb->query($query_delete);
                $query_delete = "DELETE FROM {$wp_dlm_db_stats} WHERE download_id=" . $wpdb->escape($_GET['id']) . ";";
                $wpdb->query($query_delete);
                $query_delete = "DELETE FROM {$wp_dlm_db_log} WHERE download_id=" . $wpdb->escape($_GET['id']) . ";";
                $wpdb->query($query_delete);
                $query_delete = "DELETE FROM {$wp_dlm_db_meta} WHERE download_id=" . $wpdb->escape($_GET['id']) . ";";
                $wpdb->query($query_delete);
                $query_delete = "DELETE FROM {$wp_dlm_db_relationships} WHERE download_id=" . $wpdb->escape($_GET['id']) . ";";
                $wpdb->query($query_delete);
                echo '<div id="message" class="updated fade"><p><strong>' . __('Download deleted Successfully', "wp-download_monitor") . '</strong></p></div>';
                // Truncate table if empty
                $q = $wpdb->get_results("select * from {$wp_dlm_db};");
                if (empty($q)) {
                    $wpdb->query("TRUNCATE table {$wp_dlm_db}");
                }
                $show = true;
                break;
            case "cancelled":
                $show = true;
                break;
        }
    }
    /* Bulk Editing */
    if (isset($_POST['dobulkaction']) || isset($_POST['dobulkaction2'])) {
        if (isset($_POST['dobulkaction'])) {
            $action = $_POST['bulkactions'];
        } elseif (isset($_POST['dobulkaction2'])) {
            $action = $_POST['bulkactions2'];
        }
        if (isset($_POST['check'])) {
            $checked = $_POST['check'];
        } else {
            $checked = '';
        }
        $bulk_ids = array();
        if ($checked && is_array($checked)) {
            foreach ($checked as $key => $value) {
                if (key($value) && key($value) > 0) {
                    $bulk_ids[] = key($value);
                }
            }
        } elseif ($checked) {
            $bulk_ids = explode(',', $checked);
        }
        if (!$action || sizeof($bulk_ids) == 0) {
            // No action selected/or no downloads selected
            $show = true;
        } elseif ($action == 'reset') {
            // Reset Stats of selected downloads
            wp_dlm_clear_cached_stuff();
            foreach ($bulk_ids as $bid) {
                if (is_numeric($bid) && $bid > 0) {
                    $wpdb->query($wpdb->prepare("UPDATE {$wp_dlm_db} SET hits=0 WHERE id=%s;", $bid));
                }
            }
            echo '<div id="message" class="updated fade"><p><strong>' . __('Stats successfully reset for selected downloads', "wp-download_monitor") . '</strong></p></div>';
            $show = true;
        } elseif ($action == 'delete') {
            // Delete selected downloads
            wp_dlm_clear_cached_stuff();
            foreach ($bulk_ids as $bid) {
                if (is_numeric($bid) && $bid > 0) {
                    $d = $wpdb->get_row("SELECT * FROM {$wp_dlm_db} WHERE id={$bid};");
                    $file = $d->filename;
                    $dirs = wp_upload_dir();
                    $uploadpath = trailingslashit($dirs['baseurl']);
                    $absuploadpath = trailingslashit($dirs['basedir']);
                    if ($uploadpath && (strstr($d->filename, $uploadpath) || strstr($d->filename, $absuploadpath))) {
                        $file = str_replace($uploadpath, "", $d->filename);
                        if (is_file($absuploadpath . $file)) {
                            chmod($absuploadpath . $file, 0777);
                            unlink($absuploadpath . $file);
                        }
                    }
                    $query_delete = "DELETE FROM {$wp_dlm_db} WHERE id={$bid};";
                    $wpdb->query($query_delete);
                    $query_delete = "DELETE FROM {$wp_dlm_db_stats} WHERE download_id={$bid};";
                    $wpdb->query($query_delete);
                    $query_delete = "DELETE FROM {$wp_dlm_db_log} WHERE download_id={$bid};";
                    $wpdb->query($query_delete);
                    $query_delete = "DELETE FROM {$wp_dlm_db_meta} WHERE download_id={$bid};";
                    $wpdb->query($query_delete);
                    $query_delete = "DELETE FROM {$wp_dlm_db_relationships} WHERE download_id={$bid};";
                    $wpdb->query($query_delete);
                }
            }
            echo '<div id="message" class="updated fade"><p><strong>' . __('Selected Downloads deleted Successfully', "wp-download_monitor") . '</strong></p></div>';
            // Truncate table if empty
            $q = $wpdb->get_results("select * from {$wp_dlm_db};");
            if (empty($q)) {
                $wpdb->query("TRUNCATE table {$wp_dlm_db}");
            }
            $show = true;
        } elseif ($action == 'edit') {
            // Show edit form instead
            $show = false;
            $show_edit = true;
            if (isset($_POST['meta'])) {
                $custom_fields = $_POST['meta'];
            } else {
                $custom_fields = '';
            }
            if (isset($_POST['save'])) {
                // get values
                if (isset($_POST['download_cat'])) {
                    $download_cat = $_POST['download_cat'];
                } else {
                    $download_cat = '';
                }
                $change_memberonly = $_POST['change_memberonly'];
                $change_forcedownload = $_POST['change_forcedownload'];
                $members = isset($_POST['memberonly']) ? 1 : 0;
                $forcedownload = isset($_POST['forcedownload']) ? 1 : 0;
                $change_customfields = $_POST['change_customfields'];
                $change_tags = $_POST['change_tags'];
                $change_cats = $_POST['change_cats'];
                $change_thumbnail = $_POST['change_thumbnail'];
                $tags = $_POST['tags'];
                $thumbnail = $_POST['thumbnail'];
                if ($thumbnail) {
                    if (!strstr($thumbnail, '://')) {
                        $pageURL = "";
                        $pageURL = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
                        if ($_SERVER["SERVER_PORT"] != "80") {
                            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"];
                        } else {
                            $pageURL .= $_SERVER["SERVER_NAME"];
                        }
                        if (!strstr(get_bloginfo('url'), 'www.')) {
                            $pageURL = str_replace('www.', '', $pageURL);
                        }
                        if (!isset($_SERVER['DOCUMENT_ROOT'])) {
                            $_SERVER['DOCUMENT_ROOT'] = str_replace('\\', '/', substr($_SERVER['SCRIPT_FILENAME'], 0, 0 - strlen($_SERVER['PHP_SELF'])));
                        }
                        $dir_path = $_SERVER['DOCUMENT_ROOT'];
                        $thumbnail = str_replace($dir_path, $pageURL, $thumbnail);
                    }
                }
                // save options
                $queries = array();
                if ($change_memberonly == 1) {
                    $queries[] = " members='" . $wpdb->escape($members) . "' ";
                }
                if (sizeof($queries) > 0) {
                    $wpdb->query("UPDATE {$wp_dlm_db} SET " . implode(', ', $queries) . " WHERE id IN (" . $wpdb->escape(implode(', ', $bulk_ids)) . ");");
                }
                $taxonomy_ids = array();
                if ($change_cats == 1) {
                    $cats = $download_taxonomies->categories;
                    if (!empty($cats)) {
                        foreach ($cats as $c) {
                            $this_cat_value = isset($_POST['category_' . $c->id]) ? 1 : 0;
                            foreach ($bulk_ids as $bid) {
                                $wpdb->query("DELETE FROM {$wp_dlm_db_relationships} WHERE taxonomy_id = '" . $c->id . "' AND download_id = " . $bid . "");
                            }
                            if ($this_cat_value) {
                                $taxonomy_ids[] = $c->id;
                            }
                        }
                    }
                    if (sizeof($cat_ids) > 0) {
                        foreach ($cat_ids as $cat) {
                            foreach ($bulk_ids as $bid) {
                                $wpdb->query("INSERT INTO {$wp_dlm_db_relationships} (taxonomy_id, download_id) VALUES ('" . $cat . "' , " . $bid . ")");
                            }
                        }
                    }
                }
                if ($change_tags == 1) {
                    if ($tags) {
                        // Break 'em up
                        $thetags = explode(',', $tags);
                        $thetags = array_map('trim', $thetags);
                        $thetags = array_map('strtolower', $thetags);
                        if (sizeof($thetags) > 0) {
                            foreach ($thetags as $tag) {
                                if ($tag) {
                                    // Exists?
                                    $tag_id = $wpdb->get_var("SELECT id FROM {$wp_dlm_db_taxonomies} WHERE taxonomy='tag' AND name='" . $wpdb->escape($tag) . "';");
                                    // Insert
                                    if (!$tag_id) {
                                        $wpdb->query("INSERT INTO {$wp_dlm_db_taxonomies} (name, parent, taxonomy) VALUES ('" . $wpdb->escape($tag) . "', 0, 'tag');");
                                        $tag_id = $wpdb->insert_id;
                                    }
                                    foreach ($bulk_ids as $bid) {
                                        $wpdb->query("DELETE FROM {$wp_dlm_db_relationships} WHERE taxonomy_id = '" . $tag_id . "' AND download_id = " . $bid . "");
                                    }
                                    if ($tag_id) {
                                        $taxonomy_ids[] = $tag_id;
                                    }
                                }
                            }
                        }
                    }
                }
                if (sizeof($taxonomy_ids) > 0) {
                    foreach ($taxonomy_ids as $tax) {
                        foreach ($bulk_ids as $bid) {
                            $wpdb->query("INSERT INTO {$wp_dlm_db_relationships} (taxonomy_id, download_id) VALUES ('" . $tax . "' , " . $bid . ")");
                        }
                    }
                }
                if ($change_thumbnail == 1) {
                    $wpdb->query("DELETE FROM {$wp_dlm_db_meta} WHERE download_id IN (" . $wpdb->escape(implode(', ', $bulk_ids)) . ") AND meta_name IN ('thumbnail')");
                    foreach ($bulk_ids as $bid) {
                        if ($thumbnail) {
                            $wpdb->query("INSERT INTO {$wp_dlm_db_meta} (meta_name, meta_value, download_id) VALUES ('thumbnail', '" . $thumbnail . "' , " . $bid . ")");
                        }
                    }
                }
                if ($change_forcedownload == 1) {
                    $wpdb->query("DELETE FROM {$wp_dlm_db_meta} WHERE download_id IN (" . $wpdb->escape(implode(', ', $bulk_ids)) . ") AND meta_name IN ('force')");
                    foreach ($bulk_ids as $bid) {
                        if ($forcedownload) {
                            $wpdb->query("INSERT INTO {$wp_dlm_db_meta} (meta_name, meta_value, download_id) VALUES ('force', '" . $forcedownload . "' , " . $bid . ")");
                        }
                    }
                }
                // Process and save meta/custom fields
                if ($change_customfields > 0) {
                    if ($change_customfields == 1) {
                        $wpdb->query("DELETE FROM {$wp_dlm_db_meta} WHERE download_id IN (" . $wpdb->escape(implode(', ', $bulk_ids)) . ") AND meta_name NOT IN ('tags','thumbnail','force')");
                    } elseif ($change_customfields == 2) {
                        // Get posted meta names
                        $meta_names = array();
                        if ($_POST['meta']) {
                            foreach ($_POST['meta'] as $meta) {
                                if (trim($meta['key'])) {
                                    $meta_names[] = "'" . $wpdb->escape(strtolower(str_replace(' ', '-', trim($meta['key'])))) . "'";
                                }
                            }
                        }
                        $wpdb->query("DELETE FROM {$wp_dlm_db_meta} WHERE download_id IN (" . $wpdb->escape(implode(', ', $bulk_ids)) . ") AND meta_name IN (" . implode(',', $meta_names) . ")");
                    }
                    $values = array();
                    if ($_POST['meta']) {
                        foreach ($_POST['meta'] as $meta) {
                            if (trim($meta['key'])) {
                                foreach ($bulk_ids as $bid) {
                                    $values[] = '("' . $wpdb->escape(strtolower(str_replace(' ', '-', trim(stripslashes($meta['key']))))) . '", "' . $wpdb->escape($meta['value']) . '", ' . $bid . ')';
                                }
                            }
                        }
                    }
                    if (sizeof($values) > 0) {
                        $wpdb->query("INSERT INTO {$wp_dlm_db_meta} (meta_name, meta_value, download_id) VALUES " . implode(',', $values) . "");
                    }
                }
                echo '<div id="message" class="updated fade"><p><strong>' . __('Downloads edited successfully', "wp-download_monitor") . '</strong></p></div>';
                // hide edit form - show downloads
                $show_edit = false;
                $show = true;
            }
            if ($show_edit == true) {
                ?>
			<div class="wrap">
			<div id="downloadadminicon" class="icon32"><br/></div>
				<h2><?php 
                _e('Bulk Edit Downloads', "wp-download_monitor");
                ?>
</h2>
				<p><?php 
                _e('Editing downloads with id\'s:', "wp-download_monitor");
                ?>
 <code><?php 
                echo implode(', ', $bulk_ids);
                ?>
</code>. <?php 
                _e('Adding options here will overwrite the options in ALL of the selected downloads.', "wp-download_monitor");
                ?>
</p>
				<form action="admin.php?page=download-monitor/wp-download_monitor.php" method="post" id="wp_dlm_add" name="edit_download" class="form-table" cellpadding="0" cellspacing="0"> 

					<table class="optiontable niceblue">    
					
					
		                <tr valign="top">												
		                    <th scope="row"><strong><?php 
                _e('Categories', "wp-download_monitor");
                ?>
</strong></th> 
		                    <td>
		                    	<select name="change_cats" style="vertical-align:middle">
                            		<option value=""><?php 
                _e('No Change', "wp-download_monitor");
                ?>
</option>
                            		<option value="1"><?php 
                _e('Change to &darr;', "wp-download_monitor");
                ?>
</option>
                            	</select>
                            	<div id="categorydiv"><ul class="categorychecklist" style="background: #fff; border: 1px solid #DFDFDF; height: 200px; margin: 4px 1px; overflow: auto; padding: 3px 6px; width: 346px;">
		                    		<?php 
                global $download_taxonomies, $categories;
                $cats = $download_taxonomies->get_parent_cats();
                if (!empty($cats)) {
                    foreach ($cats as $c) {
                        echo '<li><label for="category_' . $c->id . '"><input type="checkbox" name="category_' . $c->id . '" id="category_' . $c->id . '" ';
                        if (isset($_POST['category_' . $c->id]) || is_array($categories) && in_array($c->id, $categories)) {
                            echo 'checked="checked"';
                        }
                        echo ' /> ' . $c->id . ' - ' . $c->name . '</label>';
                        // Do Children
                        if (!function_exists('cat_form_output_children')) {
                            function cat_form_output_children($child)
                            {
                                global $download_taxonomies, $categories;
                                if ($child) {
                                    echo '<li><label for="category_' . $child->id . '"><input type="checkbox" name="category_' . $child->id . '" id="category_' . $child->id . '" ';
                                    if (isset($_POST['category_' . $child->id]) || is_array($categories) && in_array($child->id, $categories)) {
                                        echo 'checked="checked"';
                                    }
                                    echo ' /> ' . $child->id . ' - ' . $child->name . '</label>';
                                    echo '<ul class="children">';
                                    $download_taxonomies->do_something_to_cat_children($child->id, 'cat_form_output_children', 'cat_form_output_no_children');
                                    echo '</ul>';
                                    echo '</li>';
                                }
                            }
                            function cat_form_output_no_children()
                            {
                                echo '<li></li>';
                            }
                        }
                        echo '<ul class="children">';
                        $download_taxonomies->do_something_to_cat_children($c->id, 'cat_form_output_children', 'cat_form_output_no_children');
                        echo '</ul>';
                        echo '</li>';
                    }
                }
                ?>
		                    	</ul></div><a href="#" class="add-new-cat-ajax" style="display:none"><?php 
                _e('+ Add New Category', "wp-download_monitor");
                ?>
</a><div id="add_cat_form" style="display:none">
				                    <table class="niceblue small-table" cellpadding="0" cellspacing="0" style="width:362px;">
				                        <tr>
				                            <th scope="col"><?php 
                _e('Name', "wp-download_monitor");
                ?>
:</th>
				                            <td><input type="text" name="cat_name" style="width: 220px" /></td>
				                        </tr>
				                        <tr>
				                            <th scope="col"><?php 
                _e('Parent', "wp-download_monitor");
                ?>
:</th>
				                            <td><select name="cat_parent" style="width: 220px">
				                            	<option value=""><?php 
                _e('None', "wp-download_monitor");
                ?>
</option>
				                                <?php 
                if (!empty($cats)) {
                    foreach ($cats as $c) {
                        echo '<option value="' . $c->id . '">' . $c->id . ' - ' . $c->name . '</option>';
                        echo get_option_children_cats($c->id, "{$c->name} &mdash; ", 0);
                    }
                }
                ?>
				                            </select></td>
				                        </tr>
				                    </table>
			                    	<p class="submit" style="padding:0 "><input type="submit" value="<?php 
                _e('Add', "wp-download_monitor");
                ?>
" name="add_cat" id="add_cat" /></p>
		                    	</div></td>
		                </tr>
		                <tr valign="middle">
		                    <th scope="row"><strong><?php 
                _e('Tags', "wp-download_monitor");
                ?>
: </strong></th> 
		                    <td>
		                        <select name="change_tags" style="vertical-align:middle">
                            		<option value=""><?php 
                _e('No Change', "wp-download_monitor");
                ?>
</option>
                            		<option value="1"><?php 
                _e('Change to &rarr;', "wp-download_monitor");
                ?>
</option>
                            	</select><input type="text" style="width:360px;" class="cleardefault" value="<?php 
                if (isset($download_tags)) {
                    echo $download_tags;
                }
                ?>
" name="tags" id="dltags" /><br /><span class="setting-description"><?php 
                _e('Separate tags with commas.', "wp-download_monitor");
                ?>
 <a class="browsetags" style="display:none" href="#"><?php 
                _e('Toggle Tags', "wp-download_monitor");
                ?>
</a></span>
		                    	<div id="tag-list" style="display:none;">
		                    		<?php 
                $tags = $download_taxonomies->tags;
                echo '<ul>';
                if (!empty($tags)) {
                    foreach ($tags as $tag) {
                        echo '<li><a href="#" class="ins-tag">' . $tag->name . '</a></li>';
                    }
                } else {
                    echo '<li>' . __('No Tags Found', "wp-download_monitor") . '</li>';
                }
                echo '</ul>';
                ?>
		                    	</div>
		                    </td> 
		                </tr>
		                <tr valign="middle">
		                    <th scope="row"><strong><?php 
                _e('Thumbnail', "wp-download_monitor");
                ?>
: </strong></th> 
		                    <td>
		                        <select name="change_thumbnail" style="vertical-align:middle">
                            		<option value=""><?php 
                _e('No Change', "wp-download_monitor");
                ?>
</option>
                            		<option value="1"><?php 
                _e('Change to &rarr;', "wp-download_monitor");
                ?>
</option>
                            	</select><input type="text" style="width:360px;" class="cleardefault" value="<?php 
                if (isset($thumbnail)) {
                    echo $thumbnail;
                }
                ?>
" name="thumbnail" id="thumbnail" /><br />
                            	<?php 
                if (get_option('wp_dlm_enable_file_browser') !== 'no') {
                    ?>
                            	<a class="browsefilesthumbnail" style="display:none" href="#"><?php 
                    _e('Toggle File Browser', "wp-download_monitor");
                    ?>
</a>
                    			<div id="file_browser_thumbnail"></div>
                    			<?php 
                }
                ?>
		                    </td> 
		                </tr>
                        <tr valign="top">												
                            <th scope="row"><strong><?php 
                _e('Member only file?', "wp-download_monitor");
                ?>
</strong></th> 
                            <td><select name="change_memberonly" style="vertical-align:middle">
                            	<option value=""><?php 
                _e('No Change', "wp-download_monitor");
                ?>
</option>
                            	<option value="1"><?php 
                _e('Change to &rarr;', "wp-download_monitor");
                ?>
</option>
                            </select> <input type="checkbox" name="memberonly" style="vertical-align:middle" <?php 
                if (isset($members) && $members == 1) {
                    echo "checked='checked'";
                }
                ?>
 /> <span class="setting-description"><?php 
                _e('If chosen, only logged in users will be able to access the file via a download link. You can also add a custom field called min-level or req-role to set the minimum user level needed to download the file.', "wp-download_monitor");
                ?>
</span></td>
                        </tr>
		                <tr valign="top">												
		                    <th scope="row"><strong><?php 
                _e('Force Download?', "wp-download_monitor");
                ?>
</strong></th> 
		                    <td><select name="change_forcedownload" style="vertical-align:middle">
                            	<option value=""><?php 
                _e('No Change', "wp-download_monitor");
                ?>
</option>
                            	<option value="1"><?php 
                _e('Change to &rarr;', "wp-download_monitor");
                ?>
</option>
                            </select> <input type="checkbox" name="forcedownload" style="vertical-align:middle" <?php 
                if (isset($forcedownload) && $forcedownload == 1) {
                    echo "checked='checked'";
                }
                ?>
 /> <span class="setting-description"><?php 
                _e('If chosen, Download Monitor will attempt to force the download rather than redirect. This setting is not compatible with all servers (so test it), and in most cases will only work on files hosted on the local server.', "wp-download_monitor");
                ?>
</span></td>
		                </tr>						
					</table>
					<hr/>
		            <h3><?php 
                _e('Custom fields', "wp-download_monitor");
                ?>
</h3>
		            <p><?php 
                _e('Custom fields can be used to add extra metadata to a download. Leave blank to add none. Name should be lower case with no spaces (changed automatically, e.g. <code>Some Name</code> will become <code>some-name</code>.', "wp-download_monitor");
                ?>
</p>
		            <p><select name="change_customfields" style="vertical-align:middle">
                            	<option value=""><?php 
                _e('No Change', "wp-download_monitor");
                ?>
</option>
                            	<option value="1"><?php 
                _e('Replace with:', "wp-download_monitor");
                ?>
</option>
                            	<option value="2"><?php 
                _e('Add/Update only (keep existing fields):', "wp-download_monitor");
                ?>
</option>
                            </select></p>
					<table style="width:80%">
						<thead>
							<tr>
								<th class="left"><?php 
                _e('Name', "wp-download_monitor");
                ?>
</th>
								<th><?php 
                _e('Value', "wp-download_monitor");
                ?>
</th>
							</tr>			
						</thead>
						<tbody id="customfield_list">
							<?php 
                $index = 1;
                if ($custom_fields) {
                    foreach ($custom_fields as $meta) {
                        if (!$meta['remove']) {
                            if (trim($meta['key'])) {
                                echo '<tr class="alternate">
											<td class="left" style="vertical-align:top;">
												<label class="hidden" for="meta[' . $index . '][key]">Key</label><input name="meta[' . $index . '][key]" id="meta[' . $index . '][key]" tabindex="6" size="20" value="' . strtolower(str_replace(' ', '-', trim($meta['key']))) . '" type="text" style="width:95%">
												<input type="submit" name="meta[' . $index . '][remove]" class="button" value="' . __('remove', "wp-download_monitor") . '" />
											</td>
											<td style="vertical-align:top;"><label class="hidden" for="meta[' . $index . '][value]">Value</label><textarea name="meta[' . $index . '][value]" id="meta[' . $index . '][value]" tabindex="6" rows="2" cols="30" style="width:95%">' . $meta['value'] . '</textarea></td>
										</tr>';
                            }
                        }
                        $index++;
                    }
                }
                if (isset($_POST['addmeta'])) {
                    echo '<tr class="alternate">
										<td class="left" style="vertical-align:top;">
											<label class="hidden" for="meta[' . $index . '][key]">Key</label><input name="meta[' . $index . '][key]" id="meta[' . $index . '][key]" tabindex="6" size="20" value="" type="text" style="width:95%">
											<input type="submit" name="meta[' . $index . '][remove]" class="button" value="' . __('remove', "wp-download_monitor") . '" />
										</td>
										<td style="vertical-align:top;"><label class="hidden" for="meta[' . $index . '][value]">Value</label><textarea name="meta[' . $index . '][value]" id="meta[' . $index . '][value]" tabindex="6" rows="2" cols="30" style="width:95%"></textarea></td>
								</tr>';
                }
                ?>
							<tr id="addmetarow">
								<td colspan="2" class="submit"><input id="addmetasub" name="addmeta" value="<?php 
                _e('Add Custom Field', "wp-download_monitor");
                ?>
" type="submit" style="margin-bottom: 6px !important;" /><br/><a class="seemetafields" style="display:none;" href="#"><?php 
                _e('Toggle Existing Custom Fields', "wp-download_monitor");
                ?>
</a>
								<div id="meta_fields" style="display:none">
									<?php 
                $fields = $wpdb->get_results("SELECT DISTINCT meta_name FROM {$wp_dlm_db_meta} WHERE meta_name NOT IN ('tags', 'thumbnail', 'force') ORDER BY meta_name;");
                if ($fields) {
                    echo '<ul>';
                    foreach ($fields as $field) {
                        echo '<li><strong>' . $field->meta_name . '</strong> <button type="button" class="addmeta_rel" rel="' . $field->meta_name . '">Add</button></li>';
                    }
                    echo '</ul>';
                } else {
                    echo '<p>' . __('None found.', "wp-download_monitor") . '</p>';
                }
                ?>
								</div></td>
							</tr>
						</tbody>
					</table>
					<hr />									
					<p class="submit"><input type="submit" class="btn button-primary" name="save" style="padding:5px 30px 5px 30px;" value="<?php 
                _e('Save Changes', "wp-download_monitor");
                ?>
" />
					
					<input type="hidden" name="dobulkaction" value="1" />
					<input type="hidden" name="bulkactions" value="edit" />
					<input type="hidden" name="check" value="<?php 
                echo implode(',', $bulk_ids);
                ?>
" />
					</p>
				</form>
			</div>													
			<?php 
            }
        }
    }
    /* End Bulk Editing */
    //show downloads page
    if (isset($show) && $show == true || empty($action)) {
        global $downloadurl, $downloadtype;
        ?>
	<div class="wrap alternate">    
    	<div id="downloadadminicon" class="icon32"><br/></div>
        <h2><?php 
        _e('Edit Downloads', "wp-download_monitor");
        ?>
</h2>
		<form id="downloads-form" action="admin.php?page=download-monitor/wp-download_monitor.php" method="POST">

		<div class="tablenav">
			<div class="alignleft actions">
				<label class="hidden" for="bulkactions"><?php 
        _e('Actions:', "wp-download_monitor");
        ?>
</label>
				<select name="bulkactions" id="bulkactions">
					<option value=""><?php 
        _e('Bulk Actions', "wp-download_monitor");
        ?>
</option>
					<option value="edit"><?php 
        _e('Edit', "wp-download_monitor");
        ?>
</option>
					<option value="delete"><?php 
        _e('Delete', "wp-download_monitor");
        ?>
</option>
					<option value="reset"><?php 
        _e('Reset Stats', "wp-download_monitor");
        ?>
</option>
				</select>
				<input value="<?php 
        _e('Apply', "wp-download_monitor");
        ?>
" class="button dobulkaction" name="dobulkaction" type="submit" />
			</div>
			<div class="alignright">
				<label class="hidden" for="post-search-input"><?php 
        _e('Search Downloads:', "wp-download_monitor");
        ?>
</label>
				<input class="search-input" id="post-search-input" name="search_downloads" value="<?php 
        if (isset($_REQUEST['search_downloads'])) {
            echo $_REQUEST['search_downloads'];
        }
        ?>
" type="text" />
				<input value="<?php 
        _e('Search Downloads', "wp-download_monitor");
        ?>
" class="button" type="submit" />
			</div>
			<div class="clear"></div>
		</div>
		<div class="clear"></div>
		<?php 
        $sort = "title";
        $dir = 'asc';
        if (isset($_REQUEST['sort']) && ($_REQUEST['sort'] == "id" || $_REQUEST['sort'] == "filename" || $_REQUEST['sort'] == "postDate")) {
            $sort = $_REQUEST['sort'];
        }
        if ($sort == 'postDate') {
            $dir = 'desc';
        }
        if (isset($_REQUEST['dir']) && $_REQUEST['dir'] == "desc") {
            $dir = 'desc';
        }
        if (isset($_REQUEST['dir']) && $_REQUEST['dir'] == "asc") {
            $dir = 'asc';
        }
        ?>
        <table class="widefat" style="margin-top:4px"> 
			<thead>
				<tr>
				<th scope="col" class="check-column"><input type="checkbox" name="check_all" id="check_all" class="checkbox" /></th>
				<th scope="col"><a href="?page=download-monitor/wp-download_monitor.php&amp;sort=id<?php 
        if ($sort == 'id' && $dir != 'desc') {
            echo '&amp;dir=desc';
        }
        ?>
"><?php 
        _e('ID', "wp-download_monitor");
        ?>
</a></th>
				<th scope="col"><a href="?page=download-monitor/wp-download_monitor.php&amp;sort=title<?php 
        if ($sort == 'title' && $dir != 'desc') {
            echo '&amp;dir=desc';
        }
        ?>
"><?php 
        _e('Download', "wp-download_monitor");
        ?>
</a></th>
				<th scope="col"><a href="?page=download-monitor/wp-download_monitor.php&amp;sort=filename<?php 
        if ($sort == 'filename' && $dir != 'desc') {
            echo '&amp;dir=desc';
        }
        ?>
"><?php 
        _e('File', "wp-download_monitor");
        ?>
</a></th>
                <th scope="col"><?php 
        _e('Categories', "wp-download_monitor");
        ?>
</th>
				<th scope="col" style="text-align:left;width:150px;"><?php 
        _e('Tags', "wp-download_monitor");
        ?>
</th>
                <th scope="col" style="text-align:center"><?php 
        _e('Member only', "wp-download_monitor");
        ?>
</th>
                <th scope="col" style="text-align:center"><?php 
        _e('Force Download', "wp-download_monitor");
        ?>
</th>
                <th scope="col" style="text-align:center"><?php 
        _e('Custom fields', "wp-download_monitor");
        ?>
</th>
                <th scope="col" style="text-align:center"><img src="<?php 
        echo WP_CONTENT_URL;
        ?>
/plugins/download-monitor/img/grey_arrow.gif" style="vertical-align:middle" alt="<?php 
        _e('Hits', "wp-download_monitor");
        ?>
" title="<?php 
        _e('Hits', "wp-download_monitor");
        ?>
" /></th>
				<th scope="col"><a href="?page=download-monitor/wp-download_monitor.php&amp;sort=postDate<?php 
        if ($sort == 'postDate' && $dir != 'asc') {
            echo '&amp;dir=asc';
        }
        ?>
"><?php 
        _e('Posted', "wp-download_monitor");
        ?>
</a></th>					
				<?php 
        /*<th scope="col"><?php _e('Action',"wp-download_monitor"); ?></th> */
        ?>
				</tr>
			</thead>						
		<?php 
        // If current page number, use it
        if (!isset($_REQUEST['p'])) {
            $page = 1;
        } else {
            $page = $_REQUEST['p'];
        }
        // Search
        if (!isset($_REQUEST['search_downloads'])) {
            $search = "";
        } else {
            $search = " WHERE (title LIKE '%" . $wpdb->escape($_REQUEST['search_downloads']) . "%' OR filename LIKE '%" . $wpdb->escape($_REQUEST['search_downloads']) . "%' OR ID = '" . $wpdb->escape($_REQUEST['search_downloads']) . "' ) ";
        }
        $total_results = sprintf("SELECT COUNT(id) FROM %s %s;", $wpdb->escape($wp_dlm_db), $search);
        // Figure out the limit for the query based on the current page number.
        $from = $page * 20 - 20;
        $paged_select = sprintf("SELECT {$wp_dlm_db}.* FROM {$wp_dlm_db} %s\n\t\t\t\tORDER BY %s LIMIT %s,20;", $search, $wpdb->escape($sort . ' ' . $dir), $wpdb->escape($from));
        $download = $wpdb->get_results($paged_select);
        $total = $wpdb->get_var($total_results);
        // Figure out the total number of pages. Always round up using ceil()
        $total_pages = ceil($total / 20);
        if (!empty($download)) {
            echo '<tbody id="the-list">';
            foreach ($download as $d) {
                switch ($downloadtype) {
                    case "Title":
                        $downloadlink = urlencode($d->title);
                        break;
                    case "Filename":
                        $downloadlink = $d->filename;
                        $links = explode("/", $downloadlink);
                        $downloadlink = urlencode(end($links));
                        $downloadlink = str_replace('%26', '%2526', $downloadlink);
                        break;
                    default:
                        $downloadlink = $d->id;
                        break;
                }
                // Changed from jS M Y
                $date = date_i18n(__("Y/m/d", "wp-download_monitor"), strtotime($d->postDate));
                $path = get_bloginfo('wpurl') . '/' . get_option('upload_path') . '/';
                $file = str_replace($path, "", $d->filename);
                $links = explode("/", $file);
                $file = end($links);
                echo '<tr class="alternate">';
                echo '<th class="check-column"><input type="checkbox" name="check[][' . $d->id . ']" id="check_' . $d->id . '" class="checkbox check" /></th>';
                //$onclickcode = "if ( confirm('You are about to delete this download \'".$d->title."\'.\\n \'Cancel\' to stop, \'OK\' to delete.') ){return true;}return false;";
                echo '<td>' . $d->id . '</td>
						<td class="column-title">';
                $thumb = $wpdb->get_var('SELECT meta_value FROM ' . $wp_dlm_db_meta . ' WHERE download_id = ' . $d->id . ' AND meta_name = "thumbnail" LIMIT 1');
                if (!$thumb) {
                    $thumb = $wp_dlm_root . 'page-addon/thumbnail.gif';
                }
                echo '<img src="' . $thumb . '" alt="Thumbnail" style="float: left; margin: 0 8px 0 0; padding: 3px; background: #fff; border: 1px solid #E0E0E0" width="32" height="32" />';
                echo '<strong>' . $d->title . '';
                if ($d->dlversion) {
                    echo ' (' . __('Version', "wp-download_monitor") . ' ' . $d->dlversion . ')';
                }
                echo '</strong>
						<div class="row-actions">
							<span class="edit"><a title="' . __('Edit this Download', 'wp-download_monitor') . '" href="?page=download-monitor/wp-download_monitor.php&amp;action=edit&amp;id=' . $d->id . '&amp;sort=' . $sort . '&amp;p=' . $page . '">' . __('Edit', "wp-download_monitor") . '</a> | </span><span class="delete"><a class="submitdelete" href="?page=download-monitor/wp-download_monitor.php&amp;action=delete&amp;id=' . $d->id . '&amp;sort=' . $sort . '&amp;p=' . $page . '" title="' . __('Delete this download', "wp-download_monitor") . '">' . __('Delete', "wp-download_monitor") . '</a></span>
						</div>						
						</td>
						<td><a href="' . $downloadurl . $downloadlink . '">' . $file . '</a></td>
						<td style="max-width:175px; text-align:left;">';
                $cats = get_download_taxonomy($d->id);
                if (sizeof($cats) == 0) {
                    _e('N/A', "wp-download_monitor");
                } else {
                    echo implode(', ', $cats['list']);
                }
                echo '</td>';
                echo '<td style="max-width:175px; text-align:left;">';
                $tags = get_download_taxonomy($d->id, 'tag');
                if (sizeof($tags) == 0) {
                    _e('N/A', "wp-download_monitor");
                } else {
                    echo implode(', ', $tags['names']);
                }
                echo '</td>
						<td style="text-align:center">';
                if ($d->members) {
                    echo __('Yes', "wp-download_monitor");
                } else {
                    echo __('No', "wp-download_monitor");
                }
                echo '</td>
						<td style="text-align:center">';
                if ($wpdb->get_var('SELECT meta_value FROM ' . $wp_dlm_db_meta . ' WHERE download_id = ' . $d->id . ' AND meta_name = "force" LIMIT 1')) {
                    echo __('Yes', "wp-download_monitor");
                } else {
                    echo __('No', "wp-download_monitor");
                }
                echo '</td>
						<td style="text-align:center">';
                echo $wpdb->get_var('SELECT COUNT(id) FROM ' . $wp_dlm_db_meta . ' WHERE download_id = ' . $d->id . ' AND meta_name NOT IN ("tags","thumbnail","force","filesize")');
                echo '</td>
						<td style="text-align:center">' . $d->hits . '</td><td>' . $date . '<br/>' . __('by', "wp-download_monitor") . ' ' . $d->user . '</td>';
            }
            echo '</tbody>';
        } else {
            echo '<tr><th colspan="11">' . __('No downloads found.', "wp-download_monitor") . '</th></tr>';
        }
        // FIXED: 1.6 - Colspan changed
        ?>
			
		</table>
		<div class="tablenav">
			<div class="alignleft actions">
				<label class="hidden" for="bulkactions2"><?php 
        _e('Actions:', "wp-download_monitor");
        ?>
</label>
				<select name="bulkactions2" id="bulkactions2">
					<option value=""><?php 
        _e('Bulk Actions', "wp-download_monitor");
        ?>
</option>
					<option value="edit"><?php 
        _e('Edit', "wp-download_monitor");
        ?>
</option>
					<option value="delete"><?php 
        _e('Delete', "wp-download_monitor");
        ?>
</option>
					<option value="reset"><?php 
        _e('Reset Stats', "wp-download_monitor");
        ?>
</option>
				</select>
				<input value="<?php 
        _e('Apply', "wp-download_monitor");
        ?>
" class="button dobulkaction" name="dobulkaction2" type="submit" />
			</div>
        	<div class="tablenav-pages alignright">
				<?php 
        if ($total_pages > 1) {
            if (isset($_REQUEST['search_downloads'])) {
                $search_downloads = $_REQUEST['search_downloads'];
            } else {
                $search_downloads = '';
            }
            $arr_params = array('sort' => $sort, 'page' => 'download-monitor/wp-download_monitor.php', 'search_downloads' => $search_downloads, 'p' => "%#%");
            $arr_params2 = array('action', 'id');
            $query_page = remove_query_arg($arr_params2);
            $query_page = add_query_arg($arr_params, $query_page);
            echo paginate_links(array('base' => $query_page, 'prev_text' => __('&laquo; Previous'), 'next_text' => __('Next &raquo;'), 'total' => $total_pages, 'current' => $page, 'end_size' => 1, 'mid_size' => 5));
        }
        ?>
	
				<div class="clear"></div>
            </div> 
			<div class="clear"></div>
		</div>
        <br style="clear: both; margin-bottom:1px; height:2px; line-height:2px;" />
		<script type="text/javascript">
		/* <![CDATA[ */
			jQuery('#check_all').click(function(){
				jQuery('.check').attr('checked', jQuery(this).is(':checked'));
			});
			jQuery('#check_all, .check').attr('checked',false);
			
			// Confirm
			jQuery('.dobulkaction').click(function(){
			
				if ( jQuery('select[name=bulkactions], select[name=bulkactions2]', jQuery(this).parent() ).val() == 'delete' ) {
					if ( confirm('<?php 
        echo js_escape(__("You are about to delete the selected items.\n  'Cancel' to stop, 'OK' to delete."));
        ?>
') ) 
					{
						return true;
					}
					return false;
				}				
			});
		/* ]]> */
		</script>
    </form>
    </div>
    <?php 
        if (!get_option('wp_dlm_disable_news') || get_option('wp_dlm_disable_news') == 'no') {
            ?>
    <hr />
    <div class="about">
    	<div class="about-widget">
    		<h3><?php 
            _e('Download Monitor News', "wp-download_monitor");
            ?>
</h3>
    		<div class="inside">
    		<?php 
            if (file_exists(ABSPATH . WPINC . '/class-simplepie.php')) {
                include_once ABSPATH . WPINC . '/class-simplepie.php';
                $rss = fetch_feed('http://mikejolley.com/tag/download-monitor/feed');
                if (!is_wp_error($rss)) {
                    $maxitems = $rss->get_item_quantity(5);
                    $rss_items = $rss->get_items(0, $maxitems);
                    if ($maxitems > 0) {
                        echo '<ul>';
                        foreach ($rss_items as $item) {
                            $title = wptexturize($item->get_title(), ENT_QUOTES, "UTF-8");
                            $link = $item->get_permalink();
                            $date = $item->get_date('U');
                            if (abs(time() - $date) < 86400) {
                                // 1 Day
                                $human_date = sprintf(__('%s ago', 'wp-download_monitor'), human_time_diff($date));
                            } else {
                                $human_date = date(__('F jS Y', 'wp-download_monitor'), $date);
                            }
                            echo '<li><a href="' . $link . '">' . $title . '</a> &ndash; <span class="rss-date">' . $human_date . '</span></li>';
                        }
                        echo '</ul>';
                    } else {
                        echo '<ul><li>' . __('No items found.', 'wp-download_monitor') . '</li></ul>';
                    }
                } else {
                    echo '<ul><li>' . __('No items found.', 'wp-download_monitor') . '</li></ul>';
                }
            }
            ?>
    		</div>
    	</div>
    	<div class="about-widget" style="margin-right:0;">
    		<h3><?php 
            _e('Links &amp; Documentation', "wp-download_monitor");
            ?>
</h3>
    		<div class="inside">
    			<?php 
            _e('<p>Need help? FAQ, Usage instructions and other notes can be found on the WordPress.org plugin page.</p>', "wp-download_monitor");
            ?>
    			<ul>
    				<li><a href="http://wordpress.org/extend/plugins/download-monitor/"><?php 
            _e('Download Monitor on WordPress.org', "wp-download_monitor");
            ?>
</a></li>
    				<li><a href="http://mikejolley.com/projects/download-monitor/"><?php 
            _e('Download Monitor documentation + FAQ', "wp-download_monitor");
            ?>
</a></li>
    				<li><a href="https://github.com/mikejolley/download-monitor"><?php 
            _e('Download Monitor on GitHub', "wp-download_monitor");
            ?>
</a></li>
    			</ul>
    		</div>
    	</div> 
    	<div class="about-widget" style="margin-right:0; float:right;">
    		<h3><?php 
            _e('Support Download Monitor', "wp-download_monitor");
            ?>
</h3>
    		<div class="inside">
    			<p><?php 
            _e('The Wordpress Download monitor plugin was created by <a href="http://mikejolley.com/">Mike Jolley</a>. The development of this plugin took a lot of time and effort, so please don\'t forget to donate if you found this plugin useful.', "wp-download_monitor");
            ?>
</p>
	    
	    		<p><?php 
            _e('There are also other ways of supporting download monitor to ensure it is maintained and well supported in the future! Rating the plugin on wordpress.org (if you like it), linking/spreading the word, and submitting code contributions will all help.', "wp-download_monitor");
            ?>
</p>
	    		
	    		<form action="https://www.paypal.com/cgi-bin/webscr" method="post" style="float:right">
					<input type="hidden" name="cmd" value="_s-xclick" />
					<input type="hidden" name="hosted_button_id" value="10691945" />
					<input type="image" src="https://www.paypal.com/en_GB/i/btn/btn_donate_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online." />
					<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1" />
				</form>
    		</div>
    	</div>		
		<div class="clear"></div>
	</div>
	<?php 
        }
        ?>

<?php 
    }
    echo '</div>';
}
Esempio n. 6
0
function wp_dlm_categories()
{
    //set globals
    global $wpdb, $wp_dlm_root, $wp_dlm_db, $wp_dlm_db_taxonomies, $wp_dlm_db_formats, $dlm_url, $downloadtype, $wp_dlm_db_relationships, $download_taxonomies;
    // turn off magic quotes
    wp_dlm_magic();
    ?>
	<div class="download_monitor">
	<div class="wrap alternate">

    <div id="downloadadminicon" class="icon32"><br/></div>
    <h2><?php 
    _e('Download Categories', "wp-download_monitor");
    ?>
</h2>
    <?php 
    _e('<p>You can categorise downloads using these categories. You can then show groups of downloads using the category tags or a dedicated download page (see documentation). Please note, deleting a category also deletes it\'s child categories.</p>', "wp-download_monitor");
    ?>
    <?php 
    if (isset($_POST['rename_cat'])) {
        $name = $_POST['cat_rename'];
        if (!empty($name)) {
            $category = $_POST['cat_to_rename'];
            $parent = $_POST['cat_parent_edit'];
            $parent_q = '';
            $children = array();
            if ($download_taxonomies->categories[$category]) {
                $children = $download_taxonomies->categories[$category]->get_decendents();
            }
            if ($parent == '0' || $parent > 0 and $parent !== $category and !in_array($parent, $children)) {
                $parent_q = ", parent='{$parent}'";
            }
            if ($category && is_numeric($category) && $category > 0) {
                $query = sprintf("UPDATE {$wp_dlm_db_taxonomies} SET name='%s' {$parent_q} WHERE id='%s' AND taxonomy = 'category';", $wpdb->escape($name), $wpdb->escape($category));
                $wpdb->query($query);
                wp_dlm_clear_cached_stuff();
                //echo $query;
                echo '<div id="message" class="updated fade"><p><strong>' . __('Category updated', "wp-download_monitor") . '</strong></p></div>';
            }
        }
    } elseif (isset($_POST['add_cat'])) {
        $name = $_POST['cat_name'];
        if (!empty($name)) {
            $parent = $_POST['cat_parent'];
            if (!$parent) {
                $parent = 0;
            }
            $query_ins = sprintf("INSERT INTO %s (name, parent, taxonomy) VALUES ('%s','%s','category')", $wpdb->escape($wp_dlm_db_taxonomies), $wpdb->escape($name), $wpdb->escape($parent));
            $wpdb->query($query_ins);
            wp_dlm_clear_cached_stuff();
            if ($wpdb->insert_id > 0) {
                echo '<div id="message" class="updated fade"><p><strong>' . __('Category added', "wp-download_monitor") . '</strong></p></div>';
            } else {
                echo '<div id="message" class="updated fade"><p><strong>' . __('Category was not added. Try Recreating the download database from the configuration page.', "wp-download_monitor") . '</strong></p></div>';
            }
        }
    } elseif (isset($_GET['action']) && $_GET['action'] == 'deletecat') {
        $nonce = $_REQUEST['_wpnonce'];
        if (!wp_verify_nonce($nonce)) {
            die('Security check');
        }
        $id = $_GET['id'];
        // Sub cats
        $delete_cats = array();
        if ($download_taxonomies->categories[$id]) {
            $delete_cats = $download_taxonomies->categories[$id]->get_decendents();
        }
        $delete_cats[] = $id;
        // Delete
        $query_delete = sprintf("DELETE FROM %s WHERE id IN (%s) AND taxonomy = 'category';", $wpdb->escape($wp_dlm_db_taxonomies), $wpdb->escape(implode(",", $delete_cats)));
        $wpdb->query($query_delete);
        // Remove from relationships
        $query_delete = sprintf("DELETE FROM %s WHERE taxonomy_id IN (%s);", $wpdb->escape($wp_dlm_db_relationships), $wpdb->escape(implode(",", $delete_cats)));
        $wpdb->query($query_delete);
        wp_dlm_clear_cached_stuff();
        echo '<div id="message" class="updated fade"><p><strong>' . __('Category deleted Successfully', "wp-download_monitor") . '</strong></p></div>';
    }
    $download_taxonomies->download_taxonomies();
    ?>
    <form action="?page=dlm_categories" method="post">
        <table class="widefat" id="sort_dlm_cats">
            <thead>
                <tr>
                    <th scope="col" style="text-align:center; width:3em;"><?php 
    _e('ID', "wp-download_monitor");
    ?>
</th>
                    <th scope="col"><?php 
    _e('Name', "wp-download_monitor");
    ?>
</th>
                    <th scope="col" style="text-align:center; width:5em;"><?php 
    _e('Action', "wp-download_monitor");
    ?>
</th>
                </tr>
            </thead>
            <tbody id="the-list">
            	<?php 
    function output_category_option($child = '', $chain = '')
    {
        global $download_taxonomies;
        $c = $download_taxonomies->categories[$child->id];
        if ($c) {
            echo '<li id="category_' . $c->id . '"><span class="handle">(' . $c->id . ') ' . $chain . '' . $c->name . '</span> <a href="' . wp_nonce_url(admin_url('admin.php?page=dlm_categories&amp;action=deletecat&amp;id=' . $c->id)) . '" class="delete_cat" rel="' . $c->name . '"><img src="' . WP_CONTENT_URL . '/plugins/download-monitor/img/cross.png" alt="Delete" title="Delete" /></a>';
            echo '<ul class="children">';
            $download_taxonomies->do_something_to_cat_children($child->id, 'output_category_option', 'output_empty_category_option', "&mdash; ");
            echo '</ul>';
            echo '</li>';
        }
        return;
    }
    function output_empty_category_option($child = '', $chain = '')
    {
        echo "<li></li>";
    }
    $cats = $download_taxonomies->get_parent_cats();
    if ($cats) {
        foreach ($cats as $c) {
            echo '<tr id="category_' . $c->id . '"><td style="text-align:center; width:5em;">(' . $c->id . ')</td><td><span class="handle">' . $c->name . '</span>';
            echo '<ul class="children">';
            $download_taxonomies->do_something_to_cat_children($c->id, 'output_category_option', '', "&mdash; ");
            echo '</ul>';
            echo '</td><td style="text-align:center; width:5em;"><a href="' . wp_nonce_url(admin_url('admin.php?page=dlm_categories&amp;action=deletecat&amp;id=' . $c->id)) . '" class="delete_cat" rel="' . $c->name . '"><img src="' . WP_CONTENT_URL . '/plugins/download-monitor/img/cross.png" alt="Delete" title="Delete" /></a></td>';
            echo '</tr>';
        }
    } else {
        echo '<tr><td colspan="3">' . __('No categories exist', "wp-download_monitor") . '</td></tr>';
    }
    ?>
            </tbody>
        </table>
        <div style="float:left; margin-right: 20px;">
        	<h4><?php 
    _e('Add category', "wp-download_monitor");
    ?>
</h4>
            <table class="niceblue small-table" cellpadding="0" cellspacing="0">
                <tr>
                    <th scope="col"><?php 
    _e('Name', "wp-download_monitor");
    ?>
:</th>
                    <td><input type="text" name="cat_name" /></td>
                </tr>
                <tr>
                    <th scope="col"><?php 
    _e('Parent', "wp-download_monitor");
    ?>
:</th>
                    <td><select name="cat_parent">
                    	<option value=""><?php 
    _e('None', "wp-download_monitor");
    ?>
</option>
                        <?php 
    if (!empty($cats)) {
        foreach ($cats as $c) {
            echo '<option value="' . $c->id . '">' . $c->id . ' - ' . $c->name . '</option>';
            echo get_option_children_cats($c->id, "{$c->name} &mdash; ", 0);
        }
    }
    ?>
                    </select></td>
                </tr>
            </table>
            <p class="submit"><input type="submit" value="<?php 
    _e('Add', "wp-download_monitor");
    ?>
" name="add_cat" /></p>
        </div>
        <div style="float:left">
        	<h4><?php 
    _e('Edit category', "wp-download_monitor");
    ?>
</h4>
            <table class="niceblue small-table" cellpadding="0" cellspacing="0">
                <tr>
                    <th scope="col"><?php 
    _e('Category', "wp-download_monitor");
    ?>
:</th>
                    <td><select name="cat_to_rename">
                    	<option value=""><?php 
    _e('Select a category', "wp-download_monitor");
    ?>
</option>
                        <?php 
    if (!empty($cats)) {
        foreach ($cats as $c) {
            echo '<option value="' . $c->id . '">' . $c->id . ' - ' . $c->name . '</option>';
            echo get_option_children_cats($c->id, "{$c->name} &mdash; ", 0);
        }
    }
    ?>
                    </select></td>
                </tr>
                <tr>
                    <th scope="col"><?php 
    _e('Parent', "wp-download_monitor");
    ?>
:</th>
                    <td><select name="cat_parent_edit">
                    	<option value=""><?php 
    _e('No Change', "wp-download_monitor");
    ?>
</option>
                    	<option value="0"><?php 
    _e('None', "wp-download_monitor");
    ?>
</option>
                        <?php 
    if (!empty($cats)) {
        foreach ($cats as $c) {
            echo '<option value="' . $c->id . '">' . $c->id . ' - ' . $c->name . '</option>';
            echo get_option_children_cats($c->id, "{$c->name} &mdash; ", 0);
        }
    }
    ?>
                    </select></td>
                </tr>
                <tr>
                    <th scope="col"><?php 
    _e('Name', "wp-download_monitor");
    ?>
:</th>
                    <td><input type="text" name="cat_rename" /></td>
                </tr>
            </table>
            <p class="submit"><input type="submit" value="<?php 
    _e('Edit', "wp-download_monitor");
    ?>
" name="rename_cat" /></p>
        </div>
        <div class="clear"></div>
    </form>
    </div>
    </div>
	<?php 
}