back-up your database just in case. Version: 3.0 Author: Mike Jolley Author URI: http://blue-anvil.com */ /* Copyright 2006 Michael Jolley (email : jolley.small.at.googlemail.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ ################################################################################ // Vars and version ################################################################################ $dlm_build="B20090317"; $wp_dlm_root = get_bloginfo('wpurl')."/wp-content/plugins/download-monitor/"; global $table_prefix; $wp_dlm_db = $table_prefix."DLM_DOWNLOADS"; $wp_dlm_db_cats = $table_prefix."DLM_CATS"; $wp_dlm_db_formats = $table_prefix."DLM_FORMATS"; $wp_dlm_db_stats = $table_prefix."DLM_STATS"; $wp_dlm_db_log = $table_prefix."DLM_LOG"; $wp_dlm_db_meta = $table_prefix."DLM_META"; $def_format = get_option('wp_dlm_default_format'); $dlm_url = get_option('wp_dlm_url'); $downloadtype = get_option('wp_dlm_type'); if (empty($dlm_url)) $downloadurl = $wp_dlm_root.'download.php?id='; else $downloadurl = get_bloginfo('wpurl').'/'.$dlm_url; load_plugin_textdomain('wp-download_monitor', 'wp-content/plugins/download-monitor/', 'download-monitor/'); ################################################################################ // ADD MEDIA BUTTONS AND FORMS ################################################################################ function wp_dlm_add_media_button() { echo ''.__('Add Download','wp-download_monitor').''; } ################################################################################ // HANDLE UPDATES ################################################################################ function wp_dlm_update() { global $dlm_build; add_option('wp_dlm_build', $dlm_build, 'Version of DLM plugin', 'no'); if ( get_option('wp_dlm_build') != $dlm_build ) { // Init again wp_dlm_init(); // Show update message echo '
'; _e('

The plugin has recently been updated - You may need to re-save your permalinks settings (Options/settings -> Permalinks) for the changes to occur in your blog.

If you encounter any errors, such as not being able to save a file to the database, try using the Recreate Download Database option.

',"wp-download_monitor"); // Update the build update_option('wp_dlm_build', $dlm_build); } } ################################################################################ // Set up menus within the wordpress admin sections ################################################################################ function wp_dlm_menu() { global $wp_dlm_root; // Add a new top-level menu: add_menu_page(__('Downloads','wp-download_monitor'), __('Downloads','wp-download_monitor'), 6, __FILE__ , 'wp_dlm_admin', $wp_dlm_root.'/img/menu_icon.png'); // Add submenus to the custom top-level menu: add_submenu_page(__FILE__, __('Edit','wp-download_monitor'), __('Edit','wp-download_monitor') , 6, __FILE__ , 'wp_dlm_admin'); add_submenu_page(__FILE__, __('Add New','wp-download_monitor') , __('Add New','wp-download_monitor') , 6, 'dlm_addnew', 'dlm_addnew'); add_submenu_page(__FILE__, __('Add Existing','wp-download_monitor') , __('Add Existing','wp-download_monitor') , 6, 'dlm_addexisting', 'dlm_addexisting'); add_submenu_page(__FILE__, __('Configuration','wp-download_monitor') , __('Configuration','wp-download_monitor') , 6, 'dlm_config', 'wp_dlm_config'); add_submenu_page(__FILE__, __('Log','wp-download_monitor') , __('Log','wp-download_monitor') , 6, 'dlm_log', 'wp_dlm_log'); } add_action('admin_menu', 'wp_dlm_menu'); ################################################################################ // ADMIN HEADER ################################################################################ function wp_dlm_head() { global $wp_db_version, $wp_dlm_root; // Provide css based on wordpress version. if ($wp_db_version < 9872) { // 2.5 + 2.6 with new interface echo ''; } else { // 2.7 echo ''; } if ($_GET['activate'] && $_GET['activate']==true) { wp_dlm_init(); } ?> query($sql); $sql = "CREATE TABLE IF NOT EXISTS ".$wp_dlm_db_cats." ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `name` LONGTEXT NOT NULL , `parent` INT (12) UNSIGNED NOT NULL, PRIMARY KEY ( `id` ) )"; $result = $wpdb->query($sql); $sql = "CREATE TABLE IF NOT EXISTS ".$wp_dlm_db_formats." ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR (250) NOT NULL , `format` LONGTEXT NOT NULL, PRIMARY KEY ( `id` ) )"; $result = $wpdb->query($sql); $sql = "CREATE TABLE IF NOT EXISTS ".$wp_dlm_db_stats." ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `download_id` INT UNSIGNED NOT NULL, `date` DATE NOT NULL , `hits` INT (12) UNSIGNED NOT NULL, PRIMARY KEY ( `id` ) )"; $result = $wpdb->query($sql); $sql = "CREATE TABLE IF NOT EXISTS ".$wp_dlm_db_log." ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `download_id` INT UNSIGNED NOT NULL, `user_id` INT UNSIGNED NOT NULL, `date` DATETIME NULL , `ip_address` VARCHAR (200) NULL , PRIMARY KEY ( `id` ) )"; $result = $wpdb->query($sql); $sql = "CREATE TABLE IF NOT EXISTS ".$wp_dlm_db_meta." ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `meta_name` LONGTEXT NOT NULL , `meta_value` LONGTEXT NOT NULL , `download_id` INT (12) UNSIGNED NOT NULL, PRIMARY KEY ( `id` ) )"; $result = $wpdb->query($sql); $q = $wpdb->get_results("select * from $wp_dlm_db;"); if ( empty( $q ) ) { $wpdb->query("TRUNCATE table $wp_dlm_db"); } return; } ################################################################################ // Reinstall function ################################################################################ function wp_dlm_reinstall() { global $wpdb, $wp_dlm_db, $wp_dlm_db_cats; // GET OLD DATA $wpdb->show_errors; $query = sprintf("SELECT * from %s;", $wpdb->escape( $wp_dlm_db )); $result_d = $wpdb->get_results($query); if($result_d && $wpdb->num_rows>0) { $values=""; foreach($result_d as $d) { $id=$d->id; $title=$d->title; $filename=$d->filename; $dlversion=$d->dlversion; $postDate=$d->postDate; $hits=$d->hits; $user=$d->user; $members=$d->members; $category_id=$d->category_id; $mirrors=$d->mirrors; $file_description=$d->file_description; $values.='("'.$id.'","'.$title.'","'.$filename.'","'.$dlversion.'","'.$postDate.'","'.$hits.'","'.$user.'","'.$members.'","'.$category_id.'","'.$mirrors.'","'.$file_description.'"),'; } $values = substr_replace($values,"",-1); } $query = sprintf("SELECT * from %s;", $wpdb->escape( $wp_dlm_db_cats )); $result_cats = $wpdb->get_results($query); if($result_cats && $wpdb->num_rows>0) { $values2=""; foreach($result_cats as $d) { $id=$d->id; $name=$d->name; $parent=$d->parent; $values2.='("'.$id.'","'.$name.'","'.$parent.'"),'; } $values2 = substr_replace($values2,"",-1); } // DROP TABLES $sql = 'DROP TABLE IF EXISTS `'.$wp_dlm_db.'`'; $wpdb->query($sql); $sql = 'DROP TABLE IF EXISTS `'.$wp_dlm_db_cats.'`'; $wpdb->query($sql); wp_dlm_init(); // ADD OLD DATA if (!empty($values)) { $query_ins = sprintf("INSERT INTO %s (id, title, filename, dlversion, postDate, hits, user, members, category_id, mirrors, file_description) VALUES %s;", $wpdb->escape( $wp_dlm_db ), $values); $wpdb->query($query_ins); } if (!empty($values2)) { $query_ins = sprintf("INSERT INTO %s (id, name, parent) VALUES %s;", $wpdb->escape( $wp_dlm_db_cats ), $values2); $wpdb->query($query_ins); } } ################################################################################ // MAGIC QUOTES - checks if magic quotes enabled, disables the add_slashes on // inputs, so ensure add_slashes before interacting with the database ################################################################################ function wp_dlm_magic() { function stripit($in) { if (!is_array($in)) $out = stripslashes($in); else $out = $in; return $out; } if (get_magic_quotes_gpc()){ $_GET = array_map('stripit', $_GET); $_POST = array_map('stripit', $_POST); } return; } ################################################################################ // INSERT BUTTON ON POST SCREEN ################################################################################ function wp_dlm_ins_button() { //set globals global $table_prefix,$wpdb,$wp_dlm_db,$wp_dlm_db_cats; if( strpos($_SERVER['REQUEST_URI'], 'post.php') || strstr($_SERVER['PHP_SELF'], 'page-new.php') || strstr($_SERVER['PHP_SELF'], 'page.php') || strstr($_SERVER['PHP_SELF'], 'post-new.php') ) { // select all downloads $query_select = sprintf("SELECT * FROM %s ORDER BY id;", $wpdb->escape($wp_dlm_db)); $downloads = $wpdb->get_results($query_select); $js .= ''; $js .= ''; $js .= ''; $js .= ''; if (!empty($downloads)) { $js .= ''; foreach( $downloads as $d ) { $js .= ''; } $js .= ''; // select all cats $query_select_cats = sprintf("SELECT * FROM %s WHERE parent=0 ORDER BY id;", $wpdb->escape( $wp_dlm_db_cats )); $cats = $wpdb->get_results($query_select_cats); if (!empty($cats)) { $js .= ''; foreach ( $cats as $c ) { $js .= ''; $js .= addslashes(get_option_children_cats($c->id, "$c->name — ", 0)); } $js .= ''; } ?> escape($wp_dlm_db_formats), $wpdb->escape($id)); $format = $wpdb->get_row($query_select); return $format->format; } ################################################################################ // SHORTCODES ################################################################################ function wp_dlm_shortcode_download( $atts ) { extract(shortcode_atts(array( 'id' => '0', 'format' => '0', 'autop' => false ), $atts)); global $wpdb,$wp_dlm_root,$wp_dlm_db,$wp_dlm_db_formats,$wp_dlm_db_cats, $def_format, $dlm_url, $downloadurl, $downloadtype, $wp_dlm_db_meta; if ($id>0) { // Handle Formats if ($format==0 && $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 { // Format is set! $format = htmlspecialchars_decode($format); } if (empty($format) || $format=='0') { $format = '{title} ({hits})'; } // Get download info $d = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wp_dlm_db WHERE id = %s" , $id ) ); if ($d) { switch ($downloadtype) { case ("Title") : $downloadlink = urlencode($d->title); break; case ("Filename") : $downloadlink = $d->filename; $links = explode("/",$downloadlink); $downloadlink = end($links); break; default : $downloadlink = $d->id; break; } $format = str_replace('\\"',"'",$format); $fpatts = array('{url}', '{version}', '{title}', '{size}', '{hits}', '{image_url}', '{description}', '{description-autop}', '{category}'); $fsubs = array( $downloadurl.$downloadlink , $d->dlversion , $d->title , wp_dlm_get_size($d->filename) , $d->hits , get_option('wp_dlm_image_url') , $d->file_description , wpautop($d->file_description) ); // Category if ($d->category_id>0) { $c = $wpdb->get_row("SELECT name FROM $wp_dlm_db_cats where id=".$d->category_id." LIMIT 1;"); $fsubs[] = $c->name; preg_match("/{category,\"([^\"]*?)\",\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; $fsubs[] = $match[1].$c->name.$match[2]; } else { $fsubs[] = ""; preg_match("/{category,\"([^\"]*?)\",\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; $fsubs[] = ""; } // Hits (special) {hits, none, one, many) preg_match("/{hits,\"([^\"]*?)\",\"([^\"]*?)\",\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; if ( $d->hits == 1 ) { $text = str_replace('%',$d->hits,$match[2]); $fsubs[] = $text; } elseif ( $d->hits > 1 ) { $text = str_replace('%',$d->hits,$match[3]); $fsubs[] = $text; } else { $text = str_replace('%',$d->hits,$match[1]); $fsubs[] = $text; } // Version preg_match("/{version,\"([^\"]*?)\",\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; if ($d->dlversion) $fsubs[] = $match[1].$d->dlversion.$match[2]; else $fsubs[] = ""; // Other preg_match("/{description,\"([^\"]*?)\",\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; if ($d->file_description) $fsubs[] = $match[1].$d->file_description.$match[2]; else $fsubs[] = ""; preg_match("/{description-autop,\"([^\"]*?)\",\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; if ($d->file_description) $fsubs[] = $match[1].wpautop($d->file_description).$match[2]; else $fsubs[] = ""; // meta if (preg_match("/{meta-([^,]*?)}/", $format, $match)) { $meta_data = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wp_dlm_db_meta WHERE download_id = %s" , $id ) ); foreach($meta_data as $meta) { $fpatts[] = "{meta-".$meta->meta_name."}"; $fsubs[] = $meta->meta_value; $fpatts[] = "{meta-autop-".$meta->meta_name."}"; $fsubs[] = wpautop($meta->meta_value); } } $output = str_replace( $fpatts , $fsubs , $format ); } else $output = '[Download not found]'; } else $output = '[Download id not defined]'; if ($autop) return wpautop($output); return $output; } add_shortcode('download', 'wp_dlm_shortcode_download'); ################################################################################ // LEGACY TAGS SUPPORT ################################################################################ function wp_dlm_parse_downloads($data) { if (substr_count($data,"[download#")) { preg_match_all("/\[download#([0-9]+)#format=([0-9]+)\]/", $data, $matches, PREG_SET_ORDER); if ( sizeof( $matches ) > 0 ) foreach ($matches as $val) { $code = '[download id="'.$val[1].'" format="'.$val[2].'"]'; $data = str_replace( $val[0] , $code , $data ); } // End foreach // Handle Non-formatted downloads preg_match_all("/\[download#([0-9]+)/", $data, $matches, PREG_SET_ORDER); $patts = array(); $subs = array(); if ( sizeof( $matches ) > 0 ) foreach ($matches as $val) { $patts[] = "[download#" . $val[1] . "]"; $subs[] = '[download id="'.$val[1].'"]'; // No hit counter $format = '{title}'; $patts[] = "[download#" . $val[1] . "#nohits]"; $subs[] = '[download id="'.$val[1].'" format="'.htmlspecialchars($format).'"]'; // URL only $format = '{url}'; $patts[] = "[download#" . $val[1] . "#url]"; $subs[] = '[download id="'.$val[1].'" format="'.htmlspecialchars($format).'"]'; // Description only $format = '{description}'; $patts[] = "[download#" . $val[1] . "#description]"; $subs[] = '[download id="'.$val[1].'" format="'.htmlspecialchars($format).'"]'; // Description (autop) only $format = '{description-autop}'; $patts[] = "[download#" . $val[1] . "#description_autop]"; $subs[] = '[download id="'.$val[1].'" format="'.htmlspecialchars($format).'"]'; // Hits only $format = '{hits}';; $patts[] = "[download#" . $val[1] . "#hits]"; $subs[] = '[download id="'.$val[1].'" format="'.htmlspecialchars($format).'"]'; // Image link $format = ''.__('; $patts[] = "[download#" . $val[1] . "#image]"; $subs[] = '[download id="'.$val[1].'" format="'.htmlspecialchars($format).'"]'; // Regular download link WITH filesize $format = '{title} ({hits}) - {size}'; $patts[] = "[download#" . $val[1] . "#size]"; $subs[] = '[download id="'.$val[1].'" format="'.htmlspecialchars($format).'"]'; // No hit counter + filesize $format = '{title} ({size})'; $patts[] = "[download#" . $val[1] . "#size#nohits]"; $subs[] = '[download id="'.$val[1].'" format="'.htmlspecialchars($format).'"]'; } // End foreach $data = str_replace($patts, $subs, $data); } // End if [download# found global $wpdb, $wp_dlm_db, $wp_dlm_db_meta, $wp_dlm_db_cats, $downloadurl; // Handle CATEGORIES if (substr_count($data,"[download_cat#")) { $patts = array(); $subs = array(); preg_match_all("/\[download_cat#([0-9]+)#format=([0-9]+)\]/", $data, $result, PREG_SET_ORDER); if ($result) foreach ($result as $val) { $format = wp_dlm_get_custom_format($val[2]); if ($format) { $format = str_replace('\\"',"'",$format); // Traverse through categories to get sub-cats $the_cats = array(); $the_cats[] = $val[1]; $the_cats = wp_dlm_get_sub_cats($the_cats); // Get downloads for category and sub-categories $query = "SELECT * FROM $wp_dlm_db WHERE category_id IN (".implode(',',$the_cats).") ORDER BY 'title'"; $downloads = $wpdb->get_results($query); // GENERATE LIST $links = ''; $patts[] = "[download_cat#" . $val[1] . "#format=" . $val[2] . "]"; $subs[] = $links; } // End if format } // End foreach $data = str_replace($patts, $subs, $data); $patts = array(); $subs = array(); preg_match_all("|\[download_cat#([0-9]+)\]|U",$data,$result,PREG_SET_ORDER); if ($result) foreach ($result as $val) { // Traverse through categories to get sub-cats $the_cats = array(); $the_cats[] = $val[1]; $the_cats = wp_dlm_get_sub_cats($the_cats); // Get downloads for category and sub-categories $query ="SELECT * FROM $wp_dlm_db WHERE category_id IN (".implode(',',$the_cats).") ORDER BY 'title'"; $downloads = $wpdb->get_results($query); // GENERATE LIST $links = ''; $patts[] = "[download_cat#" . $val[1] . "]"; $subs[] = $links; } // endforeach $data = str_replace($patts, $subs, $data); } // End if [download_cat# found return $data; } ################################################################################ // File size formatting ################################################################################ function wp_dlm_get_size($path) { $path = str_replace(get_bloginfo('wpurl'),"./",$path); if (file_exists($path)) { $size = filesize($path); if ($size) { $bytes = array('bytes','KB','MB','GB','TB'); foreach($bytes as $val) { if($size > 1024){ $size = $size / 1024; }else{ break; } } return round($size, 2)." ".$val; } } } ################################################################################ // Get children categories ################################################################################ function get_option_children_cats($parent,$chain,$current,$showid=1) { global $wp_dlm_db_cats,$wpdb; $sql = sprintf("SELECT * FROM %s WHERE parent=%s ORDER BY id;", $wpdb->escape( $wp_dlm_db_cats ), $wpdb->escape( $parent )); $scats = $wpdb->get_results($sql); if (!empty($scats)) { foreach ( $scats as $c ) { $string.= ''; $string.= get_option_children_cats($c->id, "$chain$c->name — ",$current); } } return $string; } if (!function_exists('wp_dlm_get_sub_cats')) { function wp_dlm_get_sub_cats($the_cats) { global $wpdb, $wp_dlm_db_cats; $a=sizeof($the_cats); $query = sprintf("SELECT id from %s WHERE parent IN (%s);", $wpdb->escape( $wp_dlm_db_cats ), $wpdb->escape( implode(",",$the_cats) )); $res = $wpdb->get_results($query); if ($res) { foreach($res as $r) { if (!in_array($r->id, $the_cats)) $the_cats[]=$r->id; } } $b=sizeof($the_cats); if ($a!=$b) { $sub_cats = wp_dlm_get_sub_cats($the_cats); $the_cats = $the_cats + $sub_cats; } return $the_cats; } } ################################################################################ // ADMIN PAGE ################################################################################ function wp_dlm_admin() { //set globals global $wpdb,$wp_dlm_root,$wp_dlm_db,$wp_dlm_db_cats,$wp_dlm_db_formats,$wp_dlm_db_stats, $wp_dlm_db_meta, $wp_dlm_db_log; // turn off magic quotes wp_dlm_magic(); wp_dlm_update(); echo '
'; // DEFINE QUERIES // select all downloads if (empty( $_POST['dlhits'] )) $_POST['dlhits'] = 0; // select a downloads $query_select_1 = sprintf("SELECT * FROM %s WHERE id=%s;", $wpdb->escape( $wp_dlm_db ), $wpdb->escape( $_GET['id'] )); $action = $_GET['action']; if (!empty($action)) { switch ($action) { case "delete" : $d = $wpdb->get_row($query_select_1); global $wp_db_version; $adminpage = 'admin.php'; ?>

"title; ?>"

'.__('Required field: Title omitted',"wp-download_monitor").'
'; if (empty( $_POST['dlfilename'] ) && empty($_FILES['upload']['tmp_name'])) $errors.='
'.__('Required field: File URL omitted',"wp-download_monitor").'
'; if (empty( $_POST['dlhits'] )) $_POST['dlhits'] = 0; if (!is_numeric($_POST['dlhits'] )) $errors.='
'.__('Invalid hits entered',"wp-download_monitor").'
'; $members = (isset($_POST['memberonly'])) ? 1 : 0; $removefile = (isset($_POST['removefile'])) ? 1 : 0; if (empty($errors)) { if (!empty($_FILES['upload']['tmp_name'])) { $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; if ( strstr ( $d->filename, "/wp-content/uploads/" ) ) { $path = get_bloginfo('wpurl')."/wp-content/uploads/"; $file = str_replace( $path , "" , $d->filename); if(is_file('../wp-content/uploads/'.$file)){ chmod('../wp-content/uploads/'.$file, 0777); unlink('../wp-content/uploads/'.$file); } } } $file = wp_handle_upload($_FILES['upload'], $overrides, $time); if ( !isset($file['error']) ) { $full_path = $file['url']; $info = $file['url']; $filename = $file['url']; } else $errors = '
'.$file['error'].'
'; // update download & file $query_update_file = sprintf("UPDATE %s SET title='%s', dlversion='%s', hits='%s', filename='%s', postDate='%s', user='%s',members='%s',category_id='%s', mirrors='%s', file_description='%s' WHERE id=%s;", $wpdb->escape( $wp_dlm_db ), $wpdb->escape( $_POST['title'] ), mysql_real_escape_string( $_POST['dlversion'] ), mysql_real_escape_string( $_POST['dlhits'] ), $wpdb->escape( $filename ), $wpdb->escape( $_POST['postDate'] ), $wpdb->escape( $_POST['user'] ), $wpdb->escape( $members ), $wpdb->escape( $_POST['download_cat'] ), $wpdb->escape( trim($_POST['mirrors']) ) , $wpdb->escape( trim($_POST['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'].""); $index = 1; $values = array(); if ($_POST['meta']) foreach ($_POST['meta'] as $meta) { if (trim($meta['key'])) { $values[] = '("'.$wpdb->escape(strtolower((str_replace(' ','-',trim($meta['key']))))).'", "'.$wpdb->escape($meta['value']).'", '.$_GET['id'].')'; $index ++; } } $wpdb->query("INSERT INTO $wp_dlm_db_meta (meta_name, meta_value, download_id) VALUES ".implode(',', $values).""); echo '

'.__('Download edited Successfully',"wp-download_monitor").' - '.$info.'

'; } else { //not replacing file $query_update = sprintf("UPDATE %s SET title='%s', dlversion='%s', hits='%s', filename='%s',members='%s',category_id='%s', mirrors='%s', file_description='%s' WHERE id=%s;", $wpdb->escape( $wp_dlm_db ), $wpdb->escape( $_POST['title'] ), mysql_real_escape_string( $_POST['dlversion'] ), mysql_real_escape_string( $_POST['dlhits'] ), $wpdb->escape( $_POST['dlfilename'] ), $wpdb->escape( $members ), $wpdb->escape( $_POST['download_cat'] ), $wpdb->escape( trim($_POST['mirrors']) ) , $wpdb->escape( trim($_POST['file_description']) ) , $wpdb->escape( $_GET['id'] )); $d = $wpdb->get_row($query_update); $show=true; // Process and save meta/custom fields $wpdb->query("DELETE FROM $wp_dlm_db_meta WHERE download_id = ".$_GET['id'].""); $index = 1; $values = array(); if ($_POST['meta']) foreach ($_POST['meta'] as $meta) { if (trim($meta['key'])) { $values[] = '("'.$wpdb->escape(strtolower((str_replace(' ','-',trim($meta['key']))))).'", "'.$wpdb->escape($meta['value']).'", '.$_GET['id'].')'; $index ++; } } $wpdb->query("INSERT INTO $wp_dlm_db_meta (meta_name, meta_value, download_id) VALUES ".implode(',', $values).""); echo '

'.__('Download edited Successfully',"wp-download_monitor").'

'; } } 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; $download_cat = $d->category_id; $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(); if ($fields) foreach ($fields as $meta) { $custom_fields[$index]['key'] = $meta->meta_name; $custom_fields[$index]['value'] = $meta->meta_value; $custom_fields[$index]['remove'] = 0; $index++; } } if ($show==false) { $max_upload_size_text = ''; if (function_exists('ini_get')) { $max_upload_size = min(let_to_num(ini_get('post_max_size')), 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 = ''; } ?>

:
:
:
:

/>
:


= .
/>
" /> user_login.'" />'; ?>

Some Name will become some-name.',"wp-download_monitor"); ?>

'; } } $index ++; } if ($_POST['addmeta']) { echo ''; } ?>
" type="submit">

" />

get_row($query_select_1); $file = $d->filename; if ( strstr ( $d->filename, "/wp-content/uploads/" ) ) { $path = get_bloginfo('wpurl')."/wp-content/uploads/"; $file = str_replace( $path , "" , $d->filename); if(is_file('../wp-content/uploads/'.$file)){ chmod('../wp-content/uploads/'.$file, 0777); unlink('../wp-content/uploads/'.$file); } } $query_delete = sprintf("DELETE FROM $wp_dlm_db WHERE id=%s;", $wpdb->escape( $_GET['id'] )); $wpdb->query($query_delete); $query_delete = sprintf("DELETE FROM $wp_dlm_db_stats WHERE download_id=%s;", $wpdb->escape( $_GET['id'] )); $wpdb->query($query_delete); $query_delete = sprintf("DELETE FROM $wp_dlm_db_log WHERE download_id=%s;", $wpdb->escape( $_GET['id'] )); $wpdb->query($query_delete); $query_delete = sprintf("DELETE FROM $wp_dlm_db_meta WHERE download_id=%s;", $wpdb->escape( $_GET['id'] )); $wpdb->query($query_delete); echo '

'.__('Download deleted Successfully',"wp-download_monitor").'

'; // 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; } } //show downloads page if ( ($show==true) || ( empty($action) ) ) { global $downloadurl, $downloadtype; ?>


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.*, $wp_dlm_db_cats.parent, $wp_dlm_db_cats.name FROM $wp_dlm_db LEFT JOIN $wp_dlm_db_cats ON $wp_dlm_db.category_id = $wp_dlm_db_cats.id %s ORDER BY %s LIMIT %s,20;", $search, $wpdb->escape( $sort ), $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 ''; foreach ( $download as $d ) { $date = date("jS M Y", strtotime($d->postDate)); $path = get_bloginfo('wpurl')."/wp-content/uploads/"; $file = str_replace($path, "", $d->filename); $links = explode("/",$file); $file = end($links); echo (''); echo ''; if (strlen($d->file_description) > 50) $file_description = substr(htmlspecialchars($d->file_description), 0, strrpos(substr(htmlspecialchars($d->file_description), 0, 50), ' ')) . ' [...]'; else $file_description = htmlspecialchars($d->file_description); echo ''; } echo ''; } else echo ''; // FIXED: 1.6 - Colspan changed ?>
'.$d->id.' '.$d->title.' '.$file.' '; if ($d->category_id=="" || $d->category_id==0) echo "N/A"; else { //$c = $wpdb->get_row("SELECT * FROM $wp_dlm_db_cats where id=".$d->category_id." LIMIT 1;"); //$chain = $c->name; $chain = $d->name; $c = $d->parent; while ($c>0) { $c = $wpdb->get_row("SELECT * FROM $wp_dlm_db_cats where id=".$c->parent." LIMIT 1;"); $chain = $d->name.' — '.$chain; } echo $d->category_id." - ".$chain; } echo ' '.$d->dlversion.''.nl2br($file_description).' '; if ($d->members) echo __('Yes',"wp-download_monitor"); else echo __('No',"wp-download_monitor"); echo ' '.$date.' by '.$d->user.' '; echo $wpdb->get_var('SELECT COUNT(id) FROM '.$wp_dlm_db_meta.' WHERE download_id = '.$d->id.''); echo ' '.$d->hits.' Edit Delete
'.__('No downloads added yet.',"wp-download_monitor").'
1) { // FIXED: 1.6 - Stops it displaying when un-needed // Build Page Number Hyperlinks if($page > 1){ $prev = ($page - 1); echo "« ".__('Previous',"wp-download_monitor")." "; } else echo "« ".__('Previous',"wp-download_monitor").""; for($i = 1; $i <= $total_pages; $i++){ if(($page) == $i){ echo " $i "; } else { echo " $i "; } } // Build Next Link if($page < $total_pages){ $next = ($page + 1); echo "".__('Next',"wp-download_monitor")." »"; } else echo "".__('Next',"wp-download_monitor")." »"; } ?>


Need help? FAQ, Usage instructions and other notes can be found on the plugin page here.

',"wp-download_monitor"); ?> The Wordpress Download monitor plugin was created by Mike Jolley. 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 to ensure continued development.

',"wp-download_monitor"); ?>
'; } ################################################################################ // Configuration page ################################################################################ function wp_dlm_config() { //set globals global $wpdb,$wp_dlm_root,$wp_dlm_db,$wp_dlm_db_cats,$wp_dlm_db_formats,$dlm_url; // turn off magic quotes wp_dlm_magic(); wp_dlm_update(); ?>

'; _e('

Download URL updated - You need to re-save your permalinks settings (Options/settings -> Permalinks) for the changes to occur in your blog.

If your .htaccess file cannot be written to by WordPress, add the following to your .htaccess file above the "# BEGIN WordPress" line:

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^download/(.*) wp-content/plugins/download-monitor/download.php?id=$1 [L]

replacing "download/" with your custom url.

',"wp-download_monitor"); echo '
'; } else { echo '
'; _e('

Download URL updated - You need to re-save your permalinks settings (Options/settings -> Permalinks) for the changes to occur in your blog.

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:

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^download/(.*) wp-content/plugins/download-monitor/download.php?id=$1 [L]

replacing "download/" with your previous custom url.

',"wp-download_monitor"); echo '
'; } $save_url = true; $show=true; break; case "saveoptions" : 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']); $save_opt=true; echo '
'; _e('

Options updated

',"wp-download_monitor"); echo '
'; $show=true; break; case "categories" : $name = $_POST['cat_name']; if (!empty($name)) { $parent = $_POST['cat_parent']; if (!$parent) $parent=0; $query_ins = sprintf("INSERT INTO %s (name, parent) VALUES ('%s','%s')", $wpdb->escape( $wp_dlm_db_cats ), $wpdb->escape( $name ), $wpdb->escape( $parent )); $wpdb->query($query_ins); echo '

'.__('Category added',"wp-download_monitor").'

'; $ins_cat=true; } $show=true; break; case "deletecat" : $id = $_GET['id']; // Get 'em $delete_cats=array(); $delete_cats[]=$id; // Sub cats function dlm_get_cats($delete_cats) { global $wpdb, $wp_dlm_db_cats; $query = sprintf("SELECT id from %s WHERE parent IN (%s);", $wpdb->escape( $wp_dlm_db_cats ), $wpdb->escape( implode(",",$delete_cats) )); $res = $wpdb->get_results($query); $b=sizeof($delete_cats); if ($res) { foreach($res as $r) { if (!in_array($r->id,$delete_cats)) $delete_cats[]=$r->id; } } $a=sizeof($delete_cats); while ($b!=$a) { $query = sprintf("SELECT id from %s WHERE parent IN (%s);", $wpdb->escape( $wp_dlm_db_cats ), $wpdb->escape( implode(",",$delete_cats) )); $res = $wpdb->get_results($query); $b=sizeof($delete_cats); if ($res) { foreach($res as $r) { if (!in_array($r->id,$delete_cats)) $delete_cats[]=$r->id; } } $a=sizeof($delete_cats); } return $delete_cats; } $delete_cats = dlm_get_cats($delete_cats); // Delete $query_delete = sprintf("DELETE FROM %s WHERE id IN (%s);", $wpdb->escape( $wp_dlm_db_cats ), $wpdb->escape( implode(",",$delete_cats) )); $wpdb->query($query_delete); // Remove from downloads $query_update = sprintf("UPDATE %s SET category_id='N/A' WHERE category_id IN (%s);", $wpdb->escape( $wp_dlm_db ), $wpdb->escape( implode(",",$delete_cats) )); $d = $wpdb->get_row($query_update); echo '

'.__('Category deleted Successfully',"wp-download_monitor").'

'; $ins_cat=true; $show=true; break; case "reinstall" : wp_dlm_reinstall(); echo '

'.__('Database recreated',"wp-download_monitor").'

'; $show=true; break; case "formats" : if ($_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 '

'.__('Formats updated',"wp-download_monitor").'

'; $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 '

'.__('Format added',"wp-download_monitor").'

'; $ins_format=true; } } $show=true; break; case "deleteformat" : $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 '

'.__('Format deleted Successfully',"wp-download_monitor").'

'; $ins_format=true; $show=true; break; } } if ( ($show==true) || ( empty($action) ) ) { ?>

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.

',"wp-download_monitor"); ?>
escape( $wp_dlm_db_cats ), $wpdb->escape( $parent )); $scats = $wpdb->get_results($sql); if (!empty($scats)) { foreach ( $scats as $c ) { echo ''; get_children_cats($c->id, "$chain$c->name — "); } } return; } $query_select_cats = sprintf("SELECT * FROM %s WHERE parent=0 ORDER BY id;", $wpdb->escape( $wp_dlm_db_cats )); $cats = $wpdb->get_results($query_select_cats); if (!empty($cats)) { foreach ( $cats as $c ) { echo ''; get_children_cats($c->id, "$c->name — "); } } else { echo ''; } ?>
'.$c->id.''.$chain.''.$c->name.'Delete
'.$c->id.''.$c->name.'Delete
'.__('No categories exist',"wp-download_monitor").'

:
:

" />

This allows you to define formats in which to output your downloads however you want.

',"wp-download_monitor"); ?>
escape( $wp_dlm_db_formats )); $formats = $wpdb->get_results($query_select_formats); if (!empty($formats)) { foreach ( $formats as $f ) { echo ''; } } else { echo ''; } ?>
'.$f->id.''.$f->name.' Delete
'.__('No formats exist',"wp-download_monitor").'

" />

Use the following tags in your custom formats: note if you use " (quote) characters within the special attributes e.g. "before" you should either escape them or use html entities.

  • {url} - Url of download (does not include hyperlink)
  • {version} - Version of download
  • {version,"before","after"} - Version of download. Not outputted if none set. Replace "before" with preceding text/html and "after" with succeeding text/html.
  • {title} - Title of download
  • {size} - Filesize of download
  • {category,"before","after"} or {category} - Download Category. Replace "before" with preceding text/html and "after" with succeeding text/html.
  • {hits} - Current hit count
  • {hits,"No hits","1 Hit","% hits"} - Formatted hit count depending on hits. % replaced with hit count.
  • {image_url} - URL of the download image
  • {description,"before","after"} or {description} - Description you gave download. Not outputted if none set. Replace "before" with preceding text/html and "after" with succeeding text/html.
  • {description-autop,"before","after"} or {description-autop} - Description formatted with autop (converts double line breaks to paragraphs)
  • {meta-key} - Custom field value
  • {meta-autop-key} - Custom field value formatted with autop

Example Format - Link and description of download with hits in title:

<a href="{url}" title="Downloaded {hits} times">{title}</a> - {description}

',"wp-download_monitor"); ?>
:
:

" />

Set a custom url for your downloads, e.g. download/. You can also choose how to link to the download in it\'s url, e.g. selecting "filename" would make the link appear as http://yoursite.com/download/filename.zip.

Leave this option blank to use the default download path (wp-content/plugins/download-monitor/download.php?id=)

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.

',"wp-download_monitor"); ?> Explanation
: /

" />

: Leave blank for no redirect.
: Leave blank for no redirect.
: #image download tag and the {image_url} tag on this page. Please use an absolute url (e.g. http://yoursite.com/image.gif).',"wp-download_monitor"); ?>
:

" />

This will delete the old download monitor tables and recreate them. You should only do this as a last resort if experiencing database errors after updating the plugin. Download monitor will attempt to re-add any downloads currently in the database.

',"wp-download_monitor"); ?> WARNING: THIS MAY DELETE DOWNLOAD DATA IN THE DATABASE; BACKUP YOUR DATABASE FIRST!

',"wp-download_monitor"); ?>

" />

'; } ################################################################################ // let_to_num used for file sizes ################################################################################ function let_to_num($v){ //This function transforms the php.ini notation for numbers (like '2M') to an integer (2*1024*1024 in this case) $l = substr($v, -1); $ret = substr($v, 0, -1); switch(strtoupper($l)){ case 'P': $ret *= 1024; case 'T': $ret *= 1024; case 'G': $ret *= 1024; case 'M': $ret *= 1024; case 'K': $ret *= 1024; break; } return $ret; } ################################################################################ // Add Download Page ################################################################################ function dlm_addnew() { //set globals global $wpdb,$wp_dlm_root,$wp_dlm_db,$wp_dlm_db_cats,$wp_dlm_db_formats,$wp_dlm_db_meta; // turn off magic quotes wp_dlm_magic(); wp_dlm_update(); ?>

Required field: Title omitted
',"wp-download_monitor"); if (empty( $_POST['dlhits'] )) $_POST['dlhits'] = 0; if (!is_numeric($_POST['dlhits'] )) $errors.=__('
Invalid hits entered
',"wp-download_monitor"); //attempt to upload file if ( empty($errors ) ) { $time = current_time('mysql'); $overrides = array('test_form'=>false); $file = wp_handle_upload($_FILES['upload'], $overrides, $time); if ( !isset($file['error']) ) { $full_path = $file['url']; $info = $file['url']; $filename = $file['url']; } else $errors = '
'.$file['error'].'
'; } //save to db if ( empty($errors ) ) { // Add download $query_add = sprintf("INSERT INTO %s (title, filename, dlversion, postDate, hits, user, members,category_id, mirrors, file_description) VALUES ('%s','%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($download_cat), $wpdb->escape($mirrors), $wpdb->escape($file_description) ); $result = $wpdb->query($query_add); if ($result) { // Process and save meta/custom fields $index = 1; $values = array(); if ($_POST['meta']) foreach ($_POST['meta'] as $meta) { if (trim($meta['key'])) { $values[] = '("'.$wpdb->escape(strtolower((str_replace(' ','-',trim($meta['key']))))).'", "'.$wpdb->escape($meta['value']).'", '.$wpdb->insert_id.')'; $index ++; } } $wpdb->query("INSERT INTO $wp_dlm_db_meta (meta_name, meta_value, download_id) VALUES ".implode(',', $values).""); if (empty($info)) echo '

'.__("Download added Successfully","wp-download_monitor").'

'; else echo '

'.__("Download added Successfully","wp-download_monitor").' - '.$info.'

'; // Redirect echo ''; exit; } else _e('
Error saving to database
',"wp-download_monitor"); } else echo $errors; } $max_upload_size_text = ''; if (function_exists('ini_get')) { $max_upload_size = min(let_to_num(ini_get('post_max_size')), 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 = ''; } ?>
:
:
:
:

= .

/>

Some Name will become some-name.',"wp-download_monitor"); ?>

'; } } $index ++; } if ($_POST['addmeta']) { echo ''; } } ?>
" type="submit">

" />

" /> user_login.'" />'; ?>
'; } ################################################################################ // Add Existing Download Page ################################################################################ function dlm_addexisting() { //set globals global $wpdb,$wp_dlm_root,$wp_dlm_db,$wp_dlm_db_cats,$wp_dlm_db_formats,$wp_dlm_db_meta; // turn off magic quotes wp_dlm_magic(); wp_dlm_update(); ?>

Required field: Title omitted
',"wp-download_monitor"); if (empty( $_POST['dlhits'] )) $_POST['dlhits'] = 0; if (!is_numeric($_POST['dlhits'] )) $errors.=__('
Invalid hits entered
',"wp-download_monitor"); if ( empty( $_POST['filename']) ) $errors.=__('
No file selected
',"wp-download_monitor"); //save to db if ( empty($errors ) ) { $query_add = sprintf("INSERT INTO %s (title, filename, dlversion, postDate, hits, user, members,category_id, mirrors, file_description) VALUES ('%s','%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($download_cat), $wpdb->escape($mirrors), $wpdb->escape($file_description) ); $result = $wpdb->query($query_add); if ($result) { // Process and save meta/custom fields $index = 1; $values = array(); if ($_POST['meta']) foreach ($_POST['meta'] as $meta) { if (trim($meta['key'])) { $values[] = '("'.$wpdb->escape(strtolower((str_replace(' ','-',trim($meta['key']))))).'", "'.$wpdb->escape($meta['value']).'", '.$wpdb->insert_id.')'; $index ++; } } $wpdb->query("INSERT INTO $wp_dlm_db_meta (meta_name, meta_value, download_id) VALUES ".implode(',', $values).""); if (empty($info)) echo '

'.__("Download added Successfully","wp-download_monitor").'

'; else echo '

'.__("Download added Successfully","wp-download_monitor").' - '.$info.'

'; // Redirect echo ''; exit; } else _e('
Error saving to database
',"wp-download_monitor"); } else echo $errors; } ?>
:
:
:
:
:

/>

Some Name will become some-name.',"wp-download_monitor"); ?>

'; } } $index ++; } if ($_POST['addmeta']) { echo ''; } } ?>
" type="submit">

" />

" /> user_login.'" />'; ?>
'; } ################################################################################ // LOG VIEWER PAGE ################################################################################ function wp_dlm_log() { //set globals global $wpdb,$wp_dlm_root,$wp_dlm_db,$wp_dlm_db_cats,$wp_dlm_db_formats, $wp_dlm_db_log; wp_dlm_update(); echo '
'; $action = $_GET['action']; if (!empty($action)) { switch ($action) { case "clear_logs" : $wpdb->query("DELETE FROM $wp_dlm_db_log;"); break; } } ?>

escape( $from )); $logs = $wpdb->get_results($paged_select); $total = $wpdb->get_var("SELECT COUNT(id) FROM $wp_dlm_db_log;"); // Figure out the total number of pages. Always round up using ceil() $total_pages = ceil($total / 20); if (!empty($logs)) { echo ''; foreach ( $logs as $log ) { $date = date("jS M Y", strtotime($log->date)); $path = get_bloginfo('wpurl')."/wp-content/uploads/"; $file = str_replace($path, "", $log->filename); $links = explode("/",$file); $file = end($links); echo ''; echo ''; } echo ''; } else echo ''; ?>
'.$log->id.' '.$log->title.' '.$file.' '; if ($log->user_id) { $user_info = get_userdata($log->user_id); echo $user_info->user_login . ' ('.$user_info->ID.')'; } echo ' '.$log->ip_address.' '.$date.'
'.__('No downloads logged.',"wp-download_monitor").'
1) { // Build Page Number Hyperlinks if($page > 1){ $prev = ($page - 1); echo "« ".__('Previous',"wp-download_monitor")." "; } else echo "« ".__('Previous',"wp-download_monitor").""; for($i = 1; $i <= $total_pages; $i++){ if(($page) == $i){ echo " $i "; } else { echo " $i "; } } // Build Next Link if($page < $total_pages){ $next = ($page + 1); echo "".__('Next',"wp-download_monitor")." »"; } else echo "".__('Next',"wp-download_monitor")." »"; } ?>

strlen($base_url)) $offset = substr(str_replace($base_url, '', $blog), 1) . '/'; else $offset = ''; $rule = (' Options +FollowSymLinks RewriteEngine on RewriteRule ^'.$offset.$dlm_url.'(.*)$ '.$offset.'wp-content/plugins/download-monitor/download.php?id=$1 [L] '); return $rule.$rewrite; } // Hook in. global $dlm_url; if (!empty($dlm_url)) add_filter('mod_rewrite_rules', 'wp_dlm_rewrite'); ################################################################################ // Main template tag (get) function ################################################################################ class download_object { var $id; var $url; var $size; var $version; var $image; var $desc; var $category; var $category_id; var $memberonly; var $dlversion; var $file_description; var $postDate; var $members; var $filename; var $hits; var $user; var $mirrors; var $title; } function get_downloads($args = null) { global $wpdb,$wp_dlm_root, $wp_dlm_db, $wp_dlm_db_cats, $dlm_url, $downloadurl, $downloadtype; $defaults = array( 'limit' => '', 'offset' => 0, 'vip' => 0, 'category' => '', 'orderby' => 'id', 'order' => 'ASC' ); $r = wp_parse_args( $args, $defaults ); $where = array(); if ( empty( $r['limit'] ) || !is_numeric($r['limit']) ) $r['limit'] = ''; if ( !empty( $r['limit'] ) && (empty($r['offset']) || !is_numeric($r['offset'])) ) $r['offset'] = 0; else $r['offset'] = ''; if ( !empty( $r['limit'] ) ) $limitandoffset = ' LIMIT '.$r['offset'].', '.$r['limit'].' '; if ( ! empty($r['category']) ) { $categories = explode(',',$r['category']); $the_cats = array(); // Traverse through categories to get sub-cats foreach ($categories as $cat) { $the_cats[] = $cat; $the_cats = wp_dlm_get_sub_cats($the_cats); } $categories = implode(',',$the_cats); $where[] = ' category_id IN ('.$categories.') '; } else $category = ''; if ( $vip==1 ) { global $user_ID; // If not logged in dont show member only files if (!isset($user_ID)) { $where[] = ' members = 0 '; } } if ( ! empty($r['orderby']) ) { // Can order by date/postDate, filename, title, id, hits, random $r['orderby'] = strtolower($r['orderby']); switch ($r['orderby']) { case 'postdate' : case 'date' : $orderby = 'postDate'; break; case 'filename' : $orderby = 'filename'; break; case 'title' : $orderby = 'title'; break; case 'hits' : $orderby = 'hits'; break; case 'rand' : case 'random' : $orderby = 'RAND()'; break; case 'id' : default : $orderby = $wp_dlm_db.'.id'; break; } } if (strtolower($r['order'])!='desc' && strtolower($r['order'])!='asc') $r['order']='desc'; // Process where clause if (sizeof($where)>0) $where = ' WHERE '.implode(' AND ', $where); else $where = ''; $downloads = $wpdb->get_results( "SELECT $wp_dlm_db.*, $wp_dlm_db_cats.parent, $wp_dlm_db_cats.name FROM $wp_dlm_db LEFT JOIN $wp_dlm_db_cats ON $wp_dlm_db.category_id = $wp_dlm_db_cats.id ".$where." ORDER BY $orderby ".$r['order']." ".$limitandoffset.";" ); $return_downloads = array(); // Process download variables foreach ($downloads as $dl) { switch ($downloadtype) { case ("Title") : $downloadlink = urlencode($dl->title); break; case ("Filename") : $downloadlink = $dl->filename; $link = explode("/",$downloadlink); $downloadlink = end($link); break; default : $downloadlink = $dl->id; break; } $d = new download_object; // Can use size, url, title, version, hits, image, desc, category, category_id, id, date, memberonly $d->id = $dl->id; $d->title = $dl->title; $d->filename = $dl->filename; $d->mirrors = $dl->mirrors; $d->user = $dl->user; $d->hits = $dl->hits; $d->members = $dl->members; $d->postDate = $dl->postDate; $d->file_description = $dl->file_description; $d->dlversion = $dl->dlversion; $d->size = wp_dlm_get_size($dl->filename); $d->url = $downloadurl.$downloadlink; $d->version = $dl->dlversion; $d->image = get_option('wp_dlm_image_url'); $d->desc = $dl->file_description; $d->category = $dl->name; $d->category_id = $dl->category_id; $d->date = $dl->postDate; $d->memberonly = $dl->members; $return_downloads[] = $d; } return $return_downloads; } ################################################################################ // SHORTCODE FOR MULTIPLE DOWNLOADS ################################################################################ function wp_dlm_shortcode_downloads( $atts ) { extract(shortcode_atts(array( 'query' => 'limit=5&orderby=rand', 'format' => 0, 'autop' => false, 'wrap' => 'ul', 'before' => '
  • ', 'after' => '
  • ' ), $atts)); global $wpdb,$wp_dlm_root,$wp_dlm_db,$wp_dlm_db_formats,$wp_dlm_db_cats, $def_format, $wp_dlm_db_meta; $dl = get_downloads($query); if (!empty($dl)) { // Handle Formats if ($format==0 && $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 { // Format is set! $format = htmlspecialchars_decode($format); } if (empty($format) || $format=='0') { $format = '{title} ({hits})'; } $format = str_replace('\\"',"'",$format); foreach ($dl as $d) { $fpatts = array('{url}', '{version}', '{title}', '{size}', '{hits}', '{image_url}', '{description}', '{description-autop}', '{category}'); $fsubs = array( $d->url , $d->version , $d->title , $d->size , $d->hits , get_option('wp_dlm_image_url') , $d->desc , wpautop($d->desc) ); // Category if ($d->category_id>0) { $fsubs[] = $d->category; preg_match("/{category,\"([^\"]*?)\",\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; $fsubs[] = $match[1].$d->category.$match[2]; } else { $fsubs[] = ""; preg_match("/{category,\"([^\"]*?)\",\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; $fsubs[] = ""; } // Hits (special) {hits, none, one, many) preg_match("/{hits,\"([^\"]*?)\",\"([^\"]*?)\",\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; if ( $d->hits == 1 ) { $text = str_replace('%',$d->hits,$match[2]); $fsubs[] = $text; } elseif ( $d->hits > 1 ) { $text = str_replace('%',$d->hits,$match[3]); $fsubs[] = $text; } else { $text = str_replace('%',$d->hits,$match[1]); $fsubs[] = $text; } // Version preg_match("/{version,\"([^\"]*?)\",\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; if ($d->version) $fsubs[] = $match[1].$d->version.$match[2]; else $fsubs[] = ""; // Other preg_match("/{description,\"([^\"]*?)\",\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; if ($d->desc) $fsubs[] = $match[1].$d->desc.$match[2]; else $fsubs[] = ""; preg_match("/{description-autop,\"([^\"]*?)\",\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; if ($d->desc) $fsubs[] = $match[1].wpautop($d->desc).$match[2]; else $fsubs[] = ""; // meta if (preg_match("/{meta-([^,]*?)}/", $format, $match)) { $meta_data = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wp_dlm_db_meta WHERE download_id = %s" , $d->id ) ); foreach($meta_data as $meta) { $fpatts[] = "{meta-".$meta->meta_name."}"; $fsubs[] = $meta->meta_value; $fpatts[] = "{meta-autop-".$meta->meta_name."}"; $fsubs[] = wpautop($meta->meta_value); } } $output .= htmlspecialchars_decode($before).str_replace( $fpatts , $fsubs , $format ).htmlspecialchars_decode($after); } } else $output = '[Downloads not found]'; if ($wrap=='ul') { $output = '
      '.$output.'
    '; } if ($autop) return wpautop($output); return $output; } add_shortcode('downloads', 'wp_dlm_shortcode_downloads'); ################################################################################ // LEGACY TEMPLATE TAGS ################################################################################ function wp_dlm_show_downloads($mode = 1,$no = 5) { switch ($mode) { case 1 : $dl = get_downloads('limit='.$no.'&orderby=hits&order=desc'); break; case 2 : $dl = get_downloads('limit='.$no.'&orderby=date&order=desc'); break; case 3 : $dl = get_downloads('limit='.$no.'&orderby=random&order=desc'); break; } if (!empty($dl)) { echo ''; } } function wp_dlm_all() { global $wpdb,$wp_dlm_root,$allowed_extentions,$max_upload_size,$wp_dlm_db; $dl = get_downloads('limit=&orderby=title&order=asc'); if (!empty($dl)) { $retval = ''; } return $retval; } function wp_dlm_advanced() { global $wpdb,$wp_dlm_root,$wp_dlm_db,$wp_dlm_db_cats,$downloadurl,$dlm_url,$downloadtype; // Get post data $showing = (int) $_POST['show_downloads']; if ($showing==0 || $showing=="") { $dl = get_downloads('limit=10&orderby=hits&order=desc'); } else { $dl = get_downloads('limit=&orderby=title&order=asc&category='.$showing.''); } // Output selector box $retval = '
    '; if (!empty($dl)) { $retval .= ''; } else $retval .='

    '.__('No Downloads Found',"wp-download_monitor").'

    '; $retval .= "
    "; return $retval; } function wp_dlm_parse_downloads_all($data) { if (substr_count($data,"[#show_downloads]")) { $data = str_replace("[#show_downloads]",wp_dlm_all(), $data); } if (substr_count($data,"[#advanced_downloads]")) { $data = str_replace("[#advanced_downloads]",wp_dlm_advanced(), $data); } return $data; } ################################################################################ // Gap filler for dates/stats ################################################################################ if (!function_exists('dlm_fill_date_gaps')) { function dlm_fill_date_gaps($prev, $date, $gapcalc, $dateformat) { global $wp_dlm_root; $string = array(); $loop = 0; while ( $date>$prev ) : $date = strtotime($gapcalc, $date ); $string[] = ' '.date($dateformat, $date ).' 0 '; $loop++; endwhile; return implode('',array_reverse($string)); } } ################################################################################ // Dashboard widgets ################################################################################ // Only for wordpress 2.5 and above! if ($wp_db_version > 6124) { class wp_dlm_dash { // Class initialization function wp_dlm_dash() { // Add to dashboard add_action( 'wp_dashboard_setup', array(&$this, 'register_widget') ); add_filter( 'wp_dashboard_widgets', array(&$this, 'add_widget') ); } // Register the widget for dashboard use function register_widget() { global $wp_db_version; $adminpage = 'admin.php'; wp_register_sidebar_widget( 'download_monitor_dash', __( 'Download Stats', 'wp-download_monitor' ), array(&$this, 'widget') ); } // Insert into dashboard function add_widget( $widgets ) { global $wp_registered_widgets; if ( !isset($wp_registered_widgets['download_monitor_dash']) ) return $widgets; array_splice( $widgets, 2, 0, 'download_monitor_dash' ); return $widgets; } // Output the widget function widget( $args ) { if (is_array($args)) extract( $args, EXTR_SKIP ); echo $before_widget; echo $before_title; echo $widget_name; echo $after_title; global $wp_dlm_db,$wpdb,$wp_dlm_db_stats, $wp_dlm_root; // select all downloads $downloads = $wpdb->get_results("SELECT * FROM $wp_dlm_db ORDER BY id;"); // Get stats for download if ($_REQUEST['download_stats_id']>0) $d = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wp_dlm_db WHERE id = %s LIMIT 1;", $_REQUEST['download_stats_id'] )); else $d = 0; if ($_REQUEST['show_download_stats']=='monthly') $stattype = 'monthly'; else $stattype = 'weekly'; // Get post/get data $period = $_GET['download_stats_period']; if (!$period || !is_numeric($period)) $period = '-1'; else $period = $period-1; $mindate = $wpdb->get_var( $wpdb->prepare("SELECT MIN(date) FROM $wp_dlm_db_stats;", $d->id)); if ($stattype=='weekly') { if ($period<-1) $maxdate = strtotime(($period+1).' week'); else $maxdate = strtotime(date('Y-m-d')); // get stats $max = $wpdb->get_var( $wpdb->prepare("SELECT MAX(hits) FROM $wp_dlm_db_stats WHERE download_id = %s AND date>=%s AND date<=%s;", $d->id, date('Y-m-d', strtotime("".$period." week") ), date('Y-m-d', strtotime("".($period+1)." week") ) )); $stats = $wpdb->get_results( $wpdb->prepare("SELECT *, hits as thehits FROM $wp_dlm_db_stats WHERE download_id = %s AND date>=%s AND date<=%s ORDER BY date ASC LIMIT 7;", $d->id, date('Y-m-d', strtotime("".$period." week") ), date('Y-m-d', strtotime("".($period+1)." week") ) )); $prev = strtotime(''.$period.' week'); $prevcalc = '+1 day'; $gapcalc = '-1 day'; $dateformat = 'D j M'; $previous_text = '« Previous Week'; $this_text = 'This Week'; $next_text = 'Next Week »'; } elseif ($stattype=='monthly') { $monthperiod = $period*6; if ($period<-1) $maxdate = strtotime(($monthperiod+6).' month'); else $maxdate = strtotime(date('Y-m-d')); // get stats $max = $wpdb->get_var( $wpdb->prepare("SELECT MAX(t1.thehits) FROM (SELECT SUM(hits) AS thehits FROM $wp_dlm_db_stats WHERE download_id = %s AND date>=%s AND date<=%s group by month(date)) AS t1;", $d->id, date('Y-m-d', strtotime("".$monthperiod." month") ), date('Y-m-d', strtotime("".($monthperiod+6)." month") ) )); $stats = $wpdb->get_results( $wpdb->prepare("SELECT *, SUM(hits) as thehits FROM $wp_dlm_db_stats WHERE download_id = %s AND date>=%s AND date<=%s group by month(date) ORDER BY date ASC;", $d->id, date('Y-m-d', strtotime("".$monthperiod." month") ), date('Y-m-d', strtotime("".($monthperiod+6)." month") ) )); $prev = strtotime(''.$monthperiod.' month'); $prevcalc = '+1 month'; $gapcalc = '-1 month'; $dateformat = 'F Y'; $previous_text = '« Previous 6 months'; $this_text = 'Last 6 months'; $next_text = 'Next 6 months »'; } if (!empty($downloads)) { // Output download select form echo '
    '; if ($d) { echo '
    '; if (strtotime($period.' week')>strtotime($mindate)) echo ''.$previous_text.''; if ($period<-1) echo ''.$next_text.''; echo ''.$this_text.''; echo '
    '; echo '
    '; ?> title ?>" cellpadding="0" cellspacing="0"> thehits; $date = strtotime($stat->date); $width = ($hits / $max * 100) - 10; // Fill in gaps echo dlm_fill_date_gaps($prev, $date, $gapcalc, $dateformat); $prev = strtotime($prevcalc, $date); echo ' '; $loop++; } } echo dlm_fill_date_gaps($prev, $maxdate, $gapcalc, $dateformat); ?>
    Day Number of downloads
    '.date($dateformat,$date).' '.$hits.'
    None Found

    '; echo $after_widget; } } add_action( 'plugins_loaded', create_function( '', 'global $wp_dlm_dash; $wp_dlm_dash = new wp_dlm_dash();' ) ); class wp_dlm_dash2 { // Class initialization function wp_dlm_dash2() { // Add to dashboard add_action( 'wp_dashboard_setup', array(&$this, 'register_widget') ); add_filter( 'wp_dashboard_widgets', array(&$this, 'add_widget') ); } // Register the widget for dashboard use function register_widget() { global $wp_db_version; $adminpage = 'admin.php'; wp_register_sidebar_widget( 'download_monitor_dash2', __( 'Top 5 Downloads', 'wp-download_monitor' ), array(&$this, 'widget') ); } // Insert into dashboard function add_widget( $widgets ) { global $wp_registered_widgets; if ( !isset($wp_registered_widgets['download_monitor_dash2']) ) return $widgets; array_splice( $widgets, 2, 0, 'download_monitor_dash2' ); return $widgets; } // Output the widget function widget( $args ) { if (is_array($args)) extract( $args, EXTR_SKIP ); echo $before_widget; echo $before_title; echo $widget_name; echo $after_title; global $wp_dlm_db,$wpdb,$wp_dlm_db_stats, $wp_dlm_root; $downloads = $wpdb->get_results( "SELECT * FROM $wp_dlm_db ORDER BY hits DESC LIMIT 5;" ); ?> " cellpadding="0" cellspacing="0"> get_var( "SELECT MAX(hits) FROM $wp_dlm_db"); $first = 'first'; $loop = 1; $size = sizeof($downloads); $last = ""; if ($downloads) { foreach ($downloads as $d) { $hits = $d->hits; $date = $d->date; $width = ($hits / $max * 100) - 10; if ($loop==$size) $last = 'last'; echo ' '; $first = ""; $loop++; } } else { echo ''; } ?>
    Name Number of downloads
    '.$d->title.' '.$hits.'
    None Found
    get_results("show tables;"); foreach ( $tables as $table ) { foreach ( $table as $value ) { if ( strtolower($value) == strtolower($wp_dlm_db) ) $wp_dlm_db_exists = true; } } if ($wp_dlm_db_exists==true) { add_filter('the_content', 'wp_dlm_parse_downloads',0); add_filter('the_excerpt', 'wp_dlm_parse_downloads',0); add_filter('the_meta_key', 'wp_dlm_parse_downloads',0); add_filter('widget_text', 'wp_dlm_parse_downloads',0); add_filter('widget_title', 'wp_dlm_parse_downloads',0); add_filter('the_content', 'wp_dlm_parse_downloads_all',0); add_filter('admin_head', 'wp_dlm_ins_button'); add_action('media_buttons', 'wp_dlm_add_media_button', 20); add_filter('the_excerpt', 'do_shortcode',11); add_filter('the_meta_key', 'do_shortcode',11); add_filter('widget_text', 'do_shortcode',11); add_filter('widget_title', 'do_shortcode',11); } } add_action('init','wp_dlm_init_hooks',1); ?>