/**
  * column_default function.
  *
  * @access public
  *
  * @param mixed $log
  * @param mixed $column_name
  *
  * @return void
  */
 function column_default($log, $column_name)
 {
     switch ($column_name) {
         case 'status':
             switch ($log->download_status) {
                 case 'failed':
                     $download_status = '<span class="failed" title="' . esc_attr($log->download_status_message) . '">&nbsp;</span>';
                     break;
                 case 'redirected':
                     $download_status = '<span class="redirected" title="' . esc_attr($log->download_status_message) . '">&nbsp;</span>';
                     break;
                 default:
                     $download_status = '<span class="completed" title="' . __('Download Complete', 'download-monitor') . '">&nbsp;</span>';
                     break;
             }
             return $download_status;
             break;
         case 'date':
             return '<time title="' . date_i18n(get_option('date_format') . ' @ ' . get_option('time_format'), strtotime($log->download_date)) . '"">' . sprintf(__('%s ago', 'download-monitor'), human_time_diff(strtotime($log->download_date), current_time('timestamp'))) . '</time>';
             break;
         case 'download':
             $download = new DLM_Download($log->download_id);
             $download->set_version($log->version_id);
             if (!$download->exists()) {
                 $download_string = sprintf(__('Download #%d (no longer exists)', 'download-monitor'), $log->download_id);
             } else {
                 $download_string = '<a href="' . admin_url('post.php?post=' . $download->id . '&action=edit') . '">';
                 $download_string .= '#' . $download->id . ' &ndash; ' . $download->get_the_title();
                 $download_string .= '</a>';
             }
             if ($log->version) {
                 $download_string .= ' (' . sprintf(__('v%s', 'download-monitor'), $log->version) . ')';
             }
             return $download_string;
             break;
         case 'file':
             $download = new DLM_Download($log->download_id);
             $download->set_version($log->version_id);
             if ($download->exists() && $download->get_the_filename()) {
                 $download_string = '<code>' . $download->get_the_filename() . '</code>';
             } else {
                 $download_string = '&ndash;';
             }
             return $download_string;
             break;
         case 'user':
             if ($log->user_id) {
                 $user = get_user_by('id', $log->user_id);
             }
             if (!isset($user) || !$user) {
                 $user_string = __('Non-member', 'download-monitor');
             } else {
                 $user_string = '<a href="' . admin_url('user-edit.php?user_id=' . $user->ID) . '">';
                 $user_string .= $user->user_login . ' &ndash; ';
                 $user_string .= '<a href="mailto:' . $user->user_email . '">';
                 $user_string .= $user->user_email;
                 $user_string .= '</a>';
             }
             return $user_string;
             break;
         case 'user_ip':
             return '<a href="http://whois.arin.net/rest/ip/' . $log->user_ip . '" target="_blank">' . $log->user_ip . '</a>';
             break;
         case 'user_ua':
             $ua = $this->uaparser->parse($log->user_agent);
             return $ua->toFullString;
             break;
     }
 }
    /**
     * media_browser function.
     *
     * @access public
     * @return void
     */
    public function media_browser()
    {
        global $download_monitor;
        // Enqueue scripts and styles for panel
        wp_enqueue_script('chosen', $download_monitor->plugin_url() . '/assets/js/chosen/chosen.jquery.min.js');
        wp_enqueue_style('chosen', $download_monitor->plugin_url() . '/assets/js/chosen/chosen.css');
        wp_enqueue_style('download_monitor_admin_css', $download_monitor->plugin_url() . '/assets/css/admin.css');
        wp_enqueue_script('common');
        wp_enqueue_style('global');
        wp_enqueue_style('wp-admin');
        wp_enqueue_style('colors');
        wp_enqueue_script('plupload-all');
        echo '<!DOCTYPE html><html lang="en"><head><title>' . __('Insert Download', 'download_monitor') . '</title><meta charset="utf-8" />';
        do_action('admin_print_styles');
        do_action('admin_print_scripts');
        do_action('admin_head');
        echo '<body id="insert-download" class="wp-core-ui">';
        ?>
		<h2 class="nav-tab-wrapper">
			<a href="#insert-shortcode" class="nav-tab nav-tab-active"><?php 
        _e('Insert Shortcode', 'download_monitor');
        ?>
</a><a href="#quick-add" class="nav-tab"><?php 
        _e('Quick-add download', 'download_monitor');
        ?>
</a>
		</h2>
		<?php 
        // Handle quick-add form
        if (!empty($_POST['download_url']) && !empty($_POST['download_title']) && wp_verify_nonce($_POST['quick-add-nonce'], 'quick-add')) {
            $url = stripslashes($_POST['download_url']);
            $title = sanitize_text_field(stripslashes($_POST['download_title']));
            $version = sanitize_text_field(stripslashes($_POST['download_version']));
            try {
                $download = array('post_title' => $title, 'post_content' => '', 'post_status' => 'publish', 'post_author' => get_current_user_id(), 'post_type' => 'dlm_download');
                $download_id = wp_insert_post($download);
                if ($download_id) {
                    // Meta
                    update_post_meta($download_id, '_featured', 'no');
                    update_post_meta($download_id, '_members_only', 'no');
                    update_post_meta($download_id, '_redirect_only', 'no');
                    update_post_meta($download_id, '_download_count', 0);
                    // File
                    $file = array('post_title' => 'Download #' . $download_id . ' File Version', 'post_content' => '', 'post_status' => 'publish', 'post_author' => get_current_user_id(), 'post_parent' => $download_id, 'post_type' => 'dlm_download_version');
                    $file_id = wp_insert_post($file);
                    if (!$file_id) {
                        throw new Exception(__('Error: File was not created.', 'download_monitor'));
                    }
                    // Meta
                    update_post_meta($file_id, '_version', $version);
                    update_post_meta($file_id, '_files', array($url));
                    update_post_meta($file_id, '_filesize', $download_monitor->get_filesize($url));
                    echo '<div class="updated"><p>' . __('Download successfully created.', 'download_monitor') . '</p></div>';
                } else {
                    throw new Exception(__('Error: Download was not created.', 'download_monitor'));
                }
            } catch (Exception $e) {
                echo '<div class="error"><p>' . $e->getMessage() . "</p></div>";
            }
        }
        // Get all downloads
        $downloads = get_posts(array('post_status' => 'publish', 'post_type' => 'dlm_download', 'posts_per_page' => -1));
        ?>
		<form id="insert-shortcode">

			<p>
				<label for="download_id"><?php 
        _e('Choose a download', 'download_monitor');
        ?>
:</label>
				<select id="download_id" class="input">
					<?php 
        foreach ($downloads as $download) {
            $download = new DLM_Download($download->ID);
            echo '<option value="' . $download->id . '">#' . $download->id . ' &ndash; ' . $download->get_the_title() . ' &ndash; ' . $download->get_the_filename() . '</option>';
        }
        ?>
				</select>
			</p>
			<p>
				<label for="template_name"><?php 
        _e('Template', 'download_monitor');
        ?>
:</label>
				<input type="text" id="template_name" value="" class="input" placeholder="<?php 
        _e('Template Name', 'download_monitor');
        ?>
" />
				<span class="description">
					<?php 
        _e('Leaving this blank will use the default <code>content-download.php</code> template file. If you enter, for example, <code>image</code>, the <code>content-download-image.php</code> template will be used instead.', 'download_monitor');
        ?>
				</span>
			</p>
			<p>
				<input type="button" class="button insert_download button-primary button-large" value="<?php 
        _e('Insert Shortcode', 'download_monitor');
        ?>
" />
			</p>

		</form>

		<form id="quick-add" action="" method="post">

			<!-- Uploader section -->
			<div id="plupload-upload-ui" class="hide-if-no-js">
				<div id="drag-drop-area" style="height:240px">
					<div class="drag-drop-inside">
						<p class="drag-drop-info"><?php 
        _e('Drop file here', 'download_monitor');
        ?>
</p>
						<p><?php 
        _e('or', 'download_monitor');
        ?>
</p>
						<p class="drag-drop-buttons"><input id="plupload-browse-button" type="button" value="<?php 
        esc_attr_e('Select File', 'download_monitor');
        ?>
" class="button" /></p>
						<p><?php 
        _e('or', 'download_monitor');
        ?>
</p>
						<p><a href="#" class="add_manually"><?php 
        _e('Enter URL manually', 'download_monitor');
        ?>
</a></p>
					</div>
				</div>
			</div>
			<div id="quick-add-details" style="display:none">
				<p>
					<label for="download_url"><?php 
        _e('Download URL', 'download_monitor');
        ?>
:</label>
					<input type="text" name="download_url" id="download_url" value="" class="download_url input" placeholder="<?php 
        _e('Required URL', 'download_monitor');
        ?>
" />
				</p>
				<p>
					<label for="download_title"><?php 
        _e('Download Title', 'download_monitor');
        ?>
:</label>
					<input type="text" name="download_title" id="download_title" value="" class="download_title input" placeholder="<?php 
        _e('Required title', 'download_monitor');
        ?>
" />
				</p>
				<p>
					<label for="download_version"><?php 
        _e('Version', 'download_monitor');
        ?>
:</label>
					<input type="text" name="download_version" id="download_version" value="" class="input" placeholder="<?php 
        _e('Optional version number', 'download_monitor');
        ?>
" />
				</p>
				<p>
					<input type="submit" class="button button-primary button-large" value="<?php 
        _e('Save Download', 'download_monitor');
        ?>
" />
					<?php 
        wp_nonce_field('quick-add', 'quick-add-nonce');
        ?>
				</p>
			</div>

		</form>

		<script type="text/javascript">
			jQuery(function() {

				jQuery('.nav-tab-wrapper a').click(function() {
					jQuery('#insert-shortcode, #quick-add').hide();
					jQuery(jQuery(this).attr('href')).show();
					jQuery('a.nav-tab-active').removeClass('nav-tab-active');
					jQuery(this).addClass('nav-tab-active');
					return false;
				});

				jQuery('#quick-add').hide();

				jQuery('#download_id').chosen();

				jQuery('body').on('click', '.insert_download', function(){

					var win = window.dialogArguments || opener || parent || top;

					var download_id = jQuery('#download_id').val();
					var template    = jQuery('#template_name').val();
					var shortcode   = '[download id="' + jQuery('#download_id').val() + '"';

					if ( template )
						shortcode = shortcode + ' template="' + template + '"';

					shortcode = shortcode + ']';

					win.send_to_editor( shortcode );

					return false;
				});

				jQuery('.add_manually').click(function() {
					jQuery('#plupload-upload-ui').slideUp();
					jQuery('#quick-add-details').slideDown();
					return false;
				});

				<?php 
        $plupload_init = array('runtimes' => 'html5,silverlight,flash,html4', 'browse_button' => 'plupload-browse-button', 'container' => 'plupload-upload-ui', 'drop_element' => 'drag-drop-area', 'file_data_name' => 'async-upload', 'multiple_queues' => false, 'max_file_size' => wp_max_upload_size() . 'b', 'url' => admin_url('admin-ajax.php'), 'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'), 'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'), 'filters' => array(array('title' => __('Allowed Files'), 'extensions' => '*')), 'multipart' => true, 'urlstream_upload' => true, 'multipart_params' => array('_ajax_nonce' => wp_create_nonce('file-upload'), 'action' => 'download_monitor_insert_panel_upload', 'type' => 'dlm_download'));
        // we should probably not apply this filter, plugins may expect wp's media uploader...
        $plupload_init = apply_filters('plupload_init', $plupload_init);
        ?>

				// create the uploader and pass the config from above
				var uploader = new plupload.Uploader(<?php 
        echo json_encode($plupload_init);
        ?>
);

				// checks if browser supports drag and drop upload, makes some css adjustments if necessary
				uploader.bind('Init', function(up){
					var uploaddiv = jQuery('#plupload-upload-ui');

					if ( up.features.dragdrop ) {
						uploaddiv.addClass('drag-drop');

						jQuery('#drag-drop-area')
							.bind('dragover.wp-uploader', function() {
								uploaddiv.addClass('drag-over');
							})
							.bind('dragleave.wp-uploader, drop.wp-uploader', function() {
								uploaddiv.removeClass('drag-over');
							});

					} else {
						uploaddiv.removeClass('drag-drop');
						jQuery('#drag-drop-area').unbind('.wp-uploader');
					}
				});

				uploader.init();

				// a file was added in the queue
				uploader.bind('FilesAdded', function(up, files) {
					var hundredmb = 100 * 1024 * 1024, max = parseInt(up.settings.max_file_size, 10);

					plupload.each(files, function(file) {
						if ( max > hundredmb && file.size > hundredmb && up.runtime != 'html5' ) {
							// file size error?
						} else {
							jQuery('.drag-drop-inside').html('<p><?php 
        _e('Please wait...', 'download_monitor');
        ?>
</p>');
						}
					});

					up.refresh();
					up.start();
				});

				// a file was uploaded
				uploader.bind('FileUploaded', function( up, file, response ) {
					jQuery('#quick-add-details').find('input.download_url').val( response.response );
					jQuery('#quick-add-details').find('input.download_title').val( basename( response.response ) );
					jQuery('#plupload-upload-ui').slideUp();
					jQuery('#quick-add-details').slideDown();
				});

				function basename(path) {
				   return path.split('/').reverse()[0];
				}

			});
		</script>
		<?php 
        echo '</body></html>';
    }
 /**
  * export_logs function
  */
 public function export_logs()
 {
     global $wpdb;
     if (empty($_GET['dlm_download_logs'])) {
         return;
     }
     $filter_status = isset($_REQUEST['filter_status']) ? sanitize_text_field($_REQUEST['filter_status']) : '';
     $filter_month = !empty($_REQUEST['filter_month']) ? sanitize_text_field($_REQUEST['filter_month']) : '';
     $items = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->download_log}\n\t\t    \tWHERE type = 'download'\n\t\t    \t" . ($filter_status ? "AND download_status = '%s'" : "%s") . "\n\t            " . ($filter_month ? "AND download_date >= '%s'" : "%s") . "\n\t            " . ($filter_month ? "AND download_date <= '%s'" : "%s") . "\n\t\t    \tORDER BY download_date DESC", $filter_status ? $filter_status : "", $filter_month ? date('Y-m-01', strtotime($filter_month)) : "", $filter_month ? date('Y-m-t', strtotime($filter_month)) : ""));
     $rows = array();
     $row = array();
     $row[] = __('Download ID', 'download_monitor');
     $row[] = __('Version ID', 'download_monitor');
     $row[] = __('Filename', 'download_monitor');
     $row[] = __('User ID', 'download_monitor');
     $row[] = __('User Login', 'download_monitor');
     $row[] = __('User Email', 'download_monitor');
     $row[] = __('User IP', 'download_monitor');
     $row[] = __('User Agent', 'download_monitor');
     $row[] = __('Date', 'download_monitor');
     $row[] = __('Status', 'download_monitor');
     $rows[] = '"' . implode('","', $row) . '"';
     if (!empty($items)) {
         foreach ($items as $item) {
             $row = array();
             $row[] = $item->download_id;
             $row[] = $item->version_id;
             $download = new DLM_Download($item->download_id);
             $download->set_version($item->version_id);
             if ($download->exists() && $download->get_the_filename()) {
                 $row[] = $download->get_the_filename();
             } else {
                 $row[] = '-';
             }
             $row[] = $item->user_id;
             if ($item->user_id) {
                 $user = get_user_by('id', $item->user_id);
             }
             if (!isset($user) || !$user) {
                 $row[] = '-';
                 $row[] = '-';
             } else {
                 $row[] = $user->user_login;
                 $row[] = $user->user_email;
             }
             $row[] = $item->user_ip;
             $row[] = $item->user_agent;
             $row[] = $item->download_date;
             $row[] = $item->download_status . ($item->download_status_message ? ' - ' : '') . $item->download_status_message;
             $rows[] = '"' . implode('","', $row) . '"';
         }
     }
     $log = implode("\n", $rows);
     header("Content-type: text/csv");
     header("Content-Disposition: attachment; filename=download_log.csv");
     header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
     header("Content-Length: " . strlen($log));
     echo $log;
     exit;
 }
 /**
  * download_data function.
  *
  * @access public
  * @param mixed $atts
  * @param mixed $content
  * @return void
  */
 public function download_data($atts)
 {
     global $download_monitor;
     extract(shortcode_atts(array('id' => '', 'data' => '', 'version_id' => '', 'version' => ''), $atts));
     $id = apply_filters('dlm_shortcode_download_id', $id);
     if (empty($id) || empty($data)) {
         return;
     }
     $download = new DLM_Download($id);
     if ($version) {
         $version_id = $download->get_version_id($version);
     }
     if ($version_id) {
         $download->set_version($version_id);
     }
     switch ($data) {
         // File / Version Info
         case 'filename':
             return $download->get_the_filename();
         case 'filetype':
             return $download->get_the_filetype();
         case 'filesize':
             return $download->get_the_filesize();
         case 'version':
             return $download->get_the_version_number();
             // Download Info
         // Download Info
         case 'title':
             return $download->get_the_title();
         case 'short_description':
             return $download->get_the_short_description();
         case 'download_link':
             return $download->get_the_download_link();
         case 'download_count':
             return $download->get_the_download_count();
         case 'post_content':
             return wpautop(wptexturize(do_shortcode($download->post->post_content)));
         case 'post_date':
             return date_i18n(get_option('date_format', $download->post->post_date));
         case 'author':
             return $download->get_the_author();
             // Images
         // Images
         case 'image':
             return $download->get_the_image('full');
         case 'thumbnail':
             return $download->get_the_image('thumbnail');
             // Taxonomies
         // Taxonomies
         case 'tags':
             return get_the_term_list($id, 'dlm_download_tags', '', ', ', '');
         case 'categories':
             return get_the_term_list($id, 'dlm_download_category', '', ', ', '');
     }
 }