back-up your database first just in case. You may need to re-save your permalink settings after upgrading if your downloads stop working. Version: 3.2 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 ################################################################################ global $wp_db_version; if ($wp_db_version < 8201) { // Pre 2.6 compatibility (BY Stephen Rider) if ( ! defined( 'WP_CONTENT_URL' ) ) { if ( defined( 'WP_SITEURL' ) ) define( 'WP_CONTENT_URL', WP_SITEURL . '/wp-content' ); else define( 'WP_CONTENT_URL', get_option( 'url' ) . '/wp-content' ); } if ( ! defined( 'WP_CONTENT_DIR' ) ) define( 'WP_CONTENT_DIR', ABSPATH . 'wp-content' ); if ( ! defined( 'WP_PLUGIN_URL' ) ) define( 'WP_PLUGIN_URL', WP_CONTENT_URL. '/plugins' ); if ( ! defined( 'WP_PLUGIN_DIR' ) ) define( 'WP_PLUGIN_DIR', WP_CONTENT_DIR . '/plugins' ); } $dlm_build="B20090622"; $wp_dlm_root = WP_PLUGIN_URL."/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('url').'/'.$dlm_url; //$downloadurl = get_bloginfo('wpurl').'/'.$dlm_url; /* Changed to url so that wordpress in a sub dir works with custom urls */ load_plugin_textdomain('wp-download_monitor', WP_PLUGIN_URL.'/download-monitor/languages/', 'download-monitor/languages/'); ################################################################################ // ADD MEDIA BUTTONS AND FORMS ################################################################################ function wp_dlm_add_media_button() { global $wp_dlm_root; $url = WP_PLUGIN_URL.'/download-monitor/uploader.php?tab=add&TB_iframe=true&height=500&width=640'; if (is_ssl()) $url = preg_replace( '/^http:\/\//', 'https://', $url ); 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(); // 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'), 'user_can_edit_downloads', __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') , 'user_can_edit_downloads', __FILE__ , 'wp_dlm_admin'); add_submenu_page(__FILE__, __('Add New','wp-download_monitor') , __('Add New','wp-download_monitor') , 'user_can_add_new_downloads', 'dlm_addnew', 'dlm_addnew'); add_submenu_page(__FILE__, __('Add Existing','wp-download_monitor') , __('Add Existing','wp-download_monitor') , 'user_can_add_existing_downloads', 'dlm_addexisting', 'dlm_addexisting'); add_submenu_page(__FILE__, __('Configuration','wp-download_monitor') , __('Configuration','wp-download_monitor') , 'user_can_config_downloads', 'dlm_config', 'wp_dlm_config'); if (get_option('wp_dlm_log_downloads')=='yes') add_submenu_page(__FILE__, __('Log','wp-download_monitor') , __('Log','wp-download_monitor') , 'user_can_view_downloads_log', '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 ( $_REQUEST['page']=='dlm_addnew' || $_REQUEST['page']=='dlm_addexisting' || $_REQUEST['page']=='download-monitor/wp-download_monitor.php' || $_REQUEST['page']=='download-monitor/wp-download_monitor.php' ) { ?> add_cap( 'administrator', 'user_can_config_downloads' ); $wp_roles->add_cap( 'administrator', 'user_can_edit_downloads' ); $wp_roles->add_cap( 'administrator', 'user_can_add_new_downloads' ); $wp_roles->add_cap( 'administrator', 'user_can_add_existing_downloads' ); $wp_roles->add_cap( 'administrator', 'user_can_view_downloads_log' ); global $wp_dlm_db,$wp_dlm_db_cats,$wp_dlm_db_formats,$wpdb,$wp_dlm_db_stats,$wp_dlm_db_log,$wp_dlm_db_meta; // Get Collation $collate = ""; if($wpdb->supports_collation()) { if(!empty($wpdb->charset)) $collate = "DEFAULT CHARACTER SET $wpdb->charset"; if(!empty($wpdb->collate)) $collate .= " COLLATE $wpdb->collate"; } // Create tables $sql = "CREATE TABLE IF NOT EXISTS ".$wp_dlm_db." ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `title` VARCHAR (200) NOT NULL , `filename` LONGTEXT NOT NULL , `file_description` LONGTEXT NULL , `dlversion` VARCHAR (200) NOT NULL , `postDate` DATETIME NOT NULL , `hits` INT (12) UNSIGNED NOT NULL , `user` VARCHAR (200) NOT NULL , `category_id` INT (12) NULL, `members` INT (1) NULL, `mirrors` LONGTEXT NULL, PRIMARY KEY ( `id` )) $collate;"; $result = $wpdb->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` )) $collate;"; $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` )) $collate;"; $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` )) $collate;"; $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` )) $collate;"; $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` )) $collate;"; $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(); // Change Collation (we forgot to do this in older versions) if($wpdb->supports_collation()) { if(!empty($wpdb->charset)) $char_set = $wpdb->charset; if(!empty($wpdb->collate)) $collate = 'collate '.$wpdb->collate; } if ($char_set) { global $wp_dlm_db_formats,$wp_dlm_db_stats,$wp_dlm_db_log,$wp_dlm_db_meta; $wpdb->query('ALTER TABLE '.$wp_dlm_db_formats.' convert to character set '.$char_set.' '.$collate.';'); $wpdb->query('ALTER TABLE '.$wp_dlm_db_stats.' convert to character set '.$char_set.' '.$collate.';'); $wpdb->query('ALTER TABLE '.$wp_dlm_db_log.' convert to character set '.$char_set.' '.$collate.';'); $wpdb->query('ALTER TABLE '.$wp_dlm_db_meta.' convert to character set '.$char_set.' '.$collate.';'); } // 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 - WORDPRESS DOES THIS BUT ADDS THE SLASHES BACK - I DONT WANT THEM! ################################################################################ if (!function_exists('wp_dlm_magic')) { function wp_dlm_magic() { if (!function_exists('stripit')) { function stripit($in) { if (!is_array($in)) $out = stripslashes($in); else $out = $in; return $out; } } //if (get_magic_quotes_gpc() || get_magic_quotes_runtime() ){ $_GET = array_map('stripit', $_GET); $_POST = array_map('stripit', $_POST); $_REQUEST = array_map('stripit', $_REQUEST); //} 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)); $output = ''; $cached_code = wp_cache_get('download_'.$id.'_'.$format); if($cached_code == false) { 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 && $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 = html_entity_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 = urlencode(end($links)); break; default : $downloadlink = $d->id; break; } $format = str_replace('\\"',"'",$format); $fpatts = array('{url}', '{id}', '{user}', '{version}', '{title}', '{size}', '{hits}', '{image_url}', '{description}', '{description-autop}', '{category}'); $fsubs = array( $downloadurl.$downloadlink , $d->id, $d->user, $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,\s*\"([^\"]*?)\",\s*\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; $fsubs[] = $match[1].$c->name.$match[2]; } else { $fsubs[] = ""; preg_match("/{category,\s*\"([^\"]*?)\",\s*\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; $fsubs[] = ""; } // Hits (special) {hits, none, one, many) preg_match("/{hits,\s*\"([^\"]*?)\",\s*\"([^\"]*?)\",\s*\"([^\"]*?)\"}/", $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,\s*\"([^\"]*?)\",\s*\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; if ($d->dlversion) $fsubs[] = $match[1].$d->dlversion.$match[2]; else $fsubs[] = ""; // Date preg_match("/{date,\s*\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; if ($d->postDate) $fsubs[] = date_i18n($match[1],strtotime($d->postDate)); else $fsubs[] = ""; // Other preg_match("/{description,\s*\"([^\"]*?)\",\s*\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; if ($d->file_description) $fsubs[] = $match[1].$d->file_description.$match[2]; else $fsubs[] = ""; preg_match("/{description-autop,\s*\"([^\"]*?)\",\s*\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; if ($d->file_description) $fsubs[] = $match[1].wpautop($d->file_description).$match[2]; else $fsubs[] = ""; // tags $tags = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM $wp_dlm_db_meta WHERE download_id = %s AND meta_name = 'tags'" , $id ) ); if (!$tags) $tags = 'Untagged'; $fpatts[] = "{tags}"; $fsubs[] = $tags; // Thumbnail $thumbnail = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM $wp_dlm_db_meta WHERE download_id = %s AND meta_name = 'thumbnail'" , $id ) ); if (!$thumbnail) $thumbnail = $wp_dlm_root.'/page-addon/thumbnail.gif'; $fpatts[] = "{thumbnail}"; $fsubs[] = $thumbnail; // 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 ) ); $meta_names = array(); 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); $meta_names[] = $meta->meta_name; } // Blank Meta $meta_data = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wp_dlm_db_meta WHERE meta_name NOT IN ( %s )" , implode(',', $meta_names) ) ); foreach($meta_data as $meta) { $fpatts[] = "{meta-".$meta->meta_name."}"; $fsubs[] = ''; $fpatts[] = "{meta-autop-".$meta->meta_name."}"; $fsubs[] = ''; } } $output = str_replace( $fpatts , $fsubs , $format ); } else $output = '[Download not found]'; } else $output = '[Download id not defined]'; wp_cache_set('download_'.$id.'_'.$format, $output); } else { $output = $cached_code; } if ($autop && $autop != "false") 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, $downloadtype; // 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'), ABSPATH,$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,$showid); } } 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" : wp_cache_flush(); $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, "/uploads/" ) ) { $path = WP_CONTENT_URL."/uploads/"; $file = str_replace( $path , "" , $d->filename); if(is_file(WP_CONTENT_DIR.'/uploads/'.$file)){ chmod(WP_CONTENT_DIR.'/uploads/'.$file, 0777); unlink(WP_CONTENT_DIR.'/uploads/'.$file); } } } $file = wp_handle_upload($_FILES['upload'], $overrides, $time); if ( !isset($file['error']) ) { $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'].""); // Tags if ($tags = $_POST['tags']) { $wpdb->query("INSERT INTO $wp_dlm_db_meta (meta_name, meta_value, download_id) VALUES ('tags', '".$wpdb->escape( $tags )."', '".$_GET['id']."')"); } // Thumbnail if ($thumbnail = $_POST['thumbnail']) { $wpdb->query("INSERT INTO $wp_dlm_db_meta (meta_name, meta_value, download_id) VALUES ('thumbnail', '".$wpdb->escape( $thumbnail )."', '".$_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 ++; } } if (sizeof($values)>0) $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'].""); // Tags if ($tags = $_POST['tags']) { $wpdb->query("INSERT INTO $wp_dlm_db_meta (meta_name, meta_value, download_id) VALUES ('tags', '".$wpdb->escape( $tags )."', '".$_GET['id']."')"); } // Thumbnail if ($thumbnail = $_POST['thumbnail']) { $wpdb->query("INSERT INTO $wp_dlm_db_meta (meta_name, meta_value, download_id) VALUES ('thumbnail', '".$wpdb->escape( $thumbnail )."', '".$_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 ++; } } if (sizeof($values)>0) $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(); $tags = ''; $thumbnail = ''; if ($fields) foreach ($fields as $meta) { if ($meta->meta_name=='tags') { $tags = $meta->meta_value; } elseif ($meta->meta_name=='thumbnail') { $thumbnail = $meta->meta_value; } else { $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 = ''; } ?>

:
:
:
:

:
:
/>
:


= .
/>
postDate)) ;?>" /> 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, "/uploads/" ) ) { $path = WP_CONTENT_URL."/uploads/"; $file = str_replace( $path , "" , $d->filename); if(is_file(WP_CONTENT_DIR.'/uploads/'.$file)){ chmod(WP_CONTENT_DIR.'/uploads/'.$file, 0777); unlink(WP_CONTENT_DIR.'/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; } } /* Bulk Editing */ if ($_POST['dobulkaction'] || $_POST['dobulkaction2']) { if ($_POST['dobulkaction']) $action = $_POST['bulkactions']; elseif ($_POST['dobulkaction2']) $action = $_POST['bulkactions2']; $checked = $_POST['check']; $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_cache_flush(); 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 '

'.__('Stats successfully reset for selected downloads',"wp-download_monitor").'

'; $show=true; } elseif ($action=='delete') { // Delete selected downloads wp_cache_flush(); 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; if ( strstr ( $d->filename, "/uploads/" ) ) { $path = WP_CONTENT_URL."/uploads/"; $file = str_replace( $path , "" , $d->filename); if(is_file(WP_CONTENT_DIR.'/uploads/'.$file)){ chmod(WP_CONTENT_DIR.'/uploads/'.$file, 0777); unlink(WP_CONTENT_DIR.'/uploads/'.$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); } } echo '

'.__('Selected Downloads 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; } elseif ($action=='edit'){ // Show edit form instead $show=false; $show_edit = true; $custom_fields = $_POST['meta']; if ($_POST['save']) { // get values $download_cat = $_POST['download_cat']; $change_memberonly = $_POST['change_memberonly']; $members = (isset($_POST['memberonly'])) ? 1 : 0; $change_customfields = $_POST['change_customfields']; $change_tags = $_POST['change_tags']; $change_thumbnail = $_POST['change_thumbnail']; $tags = $_POST['tags']; $thumbnail = $_POST['thumbnail']; // save options $queries = array(); if ($change_memberonly==1) { $queries[] = " members='".$wpdb->escape($members)."' "; } if ($download_cat && $download_cat!=='no') { $queries[] = " category_id='".$wpdb->escape($download_cat)."' "; } if (sizeof($queries)>0) { $wpdb->query( "UPDATE $wp_dlm_db SET ".implode(', ', $queries)." WHERE id IN (".$wpdb->escape( implode(', ',$bulk_ids) ).");" ); } if ($change_tags==1) { $wpdb->query("DELETE FROM $wp_dlm_db_meta WHERE download_id IN (".$wpdb->escape( implode(', ',$bulk_ids) ).") AND meta_name IN ('tags')"); foreach($bulk_ids as $bid) { if ($tags) $wpdb->query("INSERT INTO $wp_dlm_db_meta (meta_name, meta_value, download_id) VALUES ('tags', '".$tags."' , ".$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.")"); } } // 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')"); } 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($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 '

'.__('Downloads edited successfully',"wp-download_monitor").'

'; // hide edit form - show downloads $show_edit = false; $show=true; } if ($show_edit==true) : ?>

.


:
:

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

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

" />


" class="button dobulkaction" name="dobulkaction" type="submit" />
" class="button" name="search_downloads" type="submit" />
*/ ?> escape($_REQUEST['search_downloads'])."%' OR filename LIKE '%".$wpdb->escape($_REQUEST['search_downloads'])."%') "; } // Sort column $sort = "title"; $sort_ex = ''; if ($_REQUEST['sort'] && ($_REQUEST['sort']=="id" || $_REQUEST['sort']=="filename" || $_REQUEST['sort']=="postDate")) $sort = $_REQUEST['sort']; if ($_REQUEST['sort']=="id") $sort_ex =' ASC'; $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.*, $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.$sort_ex ), $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 ) { // Changed from jS M Y $date = date_i18n(__("Y/m/d","wp-download_monitor"), strtotime($d->postDate)); $path = WP_CONTENT_URL."/uploads/"; $file = str_replace($path, "", $d->filename); $links = explode("/",$file); $file = end($links); echo ''; echo ''; //$onclickcode = "if ( confirm('You are about to delete this download \'".$d->title."\'.\\n \'Cancel\' to stop, \'OK\' to delete.') ){return true;}return false;"; 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 ?>
<?php _e('Hits'," title="" />
'.$d->id.' '; $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 'Thumbnail'; echo ''.$d->title.''; if ($d->dlversion) echo ' ('.__('Version',"wp-download_monitor").' '.$d->dlversion.')'; echo ' '.$file.' '; if ($d->category_id=="" || $d->category_id==0) _e('N/A',"wp-download_monitor"); else { $c = $wpdb->get_row("SELECT * FROM $wp_dlm_db_cats where id=".$d->category_id." LIMIT 1;"); $chain = $c->name; while ($c->parent > 0 ) { $c = $wpdb->get_row("SELECT * FROM $wp_dlm_db_cats where id=".$c->parent." LIMIT 1;"); $chain = $c->name.' — '.$chain; } echo $d->category_id." - ".$chain; } echo ''; echo $wpdb->get_var('SELECT meta_value FROM '.$wp_dlm_db_meta.' WHERE download_id = '.$d->id.' AND meta_name = "tags" LIMIT 1'); echo ' '; if ($d->members) echo __('Yes',"wp-download_monitor"); else echo __('No',"wp-download_monitor"); echo ' '; echo $wpdb->get_var('SELECT COUNT(id) FROM '.$wp_dlm_db_meta.' WHERE download_id = '.$d->id.' AND meta_name NOT IN ("tags","thumbnail")'); echo ' '.$d->hits.''.$date.'
'.__('by',"wp-download_monitor").' '.$d->user.'
Edit Delete
'.__('No downloads found.',"wp-download_monitor").'
" class="button dobulkaction" name="dobulkaction2" type="submit" />
1) { $arr_params = array ( 'sort' => $sort, 'page' => 'download-monitor/wp-download_monitor.php', 'search_downloads' => $_REQUEST['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' => __('« Previous'), 'next_text' => __('Next »'), 'total' => $total_pages, 'current' => $page, 'end_size' => 1, 'mid_size' => 5, )); } ?>


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,$downloadtype; // 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/([^/]+)$ *your wp-content dir*/plugins/download-monitor/download.php?id=$1 [L]

replacing "download/" with your custom url and "*your wp-content dir*" with your wp-content directory.

',"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/([^/]+)$ *your wp-content dir*/plugins/download-monitor/download.php?id=$1 [L]

replacing "download/" with your previous custom url and "*your wp-content dir*" with your wp-content directory.

',"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']); update_option('wp_dlm_log_downloads', $_POST['wp_dlm_log_downloads']); update_option('wp_dlm_file_browser_root', $_POST['wp_dlm_file_browser_root']); $save_opt=true; echo '
'; _e('

Options updated

',"wp-download_monitor"); echo '
'; $show=true; break; case "categories" : if ($_POST['rename_cat']) { $name = $_POST['cat_rename']; if (!empty($name)) { $category = $_POST['cat_to_rename']; $parent = $_POST['cat_parent_edit']; $parent_q = ''; if (($parent=='0' || $parent>0) AND $parent!==$category) $parent_q = ", parent='$parent'"; if ($category && is_numeric($category) && $category>0) { $query = sprintf("UPDATE %s SET name='%s' $parent_q WHERE id='%s'", $wpdb->escape( $wp_dlm_db_cats ), $wpdb->escape( $name ), $wpdb->escape( $category )); $wpdb->query($query); //echo $query; echo '

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

'; } } } elseif ($_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) VALUES ('%s','%s')", $wpdb->escape( $wp_dlm_db_cats ), $wpdb->escape( $name ), $wpdb->escape( $parent )); $wpdb->query($query_ins); if ($wpdb->insert_id>0) echo '

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

'; else echo '

'.__('Category was not added. Try Recreating the download database from the configuration page.',"wp-download_monitor").'

'; } } $show=true; $ins_cat=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='0' 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" : wp_cache_flush(); 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" : 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 '

'.__('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").'

:
:

" name="add_cat" />

:
:
:

" name="rename_cat" />

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)
  • {id} - ID of download
  • {user} - Username of whoever posted download
  • {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)
  • {date,"Y-m-d"} - Date posted. Second argument is for date format.
  • {tags} - Output tags
  • {thumbnail} - Output thumbnail URL (or placeholder)
  • {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. This option will only work if using wordpress permalinks (other than default).

Leave this option blank to use the default download path (/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

Explanation
: /

" />

*/ ?>
:
: {referrer} will be replaced with current url. Useful if sending user to the login page and then back to the download :) e.g. http://yourdomain.com/wp-login.php?redirect_to={referrer}.',"wp-download_monitor"); ?>
: #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"); ?>
:
:
:
: and above.

" />

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"); $tags = $_POST['tags']; $thumbnail = $_POST['thumbnail']; //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) { $download_insert_id = $wpdb->insert_id; // Tags if ($tags = $_POST['tags']) { $wpdb->query("INSERT INTO $wp_dlm_db_meta (meta_name, meta_value, download_id) VALUES ('tags', '".$wpdb->escape( $tags )."', '".$download_insert_id."')"); } // Thumbnail if ($thumbnail = $_POST['thumbnail']) { $wpdb->query("INSERT INTO $wp_dlm_db_meta (meta_name, meta_value, download_id) VALUES ('thumbnail', '".$wpdb->escape( $thumbnail )."', '".$download_insert_id."')"); } // 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']).'", '.$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 '

'.__("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"); $tags = $_POST['tags']; $thumbnail = $_POST['thumbnail']; //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) { $download_insert_id = $wpdb->insert_id; // Tags if ($tags = $_POST['tags']) { $wpdb->query("INSERT INTO $wp_dlm_db_meta (meta_name, meta_value, download_id) VALUES ('tags', '".$wpdb->escape( $tags )."', '".$download_insert_id."')"); } // Thumbnail if ($thumbnail = $_POST['thumbnail']) { $wpdb->query("INSERT INTO $wp_dlm_db_meta (meta_name, meta_value, download_id) VALUES ('thumbnail', '".$wpdb->escape( $thumbnail )."', '".$download_insert_id."')"); } // 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']).'", '.$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 '

'.__("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(*) FROM $wp_dlm_db_log INNER JOIN $wp_dlm_db ON $wp_dlm_db_log.download_id = $wp_dlm_db.id;"); // 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_i18n(__("jS M Y H:i:s","wp-download_monitor"), strtotime($log->date)); $path = WP_CONTENT_URL."/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.'([^/]+)$ '.WP_PLUGIN_URL.'/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) { $defaults = array( 'limit' => '', 'offset' => '0', 'orderby' => 'id', 'meta_name' => '', 'vip' => '0', 'category' => '', 'tags' => '', 'order' => 'asc', 'digforcats' => 'true', 'exclude' => '' ); $args = str_replace('&','&',$args); $r = wp_parse_args( $args, $defaults ); global $wpdb,$wp_dlm_root, $wp_dlm_db, $wp_dlm_db_cats, $wp_dlm_db_meta, $dlm_url, $downloadurl, $downloadtype; $where = array(); $join = ''; $select = ''; // Handle $exclude $exclude_array = array(); if ( $r['exclude'] ) { $exclude_unclean = explode(',',$r['exclude']); foreach ($exclude_unclean as $e) { $e = trim($e); if (is_numeric($e)) $exclude_array[] = $e; } } if (sizeof($exclude_array) > 0) { $where[] = ' '.$wp_dlm_db.'.id NOT IN ('.implode(',',$exclude_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; elseif ( empty( $r['limit'] )) $r['offset'] = ''; if ( !empty( $r['limit'] ) ) $limitandoffset = ' LIMIT '.$r['offset'].', '.$r['limit'].' '; if ( ! empty($r['category']) && $r['category']!='none' ) { $categories = explode(',',$r['category']); $the_cats = array(); // Traverse through categories to get sub-cats foreach ($categories as $cat) { $the_cats[] = $cat; if ($r['digforcats']) $the_cats = wp_dlm_get_sub_cats($the_cats); } $categories = implode(',',$the_cats); $where[] = ' category_id IN ('.$categories.') '; } elseif ($r['category']=='none') { $where[] = ' category_id = 0 '; } else $category = ''; if ( ! empty($r['tags']) ) { $tags = explode(',', $r['tags']); if (sizeof($tags)>0) { // Get posts with tags $tagged = $wpdb->get_results( "SELECT * FROM $wp_dlm_db INNER JOIN $wp_dlm_db_meta ON $wp_dlm_db.id = $wp_dlm_db_meta.download_id WHERE $wp_dlm_db_meta.meta_name = 'tags';"); $postIDS = array(); foreach ($tagged as $t) { $my_tags = explode(',', $t->meta_value ); $my_clean_tags = array(); foreach ($my_tags as $tag) { $my_clean_tags[] = trim(strtolower($tag)); } foreach ($tags as $tag) { if (in_array(trim(strtolower($tag)), $my_clean_tags)) $postIDS[] = $t->download_id; } } $where[] = ' '.$wp_dlm_db.'.id IN ('.implode(',',$postIDS).') '; } } else $tags = ''; 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 'meta' : $orderby = 'meta'; $join = " LEFT JOIN $wp_dlm_db_meta ON $wp_dlm_db.id = $wp_dlm_db_meta.download_id "; $select = ", $wp_dlm_db_meta.meta_value as meta"; $where[] = ' meta_name = "'.$r['meta_name'].'"'; 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 ".$select." FROM $wp_dlm_db LEFT JOIN $wp_dlm_db_cats ON $wp_dlm_db.category_id = $wp_dlm_db_cats.id ".$join." ".$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 = urlencode(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)); $query = str_replace('&','&', $query); 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 && $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 = html_entity_decode($format); } if (empty($format) || $format=='0') { $format = '{title} ({hits})'; } $format = str_replace('\\"',"'",$format); foreach ($dl as $d) { $fpatts = array('{url}', '{id}', '{user}', '{version}', '{title}', '{size}', '{hits}', '{image_url}', '{description}', '{description-autop}', '{category}', ); $fsubs = array( $d->url , $d->id, $d->user, $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,\s*\"([^\"]*?)\",\s*\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; $fsubs[] = $match[1].$d->category.$match[2]; } else { $fsubs[] = ""; preg_match("/{category,\s*\"([^\"]*?)\",\s*\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; $fsubs[] = ""; } // Hits (special) {hits, none, one, many) preg_match("/{hits,\s*\"([^\"]*?)\",\s*\"([^\"]*?)\",\s*\"([^\"]*?)\"}/", $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,\s*\"([^\"]*?)\",\s*\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; if ($d->version) $fsubs[] = $match[1].$d->version.$match[2]; else $fsubs[] = ""; // Date preg_match("/{date,\s*\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; if ($d->postDate) $fsubs[] = date_i18n($match[1],strtotime($d->postDate)); else $fsubs[] = ""; // Other preg_match("/{description,\s*\"([^\"]*?)\",\s*\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; if ($d->desc) $fsubs[] = $match[1].$d->desc.$match[2]; else $fsubs[] = ""; preg_match("/{description-autop,\s*\"([^\"]*?)\",\s*\"([^\"]*?)\"}/", $format, $match); $fpatts[] = $match[0]; if ($d->desc) $fsubs[] = $match[1].wpautop($d->desc).$match[2]; else $fsubs[] = ""; // tags $tags = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM $wp_dlm_db_meta WHERE download_id = %s AND meta_name = 'tags'" , $d->id ) ); if (!$tags) $tags = 'Untagged'; $fpatts[] = "{tags}"; $fsubs[] = $tags; // Thumbnail $thumbnail = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM $wp_dlm_db_meta WHERE download_id = %s AND meta_name = 'thumbnail'" , $d->id ) ); if (!$thumbnail) $thumbnail = $wp_dlm_root.'/page-addon/thumbnail.gif'; $fpatts[] = "{thumbnail}"; $fsubs[] = $thumbnail; // 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 ) ); $meta_names = array(); 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); $meta_names[] = $meta->meta_name; } // Blank Meta $meta_data = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wp_dlm_db_meta WHERE meta_name NOT IN ( %s )" , implode(',', $meta_names) ) ); foreach($meta_data as $meta) { $fpatts[] = "{meta-".$meta->meta_name."}"; $fsubs[] = ''; $fpatts[] = "{meta-autop-".$meta->meta_name."}"; $fsubs[] = ''; } } $output .= html_entity_decode($before).str_replace( $fpatts , $fsubs , $format ).html_entity_decode($after); } } else $output = '['.__("No Downloads found","wp-download_monitor").']'; 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_i18n($dateformat, $date ).' 0 '; $loop++; endwhile; return implode('',array_reverse($string)); } } ################################################################################ // Dashboard widgets ################################################################################ // Only for wordpress 2.5 and above if ($wp_db_version > 6124) { function dlm_download_stats_widget() { 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',"wp-download_monitor"); $previous_text = '« '.__('Previous Week',"wp-download_monitor").''; $this_text = ''.__('This Week',"wp-download_monitor").''; $next_text = ''.__('Next Week',"wp-download_monitor").' »'; } 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',"wp-download_monitor"); $previous_text = '« '.__('Previous 6 months',"wp-download_monitor").''; $this_text = ''.__('Last 6 months',"wp-download_monitor").''; $next_text = ''.__('Next 6 months',"wp-download_monitor").' »'; } 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); ?>
    '.date_i18n($dateformat,$date).' '.$hits.'
    '.__('None Found',"wp-download_monitor").'

    '; } function dlm_download_top_widget() { 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 && $max>0) { 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 ''; } ?>
    '.$d->title.' '.$hits.'
    '.__('No stats yet',"wp-download_monitor").'
    8644) { function dlm_download_stats_widget_setup() { wp_add_dashboard_widget( 'dlm_download_stats_widget', __( 'Download Stats' ), 'dlm_download_stats_widget' ); wp_add_dashboard_widget( 'dlm_download_top_widget', __( 'Top 5 Downloads' ), 'dlm_download_top_widget' ); } add_action('wp_dashboard_setup', 'dlm_download_stats_widget_setup'); } else { // Old Method using Classes 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; dlm_download_stats_widget(); 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; dlm_download_top_widget(); echo $after_widget; } } add_action( 'plugins_loaded', create_function( '', 'global $wp_dlm_dash2; $wp_dlm_dash2 = new wp_dlm_dash2();' ) ); } } ################################################################################ // Hooks ################################################################################ function wp_dlm_init_hooks() { global $wpdb,$wp_dlm_db,$wp_dlm_db_formats,$wp_dlm_db_cats; if (isset($_GET['activate']) && $_GET['activate']==true) { wp_dlm_init(); } $wp_dlm_db_exists = false; // Check tables exist $tables = $wpdb->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',1); add_filter('the_excerpt', 'wp_dlm_parse_downloads',1); add_filter('the_meta_key', 'wp_dlm_parse_downloads',1); add_filter('widget_text', 'wp_dlm_parse_downloads',1); add_filter('widget_title', 'wp_dlm_parse_downloads',1); add_filter('the_content', 'wp_dlm_parse_downloads_all',1); 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); ################################################################################ // Addons ################################################################################ if (!function_exists('wp_dlmp_styles')) include('page-addon/download-monitor-page-addon.php'); ?>