Manage your attachements, detect duplicates, and enable zip downloading of files
Version: 1.0.2 Framework: SL_Framework Author: sedLex Author URI: http://www.sedlex.fr/ Author Email: sedlex@sedlex.fr Framework Email: sedlex@sedlex.fr Plugin URI: http://wordpress.org/plugins/attachments-handler/ License: GPL3 */ //Including the framework in order to make the plugin work require_once('core.php') ; /** ==================================================================================================================================================== * This class has to be extended from the pluginSedLex class which is defined in the framework */ class attachments_handler extends pluginSedLex { /** ==================================================================================================================================================== * Plugin initialization * * @return void */ static $instance = false; protected function _init() { global $wpdb ; // Name of the plugin (Please modify) $this->pluginName = 'Attachments Handler' ; // The structure of the SQL table if needed (for instance, 'id_post mediumint(9) NOT NULL, short_url TEXT DEFAULT '', UNIQUE KEY id_post (id_post)') $this->tableSQL = "id mediumint(9) NOT NULL, id_post mediumint(9) NOT NULL, url VARCHAR(400), path TEXT DEFAULT '', description TEXT DEFAULT '', titre TEXT DEFAULT '', legende TEXT DEFAULT '', sha1 VARCHAR(40), attach_used_in TEXT DEFAULT '', is_exist BOOL" ; // The name of the SQL table (Do no modify except if you know what you do) $this->table_name = $wpdb->prefix . "pluginSL_" . get_class() ; //Initilisation of plugin variables if needed (Please modify) $this->your_var1 = 1 ; $this->your_var2 = array() ; $this->your_varn = "n" ; //Configuration of callbacks, shortcode, ... (Please modify) // For instance, see // - add_shortcode (http://codex.wordpress.org/Function_Reference/add_shortcode) // - add_action // - http://codex.wordpress.org/Function_Reference/add_action // - http://codex.wordpress.org/Plugin_API/Action_Reference // - add_filter // - http://codex.wordpress.org/Function_Reference/add_filter // - http://codex.wordpress.org/Plugin_API/Filter_Reference // Be aware that the second argument should be of the form of array($this,"the_function") // For instance add_action( "wp_ajax_foo", array($this,"bar")) : this function will call the method 'bar' when the ajax action 'foo' is called add_shortcode( 'attach', array( $this, 'displayAttachments' ) ); add_action( 'wp_ajax_nopriv_checkIfAttachmentsHandlerNeeded', array( $this, 'checkIfAttachmentsHandlerNeeded')); add_action( 'wp_ajax_checkIfAttachmentsHandlerNeeded', array( $this, 'checkIfAttachmentsHandlerNeeded')); add_action( "wp_ajax_stopAnalysisAttachments", array($this,"stopAnalysisAttachments")) ; add_action( "wp_ajax_forceAnalysisAttachments", array($this,"forceAnalysisAttachments")) ; add_action( "wp_ajax_cleanAnalysisAttachments", array($this,"cleanAnalysisAttachments")) ; add_action( 'save_post', array( $this, 'whenPostIsSaved') ); add_action( 'edit_attachment', array( $this, 'whenAttachmentIsSaved') ); // Important variables initialisation (Do not modify) $this->path = __FILE__ ; $this->pluginID = get_class() ; // activation and deactivation functions (Do not modify) register_activation_hook(__FILE__, array($this,'install')); register_deactivation_hook(__FILE__, array($this,'deactivate')); register_uninstall_hook(__FILE__, array('attachments_handler','uninstall_removedata')); } /** ==================================================================================================================================================== * In order to uninstall the plugin, few things are to be done ... * (do not modify this function) * * @return void */ static public function uninstall_removedata () { global $wpdb ; // DELETE OPTIONS delete_option('attachments_handler'.'_options') ; if (is_multisite()) { delete_site_option('attachments_handler'.'_options') ; } // DELETE SQL if (function_exists('is_multisite') && is_multisite()){ $old_blog = $wpdb->blogid; $old_prefix = $wpdb->prefix ; // Get all blog ids $blogids = $wpdb->get_col($wpdb->prepare("SELECT blog_id FROM ".$wpdb->blogs)); foreach ($blogids as $blog_id) { switch_to_blog($blog_id); $wpdb->query("DROP TABLE ".str_replace($old_prefix, $wpdb->prefix, $wpdb->prefix . "pluginSL_" . 'attachments_handler')) ; } switch_to_blog($old_blog); } else { $wpdb->query("DROP TABLE ".$wpdb->prefix . "pluginSL_" . 'attachments_handler' ) ; } } /**==================================================================================================================================================== * Function called when the plugin is activated * For instance, you can do stuff regarding the update of the format of the database if needed * If you do not need this function, you may delete it. * * @return void */ public function _update() { SL_Debug::log(get_class(), "Update the plugin." , 4) ; } /**==================================================================================================================================================== * Function called to return a number of notification of this plugin * This number will be displayed in the admin menu * * @return int the number of notifications available */ public function _notify() { return 0 ; } /** ==================================================================================================================================================== * Init javascript for the public side * If you want to load a script, please type : *wp_enqueue_script( 'jsapi', 'https://www.google.com/jsapi'); or
* wp_enqueue_script('attachments_handler_script', plugins_url('/script.js', __FILE__));
* $this->add_inline_js($js_text);
* $this->add_js($js_url_file);
*
* @return void
*/
function _public_js_load() {
ob_start() ;
?>
function checkIfAttachmentsHandlerNeeded() {
var arguments = {
action: 'checkIfAttachmentsHandlerNeeded'
}
var ajaxurl2 = "" ;
jQuery.post(ajaxurl2, arguments, function(response) {
// We do nothing as the process should be as silent as possible
});
}
// We launch the callback
if (window.attachEvent) {window.attachEvent('onload', checkIfAttachmentsHandlerNeeded);}
else if (window.addEventListener) {window.addEventListener('load', checkIfAttachmentsHandlerNeeded, false);}
else {document.addEventListener('load', checkIfAttachmentsHandlerNeeded, false);}
add_inline_js($java) ;
}
/** ====================================================================================================================================================
* Init css for the public side
* If you want to load a style sheet, please type :
* $this->add_inline_css($css_text);
* $this->add_css($css_url_file);
*
* @return void
*/
function _public_css_load() {
$css = $this->get_param('css') ;
$this->add_inline_css($css) ;
}
/** ====================================================================================================================================================
* Init javascript for the admin side
* If you want to load a script, please type :
* wp_enqueue_script( 'jsapi', 'https://www.google.com/jsapi'); or
* wp_enqueue_script('attachments_handler_script', plugins_url('/script.js', __FILE__));
* $this->add_inline_js($js_text);
* $this->add_js($js_url_file);
*
* @return void
*/
function _admin_js_load() {
}
/** ====================================================================================================================================================
* Init css for the admin side
* If you want to load a style sheet, please type :
* $this->add_inline_css($css_text);
* $this->add_css($css_url_file);
*
* @return void
*/
function _admin_css_load() {
}
/** ====================================================================================================================================================
* Called when the content is displayed
*
* @param string $content the content which will be displayed
* @param string $type the type of the article (e.g. post, page, custom_type1, etc.)
* @param boolean $excerpt if the display is performed during the loop
* @return string the new content
*/
function _modify_content($content, $type, $excerpt) {
return $content;
}
/** ====================================================================================================================================================
* Add a button in the TinyMCE Editor
*
* To add a new button, copy the commented lines a plurality of times (and uncomment them)
*
* @return array of buttons
*/
function add_tinymce_buttons() {
$buttons = array() ;
//$buttons[] = array(__('title', $this->pluginID), '[tag]', '[/tag]', plugin_dir_url("/").'/'.str_replace(basename( __FILE__),"",plugin_basename( __FILE__)).'img/img_button.png') ;
return $buttons ;
}
/**====================================================================================================================================================
* Function to instantiate the class and make it a singleton
* This function is not supposed to be modified or called (the only call is declared at the end of this file)
*
* @return void
*/
public static function getInstance() {
if ( !self::$instance ) {
self::$instance = new self;
}
return self::$instance;
}
/** ====================================================================================================================================================
* Define the default option values of the plugin
* This function is called when the $this->get_param function do not find any value fo the given option
* Please note that the default return value will define the type of input form: if the default return value is a:
* - string, the input form will be an input text
* - integer, the input form will be an input text accepting only integer
* - string beggining with a '*', the input form will be a textarea
* - boolean, the input form will be a checkbox
*
* @param string $option the name of the option
* @return variant of the option
*/
public function get_default_option($option) {
switch ($option) {
// Alternative default return values (Please modify)
case 'type_page' : return "page,post" ; break ;
case 'list_post_id_to_check': return array() ; break ;
case 'nb_post_to_check' : return 0 ; break ;
case 'max_page_to_check' : return 200 ; break ;
case 'titre' : return "List of all attached files" ; break ;
case 'html' : return "*%link%
%description%
" ; break ; case 'css' : return "*div.attach_div{ border: 1px solid #AAAAAA; padding: 5px; padding-left: 20px; padding-right: 20px; padding-bottom: 10px; min-width:100px; } div.attach_div h2 { text-align: center; font-size: 13px; line-height: 15px ; font-weight: bold; margin : 3px ; padding-top : 5px ; padding-bottom : 5px ; } div.attach_list p{ margin : 2px ; padding : 2px ; font-size: 11px; line-height: 11px ; } div.attach_list p.description{ padding-left:30px ; }" ; break ; case 'last_request' : return 0 ; break ; case 'between_two_requests' : return 5 ; break ; } return null ; } /** ==================================================================================================================================================== * The admin configuration page * This function will be called when you select the plugin in the admin backend * * @return void */ public function configuration_page() { global $wpdb; global $blog_id ; SL_Debug::log(get_class(), "Print the configuration page." , 4) ; ?>pluginID) ;?>
pluginID),"[attach child=1 only_admin=1 title='Title you want' extension='pdf,doc,png']") ;?>
" ; echo "" ; echo "pluginID)."' />" ; echo "" ; echo " pluginID)."' />" ; echo "" ; echo " pluginID)."' />" ; echo "
" ; $tabs->add_tab(__('Attachments issues', $this->pluginID), ob_get_clean()) ; ob_start() ; $maxnb = 20 ; $table = new adminTable(0, $maxnb, true, true) ; $table->title(array(__('Title of the file', $this->pluginID),__('Description of the file', $this->pluginID), __('File in used', $this->pluginID))) ; // We order the posts page according to the choice of the user $order = " ORDER BY " ; if ($table->current_ordercolumn()==1) { $order .= "description" ; } else { $order .= "titre" ; } if ($table->current_orderdir()=="DESC") { $order .= " DESC" ; } else { $order .= " ASC" ; } $nb = $wpdb->get_var("SELECT COUNT(*) FROM ".$this->table_name." WHERE url!='' AND (titre like '%".str_replace("'","",$table->current_filter())."%' OR description like '%".str_replace("'","",$table->current_filter())."%')".$order) ; $table->set_nb_all_Items($nb) ; $limit = "" ; if ($nb>$maxnb) { $limit = " LIMIT ".(($table->current_page()-1)*$maxnb).",".$maxnb ; } $results = $wpdb->get_results("SELECT * FROM ".$this->table_name." WHERE url!='' AND (titre like '%".str_replace("'","",$table->current_filter())."%' OR description like '%".str_replace("'","",$table->current_filter())."%')".$order.$limit) ; $ligne=0 ; foreach ($results as $r) { $ligne++ ; if ($r->titre=="") { $r->titre = $r->url ; } $all_id = explode(',',$r->attach_used_in) ; $post_used = "" ; foreach ($all_id as $ai) { if ($ai!="") { $tit_pos = get_the_title($ai); if ($tit_pos=="") { $tit_pos = __("No title", $this->pluginID) ; } $post_used .= "".$tit_pos." (".__('Edit', $this->pluginID).")
" ; } } if ($post_used == "") { $post_used = "".__("(Not used)", $this->pluginID)."
" ; } if ($r->id==0) { $cel1 = new adminCell("") ; } else { $cel1 = new adminCell("url)."\">".$r->titre." (id))."\">".__('Edit', $this->pluginID).")
") ; } $cel2 = new adminCell("".$r->description."
") ; $cel3 = new adminCell($post_used) ; $table->add_line(array($cel1, $cel2, $cel3), $ligne) ; } echo $table->flush() ; $tabs->add_tab(__('All links', $this->pluginID), ob_get_clean()) ; ob_start() ; $params = new parametersSedLex($this, "tab-parameters") ; $params->add_title(__('Analysis of', $this->pluginID)) ; $params->add_param('type_page', __('Type of page to be analysed:', $this->pluginID)) ; $params->add_title(__('Appearence', $this->pluginID)) ; $params->add_param('titre', __('Default title:', $this->pluginID)) ; $params->add_param('html', __('The HTML displayed for the shortcode:', $this->pluginID)) ; $params->add_comment(__("The default value is:", $this->pluginID)) ; $params->add_comment_default_value('html') ; $params->add_param('html_entry', __('The HTML displayed for each entry of the list:', $this->pluginID)) ; $params->add_comment(__("The default value is:", $this->pluginID)) ; $params->add_comment_default_value('html_entry') ; $params->add_param('css', __('The CSS used for the shortcode:', $this->pluginID)) ; $params->add_comment(__("The default value is:", $this->pluginID)) ; $params->add_comment_default_value('css') ; $params->add_title(__('Advanced', $this->pluginID)) ; $params->add_param('max_page_to_check', __('Max number of post to be checked when an analysis is forced:', $this->pluginID)) ; $params->add_param('between_two_requests', __('Number of minutes between two background check:', $this->pluginID)) ; $params->flush() ; $tabs->add_tab(__('Parameters', $this->pluginID), ob_get_clean() , plugin_dir_url("/").'/'.str_replace(basename(__FILE__),"",plugin_basename(__FILE__))."core/img/tab_param.png") ; $frmk = new coreSLframework() ; if (((is_multisite())&&($blog_id == 1))||(!is_multisite())||($frmk->get_param('global_allow_translation_by_blogs'))) { ob_start() ; $plugin = str_replace("/","",str_replace(basename(__FILE__),"",plugin_basename( __FILE__))) ; $trans = new translationSL($this->pluginID, $plugin) ; $trans->enable_translation() ; $tabs->add_tab(__('Manage translations', $this->pluginID), ob_get_clean() , plugin_dir_url("/").'/'.str_replace(basename(__FILE__),"",plugin_basename(__FILE__))."core/img/tab_trad.png") ; } ob_start() ; $plugin = str_replace("/","",str_replace(basename(__FILE__),"",plugin_basename( __FILE__))) ; $trans = new feedbackSL($plugin, $this->pluginID) ; $trans->enable_feedback() ; $tabs->add_tab(__('Give feedback', $this->pluginID), ob_get_clean() , plugin_dir_url("/").'/'.str_replace(basename(__FILE__),"",plugin_basename(__FILE__))."core/img/tab_mail.png") ; ob_start() ; // A list of plugin slug to be excluded $exlude = array('wp-pirate-search') ; // Replace sedLex by your own author name $trans = new otherPlugins("sedLex", $exlude) ; $trans->list_plugins() ; $tabs->add_tab(__('Other plugins', $this->pluginID), ob_get_clean() , plugin_dir_url("/").'/'.str_replace(basename(__FILE__),"",plugin_basename(__FILE__))."core/img/tab_plug.png") ; echo $tabs->flush() ; // Before this comment, you may modify whatever you want //=============================================================================================== ?> signature ; ?>".sprintf(__('%s posts/articles have been analysed while there is %s posts/articles to be analysed (%s links found).', $this->pluginID), "".$verified."", "".$total."" , "".$nb_links."" )."
" ; echo "".__('If all posts/articles have not been analysed, the results cannot be displayed ... Thus, wait or force the verification!', $this->pluginID)."
" ; } else { echo "".sprintf(__('Each of the %s posts/articles has been analysed (%s links found).', $this->pluginID), "".$total."" , "".$nb_links."" )."
" ; // DETECT MISSING FILES ON HARD DISK echo "".__('The following files have been deleted on the hard disk but is still registered by Wordpress.', $this->pluginID)."
" ; echo "".__('You have to modify the post/page and thus to remove this file from the media manager.', $this->pluginID)."
" ; $table = new adminTable() ; $table->title(array(__('Title of the file', $this->pluginID), __('This file is used in', $this->pluginID))) ; $ligne = 0 ; foreach ($res as $r) { $ligne++ ; if ($r->titre=="") { $r->titre = $r->url ; } $all_id = explode(',',$r->attach_used_in) ; $post_used = "" ; foreach ($all_id as $ai) { if ($ai!="") { $tit_pos = get_the_title($ai); if ($tit_pos=="") { $tit_pos = __("No title", $this->pluginID) ; } $post_used .= "".$tit_pos." (".__('Edit', $this->pluginID).")
" ; } } if ($post_used == "") { $post_used = "".__("(Not used)", $this->pluginID)."
" ; } if ($r->id!=0){ $cel1 = new adminCell("url)."\">".$r->titre." (id))."\">".__('Edit', $this->pluginID).")
") ; } else { $cel1 = new adminCell("") ; } $cel2 = new adminCell($post_used) ; $table->add_line(array($cel1, $cel2), $ligne) ; } echo $table->flush() ; } else { echo "".__('No missing files.', $this->pluginID)."
" ; } // DETECT DUPLICATE FILES echo "".__('The following files are duplicated on the hard disk.', $this->pluginID)."
" ; echo "".__('You have to modify the post/page and thus to remove the extras files from the media manager.', $this->pluginID)."
" ; $ligne = 0 ; $old_sha1 = "" ; $nb_entr = 0 ; foreach ($res as $r) { if ($r->sha1!=$old_sha1) { if ($nb_entr!=0) { echo $table->flush() ; echo "" ; } $table = new adminTable() ; $table->title(array(__('Title of the file', $this->pluginID), __('This file is used in', $this->pluginID))) ; $nb_entr = 0 ; $old_sha1 = $r->sha1 ; } $nb_entr ++ ; $ligne++ ; if ($r->titre=="") { $r->titre = $r->url ; } $all_id = explode(',',$r->attach_used_in) ; $post_used = "" ; foreach ($all_id as $ai) { if ($ai!="") { $tit_pos = get_the_title($ai); if ($tit_pos=="") { $tit_pos = __("No title", $this->pluginID) ; } $post_used .= "
".$tit_pos." (".__('Edit', $this->pluginID).")
" ; } } if ($post_used == "") { $post_used = "".__("(Not used)", $this->pluginID)."
" ; } if ($r->id!=0){ $cel1 = new adminCell("url)."\">".$r->titre." (id))."\">".__('Edit', $this->pluginID).")
") ; } else { $cel1 = new adminCell("") ; } $cel2 = new adminCell($post_used) ; $table->add_line(array($cel1, $cel2), $ligne) ; } if ($nb_entr!=0) { echo $table->flush() ; } } else { echo "".__('No duplicate files.', $this->pluginID)."
" ; } // DETECT FILES THAT ARE NOT USED IN ANY PAGES echo "".__('The following files exists on the disk but does not seems to be used ...', $this->pluginID)."
" ; echo "".__('You may remove them from the media manager.', $this->pluginID)."
" ; $table = new adminTable() ; $table->title(array(__('Title of the file', $this->pluginID))) ; $ligne = 0 ; foreach ($res as $r) { $ligne++ ; if ($r->titre=="") { $r->titre = $r->url ; } $cel1 = new adminCell("url)."\">".$r->titre." (id))."\">".__('Edit', $this->pluginID).")
") ; $table->add_line(array($cel1), $ligne) ; } echo $table->flush() ; } else { echo "".__('No unused files.', $this->pluginID)."
" ; } // DETECT FILES THAT ARE ON THE DISK BUT NOT HANDLED BY THE MEDIA MANAGER } } /** ==================================================================================================================================================== * Ajax Callback to force attachment anaysis * @return void */ function forceAnalysisAttachments() { global $post, $wpdb ; // Initialize the list $at = $this->get_param('list_post_id_to_check') ; if (empty($at)) { // We get the post $args = array( 'posts_per_page' => intval($this->get_param('max_page_to_check')), 'orderby' => 'rand', 'post_type' => explode(",",$this->get_param('type_page')), 'fields' => 'ids', 'post_status' => 'publish' ); $myQuery = new WP_Query( $args ); //Looping through the posts $post_temp = array() ; while ( $myQuery->have_posts() ) { $myQuery->the_post(); $post_temp[] = $post; } // Reset Post Data wp_reset_postdata(); $this->set_param('list_post_id_to_check', $post_temp) ; $this->set_param('nb_post_to_check', count($post_temp)) ; } // Get the first post of the list $post_temp = $this->get_param('list_post_id_to_check') ; $pid = array_pop($post_temp) ; $this->set_param('list_post_id_to_check', $post_temp) ; $this->check_post_for_attachments($pid,false) ; $this->displayTable() ; $at = $this->get_param('list_post_id_to_check') ; if (empty($at)) { $this->set_param('nb_post_to_check', 0) ; } else { $pc = floor(100*($this->get_param('nb_post_to_check')-count($this->get_param('list_post_id_to_check')))/$this->get_param('nb_post_to_check')) ; $pb = new progressBarAdmin(500, 20, $pc, "PROGRESS - ".($this->get_param('nb_post_to_check')-count($this->get_param('list_post_id_to_check')))." / ".$this->get_param('nb_post_to_check')) ; echo "