code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
<?php /** * Deprecated multisite admin functions from past WordPress versions and WordPress MU. * You shouldn't use these functions and look for the alternatives instead. The functions * will be removed in a later version. * * @package WordPress * @subpackage Deprecated * @since 3.0.0 */ /** * @deprecated 3.0.0 */ function wpmu_menu() { _deprecated_function(__FUNCTION__, '3.0' ); // deprecated. See #11763 } /** * Determines if the available space defined by the admin has been exceeded by the user. * * @deprecated 3.0.0 * @see is_upload_space_available() */ function wpmu_checkAvailableSpace() { _deprecated_function(__FUNCTION__, '3.0', 'is_upload_space_available()' ); if ( !is_upload_space_available() ) wp_die( __('Sorry, you must delete files before you can upload any more.') ); } /** * @deprecated 3.0.0 */ function mu_options( $options ) { _deprecated_function(__FUNCTION__, '3.0' ); return $options; } /** * @deprecated 3.0.0 * @see activate_plugin() */ function activate_sitewide_plugin() { _deprecated_function(__FUNCTION__, '3.0', 'activate_plugin()' ); return false; } /** * @deprecated 3.0.0 * @see deactivate_sitewide_plugin() */ function deactivate_sitewide_plugin( $plugin = false ) { _deprecated_function(__FUNCTION__, '3.0', 'deactivate_plugin()' ); return; } /** * @deprecated 3.0.0 * @see is_network_only_plugin() */ function is_wpmu_sitewide_plugin( $file ) { _deprecated_function(__FUNCTION__, '3.0', 'is_network_only_plugin()' ); return is_network_only_plugin( $file ); } function get_site_allowed_themes() { _deprecated_function( __FUNCTION__, '3.4', 'WP_Theme::get_allowed_on_network()' ); return array_map( 'intval', WP_Theme::get_allowed_on_network() ); } function wpmu_get_blog_allowedthemes( $blog_id = 0 ) { _deprecated_function( __FUNCTION__, '3.4', 'WP_Theme::get_allowed_on_site()' ); return array_map( 'intval', WP_Theme::get_allowed_on_site( $blog_id ) ); } function ms_deprecated_blogs_file() {}
zyblog
trunk/zyblog/wp-admin/includes/ms-deprecated.php
PHP
asf20
1,995
<?php /** * Links Manager List Table class. * * @package WordPress * @subpackage List_Table * @since 3.1.0 * @access private */ class WP_Links_List_Table extends WP_List_Table { function __construct( $args = array() ) { parent::__construct( array( 'plural' => 'bookmarks', 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); } function ajax_user_can() { return current_user_can( 'manage_links' ); } function prepare_items() { global $cat_id, $s, $orderby, $order; wp_reset_vars( array( 'action', 'cat_id', 'linkurl', 'name', 'image', 'description', 'visible', 'target', 'category', 'link_id', 'submit', 'orderby', 'order', 'links_show_cat_id', 'rating', 'rel', 'notes', 'linkcheck[]', 's' ) ); $args = array( 'hide_invisible' => 0, 'hide_empty' => 0 ); if ( 'all' != $cat_id ) $args['category'] = $cat_id; if ( !empty( $s ) ) $args['search'] = $s; if ( !empty( $orderby ) ) $args['orderby'] = $orderby; if ( !empty( $order ) ) $args['order'] = $order; $this->items = get_bookmarks( $args ); } function no_items() { _e( 'No links found.' ); } function get_bulk_actions() { $actions = array(); $actions['delete'] = __( 'Delete' ); return $actions; } function extra_tablenav( $which ) { global $cat_id; if ( 'top' != $which ) return; ?> <div class="alignleft actions"> <?php $dropdown_options = array( 'selected' => $cat_id, 'name' => 'cat_id', 'taxonomy' => 'link_category', 'show_option_all' => __( 'View all categories' ), 'hide_empty' => true, 'hierarchical' => 1, 'show_count' => 0, 'orderby' => 'name', ); wp_dropdown_categories( $dropdown_options ); submit_button( __( 'Filter' ), 'button', false, false, array( 'id' => 'post-query-submit' ) ); ?> </div> <?php } function get_columns() { return array( 'cb' => '<input type="checkbox" />', 'name' => _x( 'Name', 'link name' ), 'url' => __( 'URL' ), 'categories' => __( 'Categories' ), 'rel' => __( 'Relationship' ), 'visible' => __( 'Visible' ), 'rating' => __( 'Rating' ) ); } function get_sortable_columns() { return array( 'name' => 'name', 'url' => 'url', 'visible' => 'visible', 'rating' => 'rating' ); } function display_rows() { global $cat_id; $alt = 0; foreach ( $this->items as $link ) { $link = sanitize_bookmark( $link ); $link->link_name = esc_attr( $link->link_name ); $link->link_category = wp_get_link_cats( $link->link_id ); $short_url = url_shorten( $link->link_url ); $visible = ( $link->link_visible == 'Y' ) ? __( 'Yes' ) : __( 'No' ); $rating = $link->link_rating; $style = ( $alt++ % 2 ) ? '' : ' class="alternate"'; $edit_link = get_edit_bookmark_link( $link ); ?> <tr id="link-<?php echo $link->link_id; ?>" valign="middle" <?php echo $style; ?>> <?php list( $columns, $hidden ) = $this->get_column_info(); foreach ( $columns as $column_name => $column_display_name ) { $class = "class='column-$column_name'"; $style = ''; if ( in_array( $column_name, $hidden ) ) $style = ' style="display:none;"'; $attributes = $class . $style; switch ( $column_name ) { case 'cb': ?> <th scope="row" class="check-column"> <label class="screen-reader-text" for="cb-select-<?php echo $link->link_id; ?>"><?php echo sprintf( __( 'Select %s' ), $link->link_name ); ?></label> <input type="checkbox" name="linkcheck[]" id="cb-select-<?php echo $link->link_id; ?>" value="<?php echo esc_attr( $link->link_id ); ?>" /> </th> <?php break; case 'name': echo "<td $attributes><strong><a class='row-title' href='$edit_link' title='" . esc_attr( sprintf( __( 'Edit &#8220;%s&#8221;' ), $link->link_name ) ) . "'>$link->link_name</a></strong><br />"; $actions = array(); $actions['edit'] = '<a href="' . $edit_link . '">' . __( 'Edit' ) . '</a>'; $actions['delete'] = "<a class='submitdelete' href='" . wp_nonce_url( "link.php?action=delete&amp;link_id=$link->link_id", 'delete-bookmark_' . $link->link_id ) . "' onclick=\"if ( confirm( '" . esc_js( sprintf( __( "You are about to delete this link '%s'\n 'Cancel' to stop, 'OK' to delete." ), $link->link_name ) ) . "' ) ) { return true;}return false;\">" . __( 'Delete' ) . "</a>"; echo $this->row_actions( $actions ); echo '</td>'; break; case 'url': echo "<td $attributes><a href='$link->link_url' title='". esc_attr( sprintf( __( 'Visit %s' ), $link->link_name ) )."'>$short_url</a></td>"; break; case 'categories': ?><td <?php echo $attributes ?>><?php $cat_names = array(); foreach ( $link->link_category as $category ) { $cat = get_term( $category, 'link_category', OBJECT, 'display' ); if ( is_wp_error( $cat ) ) echo $cat->get_error_message(); $cat_name = $cat->name; if ( $cat_id != $category ) $cat_name = "<a href='link-manager.php?cat_id=$category'>$cat_name</a>"; $cat_names[] = $cat_name; } echo implode( ', ', $cat_names ); ?></td><?php break; case 'rel': ?><td <?php echo $attributes ?>><?php echo empty( $link->link_rel ) ? '<br />' : $link->link_rel; ?></td><?php break; case 'visible': ?><td <?php echo $attributes ?>><?php echo $visible; ?></td><?php break; case 'rating': ?><td <?php echo $attributes ?>><?php echo $rating; ?></td><?php break; default: ?> <td <?php echo $attributes ?>><?php do_action( 'manage_link_custom_column', $column_name, $link->link_id ); ?></td> <?php break; } } ?> </tr> <?php } } }
zyblog
trunk/zyblog/wp-admin/includes/class-wp-links-list-table.php
PHP
asf20
5,751
<?php /** * Misc WordPress Administration API. * * @package WordPress * @subpackage Administration */ /** * {@internal Missing Short Description}} * * @since 2.0.0 * * @return unknown */ function got_mod_rewrite() { $got_rewrite = apache_mod_loaded('mod_rewrite', true); return apply_filters('got_rewrite', $got_rewrite); } /** * {@internal Missing Short Description}} * * @since 1.5.0 * * @param unknown_type $filename * @param unknown_type $marker * @return array An array of strings from a file (.htaccess ) from between BEGIN and END markers. */ function extract_from_markers( $filename, $marker ) { $result = array (); if (!file_exists( $filename ) ) { return $result; } if ( $markerdata = explode( "\n", implode( '', file( $filename ) ) )); { $state = false; foreach ( $markerdata as $markerline ) { if (strpos($markerline, '# END ' . $marker) !== false) $state = false; if ( $state ) $result[] = $markerline; if (strpos($markerline, '# BEGIN ' . $marker) !== false) $state = true; } } return $result; } /** * {@internal Missing Short Description}} * * Inserts an array of strings into a file (.htaccess ), placing it between * BEGIN and END markers. Replaces existing marked info. Retains surrounding * data. Creates file if none exists. * * @since 1.5.0 * * @param unknown_type $filename * @param unknown_type $marker * @param unknown_type $insertion * @return bool True on write success, false on failure. */ function insert_with_markers( $filename, $marker, $insertion ) { if (!file_exists( $filename ) || is_writeable( $filename ) ) { if (!file_exists( $filename ) ) { $markerdata = ''; } else { $markerdata = explode( "\n", implode( '', file( $filename ) ) ); } if ( !$f = @fopen( $filename, 'w' ) ) return false; $foundit = false; if ( $markerdata ) { $state = true; foreach ( $markerdata as $n => $markerline ) { if (strpos($markerline, '# BEGIN ' . $marker) !== false) $state = false; if ( $state ) { if ( $n + 1 < count( $markerdata ) ) fwrite( $f, "{$markerline}\n" ); else fwrite( $f, "{$markerline}" ); } if (strpos($markerline, '# END ' . $marker) !== false) { fwrite( $f, "# BEGIN {$marker}\n" ); if ( is_array( $insertion )) foreach ( $insertion as $insertline ) fwrite( $f, "{$insertline}\n" ); fwrite( $f, "# END {$marker}\n" ); $state = true; $foundit = true; } } } if (!$foundit) { fwrite( $f, "\n# BEGIN {$marker}\n" ); foreach ( $insertion as $insertline ) fwrite( $f, "{$insertline}\n" ); fwrite( $f, "# END {$marker}\n" ); } fclose( $f ); return true; } else { return false; } } /** * Updates the htaccess file with the current rules if it is writable. * * Always writes to the file if it exists and is writable to ensure that we * blank out old rules. * * @since 1.5.0 */ function save_mod_rewrite_rules() { if ( is_multisite() ) return; global $wp_rewrite; $home_path = get_home_path(); $htaccess_file = $home_path.'.htaccess'; // If the file doesn't already exist check for write access to the directory and whether we have some rules. // else check for write access to the file. if ((!file_exists($htaccess_file) && is_writable($home_path) && $wp_rewrite->using_mod_rewrite_permalinks()) || is_writable($htaccess_file)) { if ( got_mod_rewrite() ) { $rules = explode( "\n", $wp_rewrite->mod_rewrite_rules() ); return insert_with_markers( $htaccess_file, 'WordPress', $rules ); } } return false; } /** * Updates the IIS web.config file with the current rules if it is writable. * If the permalinks do not require rewrite rules then the rules are deleted from the web.config file. * * @since 2.8.0 * * @return bool True if web.config was updated successfully */ function iis7_save_url_rewrite_rules(){ if ( is_multisite() ) return; global $wp_rewrite; $home_path = get_home_path(); $web_config_file = $home_path . 'web.config'; // Using win_is_writable() instead of is_writable() because of a bug in Windows PHP if ( iis7_supports_permalinks() && ( ( ! file_exists($web_config_file) && win_is_writable($home_path) && $wp_rewrite->using_mod_rewrite_permalinks() ) || win_is_writable($web_config_file) ) ) { $rule = $wp_rewrite->iis7_url_rewrite_rules(false, '', ''); if ( ! empty($rule) ) { return iis7_add_rewrite_rule($web_config_file, $rule); } else { return iis7_delete_rewrite_rule($web_config_file); } } return false; } /** * {@internal Missing Short Description}} * * @since 1.5.0 * * @param unknown_type $file */ function update_recently_edited( $file ) { $oldfiles = (array ) get_option( 'recently_edited' ); if ( $oldfiles ) { $oldfiles = array_reverse( $oldfiles ); $oldfiles[] = $file; $oldfiles = array_reverse( $oldfiles ); $oldfiles = array_unique( $oldfiles ); if ( 5 < count( $oldfiles )) array_pop( $oldfiles ); } else { $oldfiles[] = $file; } update_option( 'recently_edited', $oldfiles ); } /** * If siteurl, home or page_on_front changed, flush rewrite rules. * * @since 2.1.0 * * @param string $old_value * @param string $value */ function update_home_siteurl( $old_value, $value ) { if ( defined( "WP_INSTALLING" ) ) return; // If home changed, write rewrite rules to new location. flush_rewrite_rules(); } add_action( 'update_option_home', 'update_home_siteurl', 10, 2 ); add_action( 'update_option_siteurl', 'update_home_siteurl', 10, 2 ); add_action( 'update_option_page_on_front', 'update_home_siteurl', 10, 2 ); /** * Shorten an URL, to be used as link text * * @since 1.2.1 * * @param string $url * @return string */ function url_shorten( $url ) { $short_url = str_replace( 'http://', '', stripslashes( $url )); $short_url = str_replace( 'www.', '', $short_url ); $short_url = untrailingslashit( $short_url ); if ( strlen( $short_url ) > 35 ) $short_url = substr( $short_url, 0, 32 ) . '...'; return $short_url; } /** * Resets global variables based on $_GET and $_POST * * This function resets global variables based on the names passed * in the $vars array to the value of $_POST[$var] or $_GET[$var] or '' * if neither is defined. * * @since 2.0.0 * * @param array $vars An array of globals to reset. */ function wp_reset_vars( $vars ) { for ( $i=0; $i<count( $vars ); $i += 1 ) { $var = $vars[$i]; global $$var; if ( empty( $_POST[$var] ) ) { if ( empty( $_GET[$var] ) ) $$var = ''; else $$var = $_GET[$var]; } else { $$var = $_POST[$var]; } } } /** * {@internal Missing Short Description}} * * @since 2.1.0 * * @param unknown_type $message */ function show_message($message) { if ( is_wp_error($message) ){ if ( $message->get_error_data() ) $message = $message->get_error_message() . ': ' . $message->get_error_data(); else $message = $message->get_error_message(); } echo "<p>$message</p>\n"; wp_ob_end_flush_all(); flush(); } function wp_doc_link_parse( $content ) { if ( !is_string( $content ) || empty( $content ) ) return array(); if ( !function_exists('token_get_all') ) return array(); $tokens = token_get_all( $content ); $functions = array(); $ignore_functions = array(); for ( $t = 0, $count = count( $tokens ); $t < $count; $t++ ) { if ( !is_array( $tokens[$t] ) ) continue; if ( T_STRING == $tokens[$t][0] && ( '(' == $tokens[ $t + 1 ] || '(' == $tokens[ $t + 2 ] ) ) { // If it's a function or class defined locally, there's not going to be any docs available if ( ( isset( $tokens[ $t - 2 ][1] ) && in_array( $tokens[ $t - 2 ][1], array( 'function', 'class' ) ) ) || ( isset( $tokens[ $t - 2 ][0] ) && T_OBJECT_OPERATOR == $tokens[ $t - 1 ][0] ) ) { $ignore_functions[] = $tokens[$t][1]; } // Add this to our stack of unique references $functions[] = $tokens[$t][1]; } } $functions = array_unique( $functions ); sort( $functions ); $ignore_functions = apply_filters( 'documentation_ignore_functions', $ignore_functions ); $ignore_functions = array_unique( $ignore_functions ); $out = array(); foreach ( $functions as $function ) { if ( in_array( $function, $ignore_functions ) ) continue; $out[] = $function; } return $out; } /** * Saves option for number of rows when listing posts, pages, comments, etc. * * @since 2.8 **/ function set_screen_options() { if ( isset($_POST['wp_screen_options']) && is_array($_POST['wp_screen_options']) ) { check_admin_referer( 'screen-options-nonce', 'screenoptionnonce' ); if ( !$user = wp_get_current_user() ) return; $option = $_POST['wp_screen_options']['option']; $value = $_POST['wp_screen_options']['value']; if ( $option != sanitize_key( $option ) ) return; $map_option = $option; $type = str_replace('edit_', '', $map_option); $type = str_replace('_per_page', '', $type); if ( in_array( $type, get_taxonomies() ) ) $map_option = 'edit_tags_per_page'; elseif ( in_array( $type, get_post_types() ) ) $map_option = 'edit_per_page'; else $option = str_replace('-', '_', $option); switch ( $map_option ) { case 'edit_per_page': case 'users_per_page': case 'edit_comments_per_page': case 'upload_per_page': case 'edit_tags_per_page': case 'plugins_per_page': // Network admin case 'sites_network_per_page': case 'users_network_per_page': case 'site_users_network_per_page': case 'plugins_network_per_page': case 'themes_network_per_page': case 'site_themes_network_per_page': $value = (int) $value; if ( $value < 1 || $value > 999 ) return; break; default: $value = apply_filters('set-screen-option', false, $option, $value); if ( false === $value ) return; break; } update_user_meta($user->ID, $option, $value); wp_safe_redirect( remove_query_arg( array('pagenum', 'apage', 'paged'), wp_get_referer() ) ); exit; } } /** * Check if rewrite rule for WordPress already exists in the IIS 7 configuration file * * @since 2.8.0 * * @return bool * @param string $filename The file path to the configuration file */ function iis7_rewrite_rule_exists($filename) { if ( ! file_exists($filename) ) return false; if ( ! class_exists('DOMDocument') ) return false; $doc = new DOMDocument(); if ( $doc->load($filename) === false ) return false; $xpath = new DOMXPath($doc); $rules = $xpath->query('/configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'wordpress\')]'); if ( $rules->length == 0 ) return false; else return true; } /** * Delete WordPress rewrite rule from web.config file if it exists there * * @since 2.8.0 * * @param string $filename Name of the configuration file * @return bool */ function iis7_delete_rewrite_rule($filename) { // If configuration file does not exist then rules also do not exist so there is nothing to delete if ( ! file_exists($filename) ) return true; if ( ! class_exists('DOMDocument') ) return false; $doc = new DOMDocument(); $doc->preserveWhiteSpace = false; if ( $doc -> load($filename) === false ) return false; $xpath = new DOMXPath($doc); $rules = $xpath->query('/configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'wordpress\')]'); if ( $rules->length > 0 ) { $child = $rules->item(0); $parent = $child->parentNode; $parent->removeChild($child); $doc->formatOutput = true; saveDomDocument($doc, $filename); } return true; } /** * Add WordPress rewrite rule to the IIS 7 configuration file. * * @since 2.8.0 * * @param string $filename The file path to the configuration file * @param string $rewrite_rule The XML fragment with URL Rewrite rule * @return bool */ function iis7_add_rewrite_rule($filename, $rewrite_rule) { if ( ! class_exists('DOMDocument') ) return false; // If configuration file does not exist then we create one. if ( ! file_exists($filename) ) { $fp = fopen( $filename, 'w'); fwrite($fp, '<configuration/>'); fclose($fp); } $doc = new DOMDocument(); $doc->preserveWhiteSpace = false; if ( $doc->load($filename) === false ) return false; $xpath = new DOMXPath($doc); // First check if the rule already exists as in that case there is no need to re-add it $wordpress_rules = $xpath->query('/configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'wordpress\')]'); if ( $wordpress_rules->length > 0 ) return true; // Check the XPath to the rewrite rule and create XML nodes if they do not exist $xmlnodes = $xpath->query('/configuration/system.webServer/rewrite/rules'); if ( $xmlnodes->length > 0 ) { $rules_node = $xmlnodes->item(0); } else { $rules_node = $doc->createElement('rules'); $xmlnodes = $xpath->query('/configuration/system.webServer/rewrite'); if ( $xmlnodes->length > 0 ) { $rewrite_node = $xmlnodes->item(0); $rewrite_node->appendChild($rules_node); } else { $rewrite_node = $doc->createElement('rewrite'); $rewrite_node->appendChild($rules_node); $xmlnodes = $xpath->query('/configuration/system.webServer'); if ( $xmlnodes->length > 0 ) { $system_webServer_node = $xmlnodes->item(0); $system_webServer_node->appendChild($rewrite_node); } else { $system_webServer_node = $doc->createElement('system.webServer'); $system_webServer_node->appendChild($rewrite_node); $xmlnodes = $xpath->query('/configuration'); if ( $xmlnodes->length > 0 ) { $config_node = $xmlnodes->item(0); $config_node->appendChild($system_webServer_node); } else { $config_node = $doc->createElement('configuration'); $doc->appendChild($config_node); $config_node->appendChild($system_webServer_node); } } } } $rule_fragment = $doc->createDocumentFragment(); $rule_fragment->appendXML($rewrite_rule); $rules_node->appendChild($rule_fragment); $doc->encoding = "UTF-8"; $doc->formatOutput = true; saveDomDocument($doc, $filename); return true; } /** * Saves the XML document into a file * * @since 2.8.0 * * @param DOMDocument $doc * @param string $filename */ function saveDomDocument($doc, $filename) { $config = $doc->saveXML(); $config = preg_replace("/([^\r])\n/", "$1\r\n", $config); $fp = fopen($filename, 'w'); fwrite($fp, $config); fclose($fp); } /** * Display the default admin color scheme picker (Used in user-edit.php) * * @since 3.0.0 */ function admin_color_scheme_picker() { global $_wp_admin_css_colors, $user_id; ?> <fieldset><legend class="screen-reader-text"><span><?php _e('Admin Color Scheme')?></span></legend> <?php $current_color = get_user_option('admin_color', $user_id); if ( empty($current_color) ) $current_color = 'fresh'; foreach ( $_wp_admin_css_colors as $color => $color_info ): ?> <div class="color-option"><input name="admin_color" id="admin_color_<?php echo esc_attr( $color ); ?>" type="radio" value="<?php echo esc_attr( $color ); ?>" class="tog" <?php checked($color, $current_color); ?> /> <table class="color-palette"> <tr> <?php foreach ( $color_info->colors as $html_color ): ?> <td style="background-color: <?php echo esc_attr( $html_color ); ?>" title="<?php echo esc_attr( $color ); ?>">&nbsp;</td> <?php endforeach; ?> </tr> </table> <label for="admin_color_<?php echo esc_attr( $color ); ?>"><?php echo esc_html( $color_info->name ); ?></label> </div> <?php endforeach; ?> </fieldset> <?php } function _ipad_meta() { if ( wp_is_mobile() ) { ?> <meta name="viewport" id="viewport-meta" content="width=device-width, initial-scale=1"> <?php } } add_action('admin_head', '_ipad_meta');
zyblog
trunk/zyblog/wp-admin/includes/misc.php
PHP
asf20
15,591
<?php /** * WordPress core upgrade functionality. * * @package WordPress * @subpackage Administration * @since 2.7.0 */ /** * Stores files to be deleted. * * @since 2.7.0 * @global array $_old_files * @var array * @name $_old_files */ global $_old_files; $_old_files = array( // 2.0 'wp-admin/import-b2.php', 'wp-admin/import-blogger.php', 'wp-admin/import-greymatter.php', 'wp-admin/import-livejournal.php', 'wp-admin/import-mt.php', 'wp-admin/import-rss.php', 'wp-admin/import-textpattern.php', 'wp-admin/quicktags.js', 'wp-images/fade-butt.png', 'wp-images/get-firefox.png', 'wp-images/header-shadow.png', 'wp-images/smilies', 'wp-images/wp-small.png', 'wp-images/wpminilogo.png', 'wp.php', // 2.0.8 'wp-includes/js/tinymce/plugins/inlinepopups/readme.txt', // 2.1 'wp-admin/edit-form-ajax-cat.php', 'wp-admin/execute-pings.php', 'wp-admin/inline-uploading.php', 'wp-admin/link-categories.php', 'wp-admin/list-manipulation.js', 'wp-admin/list-manipulation.php', 'wp-includes/comment-functions.php', 'wp-includes/feed-functions.php', 'wp-includes/functions-compat.php', 'wp-includes/functions-formatting.php', 'wp-includes/functions-post.php', 'wp-includes/js/dbx-key.js', 'wp-includes/js/tinymce/plugins/autosave/langs/cs.js', 'wp-includes/js/tinymce/plugins/autosave/langs/sv.js', 'wp-includes/links.php', 'wp-includes/pluggable-functions.php', 'wp-includes/template-functions-author.php', 'wp-includes/template-functions-category.php', 'wp-includes/template-functions-general.php', 'wp-includes/template-functions-links.php', 'wp-includes/template-functions-post.php', 'wp-includes/wp-l10n.php', // 2.2 'wp-admin/cat-js.php', 'wp-admin/import/b2.php', 'wp-includes/js/autosave-js.php', 'wp-includes/js/list-manipulation-js.php', 'wp-includes/js/wp-ajax-js.php', // 2.3 'wp-admin/admin-db.php', 'wp-admin/cat.js', 'wp-admin/categories.js', 'wp-admin/custom-fields.js', 'wp-admin/dbx-admin-key.js', 'wp-admin/edit-comments.js', 'wp-admin/install-rtl.css', 'wp-admin/install.css', 'wp-admin/upgrade-schema.php', 'wp-admin/upload-functions.php', 'wp-admin/upload-rtl.css', 'wp-admin/upload.css', 'wp-admin/upload.js', 'wp-admin/users.js', 'wp-admin/widgets-rtl.css', 'wp-admin/widgets.css', 'wp-admin/xfn.js', 'wp-includes/js/tinymce/license.html', // 2.5 'wp-admin/css/upload.css', 'wp-admin/images/box-bg-left.gif', 'wp-admin/images/box-bg-right.gif', 'wp-admin/images/box-bg.gif', 'wp-admin/images/box-butt-left.gif', 'wp-admin/images/box-butt-right.gif', 'wp-admin/images/box-butt.gif', 'wp-admin/images/box-head-left.gif', 'wp-admin/images/box-head-right.gif', 'wp-admin/images/box-head.gif', 'wp-admin/images/heading-bg.gif', 'wp-admin/images/login-bkg-bottom.gif', 'wp-admin/images/login-bkg-tile.gif', 'wp-admin/images/notice.gif', 'wp-admin/images/toggle.gif', 'wp-admin/includes/upload.php', 'wp-admin/js/dbx-admin-key.js', 'wp-admin/js/link-cat.js', 'wp-admin/profile-update.php', 'wp-admin/templates.php', 'wp-includes/images/wlw/WpComments.png', 'wp-includes/images/wlw/WpIcon.png', 'wp-includes/images/wlw/WpWatermark.png', 'wp-includes/js/dbx.js', 'wp-includes/js/fat.js', 'wp-includes/js/list-manipulation.js', 'wp-includes/js/tinymce/langs/en.js', 'wp-includes/js/tinymce/plugins/autosave/editor_plugin_src.js', 'wp-includes/js/tinymce/plugins/autosave/langs', 'wp-includes/js/tinymce/plugins/directionality/images', 'wp-includes/js/tinymce/plugins/directionality/langs', 'wp-includes/js/tinymce/plugins/inlinepopups/css', 'wp-includes/js/tinymce/plugins/inlinepopups/images', 'wp-includes/js/tinymce/plugins/inlinepopups/jscripts', 'wp-includes/js/tinymce/plugins/paste/images', 'wp-includes/js/tinymce/plugins/paste/jscripts', 'wp-includes/js/tinymce/plugins/paste/langs', 'wp-includes/js/tinymce/plugins/spellchecker/classes/HttpClient.class.php', 'wp-includes/js/tinymce/plugins/spellchecker/classes/TinyGoogleSpell.class.php', 'wp-includes/js/tinymce/plugins/spellchecker/classes/TinyPspell.class.php', 'wp-includes/js/tinymce/plugins/spellchecker/classes/TinyPspellShell.class.php', 'wp-includes/js/tinymce/plugins/spellchecker/css/spellchecker.css', 'wp-includes/js/tinymce/plugins/spellchecker/images', 'wp-includes/js/tinymce/plugins/spellchecker/langs', 'wp-includes/js/tinymce/plugins/spellchecker/tinyspell.php', 'wp-includes/js/tinymce/plugins/wordpress/images', 'wp-includes/js/tinymce/plugins/wordpress/langs', 'wp-includes/js/tinymce/plugins/wordpress/wordpress.css', 'wp-includes/js/tinymce/plugins/wphelp', 'wp-includes/js/tinymce/themes/advanced/css', 'wp-includes/js/tinymce/themes/advanced/images', 'wp-includes/js/tinymce/themes/advanced/jscripts', 'wp-includes/js/tinymce/themes/advanced/langs', // 2.5.1 'wp-includes/js/tinymce/tiny_mce_gzip.php', // 2.6 'wp-admin/bookmarklet.php', 'wp-includes/js/jquery/jquery.dimensions.min.js', 'wp-includes/js/tinymce/plugins/wordpress/popups.css', 'wp-includes/js/wp-ajax.js', // 2.7 'wp-admin/css/press-this-ie-rtl.css', 'wp-admin/css/press-this-ie.css', 'wp-admin/css/upload-rtl.css', 'wp-admin/edit-form.php', 'wp-admin/images/comment-pill.gif', 'wp-admin/images/comment-stalk-classic.gif', 'wp-admin/images/comment-stalk-fresh.gif', 'wp-admin/images/comment-stalk-rtl.gif', 'wp-admin/images/del.png', 'wp-admin/images/gear.png', 'wp-admin/images/media-button-gallery.gif', 'wp-admin/images/media-buttons.gif', 'wp-admin/images/postbox-bg.gif', 'wp-admin/images/tab.png', 'wp-admin/images/tail.gif', 'wp-admin/js/forms.js', 'wp-admin/js/upload.js', 'wp-admin/link-import.php', 'wp-includes/images/audio.png', 'wp-includes/images/css.png', 'wp-includes/images/default.png', 'wp-includes/images/doc.png', 'wp-includes/images/exe.png', 'wp-includes/images/html.png', 'wp-includes/images/js.png', 'wp-includes/images/pdf.png', 'wp-includes/images/swf.png', 'wp-includes/images/tar.png', 'wp-includes/images/text.png', 'wp-includes/images/video.png', 'wp-includes/images/zip.png', 'wp-includes/js/tinymce/tiny_mce_config.php', 'wp-includes/js/tinymce/tiny_mce_ext.js', // 2.8 'wp-admin/js/users.js', 'wp-includes/js/swfupload/plugins/swfupload.documentready.js', 'wp-includes/js/swfupload/plugins/swfupload.graceful_degradation.js', 'wp-includes/js/swfupload/swfupload_f9.swf', 'wp-includes/js/tinymce/plugins/autosave', 'wp-includes/js/tinymce/plugins/paste/css', 'wp-includes/js/tinymce/utils/mclayer.js', 'wp-includes/js/tinymce/wordpress.css', // 2.8.5 'wp-admin/import/btt.php', 'wp-admin/import/jkw.php', // 2.9 'wp-admin/js/page.dev.js', 'wp-admin/js/page.js', 'wp-admin/js/set-post-thumbnail-handler.dev.js', 'wp-admin/js/set-post-thumbnail-handler.js', 'wp-admin/js/slug.dev.js', 'wp-admin/js/slug.js', 'wp-includes/gettext.php', 'wp-includes/js/tinymce/plugins/wordpress/js', 'wp-includes/streams.php', // MU 'README.txt', 'htaccess.dist', 'index-install.php', 'wp-admin/css/mu-rtl.css', 'wp-admin/css/mu.css', 'wp-admin/images/site-admin.png', 'wp-admin/includes/mu.php', 'wp-admin/wpmu-admin.php', 'wp-admin/wpmu-blogs.php', 'wp-admin/wpmu-edit.php', 'wp-admin/wpmu-options.php', 'wp-admin/wpmu-themes.php', 'wp-admin/wpmu-upgrade-site.php', 'wp-admin/wpmu-users.php', 'wp-includes/images/wordpress-mu.png', 'wp-includes/wpmu-default-filters.php', 'wp-includes/wpmu-functions.php', 'wpmu-settings.php', // 3.0 'wp-admin/categories.php', 'wp-admin/edit-category-form.php', 'wp-admin/edit-page-form.php', 'wp-admin/edit-pages.php', 'wp-admin/images/admin-header-footer.png', 'wp-admin/images/browse-happy.gif', 'wp-admin/images/ico-add.png', 'wp-admin/images/ico-close.png', 'wp-admin/images/ico-edit.png', 'wp-admin/images/ico-viewpage.png', 'wp-admin/images/fav-top.png', 'wp-admin/images/screen-options-left.gif', 'wp-admin/images/wp-logo-vs.gif', 'wp-admin/images/wp-logo.gif', 'wp-admin/import', 'wp-admin/js/wp-gears.dev.js', 'wp-admin/js/wp-gears.js', 'wp-admin/options-misc.php', 'wp-admin/page-new.php', 'wp-admin/page.php', 'wp-admin/rtl.css', 'wp-admin/rtl.dev.css', 'wp-admin/update-links.php', 'wp-admin/wp-admin.css', 'wp-admin/wp-admin.dev.css', 'wp-includes/js/codepress', 'wp-includes/js/codepress/engines/khtml.js', 'wp-includes/js/codepress/engines/older.js', 'wp-includes/js/jquery/autocomplete.dev.js', 'wp-includes/js/jquery/autocomplete.js', 'wp-includes/js/jquery/interface.js', 'wp-includes/js/scriptaculous/prototype.js', 'wp-includes/js/tinymce/wp-tinymce.js', // 3.1 'wp-admin/edit-attachment-rows.php', 'wp-admin/edit-link-categories.php', 'wp-admin/edit-link-category-form.php', 'wp-admin/edit-post-rows.php', 'wp-admin/images/button-grad-active-vs.png', 'wp-admin/images/button-grad-vs.png', 'wp-admin/images/fav-arrow-vs-rtl.gif', 'wp-admin/images/fav-arrow-vs.gif', 'wp-admin/images/fav-top-vs.gif', 'wp-admin/images/list-vs.png', 'wp-admin/images/screen-options-right-up.gif', 'wp-admin/images/screen-options-right.gif', 'wp-admin/images/visit-site-button-grad-vs.gif', 'wp-admin/images/visit-site-button-grad.gif', 'wp-admin/link-category.php', 'wp-admin/sidebar.php', 'wp-includes/classes.php', 'wp-includes/js/tinymce/blank.htm', 'wp-includes/js/tinymce/plugins/media/css/content.css', 'wp-includes/js/tinymce/plugins/media/img', 'wp-includes/js/tinymce/plugins/safari', // 3.2 'wp-admin/images/logo-login.gif', 'wp-admin/images/star.gif', 'wp-admin/js/list-table.dev.js', 'wp-admin/js/list-table.js', 'wp-includes/default-embeds.php', 'wp-includes/js/tinymce/plugins/wordpress/img/help.gif', 'wp-includes/js/tinymce/plugins/wordpress/img/more.gif', 'wp-includes/js/tinymce/plugins/wordpress/img/toolbars.gif', 'wp-includes/js/tinymce/themes/advanced/img/fm.gif', 'wp-includes/js/tinymce/themes/advanced/img/sflogo.png', // 3.3 'wp-admin/css/colors-classic-rtl.css', 'wp-admin/css/colors-classic-rtl.dev.css', 'wp-admin/css/colors-fresh-rtl.css', 'wp-admin/css/colors-fresh-rtl.dev.css', 'wp-admin/css/dashboard-rtl.css', 'wp-admin/css/dashboard-rtl.dev.css', 'wp-admin/css/dashboard.css', 'wp-admin/css/dashboard.dev.css', 'wp-admin/css/farbtastic-rtl.css', 'wp-admin/css/global-rtl.css', 'wp-admin/css/global-rtl.dev.css', 'wp-admin/css/global.css', 'wp-admin/css/global.dev.css', 'wp-admin/css/install-rtl.css', 'wp-admin/css/install-rtl.dev.css', 'wp-admin/css/login-rtl.css', 'wp-admin/css/login-rtl.dev.css', 'wp-admin/css/login.css', 'wp-admin/css/login.dev.css', 'wp-admin/css/ms.css', 'wp-admin/css/ms.dev.css', 'wp-admin/css/nav-menu-rtl.css', 'wp-admin/css/nav-menu-rtl.dev.css', 'wp-admin/css/nav-menu.css', 'wp-admin/css/nav-menu.dev.css', 'wp-admin/css/plugin-install-rtl.css', 'wp-admin/css/plugin-install-rtl.dev.css', 'wp-admin/css/plugin-install.css', 'wp-admin/css/plugin-install.dev.css', 'wp-admin/css/press-this-rtl.css', 'wp-admin/css/press-this-rtl.dev.css', 'wp-admin/css/press-this.css', 'wp-admin/css/press-this.dev.css', 'wp-admin/css/theme-editor-rtl.css', 'wp-admin/css/theme-editor-rtl.dev.css', 'wp-admin/css/theme-editor.css', 'wp-admin/css/theme-editor.dev.css', 'wp-admin/css/theme-install-rtl.css', 'wp-admin/css/theme-install-rtl.dev.css', 'wp-admin/css/theme-install.css', 'wp-admin/css/theme-install.dev.css', 'wp-admin/css/widgets-rtl.css', 'wp-admin/css/widgets-rtl.dev.css', 'wp-admin/css/widgets.css', 'wp-admin/css/widgets.dev.css', 'wp-admin/includes/internal-linking.php', 'wp-includes/images/admin-bar-sprite-rtl.png', 'wp-includes/js/jquery/ui.button.js', 'wp-includes/js/jquery/ui.core.js', 'wp-includes/js/jquery/ui.dialog.js', 'wp-includes/js/jquery/ui.draggable.js', 'wp-includes/js/jquery/ui.droppable.js', 'wp-includes/js/jquery/ui.mouse.js', 'wp-includes/js/jquery/ui.position.js', 'wp-includes/js/jquery/ui.resizable.js', 'wp-includes/js/jquery/ui.selectable.js', 'wp-includes/js/jquery/ui.sortable.js', 'wp-includes/js/jquery/ui.tabs.js', 'wp-includes/js/jquery/ui.widget.js', 'wp-includes/js/l10n.dev.js', 'wp-includes/js/l10n.js', 'wp-includes/js/tinymce/plugins/wplink/css', 'wp-includes/js/tinymce/plugins/wplink/img', 'wp-includes/js/tinymce/plugins/wplink/js', 'wp-includes/js/tinymce/themes/advanced/img/wpicons.png', 'wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/butt2.png', 'wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/button_bg.png', 'wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/down_arrow.gif', 'wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/fade-butt.png', 'wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/separator.gif', // Don't delete, yet: 'wp-rss.php', // Don't delete, yet: 'wp-rdf.php', // Don't delete, yet: 'wp-rss2.php', // Don't delete, yet: 'wp-commentsrss2.php', // Don't delete, yet: 'wp-atom.php', // Don't delete, yet: 'wp-feed.php', // 3.4 'wp-admin/images/gray-star.png', 'wp-admin/images/logo-login.png', 'wp-admin/images/star.png', 'wp-admin/index-extra.php', 'wp-admin/network/index-extra.php', 'wp-admin/user/index-extra.php', 'wp-admin/images/screenshots/admin-flyouts.png', 'wp-admin/images/screenshots/coediting.png', 'wp-admin/images/screenshots/drag-and-drop.png', 'wp-admin/images/screenshots/help-screen.png', 'wp-admin/images/screenshots/media-icon.png', 'wp-admin/images/screenshots/new-feature-pointer.png', 'wp-admin/images/screenshots/welcome-screen.png', 'wp-includes/css/editor-buttons.css', 'wp-includes/css/editor-buttons.dev.css', 'wp-includes/js/tinymce/plugins/paste/blank.htm', 'wp-includes/js/tinymce/plugins/wordpress/css', 'wp-includes/js/tinymce/plugins/wordpress/editor_plugin.dev.js', 'wp-includes/js/tinymce/plugins/wordpress/img/embedded.png', 'wp-includes/js/tinymce/plugins/wordpress/img/more_bug.gif', 'wp-includes/js/tinymce/plugins/wordpress/img/page_bug.gif', 'wp-includes/js/tinymce/plugins/wpdialogs/editor_plugin.dev.js', 'wp-includes/js/tinymce/plugins/wpeditimage/css/editimage-rtl.css', 'wp-includes/js/tinymce/plugins/wpeditimage/editor_plugin.dev.js', 'wp-includes/js/tinymce/plugins/wpfullscreen/editor_plugin.dev.js', 'wp-includes/js/tinymce/plugins/wpgallery/editor_plugin.dev.js', 'wp-includes/js/tinymce/plugins/wpgallery/img/gallery.png', 'wp-includes/js/tinymce/plugins/wplink/editor_plugin.dev.js', // Don't delete, yet: 'wp-pass.php', // Don't delete, yet: 'wp-register.php', // 3.5 'wp-admin/gears-manifest.php', 'wp-admin/includes/manifest.php', 'wp-admin/images/archive-link.png', 'wp-admin/images/blue-grad.png', 'wp-admin/images/button-grad-active.png', 'wp-admin/images/button-grad.png', 'wp-admin/images/ed-bg-vs.gif', 'wp-admin/images/ed-bg.gif', 'wp-admin/images/fade-butt.png', 'wp-admin/images/fav-arrow-rtl.gif', 'wp-admin/images/fav-arrow.gif', 'wp-admin/images/fav-vs.png', 'wp-admin/images/fav.png', 'wp-admin/images/gray-grad.png', 'wp-admin/images/loading-publish.gif', 'wp-admin/images/logo-ghost.png', 'wp-admin/images/logo.gif', 'wp-admin/images/menu-arrow-frame-rtl.png', 'wp-admin/images/menu-arrow-frame.png', 'wp-admin/images/menu-arrows.gif', 'wp-admin/images/menu-bits-rtl-vs.gif', 'wp-admin/images/menu-bits-rtl.gif', 'wp-admin/images/menu-bits-vs.gif', 'wp-admin/images/menu-bits.gif', 'wp-admin/images/menu-dark-rtl-vs.gif', 'wp-admin/images/menu-dark-rtl.gif', 'wp-admin/images/menu-dark-vs.gif', 'wp-admin/images/menu-dark.gif', 'wp-admin/images/required.gif', 'wp-admin/images/screen-options-toggle-vs.gif', 'wp-admin/images/screen-options-toggle.gif', 'wp-admin/images/toggle-arrow-rtl.gif', 'wp-admin/images/toggle-arrow.gif', 'wp-admin/images/upload-classic.png', 'wp-admin/images/upload-fresh.png', 'wp-admin/images/white-grad-active.png', 'wp-admin/images/white-grad.png', 'wp-admin/images/widgets-arrow-vs.gif', 'wp-admin/images/widgets-arrow.gif', 'wp-admin/images/wpspin_dark.gif', 'wp-includes/images/upload.png', 'wp-includes/js/prototype.js', 'wp-includes/js/scriptaculous', 'wp-admin/css/wp-admin-rtl.dev.css', 'wp-admin/css/wp-admin.dev.css', 'wp-admin/css/media-rtl.dev.css', 'wp-admin/css/media.dev.css', 'wp-admin/css/colors-classic.dev.css', 'wp-admin/css/customize-controls-rtl.dev.css', 'wp-admin/css/customize-controls.dev.css', 'wp-admin/css/ie-rtl.dev.css', 'wp-admin/css/ie.dev.css', 'wp-admin/css/install.dev.css', 'wp-admin/css/colors-fresh.dev.css', 'wp-includes/js/customize-base.dev.js', 'wp-includes/js/json2.dev.js', 'wp-includes/js/comment-reply.dev.js', 'wp-includes/js/customize-preview.dev.js', 'wp-includes/js/wplink.dev.js', 'wp-includes/js/tw-sack.dev.js', 'wp-includes/js/wp-list-revisions.dev.js', 'wp-includes/js/autosave.dev.js', 'wp-includes/js/admin-bar.dev.js', 'wp-includes/js/quicktags.dev.js', 'wp-includes/js/wp-ajax-response.dev.js', 'wp-includes/js/wp-pointer.dev.js', 'wp-includes/js/hoverIntent.dev.js', 'wp-includes/js/colorpicker.dev.js', 'wp-includes/js/wp-lists.dev.js', 'wp-includes/js/customize-loader.dev.js', 'wp-includes/js/jquery/jquery.table-hotkeys.dev.js', 'wp-includes/js/jquery/jquery.color.dev.js', 'wp-includes/js/jquery/jquery.color.js', 'wp-includes/js/jquery/jquery.hotkeys.dev.js', 'wp-includes/js/jquery/jquery.form.dev.js', 'wp-includes/js/jquery/suggest.dev.js', 'wp-admin/js/xfn.dev.js', 'wp-admin/js/set-post-thumbnail.dev.js', 'wp-admin/js/comment.dev.js', 'wp-admin/js/theme.dev.js', 'wp-admin/js/cat.dev.js', 'wp-admin/js/password-strength-meter.dev.js', 'wp-admin/js/user-profile.dev.js', 'wp-admin/js/theme-preview.dev.js', 'wp-admin/js/post.dev.js', 'wp-admin/js/media-upload.dev.js', 'wp-admin/js/word-count.dev.js', 'wp-admin/js/plugin-install.dev.js', 'wp-admin/js/edit-comments.dev.js', 'wp-admin/js/media-gallery.dev.js', 'wp-admin/js/custom-fields.dev.js', 'wp-admin/js/custom-background.dev.js', 'wp-admin/js/common.dev.js', 'wp-admin/js/inline-edit-tax.dev.js', 'wp-admin/js/gallery.dev.js', 'wp-admin/js/utils.dev.js', 'wp-admin/js/widgets.dev.js', 'wp-admin/js/wp-fullscreen.dev.js', 'wp-admin/js/nav-menu.dev.js', 'wp-admin/js/dashboard.dev.js', 'wp-admin/js/link.dev.js', 'wp-admin/js/user-suggest.dev.js', 'wp-admin/js/postbox.dev.js', 'wp-admin/js/tags.dev.js', 'wp-admin/js/image-edit.dev.js', 'wp-admin/js/media.dev.js', 'wp-admin/js/customize-controls.dev.js', 'wp-admin/js/inline-edit-post.dev.js', 'wp-admin/js/categories.dev.js', 'wp-admin/js/editor.dev.js', 'wp-includes/js/tinymce/plugins/wpeditimage/js/editimage.dev.js', 'wp-includes/js/tinymce/plugins/wpdialogs/js/popup.dev.js', 'wp-includes/js/tinymce/plugins/wpdialogs/js/wpdialog.dev.js', 'wp-includes/js/plupload/handlers.dev.js', 'wp-includes/js/plupload/wp-plupload.dev.js', 'wp-includes/js/swfupload/handlers.dev.js', 'wp-includes/js/jcrop/jquery.Jcrop.dev.js', 'wp-includes/js/jcrop/jquery.Jcrop.js', 'wp-includes/js/jcrop/jquery.Jcrop.css', 'wp-includes/js/imgareaselect/jquery.imgareaselect.dev.js', 'wp-includes/css/wp-pointer.dev.css', 'wp-includes/css/editor.dev.css', 'wp-includes/css/jquery-ui-dialog.dev.css', 'wp-includes/css/admin-bar-rtl.dev.css', 'wp-includes/css/admin-bar.dev.css', 'wp-includes/js/jquery/ui/jquery.effects.clip.min.js', 'wp-includes/js/jquery/ui/jquery.effects.scale.min.js', 'wp-includes/js/jquery/ui/jquery.effects.blind.min.js', 'wp-includes/js/jquery/ui/jquery.effects.core.min.js', 'wp-includes/js/jquery/ui/jquery.effects.shake.min.js', 'wp-includes/js/jquery/ui/jquery.effects.fade.min.js', 'wp-includes/js/jquery/ui/jquery.effects.explode.min.js', 'wp-includes/js/jquery/ui/jquery.effects.slide.min.js', 'wp-includes/js/jquery/ui/jquery.effects.drop.min.js', 'wp-includes/js/jquery/ui/jquery.effects.highlight.min.js', 'wp-includes/js/jquery/ui/jquery.effects.bounce.min.js', 'wp-includes/js/jquery/ui/jquery.effects.pulsate.min.js', 'wp-includes/js/jquery/ui/jquery.effects.transfer.min.js', 'wp-includes/js/jquery/ui/jquery.effects.fold.min.js', ); /** * Stores new files in wp-content to copy * * The contents of this array indicate any new bundled plugins/themes which * should be installed with the WordPress Upgrade. These items will not be * re-installed in future upgrades, this behaviour is controlled by the * introduced version present here being older than the current installed version. * * The content of this array should follow the following format: * Filename (relative to wp-content) => Introduced version * Directories should be noted by suffixing it with a trailing slash (/) * * @since 3.2.0 * @global array $_new_bundled_files * @var array * @name $_new_bundled_files */ global $_new_bundled_files; $_new_bundled_files = array( 'plugins/akismet/' => '2.0', 'themes/twentyten/' => '3.0', 'themes/twentyeleven/' => '3.2', 'themes/twentytwelve/' => '3.5', ); /** * Upgrade the core of WordPress. * * This will create a .maintenance file at the base of the WordPress directory * to ensure that people can not access the web site, when the files are being * copied to their locations. * * The files in the {@link $_old_files} list will be removed and the new files * copied from the zip file after the database is upgraded. * * The files in the {@link $_new_bundled_files} list will be added to the installation * if the version is greater than or equal to the old version being upgraded. * * The steps for the upgrader for after the new release is downloaded and * unzipped is: * 1. Test unzipped location for select files to ensure that unzipped worked. * 2. Create the .maintenance file in current WordPress base. * 3. Copy new WordPress directory over old WordPress files. * 4. Upgrade WordPress to new version. * 4.1. Copy all files/folders other than wp-content * 4.2. Copy any language files to WP_LANG_DIR (which may differ from WP_CONTENT_DIR * 4.3. Copy any new bundled themes/plugins to their respective locations * 5. Delete new WordPress directory path. * 6. Delete .maintenance file. * 7. Remove old files. * 8. Delete 'update_core' option. * * There are several areas of failure. For instance if PHP times out before step * 6, then you will not be able to access any portion of your site. Also, since * the upgrade will not continue where it left off, you will not be able to * automatically remove old files and remove the 'update_core' option. This * isn't that bad. * * If the copy of the new WordPress over the old fails, then the worse is that * the new WordPress directory will remain. * * If it is assumed that every file will be copied over, including plugins and * themes, then if you edit the default theme, you should rename it, so that * your changes remain. * * @since 2.7.0 * * @param string $from New release unzipped path. * @param string $to Path to old WordPress installation. * @return WP_Error|null WP_Error on failure, null on success. */ function update_core($from, $to) { global $wp_filesystem, $_old_files, $_new_bundled_files, $wpdb; @set_time_limit( 300 ); // Sanity check the unzipped distribution apply_filters( 'update_feedback', __('Verifying the unpacked files&#8230;') ); $distro = ''; $roots = array( '/wordpress/', '/wordpress-mu/' ); foreach ( $roots as $root ) { if ( $wp_filesystem->exists( $from . $root . 'readme.html' ) && $wp_filesystem->exists( $from . $root . 'wp-includes/version.php' ) ) { $distro = $root; break; } } if ( ! $distro ) { $wp_filesystem->delete( $from, true ); return new WP_Error( 'insane_distro', __('The update could not be unpacked') ); } // Import $wp_version, $required_php_version, and $required_mysql_version from the new version $versions_file = $wp_filesystem->wp_content_dir() . 'upgrade/version-current.php'; if ( ! $wp_filesystem->copy( $from . $distro . 'wp-includes/version.php', $versions_file ) ) { $wp_filesystem->delete( $from, true ); return new WP_Error( 'copy_failed', __('Could not copy file.') ); } $wp_filesystem->chmod( $versions_file, FS_CHMOD_FILE ); require_once( WP_CONTENT_DIR . '/upgrade/version-current.php' ); $wp_filesystem->delete( $versions_file ); $php_version = phpversion(); $mysql_version = $wpdb->db_version(); $old_wp_version = $GLOBALS['wp_version']; // The version of WordPress we're updating from $development_build = ( false !== strpos( $old_wp_version . $wp_version, '-' ) ); // a dash in the version indicates a Development release $php_compat = version_compare( $php_version, $required_php_version, '>=' ); if ( file_exists( WP_CONTENT_DIR . '/db.php' ) && empty( $wpdb->is_mysql ) ) $mysql_compat = true; else $mysql_compat = version_compare( $mysql_version, $required_mysql_version, '>=' ); if ( !$mysql_compat || !$php_compat ) $wp_filesystem->delete($from, true); if ( !$mysql_compat && !$php_compat ) return new WP_Error( 'php_mysql_not_compatible', sprintf( __('The update cannot be installed because WordPress %1$s requires PHP version %2$s or higher and MySQL version %3$s or higher. You are running PHP version %4$s and MySQL version %5$s.'), $wp_version, $required_php_version, $required_mysql_version, $php_version, $mysql_version ) ); elseif ( !$php_compat ) return new WP_Error( 'php_not_compatible', sprintf( __('The update cannot be installed because WordPress %1$s requires PHP version %2$s or higher. You are running version %3$s.'), $wp_version, $required_php_version, $php_version ) ); elseif ( !$mysql_compat ) return new WP_Error( 'mysql_not_compatible', sprintf( __('The update cannot be installed because WordPress %1$s requires MySQL version %2$s or higher. You are running version %3$s.'), $wp_version, $required_mysql_version, $mysql_version ) ); apply_filters('update_feedback', __('Installing the latest version&#8230;')); // Create maintenance file to signal that we are upgrading $maintenance_string = '<?php $upgrading = ' . time() . '; ?>'; $maintenance_file = $to . '.maintenance'; $wp_filesystem->delete($maintenance_file); $wp_filesystem->put_contents($maintenance_file, $maintenance_string, FS_CHMOD_FILE); // Copy new versions of WP files into place. $result = _copy_dir($from . $distro, $to, array('wp-content') ); // Custom Content Directory needs updating now. // Copy Languages if ( !is_wp_error($result) && $wp_filesystem->is_dir($from . $distro . 'wp-content/languages') ) { if ( WP_LANG_DIR != ABSPATH . WPINC . '/languages' || @is_dir(WP_LANG_DIR) ) $lang_dir = WP_LANG_DIR; else $lang_dir = WP_CONTENT_DIR . '/languages'; if ( !@is_dir($lang_dir) && 0 === strpos($lang_dir, ABSPATH) ) { // Check the language directory exists first $wp_filesystem->mkdir($to . str_replace(ABSPATH, '', $lang_dir), FS_CHMOD_DIR); // If it's within the ABSPATH we can handle it here, otherwise they're out of luck. clearstatcache(); // for FTP, Need to clear the stat cache } if ( @is_dir($lang_dir) ) { $wp_lang_dir = $wp_filesystem->find_folder($lang_dir); if ( $wp_lang_dir ) $result = copy_dir($from . $distro . 'wp-content/languages/', $wp_lang_dir); } } // Copy New bundled plugins & themes // This gives us the ability to install new plugins & themes bundled with future versions of WordPress whilst avoiding the re-install upon upgrade issue. // $development_build controls us overwriting bundled themes and plugins when a non-stable release is being updated if ( !is_wp_error($result) && ( ! defined('CORE_UPGRADE_SKIP_NEW_BUNDLED') || ! CORE_UPGRADE_SKIP_NEW_BUNDLED ) ) { foreach ( (array) $_new_bundled_files as $file => $introduced_version ) { // If a $development_build or if $introduced version is greater than what the site was previously running if ( $development_build || version_compare( $introduced_version, $old_wp_version, '>' ) ) { $directory = ('/' == $file[ strlen($file)-1 ]); list($type, $filename) = explode('/', $file, 2); if ( 'plugins' == $type ) $dest = $wp_filesystem->wp_plugins_dir(); elseif ( 'themes' == $type ) $dest = trailingslashit($wp_filesystem->wp_themes_dir()); // Back-compat, ::wp_themes_dir() did not return trailingslash'd pre-3.2 else continue; if ( ! $directory ) { if ( ! $development_build && $wp_filesystem->exists( $dest . $filename ) ) continue; if ( ! $wp_filesystem->copy($from . $distro . 'wp-content/' . $file, $dest . $filename, FS_CHMOD_FILE) ) $result = new WP_Error('copy_failed', __('Could not copy file.'), $dest . $filename); } else { if ( ! $development_build && $wp_filesystem->is_dir( $dest . $filename ) ) continue; $wp_filesystem->mkdir($dest . $filename, FS_CHMOD_DIR); $_result = copy_dir( $from . $distro . 'wp-content/' . $file, $dest . $filename); if ( is_wp_error($_result) ) //If a error occurs partway through this final step, keep the error flowing through, but keep process going. $result = $_result; } } } //end foreach } // Handle $result error from the above blocks if ( is_wp_error($result) ) { $wp_filesystem->delete($maintenance_file); $wp_filesystem->delete($from, true); return $result; } // Remove old files foreach ( $_old_files as $old_file ) { $old_file = $to . $old_file; if ( !$wp_filesystem->exists($old_file) ) continue; $wp_filesystem->delete($old_file, true); } // Upgrade DB with separate request apply_filters('update_feedback', __('Upgrading database&#8230;')); $db_upgrade_url = admin_url('upgrade.php?step=upgrade_db'); wp_remote_post($db_upgrade_url, array('timeout' => 60)); // Remove working directory $wp_filesystem->delete($from, true); // Force refresh of update information if ( function_exists('delete_site_transient') ) delete_site_transient('update_core'); else delete_option('update_core'); // Remove maintenance file, we're done. $wp_filesystem->delete($maintenance_file); // If we made it this far: do_action( '_core_updated_successfully', $wp_version ); return $wp_version; } /** * Copies a directory from one location to another via the WordPress Filesystem Abstraction. * Assumes that WP_Filesystem() has already been called and setup. * * This is a temporary function for the 3.1 -> 3.2 upgrade only and will be removed in 3.3 * * @ignore * @since 3.2.0 * @see copy_dir() * * @param string $from source directory * @param string $to destination directory * @param array $skip_list a list of files/folders to skip copying * @return mixed WP_Error on failure, True on success. */ function _copy_dir($from, $to, $skip_list = array() ) { global $wp_filesystem; $dirlist = $wp_filesystem->dirlist($from); $from = trailingslashit($from); $to = trailingslashit($to); $skip_regex = ''; foreach ( (array)$skip_list as $key => $skip_file ) $skip_regex .= preg_quote($skip_file, '!') . '|'; if ( !empty($skip_regex) ) $skip_regex = '!(' . rtrim($skip_regex, '|') . ')$!i'; foreach ( (array) $dirlist as $filename => $fileinfo ) { if ( !empty($skip_regex) ) if ( preg_match($skip_regex, $from . $filename) ) continue; if ( 'f' == $fileinfo['type'] ) { if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) ) { // If copy failed, chmod file to 0644 and try again. $wp_filesystem->chmod($to . $filename, 0644); if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) ) return new WP_Error('copy_failed', __('Could not copy file.'), $to . $filename); } } elseif ( 'd' == $fileinfo['type'] ) { if ( !$wp_filesystem->is_dir($to . $filename) ) { if ( !$wp_filesystem->mkdir($to . $filename, FS_CHMOD_DIR) ) return new WP_Error('mkdir_failed', __('Could not create directory.'), $to . $filename); } $result = _copy_dir($from . $filename, $to . $filename, $skip_list); if ( is_wp_error($result) ) return $result; } } return true; } /** * Redirect to the About WordPress page after a successful upgrade. * * This function is only needed when the existing install is older than 3.4.0. * * @since 3.3.0 * */ function _redirect_to_about_wordpress( $new_version ) { global $wp_version, $pagenow, $action; if ( version_compare( $wp_version, '3.4-RC1', '>=' ) ) return; // Ensure we only run this on the update-core.php page. wp_update_core() could be called in other contexts. if ( 'update-core.php' != $pagenow ) return; if ( 'do-core-upgrade' != $action && 'do-core-reinstall' != $action ) return; // Load the updated default text localization domain for new strings load_default_textdomain(); // See do_core_upgrade() show_message( __('WordPress updated successfully') ); // self_admin_url() won't exist when upgrading from <= 3.0, so relative URLs are intentional. show_message( '<span class="hide-if-no-js">' . sprintf( __( 'Welcome to WordPress %1$s. You will be redirected to the About WordPress screen. If not, click <a href="%2$s">here</a>.' ), $new_version, 'about.php?updated' ) . '</span>' ); show_message( '<span class="hide-if-js">' . sprintf( __( 'Welcome to WordPress %1$s. <a href="%2$s">Learn more</a>.' ), $new_version, 'about.php?updated' ) . '</span>' ); echo '</div>'; ?> <script type="text/javascript"> window.location = 'about.php?updated'; </script> <?php // Include admin-footer.php and exit include(ABSPATH . 'wp-admin/admin-footer.php'); exit(); } add_action( '_core_updated_successfully', '_redirect_to_about_wordpress' );
zyblog
trunk/zyblog/wp-admin/includes/update-core.php
PHP
asf20
32,893
<?php /** * Includes all of the WordPress Administration API files. * * @package WordPress * @subpackage Administration */ if ( ! defined('WP_ADMIN') ) { // This file is being included from a file other than wp-admin/admin.php, so // some setup was skipped. Make sure the admin message catalog is loaded since // load_default_textdomain() will not have done so in this context. load_textdomain( 'default', WP_LANG_DIR . '/admin-' . get_locale() . '.mo' ); } /** WordPress Bookmark Administration API */ require_once(ABSPATH . 'wp-admin/includes/bookmark.php'); /** WordPress Comment Administration API */ require_once(ABSPATH . 'wp-admin/includes/comment.php'); /** WordPress Administration File API */ require_once(ABSPATH . 'wp-admin/includes/file.php'); /** WordPress Image Administration API */ require_once(ABSPATH . 'wp-admin/includes/image.php'); /** WordPress Media Administration API */ require_once(ABSPATH . 'wp-admin/includes/media.php'); /** WordPress Import Administration API */ require_once(ABSPATH . 'wp-admin/includes/import.php'); /** WordPress Misc Administration API */ require_once(ABSPATH . 'wp-admin/includes/misc.php'); /** WordPress Plugin Administration API */ require_once(ABSPATH . 'wp-admin/includes/plugin.php'); /** WordPress Post Administration API */ require_once(ABSPATH . 'wp-admin/includes/post.php'); /** WordPress Administration Screen API */ require_once(ABSPATH . 'wp-admin/includes/screen.php'); /** WordPress Taxonomy Administration API */ require_once(ABSPATH . 'wp-admin/includes/taxonomy.php'); /** WordPress Template Administration API */ require_once(ABSPATH . 'wp-admin/includes/template.php'); /** WordPress List Table Administration API and base class */ require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php'); require_once(ABSPATH . 'wp-admin/includes/list-table.php'); /** WordPress Theme Administration API */ require_once(ABSPATH . 'wp-admin/includes/theme.php'); /** WordPress User Administration API */ require_once(ABSPATH . 'wp-admin/includes/user.php'); /** WordPress Update Administration API */ require_once(ABSPATH . 'wp-admin/includes/update.php'); /** WordPress Deprecated Administration API */ require_once(ABSPATH . 'wp-admin/includes/deprecated.php'); /** WordPress Multisite support API */ if ( is_multisite() ) { require_once(ABSPATH . 'wp-admin/includes/ms.php'); require_once(ABSPATH . 'wp-admin/includes/ms-deprecated.php'); }
zyblog
trunk/zyblog/wp-admin/includes/admin.php
PHP
asf20
2,443
<?php /** * Plugins List Table class. * * @package WordPress * @subpackage List_Table * @since 3.1.0 * @access private */ class WP_Plugins_List_Table extends WP_List_Table { function __construct( $args = array() ) { global $status, $page; parent::__construct( array( 'plural' => 'plugins', 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); $status = 'all'; if ( isset( $_REQUEST['plugin_status'] ) && in_array( $_REQUEST['plugin_status'], array( 'active', 'inactive', 'recently_activated', 'upgrade', 'mustuse', 'dropins', 'search' ) ) ) $status = $_REQUEST['plugin_status']; if ( isset($_REQUEST['s']) ) $_SERVER['REQUEST_URI'] = add_query_arg('s', stripslashes($_REQUEST['s']) ); $page = $this->get_pagenum(); } function get_table_classes() { return array( 'widefat', $this->_args['plural'] ); } function ajax_user_can() { return current_user_can('activate_plugins'); } function prepare_items() { global $status, $plugins, $totals, $page, $orderby, $order, $s; wp_reset_vars( array( 'orderby', 'order', 's' ) ); $plugins = array( 'all' => apply_filters( 'all_plugins', get_plugins() ), 'search' => array(), 'active' => array(), 'inactive' => array(), 'recently_activated' => array(), 'upgrade' => array(), 'mustuse' => array(), 'dropins' => array() ); $screen = $this->screen; if ( ! is_multisite() || ( $screen->is_network && current_user_can('manage_network_plugins') ) ) { if ( apply_filters( 'show_advanced_plugins', true, 'mustuse' ) ) $plugins['mustuse'] = get_mu_plugins(); if ( apply_filters( 'show_advanced_plugins', true, 'dropins' ) ) $plugins['dropins'] = get_dropins(); if ( current_user_can( 'update_plugins' ) ) { $current = get_site_transient( 'update_plugins' ); foreach ( (array) $plugins['all'] as $plugin_file => $plugin_data ) { if ( isset( $current->response[ $plugin_file ] ) ) { $plugins['all'][ $plugin_file ]['update'] = true; $plugins['upgrade'][ $plugin_file ] = $plugins['all'][ $plugin_file ]; } } } } set_transient( 'plugin_slugs', array_keys( $plugins['all'] ), DAY_IN_SECONDS ); if ( ! $screen->is_network ) { $recently_activated = get_option( 'recently_activated', array() ); foreach ( $recently_activated as $key => $time ) if ( $time + WEEK_IN_SECONDS < time() ) unset( $recently_activated[$key] ); update_option( 'recently_activated', $recently_activated ); } foreach ( (array) $plugins['all'] as $plugin_file => $plugin_data ) { // Filter into individual sections if ( is_multisite() && ! $screen->is_network && is_network_only_plugin( $plugin_file ) ) { unset( $plugins['all'][ $plugin_file ] ); } elseif ( ! $screen->is_network && is_plugin_active_for_network( $plugin_file ) ) { unset( $plugins['all'][ $plugin_file ] ); } elseif ( ( ! $screen->is_network && is_plugin_active( $plugin_file ) ) || ( $screen->is_network && is_plugin_active_for_network( $plugin_file ) ) ) { $plugins['active'][ $plugin_file ] = $plugin_data; } else { if ( ! $screen->is_network && isset( $recently_activated[ $plugin_file ] ) ) // Was the plugin recently activated? $plugins['recently_activated'][ $plugin_file ] = $plugin_data; $plugins['inactive'][ $plugin_file ] = $plugin_data; } } if ( $s ) { $status = 'search'; $plugins['search'] = array_filter( $plugins['all'], array( &$this, '_search_callback' ) ); } $totals = array(); foreach ( $plugins as $type => $list ) $totals[ $type ] = count( $list ); if ( empty( $plugins[ $status ] ) && !in_array( $status, array( 'all', 'search' ) ) ) $status = 'all'; $this->items = array(); foreach ( $plugins[ $status ] as $plugin_file => $plugin_data ) { // Translate, Don't Apply Markup, Sanitize HTML $this->items[$plugin_file] = _get_plugin_data_markup_translate( $plugin_file, $plugin_data, false, true ); } $total_this_page = $totals[ $status ]; if ( $orderby ) { $orderby = ucfirst( $orderby ); $order = strtoupper( $order ); uasort( $this->items, array( &$this, '_order_callback' ) ); } $plugins_per_page = $this->get_items_per_page( str_replace( '-', '_', $screen->id . '_per_page' ), 999 ); $start = ( $page - 1 ) * $plugins_per_page; if ( $total_this_page > $plugins_per_page ) $this->items = array_slice( $this->items, $start, $plugins_per_page ); $this->set_pagination_args( array( 'total_items' => $total_this_page, 'per_page' => $plugins_per_page, ) ); } function _search_callback( $plugin ) { static $term; if ( is_null( $term ) ) $term = stripslashes( $_REQUEST['s'] ); foreach ( $plugin as $value ) if ( stripos( $value, $term ) !== false ) return true; return false; } function _order_callback( $plugin_a, $plugin_b ) { global $orderby, $order; $a = $plugin_a[$orderby]; $b = $plugin_b[$orderby]; if ( $a == $b ) return 0; if ( 'DESC' == $order ) return ( $a < $b ) ? 1 : -1; else return ( $a < $b ) ? -1 : 1; } function no_items() { global $plugins; if ( !empty( $plugins['all'] ) ) _e( 'No plugins found.' ); else _e( 'You do not appear to have any plugins available at this time.' ); } function get_columns() { global $status; return array( 'cb' => !in_array( $status, array( 'mustuse', 'dropins' ) ) ? '<input type="checkbox" />' : '', 'name' => __( 'Plugin' ), 'description' => __( 'Description' ), ); } function get_sortable_columns() { return array(); } function get_views() { global $totals, $status; $status_links = array(); foreach ( $totals as $type => $count ) { if ( !$count ) continue; switch ( $type ) { case 'all': $text = _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $count, 'plugins' ); break; case 'active': $text = _n( 'Active <span class="count">(%s)</span>', 'Active <span class="count">(%s)</span>', $count ); break; case 'recently_activated': $text = _n( 'Recently Active <span class="count">(%s)</span>', 'Recently Active <span class="count">(%s)</span>', $count ); break; case 'inactive': $text = _n( 'Inactive <span class="count">(%s)</span>', 'Inactive <span class="count">(%s)</span>', $count ); break; case 'mustuse': $text = _n( 'Must-Use <span class="count">(%s)</span>', 'Must-Use <span class="count">(%s)</span>', $count ); break; case 'dropins': $text = _n( 'Drop-ins <span class="count">(%s)</span>', 'Drop-ins <span class="count">(%s)</span>', $count ); break; case 'upgrade': $text = _n( 'Update Available <span class="count">(%s)</span>', 'Update Available <span class="count">(%s)</span>', $count ); break; } if ( 'search' != $type ) { $status_links[$type] = sprintf( "<a href='%s' %s>%s</a>", add_query_arg('plugin_status', $type, 'plugins.php'), ( $type == $status ) ? ' class="current"' : '', sprintf( $text, number_format_i18n( $count ) ) ); } } return $status_links; } function get_bulk_actions() { global $status; $actions = array(); if ( 'active' != $status ) $actions['activate-selected'] = $this->screen->is_network ? __( 'Network Activate' ) : __( 'Activate' ); if ( 'inactive' != $status && 'recent' != $status ) $actions['deactivate-selected'] = $this->screen->is_network ? __( 'Network Deactivate' ) : __( 'Deactivate' ); if ( !is_multisite() || $this->screen->is_network ) { if ( current_user_can( 'update_plugins' ) ) $actions['update-selected'] = __( 'Update' ); if ( current_user_can( 'delete_plugins' ) && ( 'active' != $status ) ) $actions['delete-selected'] = __( 'Delete' ); } return $actions; } function bulk_actions() { global $status; if ( in_array( $status, array( 'mustuse', 'dropins' ) ) ) return; parent::bulk_actions(); } function extra_tablenav( $which ) { global $status; if ( ! in_array($status, array('recently_activated', 'mustuse', 'dropins') ) ) return; echo '<div class="alignleft actions">'; if ( ! $this->screen->is_network && 'recently_activated' == $status ) submit_button( __( 'Clear List' ), 'button', 'clear-recent-list', false ); elseif ( 'top' == $which && 'mustuse' == $status ) echo '<p>' . sprintf( __( 'Files in the <code>%s</code> directory are executed automatically.' ), str_replace( ABSPATH, '/', WPMU_PLUGIN_DIR ) ) . '</p>'; elseif ( 'top' == $which && 'dropins' == $status ) echo '<p>' . sprintf( __( 'Drop-ins are advanced plugins in the <code>%s</code> directory that replace WordPress functionality when present.' ), str_replace( ABSPATH, '', WP_CONTENT_DIR ) ) . '</p>'; echo '</div>'; } function current_action() { if ( isset($_POST['clear-recent-list']) ) return 'clear-recent-list'; return parent::current_action(); } function display_rows() { global $status; if ( is_multisite() && ! $this->screen->is_network && in_array( $status, array( 'mustuse', 'dropins' ) ) ) return; foreach ( $this->items as $plugin_file => $plugin_data ) $this->single_row( array( $plugin_file, $plugin_data ) ); } function single_row( $item ) { global $status, $page, $s, $totals; list( $plugin_file, $plugin_data ) = $item; $context = $status; $screen = $this->screen; // preorder $actions = array( 'deactivate' => '', 'activate' => '', 'edit' => '', 'delete' => '', ); if ( 'mustuse' == $context ) { $is_active = true; } elseif ( 'dropins' == $context ) { $dropins = _get_dropins(); $plugin_name = $plugin_file; if ( $plugin_file != $plugin_data['Name'] ) $plugin_name .= '<br/>' . $plugin_data['Name']; if ( true === ( $dropins[ $plugin_file ][1] ) ) { // Doesn't require a constant $is_active = true; $description = '<p><strong>' . $dropins[ $plugin_file ][0] . '</strong></p>'; } elseif ( constant( $dropins[ $plugin_file ][1] ) ) { // Constant is true $is_active = true; $description = '<p><strong>' . $dropins[ $plugin_file ][0] . '</strong></p>'; } else { $is_active = false; $description = '<p><strong>' . $dropins[ $plugin_file ][0] . ' <span class="attention">' . __('Inactive:') . '</span></strong> ' . sprintf( __( 'Requires <code>%s</code> in <code>wp-config.php</code>.' ), "define('" . $dropins[ $plugin_file ][1] . "', true);" ) . '</p>'; } if ( $plugin_data['Description'] ) $description .= '<p>' . $plugin_data['Description'] . '</p>'; } else { if ( $screen->is_network ) $is_active = is_plugin_active_for_network( $plugin_file ); else $is_active = is_plugin_active( $plugin_file ); if ( $screen->is_network ) { if ( $is_active ) { if ( current_user_can( 'manage_network_plugins' ) ) $actions['deactivate'] = '<a href="' . wp_nonce_url('plugins.php?action=deactivate&amp;plugin=' . $plugin_file . '&amp;plugin_status=' . $context . '&amp;paged=' . $page . '&amp;s=' . $s, 'deactivate-plugin_' . $plugin_file) . '" title="' . esc_attr__('Deactivate this plugin') . '">' . __('Network Deactivate') . '</a>'; } else { if ( current_user_can( 'manage_network_plugins' ) ) $actions['activate'] = '<a href="' . wp_nonce_url('plugins.php?action=activate&amp;plugin=' . $plugin_file . '&amp;plugin_status=' . $context . '&amp;paged=' . $page . '&amp;s=' . $s, 'activate-plugin_' . $plugin_file) . '" title="' . esc_attr__('Activate this plugin for all sites in this network') . '" class="edit">' . __('Network Activate') . '</a>'; if ( current_user_can( 'delete_plugins' ) && ! is_plugin_active( $plugin_file ) ) $actions['delete'] = '<a href="' . wp_nonce_url('plugins.php?action=delete-selected&amp;checked[]=' . $plugin_file . '&amp;plugin_status=' . $context . '&amp;paged=' . $page . '&amp;s=' . $s, 'bulk-plugins') . '" title="' . esc_attr__('Delete this plugin') . '" class="delete">' . __('Delete') . '</a>'; } } else { if ( $is_active ) { $actions['deactivate'] = '<a href="' . wp_nonce_url('plugins.php?action=deactivate&amp;plugin=' . $plugin_file . '&amp;plugin_status=' . $context . '&amp;paged=' . $page . '&amp;s=' . $s, 'deactivate-plugin_' . $plugin_file) . '" title="' . esc_attr__('Deactivate this plugin') . '">' . __('Deactivate') . '</a>'; } else { $actions['activate'] = '<a href="' . wp_nonce_url('plugins.php?action=activate&amp;plugin=' . $plugin_file . '&amp;plugin_status=' . $context . '&amp;paged=' . $page . '&amp;s=' . $s, 'activate-plugin_' . $plugin_file) . '" title="' . esc_attr__('Activate this plugin') . '" class="edit">' . __('Activate') . '</a>'; if ( ! is_multisite() && current_user_can('delete_plugins') ) $actions['delete'] = '<a href="' . wp_nonce_url('plugins.php?action=delete-selected&amp;checked[]=' . $plugin_file . '&amp;plugin_status=' . $context . '&amp;paged=' . $page . '&amp;s=' . $s, 'bulk-plugins') . '" title="' . esc_attr__('Delete this plugin') . '" class="delete">' . __('Delete') . '</a>'; } // end if $is_active } // end if $screen->is_network if ( ( ! is_multisite() || $screen->is_network ) && current_user_can('edit_plugins') && is_writable(WP_PLUGIN_DIR . '/' . $plugin_file) ) $actions['edit'] = '<a href="plugin-editor.php?file=' . $plugin_file . '" title="' . esc_attr__('Open this file in the Plugin Editor') . '" class="edit">' . __('Edit') . '</a>'; } // end if $context $prefix = $screen->is_network ? 'network_admin_' : ''; $actions = apply_filters( $prefix . 'plugin_action_links', array_filter( $actions ), $plugin_file, $plugin_data, $context ); $actions = apply_filters( $prefix . "plugin_action_links_$plugin_file", $actions, $plugin_file, $plugin_data, $context ); $class = $is_active ? 'active' : 'inactive'; $checkbox_id = "checkbox_" . md5($plugin_data['Name']); if ( in_array( $status, array( 'mustuse', 'dropins' ) ) ) { $checkbox = ''; } else { $checkbox = "<label class='screen-reader-text' for='" . $checkbox_id . "' >" . sprintf( __( 'Select %s' ), $plugin_data['Name'] ) . "</label>" . "<input type='checkbox' name='checked[]' value='" . esc_attr( $plugin_file ) . "' id='" . $checkbox_id . "' />"; } if ( 'dropins' != $context ) { $description = '<p>' . ( $plugin_data['Description'] ? $plugin_data['Description'] : '&nbsp;' ) . '</p>'; $plugin_name = $plugin_data['Name']; } $id = sanitize_title( $plugin_name ); if ( ! empty( $totals['upgrade'] ) && ! empty( $plugin_data['update'] ) ) $class .= ' update'; echo "<tr id='$id' class='$class'>"; list( $columns, $hidden ) = $this->get_column_info(); foreach ( $columns as $column_name => $column_display_name ) { $style = ''; if ( in_array( $column_name, $hidden ) ) $style = ' style="display:none;"'; switch ( $column_name ) { case 'cb': echo "<th scope='row' class='check-column'>$checkbox</th>"; break; case 'name': echo "<td class='plugin-title'$style><strong>$plugin_name</strong>"; echo $this->row_actions( $actions, true ); echo "</td>"; break; case 'description': echo "<td class='column-description desc'$style> <div class='plugin-description'>$description</div> <div class='$class second plugin-version-author-uri'>"; $plugin_meta = array(); if ( !empty( $plugin_data['Version'] ) ) $plugin_meta[] = sprintf( __( 'Version %s' ), $plugin_data['Version'] ); if ( !empty( $plugin_data['Author'] ) ) { $author = $plugin_data['Author']; if ( !empty( $plugin_data['AuthorURI'] ) ) $author = '<a href="' . $plugin_data['AuthorURI'] . '" title="' . esc_attr__( 'Visit author homepage' ) . '">' . $plugin_data['Author'] . '</a>'; $plugin_meta[] = sprintf( __( 'By %s' ), $author ); } if ( ! empty( $plugin_data['PluginURI'] ) ) $plugin_meta[] = '<a href="' . $plugin_data['PluginURI'] . '" title="' . esc_attr__( 'Visit plugin site' ) . '">' . __( 'Visit plugin site' ) . '</a>'; $plugin_meta = apply_filters( 'plugin_row_meta', $plugin_meta, $plugin_file, $plugin_data, $status ); echo implode( ' | ', $plugin_meta ); echo "</div></td>"; break; default: echo "<td class='$column_name column-$column_name'$style>"; do_action( 'manage_plugins_custom_column', $column_name, $plugin_file, $plugin_data ); echo "</td>"; } } echo "</tr>"; do_action( 'after_plugin_row', $plugin_file, $plugin_data, $status ); do_action( "after_plugin_row_$plugin_file", $plugin_file, $plugin_data, $status ); } }
zyblog
trunk/zyblog/wp-admin/includes/class-wp-plugins-list-table.php
PHP
asf20
16,615
<?php /** * WordPress Theme Administration API * * @package WordPress * @subpackage Administration */ /** * Remove a theme * * @since 2.8.0 * * @param string $stylesheet Stylesheet of the theme to delete * @param string $redirect Redirect to page when complete. * @return mixed */ function delete_theme($stylesheet, $redirect = '') { global $wp_filesystem; if ( empty($stylesheet) ) return false; ob_start(); if ( empty( $redirect ) ) $redirect = wp_nonce_url('themes.php?action=delete&stylesheet=' . urlencode( $stylesheet ), 'delete-theme_' . $stylesheet); if ( false === ($credentials = request_filesystem_credentials($redirect)) ) { $data = ob_get_contents(); ob_end_clean(); if ( ! empty($data) ){ include_once( ABSPATH . 'wp-admin/admin-header.php'); echo $data; include( ABSPATH . 'wp-admin/admin-footer.php'); exit; } return; } if ( ! WP_Filesystem($credentials) ) { request_filesystem_credentials($url, '', true); // Failed to connect, Error and request again $data = ob_get_contents(); ob_end_clean(); if ( ! empty($data) ) { include_once( ABSPATH . 'wp-admin/admin-header.php'); echo $data; include( ABSPATH . 'wp-admin/admin-footer.php'); exit; } return; } if ( ! is_object($wp_filesystem) ) return new WP_Error('fs_unavailable', __('Could not access filesystem.')); if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() ) return new WP_Error('fs_error', __('Filesystem error.'), $wp_filesystem->errors); //Get the base plugin folder $themes_dir = $wp_filesystem->wp_themes_dir(); if ( empty($themes_dir) ) return new WP_Error('fs_no_themes_dir', __('Unable to locate WordPress theme directory.')); $themes_dir = trailingslashit( $themes_dir ); $theme_dir = trailingslashit($themes_dir . $stylesheet); $deleted = $wp_filesystem->delete($theme_dir, true); if ( ! $deleted ) return new WP_Error('could_not_remove_theme', sprintf(__('Could not fully remove the theme %s.'), $stylesheet) ); // Force refresh of theme update information delete_site_transient('update_themes'); return true; } /** * Get the Page Templates available in this theme * * @since 1.5.0 * * @return array Key is the template name, value is the filename of the template */ function get_page_templates() { return array_flip( wp_get_theme()->get_page_templates() ); } /** * Tidies a filename for url display by the theme editor. * * @since 2.9.0 * @access private * * @param string $fullpath Full path to the theme file * @param string $containingfolder Path of the theme parent folder * @return string */ function _get_template_edit_filename($fullpath, $containingfolder) { return str_replace(dirname(dirname( $containingfolder )) , '', $fullpath); } /** * Check if there is an update for a theme available. * * Will display link, if there is an update available. * * @since 2.7.0 * * @param object $theme Theme data object. * @return bool False if no valid info was passed. */ function theme_update_available( $theme ) { static $themes_update; if ( !current_user_can('update_themes' ) ) return; if ( !isset($themes_update) ) $themes_update = get_site_transient('update_themes'); if ( ! is_a( $theme, 'WP_Theme' ) ) return; $stylesheet = $theme->get_stylesheet(); if ( isset($themes_update->response[ $stylesheet ]) ) { $update = $themes_update->response[ $stylesheet ]; $theme_name = $theme->display('Name'); $details_url = add_query_arg(array('TB_iframe' => 'true', 'width' => 1024, 'height' => 800), $update['url']); //Theme browser inside WP? replace this, Also, theme preview JS will override this on the available list. $update_url = wp_nonce_url('update.php?action=upgrade-theme&amp;theme=' . urlencode($stylesheet), 'upgrade-theme_' . $stylesheet); $update_onclick = 'onclick="if ( confirm(\'' . esc_js( __("Updating this theme will lose any customizations you have made. 'Cancel' to stop, 'OK' to update.") ) . '\') ) {return true;}return false;"'; if ( !is_multisite() ) { if ( ! current_user_can('update_themes') ) printf( '<p><strong>' . __('There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%1$s">View version %3$s details</a>.') . '</strong></p>', $theme_name, $details_url, $update['new_version']); else if ( empty($update['package']) ) printf( '<p><strong>' . __('There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%1$s">View version %3$s details</a>. <em>Automatic update is unavailable for this theme.</em>') . '</strong></p>', $theme_name, $details_url, $update['new_version']); else printf( '<p><strong>' . __('There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%1$s">View version %3$s details</a> or <a href="%4$s" %5$s>update now</a>.') . '</strong></p>', $theme_name, $details_url, $update['new_version'], $update_url, $update_onclick ); } } } /** * Retrieve list of WordPress theme features (aka theme tags) * * @since 3.1.0 * * @param bool $api Optional. Whether try to fetch tags from the WP.org API. Defaults to true. * @return array Array of features keyed by category with translations keyed by slug. */ function get_theme_feature_list( $api = true ) { // Hard-coded list is used if api not accessible. $features = array( __( 'Colors' ) => array( 'black' => __( 'Black' ), 'blue' => __( 'Blue' ), 'brown' => __( 'Brown' ), 'gray' => __( 'Gray' ), 'green' => __( 'Green' ), 'orange' => __( 'Orange' ), 'pink' => __( 'Pink' ), 'purple' => __( 'Purple' ), 'red' => __( 'Red' ), 'silver' => __( 'Silver' ), 'tan' => __( 'Tan' ), 'white' => __( 'White' ), 'yellow' => __( 'Yellow' ), 'dark' => __( 'Dark' ), 'light' => __( 'Light' ), ), __( 'Columns' ) => array( 'one-column' => __( 'One Column' ), 'two-columns' => __( 'Two Columns' ), 'three-columns' => __( 'Three Columns' ), 'four-columns' => __( 'Four Columns' ), 'left-sidebar' => __( 'Left Sidebar' ), 'right-sidebar' => __( 'Right Sidebar' ), ), __( 'Width' ) => array( 'fixed-width' => __( 'Fixed Width' ), 'flexible-width' => __( 'Flexible Width' ), ), __( 'Features' ) => array( 'blavatar' => __( 'Blavatar' ), 'buddypress' => __( 'BuddyPress' ), 'custom-background' => __( 'Custom Background' ), 'custom-colors' => __( 'Custom Colors' ), 'custom-header' => __( 'Custom Header' ), 'custom-menu' => __( 'Custom Menu' ), 'editor-style' => __( 'Editor Style' ), 'featured-image-header' => __( 'Featured Image Header' ), 'featured-images' => __( 'Featured Images' ), 'flexible-header' => __( 'Flexible Header' ), 'front-page-post-form' => __( 'Front Page Posting' ), 'full-width-template' => __( 'Full Width Template' ), 'microformats' => __( 'Microformats' ), 'post-formats' => __( 'Post Formats' ), 'rtl-language-support' => __( 'RTL Language Support' ), 'sticky-post' => __( 'Sticky Post' ), 'theme-options' => __( 'Theme Options' ), 'threaded-comments' => __( 'Threaded Comments' ), 'translation-ready' => __( 'Translation Ready' ), ), __( 'Subject' ) => array( 'holiday' => __( 'Holiday' ), 'photoblogging' => __( 'Photoblogging' ), 'seasonal' => __( 'Seasonal' ), ) ); if ( ! $api || ! current_user_can( 'install_themes' ) ) return $features; if ( !$feature_list = get_site_transient( 'wporg_theme_feature_list' ) ) set_site_transient( 'wporg_theme_feature_list', array( ), 10800); if ( !$feature_list ) { $feature_list = themes_api( 'feature_list', array( ) ); if ( is_wp_error( $feature_list ) ) return $features; } if ( !$feature_list ) return $features; set_site_transient( 'wporg_theme_feature_list', $feature_list, 10800 ); $category_translations = array( 'Colors' => __('Colors'), 'Columns' => __('Columns'), 'Width' => __('Width'), 'Features' => __('Features'), 'Subject' => __('Subject') ); // Loop over the wporg canonical list and apply translations $wporg_features = array(); foreach ( (array) $feature_list as $feature_category => $feature_items ) { if ( isset($category_translations[$feature_category]) ) $feature_category = $category_translations[$feature_category]; $wporg_features[$feature_category] = array(); foreach ( $feature_items as $feature ) { if ( isset($features[$feature_category][$feature]) ) $wporg_features[$feature_category][$feature] = $features[$feature_category][$feature]; else $wporg_features[$feature_category][$feature] = $feature; } } return $wporg_features; } /** * Retrieve theme installer pages from WordPress Themes API. * * It is possible for a theme to override the Themes API result with three * filters. Assume this is for themes, which can extend on the Theme Info to * offer more choices. This is very powerful and must be used with care, when * overridding the filters. * * The first filter, 'themes_api_args', is for the args and gives the action as * the second parameter. The hook for 'themes_api_args' must ensure that an * object is returned. * * The second filter, 'themes_api', is the result that would be returned. * * @since 2.8.0 * * @param string $action * @param array|object $args Optional. Arguments to serialize for the Theme Info API. * @return mixed */ function themes_api($action, $args = null) { if ( is_array($args) ) $args = (object)$args; if ( !isset($args->per_page) ) $args->per_page = 24; $args = apply_filters('themes_api_args', $args, $action); //NOTE: Ensure that an object is returned via this filter. $res = apply_filters('themes_api', false, $action, $args); //NOTE: Allows a theme to completely override the builtin WordPress.org API. if ( ! $res ) { $request = wp_remote_post('http://api.wordpress.org/themes/info/1.0/', array( 'body' => array('action' => $action, 'request' => serialize($args))) ); if ( is_wp_error($request) ) { $res = new WP_Error('themes_api_failed', __( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server&#8217;s configuration. If you continue to have problems, please try the <a href="http://wordpress.org/support/">support forums</a>.' ), $request->get_error_message() ); } else { $res = maybe_unserialize( wp_remote_retrieve_body( $request ) ); if ( ! is_object( $res ) && ! is_array( $res ) ) $res = new WP_Error('themes_api_failed', __( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server&#8217;s configuration. If you continue to have problems, please try the <a href="http://wordpress.org/support/">support forums</a>.' ), wp_remote_retrieve_body( $request ) ); } } return apply_filters('themes_api_result', $res, $action, $args); }
zyblog
trunk/zyblog/wp-admin/includes/theme.php
PHP
asf20
10,986
<?php /** * WordPress Image Editor * * @package WordPress * @subpackage Administration */ function wp_image_editor($post_id, $msg = false) { $nonce = wp_create_nonce("image_editor-$post_id"); $meta = wp_get_attachment_metadata($post_id); $thumb = image_get_intermediate_size($post_id, 'thumbnail'); $sub_sizes = isset($meta['sizes']) && is_array($meta['sizes']); $note = ''; if ( is_array($meta) && isset($meta['width']) ) $big = max( $meta['width'], $meta['height'] ); else die( __('Image data does not exist. Please re-upload the image.') ); $sizer = $big > 400 ? 400 / $big : 1; $backup_sizes = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true ); $can_restore = !empty($backup_sizes) && isset($backup_sizes['full-orig']) && $backup_sizes['full-orig']['file'] != basename($meta['file']); if ( $msg ) { if ( isset($msg->error) ) $note = "<div class='error'><p>$msg->error</p></div>"; elseif ( isset($msg->msg) ) $note = "<div class='updated'><p>$msg->msg</p></div>"; } ?> <div class="imgedit-wrap"> <?php echo $note; ?> <table id="imgedit-panel-<?php echo $post_id; ?>"><tbody> <tr><td> <div class="imgedit-menu"> <div onclick="imageEdit.crop(<?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-crop disabled" title="<?php esc_attr_e( 'Crop' ); ?>"></div><?php // On some setups GD library does not provide imagerotate() - Ticket #11536 if ( wp_image_editor_supports( array( 'mime_type' => get_post_mime_type( $post_id ), 'methods' => array( 'rotate' ) ) ) ) { ?> <div class="imgedit-rleft" onclick="imageEdit.rotate( 90, <?php echo "$post_id, '$nonce'"; ?>, this)" title="<?php esc_attr_e( 'Rotate counter-clockwise' ); ?>"></div> <div class="imgedit-rright" onclick="imageEdit.rotate(-90, <?php echo "$post_id, '$nonce'"; ?>, this)" title="<?php esc_attr_e( 'Rotate clockwise' ); ?>"></div> <?php } else { $note_no_rotate = esc_attr__('Image rotation is not supported by your web host.'); ?> <div class="imgedit-rleft disabled" title="<?php echo $note_no_rotate; ?>"></div> <div class="imgedit-rright disabled" title="<?php echo $note_no_rotate; ?>"></div> <?php } ?> <div onclick="imageEdit.flip(1, <?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-flipv" title="<?php esc_attr_e( 'Flip vertically' ); ?>"></div> <div onclick="imageEdit.flip(2, <?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-fliph" title="<?php esc_attr_e( 'Flip horizontally' ); ?>"></div> <div id="image-undo-<?php echo $post_id; ?>" onclick="imageEdit.undo(<?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-undo disabled" title="<?php esc_attr_e( 'Undo' ); ?>"></div> <div id="image-redo-<?php echo $post_id; ?>" onclick="imageEdit.redo(<?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-redo disabled" title="<?php esc_attr_e( 'Redo' ); ?>"></div> <br class="clear" /> </div> <input type="hidden" id="imgedit-sizer-<?php echo $post_id; ?>" value="<?php echo $sizer; ?>" /> <input type="hidden" id="imgedit-minthumb-<?php echo $post_id; ?>" value="<?php echo ( get_option('thumbnail_size_w') . ':' . get_option('thumbnail_size_h') ); ?>" /> <input type="hidden" id="imgedit-history-<?php echo $post_id; ?>" value="" /> <input type="hidden" id="imgedit-undone-<?php echo $post_id; ?>" value="0" /> <input type="hidden" id="imgedit-selection-<?php echo $post_id; ?>" value="" /> <input type="hidden" id="imgedit-x-<?php echo $post_id; ?>" value="<?php echo $meta['width']; ?>" /> <input type="hidden" id="imgedit-y-<?php echo $post_id; ?>" value="<?php echo $meta['height']; ?>" /> <div id="imgedit-crop-<?php echo $post_id; ?>" class="imgedit-crop-wrap"> <img id="image-preview-<?php echo $post_id; ?>" onload="imageEdit.imgLoaded('<?php echo $post_id; ?>')" src="<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>?action=imgedit-preview&amp;_ajax_nonce=<?php echo $nonce; ?>&amp;postid=<?php echo $post_id; ?>&amp;rand=<?php echo rand(1, 99999); ?>" /> </div> <div class="imgedit-submit"> <input type="button" onclick="imageEdit.close(<?php echo $post_id; ?>, 1)" class="button" value="<?php esc_attr_e( 'Cancel' ); ?>" /> <input type="button" onclick="imageEdit.save(<?php echo "$post_id, '$nonce'"; ?>)" disabled="disabled" class="button-primary imgedit-submit-btn" value="<?php esc_attr_e( 'Save' ); ?>" /> </div> </td> <td class="imgedit-settings"> <div class="imgedit-group"> <div class="imgedit-group-top"> <a class="imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;" href="#"><strong><?php _e('Scale Image'); ?></strong></a> <div class="imgedit-help"> <p><?php _e('You can proportionally scale the original image. For best results the scaling should be done before performing any other operations on it like crop, rotate, etc. Note that if you make the image larger it may become fuzzy.'); ?></p> <p><?php printf( __('Original dimensions %s'), $meta['width'] . '&times;' . $meta['height'] ); ?></p> <div class="imgedit-submit"> <span class="nowrap"><input type="text" id="imgedit-scale-width-<?php echo $post_id; ?>" onkeyup="imageEdit.scaleChanged(<?php echo $post_id; ?>, 1)" onblur="imageEdit.scaleChanged(<?php echo $post_id; ?>, 1)" style="width:4em;" value="<?php echo $meta['width']; ?>" />&times;<input type="text" id="imgedit-scale-height-<?php echo $post_id; ?>" onkeyup="imageEdit.scaleChanged(<?php echo $post_id; ?>, 0)" onblur="imageEdit.scaleChanged(<?php echo $post_id; ?>, 0)" style="width:4em;" value="<?php echo $meta['height']; ?>" /> <span class="imgedit-scale-warn" id="imgedit-scale-warn-<?php echo $post_id; ?>">!</span></span> <input type="button" onclick="imageEdit.action(<?php echo "$post_id, '$nonce'"; ?>, 'scale')" class="button-primary" value="<?php esc_attr_e( 'Scale' ); ?>" /> </div> </div> </div> <?php if ( $can_restore ) { ?> <div class="imgedit-group-top"> <a class="imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;" href="#"><strong><?php _e('Restore Original Image'); ?></strong></a> <div class="imgedit-help"> <p><?php _e('Discard any changes and restore the original image.'); if ( !defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE ) echo ' '.__('Previously edited copies of the image will not be deleted.'); ?></p> <div class="imgedit-submit"> <input type="button" onclick="imageEdit.action(<?php echo "$post_id, '$nonce'"; ?>, 'restore')" class="button-primary" value="<?php esc_attr_e( 'Restore image' ); ?>" <?php echo $can_restore; ?> /> </div> </div> </div> <?php } ?> </div> <div class="imgedit-group"> <div class="imgedit-group-top"> <strong><?php _e('Image Crop'); ?></strong> <a class="imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;" href="#"><?php _e('(help)'); ?></a> <div class="imgedit-help"> <p><?php _e('The image can be cropped by clicking on it and dragging to select the desired part. While dragging the dimensions of the selection are displayed below.'); ?></p> <p><strong><?php _e('Crop Aspect Ratio'); ?></strong><br /> <?php _e('You can specify the crop selection aspect ratio then hold down the Shift key while dragging to lock it. The values can be 1:1 (square), 4:3, 16:9, etc. If there is a selection, specifying aspect ratio will set it immediately.'); ?></p> <p><strong><?php _e('Crop Selection'); ?></strong><br /> <?php _e('Once started, the selection can be adjusted by entering new values (in pixels). Note that these values are scaled to approximately match the original image dimensions. The minimum selection size equals the thumbnail size as set in the Media settings.'); ?></p> </div> </div> <p> <?php _e('Aspect ratio:'); ?> <span class="nowrap"> <input type="text" id="imgedit-crop-width-<?php echo $post_id; ?>" onkeyup="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 0, this)" style="width:3em;" /> : <input type="text" id="imgedit-crop-height-<?php echo $post_id; ?>" onkeyup="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 1, this)" style="width:3em;" /> </span> </p> <p id="imgedit-crop-sel-<?php echo $post_id; ?>"> <?php _e('Selection:'); ?> <span class="nowrap"> <input type="text" id="imgedit-sel-width-<?php echo $post_id; ?>" onkeyup="imageEdit.setNumSelection(<?php echo $post_id; ?>)" style="width:4em;" /> : <input type="text" id="imgedit-sel-height-<?php echo $post_id; ?>" onkeyup="imageEdit.setNumSelection(<?php echo $post_id; ?>)" style="width:4em;" /> </span> </p> </div> <?php if ( $thumb && $sub_sizes ) { $thumb_img = wp_constrain_dimensions( $thumb['width'], $thumb['height'], 160, 120 ); ?> <div class="imgedit-group imgedit-applyto"> <div class="imgedit-group-top"> <strong><?php _e('Thumbnail Settings'); ?></strong> <a class="imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;" href="#"><?php _e('(help)'); ?></a> <p class="imgedit-help"><?php _e('The thumbnail image can be cropped differently. For example it can be square or contain only a portion of the original image to showcase it better. Here you can select whether to apply changes to all image sizes or make the thumbnail different.'); ?></p> </div> <p> <img src="<?php echo $thumb['url']; ?>" width="<?php echo $thumb_img[0]; ?>" height="<?php echo $thumb_img[1]; ?>" class="imgedit-size-preview" alt="" /><br /><?php _e('Current thumbnail'); ?> </p> <p id="imgedit-save-target-<?php echo $post_id; ?>"> <strong><?php _e('Apply changes to:'); ?></strong><br /> <label class="imgedit-label"> <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="all" checked="checked" /> <?php _e('All image sizes'); ?></label> <label class="imgedit-label"> <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="thumbnail" /> <?php _e('Thumbnail'); ?></label> <label class="imgedit-label"> <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="nothumb" /> <?php _e('All sizes except thumbnail'); ?></label> </p> </div> <?php } ?> </td></tr> </tbody></table> <div class="imgedit-wait" id="imgedit-wait-<?php echo $post_id; ?>"></div> <script type="text/javascript">jQuery( function() { imageEdit.init(<?php echo $post_id; ?>); });</script> <div class="hidden" id="imgedit-leaving-<?php echo $post_id; ?>"><?php _e("There are unsaved changes that will be lost. 'OK' to continue, 'Cancel' to return to the Image Editor."); ?></div> </div> <?php } /** * Streams image in WP_Image_Editor to browser. * Provided for backcompat reasons * * @param WP_Image_Editor $image * @param string $mime_type * @param int $post_id * @return boolean */ function wp_stream_image( $image, $mime_type, $post_id ) { if ( $image instanceof WP_Image_Editor ) { $image = apply_filters('image_editor_save_pre', $image, $post_id); if ( is_wp_error( $image->stream( $mime_type ) ) ) return false; return true; } else { _deprecated_argument( __FUNCTION__, '3.5', __( '$image needs to be an WP_Image_Editor object' ) ); $image = apply_filters('image_save_pre', $image, $post_id); switch ( $mime_type ) { case 'image/jpeg': header( 'Content-Type: image/jpeg' ); return imagejpeg( $image, null, 90 ); case 'image/png': header( 'Content-Type: image/png' ); return imagepng( $image ); case 'image/gif': header( 'Content-Type: image/gif' ); return imagegif( $image ); default: return false; } } } /** * Saves Image to File * * @param string $filename * @param WP_Image_Editor $image * @param string $mime_type * @param int $post_id * @return boolean */ function wp_save_image_file( $filename, $image, $mime_type, $post_id ) { if ( $image instanceof WP_Image_Editor ) { $image = apply_filters('image_editor_save_pre', $image, $post_id); $saved = apply_filters('wp_save_image_editor_file', null, $filename, $image, $mime_type, $post_id); if ( null !== $saved ) return $saved; return $image->save( $filename, $mime_type ); } else { _deprecated_argument( __FUNCTION__, '3.5', __( '$image needs to be an WP_Image_Editor object' ) ); $image = apply_filters('image_save_pre', $image, $post_id); $saved = apply_filters('wp_save_image_file', null, $filename, $image, $mime_type, $post_id); if ( null !== $saved ) return $saved; switch ( $mime_type ) { case 'image/jpeg': return imagejpeg( $image, $filename, apply_filters( 'jpeg_quality', 90, 'edit_image' ) ); case 'image/png': return imagepng( $image, $filename ); case 'image/gif': return imagegif( $image, $filename ); default: return false; } } } function _image_get_preview_ratio($w, $h) { $max = max($w, $h); return $max > 400 ? (400 / $max) : 1; } // @TODO: Returns GD resource, but is NOT public function _rotate_image_resource($img, $angle) { _deprecated_function( __FUNCTION__, '3.5', __( 'Use WP_Image_Editor::rotate' ) ); if ( function_exists('imagerotate') ) { $rotated = imagerotate($img, $angle, 0); if ( is_resource($rotated) ) { imagedestroy($img); $img = $rotated; } } return $img; } /** * @TODO: Only used within image_edit_apply_changes * and receives/returns GD Resource. * Consider removal. * * @param GD_Resource $img * @param boolean $horz * @param boolean $vert * @return GD_Resource */ function _flip_image_resource($img, $horz, $vert) { _deprecated_function( __FUNCTION__, '3.5', __( 'Use WP_Image_Editor::flip' ) ); $w = imagesx($img); $h = imagesy($img); $dst = wp_imagecreatetruecolor($w, $h); if ( is_resource($dst) ) { $sx = $vert ? ($w - 1) : 0; $sy = $horz ? ($h - 1) : 0; $sw = $vert ? -$w : $w; $sh = $horz ? -$h : $h; if ( imagecopyresampled($dst, $img, 0, 0, $sx, $sy, $w, $h, $sw, $sh) ) { imagedestroy($img); $img = $dst; } } return $img; } /** * @TODO: Only used within image_edit_apply_changes * and receives/returns GD Resource. * Consider removal. * * @param GD_Resource $img * @param float $x * @param float $y * @param float $w * @param float $h * @return GD_Resource */ function _crop_image_resource($img, $x, $y, $w, $h) { $dst = wp_imagecreatetruecolor($w, $h); if ( is_resource($dst) ) { if ( imagecopy($dst, $img, 0, 0, $x, $y, $w, $h) ) { imagedestroy($img); $img = $dst; } } return $img; } /** * Performs group of changes on Editor specified. * * @param WP_Image_Editor $image * @param type $changes * @return WP_Image_Editor */ function image_edit_apply_changes( $image, $changes ) { if ( is_resource( $image ) ) _deprecated_argument( __FUNCTION__, '3.5', __( '$image needs to be an WP_Image_Editor object' ) ); if ( !is_array($changes) ) return $image; // expand change operations foreach ( $changes as $key => $obj ) { if ( isset($obj->r) ) { $obj->type = 'rotate'; $obj->angle = $obj->r; unset($obj->r); } elseif ( isset($obj->f) ) { $obj->type = 'flip'; $obj->axis = $obj->f; unset($obj->f); } elseif ( isset($obj->c) ) { $obj->type = 'crop'; $obj->sel = $obj->c; unset($obj->c); } $changes[$key] = $obj; } // combine operations if ( count($changes) > 1 ) { $filtered = array($changes[0]); for ( $i = 0, $j = 1; $j < count($changes); $j++ ) { $combined = false; if ( $filtered[$i]->type == $changes[$j]->type ) { switch ( $filtered[$i]->type ) { case 'rotate': $filtered[$i]->angle += $changes[$j]->angle; $combined = true; break; case 'flip': $filtered[$i]->axis ^= $changes[$j]->axis; $combined = true; break; } } if ( !$combined ) $filtered[++$i] = $changes[$j]; } $changes = $filtered; unset($filtered); } // image resource before applying the changes if ( $image instanceof WP_Image_Editor ) $image = apply_filters('wp_image_editor_before_change', $image, $changes); elseif ( is_resource( $image ) ) $image = apply_filters('image_edit_before_change', $image, $changes); foreach ( $changes as $operation ) { switch ( $operation->type ) { case 'rotate': if ( $operation->angle != 0 ) { if ( $image instanceof WP_Image_Editor ) $image->rotate( $operation->angle ); else $image = _rotate_image_resource( $image, $operation->angle ); } break; case 'flip': if ( $operation->axis != 0 ) if ( $image instanceof WP_Image_Editor ) $image->flip( ($operation->axis & 1) != 0, ($operation->axis & 2) != 0 ); else $image = _flip_image_resource( $image, ( $operation->axis & 1 ) != 0, ( $operation->axis & 2 ) != 0 ); break; case 'crop': $sel = $operation->sel; if ( $image instanceof WP_Image_Editor ) { $size = $image->get_size(); $w = $size['width']; $h = $size['height']; $scale = 1 / _image_get_preview_ratio( $w, $h ); // discard preview scaling $image->crop( $sel->x * $scale, $sel->y * $scale, $sel->w * $scale, $sel->h * $scale ); } else { $scale = 1 / _image_get_preview_ratio( imagesx( $image ), imagesy( $image ) ); // discard preview scaling $image = _crop_image_resource( $image, $sel->x * $scale, $sel->y * $scale, $sel->w * $scale, $sel->h * $scale ); } break; } } return $image; } /** * Streams image in post to browser, along with enqueued changes * in $_REQUEST['history'] * * @param int $post_id * @return boolean */ function stream_preview_image( $post_id ) { $post = get_post( $post_id ); @ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', WP_MAX_MEMORY_LIMIT ) ); $img = wp_get_image_editor( _load_image_to_edit_path( $post_id ) ); if ( is_wp_error( $img ) ) return false; $changes = !empty($_REQUEST['history']) ? json_decode( stripslashes($_REQUEST['history']) ) : null; if ( $changes ) $img = image_edit_apply_changes( $img, $changes ); // scale the image $size = $img->get_size(); $w = $size['width']; $h = $size['height']; $ratio = _image_get_preview_ratio( $w, $h ); $w2 = $w * $ratio; $h2 = $h * $ratio; if ( is_wp_error( $img->resize( $w2, $h2 ) ) ) return false; return wp_stream_image( $img, $post->post_mime_type, $post_id ); } function wp_restore_image($post_id) { $meta = wp_get_attachment_metadata($post_id); $file = get_attached_file($post_id); $backup_sizes = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true ); $restored = false; $msg = new stdClass; if ( !is_array($backup_sizes) ) { $msg->error = __('Cannot load image metadata.'); return $msg; } $parts = pathinfo($file); $suffix = time() . rand(100, 999); $default_sizes = get_intermediate_image_sizes(); if ( isset($backup_sizes['full-orig']) && is_array($backup_sizes['full-orig']) ) { $data = $backup_sizes['full-orig']; if ( $parts['basename'] != $data['file'] ) { if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE ) { // delete only if it's edited image if ( preg_match('/-e[0-9]{13}\./', $parts['basename']) ) { $delpath = apply_filters('wp_delete_file', $file); @unlink($delpath); } } else { $backup_sizes["full-$suffix"] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $parts['basename']); } } $restored_file = path_join($parts['dirname'], $data['file']); $restored = update_attached_file($post_id, $restored_file); $meta['file'] = _wp_relative_upload_path( $restored_file ); $meta['width'] = $data['width']; $meta['height'] = $data['height']; } foreach ( $default_sizes as $default_size ) { if ( isset($backup_sizes["$default_size-orig"]) ) { $data = $backup_sizes["$default_size-orig"]; if ( isset($meta['sizes'][$default_size]) && $meta['sizes'][$default_size]['file'] != $data['file'] ) { if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE ) { // delete only if it's edited image if ( preg_match('/-e[0-9]{13}-/', $meta['sizes'][$default_size]['file']) ) { $delpath = apply_filters( 'wp_delete_file', path_join($parts['dirname'], $meta['sizes'][$default_size]['file']) ); @unlink($delpath); } } else { $backup_sizes["$default_size-{$suffix}"] = $meta['sizes'][$default_size]; } } $meta['sizes'][$default_size] = $data; } else { unset($meta['sizes'][$default_size]); } } if ( !wp_update_attachment_metadata($post_id, $meta) || !update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes) ) { $msg->error = __('Cannot save image metadata.'); return $msg; } if ( !$restored ) $msg->error = __('Image metadata is inconsistent.'); else $msg->msg = __('Image restored successfully.'); return $msg; } /** * Saves image to post along with enqueued changes * in $_REQUEST['history'] * * @param int $post_id * @return \stdClass */ function wp_save_image( $post_id ) { $return = new stdClass; $success = $delete = $scaled = $nocrop = false; $post = get_post( $post_id ); $img = wp_get_image_editor( _load_image_to_edit_path( $post_id, 'full' ) ); if ( is_wp_error( $img ) ) { $return->error = esc_js( __('Unable to create new image.') ); return $return; } $fwidth = !empty($_REQUEST['fwidth']) ? intval($_REQUEST['fwidth']) : 0; $fheight = !empty($_REQUEST['fheight']) ? intval($_REQUEST['fheight']) : 0; $target = !empty($_REQUEST['target']) ? preg_replace('/[^a-z0-9_-]+/i', '', $_REQUEST['target']) : ''; $scale = !empty($_REQUEST['do']) && 'scale' == $_REQUEST['do']; if ( $scale && $fwidth > 0 && $fheight > 0 ) { $size = $img->get_size(); $sX = $size['width']; $sY = $size['height']; // check if it has roughly the same w / h ratio $diff = round($sX / $sY, 2) - round($fwidth / $fheight, 2); if ( -0.1 < $diff && $diff < 0.1 ) { // scale the full size image if ( $img->resize( $fwidth, $fheight ) ) $scaled = true; } if ( !$scaled ) { $return->error = esc_js( __('Error while saving the scaled image. Please reload the page and try again.') ); return $return; } } elseif ( !empty($_REQUEST['history']) ) { $changes = json_decode( stripslashes($_REQUEST['history']) ); if ( $changes ) $img = image_edit_apply_changes($img, $changes); } else { $return->error = esc_js( __('Nothing to save, the image has not changed.') ); return $return; } $meta = wp_get_attachment_metadata($post_id); $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true ); if ( !is_array($meta) ) { $return->error = esc_js( __('Image data does not exist. Please re-upload the image.') ); return $return; } if ( !is_array($backup_sizes) ) $backup_sizes = array(); // generate new filename $path = get_attached_file($post_id); $path_parts = pathinfo( $path ); $filename = $path_parts['filename']; $suffix = time() . rand(100, 999); if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE && isset($backup_sizes['full-orig']) && $backup_sizes['full-orig']['file'] != $path_parts['basename'] ) { if ( 'thumbnail' == $target ) $new_path = "{$path_parts['dirname']}/{$filename}-temp.{$path_parts['extension']}"; else $new_path = $path; } else { while( true ) { $filename = preg_replace( '/-e([0-9]+)$/', '', $filename ); $filename .= "-e{$suffix}"; $new_filename = "{$filename}.{$path_parts['extension']}"; $new_path = "{$path_parts['dirname']}/$new_filename"; if ( file_exists($new_path) ) $suffix++; else break; } } // save the full-size file, also needed to create sub-sizes if ( !wp_save_image_file($new_path, $img, $post->post_mime_type, $post_id) ) { $return->error = esc_js( __('Unable to save the image.') ); return $return; } if ( 'nothumb' == $target || 'all' == $target || 'full' == $target || $scaled ) { $tag = false; if ( isset($backup_sizes['full-orig']) ) { if ( ( !defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE ) && $backup_sizes['full-orig']['file'] != $path_parts['basename'] ) $tag = "full-$suffix"; } else { $tag = 'full-orig'; } if ( $tag ) $backup_sizes[$tag] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $path_parts['basename']); $success = update_attached_file( $post_id, $new_path ); $meta['file'] = _wp_relative_upload_path( $new_path ); $size = $img->get_size(); $meta['width'] = $size['width']; $meta['height'] = $size['height']; if ( $success && ('nothumb' == $target || 'all' == $target) ) { $sizes = get_intermediate_image_sizes(); if ( 'nothumb' == $target ) $sizes = array_diff( $sizes, array('thumbnail') ); } $return->fw = $meta['width']; $return->fh = $meta['height']; } elseif ( 'thumbnail' == $target ) { $sizes = array( 'thumbnail' ); $success = $delete = $nocrop = true; } if ( isset( $sizes ) ) { $_sizes = array(); foreach ( $sizes as $size ) { $tag = false; if ( isset( $meta['sizes'][$size] ) ) { if ( isset($backup_sizes["$size-orig"]) ) { if ( ( !defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE ) && $backup_sizes["$size-orig"]['file'] != $meta['sizes'][$size]['file'] ) $tag = "$size-$suffix"; } else { $tag = "$size-orig"; } if ( $tag ) $backup_sizes[$tag] = $meta['sizes'][$size]; } $crop = $nocrop ? false : get_option("{$size}_crop"); $_sizes[ $size ] = array( 'width' => get_option("{$size}_size_w"), 'height' => get_option("{$size}_size_h"), 'crop' => $crop ); } $meta['sizes'] = $img->multi_resize( $_sizes ); } unset( $img ); if ( $success ) { wp_update_attachment_metadata( $post_id, $meta ); update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes); if ( $target == 'thumbnail' || $target == 'all' || $target == 'full' ) { // Check if it's an image edit from attachment edit screen if ( ! empty( $_REQUEST['context'] ) && 'edit-attachment' == $_REQUEST['context'] ) { $thumb_url = wp_get_attachment_image_src( $post_id, array( 900, 600 ), true ); $return->thumbnail = $thumb_url[0]; } else { $file_url = wp_get_attachment_url($post_id); if ( $thumb = $meta['sizes']['thumbnail'] ) $return->thumbnail = path_join( dirname($file_url), $thumb['file'] ); else $return->thumbnail = "$file_url?w=128&h=128"; } } } else { $delete = true; } if ( $delete ) { $delpath = apply_filters('wp_delete_file', $new_path); @unlink( $delpath ); } $return->msg = esc_js( __('Image saved') ); return $return; }
zyblog
trunk/zyblog/wp-admin/includes/image-edit.php
PHP
asf20
26,355
<?php /** * WordPress SSH2 Filesystem. * * @package WordPress * @subpackage Filesystem */ /** * WordPress Filesystem Class for implementing SSH2. * * To use this class you must follow these steps for PHP 5.2.6+ * * @contrib http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/ - Installation Notes * * Complie libssh2 (Note: Only 0.14 is officaly working with PHP 5.2.6+ right now, But many users have found the latest versions work) * * cd /usr/src * wget http://surfnet.dl.sourceforge.net/sourceforge/libssh2/libssh2-0.14.tar.gz * tar -zxvf libssh2-0.14.tar.gz * cd libssh2-0.14/ * ./configure * make all install * * Note: Do not leave the directory yet! * * Enter: pecl install -f ssh2 * * Copy the ssh.so file it creates to your PHP Module Directory. * Open up your PHP.INI file and look for where extensions are placed. * Add in your PHP.ini file: extension=ssh2.so * * Restart Apache! * Check phpinfo() streams to confirm that: ssh2.shell, ssh2.exec, ssh2.tunnel, ssh2.scp, ssh2.sftp exist. * * Note: as of WordPress 2.8, This utilises the PHP5+ function 'stream_get_contents' * * @since 2.7 * @package WordPress * @subpackage Filesystem * @uses WP_Filesystem_Base Extends class */ class WP_Filesystem_SSH2 extends WP_Filesystem_Base { var $link = false; var $sftp_link = false; var $keys = false; var $errors = array(); var $options = array(); function __construct($opt='') { $this->method = 'ssh2'; $this->errors = new WP_Error(); //Check if possible to use ssh2 functions. if ( ! extension_loaded('ssh2') ) { $this->errors->add('no_ssh2_ext', __('The ssh2 PHP extension is not available')); return false; } if ( !function_exists('stream_get_contents') ) { $this->errors->add('ssh2_php_requirement', __('The ssh2 PHP extension is available, however, we require the PHP5 function <code>stream_get_contents()</code>')); return false; } // Set defaults: if ( empty($opt['port']) ) $this->options['port'] = 22; else $this->options['port'] = $opt['port']; if ( empty($opt['hostname']) ) $this->errors->add('empty_hostname', __('SSH2 hostname is required')); else $this->options['hostname'] = $opt['hostname']; if ( ! empty($opt['base']) ) $this->wp_base = $opt['base']; // Check if the options provided are OK. if ( !empty ($opt['public_key']) && !empty ($opt['private_key']) ) { $this->options['public_key'] = $opt['public_key']; $this->options['private_key'] = $opt['private_key']; $this->options['hostkey'] = array('hostkey' => 'ssh-rsa'); $this->keys = true; } elseif ( empty ($opt['username']) ) { $this->errors->add('empty_username', __('SSH2 username is required')); } if ( !empty($opt['username']) ) $this->options['username'] = $opt['username']; if ( empty ($opt['password']) ) { if ( !$this->keys ) //password can be blank if we are using keys $this->errors->add('empty_password', __('SSH2 password is required')); } else { $this->options['password'] = $opt['password']; } } function connect() { if ( ! $this->keys ) { $this->link = @ssh2_connect($this->options['hostname'], $this->options['port']); } else { $this->link = @ssh2_connect($this->options['hostname'], $this->options['port'], $this->options['hostkey']); } if ( ! $this->link ) { $this->errors->add('connect', sprintf(__('Failed to connect to SSH2 Server %1$s:%2$s'), $this->options['hostname'], $this->options['port'])); return false; } if ( !$this->keys ) { if ( ! @ssh2_auth_password($this->link, $this->options['username'], $this->options['password']) ) { $this->errors->add('auth', sprintf(__('Username/Password incorrect for %s'), $this->options['username'])); return false; } } else { if ( ! @ssh2_auth_pubkey_file($this->link, $this->options['username'], $this->options['public_key'], $this->options['private_key'], $this->options['password'] ) ) { $this->errors->add('auth', sprintf(__('Public and Private keys incorrect for %s'), $this->options['username'])); return false; } } $this->sftp_link = ssh2_sftp($this->link); return true; } function run_command( $command, $returnbool = false) { if ( ! $this->link ) return false; if ( ! ($stream = ssh2_exec($this->link, $command)) ) { $this->errors->add('command', sprintf(__('Unable to perform command: %s'), $command)); } else { stream_set_blocking( $stream, true ); stream_set_timeout( $stream, FS_TIMEOUT ); $data = stream_get_contents( $stream ); fclose( $stream ); if ( $returnbool ) return ( $data === false ) ? false : '' != trim($data); else return $data; } return false; } function get_contents($file, $type = '', $resumepos = 0 ) { $file = ltrim($file, '/'); return file_get_contents('ssh2.sftp://' . $this->sftp_link . '/' . $file); } function get_contents_array($file) { $file = ltrim($file, '/'); return file('ssh2.sftp://' . $this->sftp_link . '/' . $file); } function put_contents($file, $contents, $mode = false ) { $file = ltrim($file, '/'); $ret = file_put_contents('ssh2.sftp://' . $this->sftp_link . '/' . $file, $contents); $this->chmod($file, $mode); return false !== $ret; } function cwd() { $cwd = $this->run_command('pwd'); if ( $cwd ) $cwd = trailingslashit($cwd); return $cwd; } function chdir($dir) { return $this->run_command('cd ' . $dir, true); } function chgrp($file, $group, $recursive = false ) { if ( ! $this->exists($file) ) return false; if ( ! $recursive || ! $this->is_dir($file) ) return $this->run_command(sprintf('chgrp %o %s', $mode, escapeshellarg($file)), true); return $this->run_command(sprintf('chgrp -R %o %s', $mode, escapeshellarg($file)), true); } function chmod($file, $mode = false, $recursive = false) { if ( ! $this->exists($file) ) return false; if ( ! $mode ) { if ( $this->is_file($file) ) $mode = FS_CHMOD_FILE; elseif ( $this->is_dir($file) ) $mode = FS_CHMOD_DIR; else return false; } if ( ! $recursive || ! $this->is_dir($file) ) return $this->run_command(sprintf('chmod %o %s', $mode, escapeshellarg($file)), true); return $this->run_command(sprintf('chmod -R %o %s', $mode, escapeshellarg($file)), true); } function chown($file, $owner, $recursive = false ) { if ( ! $this->exists($file) ) return false; if ( ! $recursive || ! $this->is_dir($file) ) return $this->run_command(sprintf('chown %o %s', $mode, escapeshellarg($file)), true); return $this->run_command(sprintf('chown -R %o %s', $mode, escapeshellarg($file)), true); } function owner($file) { $owneruid = @fileowner('ssh2.sftp://' . $this->sftp_link . '/' . ltrim($file, '/')); if ( ! $owneruid ) return false; if ( ! function_exists('posix_getpwuid') ) return $owneruid; $ownerarray = posix_getpwuid($owneruid); return $ownerarray['name']; } function getchmod($file) { return substr(decoct(@fileperms( 'ssh2.sftp://' . $this->sftp_link . '/' . ltrim($file, '/') )),3); } function group($file) { $gid = @filegroup('ssh2.sftp://' . $this->sftp_link . '/' . ltrim($file, '/')); if ( ! $gid ) return false; if ( ! function_exists('posix_getgrgid') ) return $gid; $grouparray = posix_getgrgid($gid); return $grouparray['name']; } function copy($source, $destination, $overwrite = false, $mode = false) { if ( ! $overwrite && $this->exists($destination) ) return false; $content = $this->get_contents($source); if ( false === $content) return false; return $this->put_contents($destination, $content, $mode); } function move($source, $destination, $overwrite = false) { return @ssh2_sftp_rename($this->link, $source, $destination); } function delete($file, $recursive = false, $type = false) { if ( 'f' == $type || $this->is_file($file) ) return ssh2_sftp_unlink($this->sftp_link, $file); if ( ! $recursive ) return ssh2_sftp_rmdir($this->sftp_link, $file); $filelist = $this->dirlist($file); if ( is_array($filelist) ) { foreach ( $filelist as $filename => $fileinfo) { $this->delete($file . '/' . $filename, $recursive, $fileinfo['type']); } } return ssh2_sftp_rmdir($this->sftp_link, $file); } function exists($file) { $file = ltrim($file, '/'); return file_exists('ssh2.sftp://' . $this->sftp_link . '/' . $file); } function is_file($file) { $file = ltrim($file, '/'); return is_file('ssh2.sftp://' . $this->sftp_link . '/' . $file); } function is_dir($path) { $path = ltrim($path, '/'); return is_dir('ssh2.sftp://' . $this->sftp_link . '/' . $path); } function is_readable($file) { $file = ltrim($file, '/'); return is_readable('ssh2.sftp://' . $this->sftp_link . '/' . $file); } function is_writable($file) { $file = ltrim($file, '/'); return is_writable('ssh2.sftp://' . $this->sftp_link . '/' . $file); } function atime($file) { $file = ltrim($file, '/'); return fileatime('ssh2.sftp://' . $this->sftp_link . '/' . $file); } function mtime($file) { $file = ltrim($file, '/'); return filemtime('ssh2.sftp://' . $this->sftp_link . '/' . $file); } function size($file) { $file = ltrim($file, '/'); return filesize('ssh2.sftp://' . $this->sftp_link . '/' . $file); } function touch($file, $time = 0, $atime = 0) { //Not implemented. } function mkdir($path, $chmod = false, $chown = false, $chgrp = false) { $path = untrailingslashit($path); if ( empty($path) ) return false; if ( ! $chmod ) $chmod = FS_CHMOD_DIR; if ( ! ssh2_sftp_mkdir($this->sftp_link, $path, $chmod, true) ) return false; if ( $chown ) $this->chown($path, $chown); if ( $chgrp ) $this->chgrp($path, $chgrp); return true; } function rmdir($path, $recursive = false) { return $this->delete($path, $recursive); } function dirlist($path, $include_hidden = true, $recursive = false) { if ( $this->is_file($path) ) { $limit_file = basename($path); $path = dirname($path); } else { $limit_file = false; } if ( ! $this->is_dir($path) ) return false; $ret = array(); $dir = @dir('ssh2.sftp://' . $this->sftp_link .'/' . ltrim($path, '/') ); if ( ! $dir ) return false; while (false !== ($entry = $dir->read()) ) { $struc = array(); $struc['name'] = $entry; if ( '.' == $struc['name'] || '..' == $struc['name'] ) continue; //Do not care about these folders. if ( ! $include_hidden && '.' == $struc['name'][0] ) continue; if ( $limit_file && $struc['name'] != $limit_file ) continue; $struc['perms'] = $this->gethchmod($path.'/'.$entry); $struc['permsn'] = $this->getnumchmodfromh($struc['perms']); $struc['number'] = false; $struc['owner'] = $this->owner($path.'/'.$entry); $struc['group'] = $this->group($path.'/'.$entry); $struc['size'] = $this->size($path.'/'.$entry); $struc['lastmodunix']= $this->mtime($path.'/'.$entry); $struc['lastmod'] = date('M j',$struc['lastmodunix']); $struc['time'] = date('h:i:s',$struc['lastmodunix']); $struc['type'] = $this->is_dir($path.'/'.$entry) ? 'd' : 'f'; if ( 'd' == $struc['type'] ) { if ( $recursive ) $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $include_hidden, $recursive); else $struc['files'] = array(); } $ret[ $struc['name'] ] = $struc; } $dir->close(); unset($dir); return $ret; } }
zyblog
trunk/zyblog/wp-admin/includes/class-wp-filesystem-ssh2.php
PHP
asf20
11,437
<?php /** * Functions for reading, writing, modifying, and deleting files on the file system. * Includes functionality for theme-specific files as well as operations for uploading, * archiving, and rendering output when necessary. * * @package WordPress * @subpackage Administration */ /** The descriptions for theme files. */ $wp_file_descriptions = array( 'index.php' => __( 'Main Index Template' ), 'style.css' => __( 'Stylesheet' ), 'editor-style.css' => __( 'Visual Editor Stylesheet' ), 'editor-style-rtl.css' => __( 'Visual Editor RTL Stylesheet' ), 'rtl.css' => __( 'RTL Stylesheet' ), 'comments.php' => __( 'Comments' ), 'comments-popup.php' => __( 'Popup Comments' ), 'footer.php' => __( 'Footer' ), 'header.php' => __( 'Header' ), 'sidebar.php' => __( 'Sidebar' ), 'archive.php' => __( 'Archives' ), 'author.php' => __( 'Author Template' ), 'tag.php' => __( 'Tag Template' ), 'category.php' => __( 'Category Template' ), 'page.php' => __( 'Page Template' ), 'search.php' => __( 'Search Results' ), 'searchform.php' => __( 'Search Form' ), 'single.php' => __( 'Single Post' ), '404.php' => __( '404 Template' ), 'link.php' => __( 'Links Template' ), 'functions.php' => __( 'Theme Functions' ), 'attachment.php' => __( 'Attachment Template' ), 'image.php' => __('Image Attachment Template'), 'video.php' => __('Video Attachment Template'), 'audio.php' => __('Audio Attachment Template'), 'application.php' => __('Application Attachment Template'), 'my-hacks.php' => __( 'my-hacks.php (legacy hacks support)' ), '.htaccess' => __( '.htaccess (for rewrite rules )' ), // Deprecated files 'wp-layout.css' => __( 'Stylesheet' ), 'wp-comments.php' => __( 'Comments Template' ), 'wp-comments-popup.php' => __( 'Popup Comments Template' ), ); /** * Get the description for standard WordPress theme files and other various standard * WordPress files * * @since 1.5.0 * * @uses _cleanup_header_comment * @uses $wp_file_descriptions * @param string $file Filesystem path or filename * @return string Description of file from $wp_file_descriptions or basename of $file if description doesn't exist */ function get_file_description( $file ) { global $wp_file_descriptions; if ( isset( $wp_file_descriptions[basename( $file )] ) ) { return $wp_file_descriptions[basename( $file )]; } elseif ( file_exists( $file ) && is_file( $file ) ) { $template_data = implode( '', file( $file ) ); if ( preg_match( '|Template Name:(.*)$|mi', $template_data, $name )) return sprintf( __( '%s Page Template' ), _cleanup_header_comment($name[1]) ); } return trim( basename( $file ) ); } /** * Get the absolute filesystem path to the root of the WordPress installation * * @since 1.5.0 * * @uses get_option * @return string Full filesystem path to the root of the WordPress installation */ function get_home_path() { $home = get_option( 'home' ); $siteurl = get_option( 'siteurl' ); if ( ! empty( $home ) && 0 !== strcasecmp( $home, $siteurl ) ) { $wp_path_rel_to_home = str_ireplace( $home, '', $siteurl ); /* $siteurl - $home */ $pos = strripos( str_replace( '\\', '/', $_SERVER['SCRIPT_FILENAME'] ), trailingslashit( $wp_path_rel_to_home ) ); $home_path = substr( $_SERVER['SCRIPT_FILENAME'], 0, $pos ); $home_path = trailingslashit( $home_path ); } else { $home_path = ABSPATH; } return $home_path; } /** * Get the real file system path to a file to edit within the admin * * If the $file is index.php or .htaccess this function will assume it is relative * to the install root, otherwise it is assumed the file is relative to the wp-content * directory * * @since 1.5.0 * * @uses get_home_path * @uses WP_CONTENT_DIR full filesystem path to the wp-content directory * @param string $file filesystem path relative to the WordPress install directory or to the wp-content directory * @return string full file system path to edit */ function get_real_file_to_edit( $file ) { if ('index.php' == $file || '.htaccess' == $file ) { $real_file = get_home_path() . $file; } else { $real_file = WP_CONTENT_DIR . $file; } return $real_file; } /** * Returns a listing of all files in the specified folder and all subdirectories up to 100 levels deep. * The depth of the recursiveness can be controlled by the $levels param. * * @since 2.6.0 * * @param string $folder Full path to folder * @param int $levels (optional) Levels of folders to follow, Default: 100 (PHP Loop limit). * @return bool|array False on failure, Else array of files */ function list_files( $folder = '', $levels = 100 ) { if ( empty($folder) ) return false; if ( ! $levels ) return false; $files = array(); if ( $dir = @opendir( $folder ) ) { while (($file = readdir( $dir ) ) !== false ) { if ( in_array($file, array('.', '..') ) ) continue; if ( is_dir( $folder . '/' . $file ) ) { $files2 = list_files( $folder . '/' . $file, $levels - 1); if ( $files2 ) $files = array_merge($files, $files2 ); else $files[] = $folder . '/' . $file . '/'; } else { $files[] = $folder . '/' . $file; } } } @closedir( $dir ); return $files; } /** * Returns a filename of a Temporary unique file. * Please note that the calling function must unlink() this itself. * * The filename is based off the passed parameter or defaults to the current unix timestamp, * while the directory can either be passed as well, or by leaving it blank, default to a writable temporary directory. * * @since 2.6.0 * * @param string $filename (optional) Filename to base the Unique file off * @param string $dir (optional) Directory to store the file in * @return string a writable filename */ function wp_tempnam($filename = '', $dir = '') { if ( empty($dir) ) $dir = get_temp_dir(); $filename = basename($filename); if ( empty($filename) ) $filename = time(); $filename = preg_replace('|\..*$|', '.tmp', $filename); $filename = $dir . wp_unique_filename($dir, $filename); touch($filename); return $filename; } /** * Make sure that the file that was requested to edit, is allowed to be edited * * Function will die if if you are not allowed to edit the file * * @since 1.5.0 * * @uses wp_die * @uses validate_file * @param string $file file the users is attempting to edit * @param array $allowed_files Array of allowed files to edit, $file must match an entry exactly * @return null */ function validate_file_to_edit( $file, $allowed_files = '' ) { $code = validate_file( $file, $allowed_files ); if (!$code ) return $file; switch ( $code ) { case 1 : wp_die( __('Sorry, can&#8217;t edit files with &#8220;..&#8221; in the name. If you are trying to edit a file in your WordPress home directory, you can just type the name of the file in.' )); //case 2 : // wp_die( __('Sorry, can&#8217;t call files with their real path.' )); case 3 : wp_die( __('Sorry, that file cannot be edited.' )); } } /** * Handle PHP uploads in WordPress, sanitizing file names, checking extensions for mime type, * and moving the file to the appropriate directory within the uploads directory. * * @since 2.0 * * @uses wp_handle_upload_error * @uses apply_filters * @uses is_multisite * @uses wp_check_filetype_and_ext * @uses current_user_can * @uses wp_upload_dir * @uses wp_unique_filename * @uses delete_transient * @param array $file Reference to a single element of $_FILES. Call the function once for each uploaded file. * @param array $overrides Optional. An associative array of names=>values to override default variables with extract( $overrides, EXTR_OVERWRITE ). * @param string $time Optional. Time formatted in 'yyyy/mm'. * @return array On success, returns an associative array of file attributes. On failure, returns $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ). */ function wp_handle_upload( &$file, $overrides = false, $time = null ) { // The default error handler. if ( ! function_exists( 'wp_handle_upload_error' ) ) { function wp_handle_upload_error( &$file, $message ) { return array( 'error'=>$message ); } } $file = apply_filters( 'wp_handle_upload_prefilter', $file ); // You may define your own function and pass the name in $overrides['upload_error_handler'] $upload_error_handler = 'wp_handle_upload_error'; // You may have had one or more 'wp_handle_upload_prefilter' functions error out the file. Handle that gracefully. if ( isset( $file['error'] ) && !is_numeric( $file['error'] ) && $file['error'] ) return $upload_error_handler( $file, $file['error'] ); // You may define your own function and pass the name in $overrides['unique_filename_callback'] $unique_filename_callback = null; // $_POST['action'] must be set and its value must equal $overrides['action'] or this: $action = 'wp_handle_upload'; // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error']. $upload_error_strings = array( false, __( "The uploaded file exceeds the upload_max_filesize directive in php.ini." ), __( "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form." ), __( "The uploaded file was only partially uploaded." ), __( "No file was uploaded." ), '', __( "Missing a temporary folder." ), __( "Failed to write file to disk." ), __( "File upload stopped by extension." )); // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false; $test_form = true; $test_size = true; $test_upload = true; // If you override this, you must provide $ext and $type!!!! $test_type = true; $mimes = false; // Install user overrides. Did we mention that this voids your warranty? if ( is_array( $overrides ) ) extract( $overrides, EXTR_OVERWRITE ); // A correct form post will pass this test. if ( $test_form && (!isset( $_POST['action'] ) || ($_POST['action'] != $action ) ) ) return call_user_func($upload_error_handler, $file, __( 'Invalid form submission.' )); // A successful upload will pass this test. It makes no sense to override this one. if ( $file['error'] > 0 ) return call_user_func($upload_error_handler, $file, $upload_error_strings[$file['error']] ); // A non-empty file will pass this test. if ( $test_size && !($file['size'] > 0 ) ) { if ( is_multisite() ) $error_msg = __( 'File is empty. Please upload something more substantial.' ); else $error_msg = __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini.' ); return call_user_func($upload_error_handler, $file, $error_msg); } // A properly uploaded file will pass this test. There should be no reason to override this one. if ( $test_upload && ! @ is_uploaded_file( $file['tmp_name'] ) ) return call_user_func($upload_error_handler, $file, __( 'Specified file failed upload test.' )); // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter. if ( $test_type ) { $wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $mimes ); extract( $wp_filetype ); // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect if ( $proper_filename ) $file['name'] = $proper_filename; if ( ( !$type || !$ext ) && !current_user_can( 'unfiltered_upload' ) ) return call_user_func($upload_error_handler, $file, __( 'Sorry, this file type is not permitted for security reasons.' )); if ( !$ext ) $ext = ltrim(strrchr($file['name'], '.'), '.'); if ( !$type ) $type = $file['type']; } else { $type = ''; } // A writable uploads dir will pass this test. Again, there's no point overriding this one. if ( ! ( ( $uploads = wp_upload_dir($time) ) && false === $uploads['error'] ) ) return call_user_func($upload_error_handler, $file, $uploads['error'] ); $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback ); // Move the file to the uploads dir $new_file = $uploads['path'] . "/$filename"; if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) ) return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) ); // Set correct file permissions $stat = stat( dirname( $new_file )); $perms = $stat['mode'] & 0000666; @ chmod( $new_file, $perms ); // Compute the URL $url = $uploads['url'] . "/$filename"; if ( is_multisite() ) delete_transient( 'dirsize_cache' ); return apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ), 'upload' ); } /** * Handle sideloads, which is the process of retrieving a media item from another server instead of * a traditional media upload. This process involves sanitizing the filename, checking extensions * for mime type, and moving the file to the appropriate directory within the uploads directory. * * @since 2.6.0 * * @uses wp_handle_upload_error * @uses apply_filters * @uses wp_check_filetype_and_ext * @uses current_user_can * @uses wp_upload_dir * @uses wp_unique_filename * @param array $file an array similar to that of a PHP $_FILES POST array * @param array $overrides Optional. An associative array of names=>values to override default variables with extract( $overrides, EXTR_OVERWRITE ). * @param string $time Optional. Time formatted in 'yyyy/mm'. * @return array On success, returns an associative array of file attributes. On failure, returns $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ). */ function wp_handle_sideload( &$file, $overrides = false, $time = null ) { // The default error handler. if (! function_exists( 'wp_handle_upload_error' ) ) { function wp_handle_upload_error( &$file, $message ) { return array( 'error'=>$message ); } } // You may define your own function and pass the name in $overrides['upload_error_handler'] $upload_error_handler = 'wp_handle_upload_error'; // You may define your own function and pass the name in $overrides['unique_filename_callback'] $unique_filename_callback = null; // $_POST['action'] must be set and its value must equal $overrides['action'] or this: $action = 'wp_handle_sideload'; // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error']. $upload_error_strings = array( false, __( "The uploaded file exceeds the <code>upload_max_filesize</code> directive in <code>php.ini</code>." ), __( "The uploaded file exceeds the <em>MAX_FILE_SIZE</em> directive that was specified in the HTML form." ), __( "The uploaded file was only partially uploaded." ), __( "No file was uploaded." ), '', __( "Missing a temporary folder." ), __( "Failed to write file to disk." ), __( "File upload stopped by extension." )); // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false; $test_form = true; $test_size = true; // If you override this, you must provide $ext and $type!!!! $test_type = true; $mimes = false; // Install user overrides. Did we mention that this voids your warranty? if ( is_array( $overrides ) ) extract( $overrides, EXTR_OVERWRITE ); // A correct form post will pass this test. if ( $test_form && (!isset( $_POST['action'] ) || ($_POST['action'] != $action ) ) ) return $upload_error_handler( $file, __( 'Invalid form submission.' )); // A successful upload will pass this test. It makes no sense to override this one. if ( ! empty( $file['error'] ) ) return $upload_error_handler( $file, $upload_error_strings[$file['error']] ); // A non-empty file will pass this test. if ( $test_size && !(filesize($file['tmp_name']) > 0 ) ) return $upload_error_handler( $file, __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini.' )); // A properly uploaded file will pass this test. There should be no reason to override this one. if (! @ is_file( $file['tmp_name'] ) ) return $upload_error_handler( $file, __( 'Specified file does not exist.' )); // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter. if ( $test_type ) { $wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $mimes ); extract( $wp_filetype ); // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect if ( $proper_filename ) $file['name'] = $proper_filename; if ( ( !$type || !$ext ) && !current_user_can( 'unfiltered_upload' ) ) return $upload_error_handler( $file, __( 'Sorry, this file type is not permitted for security reasons.' )); if ( !$ext ) $ext = ltrim(strrchr($file['name'], '.'), '.'); if ( !$type ) $type = $file['type']; } // A writable uploads dir will pass this test. Again, there's no point overriding this one. if ( ! ( ( $uploads = wp_upload_dir( $time ) ) && false === $uploads['error'] ) ) return $upload_error_handler( $file, $uploads['error'] ); $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback ); // Strip the query strings. $filename = str_replace('?','-', $filename); $filename = str_replace('&','-', $filename); // Move the file to the uploads dir $new_file = $uploads['path'] . "/$filename"; if ( false === @ rename( $file['tmp_name'], $new_file ) ) { return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) ); } // Set correct file permissions $stat = stat( dirname( $new_file )); $perms = $stat['mode'] & 0000666; @ chmod( $new_file, $perms ); // Compute the URL $url = $uploads['url'] . "/$filename"; $return = apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ), 'sideload' ); return $return; } /** * Downloads a url to a local temporary file using the WordPress HTTP Class. * Please note, That the calling function must unlink() the file. * * @since 2.5.0 * * @param string $url the URL of the file to download * @param int $timeout The timeout for the request to download the file default 300 seconds * @return mixed WP_Error on failure, string Filename on success. */ function download_url( $url, $timeout = 300 ) { //WARNING: The file is not automatically deleted, The script must unlink() the file. if ( ! $url ) return new WP_Error('http_no_url', __('Invalid URL Provided.')); $tmpfname = wp_tempnam($url); if ( ! $tmpfname ) return new WP_Error('http_no_file', __('Could not create Temporary file.')); $response = wp_remote_get( $url, array( 'timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname ) ); if ( is_wp_error( $response ) ) { unlink( $tmpfname ); return $response; } if ( 200 != wp_remote_retrieve_response_code( $response ) ){ unlink( $tmpfname ); return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ) ); } return $tmpfname; } /** * Unzips a specified ZIP file to a location on the Filesystem via the WordPress Filesystem Abstraction. * Assumes that WP_Filesystem() has already been called and set up. Does not extract a root-level __MACOSX directory, if present. * * Attempts to increase the PHP Memory limit to 256M before uncompressing, * However, The most memory required shouldn't be much larger than the Archive itself. * * @since 2.5.0 * * @param string $file Full path and filename of zip archive * @param string $to Full path on the filesystem to extract archive to * @return mixed WP_Error on failure, True on success */ function unzip_file($file, $to) { global $wp_filesystem; if ( ! $wp_filesystem || !is_object($wp_filesystem) ) return new WP_Error('fs_unavailable', __('Could not access filesystem.')); // Unzip can use a lot of memory, but not this much hopefully @ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', WP_MAX_MEMORY_LIMIT ) ); $needed_dirs = array(); $to = trailingslashit($to); // Determine any parent dir's needed (of the upgrade directory) if ( ! $wp_filesystem->is_dir($to) ) { //Only do parents if no children exist $path = preg_split('![/\\\]!', untrailingslashit($to)); for ( $i = count($path); $i >= 0; $i-- ) { if ( empty($path[$i]) ) continue; $dir = implode('/', array_slice($path, 0, $i+1) ); if ( preg_match('!^[a-z]:$!i', $dir) ) // Skip it if it looks like a Windows Drive letter. continue; if ( ! $wp_filesystem->is_dir($dir) ) $needed_dirs[] = $dir; else break; // A folder exists, therefor, we dont need the check the levels below this } } if ( class_exists('ZipArchive') && apply_filters('unzip_file_use_ziparchive', true ) ) { $result = _unzip_file_ziparchive($file, $to, $needed_dirs); if ( true === $result ) { return $result; } elseif ( is_wp_error($result) ) { if ( 'incompatible_archive' != $result->get_error_code() ) return $result; } } // Fall through to PclZip if ZipArchive is not available, or encountered an error opening the file. return _unzip_file_pclzip($file, $to, $needed_dirs); } /** * This function should not be called directly, use unzip_file instead. Attempts to unzip an archive using the ZipArchive class. * Assumes that WP_Filesystem() has already been called and set up. * * @since 3.0.0 * @see unzip_file * @access private * * @param string $file Full path and filename of zip archive * @param string $to Full path on the filesystem to extract archive to * @param array $needed_dirs A partial list of required folders needed to be created. * @return mixed WP_Error on failure, True on success */ function _unzip_file_ziparchive($file, $to, $needed_dirs = array() ) { global $wp_filesystem; $z = new ZipArchive(); // PHP4-compat - php4 classes can't contain constants $zopen = $z->open($file, /* ZIPARCHIVE::CHECKCONS */ 4); if ( true !== $zopen ) return new WP_Error('incompatible_archive', __('Incompatible Archive.')); for ( $i = 0; $i < $z->numFiles; $i++ ) { if ( ! $info = $z->statIndex($i) ) return new WP_Error('stat_failed', __('Could not retrieve file from archive.')); if ( '__MACOSX/' === substr($info['name'], 0, 9) ) // Skip the OS X-created __MACOSX directory continue; if ( '/' == substr($info['name'], -1) ) // directory $needed_dirs[] = $to . untrailingslashit($info['name']); else $needed_dirs[] = $to . untrailingslashit(dirname($info['name'])); } $needed_dirs = array_unique($needed_dirs); foreach ( $needed_dirs as $dir ) { // Check the parent folders of the folders all exist within the creation array. if ( untrailingslashit($to) == $dir ) // Skip over the working directory, We know this exists (or will exist) continue; if ( strpos($dir, $to) === false ) // If the directory is not within the working directory, Skip it continue; $parent_folder = dirname($dir); while ( !empty($parent_folder) && untrailingslashit($to) != $parent_folder && !in_array($parent_folder, $needed_dirs) ) { $needed_dirs[] = $parent_folder; $parent_folder = dirname($parent_folder); } } asort($needed_dirs); // Create those directories if need be: foreach ( $needed_dirs as $_dir ) { if ( ! $wp_filesystem->mkdir($_dir, FS_CHMOD_DIR) && ! $wp_filesystem->is_dir($_dir) ) // Only check to see if the Dir exists upon creation failure. Less I/O this way. return new WP_Error('mkdir_failed', __('Could not create directory.'), $_dir); } unset($needed_dirs); for ( $i = 0; $i < $z->numFiles; $i++ ) { if ( ! $info = $z->statIndex($i) ) return new WP_Error('stat_failed', __('Could not retrieve file from archive.')); if ( '/' == substr($info['name'], -1) ) // directory continue; if ( '__MACOSX/' === substr($info['name'], 0, 9) ) // Don't extract the OS X-created __MACOSX directory files continue; $contents = $z->getFromIndex($i); if ( false === $contents ) return new WP_Error('extract_failed', __('Could not extract file from archive.'), $info['name']); if ( ! $wp_filesystem->put_contents( $to . $info['name'], $contents, FS_CHMOD_FILE) ) return new WP_Error('copy_failed', __('Could not copy file.'), $to . $info['name']); } $z->close(); return true; } /** * This function should not be called directly, use unzip_file instead. Attempts to unzip an archive using the PclZip library. * Assumes that WP_Filesystem() has already been called and set up. * * @since 3.0.0 * @see unzip_file * @access private * * @param string $file Full path and filename of zip archive * @param string $to Full path on the filesystem to extract archive to * @param array $needed_dirs A partial list of required folders needed to be created. * @return mixed WP_Error on failure, True on success */ function _unzip_file_pclzip($file, $to, $needed_dirs = array()) { global $wp_filesystem; // See #15789 - PclZip uses string functions on binary data, If it's overloaded with Multibyte safe functions the results are incorrect. if ( ini_get('mbstring.func_overload') && function_exists('mb_internal_encoding') ) { $previous_encoding = mb_internal_encoding(); mb_internal_encoding('ISO-8859-1'); } require_once(ABSPATH . 'wp-admin/includes/class-pclzip.php'); $archive = new PclZip($file); $archive_files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING); if ( isset($previous_encoding) ) mb_internal_encoding($previous_encoding); // Is the archive valid? if ( !is_array($archive_files) ) return new WP_Error('incompatible_archive', __('Incompatible Archive.'), $archive->errorInfo(true)); if ( 0 == count($archive_files) ) return new WP_Error('empty_archive', __('Empty archive.')); // Determine any children directories needed (From within the archive) foreach ( $archive_files as $file ) { if ( '__MACOSX/' === substr($file['filename'], 0, 9) ) // Skip the OS X-created __MACOSX directory continue; $needed_dirs[] = $to . untrailingslashit( $file['folder'] ? $file['filename'] : dirname($file['filename']) ); } $needed_dirs = array_unique($needed_dirs); foreach ( $needed_dirs as $dir ) { // Check the parent folders of the folders all exist within the creation array. if ( untrailingslashit($to) == $dir ) // Skip over the working directory, We know this exists (or will exist) continue; if ( strpos($dir, $to) === false ) // If the directory is not within the working directory, Skip it continue; $parent_folder = dirname($dir); while ( !empty($parent_folder) && untrailingslashit($to) != $parent_folder && !in_array($parent_folder, $needed_dirs) ) { $needed_dirs[] = $parent_folder; $parent_folder = dirname($parent_folder); } } asort($needed_dirs); // Create those directories if need be: foreach ( $needed_dirs as $_dir ) { if ( ! $wp_filesystem->mkdir($_dir, FS_CHMOD_DIR) && ! $wp_filesystem->is_dir($_dir) ) // Only check to see if the dir exists upon creation failure. Less I/O this way. return new WP_Error('mkdir_failed', __('Could not create directory.'), $_dir); } unset($needed_dirs); // Extract the files from the zip foreach ( $archive_files as $file ) { if ( $file['folder'] ) continue; if ( '__MACOSX/' === substr($file['filename'], 0, 9) ) // Don't extract the OS X-created __MACOSX directory files continue; if ( ! $wp_filesystem->put_contents( $to . $file['filename'], $file['content'], FS_CHMOD_FILE) ) return new WP_Error('copy_failed', __('Could not copy file.'), $to . $file['filename']); } return true; } /** * Copies a directory from one location to another via the WordPress Filesystem Abstraction. * Assumes that WP_Filesystem() has already been called and setup. * * @since 2.5.0 * * @param string $from source directory * @param string $to destination directory * @param array $skip_list a list of files/folders to skip copying * @return mixed WP_Error on failure, True on success. */ function copy_dir($from, $to, $skip_list = array() ) { global $wp_filesystem; $dirlist = $wp_filesystem->dirlist($from); $from = trailingslashit($from); $to = trailingslashit($to); $skip_regex = ''; foreach ( (array)$skip_list as $key => $skip_file ) $skip_regex .= preg_quote($skip_file, '!') . '|'; if ( !empty($skip_regex) ) $skip_regex = '!(' . rtrim($skip_regex, '|') . ')$!i'; foreach ( (array) $dirlist as $filename => $fileinfo ) { if ( !empty($skip_regex) ) if ( preg_match($skip_regex, $from . $filename) ) continue; if ( 'f' == $fileinfo['type'] ) { if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) ) { // If copy failed, chmod file to 0644 and try again. $wp_filesystem->chmod($to . $filename, 0644); if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) ) return new WP_Error('copy_failed', __('Could not copy file.'), $to . $filename); } } elseif ( 'd' == $fileinfo['type'] ) { if ( !$wp_filesystem->is_dir($to . $filename) ) { if ( !$wp_filesystem->mkdir($to . $filename, FS_CHMOD_DIR) ) return new WP_Error('mkdir_failed', __('Could not create directory.'), $to . $filename); } $result = copy_dir($from . $filename, $to . $filename, $skip_list); if ( is_wp_error($result) ) return $result; } } return true; } /** * Initialises and connects the WordPress Filesystem Abstraction classes. * This function will include the chosen transport and attempt connecting. * * Plugins may add extra transports, And force WordPress to use them by returning the filename via the 'filesystem_method_file' filter. * * @since 2.5.0 * * @param array $args (optional) Connection args, These are passed directly to the WP_Filesystem_*() classes. * @param string $context (optional) Context for get_filesystem_method(), See function declaration for more information. * @return boolean false on failure, true on success */ function WP_Filesystem( $args = false, $context = false ) { global $wp_filesystem; require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php'); $method = get_filesystem_method($args, $context); if ( ! $method ) return false; if ( ! class_exists("WP_Filesystem_$method") ) { $abstraction_file = apply_filters('filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method); if ( ! file_exists($abstraction_file) ) return; require_once($abstraction_file); } $method = "WP_Filesystem_$method"; $wp_filesystem = new $method($args); //Define the timeouts for the connections. Only available after the construct is called to allow for per-transport overriding of the default. if ( ! defined('FS_CONNECT_TIMEOUT') ) define('FS_CONNECT_TIMEOUT', 30); if ( ! defined('FS_TIMEOUT') ) define('FS_TIMEOUT', 30); if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() ) return false; if ( !$wp_filesystem->connect() ) return false; //There was an error connecting to the server. // Set the permission constants if not already set. if ( ! defined('FS_CHMOD_DIR') ) define('FS_CHMOD_DIR', 0755 ); if ( ! defined('FS_CHMOD_FILE') ) define('FS_CHMOD_FILE', 0644 ); return true; } /** * Determines which Filesystem Method to use. * The priority of the Transports are: Direct, SSH2, FTP PHP Extension, FTP Sockets (Via Sockets class, or fsockopen()) * * Note that the return value of this function can be overridden in 2 ways * - By defining FS_METHOD in your <code>wp-config.php</code> file * - By using the filesystem_method filter * Valid values for these are: 'direct', 'ssh', 'ftpext' or 'ftpsockets' * Plugins may also define a custom transport handler, See the WP_Filesystem function for more information. * * @since 2.5.0 * * @param array $args Connection details. * @param string $context Full path to the directory that is tested for being writable. * @return string The transport to use, see description for valid return values. */ function get_filesystem_method($args = array(), $context = false) { $method = defined('FS_METHOD') ? FS_METHOD : false; //Please ensure that this is either 'direct', 'ssh', 'ftpext' or 'ftpsockets' if ( ! $method && function_exists('getmyuid') && function_exists('fileowner') ){ if ( !$context ) $context = WP_CONTENT_DIR; $context = trailingslashit($context); $temp_file_name = $context . 'temp-write-test-' . time(); $temp_handle = @fopen($temp_file_name, 'w'); if ( $temp_handle ) { if ( getmyuid() == @fileowner($temp_file_name) ) $method = 'direct'; @fclose($temp_handle); @unlink($temp_file_name); } } if ( ! $method && isset($args['connection_type']) && 'ssh' == $args['connection_type'] && extension_loaded('ssh2') && function_exists('stream_get_contents') ) $method = 'ssh2'; if ( ! $method && extension_loaded('ftp') ) $method = 'ftpext'; if ( ! $method && ( extension_loaded('sockets') || function_exists('fsockopen') ) ) $method = 'ftpsockets'; //Sockets: Socket extension; PHP Mode: FSockopen / fwrite / fread return apply_filters('filesystem_method', $method, $args); } /** * Displays a form to the user to request for their FTP/SSH details in order to connect to the filesystem. * All chosen/entered details are saved, Excluding the Password. * * Hostnames may be in the form of hostname:portnumber (eg: wordpress.org:2467) to specify an alternate FTP/SSH port. * * Plugins may override this form by returning true|false via the <code>request_filesystem_credentials</code> filter. * * @since 2.5.0 * * @param string $form_post the URL to post the form to * @param string $type the chosen Filesystem method in use * @param boolean $error if the current request has failed to connect * @param string $context The directory which is needed access to, The write-test will be performed on this directory by get_filesystem_method() * @param string $extra_fields Extra POST fields which should be checked for to be included in the post. * @return boolean False on failure. True on success. */ function request_filesystem_credentials($form_post, $type = '', $error = false, $context = false, $extra_fields = null) { $req_cred = apply_filters( 'request_filesystem_credentials', '', $form_post, $type, $error, $context, $extra_fields ); if ( '' !== $req_cred ) return $req_cred; if ( empty($type) ) $type = get_filesystem_method(array(), $context); if ( 'direct' == $type ) return true; if ( is_null( $extra_fields ) ) $extra_fields = array( 'version', 'locale' ); $credentials = get_option('ftp_credentials', array( 'hostname' => '', 'username' => '')); // If defined, set it to that, Else, If POST'd, set it to that, If not, Set it to whatever it previously was(saved details in option) $credentials['hostname'] = defined('FTP_HOST') ? FTP_HOST : (!empty($_POST['hostname']) ? stripslashes($_POST['hostname']) : $credentials['hostname']); $credentials['username'] = defined('FTP_USER') ? FTP_USER : (!empty($_POST['username']) ? stripslashes($_POST['username']) : $credentials['username']); $credentials['password'] = defined('FTP_PASS') ? FTP_PASS : (!empty($_POST['password']) ? stripslashes($_POST['password']) : ''); // Check to see if we are setting the public/private keys for ssh $credentials['public_key'] = defined('FTP_PUBKEY') ? FTP_PUBKEY : (!empty($_POST['public_key']) ? stripslashes($_POST['public_key']) : ''); $credentials['private_key'] = defined('FTP_PRIKEY') ? FTP_PRIKEY : (!empty($_POST['private_key']) ? stripslashes($_POST['private_key']) : ''); //sanitize the hostname, Some people might pass in odd-data: $credentials['hostname'] = preg_replace('|\w+://|', '', $credentials['hostname']); //Strip any schemes off if ( strpos($credentials['hostname'], ':') ) { list( $credentials['hostname'], $credentials['port'] ) = explode(':', $credentials['hostname'], 2); if ( ! is_numeric($credentials['port']) ) unset($credentials['port']); } else { unset($credentials['port']); } if ( (defined('FTP_SSH') && FTP_SSH) || (defined('FS_METHOD') && 'ssh' == FS_METHOD) ) $credentials['connection_type'] = 'ssh'; else if ( (defined('FTP_SSL') && FTP_SSL) && 'ftpext' == $type ) //Only the FTP Extension understands SSL $credentials['connection_type'] = 'ftps'; else if ( !empty($_POST['connection_type']) ) $credentials['connection_type'] = stripslashes($_POST['connection_type']); else if ( !isset($credentials['connection_type']) ) //All else fails (And its not defaulted to something else saved), Default to FTP $credentials['connection_type'] = 'ftp'; if ( ! $error && ( ( !empty($credentials['password']) && !empty($credentials['username']) && !empty($credentials['hostname']) ) || ( 'ssh' == $credentials['connection_type'] && !empty($credentials['public_key']) && !empty($credentials['private_key']) ) ) ) { $stored_credentials = $credentials; if ( !empty($stored_credentials['port']) ) //save port as part of hostname to simplify above code. $stored_credentials['hostname'] .= ':' . $stored_credentials['port']; unset($stored_credentials['password'], $stored_credentials['port'], $stored_credentials['private_key'], $stored_credentials['public_key']); update_option('ftp_credentials', $stored_credentials); return $credentials; } $hostname = ''; $username = ''; $password = ''; $connection_type = ''; if ( !empty($credentials) ) extract($credentials, EXTR_OVERWRITE); if ( $error ) { $error_string = __('<strong>ERROR:</strong> There was an error connecting to the server, Please verify the settings are correct.'); if ( is_wp_error($error) ) $error_string = esc_html( $error->get_error_message() ); echo '<div id="message" class="error"><p>' . $error_string . '</p></div>'; } $types = array(); if ( extension_loaded('ftp') || extension_loaded('sockets') || function_exists('fsockopen') ) $types[ 'ftp' ] = __('FTP'); if ( extension_loaded('ftp') ) //Only this supports FTPS $types[ 'ftps' ] = __('FTPS (SSL)'); if ( extension_loaded('ssh2') && function_exists('stream_get_contents') ) $types[ 'ssh' ] = __('SSH2'); $types = apply_filters('fs_ftp_connection_types', $types, $credentials, $type, $error, $context); ?> <script type="text/javascript"> <!-- jQuery(function($){ jQuery("#ssh").click(function () { jQuery("#ssh_keys").show(); }); jQuery("#ftp, #ftps").click(function () { jQuery("#ssh_keys").hide(); }); jQuery('form input[value=""]:first').focus(); }); --> </script> <form action="<?php echo $form_post ?>" method="post"> <div class="wrap"> <?php screen_icon(); ?> <h2><?php _e('Connection Information') ?></h2> <p><?php $label_user = __('Username'); $label_pass = __('Password'); _e('To perform the requested action, WordPress needs to access your web server.'); echo ' '; if ( ( isset( $types['ftp'] ) || isset( $types['ftps'] ) ) ) { if ( isset( $types['ssh'] ) ) { _e('Please enter your FTP or SSH credentials to proceed.'); $label_user = __('FTP/SSH Username'); $label_pass = __('FTP/SSH Password'); } else { _e('Please enter your FTP credentials to proceed.'); $label_user = __('FTP Username'); $label_pass = __('FTP Password'); } echo ' '; } _e('If you do not remember your credentials, you should contact your web host.'); ?></p> <table class="form-table"> <tr valign="top"> <th scope="row"><label for="hostname"><?php _e('Hostname') ?></label></th> <td><input name="hostname" type="text" id="hostname" value="<?php echo esc_attr($hostname); if ( !empty($port) ) echo ":$port"; ?>"<?php disabled( defined('FTP_HOST') ); ?> size="40" /></td> </tr> <tr valign="top"> <th scope="row"><label for="username"><?php echo $label_user; ?></label></th> <td><input name="username" type="text" id="username" value="<?php echo esc_attr($username) ?>"<?php disabled( defined('FTP_USER') ); ?> size="40" /></td> </tr> <tr valign="top"> <th scope="row"><label for="password"><?php echo $label_pass; ?></label></th> <td><input name="password" type="password" id="password" value="<?php if ( defined('FTP_PASS') ) echo '*****'; ?>"<?php disabled( defined('FTP_PASS') ); ?> size="40" /></td> </tr> <?php if ( isset($types['ssh']) ) : ?> <tr id="ssh_keys" valign="top" style="<?php if ( 'ssh' != $connection_type ) echo 'display:none' ?>"> <th scope="row"><?php _e('Authentication Keys') ?> <div class="key-labels textright"> <label for="public_key"><?php _e('Public Key:') ?></label ><br /> <label for="private_key"><?php _e('Private Key:') ?></label> </div></th> <td><br /><input name="public_key" type="text" id="public_key" value="<?php echo esc_attr($public_key) ?>"<?php disabled( defined('FTP_PUBKEY') ); ?> size="40" /><br /><input name="private_key" type="text" id="private_key" value="<?php echo esc_attr($private_key) ?>"<?php disabled( defined('FTP_PRIKEY') ); ?> size="40" /> <div><?php _e('Enter the location on the server where the keys are located. If a passphrase is needed, enter that in the password field above.') ?></div></td> </tr> <?php endif; ?> <tr valign="top"> <th scope="row"><?php _e('Connection Type') ?></th> <td> <fieldset><legend class="screen-reader-text"><span><?php _e('Connection Type') ?></span></legend> <?php $disabled = disabled( (defined('FTP_SSL') && FTP_SSL) || (defined('FTP_SSH') && FTP_SSH), true, false ); foreach ( $types as $name => $text ) : ?> <label for="<?php echo esc_attr($name) ?>"> <input type="radio" name="connection_type" id="<?php echo esc_attr($name) ?>" value="<?php echo esc_attr($name) ?>"<?php checked($name, $connection_type); echo $disabled; ?> /> <?php echo $text ?> </label> <?php endforeach; ?> </fieldset> </td> </tr> </table> <?php foreach ( (array) $extra_fields as $field ) { if ( isset( $_POST[ $field ] ) ) echo '<input type="hidden" name="' . esc_attr( $field ) . '" value="' . esc_attr( stripslashes( $_POST[ $field ] ) ) . '" />'; } submit_button( __( 'Proceed' ), 'button', 'upgrade' ); ?> </div> </form> <?php return false; }
zyblog
trunk/zyblog/wp-admin/includes/file.php
PHP
asf20
42,035
<?php /** * WordPress Taxonomy Administration API. * * @package WordPress * @subpackage Administration */ // // Category // /** * {@internal Missing Short Description}} * * @since 2.0.0 * * @param unknown_type $cat_name * @return unknown */ function category_exists($cat_name, $parent = 0) { $id = term_exists($cat_name, 'category', $parent); if ( is_array($id) ) $id = $id['term_id']; return $id; } /** * {@internal Missing Short Description}} * * @since 2.0.0 * * @param unknown_type $id * @return unknown */ function get_category_to_edit( $id ) { $category = get_category( $id, OBJECT, 'edit' ); return $category; } /** * {@internal Missing Short Description}} * * @since 2.0.0 * * @param unknown_type $cat_name * @param unknown_type $parent * @return unknown */ function wp_create_category( $cat_name, $parent = 0 ) { if ( $id = category_exists($cat_name, $parent) ) return $id; return wp_insert_category( array('cat_name' => $cat_name, 'category_parent' => $parent) ); } /** * {@internal Missing Short Description}} * * @since 2.0.0 * * @param unknown_type $categories * @param unknown_type $post_id * @return unknown */ function wp_create_categories($categories, $post_id = '') { $cat_ids = array (); foreach ($categories as $category) { if ($id = category_exists($category)) $cat_ids[] = $id; else if ($id = wp_create_category($category)) $cat_ids[] = $id; } if ( $post_id ) wp_set_post_categories($post_id, $cat_ids); return $cat_ids; } /** * Updates an existing Category or creates a new Category. * * @since 2.0.0 * * @param mixed $catarr See defaults below. Set 'cat_ID' to a non-zero value to update an existing category. The 'taxonomy' key was added in 3.0.0. * @param bool $wp_error Optional, since 2.5.0. Set this to true if the caller handles WP_Error return values. * @return int|object The ID number of the new or updated Category on success. Zero or a WP_Error on failure, depending on param $wp_error. */ function wp_insert_category($catarr, $wp_error = false) { $cat_defaults = array('cat_ID' => 0, 'taxonomy' => 'category', 'cat_name' => '', 'category_description' => '', 'category_nicename' => '', 'category_parent' => ''); $catarr = wp_parse_args($catarr, $cat_defaults); extract($catarr, EXTR_SKIP); if ( trim( $cat_name ) == '' ) { if ( ! $wp_error ) return 0; else return new WP_Error( 'cat_name', __('You did not enter a category name.') ); } $cat_ID = (int) $cat_ID; // Are we updating or creating? if ( !empty ($cat_ID) ) $update = true; else $update = false; $name = $cat_name; $description = $category_description; $slug = $category_nicename; $parent = $category_parent; $parent = (int) $parent; if ( $parent < 0 ) $parent = 0; if ( empty( $parent ) || ! term_exists( $parent, $taxonomy ) || ( $cat_ID && term_is_ancestor_of( $cat_ID, $parent, $taxonomy ) ) ) $parent = 0; $args = compact('name', 'slug', 'parent', 'description'); if ( $update ) $cat_ID = wp_update_term($cat_ID, $taxonomy, $args); else $cat_ID = wp_insert_term($cat_name, $taxonomy, $args); if ( is_wp_error($cat_ID) ) { if ( $wp_error ) return $cat_ID; else return 0; } return $cat_ID['term_id']; } /** * Aliases wp_insert_category() with minimal args. * * If you want to update only some fields of an existing category, call this * function with only the new values set inside $catarr. * * @since 2.0.0 * * @param array $catarr The 'cat_ID' value is required. All other keys are optional. * @return int|bool The ID number of the new or updated Category on success. Zero or FALSE on failure. */ function wp_update_category($catarr) { $cat_ID = (int) $catarr['cat_ID']; if ( isset($catarr['category_parent']) && ($cat_ID == $catarr['category_parent']) ) return false; // First, get all of the original fields $category = get_category($cat_ID, ARRAY_A); // Escape data pulled from DB. $category = add_magic_quotes($category); // Merge old and new fields with new fields overwriting old ones. $catarr = array_merge($category, $catarr); return wp_insert_category($catarr); } // // Tags // /** * {@internal Missing Short Description}} * * @since 2.3.0 * * @param unknown_type $tag_name * @return unknown */ function tag_exists($tag_name) { return term_exists($tag_name, 'post_tag'); } /** * {@internal Missing Short Description}} * * @since 2.3.0 * * @param unknown_type $tag_name * @return unknown */ function wp_create_tag($tag_name) { return wp_create_term( $tag_name, 'post_tag'); } /** * {@internal Missing Short Description}} * * @since 2.3.0 * * @param unknown_type $post_id * @return unknown */ function get_tags_to_edit( $post_id, $taxonomy = 'post_tag' ) { return get_terms_to_edit( $post_id, $taxonomy); } /** * {@internal Missing Short Description}} * * @since 2.8.0 * * @param unknown_type $post_id * @return unknown */ function get_terms_to_edit( $post_id, $taxonomy = 'post_tag' ) { $post_id = (int) $post_id; if ( !$post_id ) return false; $tags = wp_get_post_terms($post_id, $taxonomy, array()); if ( !$tags ) return false; if ( is_wp_error($tags) ) return $tags; foreach ( $tags as $tag ) $tag_names[] = $tag->name; $tags_to_edit = join( ',', $tag_names ); $tags_to_edit = esc_attr( $tags_to_edit ); $tags_to_edit = apply_filters( 'terms_to_edit', $tags_to_edit, $taxonomy ); return $tags_to_edit; } /** * {@internal Missing Short Description}} * * @since 2.8.0 * * @param unknown_type $tag_name * @return unknown */ function wp_create_term($tag_name, $taxonomy = 'post_tag') { if ( $id = term_exists($tag_name, $taxonomy) ) return $id; return wp_insert_term($tag_name, $taxonomy); }
zyblog
trunk/zyblog/wp-admin/includes/taxonomy.php
PHP
asf20
5,745
<?php /** * Comments and Post Comments List Table classes. * * @package WordPress * @subpackage List_Table * @since 3.1.0 */ /** * Comments List Table class. * * @package WordPress * @subpackage List_Table * @since 3.1.0 * @access private */ class WP_Comments_List_Table extends WP_List_Table { var $checkbox = true; var $pending_count = array(); function __construct( $args = array() ) { global $post_id; $post_id = isset( $_REQUEST['p'] ) ? absint( $_REQUEST['p'] ) : 0; if ( get_option('show_avatars') ) add_filter( 'comment_author', 'floated_admin_avatar' ); parent::__construct( array( 'plural' => 'comments', 'singular' => 'comment', 'ajax' => true, 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); } function ajax_user_can() { return current_user_can('edit_posts'); } function prepare_items() { global $post_id, $comment_status, $search, $comment_type; $comment_status = isset( $_REQUEST['comment_status'] ) ? $_REQUEST['comment_status'] : 'all'; if ( !in_array( $comment_status, array( 'all', 'moderated', 'approved', 'spam', 'trash' ) ) ) $comment_status = 'all'; $comment_type = !empty( $_REQUEST['comment_type'] ) ? $_REQUEST['comment_type'] : ''; $search = ( isset( $_REQUEST['s'] ) ) ? $_REQUEST['s'] : ''; $user_id = ( isset( $_REQUEST['user_id'] ) ) ? $_REQUEST['user_id'] : ''; $orderby = ( isset( $_REQUEST['orderby'] ) ) ? $_REQUEST['orderby'] : ''; $order = ( isset( $_REQUEST['order'] ) ) ? $_REQUEST['order'] : ''; $comments_per_page = $this->get_per_page( $comment_status ); $doing_ajax = defined( 'DOING_AJAX' ) && DOING_AJAX; if ( isset( $_REQUEST['number'] ) ) { $number = (int) $_REQUEST['number']; } else { $number = $comments_per_page + min( 8, $comments_per_page ); // Grab a few extra } $page = $this->get_pagenum(); if ( isset( $_REQUEST['start'] ) ) { $start = $_REQUEST['start']; } else { $start = ( $page - 1 ) * $comments_per_page; } if ( $doing_ajax && isset( $_REQUEST['offset'] ) ) { $start += $_REQUEST['offset']; } $status_map = array( 'moderated' => 'hold', 'approved' => 'approve', 'all' => '', ); $args = array( 'status' => isset( $status_map[$comment_status] ) ? $status_map[$comment_status] : $comment_status, 'search' => $search, 'user_id' => $user_id, 'offset' => $start, 'number' => $number, 'post_id' => $post_id, 'type' => $comment_type, 'orderby' => $orderby, 'order' => $order, ); $_comments = get_comments( $args ); update_comment_cache( $_comments ); $this->items = array_slice( $_comments, 0, $comments_per_page ); $this->extra_items = array_slice( $_comments, $comments_per_page ); $total_comments = get_comments( array_merge( $args, array('count' => true, 'offset' => 0, 'number' => 0) ) ); $_comment_post_ids = array(); foreach ( $_comments as $_c ) { $_comment_post_ids[] = $_c->comment_post_ID; } $_comment_post_ids = array_unique( $_comment_post_ids ); $this->pending_count = get_pending_comments_num( $_comment_post_ids ); $this->set_pagination_args( array( 'total_items' => $total_comments, 'per_page' => $comments_per_page, ) ); } function get_per_page( $comment_status = 'all' ) { $comments_per_page = $this->get_items_per_page( 'edit_comments_per_page' ); $comments_per_page = apply_filters( 'comments_per_page', $comments_per_page, $comment_status ); return $comments_per_page; } function no_items() { global $comment_status; if ( 'moderated' == $comment_status ) _e( 'No comments awaiting moderation.' ); else _e( 'No comments found.' ); } function get_views() { global $post_id, $comment_status, $comment_type; $status_links = array(); $num_comments = ( $post_id ) ? wp_count_comments( $post_id ) : wp_count_comments(); //, number_format_i18n($num_comments->moderated) ), "<span class='comment-count'>" . number_format_i18n($num_comments->moderated) . "</span>"), //, number_format_i18n($num_comments->spam) ), "<span class='spam-comment-count'>" . number_format_i18n($num_comments->spam) . "</span>") $stati = array( 'all' => _nx_noop('All', 'All', 'comments'), // singular not used 'moderated' => _n_noop('Pending <span class="count">(<span class="pending-count">%s</span>)</span>', 'Pending <span class="count">(<span class="pending-count">%s</span>)</span>'), 'approved' => _n_noop('Approved', 'Approved'), // singular not used 'spam' => _n_noop('Spam <span class="count">(<span class="spam-count">%s</span>)</span>', 'Spam <span class="count">(<span class="spam-count">%s</span>)</span>'), 'trash' => _n_noop('Trash <span class="count">(<span class="trash-count">%s</span>)</span>', 'Trash <span class="count">(<span class="trash-count">%s</span>)</span>') ); if ( !EMPTY_TRASH_DAYS ) unset($stati['trash']); $link = 'edit-comments.php'; if ( !empty($comment_type) && 'all' != $comment_type ) $link = add_query_arg( 'comment_type', $comment_type, $link ); foreach ( $stati as $status => $label ) { $class = ( $status == $comment_status ) ? ' class="current"' : ''; if ( !isset( $num_comments->$status ) ) $num_comments->$status = 10; $link = add_query_arg( 'comment_status', $status, $link ); if ( $post_id ) $link = add_query_arg( 'p', absint( $post_id ), $link ); /* // I toyed with this, but decided against it. Leaving it in here in case anyone thinks it is a good idea. ~ Mark if ( !empty( $_REQUEST['s'] ) ) $link = add_query_arg( 's', esc_attr( stripslashes( $_REQUEST['s'] ) ), $link ); */ $status_links[$status] = "<a href='$link'$class>" . sprintf( translate_nooped_plural( $label, $num_comments->$status ), number_format_i18n( $num_comments->$status ) ) . '</a>'; } $status_links = apply_filters( 'comment_status_links', $status_links ); return $status_links; } function get_bulk_actions() { global $comment_status; $actions = array(); if ( in_array( $comment_status, array( 'all', 'approved' ) ) ) $actions['unapprove'] = __( 'Unapprove' ); if ( in_array( $comment_status, array( 'all', 'moderated' ) ) ) $actions['approve'] = __( 'Approve' ); if ( in_array( $comment_status, array( 'all', 'moderated', 'approved' ) ) ) $actions['spam'] = _x( 'Mark as Spam', 'comment' ); if ( 'trash' == $comment_status ) $actions['untrash'] = __( 'Restore' ); elseif ( 'spam' == $comment_status ) $actions['unspam'] = _x( 'Not Spam', 'comment' ); if ( in_array( $comment_status, array( 'trash', 'spam' ) ) || !EMPTY_TRASH_DAYS ) $actions['delete'] = __( 'Delete Permanently' ); else $actions['trash'] = __( 'Move to Trash' ); return $actions; } function extra_tablenav( $which ) { global $comment_status, $comment_type; ?> <div class="alignleft actions"> <?php if ( 'top' == $which ) { ?> <select name="comment_type"> <option value=""><?php _e( 'Show all comment types' ); ?></option> <?php $comment_types = apply_filters( 'admin_comment_types_dropdown', array( 'comment' => __( 'Comments' ), 'pings' => __( 'Pings' ), ) ); foreach ( $comment_types as $type => $label ) echo "\t<option value='" . esc_attr( $type ) . "'" . selected( $comment_type, $type, false ) . ">$label</option>\n"; ?> </select> <?php do_action( 'restrict_manage_comments' ); submit_button( __( 'Filter' ), 'button', false, false, array( 'id' => 'post-query-submit' ) ); } if ( ( 'spam' == $comment_status || 'trash' == $comment_status ) && current_user_can( 'moderate_comments' ) ) { wp_nonce_field( 'bulk-destroy', '_destroy_nonce' ); $title = ( 'spam' == $comment_status ) ? esc_attr__( 'Empty Spam' ) : esc_attr__( 'Empty Trash' ); submit_button( $title, 'apply', 'delete_all', false ); } do_action( 'manage_comments_nav', $comment_status ); echo '</div>'; } function current_action() { if ( isset( $_REQUEST['delete_all'] ) || isset( $_REQUEST['delete_all2'] ) ) return 'delete_all'; return parent::current_action(); } function get_columns() { global $post_id; $columns = array(); if ( $this->checkbox ) $columns['cb'] = '<input type="checkbox" />'; $columns['author'] = __( 'Author' ); $columns['comment'] = _x( 'Comment', 'column name' ); if ( !$post_id ) $columns['response'] = _x( 'In Response To', 'column name' ); return $columns; } function get_sortable_columns() { return array( 'author' => 'comment_author', 'response' => 'comment_post_ID' ); } function display() { extract( $this->_args ); wp_nonce_field( "fetch-list-" . get_class( $this ), '_ajax_fetch_list_nonce' ); $this->display_tablenav( 'top' ); ?> <table class="<?php echo implode( ' ', $this->get_table_classes() ); ?>" cellspacing="0"> <thead> <tr> <?php $this->print_column_headers(); ?> </tr> </thead> <tfoot> <tr> <?php $this->print_column_headers( false ); ?> </tr> </tfoot> <tbody id="the-comment-list" data-wp-lists="list:comment"> <?php $this->display_rows_or_placeholder(); ?> </tbody> <tbody id="the-extra-comment-list" data-wp-lists="list:comment" style="display: none;"> <?php $this->items = $this->extra_items; $this->display_rows(); ?> </tbody> </table> <?php $this->display_tablenav( 'bottom' ); } function single_row( $a_comment ) { global $post, $comment; $comment = $a_comment; $the_comment_class = join( ' ', get_comment_class( wp_get_comment_status( $comment->comment_ID ) ) ); $post = get_post( $comment->comment_post_ID ); $this->user_can = current_user_can( 'edit_comment', $comment->comment_ID ); echo "<tr id='comment-$comment->comment_ID' class='$the_comment_class'>"; echo $this->single_row_columns( $comment ); echo "</tr>\n"; } function column_cb( $comment ) { if ( $this->user_can ) { ?> <label class="screen-reader-text" for="cb-select-<?php echo $comment->comment_ID; ?>"><?php _e( 'Select comment' ); ?></label> <input id="cb-select-<?php echo $comment->comment_ID; ?>" type="checkbox" name="delete_comments[]" value="<?php echo $comment->comment_ID; ?>" /> <?php } } function column_comment( $comment ) { global $comment_status; $post = get_post(); $user_can = $this->user_can; $comment_url = esc_url( get_comment_link( $comment->comment_ID ) ); $the_comment_status = wp_get_comment_status( $comment->comment_ID ); $ptime = date( 'G', strtotime( $comment->comment_date ) ); if ( ( abs( time() - $ptime ) ) < DAY_IN_SECONDS ) $ptime = sprintf( __( '%s ago' ), human_time_diff( $ptime ) ); else $ptime = mysql2date( __( 'Y/m/d \a\t g:i A' ), $comment->comment_date ); if ( $user_can ) { $del_nonce = esc_html( '_wpnonce=' . wp_create_nonce( "delete-comment_$comment->comment_ID" ) ); $approve_nonce = esc_html( '_wpnonce=' . wp_create_nonce( "approve-comment_$comment->comment_ID" ) ); $url = "comment.php?c=$comment->comment_ID"; $approve_url = esc_url( $url . "&action=approvecomment&$approve_nonce" ); $unapprove_url = esc_url( $url . "&action=unapprovecomment&$approve_nonce" ); $spam_url = esc_url( $url . "&action=spamcomment&$del_nonce" ); $unspam_url = esc_url( $url . "&action=unspamcomment&$del_nonce" ); $trash_url = esc_url( $url . "&action=trashcomment&$del_nonce" ); $untrash_url = esc_url( $url . "&action=untrashcomment&$del_nonce" ); $delete_url = esc_url( $url . "&action=deletecomment&$del_nonce" ); } echo '<div class="submitted-on">'; /* translators: 2: comment date, 3: comment time */ printf( __( 'Submitted on <a href="%1$s">%2$s at %3$s</a>' ), $comment_url, /* translators: comment date format. See http://php.net/date */ get_comment_date( __( 'Y/m/d' ) ), /* translators: comment time format. See http://php.net/date */ get_comment_date( get_option( 'time_format' ) ) ); if ( $comment->comment_parent ) { $parent = get_comment( $comment->comment_parent ); $parent_link = esc_url( get_comment_link( $comment->comment_parent ) ); $name = get_comment_author( $parent->comment_ID ); printf( ' | '.__( 'In reply to <a href="%1$s">%2$s</a>.' ), $parent_link, $name ); } echo '</div>'; comment_text(); if ( $user_can ) { ?> <div id="inline-<?php echo $comment->comment_ID; ?>" class="hidden"> <textarea class="comment" rows="1" cols="1"><?php echo esc_textarea( apply_filters( 'comment_edit_pre', $comment->comment_content ) ); ?></textarea> <div class="author-email"><?php echo esc_attr( $comment->comment_author_email ); ?></div> <div class="author"><?php echo esc_attr( $comment->comment_author ); ?></div> <div class="author-url"><?php echo esc_attr( $comment->comment_author_url ); ?></div> <div class="comment_status"><?php echo $comment->comment_approved; ?></div> </div> <?php } if ( $user_can ) { // preorder it: Approve | Reply | Quick Edit | Edit | Spam | Trash $actions = array( 'approve' => '', 'unapprove' => '', 'reply' => '', 'quickedit' => '', 'edit' => '', 'spam' => '', 'unspam' => '', 'trash' => '', 'untrash' => '', 'delete' => '' ); if ( $comment_status && 'all' != $comment_status ) { // not looking at all comments if ( 'approved' == $the_comment_status ) $actions['unapprove'] = "<a href='$unapprove_url' data-wp-lists='delete:the-comment-list:comment-$comment->comment_ID:e7e7d3:action=dim-comment&amp;new=unapproved' class='vim-u vim-destructive' title='" . esc_attr__( 'Unapprove this comment' ) . "'>" . __( 'Unapprove' ) . '</a>'; else if ( 'unapproved' == $the_comment_status ) $actions['approve'] = "<a href='$approve_url' data-wp-lists='delete:the-comment-list:comment-$comment->comment_ID:e7e7d3:action=dim-comment&amp;new=approved' class='vim-a vim-destructive' title='" . esc_attr__( 'Approve this comment' ) . "'>" . __( 'Approve' ) . '</a>'; } else { $actions['approve'] = "<a href='$approve_url' data-wp-lists='dim:the-comment-list:comment-$comment->comment_ID:unapproved:e7e7d3:e7e7d3:new=approved' class='vim-a' title='" . esc_attr__( 'Approve this comment' ) . "'>" . __( 'Approve' ) . '</a>'; $actions['unapprove'] = "<a href='$unapprove_url' data-wp-lists='dim:the-comment-list:comment-$comment->comment_ID:unapproved:e7e7d3:e7e7d3:new=unapproved' class='vim-u' title='" . esc_attr__( 'Unapprove this comment' ) . "'>" . __( 'Unapprove' ) . '</a>'; } if ( 'spam' != $the_comment_status && 'trash' != $the_comment_status ) { $actions['spam'] = "<a href='$spam_url' data-wp-lists='delete:the-comment-list:comment-$comment->comment_ID::spam=1' class='vim-s vim-destructive' title='" . esc_attr__( 'Mark this comment as spam' ) . "'>" . /* translators: mark as spam link */ _x( 'Spam', 'verb' ) . '</a>'; } elseif ( 'spam' == $the_comment_status ) { $actions['unspam'] = "<a href='$unspam_url' data-wp-lists='delete:the-comment-list:comment-$comment->comment_ID:66cc66:unspam=1' class='vim-z vim-destructive'>" . _x( 'Not Spam', 'comment' ) . '</a>'; } elseif ( 'trash' == $the_comment_status ) { $actions['untrash'] = "<a href='$untrash_url' data-wp-lists='delete:the-comment-list:comment-$comment->comment_ID:66cc66:untrash=1' class='vim-z vim-destructive'>" . __( 'Restore' ) . '</a>'; } if ( 'spam' == $the_comment_status || 'trash' == $the_comment_status || !EMPTY_TRASH_DAYS ) { $actions['delete'] = "<a href='$delete_url' data-wp-lists='delete:the-comment-list:comment-$comment->comment_ID::delete=1' class='delete vim-d vim-destructive'>" . __( 'Delete Permanently' ) . '</a>'; } else { $actions['trash'] = "<a href='$trash_url' data-wp-lists='delete:the-comment-list:comment-$comment->comment_ID::trash=1' class='delete vim-d vim-destructive' title='" . esc_attr__( 'Move this comment to the trash' ) . "'>" . _x( 'Trash', 'verb' ) . '</a>'; } if ( 'spam' != $the_comment_status && 'trash' != $the_comment_status ) { $actions['edit'] = "<a href='comment.php?action=editcomment&amp;c={$comment->comment_ID}' title='" . esc_attr__( 'Edit comment' ) . "'>". __( 'Edit' ) . '</a>'; $actions['quickedit'] = '<a onclick="commentReply.open( \''.$comment->comment_ID.'\',\''.$post->ID.'\',\'edit\' );return false;" class="vim-q" title="'.esc_attr__( 'Quick Edit' ).'" href="#">' . __( 'Quick&nbsp;Edit' ) . '</a>'; $actions['reply'] = '<a onclick="commentReply.open( \''.$comment->comment_ID.'\',\''.$post->ID.'\' );return false;" class="vim-r" title="'.esc_attr__( 'Reply to this comment' ).'" href="#">' . __( 'Reply' ) . '</a>'; } $actions = apply_filters( 'comment_row_actions', array_filter( $actions ), $comment ); $i = 0; echo '<div class="row-actions">'; foreach ( $actions as $action => $link ) { ++$i; ( ( ( 'approve' == $action || 'unapprove' == $action ) && 2 === $i ) || 1 === $i ) ? $sep = '' : $sep = ' | '; // Reply and quickedit need a hide-if-no-js span when not added with ajax if ( ( 'reply' == $action || 'quickedit' == $action ) && ! defined('DOING_AJAX') ) $action .= ' hide-if-no-js'; elseif ( ( $action == 'untrash' && $the_comment_status == 'trash' ) || ( $action == 'unspam' && $the_comment_status == 'spam' ) ) { if ( '1' == get_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', true ) ) $action .= ' approve'; else $action .= ' unapprove'; } echo "<span class='$action'>$sep$link</span>"; } echo '</div>'; } } function column_author( $comment ) { global $comment_status; $author_url = get_comment_author_url(); if ( 'http://' == $author_url ) $author_url = ''; $author_url_display = preg_replace( '|http://(www\.)?|i', '', $author_url ); if ( strlen( $author_url_display ) > 50 ) $author_url_display = substr( $author_url_display, 0, 49 ) . '...'; echo "<strong>"; comment_author(); echo '</strong><br />'; if ( !empty( $author_url ) ) echo "<a title='$author_url' href='$author_url'>$author_url_display</a><br />"; if ( $this->user_can ) { if ( !empty( $comment->comment_author_email ) ) { comment_author_email_link(); echo '<br />'; } echo '<a href="edit-comments.php?s='; comment_author_IP(); echo '&amp;mode=detail'; if ( 'spam' == $comment_status ) echo '&amp;comment_status=spam'; echo '">'; comment_author_IP(); echo '</a>'; } } function column_date( $comment ) { return get_comment_date( __( 'Y/m/d \a\t g:ia' ) ); } function column_response( $comment ) { $post = get_post(); if ( isset( $this->pending_count[$post->ID] ) ) { $pending_comments = $this->pending_count[$post->ID]; } else { $_pending_count_temp = get_pending_comments_num( array( $post->ID ) ); $pending_comments = $this->pending_count[$post->ID] = $_pending_count_temp[$post->ID]; } if ( current_user_can( 'edit_post', $post->ID ) ) { $post_link = "<a href='" . get_edit_post_link( $post->ID ) . "'>"; $post_link .= get_the_title( $post->ID ) . '</a>'; } else { $post_link = get_the_title( $post->ID ); } echo '<div class="response-links"><span class="post-com-count-wrapper">'; echo $post_link . '<br />'; $this->comments_bubble( $post->ID, $pending_comments ); echo '</span> '; $post_type_object = get_post_type_object( $post->post_type ); echo "<a href='" . get_permalink( $post->ID ) . "'>" . $post_type_object->labels->view_item . '</a>'; echo '</div>'; if ( 'attachment' == $post->post_type && ( $thumb = wp_get_attachment_image( $post->ID, array( 80, 60 ), true ) ) ) echo $thumb; } function column_default( $comment, $column_name ) { do_action( 'manage_comments_custom_column', $column_name, $comment->comment_ID ); } } /** * Post Comments List Table class. * * @package WordPress * @subpackage List_Table * @since 3.1.0 * @access private * * @see WP_Comments_Table */ class WP_Post_Comments_List_Table extends WP_Comments_List_Table { function get_column_info() { $this->_column_headers = array( array( 'author' => __( 'Author' ), 'comment' => _x( 'Comment', 'column name' ), ), array(), array(), ); return $this->_column_headers; } function get_table_classes() { $classes = parent::get_table_classes(); $classes[] = 'comments-box'; return $classes; } function display( $output_empty = false ) { extract( $this->_args ); wp_nonce_field( "fetch-list-" . get_class( $this ), '_ajax_fetch_list_nonce' ); ?> <table class="<?php echo implode( ' ', $this->get_table_classes() ); ?>" cellspacing="0" style="display:none;"> <tbody id="the-comment-list"<?php if ( $singular ) echo " data-wp-lists='list:$singular'"; ?>> <?php if ( ! $output_empty ) $this->display_rows_or_placeholder(); ?> </tbody> </table> <?php } function get_per_page( $comment_status = false ) { return 10; } }
zyblog
trunk/zyblog/wp-admin/includes/class-wp-comments-list-table.php
PHP
asf20
20,767
<?php /** * WordPress Export Administration API * * @package WordPress * @subpackage Administration */ /** * Version number for the export format. * * Bump this when something changes that might affect compatibility. * * @since 2.5.0 */ define( 'WXR_VERSION', '1.2' ); /** * Generates the WXR export file for download * * @since 2.1.0 * * @param array $args Filters defining what should be included in the export */ function export_wp( $args = array() ) { global $wpdb, $post; $defaults = array( 'content' => 'all', 'author' => false, 'category' => false, 'start_date' => false, 'end_date' => false, 'status' => false, ); $args = wp_parse_args( $args, $defaults ); do_action( 'export_wp' ); $sitename = sanitize_key( get_bloginfo( 'name' ) ); if ( ! empty($sitename) ) $sitename .= '.'; $filename = $sitename . 'wordpress.' . date( 'Y-m-d' ) . '.xml'; header( 'Content-Description: File Transfer' ); header( 'Content-Disposition: attachment; filename=' . $filename ); header( 'Content-Type: text/xml; charset=' . get_option( 'blog_charset' ), true ); if ( 'all' != $args['content'] && post_type_exists( $args['content'] ) ) { $ptype = get_post_type_object( $args['content'] ); if ( ! $ptype->can_export ) $args['content'] = 'post'; $where = $wpdb->prepare( "{$wpdb->posts}.post_type = %s", $args['content'] ); } else { $post_types = get_post_types( array( 'can_export' => true ) ); $esses = array_fill( 0, count($post_types), '%s' ); $where = $wpdb->prepare( "{$wpdb->posts}.post_type IN (" . implode( ',', $esses ) . ')', $post_types ); } if ( $args['status'] && ( 'post' == $args['content'] || 'page' == $args['content'] ) ) $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_status = %s", $args['status'] ); else $where .= " AND {$wpdb->posts}.post_status != 'auto-draft'"; $join = ''; if ( $args['category'] && 'post' == $args['content'] ) { if ( $term = term_exists( $args['category'], 'category' ) ) { $join = "INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id)"; $where .= $wpdb->prepare( " AND {$wpdb->term_relationships}.term_taxonomy_id = %d", $term['term_taxonomy_id'] ); } } if ( 'post' == $args['content'] || 'page' == $args['content'] ) { if ( $args['author'] ) $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_author = %d", $args['author'] ); if ( $args['start_date'] ) $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date >= %s", date( 'Y-m-d', strtotime($args['start_date']) ) ); if ( $args['end_date'] ) $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date < %s", date( 'Y-m-d', strtotime('+1 month', strtotime($args['end_date'])) ) ); } // grab a snapshot of post IDs, just in case it changes during the export $post_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} $join WHERE $where" ); // get the requested terms ready, empty unless posts filtered by category or all content $cats = $tags = $terms = array(); if ( isset( $term ) && $term ) { $cat = get_term( $term['term_id'], 'category' ); $cats = array( $cat->term_id => $cat ); unset( $term, $cat ); } else if ( 'all' == $args['content'] ) { $categories = (array) get_categories( array( 'get' => 'all' ) ); $tags = (array) get_tags( array( 'get' => 'all' ) ); $custom_taxonomies = get_taxonomies( array( '_builtin' => false ) ); $custom_terms = (array) get_terms( $custom_taxonomies, array( 'get' => 'all' ) ); // put categories in order with no child going before its parent while ( $cat = array_shift( $categories ) ) { if ( $cat->parent == 0 || isset( $cats[$cat->parent] ) ) $cats[$cat->term_id] = $cat; else $categories[] = $cat; } // put terms in order with no child going before its parent while ( $t = array_shift( $custom_terms ) ) { if ( $t->parent == 0 || isset( $terms[$t->parent] ) ) $terms[$t->term_id] = $t; else $custom_terms[] = $t; } unset( $categories, $custom_taxonomies, $custom_terms ); } /** * Wrap given string in XML CDATA tag. * * @since 2.1.0 * * @param string $str String to wrap in XML CDATA tag. * @return string */ function wxr_cdata( $str ) { if ( seems_utf8( $str ) == false ) $str = utf8_encode( $str ); // $str = ent2ncr(esc_html($str)); $str = '<![CDATA[' . str_replace( ']]>', ']]]]><![CDATA[>', $str ) . ']]>'; return $str; } /** * Return the URL of the site * * @since 2.5.0 * * @return string Site URL. */ function wxr_site_url() { // ms: the base url if ( is_multisite() ) return network_home_url(); // wp: the blog url else return get_bloginfo_rss( 'url' ); } /** * Output a cat_name XML tag from a given category object * * @since 2.1.0 * * @param object $category Category Object */ function wxr_cat_name( $category ) { if ( empty( $category->name ) ) return; echo '<wp:cat_name>' . wxr_cdata( $category->name ) . '</wp:cat_name>'; } /** * Output a category_description XML tag from a given category object * * @since 2.1.0 * * @param object $category Category Object */ function wxr_category_description( $category ) { if ( empty( $category->description ) ) return; echo '<wp:category_description>' . wxr_cdata( $category->description ) . '</wp:category_description>'; } /** * Output a tag_name XML tag from a given tag object * * @since 2.3.0 * * @param object $tag Tag Object */ function wxr_tag_name( $tag ) { if ( empty( $tag->name ) ) return; echo '<wp:tag_name>' . wxr_cdata( $tag->name ) . '</wp:tag_name>'; } /** * Output a tag_description XML tag from a given tag object * * @since 2.3.0 * * @param object $tag Tag Object */ function wxr_tag_description( $tag ) { if ( empty( $tag->description ) ) return; echo '<wp:tag_description>' . wxr_cdata( $tag->description ) . '</wp:tag_description>'; } /** * Output a term_name XML tag from a given term object * * @since 2.9.0 * * @param object $term Term Object */ function wxr_term_name( $term ) { if ( empty( $term->name ) ) return; echo '<wp:term_name>' . wxr_cdata( $term->name ) . '</wp:term_name>'; } /** * Output a term_description XML tag from a given term object * * @since 2.9.0 * * @param object $term Term Object */ function wxr_term_description( $term ) { if ( empty( $term->description ) ) return; echo '<wp:term_description>' . wxr_cdata( $term->description ) . '</wp:term_description>'; } /** * Output list of authors with posts * * @since 3.1.0 */ function wxr_authors_list() { global $wpdb; $authors = array(); $results = $wpdb->get_results( "SELECT DISTINCT post_author FROM $wpdb->posts WHERE post_status != 'auto-draft'" ); foreach ( (array) $results as $result ) $authors[] = get_userdata( $result->post_author ); $authors = array_filter( $authors ); foreach ( $authors as $author ) { echo "\t<wp:author>"; echo '<wp:author_id>' . $author->ID . '</wp:author_id>'; echo '<wp:author_login>' . $author->user_login . '</wp:author_login>'; echo '<wp:author_email>' . $author->user_email . '</wp:author_email>'; echo '<wp:author_display_name>' . wxr_cdata( $author->display_name ) . '</wp:author_display_name>'; echo '<wp:author_first_name>' . wxr_cdata( $author->user_firstname ) . '</wp:author_first_name>'; echo '<wp:author_last_name>' . wxr_cdata( $author->user_lastname ) . '</wp:author_last_name>'; echo "</wp:author>\n"; } } /** * Ouput all navigation menu terms * * @since 3.1.0 */ function wxr_nav_menu_terms() { $nav_menus = wp_get_nav_menus(); if ( empty( $nav_menus ) || ! is_array( $nav_menus ) ) return; foreach ( $nav_menus as $menu ) { echo "\t<wp:term><wp:term_id>{$menu->term_id}</wp:term_id><wp:term_taxonomy>nav_menu</wp:term_taxonomy><wp:term_slug>{$menu->slug}</wp:term_slug>"; wxr_term_name( $menu ); echo "</wp:term>\n"; } } /** * Output list of taxonomy terms, in XML tag format, associated with a post * * @since 2.3.0 */ function wxr_post_taxonomy() { $post = get_post(); $taxonomies = get_object_taxonomies( $post->post_type ); if ( empty( $taxonomies ) ) return; $terms = wp_get_object_terms( $post->ID, $taxonomies ); foreach ( (array) $terms as $term ) { echo "\t\t<category domain=\"{$term->taxonomy}\" nicename=\"{$term->slug}\">" . wxr_cdata( $term->name ) . "</category>\n"; } } function wxr_filter_postmeta( $return_me, $meta_key ) { if ( '_edit_lock' == $meta_key ) $return_me = true; return $return_me; } add_filter( 'wxr_export_skip_postmeta', 'wxr_filter_postmeta', 10, 2 ); echo '<?xml version="1.0" encoding="' . get_bloginfo('charset') . "\" ?>\n"; ?> <!-- This is a WordPress eXtended RSS file generated by WordPress as an export of your site. --> <!-- It contains information about your site's posts, pages, comments, categories, and other content. --> <!-- You may use this file to transfer that content from one site to another. --> <!-- This file is not intended to serve as a complete backup of your site. --> <!-- To import this information into a WordPress site follow these steps: --> <!-- 1. Log in to that site as an administrator. --> <!-- 2. Go to Tools: Import in the WordPress admin panel. --> <!-- 3. Install the "WordPress" importer from the list. --> <!-- 4. Activate & Run Importer. --> <!-- 5. Upload this file using the form provided on that page. --> <!-- 6. You will first be asked to map the authors in this export file to users --> <!-- on the site. For each author, you may choose to map to an --> <!-- existing user on the site or to create a new user. --> <!-- 7. WordPress will then import each of the posts, pages, comments, categories, etc. --> <!-- contained in this file into your site. --> <?php the_generator( 'export' ); ?> <rss version="2.0" xmlns:excerpt="http://wordpress.org/export/<?php echo WXR_VERSION; ?>/excerpt/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:wp="http://wordpress.org/export/<?php echo WXR_VERSION; ?>/" > <channel> <title><?php bloginfo_rss( 'name' ); ?></title> <link><?php bloginfo_rss( 'url' ); ?></link> <description><?php bloginfo_rss( 'description' ); ?></description> <pubDate><?php echo date( 'D, d M Y H:i:s +0000' ); ?></pubDate> <language><?php bloginfo_rss( 'language' ); ?></language> <wp:wxr_version><?php echo WXR_VERSION; ?></wp:wxr_version> <wp:base_site_url><?php echo wxr_site_url(); ?></wp:base_site_url> <wp:base_blog_url><?php bloginfo_rss( 'url' ); ?></wp:base_blog_url> <?php wxr_authors_list(); ?> <?php foreach ( $cats as $c ) : ?> <wp:category><wp:term_id><?php echo $c->term_id ?></wp:term_id><wp:category_nicename><?php echo $c->slug; ?></wp:category_nicename><wp:category_parent><?php echo $c->parent ? $cats[$c->parent]->slug : ''; ?></wp:category_parent><?php wxr_cat_name( $c ); ?><?php wxr_category_description( $c ); ?></wp:category> <?php endforeach; ?> <?php foreach ( $tags as $t ) : ?> <wp:tag><wp:term_id><?php echo $t->term_id ?></wp:term_id><wp:tag_slug><?php echo $t->slug; ?></wp:tag_slug><?php wxr_tag_name( $t ); ?><?php wxr_tag_description( $t ); ?></wp:tag> <?php endforeach; ?> <?php foreach ( $terms as $t ) : ?> <wp:term><wp:term_id><?php echo $t->term_id ?></wp:term_id><wp:term_taxonomy><?php echo $t->taxonomy; ?></wp:term_taxonomy><wp:term_slug><?php echo $t->slug; ?></wp:term_slug><wp:term_parent><?php echo $t->parent ? $terms[$t->parent]->slug : ''; ?></wp:term_parent><?php wxr_term_name( $t ); ?><?php wxr_term_description( $t ); ?></wp:term> <?php endforeach; ?> <?php if ( 'all' == $args['content'] ) wxr_nav_menu_terms(); ?> <?php do_action( 'rss2_head' ); ?> <?php if ( $post_ids ) { global $wp_query; $wp_query->in_the_loop = true; // Fake being in the loop. // fetch 20 posts at a time rather than loading the entire table into memory while ( $next_posts = array_splice( $post_ids, 0, 20 ) ) { $where = 'WHERE ID IN (' . join( ',', $next_posts ) . ')'; $posts = $wpdb->get_results( "SELECT * FROM {$wpdb->posts} $where" ); // Begin Loop foreach ( $posts as $post ) { setup_postdata( $post ); $is_sticky = is_sticky( $post->ID ) ? 1 : 0; ?> <item> <title><?php echo apply_filters( 'the_title_rss', $post->post_title ); ?></title> <link><?php the_permalink_rss() ?></link> <pubDate><?php echo mysql2date( 'D, d M Y H:i:s +0000', get_post_time( 'Y-m-d H:i:s', true ), false ); ?></pubDate> <dc:creator><?php echo get_the_author_meta( 'login' ); ?></dc:creator> <guid isPermaLink="false"><?php esc_url( the_guid() ); ?></guid> <description></description> <content:encoded><?php echo wxr_cdata( apply_filters( 'the_content_export', $post->post_content ) ); ?></content:encoded> <excerpt:encoded><?php echo wxr_cdata( apply_filters( 'the_excerpt_export', $post->post_excerpt ) ); ?></excerpt:encoded> <wp:post_id><?php echo $post->ID; ?></wp:post_id> <wp:post_date><?php echo $post->post_date; ?></wp:post_date> <wp:post_date_gmt><?php echo $post->post_date_gmt; ?></wp:post_date_gmt> <wp:comment_status><?php echo $post->comment_status; ?></wp:comment_status> <wp:ping_status><?php echo $post->ping_status; ?></wp:ping_status> <wp:post_name><?php echo $post->post_name; ?></wp:post_name> <wp:status><?php echo $post->post_status; ?></wp:status> <wp:post_parent><?php echo $post->post_parent; ?></wp:post_parent> <wp:menu_order><?php echo $post->menu_order; ?></wp:menu_order> <wp:post_type><?php echo $post->post_type; ?></wp:post_type> <wp:post_password><?php echo $post->post_password; ?></wp:post_password> <wp:is_sticky><?php echo $is_sticky; ?></wp:is_sticky> <?php if ( $post->post_type == 'attachment' ) : ?> <wp:attachment_url><?php echo wp_get_attachment_url( $post->ID ); ?></wp:attachment_url> <?php endif; ?> <?php wxr_post_taxonomy(); ?> <?php $postmeta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = %d", $post->ID ) ); foreach ( $postmeta as $meta ) : if ( apply_filters( 'wxr_export_skip_postmeta', false, $meta->meta_key, $meta ) ) continue; ?> <wp:postmeta> <wp:meta_key><?php echo $meta->meta_key; ?></wp:meta_key> <wp:meta_value><?php echo wxr_cdata( $meta->meta_value ); ?></wp:meta_value> </wp:postmeta> <?php endforeach; ?> <?php $comments = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved <> 'spam'", $post->ID ) ); foreach ( $comments as $c ) : ?> <wp:comment> <wp:comment_id><?php echo $c->comment_ID; ?></wp:comment_id> <wp:comment_author><?php echo wxr_cdata( $c->comment_author ); ?></wp:comment_author> <wp:comment_author_email><?php echo $c->comment_author_email; ?></wp:comment_author_email> <wp:comment_author_url><?php echo esc_url_raw( $c->comment_author_url ); ?></wp:comment_author_url> <wp:comment_author_IP><?php echo $c->comment_author_IP; ?></wp:comment_author_IP> <wp:comment_date><?php echo $c->comment_date; ?></wp:comment_date> <wp:comment_date_gmt><?php echo $c->comment_date_gmt; ?></wp:comment_date_gmt> <wp:comment_content><?php echo wxr_cdata( $c->comment_content ) ?></wp:comment_content> <wp:comment_approved><?php echo $c->comment_approved; ?></wp:comment_approved> <wp:comment_type><?php echo $c->comment_type; ?></wp:comment_type> <wp:comment_parent><?php echo $c->comment_parent; ?></wp:comment_parent> <wp:comment_user_id><?php echo $c->user_id; ?></wp:comment_user_id> <?php $c_meta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->commentmeta WHERE comment_id = %d", $c->comment_ID ) ); foreach ( $c_meta as $meta ) : ?> <wp:commentmeta> <wp:meta_key><?php echo $meta->meta_key; ?></wp:meta_key> <wp:meta_value><?php echo wxr_cdata( $meta->meta_value ); ?></wp:meta_value> </wp:commentmeta> <?php endforeach; ?> </wp:comment> <?php endforeach; ?> </item> <?php } } } ?> </channel> </rss> <?php }
zyblog
trunk/zyblog/wp-admin/includes/export.php
PHP
asf20
16,090
<?php /** * Base class for displaying a list of items in an ajaxified HTML table. * * @package WordPress * @subpackage List_Table * @since 3.1.0 */ /** * Base class for displaying a list of items in an ajaxified HTML table. * * @package WordPress * @subpackage List_Table * @since 3.1.0 * @access private */ class WP_List_Table { /** * The current list of items * * @since 3.1.0 * @var array * @access protected */ var $items; /** * Various information about the current table * * @since 3.1.0 * @var array * @access private */ var $_args; /** * Various information needed for displaying the pagination * * @since 3.1.0 * @var array * @access private */ var $_pagination_args = array(); /** * The current screen * * @since 3.1.0 * @var object * @access protected */ var $screen; /** * Cached bulk actions * * @since 3.1.0 * @var array * @access private */ var $_actions; /** * Cached pagination output * * @since 3.1.0 * @var string * @access private */ var $_pagination; /** * Constructor. The child class should call this constructor from it's own constructor * * @param array $args An associative array with information about the current table * @access protected */ function __construct( $args = array() ) { $args = wp_parse_args( $args, array( 'plural' => '', 'singular' => '', 'ajax' => false, 'screen' => null, ) ); $this->screen = convert_to_screen( $args['screen'] ); add_filter( "manage_{$this->screen->id}_columns", array( &$this, 'get_columns' ), 0 ); if ( !$args['plural'] ) $args['plural'] = $this->screen->base; $args['plural'] = sanitize_key( $args['plural'] ); $args['singular'] = sanitize_key( $args['singular'] ); $this->_args = $args; if ( $args['ajax'] ) { // wp_enqueue_script( 'list-table' ); add_action( 'admin_footer', array( &$this, '_js_vars' ) ); } } /** * Checks the current user's permissions * @uses wp_die() * * @since 3.1.0 * @access public * @abstract */ function ajax_user_can() { die( 'function WP_List_Table::ajax_user_can() must be over-ridden in a sub-class.' ); } /** * Prepares the list of items for displaying. * @uses WP_List_Table::set_pagination_args() * * @since 3.1.0 * @access public * @abstract */ function prepare_items() { die( 'function WP_List_Table::prepare_items() must be over-ridden in a sub-class.' ); } /** * An internal method that sets all the necessary pagination arguments * * @param array $args An associative array with information about the pagination * @access protected */ function set_pagination_args( $args ) { $args = wp_parse_args( $args, array( 'total_items' => 0, 'total_pages' => 0, 'per_page' => 0, ) ); if ( !$args['total_pages'] && $args['per_page'] > 0 ) $args['total_pages'] = ceil( $args['total_items'] / $args['per_page'] ); // redirect if page number is invalid and headers are not already sent if ( ! headers_sent() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) && $args['total_pages'] > 0 && $this->get_pagenum() > $args['total_pages'] ) { wp_redirect( add_query_arg( 'paged', $args['total_pages'] ) ); exit; } $this->_pagination_args = $args; } /** * Access the pagination args * * @since 3.1.0 * @access public * * @param string $key * @return array */ function get_pagination_arg( $key ) { if ( 'page' == $key ) return $this->get_pagenum(); if ( isset( $this->_pagination_args[$key] ) ) return $this->_pagination_args[$key]; } /** * Whether the table has items to display or not * * @since 3.1.0 * @access public * * @return bool */ function has_items() { return !empty( $this->items ); } /** * Message to be displayed when there are no items * * @since 3.1.0 * @access public */ function no_items() { _e( 'No items found.' ); } /** * Display the search box. * * @since 3.1.0 * @access public * * @param string $text The search button text * @param string $input_id The search input id */ function search_box( $text, $input_id ) { if ( empty( $_REQUEST['s'] ) && !$this->has_items() ) return; $input_id = $input_id . '-search-input'; if ( ! empty( $_REQUEST['orderby'] ) ) echo '<input type="hidden" name="orderby" value="' . esc_attr( $_REQUEST['orderby'] ) . '" />'; if ( ! empty( $_REQUEST['order'] ) ) echo '<input type="hidden" name="order" value="' . esc_attr( $_REQUEST['order'] ) . '" />'; if ( ! empty( $_REQUEST['post_mime_type'] ) ) echo '<input type="hidden" name="post_mime_type" value="' . esc_attr( $_REQUEST['post_mime_type'] ) . '" />'; if ( ! empty( $_REQUEST['detached'] ) ) echo '<input type="hidden" name="detached" value="' . esc_attr( $_REQUEST['detached'] ) . '" />'; ?> <p class="search-box"> <label class="screen-reader-text" for="<?php echo $input_id ?>"><?php echo $text; ?>:</label> <input type="search" id="<?php echo $input_id ?>" name="s" value="<?php _admin_search_query(); ?>" /> <?php submit_button( $text, 'button', false, false, array('id' => 'search-submit') ); ?> </p> <?php } /** * Get an associative array ( id => link ) with the list * of views available on this table. * * @since 3.1.0 * @access protected * * @return array */ function get_views() { return array(); } /** * Display the list of views available on this table. * * @since 3.1.0 * @access public */ function views() { $views = $this->get_views(); $views = apply_filters( 'views_' . $this->screen->id, $views ); if ( empty( $views ) ) return; echo "<ul class='subsubsub'>\n"; foreach ( $views as $class => $view ) { $views[ $class ] = "\t<li class='$class'>$view"; } echo implode( " |</li>\n", $views ) . "</li>\n"; echo "</ul>"; } /** * Get an associative array ( option_name => option_title ) with the list * of bulk actions available on this table. * * @since 3.1.0 * @access protected * * @return array */ function get_bulk_actions() { return array(); } /** * Display the bulk actions dropdown. * * @since 3.1.0 * @access public */ function bulk_actions() { if ( is_null( $this->_actions ) ) { $no_new_actions = $this->_actions = $this->get_bulk_actions(); // This filter can currently only be used to remove actions. $this->_actions = apply_filters( 'bulk_actions-' . $this->screen->id, $this->_actions ); $this->_actions = array_intersect_assoc( $this->_actions, $no_new_actions ); $two = ''; } else { $two = '2'; } if ( empty( $this->_actions ) ) return; echo "<select name='action$two'>\n"; echo "<option value='-1' selected='selected'>" . __( 'Bulk Actions' ) . "</option>\n"; foreach ( $this->_actions as $name => $title ) { $class = 'edit' == $name ? ' class="hide-if-no-js"' : ''; echo "\t<option value='$name'$class>$title</option>\n"; } echo "</select>\n"; submit_button( __( 'Apply' ), 'action', false, false, array( 'id' => "doaction$two" ) ); echo "\n"; } /** * Get the current action selected from the bulk actions dropdown. * * @since 3.1.0 * @access public * * @return string|bool The action name or False if no action was selected */ function current_action() { if ( isset( $_REQUEST['action'] ) && -1 != $_REQUEST['action'] ) return $_REQUEST['action']; if ( isset( $_REQUEST['action2'] ) && -1 != $_REQUEST['action2'] ) return $_REQUEST['action2']; return false; } /** * Generate row actions div * * @since 3.1.0 * @access protected * * @param array $actions The list of actions * @param bool $always_visible Whether the actions should be always visible * @return string */ function row_actions( $actions, $always_visible = false ) { $action_count = count( $actions ); $i = 0; if ( !$action_count ) return ''; $out = '<div class="' . ( $always_visible ? 'row-actions-visible' : 'row-actions' ) . '">'; foreach ( $actions as $action => $link ) { ++$i; ( $i == $action_count ) ? $sep = '' : $sep = ' | '; $out .= "<span class='$action'>$link$sep</span>"; } $out .= '</div>'; return $out; } /** * Display a monthly dropdown for filtering items * * @since 3.1.0 * @access protected */ function months_dropdown( $post_type ) { global $wpdb, $wp_locale; $months = $wpdb->get_results( $wpdb->prepare( " SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month FROM $wpdb->posts WHERE post_type = %s ORDER BY post_date DESC ", $post_type ) ); $month_count = count( $months ); if ( !$month_count || ( 1 == $month_count && 0 == $months[0]->month ) ) return; $m = isset( $_GET['m'] ) ? (int) $_GET['m'] : 0; ?> <select name='m'> <option<?php selected( $m, 0 ); ?> value='0'><?php _e( 'Show all dates' ); ?></option> <?php foreach ( $months as $arc_row ) { if ( 0 == $arc_row->year ) continue; $month = zeroise( $arc_row->month, 2 ); $year = $arc_row->year; printf( "<option %s value='%s'>%s</option>\n", selected( $m, $year . $month, false ), esc_attr( $arc_row->year . $month ), /* translators: 1: month name, 2: 4-digit year */ sprintf( __( '%1$s %2$d' ), $wp_locale->get_month( $month ), $year ) ); } ?> </select> <?php } /** * Display a view switcher * * @since 3.1.0 * @access protected */ function view_switcher( $current_mode ) { $modes = array( 'list' => __( 'List View' ), 'excerpt' => __( 'Excerpt View' ) ); ?> <input type="hidden" name="mode" value="<?php echo esc_attr( $current_mode ); ?>" /> <div class="view-switch"> <?php foreach ( $modes as $mode => $title ) { $class = ( $current_mode == $mode ) ? 'class="current"' : ''; echo "<a href='" . esc_url( add_query_arg( 'mode', $mode, $_SERVER['REQUEST_URI'] ) ) . "' $class><img id='view-switch-$mode' src='" . esc_url( includes_url( 'images/blank.gif' ) ) . "' width='20' height='20' title='$title' alt='$title' /></a>\n"; } ?> </div> <?php } /** * Display a comment count bubble * * @since 3.1.0 * @access protected * * @param int $post_id * @param int $pending_comments */ function comments_bubble( $post_id, $pending_comments ) { $pending_phrase = sprintf( __( '%s pending' ), number_format( $pending_comments ) ); if ( $pending_comments ) echo '<strong>'; echo "<a href='" . esc_url( add_query_arg( 'p', $post_id, admin_url( 'edit-comments.php' ) ) ) . "' title='" . esc_attr( $pending_phrase ) . "' class='post-com-count'><span class='comment-count'>" . number_format_i18n( get_comments_number() ) . "</span></a>"; if ( $pending_comments ) echo '</strong>'; } /** * Get the current page number * * @since 3.1.0 * @access protected * * @return int */ function get_pagenum() { $pagenum = isset( $_REQUEST['paged'] ) ? absint( $_REQUEST['paged'] ) : 0; if( isset( $this->_pagination_args['total_pages'] ) && $pagenum > $this->_pagination_args['total_pages'] ) $pagenum = $this->_pagination_args['total_pages']; return max( 1, $pagenum ); } /** * Get number of items to display on a single page * * @since 3.1.0 * @access protected * * @return int */ function get_items_per_page( $option, $default = 20 ) { $per_page = (int) get_user_option( $option ); if ( empty( $per_page ) || $per_page < 1 ) $per_page = $default; return (int) apply_filters( $option, $per_page ); } /** * Display the pagination. * * @since 3.1.0 * @access protected */ function pagination( $which ) { if ( empty( $this->_pagination_args ) ) return; extract( $this->_pagination_args, EXTR_SKIP ); $output = '<span class="displaying-num">' . sprintf( _n( '1 item', '%s items', $total_items ), number_format_i18n( $total_items ) ) . '</span>'; $current = $this->get_pagenum(); $current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); $current_url = remove_query_arg( array( 'hotkeys_highlight_last', 'hotkeys_highlight_first' ), $current_url ); $page_links = array(); $disable_first = $disable_last = ''; if ( $current == 1 ) $disable_first = ' disabled'; if ( $current == $total_pages ) $disable_last = ' disabled'; $page_links[] = sprintf( "<a class='%s' title='%s' href='%s'>%s</a>", 'first-page' . $disable_first, esc_attr__( 'Go to the first page' ), esc_url( remove_query_arg( 'paged', $current_url ) ), '&laquo;' ); $page_links[] = sprintf( "<a class='%s' title='%s' href='%s'>%s</a>", 'prev-page' . $disable_first, esc_attr__( 'Go to the previous page' ), esc_url( add_query_arg( 'paged', max( 1, $current-1 ), $current_url ) ), '&lsaquo;' ); if ( 'bottom' == $which ) $html_current_page = $current; else $html_current_page = sprintf( "<input class='current-page' title='%s' type='text' name='paged' value='%s' size='%d' />", esc_attr__( 'Current page' ), $current, strlen( $total_pages ) ); $html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) ); $page_links[] = '<span class="paging-input">' . sprintf( _x( '%1$s of %2$s', 'paging' ), $html_current_page, $html_total_pages ) . '</span>'; $page_links[] = sprintf( "<a class='%s' title='%s' href='%s'>%s</a>", 'next-page' . $disable_last, esc_attr__( 'Go to the next page' ), esc_url( add_query_arg( 'paged', min( $total_pages, $current+1 ), $current_url ) ), '&rsaquo;' ); $page_links[] = sprintf( "<a class='%s' title='%s' href='%s'>%s</a>", 'last-page' . $disable_last, esc_attr__( 'Go to the last page' ), esc_url( add_query_arg( 'paged', $total_pages, $current_url ) ), '&raquo;' ); $pagination_links_class = 'pagination-links'; if ( ! empty( $infinite_scroll ) ) $pagination_links_class = ' hide-if-js'; $output .= "\n<span class='$pagination_links_class'>" . join( "\n", $page_links ) . '</span>'; if ( $total_pages ) $page_class = $total_pages < 2 ? ' one-page' : ''; else $page_class = ' no-pages'; $this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>"; echo $this->_pagination; } /** * Get a list of columns. The format is: * 'internal-name' => 'Title' * * @since 3.1.0 * @access protected * @abstract * * @return array */ function get_columns() { die( 'function WP_List_Table::get_columns() must be over-ridden in a sub-class.' ); } /** * Get a list of sortable columns. The format is: * 'internal-name' => 'orderby' * or * 'internal-name' => array( 'orderby', true ) * * The second format will make the initial sorting order be descending * * @since 3.1.0 * @access protected * * @return array */ function get_sortable_columns() { return array(); } /** * Get a list of all, hidden and sortable columns, with filter applied * * @since 3.1.0 * @access protected * * @return array */ function get_column_info() { if ( isset( $this->_column_headers ) ) return $this->_column_headers; $columns = get_column_headers( $this->screen ); $hidden = get_hidden_columns( $this->screen ); $_sortable = apply_filters( "manage_{$this->screen->id}_sortable_columns", $this->get_sortable_columns() ); $sortable = array(); foreach ( $_sortable as $id => $data ) { if ( empty( $data ) ) continue; $data = (array) $data; if ( !isset( $data[1] ) ) $data[1] = false; $sortable[$id] = $data; } $this->_column_headers = array( $columns, $hidden, $sortable ); return $this->_column_headers; } /** * Return number of visible columns * * @since 3.1.0 * @access public * * @return int */ function get_column_count() { list ( $columns, $hidden ) = $this->get_column_info(); $hidden = array_intersect( array_keys( $columns ), array_filter( $hidden ) ); return count( $columns ) - count( $hidden ); } /** * Print column headers, accounting for hidden and sortable columns. * * @since 3.1.0 * @access protected * * @param bool $with_id Whether to set the id attribute or not */ function print_column_headers( $with_id = true ) { list( $columns, $hidden, $sortable ) = $this->get_column_info(); $current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); $current_url = remove_query_arg( 'paged', $current_url ); if ( isset( $_GET['orderby'] ) ) $current_orderby = $_GET['orderby']; else $current_orderby = ''; if ( isset( $_GET['order'] ) && 'desc' == $_GET['order'] ) $current_order = 'desc'; else $current_order = 'asc'; if ( ! empty( $columns['cb'] ) ) { static $cb_counter = 1; $columns['cb'] = '<label class="screen-reader-text" for="cb-select-all-' . $cb_counter . '">' . __( 'Select All' ) . '</label>' . '<input id="cb-select-all-' . $cb_counter . '" type="checkbox" />'; $cb_counter++; } foreach ( $columns as $column_key => $column_display_name ) { $class = array( 'manage-column', "column-$column_key" ); $style = ''; if ( in_array( $column_key, $hidden ) ) $style = 'display:none;'; $style = ' style="' . $style . '"'; if ( 'cb' == $column_key ) $class[] = 'check-column'; elseif ( in_array( $column_key, array( 'posts', 'comments', 'links' ) ) ) $class[] = 'num'; if ( isset( $sortable[$column_key] ) ) { list( $orderby, $desc_first ) = $sortable[$column_key]; if ( $current_orderby == $orderby ) { $order = 'asc' == $current_order ? 'desc' : 'asc'; $class[] = 'sorted'; $class[] = $current_order; } else { $order = $desc_first ? 'desc' : 'asc'; $class[] = 'sortable'; $class[] = $desc_first ? 'asc' : 'desc'; } $column_display_name = '<a href="' . esc_url( add_query_arg( compact( 'orderby', 'order' ), $current_url ) ) . '"><span>' . $column_display_name . '</span><span class="sorting-indicator"></span></a>'; } $id = $with_id ? "id='$column_key'" : ''; if ( !empty( $class ) ) $class = "class='" . join( ' ', $class ) . "'"; echo "<th scope='col' $id $class $style>$column_display_name</th>"; } } /** * Display the table * * @since 3.1.0 * @access public */ function display() { extract( $this->_args ); $this->display_tablenav( 'top' ); ?> <table class="wp-list-table <?php echo implode( ' ', $this->get_table_classes() ); ?>" cellspacing="0"> <thead> <tr> <?php $this->print_column_headers(); ?> </tr> </thead> <tfoot> <tr> <?php $this->print_column_headers( false ); ?> </tr> </tfoot> <tbody id="the-list"<?php if ( $singular ) echo " data-wp-lists='list:$singular'"; ?>> <?php $this->display_rows_or_placeholder(); ?> </tbody> </table> <?php $this->display_tablenav( 'bottom' ); } /** * Get a list of CSS classes for the <table> tag * * @since 3.1.0 * @access protected * * @return array */ function get_table_classes() { return array( 'widefat', 'fixed', $this->_args['plural'] ); } /** * Generate the table navigation above or below the table * * @since 3.1.0 * @access protected */ function display_tablenav( $which ) { if ( 'top' == $which ) wp_nonce_field( 'bulk-' . $this->_args['plural'] ); ?> <div class="tablenav <?php echo esc_attr( $which ); ?>"> <div class="alignleft actions"> <?php $this->bulk_actions(); ?> </div> <?php $this->extra_tablenav( $which ); $this->pagination( $which ); ?> <br class="clear" /> </div> <?php } /** * Extra controls to be displayed between bulk actions and pagination * * @since 3.1.0 * @access protected */ function extra_tablenav( $which ) {} /** * Generate the <tbody> part of the table * * @since 3.1.0 * @access protected */ function display_rows_or_placeholder() { if ( $this->has_items() ) { $this->display_rows(); } else { list( $columns, $hidden ) = $this->get_column_info(); echo '<tr class="no-items"><td class="colspanchange" colspan="' . $this->get_column_count() . '">'; $this->no_items(); echo '</td></tr>'; } } /** * Generate the table rows * * @since 3.1.0 * @access protected */ function display_rows() { foreach ( $this->items as $item ) $this->single_row( $item ); } /** * Generates content for a single row of the table * * @since 3.1.0 * @access protected * * @param object $item The current item */ function single_row( $item ) { static $row_class = ''; $row_class = ( $row_class == '' ? ' class="alternate"' : '' ); echo '<tr' . $row_class . '>'; echo $this->single_row_columns( $item ); echo '</tr>'; } /** * Generates the columns for a single row of the table * * @since 3.1.0 * @access protected * * @param object $item The current item */ function single_row_columns( $item ) { list( $columns, $hidden ) = $this->get_column_info(); foreach ( $columns as $column_name => $column_display_name ) { $class = "class='$column_name column-$column_name'"; $style = ''; if ( in_array( $column_name, $hidden ) ) $style = ' style="display:none;"'; $attributes = "$class$style"; if ( 'cb' == $column_name ) { echo '<th scope="row" class="check-column">'; echo $this->column_cb( $item ); echo '</th>'; } elseif ( method_exists( $this, 'column_' . $column_name ) ) { echo "<td $attributes>"; echo call_user_func( array( &$this, 'column_' . $column_name ), $item ); echo "</td>"; } else { echo "<td $attributes>"; echo $this->column_default( $item, $column_name ); echo "</td>"; } } } /** * Handle an incoming ajax request (called from admin-ajax.php) * * @since 3.1.0 * @access public */ function ajax_response() { $this->prepare_items(); extract( $this->_args ); extract( $this->_pagination_args, EXTR_SKIP ); ob_start(); if ( ! empty( $_REQUEST['no_placeholder'] ) ) $this->display_rows(); else $this->display_rows_or_placeholder(); $rows = ob_get_clean(); $response = array( 'rows' => $rows ); if ( isset( $total_items ) ) $response['total_items_i18n'] = sprintf( _n( '1 item', '%s items', $total_items ), number_format_i18n( $total_items ) ); if ( isset( $total_pages ) ) { $response['total_pages'] = $total_pages; $response['total_pages_i18n'] = number_format_i18n( $total_pages ); } die( json_encode( $response ) ); } /** * Send required variables to JavaScript land * * @access private */ function _js_vars() { $args = array( 'class' => get_class( $this ), 'screen' => array( 'id' => $this->screen->id, 'base' => $this->screen->base, ) ); printf( "<script type='text/javascript'>list_args = %s;</script>\n", json_encode( $args ) ); } }
zyblog
trunk/zyblog/wp-admin/includes/class-wp-list-table.php
PHP
asf20
22,791
<?php /** * WordPress Core Ajax Handlers. * * @package WordPress * @subpackage Administration */ /* * No-privilege Ajax handlers. */ function wp_ajax_nopriv_autosave() { $id = isset( $_POST['post_ID'] ) ? (int) $_POST['post_ID'] : 0; if ( ! $id ) wp_die( -1 ); $message = sprintf( __('<strong>ALERT: You are logged out!</strong> Could not save draft. <a href="%s" target="_blank">Please log in again.</a>'), wp_login_url() ); $x = new WP_Ajax_Response( array( 'what' => 'autosave', 'id' => $id, 'data' => $message ) ); $x->send(); } /* * GET-based Ajax handlers. */ function wp_ajax_fetch_list() { global $wp_list_table; $list_class = $_GET['list_args']['class']; check_ajax_referer( "fetch-list-$list_class", '_ajax_fetch_list_nonce' ); $wp_list_table = _get_list_table( $list_class, array( 'screen' => $_GET['list_args']['screen']['id'] ) ); if ( ! $wp_list_table ) wp_die( 0 ); if ( ! $wp_list_table->ajax_user_can() ) wp_die( -1 ); $wp_list_table->ajax_response(); wp_die( 0 ); } function wp_ajax_ajax_tag_search() { global $wpdb; if ( isset( $_GET['tax'] ) ) { $taxonomy = sanitize_key( $_GET['tax'] ); $tax = get_taxonomy( $taxonomy ); if ( ! $tax ) wp_die( 0 ); if ( ! current_user_can( $tax->cap->assign_terms ) ) wp_die( -1 ); } else { wp_die( 0 ); } $s = stripslashes( $_GET['q'] ); $comma = _x( ',', 'tag delimiter' ); if ( ',' !== $comma ) $s = str_replace( $comma, ',', $s ); if ( false !== strpos( $s, ',' ) ) { $s = explode( ',', $s ); $s = $s[count( $s ) - 1]; } $s = trim( $s ); if ( strlen( $s ) < 2 ) wp_die(); // require 2 chars for matching $results = $wpdb->get_col( $wpdb->prepare( "SELECT t.name FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.name LIKE (%s)", $taxonomy, '%' . like_escape( $s ) . '%' ) ); echo join( $results, "\n" ); wp_die(); } function wp_ajax_wp_compression_test() { if ( !current_user_can( 'manage_options' ) ) wp_die( -1 ); if ( ini_get('zlib.output_compression') || 'ob_gzhandler' == ini_get('output_handler') ) { update_site_option('can_compress_scripts', 0); wp_die( 0 ); } if ( isset($_GET['test']) ) { header( 'Expires: Wed, 11 Jan 1984 05:00:00 GMT' ); header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' ); header( 'Cache-Control: no-cache, must-revalidate, max-age=0' ); header( 'Pragma: no-cache' ); header('Content-Type: application/x-javascript; charset=UTF-8'); $force_gzip = ( defined('ENFORCE_GZIP') && ENFORCE_GZIP ); $test_str = '"wpCompressionTest Lorem ipsum dolor sit amet consectetuer mollis sapien urna ut a. Eu nonummy condimentum fringilla tempor pretium platea vel nibh netus Maecenas. Hac molestie amet justo quis pellentesque est ultrices interdum nibh Morbi. Cras mattis pretium Phasellus ante ipsum ipsum ut sociis Suspendisse Lorem. Ante et non molestie. Porta urna Vestibulum egestas id congue nibh eu risus gravida sit. Ac augue auctor Ut et non a elit massa id sodales. Elit eu Nulla at nibh adipiscing mattis lacus mauris at tempus. Netus nibh quis suscipit nec feugiat eget sed lorem et urna. Pellentesque lacus at ut massa consectetuer ligula ut auctor semper Pellentesque. Ut metus massa nibh quam Curabitur molestie nec mauris congue. Volutpat molestie elit justo facilisis neque ac risus Ut nascetur tristique. Vitae sit lorem tellus et quis Phasellus lacus tincidunt nunc Fusce. Pharetra wisi Suspendisse mus sagittis libero lacinia Integer consequat ac Phasellus. Et urna ac cursus tortor aliquam Aliquam amet tellus volutpat Vestibulum. Justo interdum condimentum In augue congue tellus sollicitudin Quisque quis nibh."'; if ( 1 == $_GET['test'] ) { echo $test_str; wp_die(); } elseif ( 2 == $_GET['test'] ) { if ( !isset($_SERVER['HTTP_ACCEPT_ENCODING']) ) wp_die( -1 ); if ( false !== stripos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate') && function_exists('gzdeflate') && ! $force_gzip ) { header('Content-Encoding: deflate'); $out = gzdeflate( $test_str, 1 ); } elseif ( false !== stripos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') && function_exists('gzencode') ) { header('Content-Encoding: gzip'); $out = gzencode( $test_str, 1 ); } else { wp_die( -1 ); } echo $out; wp_die(); } elseif ( 'no' == $_GET['test'] ) { update_site_option('can_compress_scripts', 0); } elseif ( 'yes' == $_GET['test'] ) { update_site_option('can_compress_scripts', 1); } } wp_die( 0 ); } function wp_ajax_imgedit_preview() { $post_id = intval($_GET['postid']); if ( empty($post_id) || !current_user_can('edit_post', $post_id) ) wp_die( -1 ); check_ajax_referer( "image_editor-$post_id" ); include_once( ABSPATH . 'wp-admin/includes/image-edit.php' ); if ( ! stream_preview_image($post_id) ) wp_die( -1 ); wp_die(); } function wp_ajax_oembed_cache() { global $wp_embed; $return = ( $wp_embed->cache_oembed( $_GET['post'] ) ) ? '1' : '0'; wp_die( $return ); } function wp_ajax_autocomplete_user() { if ( ! is_multisite() || ! current_user_can( 'promote_users' ) || wp_is_large_network( 'users' ) ) wp_die( -1 ); if ( ! is_super_admin() && ! apply_filters( 'autocomplete_users_for_site_admins', false ) ) wp_die( -1 ); $return = array(); // Check the type of request if ( isset( $_REQUEST['autocomplete_type'] ) ) $type = $_REQUEST['autocomplete_type']; else $type = 'add'; // Exclude current users of this blog if ( isset( $_REQUEST['site_id'] ) ) $id = absint( $_REQUEST['site_id'] ); else $id = get_current_blog_id(); $include_blog_users = ( $type == 'search' ? get_users( array( 'blog_id' => $id, 'fields' => 'ID' ) ) : array() ); $exclude_blog_users = ( $type == 'add' ? get_users( array( 'blog_id' => $id, 'fields' => 'ID' ) ) : array() ); $users = get_users( array( 'blog_id' => false, 'search' => '*' . $_REQUEST['term'] . '*', 'include' => $include_blog_users, 'exclude' => $exclude_blog_users, 'search_columns' => array( 'user_login', 'user_nicename', 'user_email' ), ) ); foreach ( $users as $user ) { $return[] = array( /* translators: 1: user_login, 2: user_email */ 'label' => sprintf( __( '%1$s (%2$s)' ), $user->user_login, $user->user_email ), 'value' => $user->user_login, ); } wp_die( json_encode( $return ) ); } function wp_ajax_dashboard_widgets() { require_once ABSPATH . 'wp-admin/includes/dashboard.php'; switch ( $_GET['widget'] ) { case 'dashboard_incoming_links' : wp_dashboard_incoming_links(); break; case 'dashboard_primary' : wp_dashboard_primary(); break; case 'dashboard_secondary' : wp_dashboard_secondary(); break; case 'dashboard_plugins' : wp_dashboard_plugins(); break; } wp_die(); } function wp_ajax_logged_in() { wp_die( 1 ); } /* * Ajax helper. */ /** * Sends back current comment total and new page links if they need to be updated. * * Contrary to normal success AJAX response ("1"), die with time() on success. * * @since 2.7 * * @param int $comment_id * @return die */ function _wp_ajax_delete_comment_response( $comment_id, $delta = -1 ) { $total = (int) @$_POST['_total']; $per_page = (int) @$_POST['_per_page']; $page = (int) @$_POST['_page']; $url = esc_url_raw( @$_POST['_url'] ); // JS didn't send us everything we need to know. Just die with success message if ( !$total || !$per_page || !$page || !$url ) wp_die( time() ); $total += $delta; if ( $total < 0 ) $total = 0; // Only do the expensive stuff on a page-break, and about 1 other time per page if ( 0 == $total % $per_page || 1 == mt_rand( 1, $per_page ) ) { $post_id = 0; $status = 'total_comments'; // What type of comment count are we looking for? $parsed = parse_url( $url ); if ( isset( $parsed['query'] ) ) { parse_str( $parsed['query'], $query_vars ); if ( !empty( $query_vars['comment_status'] ) ) $status = $query_vars['comment_status']; if ( !empty( $query_vars['p'] ) ) $post_id = (int) $query_vars['p']; } $comment_count = wp_count_comments($post_id); if ( isset( $comment_count->$status ) ) // We're looking for a known type of comment count $total = $comment_count->$status; // else use the decremented value from above } $time = time(); // The time since the last comment count $x = new WP_Ajax_Response( array( 'what' => 'comment', 'id' => $comment_id, // here for completeness - not used 'supplemental' => array( 'total_items_i18n' => sprintf( _n( '1 item', '%s items', $total ), number_format_i18n( $total ) ), 'total_pages' => ceil( $total / $per_page ), 'total_pages_i18n' => number_format_i18n( ceil( $total / $per_page ) ), 'total' => $total, 'time' => $time ) ) ); $x->send(); } /* * POST-based Ajax handlers. */ function _wp_ajax_add_hierarchical_term() { $action = $_POST['action']; $taxonomy = get_taxonomy(substr($action, 4)); check_ajax_referer( $action, '_ajax_nonce-add-' . $taxonomy->name ); if ( !current_user_can( $taxonomy->cap->edit_terms ) ) wp_die( -1 ); $names = explode(',', $_POST['new'.$taxonomy->name]); $parent = isset($_POST['new'.$taxonomy->name.'_parent']) ? (int) $_POST['new'.$taxonomy->name.'_parent'] : 0; if ( 0 > $parent ) $parent = 0; if ( $taxonomy->name == 'category' ) $post_category = isset($_POST['post_category']) ? (array) $_POST['post_category'] : array(); else $post_category = ( isset($_POST['tax_input']) && isset($_POST['tax_input'][$taxonomy->name]) ) ? (array) $_POST['tax_input'][$taxonomy->name] : array(); $checked_categories = array_map( 'absint', (array) $post_category ); $popular_ids = wp_popular_terms_checklist($taxonomy->name, 0, 10, false); foreach ( $names as $cat_name ) { $cat_name = trim($cat_name); $category_nicename = sanitize_title($cat_name); if ( '' === $category_nicename ) continue; if ( !$cat_id = term_exists( $cat_name, $taxonomy->name, $parent ) ) $cat_id = wp_insert_term( $cat_name, $taxonomy->name, array( 'parent' => $parent ) ); if ( is_wp_error( $cat_id ) ) continue; else if ( is_array( $cat_id ) ) $cat_id = $cat_id['term_id']; $checked_categories[] = $cat_id; if ( $parent ) // Do these all at once in a second continue; ob_start(); wp_terms_checklist( 0, array( 'taxonomy' => $taxonomy->name, 'descendants_and_self' => $cat_id, 'selected_cats' => $checked_categories, 'popular_cats' => $popular_ids )); $data = ob_get_contents(); ob_end_clean(); $add = array( 'what' => $taxonomy->name, 'id' => $cat_id, 'data' => str_replace( array("\n", "\t"), '', $data), 'position' => -1 ); } if ( $parent ) { // Foncy - replace the parent and all its children $parent = get_term( $parent, $taxonomy->name ); $term_id = $parent->term_id; while ( $parent->parent ) { // get the top parent $parent = get_term( $parent->parent, $taxonomy->name ); if ( is_wp_error( $parent ) ) break; $term_id = $parent->term_id; } ob_start(); wp_terms_checklist( 0, array('taxonomy' => $taxonomy->name, 'descendants_and_self' => $term_id, 'selected_cats' => $checked_categories, 'popular_cats' => $popular_ids)); $data = ob_get_contents(); ob_end_clean(); $add = array( 'what' => $taxonomy->name, 'id' => $term_id, 'data' => str_replace( array("\n", "\t"), '', $data), 'position' => -1 ); } ob_start(); wp_dropdown_categories( array( 'taxonomy' => $taxonomy->name, 'hide_empty' => 0, 'name' => 'new'.$taxonomy->name.'_parent', 'orderby' => 'name', 'hierarchical' => 1, 'show_option_none' => '&mdash; '.$taxonomy->labels->parent_item.' &mdash;' ) ); $sup = ob_get_contents(); ob_end_clean(); $add['supplemental'] = array( 'newcat_parent' => $sup ); $x = new WP_Ajax_Response( $add ); $x->send(); } function wp_ajax_delete_comment() { $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; if ( !$comment = get_comment( $id ) ) wp_die( time() ); if ( ! current_user_can( 'edit_comment', $comment->comment_ID ) ) wp_die( -1 ); check_ajax_referer( "delete-comment_$id" ); $status = wp_get_comment_status( $comment->comment_ID ); $delta = -1; if ( isset($_POST['trash']) && 1 == $_POST['trash'] ) { if ( 'trash' == $status ) wp_die( time() ); $r = wp_trash_comment( $comment->comment_ID ); } elseif ( isset($_POST['untrash']) && 1 == $_POST['untrash'] ) { if ( 'trash' != $status ) wp_die( time() ); $r = wp_untrash_comment( $comment->comment_ID ); if ( ! isset( $_POST['comment_status'] ) || $_POST['comment_status'] != 'trash' ) // undo trash, not in trash $delta = 1; } elseif ( isset($_POST['spam']) && 1 == $_POST['spam'] ) { if ( 'spam' == $status ) wp_die( time() ); $r = wp_spam_comment( $comment->comment_ID ); } elseif ( isset($_POST['unspam']) && 1 == $_POST['unspam'] ) { if ( 'spam' != $status ) wp_die( time() ); $r = wp_unspam_comment( $comment->comment_ID ); if ( ! isset( $_POST['comment_status'] ) || $_POST['comment_status'] != 'spam' ) // undo spam, not in spam $delta = 1; } elseif ( isset($_POST['delete']) && 1 == $_POST['delete'] ) { $r = wp_delete_comment( $comment->comment_ID ); } else { wp_die( -1 ); } if ( $r ) // Decide if we need to send back '1' or a more complicated response including page links and comment counts _wp_ajax_delete_comment_response( $comment->comment_ID, $delta ); wp_die( 0 ); } function wp_ajax_delete_tag() { $tag_id = (int) $_POST['tag_ID']; check_ajax_referer( "delete-tag_$tag_id" ); $taxonomy = !empty($_POST['taxonomy']) ? $_POST['taxonomy'] : 'post_tag'; $tax = get_taxonomy($taxonomy); if ( !current_user_can( $tax->cap->delete_terms ) ) wp_die( -1 ); $tag = get_term( $tag_id, $taxonomy ); if ( !$tag || is_wp_error( $tag ) ) wp_die( 1 ); if ( wp_delete_term($tag_id, $taxonomy)) wp_die( 1 ); else wp_die( 0 ); } function wp_ajax_delete_link() { $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; check_ajax_referer( "delete-bookmark_$id" ); if ( !current_user_can( 'manage_links' ) ) wp_die( -1 ); $link = get_bookmark( $id ); if ( !$link || is_wp_error( $link ) ) wp_die( 1 ); if ( wp_delete_link( $id ) ) wp_die( 1 ); else wp_die( 0 ); } function wp_ajax_delete_meta() { $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; check_ajax_referer( "delete-meta_$id" ); if ( !$meta = get_metadata_by_mid( 'post', $id ) ) wp_die( 1 ); if ( is_protected_meta( $meta->meta_key, 'post' ) || ! current_user_can( 'delete_post_meta', $meta->post_id, $meta->meta_key ) ) wp_die( -1 ); if ( delete_meta( $meta->meta_id ) ) wp_die( 1 ); wp_die( 0 ); } function wp_ajax_delete_post( $action ) { if ( empty( $action ) ) $action = 'delete-post'; $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; check_ajax_referer( "{$action}_$id" ); if ( !current_user_can( 'delete_post', $id ) ) wp_die( -1 ); if ( !get_post( $id ) ) wp_die( 1 ); if ( wp_delete_post( $id ) ) wp_die( 1 ); else wp_die( 0 ); } function wp_ajax_trash_post( $action ) { if ( empty( $action ) ) $action = 'trash-post'; $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; check_ajax_referer( "{$action}_$id" ); if ( !current_user_can( 'delete_post', $id ) ) wp_die( -1 ); if ( !get_post( $id ) ) wp_die( 1 ); if ( 'trash-post' == $action ) $done = wp_trash_post( $id ); else $done = wp_untrash_post( $id ); if ( $done ) wp_die( 1 ); wp_die( 0 ); } function wp_ajax_untrash_post( $action ) { if ( empty( $action ) ) $action = 'untrash-post'; wp_ajax_trash_post( $action ); } function wp_ajax_delete_page( $action ) { if ( empty( $action ) ) $action = 'delete-page'; $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; check_ajax_referer( "{$action}_$id" ); if ( !current_user_can( 'delete_page', $id ) ) wp_die( -1 ); if ( ! get_post( $id ) ) wp_die( 1 ); if ( wp_delete_post( $id ) ) wp_die( 1 ); else wp_die( 0 ); } function wp_ajax_dim_comment() { $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; if ( !$comment = get_comment( $id ) ) { $x = new WP_Ajax_Response( array( 'what' => 'comment', 'id' => new WP_Error('invalid_comment', sprintf(__('Comment %d does not exist'), $id)) ) ); $x->send(); } if ( ! current_user_can( 'edit_comment', $comment->comment_ID ) && ! current_user_can( 'moderate_comments' ) ) wp_die( -1 ); $current = wp_get_comment_status( $comment->comment_ID ); if ( $_POST['new'] == $current ) wp_die( time() ); check_ajax_referer( "approve-comment_$id" ); if ( in_array( $current, array( 'unapproved', 'spam' ) ) ) $result = wp_set_comment_status( $comment->comment_ID, 'approve', true ); else $result = wp_set_comment_status( $comment->comment_ID, 'hold', true ); if ( is_wp_error($result) ) { $x = new WP_Ajax_Response( array( 'what' => 'comment', 'id' => $result ) ); $x->send(); } // Decide if we need to send back '1' or a more complicated response including page links and comment counts _wp_ajax_delete_comment_response( $comment->comment_ID ); wp_die( 0 ); } function wp_ajax_add_link_category( $action ) { if ( empty( $action ) ) $action = 'add-link-category'; check_ajax_referer( $action ); if ( !current_user_can( 'manage_categories' ) ) wp_die( -1 ); $names = explode(',', $_POST['newcat']); $x = new WP_Ajax_Response(); foreach ( $names as $cat_name ) { $cat_name = trim($cat_name); $slug = sanitize_title($cat_name); if ( '' === $slug ) continue; if ( !$cat_id = term_exists( $cat_name, 'link_category' ) ) $cat_id = wp_insert_term( $cat_name, 'link_category' ); if ( is_wp_error( $cat_id ) ) continue; else if ( is_array( $cat_id ) ) $cat_id = $cat_id['term_id']; $cat_name = esc_html(stripslashes($cat_name)); $x->add( array( 'what' => 'link-category', 'id' => $cat_id, 'data' => "<li id='link-category-$cat_id'><label for='in-link-category-$cat_id' class='selectit'><input value='" . esc_attr($cat_id) . "' type='checkbox' checked='checked' name='link_category[]' id='in-link-category-$cat_id'/> $cat_name</label></li>", 'position' => -1 ) ); } $x->send(); } function wp_ajax_add_tag() { global $wp_list_table; check_ajax_referer( 'add-tag', '_wpnonce_add-tag' ); $post_type = !empty($_POST['post_type']) ? $_POST['post_type'] : 'post'; $taxonomy = !empty($_POST['taxonomy']) ? $_POST['taxonomy'] : 'post_tag'; $tax = get_taxonomy($taxonomy); if ( !current_user_can( $tax->cap->edit_terms ) ) wp_die( -1 ); $x = new WP_Ajax_Response(); $tag = wp_insert_term($_POST['tag-name'], $taxonomy, $_POST ); if ( !$tag || is_wp_error($tag) || (!$tag = get_term( $tag['term_id'], $taxonomy )) ) { $message = __('An error has occurred. Please reload the page and try again.'); if ( is_wp_error($tag) && $tag->get_error_message() ) $message = $tag->get_error_message(); $x->add( array( 'what' => 'taxonomy', 'data' => new WP_Error('error', $message ) ) ); $x->send(); } $wp_list_table = _get_list_table( 'WP_Terms_List_Table', array( 'screen' => $_POST['screen'] ) ); $level = 0; if ( is_taxonomy_hierarchical($taxonomy) ) { $level = count( get_ancestors( $tag->term_id, $taxonomy ) ); ob_start(); $wp_list_table->single_row( $tag, $level ); $noparents = ob_get_clean(); } ob_start(); $wp_list_table->single_row( $tag ); $parents = ob_get_clean(); $x->add( array( 'what' => 'taxonomy', 'supplemental' => compact('parents', 'noparents') ) ); $x->add( array( 'what' => 'term', 'position' => $level, 'supplemental' => (array) $tag ) ); $x->send(); } function wp_ajax_get_tagcloud() { if ( isset( $_POST['tax'] ) ) { $taxonomy = sanitize_key( $_POST['tax'] ); $tax = get_taxonomy( $taxonomy ); if ( ! $tax ) wp_die( 0 ); if ( ! current_user_can( $tax->cap->assign_terms ) ) wp_die( -1 ); } else { wp_die( 0 ); } $tags = get_terms( $taxonomy, array( 'number' => 45, 'orderby' => 'count', 'order' => 'DESC' ) ); if ( empty( $tags ) ) wp_die( isset( $tax->no_tagcloud ) ? $tax->no_tagcloud : __('No tags found!') ); if ( is_wp_error( $tags ) ) wp_die( $tags->get_error_message() ); foreach ( $tags as $key => $tag ) { $tags[ $key ]->link = '#'; $tags[ $key ]->id = $tag->term_id; } // We need raw tag names here, so don't filter the output $return = wp_generate_tag_cloud( $tags, array('filter' => 0) ); if ( empty($return) ) wp_die( 0 ); echo $return; wp_die(); } function wp_ajax_get_comments( $action ) { global $wp_list_table, $post_id; if ( empty( $action ) ) $action = 'get-comments'; check_ajax_referer( $action ); $wp_list_table = _get_list_table( 'WP_Post_Comments_List_Table', array( 'screen' => 'edit-comments' ) ); if ( !current_user_can( 'edit_post', $post_id ) ) wp_die( -1 ); $wp_list_table->prepare_items(); if ( !$wp_list_table->has_items() ) wp_die( 1 ); $x = new WP_Ajax_Response(); ob_start(); foreach ( $wp_list_table->items as $comment ) { if ( ! current_user_can( 'edit_comment', $comment->comment_ID ) ) continue; get_comment( $comment ); $wp_list_table->single_row( $comment ); } $comment_list_item = ob_get_contents(); ob_end_clean(); $x->add( array( 'what' => 'comments', 'data' => $comment_list_item ) ); $x->send(); } function wp_ajax_replyto_comment( $action ) { global $wp_list_table, $wpdb; if ( empty( $action ) ) $action = 'replyto-comment'; check_ajax_referer( $action, '_ajax_nonce-replyto-comment' ); $comment_post_ID = (int) $_POST['comment_post_ID']; if ( !current_user_can( 'edit_post', $comment_post_ID ) ) wp_die( -1 ); $status = $wpdb->get_var( $wpdb->prepare("SELECT post_status FROM $wpdb->posts WHERE ID = %d", $comment_post_ID) ); if ( empty($status) ) wp_die( 1 ); elseif ( in_array($status, array('draft', 'pending', 'trash') ) ) wp_die( __('ERROR: you are replying to a comment on a draft post.') ); $user = wp_get_current_user(); if ( $user->exists() ) { $user_ID = $user->ID; $comment_author = $wpdb->escape($user->display_name); $comment_author_email = $wpdb->escape($user->user_email); $comment_author_url = $wpdb->escape($user->user_url); $comment_content = trim($_POST['content']); if ( current_user_can( 'unfiltered_html' ) ) { if ( wp_create_nonce( 'unfiltered-html-comment' ) != $_POST['_wp_unfiltered_html_comment'] ) { kses_remove_filters(); // start with a clean slate kses_init_filters(); // set up the filters } } } else { wp_die( __( 'Sorry, you must be logged in to reply to a comment.' ) ); } if ( '' == $comment_content ) wp_die( __( 'ERROR: please type a comment.' ) ); $comment_parent = absint($_POST['comment_ID']); $comment_auto_approved = false; $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID'); // automatically approve parent comment if ( !empty($_POST['approve_parent']) ) { $parent = get_comment( $comment_parent ); if ( $parent && $parent->comment_approved === '0' && $parent->comment_post_ID == $comment_post_ID ) { if ( wp_set_comment_status( $parent->comment_ID, 'approve' ) ) $comment_auto_approved = true; } } $comment_id = wp_new_comment( $commentdata ); $comment = get_comment($comment_id); if ( ! $comment ) wp_die( 1 ); $position = ( isset($_POST['position']) && (int) $_POST['position'] ) ? (int) $_POST['position'] : '-1'; ob_start(); if ( 'dashboard' == $_REQUEST['mode'] ) { require_once( ABSPATH . 'wp-admin/includes/dashboard.php' ); _wp_dashboard_recent_comments_row( $comment ); } else { if ( 'single' == $_REQUEST['mode'] ) { $wp_list_table = _get_list_table('WP_Post_Comments_List_Table', array( 'screen' => 'edit-comments' ) ); } else { $wp_list_table = _get_list_table('WP_Comments_List_Table', array( 'screen' => 'edit-comments' ) ); } $wp_list_table->single_row( $comment ); } $comment_list_item = ob_get_contents(); ob_end_clean(); $response = array( 'what' => 'comment', 'id' => $comment->comment_ID, 'data' => $comment_list_item, 'position' => $position ); if ( $comment_auto_approved ) $response['supplemental'] = array( 'parent_approved' => $parent->comment_ID ); $x = new WP_Ajax_Response(); $x->add( $response ); $x->send(); } function wp_ajax_edit_comment() { global $wp_list_table; check_ajax_referer( 'replyto-comment', '_ajax_nonce-replyto-comment' ); $comment_id = (int) $_POST['comment_ID']; if ( ! current_user_can( 'edit_comment', $comment_id ) ) wp_die( -1 ); if ( '' == $_POST['content'] ) wp_die( __( 'ERROR: please type a comment.' ) ); $_POST['comment_status'] = $_POST['status']; edit_comment(); $position = ( isset($_POST['position']) && (int) $_POST['position']) ? (int) $_POST['position'] : '-1'; $comments_status = isset($_POST['comments_listing']) ? $_POST['comments_listing'] : ''; $checkbox = ( isset($_POST['checkbox']) && true == $_POST['checkbox'] ) ? 1 : 0; $wp_list_table = _get_list_table( $checkbox ? 'WP_Comments_List_Table' : 'WP_Post_Comments_List_Table', array( 'screen' => 'edit-comments' ) ); $comment = get_comment( $comment_id ); ob_start(); $wp_list_table->single_row( $comment ); $comment_list_item = ob_get_contents(); ob_end_clean(); $x = new WP_Ajax_Response(); $x->add( array( 'what' => 'edit_comment', 'id' => $comment->comment_ID, 'data' => $comment_list_item, 'position' => $position )); $x->send(); } function wp_ajax_add_menu_item() { check_ajax_referer( 'add-menu_item', 'menu-settings-column-nonce' ); if ( ! current_user_can( 'edit_theme_options' ) ) wp_die( -1 ); require_once ABSPATH . 'wp-admin/includes/nav-menu.php'; // For performance reasons, we omit some object properties from the checklist. // The following is a hacky way to restore them when adding non-custom items. $menu_items_data = array(); foreach ( (array) $_POST['menu-item'] as $menu_item_data ) { if ( ! empty( $menu_item_data['menu-item-type'] ) && 'custom' != $menu_item_data['menu-item-type'] && ! empty( $menu_item_data['menu-item-object-id'] ) ) { switch( $menu_item_data['menu-item-type'] ) { case 'post_type' : $_object = get_post( $menu_item_data['menu-item-object-id'] ); break; case 'taxonomy' : $_object = get_term( $menu_item_data['menu-item-object-id'], $menu_item_data['menu-item-object'] ); break; } $_menu_items = array_map( 'wp_setup_nav_menu_item', array( $_object ) ); $_menu_item = array_shift( $_menu_items ); // Restore the missing menu item properties $menu_item_data['menu-item-description'] = $_menu_item->description; } $menu_items_data[] = $menu_item_data; } $item_ids = wp_save_nav_menu_items( 0, $menu_items_data ); if ( is_wp_error( $item_ids ) ) wp_die( 0 ); $menu_items = array(); foreach ( (array) $item_ids as $menu_item_id ) { $menu_obj = get_post( $menu_item_id ); if ( ! empty( $menu_obj->ID ) ) { $menu_obj = wp_setup_nav_menu_item( $menu_obj ); $menu_obj->label = $menu_obj->title; // don't show "(pending)" in ajax-added items $menu_items[] = $menu_obj; } } $walker_class_name = apply_filters( 'wp_edit_nav_menu_walker', 'Walker_Nav_Menu_Edit', $_POST['menu'] ); if ( ! class_exists( $walker_class_name ) ) wp_die( 0 ); if ( ! empty( $menu_items ) ) { $args = array( 'after' => '', 'before' => '', 'link_after' => '', 'link_before' => '', 'walker' => new $walker_class_name, ); echo walk_nav_menu_tree( $menu_items, 0, (object) $args ); } } function wp_ajax_add_meta() { check_ajax_referer( 'add-meta', '_ajax_nonce-add-meta' ); $c = 0; $pid = (int) $_POST['post_id']; $post = get_post( $pid ); if ( isset($_POST['metakeyselect']) || isset($_POST['metakeyinput']) ) { if ( !current_user_can( 'edit_post', $pid ) ) wp_die( -1 ); if ( isset($_POST['metakeyselect']) && '#NONE#' == $_POST['metakeyselect'] && empty($_POST['metakeyinput']) ) wp_die( 1 ); if ( $post->post_status == 'auto-draft' ) { $save_POST = $_POST; // Backup $_POST $_POST = array(); // Make it empty for edit_post() $_POST['action'] = 'draft'; // Warning fix $_POST['post_ID'] = $pid; $_POST['post_type'] = $post->post_type; $_POST['post_status'] = 'draft'; $now = current_time('timestamp', 1); $_POST['post_title'] = sprintf('Draft created on %s at %s', date(get_option('date_format'), $now), date(get_option('time_format'), $now)); if ( $pid = edit_post() ) { if ( is_wp_error( $pid ) ) { $x = new WP_Ajax_Response( array( 'what' => 'meta', 'data' => $pid ) ); $x->send(); } $_POST = $save_POST; // Now we can restore original $_POST again if ( !$mid = add_meta( $pid ) ) wp_die( __( 'Please provide a custom field value.' ) ); } else { wp_die( 0 ); } } else if ( !$mid = add_meta( $pid ) ) { wp_die( __( 'Please provide a custom field value.' ) ); } $meta = get_metadata_by_mid( 'post', $mid ); $pid = (int) $meta->post_id; $meta = get_object_vars( $meta ); $x = new WP_Ajax_Response( array( 'what' => 'meta', 'id' => $mid, 'data' => _list_meta_row( $meta, $c ), 'position' => 1, 'supplemental' => array('postid' => $pid) ) ); } else { // Update? $mid = (int) key( $_POST['meta'] ); $key = stripslashes( $_POST['meta'][$mid]['key'] ); $value = stripslashes( $_POST['meta'][$mid]['value'] ); if ( '' == trim($key) ) wp_die( __( 'Please provide a custom field name.' ) ); if ( '' == trim($value) ) wp_die( __( 'Please provide a custom field value.' ) ); if ( ! $meta = get_metadata_by_mid( 'post', $mid ) ) wp_die( 0 ); // if meta doesn't exist if ( is_protected_meta( $meta->meta_key, 'post' ) || is_protected_meta( $key, 'post' ) || ! current_user_can( 'edit_post_meta', $meta->post_id, $meta->meta_key ) || ! current_user_can( 'edit_post_meta', $meta->post_id, $key ) ) wp_die( -1 ); if ( $meta->meta_value != $value || $meta->meta_key != $key ) { if ( !$u = update_metadata_by_mid( 'post', $mid, $value, $key ) ) wp_die( 0 ); // We know meta exists; we also know it's unchanged (or DB error, in which case there are bigger problems). } $x = new WP_Ajax_Response( array( 'what' => 'meta', 'id' => $mid, 'old_id' => $mid, 'data' => _list_meta_row( array( 'meta_key' => $key, 'meta_value' => $value, 'meta_id' => $mid ), $c ), 'position' => 0, 'supplemental' => array('postid' => $meta->post_id) ) ); } $x->send(); } function wp_ajax_add_user( $action ) { global $wp_list_table; if ( empty( $action ) ) $action = 'add-user'; check_ajax_referer( $action ); if ( ! current_user_can('create_users') ) wp_die( -1 ); if ( ! $user_id = edit_user() ) { wp_die( 0 ); } elseif ( is_wp_error( $user_id ) ) { $x = new WP_Ajax_Response( array( 'what' => 'user', 'id' => $user_id ) ); $x->send(); } $user_object = get_userdata( $user_id ); $wp_list_table = _get_list_table('WP_Users_List_Table'); $role = current( $user_object->roles ); $x = new WP_Ajax_Response( array( 'what' => 'user', 'id' => $user_id, 'data' => $wp_list_table->single_row( $user_object, '', $role ), 'supplemental' => array( 'show-link' => sprintf(__( 'User <a href="#%s">%s</a> added' ), "user-$user_id", $user_object->user_login), 'role' => $role, ) ) ); $x->send(); } function wp_ajax_autosave() { global $login_grace_period; define( 'DOING_AUTOSAVE', true ); $nonce_age = check_ajax_referer( 'autosave', 'autosavenonce' ); $_POST['post_category'] = explode(",", $_POST['catslist']); if ( $_POST['post_type'] == 'page' || empty($_POST['post_category']) ) unset($_POST['post_category']); $do_autosave = (bool) $_POST['autosave']; $do_lock = true; $data = $alert = ''; /* translators: draft saved date format, see http://php.net/date */ $draft_saved_date_format = __('g:i:s a'); /* translators: %s: date and time */ $message = sprintf( __('Draft saved at %s.'), date_i18n( $draft_saved_date_format ) ); $supplemental = array(); if ( isset($login_grace_period) ) $alert .= sprintf( __('Your login has expired. Please open a new browser window and <a href="%s" target="_blank">log in again</a>. '), add_query_arg( 'interim-login', 1, wp_login_url() ) ); $id = $revision_id = 0; $post_ID = (int) $_POST['post_ID']; $_POST['ID'] = $post_ID; $post = get_post($post_ID); if ( 'auto-draft' == $post->post_status ) $_POST['post_status'] = 'draft'; if ( $last = wp_check_post_lock( $post->ID ) ) { $do_autosave = $do_lock = false; $last_user = get_userdata( $last ); $last_user_name = $last_user ? $last_user->display_name : __( 'Someone' ); $data = __( 'Autosave disabled.' ); $supplemental['disable_autosave'] = 'disable'; $alert .= sprintf( __( '%s is currently editing this article. If you update it, you will overwrite the changes.' ), esc_html( $last_user_name ) ); } if ( 'page' == $post->post_type ) { if ( !current_user_can('edit_page', $post_ID) ) wp_die( __( 'You are not allowed to edit this page.' ) ); } else { if ( !current_user_can('edit_post', $post_ID) ) wp_die( __( 'You are not allowed to edit this post.' ) ); } if ( $do_autosave ) { // Drafts and auto-drafts are just overwritten by autosave if ( 'auto-draft' == $post->post_status || 'draft' == $post->post_status ) { $id = edit_post(); } else { // Non drafts are not overwritten. The autosave is stored in a special post revision. $revision_id = wp_create_post_autosave( $post->ID ); if ( is_wp_error($revision_id) ) $id = $revision_id; else $id = $post->ID; } $data = $message; } else { if ( ! empty( $_POST['auto_draft'] ) ) $id = 0; // This tells us it didn't actually save else $id = $post->ID; } if ( $do_lock && empty( $_POST['auto_draft'] ) && $id && is_numeric( $id ) ) { $lock_result = wp_set_post_lock( $id ); $supplemental['active-post-lock'] = implode( ':', $lock_result ); } if ( $nonce_age == 2 ) { $supplemental['replace-autosavenonce'] = wp_create_nonce('autosave'); $supplemental['replace-getpermalinknonce'] = wp_create_nonce('getpermalink'); $supplemental['replace-samplepermalinknonce'] = wp_create_nonce('samplepermalink'); $supplemental['replace-closedpostboxesnonce'] = wp_create_nonce('closedpostboxes'); $supplemental['replace-_ajax_linking_nonce'] = wp_create_nonce( 'internal-linking' ); if ( $id ) { if ( $_POST['post_type'] == 'post' ) $supplemental['replace-_wpnonce'] = wp_create_nonce('update-post_' . $id); elseif ( $_POST['post_type'] == 'page' ) $supplemental['replace-_wpnonce'] = wp_create_nonce('update-page_' . $id); } } if ( ! empty($alert) ) $supplemental['alert'] = $alert; $x = new WP_Ajax_Response( array( 'what' => 'autosave', 'id' => $id, 'data' => $id ? $data : '', 'supplemental' => $supplemental ) ); $x->send(); } function wp_ajax_closed_postboxes() { check_ajax_referer( 'closedpostboxes', 'closedpostboxesnonce' ); $closed = isset( $_POST['closed'] ) ? explode( ',', $_POST['closed']) : array(); $closed = array_filter($closed); $hidden = isset( $_POST['hidden'] ) ? explode( ',', $_POST['hidden']) : array(); $hidden = array_filter($hidden); $page = isset( $_POST['page'] ) ? $_POST['page'] : ''; if ( $page != sanitize_key( $page ) ) wp_die( 0 ); if ( ! $user = wp_get_current_user() ) wp_die( -1 ); if ( is_array($closed) ) update_user_option($user->ID, "closedpostboxes_$page", $closed, true); if ( is_array($hidden) ) { $hidden = array_diff( $hidden, array('submitdiv', 'linksubmitdiv', 'manage-menu', 'create-menu') ); // postboxes that are always shown update_user_option($user->ID, "metaboxhidden_$page", $hidden, true); } wp_die( 1 ); } function wp_ajax_hidden_columns() { check_ajax_referer( 'screen-options-nonce', 'screenoptionnonce' ); $hidden = isset( $_POST['hidden'] ) ? $_POST['hidden'] : ''; $hidden = explode( ',', $_POST['hidden'] ); $page = isset( $_POST['page'] ) ? $_POST['page'] : ''; if ( $page != sanitize_key( $page ) ) wp_die( 0 ); if ( ! $user = wp_get_current_user() ) wp_die( -1 ); if ( is_array($hidden) ) update_user_option($user->ID, "manage{$page}columnshidden", $hidden, true); wp_die( 1 ); } function wp_ajax_update_welcome_panel() { check_ajax_referer( 'welcome-panel-nonce', 'welcomepanelnonce' ); if ( ! current_user_can( 'edit_theme_options' ) ) wp_die( -1 ); update_user_meta( get_current_user_id(), 'show_welcome_panel', empty( $_POST['visible'] ) ? 0 : 1 ); wp_die( 1 ); } function wp_ajax_menu_get_metabox() { if ( ! current_user_can( 'edit_theme_options' ) ) wp_die( -1 ); require_once ABSPATH . 'wp-admin/includes/nav-menu.php'; if ( isset( $_POST['item-type'] ) && 'post_type' == $_POST['item-type'] ) { $type = 'posttype'; $callback = 'wp_nav_menu_item_post_type_meta_box'; $items = (array) get_post_types( array( 'show_in_nav_menus' => true ), 'object' ); } elseif ( isset( $_POST['item-type'] ) && 'taxonomy' == $_POST['item-type'] ) { $type = 'taxonomy'; $callback = 'wp_nav_menu_item_taxonomy_meta_box'; $items = (array) get_taxonomies( array( 'show_ui' => true ), 'object' ); } if ( ! empty( $_POST['item-object'] ) && isset( $items[$_POST['item-object']] ) ) { $item = apply_filters( 'nav_menu_meta_box_object', $items[ $_POST['item-object'] ] ); ob_start(); call_user_func_array($callback, array( null, array( 'id' => 'add-' . $item->name, 'title' => $item->labels->name, 'callback' => $callback, 'args' => $item, ) )); $markup = ob_get_clean(); echo json_encode(array( 'replace-id' => $type . '-' . $item->name, 'markup' => $markup, )); } wp_die(); } function wp_ajax_wp_link_ajax() { check_ajax_referer( 'internal-linking', '_ajax_linking_nonce' ); $args = array(); if ( isset( $_POST['search'] ) ) $args['s'] = stripslashes( $_POST['search'] ); $args['pagenum'] = ! empty( $_POST['page'] ) ? absint( $_POST['page'] ) : 1; require(ABSPATH . WPINC . '/class-wp-editor.php'); $results = _WP_Editors::wp_link_query( $args ); if ( ! isset( $results ) ) wp_die( 0 ); echo json_encode( $results ); echo "\n"; wp_die(); } function wp_ajax_menu_locations_save() { if ( ! current_user_can( 'edit_theme_options' ) ) wp_die( -1 ); check_ajax_referer( 'add-menu_item', 'menu-settings-column-nonce' ); if ( ! isset( $_POST['menu-locations'] ) ) wp_die( 0 ); set_theme_mod( 'nav_menu_locations', array_map( 'absint', $_POST['menu-locations'] ) ); wp_die( 1 ); } function wp_ajax_meta_box_order() { check_ajax_referer( 'meta-box-order' ); $order = isset( $_POST['order'] ) ? (array) $_POST['order'] : false; $page_columns = isset( $_POST['page_columns'] ) ? $_POST['page_columns'] : 'auto'; if ( $page_columns != 'auto' ) $page_columns = (int) $page_columns; $page = isset( $_POST['page'] ) ? $_POST['page'] : ''; if ( $page != sanitize_key( $page ) ) wp_die( 0 ); if ( ! $user = wp_get_current_user() ) wp_die( -1 ); if ( $order ) update_user_option($user->ID, "meta-box-order_$page", $order, true); if ( $page_columns ) update_user_option($user->ID, "screen_layout_$page", $page_columns, true); wp_die( 1 ); } function wp_ajax_menu_quick_search() { if ( ! current_user_can( 'edit_theme_options' ) ) wp_die( -1 ); require_once ABSPATH . 'wp-admin/includes/nav-menu.php'; _wp_ajax_menu_quick_search( $_POST ); wp_die(); } function wp_ajax_get_permalink() { check_ajax_referer( 'getpermalink', 'getpermalinknonce' ); $post_id = isset($_POST['post_id'])? intval($_POST['post_id']) : 0; wp_die( add_query_arg( array( 'preview' => 'true' ), get_permalink( $post_id ) ) ); } function wp_ajax_sample_permalink() { check_ajax_referer( 'samplepermalink', 'samplepermalinknonce' ); $post_id = isset($_POST['post_id'])? intval($_POST['post_id']) : 0; $title = isset($_POST['new_title'])? $_POST['new_title'] : ''; $slug = isset($_POST['new_slug'])? $_POST['new_slug'] : null; wp_die( get_sample_permalink_html( $post_id, $title, $slug ) ); } function wp_ajax_inline_save() { global $wp_list_table; check_ajax_referer( 'inlineeditnonce', '_inline_edit' ); if ( ! isset($_POST['post_ID']) || ! ( $post_ID = (int) $_POST['post_ID'] ) ) wp_die(); if ( 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_ID ) ) wp_die( __( 'You are not allowed to edit this page.' ) ); } else { if ( ! current_user_can( 'edit_post', $post_ID ) ) wp_die( __( 'You are not allowed to edit this post.' ) ); } if ( $last = wp_check_post_lock( $post_ID ) ) { $last_user = get_userdata( $last ); $last_user_name = $last_user ? $last_user->display_name : __( 'Someone' ); printf( $_POST['post_type'] == 'page' ? __( 'Saving is disabled: %s is currently editing this page.' ) : __( 'Saving is disabled: %s is currently editing this post.' ), esc_html( $last_user_name ) ); wp_die(); } $data = &$_POST; $post = get_post( $post_ID, ARRAY_A ); $post = add_magic_quotes($post); //since it is from db $data['content'] = $post['post_content']; $data['excerpt'] = $post['post_excerpt']; // rename $data['user_ID'] = $GLOBALS['user_ID']; if ( isset($data['post_parent']) ) $data['parent_id'] = $data['post_parent']; // status if ( isset($data['keep_private']) && 'private' == $data['keep_private'] ) $data['post_status'] = 'private'; else $data['post_status'] = $data['_status']; if ( empty($data['comment_status']) ) $data['comment_status'] = 'closed'; if ( empty($data['ping_status']) ) $data['ping_status'] = 'closed'; // update the post edit_post(); $wp_list_table = _get_list_table( 'WP_Posts_List_Table', array( 'screen' => $_POST['screen'] ) ); $mode = $_POST['post_view']; $level = 0; $request_post = array( get_post( $_POST['post_ID'] ) ); $parent = $request_post[0]->post_parent; while ( $parent > 0 ) { $parent_post = get_post( $parent ); $parent = $parent_post->post_parent; $level++; } $wp_list_table->display_rows( array( get_post( $_POST['post_ID'] ) ), $level ); wp_die(); } function wp_ajax_inline_save_tax() { global $wp_list_table; check_ajax_referer( 'taxinlineeditnonce', '_inline_edit' ); $taxonomy = sanitize_key( $_POST['taxonomy'] ); $tax = get_taxonomy( $taxonomy ); if ( ! $tax ) wp_die( 0 ); if ( ! current_user_can( $tax->cap->edit_terms ) ) wp_die( -1 ); $wp_list_table = _get_list_table( 'WP_Terms_List_Table', array( 'screen' => 'edit-' . $taxonomy ) ); if ( ! isset($_POST['tax_ID']) || ! ( $id = (int) $_POST['tax_ID'] ) ) wp_die( -1 ); $tag = get_term( $id, $taxonomy ); $_POST['description'] = $tag->description; $updated = wp_update_term($id, $taxonomy, $_POST); if ( $updated && !is_wp_error($updated) ) { $tag = get_term( $updated['term_id'], $taxonomy ); if ( !$tag || is_wp_error( $tag ) ) { if ( is_wp_error($tag) && $tag->get_error_message() ) wp_die( $tag->get_error_message() ); wp_die( __( 'Item not updated.' ) ); } } else { if ( is_wp_error($updated) && $updated->get_error_message() ) wp_die( $updated->get_error_message() ); wp_die( __( 'Item not updated.' ) ); } $level = 0; $parent = $tag->parent; while ( $parent > 0 ) { $parent_tag = get_term( $parent, $taxonomy ); $parent = $parent_tag->parent; $level++; } echo $wp_list_table->single_row( $tag, $level ); wp_die(); } function wp_ajax_find_posts() { global $wpdb; check_ajax_referer( 'find-posts' ); $post_types = get_post_types( array( 'public' => true ), 'objects' ); unset( $post_types['attachment'] ); $s = stripslashes( $_POST['ps'] ); $searchand = $search = ''; $args = array( 'post_type' => array_keys( $post_types ), 'post_status' => 'any', 'posts_per_page' => 50, ); if ( '' !== $s ) $args['s'] = $s; $posts = get_posts( $args ); if ( ! $posts ) wp_die( __('No items found.') ); $html = '<table class="widefat" cellspacing="0"><thead><tr><th class="found-radio"><br /></th><th>'.__('Title').'</th><th class="no-break">'.__('Type').'</th><th class="no-break">'.__('Date').'</th><th class="no-break">'.__('Status').'</th></tr></thead><tbody>'; foreach ( $posts as $post ) { $title = trim( $post->post_title ) ? $post->post_title : __( '(no title)' ); switch ( $post->post_status ) { case 'publish' : case 'private' : $stat = __('Published'); break; case 'future' : $stat = __('Scheduled'); break; case 'pending' : $stat = __('Pending Review'); break; case 'draft' : $stat = __('Draft'); break; } if ( '0000-00-00 00:00:00' == $post->post_date ) { $time = ''; } else { /* translators: date format in table columns, see http://php.net/date */ $time = mysql2date(__('Y/m/d'), $post->post_date); } $html .= '<tr class="found-posts"><td class="found-radio"><input type="radio" id="found-'.$post->ID.'" name="found_post_id" value="' . esc_attr($post->ID) . '"></td>'; $html .= '<td><label for="found-'.$post->ID.'">' . esc_html( $title ) . '</label></td><td class="no-break">' . esc_html( $post_types[$post->post_type]->labels->singular_name ) . '</td><td class="no-break">'.esc_html( $time ) . '</td><td class="no-break">' . esc_html( $stat ). ' </td></tr>' . "\n\n"; } $html .= '</tbody></table>'; $x = new WP_Ajax_Response(); $x->add( array( 'data' => $html )); $x->send(); } function wp_ajax_widgets_order() { check_ajax_referer( 'save-sidebar-widgets', 'savewidgets' ); if ( !current_user_can('edit_theme_options') ) wp_die( -1 ); unset( $_POST['savewidgets'], $_POST['action'] ); // save widgets order for all sidebars if ( is_array($_POST['sidebars']) ) { $sidebars = array(); foreach ( $_POST['sidebars'] as $key => $val ) { $sb = array(); if ( !empty($val) ) { $val = explode(',', $val); foreach ( $val as $k => $v ) { if ( strpos($v, 'widget-') === false ) continue; $sb[$k] = substr($v, strpos($v, '_') + 1); } } $sidebars[$key] = $sb; } wp_set_sidebars_widgets($sidebars); wp_die( 1 ); } wp_die( -1 ); } function wp_ajax_save_widget() { global $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_widget_updates; check_ajax_referer( 'save-sidebar-widgets', 'savewidgets' ); if ( !current_user_can('edit_theme_options') || !isset($_POST['id_base']) ) wp_die( -1 ); unset( $_POST['savewidgets'], $_POST['action'] ); do_action('load-widgets.php'); do_action('widgets.php'); do_action('sidebar_admin_setup'); $id_base = $_POST['id_base']; $widget_id = $_POST['widget-id']; $sidebar_id = $_POST['sidebar']; $multi_number = !empty($_POST['multi_number']) ? (int) $_POST['multi_number'] : 0; $settings = isset($_POST['widget-' . $id_base]) && is_array($_POST['widget-' . $id_base]) ? $_POST['widget-' . $id_base] : false; $error = '<p>' . __('An error has occurred. Please reload the page and try again.') . '</p>'; $sidebars = wp_get_sidebars_widgets(); $sidebar = isset($sidebars[$sidebar_id]) ? $sidebars[$sidebar_id] : array(); // delete if ( isset($_POST['delete_widget']) && $_POST['delete_widget'] ) { if ( !isset($wp_registered_widgets[$widget_id]) ) wp_die( $error ); $sidebar = array_diff( $sidebar, array($widget_id) ); $_POST = array('sidebar' => $sidebar_id, 'widget-' . $id_base => array(), 'the-widget-id' => $widget_id, 'delete_widget' => '1'); } elseif ( $settings && preg_match( '/__i__|%i%/', key($settings) ) ) { if ( !$multi_number ) wp_die( $error ); $_POST['widget-' . $id_base] = array( $multi_number => array_shift($settings) ); $widget_id = $id_base . '-' . $multi_number; $sidebar[] = $widget_id; } $_POST['widget-id'] = $sidebar; foreach ( (array) $wp_registered_widget_updates as $name => $control ) { if ( $name == $id_base ) { if ( !is_callable( $control['callback'] ) ) continue; ob_start(); call_user_func_array( $control['callback'], $control['params'] ); ob_end_clean(); break; } } if ( isset($_POST['delete_widget']) && $_POST['delete_widget'] ) { $sidebars[$sidebar_id] = $sidebar; wp_set_sidebars_widgets($sidebars); echo "deleted:$widget_id"; wp_die(); } if ( !empty($_POST['add_new']) ) wp_die(); if ( $form = $wp_registered_widget_controls[$widget_id] ) call_user_func_array( $form['callback'], $form['params'] ); wp_die(); } function wp_ajax_upload_attachment() { check_ajax_referer( 'media-form' ); if ( ! current_user_can( 'upload_files' ) ) wp_die(); if ( isset( $_REQUEST['post_id'] ) ) { $post_id = $_REQUEST['post_id']; if ( ! current_user_can( 'edit_post', $post_id ) ) wp_die(); } else { $post_id = null; } $post_data = isset( $_REQUEST['post_data'] ) ? $_REQUEST['post_data'] : array(); // If the context is custom header or background, make sure the uploaded file is an image. if ( isset( $post_data['context'] ) && in_array( $post_data['context'], array( 'custom-header', 'custom-background' ) ) ) { $wp_filetype = wp_check_filetype_and_ext( $_FILES['async-upload']['tmp_name'], $_FILES['async-upload']['name'], false ); if ( ! wp_match_mime_types( 'image', $wp_filetype['type'] ) ) { echo json_encode( array( 'success' => false, 'data' => array( 'message' => __( 'The uploaded file is not a valid image. Please try again.' ), 'filename' => $_FILES['async-upload']['name'], ) ) ); wp_die(); } } $attachment_id = media_handle_upload( 'async-upload', $post_id, $post_data ); if ( is_wp_error( $attachment_id ) ) { echo json_encode( array( 'success' => false, 'data' => array( 'message' => $attachment_id->get_error_message(), 'filename' => $_FILES['async-upload']['name'], ) ) ); wp_die(); } if ( isset( $post_data['context'] ) && isset( $post_data['theme'] ) ) { if ( 'custom-background' === $post_data['context'] ) update_post_meta( $attachment_id, '_wp_attachment_is_custom_background', $post_data['theme'] ); if ( 'custom-header' === $post_data['context'] ) update_post_meta( $attachment_id, '_wp_attachment_is_custom_header', $post_data['theme'] ); } if ( ! $attachment = wp_prepare_attachment_for_js( $attachment_id ) ) wp_die(); echo json_encode( array( 'success' => true, 'data' => $attachment, ) ); wp_die(); } function wp_ajax_image_editor() { $attachment_id = intval($_POST['postid']); if ( empty($attachment_id) || !current_user_can('edit_post', $attachment_id) ) wp_die( -1 ); check_ajax_referer( "image_editor-$attachment_id" ); include_once( ABSPATH . 'wp-admin/includes/image-edit.php' ); $msg = false; switch ( $_POST['do'] ) { case 'save' : $msg = wp_save_image($attachment_id); $msg = json_encode($msg); wp_die( $msg ); break; case 'scale' : $msg = wp_save_image($attachment_id); break; case 'restore' : $msg = wp_restore_image($attachment_id); break; } wp_image_editor($attachment_id, $msg); wp_die(); } function wp_ajax_set_post_thumbnail() { $json = ! empty( $_REQUEST['json'] ); // New-style request $post_ID = intval( $_POST['post_id'] ); if ( ! current_user_can( 'edit_post', $post_ID ) ) wp_die( -1 ); $thumbnail_id = intval( $_POST['thumbnail_id'] ); if ( $json ) check_ajax_referer( "update-post_$post_ID" ); else check_ajax_referer( "set_post_thumbnail-$post_ID" ); if ( $thumbnail_id == '-1' ) { if ( delete_post_thumbnail( $post_ID ) ) { $return = _wp_post_thumbnail_html( null, $post_ID ); $json ? wp_send_json_success( $return ) : wp_die( $return ); } else { wp_die( 0 ); } } if ( set_post_thumbnail( $post_ID, $thumbnail_id ) ) { $return = _wp_post_thumbnail_html( $thumbnail_id, $post_ID ); $json ? wp_send_json_success( $return ) : wp_die( $return ); } wp_die( 0 ); } function wp_ajax_date_format() { wp_die( date_i18n( sanitize_option( 'date_format', $_POST['date'] ) ) ); } function wp_ajax_time_format() { wp_die( date_i18n( sanitize_option( 'time_format', $_POST['date'] ) ) ); } function wp_ajax_wp_fullscreen_save_post() { $post_id = isset( $_POST['post_ID'] ) ? (int) $_POST['post_ID'] : 0; $post = $post_type = null; if ( $post_id ) $post = get_post( $post_id ); if ( $post ) $post_type = $post->post_type; elseif ( isset( $_POST['post_type'] ) && post_type_exists( $_POST['post_type'] ) ) $post_type = $_POST['post_type']; check_ajax_referer('update-post_' . $post_id, '_wpnonce'); $post_id = edit_post(); if ( is_wp_error($post_id) ) { if ( $post_id->get_error_message() ) $message = $post_id->get_error_message(); else $message = __('Save failed'); echo json_encode( array( 'message' => $message, 'last_edited' => '' ) ); wp_die(); } else { $message = __('Saved.'); } if ( $post ) { $last_date = mysql2date( get_option('date_format'), $post->post_modified ); $last_time = mysql2date( get_option('time_format'), $post->post_modified ); } else { $last_date = date_i18n( get_option('date_format') ); $last_time = date_i18n( get_option('time_format') ); } if ( $last_id = get_post_meta($post_id, '_edit_last', true) ) { $last_user = get_userdata($last_id); $last_edited = sprintf( __('Last edited by %1$s on %2$s at %3$s'), esc_html( $last_user->display_name ), $last_date, $last_time ); } else { $last_edited = sprintf( __('Last edited on %1$s at %2$s'), $last_date, $last_time ); } echo json_encode( array( 'message' => $message, 'last_edited' => $last_edited ) ); wp_die(); } function wp_ajax_wp_remove_post_lock() { if ( empty( $_POST['post_ID'] ) || empty( $_POST['active_post_lock'] ) ) wp_die( 0 ); $post_id = (int) $_POST['post_ID']; if ( ! $post = get_post( $post_id ) ) wp_die( 0 ); check_ajax_referer( 'update-post_' . $post_id ); if ( ! current_user_can( 'edit_post', $post_id ) ) wp_die( -1 ); $active_lock = array_map( 'absint', explode( ':', $_POST['active_post_lock'] ) ); if ( $active_lock[1] != get_current_user_id() ) wp_die( 0 ); $new_lock = ( time() - apply_filters( 'wp_check_post_lock_window', AUTOSAVE_INTERVAL * 2 ) + 5 ) . ':' . $active_lock[1]; update_post_meta( $post_id, '_edit_lock', $new_lock, implode( ':', $active_lock ) ); wp_die( 1 ); } function wp_ajax_dismiss_wp_pointer() { $pointer = $_POST['pointer']; if ( $pointer != sanitize_key( $pointer ) ) wp_die( 0 ); // check_ajax_referer( 'dismiss-pointer_' . $pointer ); $dismissed = array_filter( explode( ',', (string) get_user_meta( get_current_user_id(), 'dismissed_wp_pointers', true ) ) ); if ( in_array( $pointer, $dismissed ) ) wp_die( 0 ); $dismissed[] = $pointer; $dismissed = implode( ',', $dismissed ); update_user_meta( get_current_user_id(), 'dismissed_wp_pointers', $dismissed ); wp_die( 1 ); } /** * Get an attachment. * * @since 3.5.0 */ function wp_ajax_get_attachment() { if ( ! isset( $_REQUEST['id'] ) ) wp_send_json_error(); if ( ! $id = absint( $_REQUEST['id'] ) ) wp_send_json_error(); if ( ! $post = get_post( $id ) ) wp_send_json_error(); if ( 'attachment' != $post->post_type ) wp_send_json_error(); if ( ! current_user_can( 'upload_files' ) ) wp_send_json_error(); if ( ! $attachment = wp_prepare_attachment_for_js( $id ) ) wp_send_json_error(); wp_send_json_success( $attachment ); } /** * Query for attachments. * * @since 3.5.0 */ function wp_ajax_query_attachments() { if ( ! current_user_can( 'upload_files' ) ) wp_send_json_error(); $query = isset( $_REQUEST['query'] ) ? (array) $_REQUEST['query'] : array(); $query = array_intersect_key( $query, array_flip( array( 's', 'order', 'orderby', 'posts_per_page', 'paged', 'post_mime_type', 'post_parent', 'post__in', 'post__not_in', ) ) ); $query['post_type'] = 'attachment'; $query['post_status'] = 'inherit'; if ( current_user_can( get_post_type_object( 'attachment' )->cap->read_private_posts ) ) $query['post_status'] .= ',private'; $query = new WP_Query( $query ); $posts = array_map( 'wp_prepare_attachment_for_js', $query->posts ); $posts = array_filter( $posts ); wp_send_json_success( $posts ); } /** * Save attachment attributes. * * @since 3.5.0 */ function wp_ajax_save_attachment() { if ( ! isset( $_REQUEST['id'] ) || ! isset( $_REQUEST['changes'] ) ) wp_send_json_error(); if ( ! $id = absint( $_REQUEST['id'] ) ) wp_send_json_error(); check_ajax_referer( 'update-post_' . $id, 'nonce' ); if ( ! current_user_can( 'edit_post', $id ) ) wp_send_json_error(); $changes = $_REQUEST['changes']; $post = get_post( $id, ARRAY_A ); if ( 'attachment' != $post['post_type'] ) wp_send_json_error(); if ( isset( $changes['title'] ) ) $post['post_title'] = $changes['title']; if ( isset( $changes['caption'] ) ) $post['post_excerpt'] = $changes['caption']; if ( isset( $changes['description'] ) ) $post['post_content'] = $changes['description']; if ( isset( $changes['alt'] ) ) { $alt = get_post_meta( $id, '_wp_attachment_image_alt', true ); $new_alt = stripslashes( $changes['alt'] ); if ( $alt != $new_alt ) { $new_alt = wp_strip_all_tags( $new_alt, true ); update_post_meta( $id, '_wp_attachment_image_alt', addslashes( $new_alt ) ); } } wp_update_post( $post ); wp_send_json_success(); } /** * Save backwards compatible attachment attributes. * * @since 3.5.0 */ function wp_ajax_save_attachment_compat() { if ( ! isset( $_REQUEST['id'] ) ) wp_send_json_error(); if ( ! $id = absint( $_REQUEST['id'] ) ) wp_send_json_error(); if ( empty( $_REQUEST['attachments'] ) || empty( $_REQUEST['attachments'][ $id ] ) ) wp_send_json_error(); $attachment_data = $_REQUEST['attachments'][ $id ]; check_ajax_referer( 'update-post_' . $id, 'nonce' ); if ( ! current_user_can( 'edit_post', $id ) ) wp_send_json_error(); $post = get_post( $id, ARRAY_A ); if ( 'attachment' != $post['post_type'] ) wp_send_json_error(); $post = apply_filters( 'attachment_fields_to_save', $post, $attachment_data ); if ( isset( $post['errors'] ) ) { $errors = $post['errors']; // @todo return me and display me! unset( $post['errors'] ); } wp_update_post( $post ); foreach ( get_attachment_taxonomies( $post ) as $taxonomy ) { if ( isset( $attachment_data[ $taxonomy ] ) ) wp_set_object_terms( $id, array_map( 'trim', preg_split( '/,+/', $attachment_data[ $taxonomy ] ) ), $taxonomy, false ); } if ( ! $attachment = wp_prepare_attachment_for_js( $id ) ) wp_send_json_error(); wp_send_json_success( $attachment ); } function wp_ajax_save_attachment_order() { if ( ! isset( $_REQUEST['post_id'] ) ) wp_send_json_error(); if ( ! $post_id = absint( $_REQUEST['post_id'] ) ) wp_send_json_error(); if ( empty( $_REQUEST['attachments'] ) ) wp_send_json_error(); check_ajax_referer( 'update-post_' . $post_id, 'nonce' ); $attachments = $_REQUEST['attachments']; if ( ! current_user_can( 'edit_post', $post_id ) ) wp_send_json_error(); $post = get_post( $post_id, ARRAY_A ); foreach ( $attachments as $attachment_id => $menu_order ) { if ( ! current_user_can( 'edit_post', $attachment_id ) ) continue; if ( ! $attachment = get_post( $attachment_id ) ) continue; if ( 'attachment' != $attachment->post_type ) continue; wp_update_post( array( 'ID' => $attachment_id, 'menu_order' => $menu_order ) ); } wp_send_json_success(); } /** * Generates the HTML to send an attachment to the editor. * Backwards compatible with the media_send_to_editor filter and the chain * of filters that follow. * * @since 3.5.0 */ function wp_ajax_send_attachment_to_editor() { check_ajax_referer( 'media-send-to-editor', 'nonce' ); $attachment = stripslashes_deep( $_POST['attachment'] ); $id = intval( $attachment['id'] ); if ( ! $post = get_post( $id ) ) wp_send_json_error(); if ( 'attachment' != $post->post_type ) wp_send_json_error(); if ( current_user_can( 'edit_post', $id ) ) { // If this attachment is unattached, attach it. Primarily a back compat thing. if ( 0 == $post->post_parent && $insert_into_post_id = intval( $_POST['post_id'] ) ) { wp_update_post( array( 'ID' => $id, 'post_parent' => $insert_into_post_id ) ); } } $rel = $url = ''; $html = $title = isset( $attachment['post_title'] ) ? $attachment['post_title'] : ''; if ( ! empty( $attachment['url'] ) ) { $url = $attachment['url']; if ( strpos( $url, 'attachment_id') || get_attachment_link( $id ) == $url ) $rel = ' rel="attachment wp-att-' . $id . '"'; $html = '<a href="' . esc_url( $url ) . '"' . $rel . '>' . $html . '</a>'; } remove_filter( 'media_send_to_editor', 'image_media_send_to_editor', 10, 3 ); if ( 'image' === substr( $post->post_mime_type, 0, 5 ) ) { $align = isset( $attachment['align'] ) ? $attachment['align'] : 'none'; $size = isset( $attachment['image-size'] ) ? $attachment['image-size'] : 'medium'; $alt = isset( $attachment['image_alt'] ) ? $attachment['image_alt'] : ''; $caption = isset( $attachment['post_excerpt'] ) ? $attachment['post_excerpt'] : ''; $title = ''; // We no longer insert title tags into <img> tags, as they are redundant. $html = get_image_send_to_editor( $id, $caption, $title, $align, $url, (bool) $rel, $size, $alt ); } $html = apply_filters( 'media_send_to_editor', $html, $id, $attachment ); wp_send_json_success( $html ); } /** * Generates the HTML to send a non-image embed link to the editor. * * Backwards compatible with the following filters: * - file_send_to_editor_url * - audio_send_to_editor_url * - video_send_to_editor_url * * @since 3.5.0 */ function wp_ajax_send_link_to_editor() { check_ajax_referer( 'media-send-to-editor', 'nonce' ); if ( ! $src = stripslashes( $_POST['src'] ) ) wp_send_json_error(); if ( ! strpos( $src, '://' ) ) $src = 'http://' . $src; if ( ! $src = esc_url_raw( $src ) ) wp_send_json_error(); if ( ! $title = trim( stripslashes( $_POST['title'] ) ) ) $title = wp_basename( $src ); $html = ''; if ( $title ) $html = '<a href="' . esc_url( $src ) . '">' . $title . '</a>'; // Figure out what filter to run: $type = 'file'; if ( ( $ext = preg_replace( '/^.+?\.([^.]+)$/', '$1', $src ) ) && ( $ext_type = wp_ext2type( $ext ) ) && ( 'audio' == $ext_type || 'video' == $ext_type ) ) $type = $ext_type; $html = apply_filters( $type . '_send_to_editor_url', $html, $src, $title ); wp_send_json_success( $html ); }
zyblog
trunk/zyblog/wp-admin/includes/ajax-actions.php
PHP
asf20
62,346
<?php /** * Users List Table class. * * @package WordPress * @subpackage List_Table * @since 3.1.0 * @access private */ class WP_Users_List_Table extends WP_List_Table { var $site_id; var $is_site_users; function __construct( $args = array() ) { parent::__construct( array( 'singular' => 'user', 'plural' => 'users', 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); $this->is_site_users = 'site-users-network' == $this->screen->id; if ( $this->is_site_users ) $this->site_id = isset( $_REQUEST['id'] ) ? intval( $_REQUEST['id'] ) : 0; } function ajax_user_can() { if ( $this->is_site_users ) return current_user_can( 'manage_sites' ); else return current_user_can( 'list_users' ); } function prepare_items() { global $role, $usersearch; $usersearch = isset( $_REQUEST['s'] ) ? trim( $_REQUEST['s'] ) : ''; $role = isset( $_REQUEST['role'] ) ? $_REQUEST['role'] : ''; $per_page = ( $this->is_site_users ) ? 'site_users_network_per_page' : 'users_per_page'; $users_per_page = $this->get_items_per_page( $per_page ); $paged = $this->get_pagenum(); $args = array( 'number' => $users_per_page, 'offset' => ( $paged-1 ) * $users_per_page, 'role' => $role, 'search' => $usersearch, 'fields' => 'all_with_meta' ); if ( '' !== $args['search'] ) $args['search'] = '*' . $args['search'] . '*'; if ( $this->is_site_users ) $args['blog_id'] = $this->site_id; if ( isset( $_REQUEST['orderby'] ) ) $args['orderby'] = $_REQUEST['orderby']; if ( isset( $_REQUEST['order'] ) ) $args['order'] = $_REQUEST['order']; // Query the user IDs for this page $wp_user_search = new WP_User_Query( $args ); $this->items = $wp_user_search->get_results(); $this->set_pagination_args( array( 'total_items' => $wp_user_search->get_total(), 'per_page' => $users_per_page, ) ); } function no_items() { _e( 'No matching users were found.' ); } function get_views() { global $wp_roles, $role; if ( $this->is_site_users ) { $url = 'site-users.php?id=' . $this->site_id; switch_to_blog( $this->site_id ); $users_of_blog = count_users(); restore_current_blog(); } else { $url = 'users.php'; $users_of_blog = count_users(); } $total_users = $users_of_blog['total_users']; $avail_roles =& $users_of_blog['avail_roles']; unset($users_of_blog); $current_role = false; $class = empty($role) ? ' class="current"' : ''; $role_links = array(); $role_links['all'] = "<a href='$url'$class>" . sprintf( _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $total_users, 'users' ), number_format_i18n( $total_users ) ) . '</a>'; foreach ( $wp_roles->get_names() as $this_role => $name ) { if ( !isset($avail_roles[$this_role]) ) continue; $class = ''; if ( $this_role == $role ) { $current_role = $role; $class = ' class="current"'; } $name = translate_user_role( $name ); /* translators: User role name with count */ $name = sprintf( __('%1$s <span class="count">(%2$s)</span>'), $name, number_format_i18n( $avail_roles[$this_role] ) ); $role_links[$this_role] = "<a href='" . esc_url( add_query_arg( 'role', $this_role, $url ) ) . "'$class>$name</a>"; } return $role_links; } function get_bulk_actions() { $actions = array(); if ( is_multisite() ) { if ( current_user_can( 'remove_users' ) ) $actions['remove'] = __( 'Remove' ); } else { if ( current_user_can( 'delete_users' ) ) $actions['delete'] = __( 'Delete' ); } return $actions; } function extra_tablenav( $which ) { if ( 'top' != $which ) return; ?> <div class="alignleft actions"> <?php if ( current_user_can( 'promote_users' ) ) : ?> <label class="screen-reader-text" for="new_role"><?php _e( 'Change role to&hellip;' ) ?></label> <select name="new_role" id="new_role"> <option value=''><?php _e( 'Change role to&hellip;' ) ?></option> <?php wp_dropdown_roles(); ?> </select> <?php submit_button( __( 'Change' ), 'button', 'changeit', false ); endif; do_action( 'restrict_manage_users' ); echo '</div>'; } function current_action() { if ( isset($_REQUEST['changeit']) && !empty($_REQUEST['new_role']) ) return 'promote'; return parent::current_action(); } function get_columns() { $c = array( 'cb' => '<input type="checkbox" />', 'username' => __( 'Username' ), 'name' => __( 'Name' ), 'email' => __( 'E-mail' ), 'role' => __( 'Role' ), 'posts' => __( 'Posts' ) ); if ( $this->is_site_users ) unset( $c['posts'] ); return $c; } function get_sortable_columns() { $c = array( 'username' => 'login', 'name' => 'name', 'email' => 'email', ); if ( $this->is_site_users ) unset( $c['posts'] ); return $c; } function display_rows() { // Query the post counts for this page if ( ! $this->is_site_users ) $post_counts = count_many_users_posts( array_keys( $this->items ) ); $editable_roles = array_keys( get_editable_roles() ); $style = ''; foreach ( $this->items as $userid => $user_object ) { if ( count( $user_object->roles ) <= 1 ) { $role = reset( $user_object->roles ); } elseif ( $roles = array_intersect( array_values( $user_object->roles ), $editable_roles ) ) { $role = reset( $roles ); } else { $role = reset( $user_object->roles ); } if ( is_multisite() && empty( $user_object->allcaps ) ) continue; $style = ( ' class="alternate"' == $style ) ? '' : ' class="alternate"'; echo "\n\t", $this->single_row( $user_object, $style, $role, isset( $post_counts ) ? $post_counts[ $userid ] : 0 ); } } /** * Generate HTML for a single row on the users.php admin panel. * * @since 2.1.0 * * @param object $user_object * @param string $style Optional. Attributes added to the TR element. Must be sanitized. * @param string $role Key for the $wp_roles array. * @param int $numposts Optional. Post count to display for this user. Defaults to zero, as in, a new user has made zero posts. * @return string */ function single_row( $user_object, $style = '', $role = '', $numposts = 0 ) { global $wp_roles; if ( !( is_object( $user_object ) && is_a( $user_object, 'WP_User' ) ) ) $user_object = get_userdata( (int) $user_object ); $user_object->filter = 'display'; $email = $user_object->user_email; if ( $this->is_site_users ) $url = "site-users.php?id={$this->site_id}&amp;"; else $url = 'users.php?'; $checkbox = ''; // Check if the user for this row is editable if ( current_user_can( 'list_users' ) ) { // Set up the user editing link $edit_link = esc_url( add_query_arg( 'wp_http_referer', urlencode( stripslashes( $_SERVER['REQUEST_URI'] ) ), get_edit_user_link( $user_object->ID ) ) ); // Set up the hover actions for this user $actions = array(); if ( current_user_can( 'edit_user', $user_object->ID ) ) { $edit = "<strong><a href=\"$edit_link\">$user_object->user_login</a></strong><br />"; $actions['edit'] = '<a href="' . $edit_link . '">' . __( 'Edit' ) . '</a>'; } else { $edit = "<strong>$user_object->user_login</strong><br />"; } if ( !is_multisite() && get_current_user_id() != $user_object->ID && current_user_can( 'delete_user', $user_object->ID ) ) $actions['delete'] = "<a class='submitdelete' href='" . wp_nonce_url( "users.php?action=delete&amp;user=$user_object->ID", 'bulk-users' ) . "'>" . __( 'Delete' ) . "</a>"; if ( is_multisite() && get_current_user_id() != $user_object->ID && current_user_can( 'remove_user', $user_object->ID ) ) $actions['remove'] = "<a class='submitdelete' href='" . wp_nonce_url( $url."action=remove&amp;user=$user_object->ID", 'bulk-users' ) . "'>" . __( 'Remove' ) . "</a>"; $actions = apply_filters( 'user_row_actions', $actions, $user_object ); $edit .= $this->row_actions( $actions ); // Set up the checkbox ( because the user is editable, otherwise its empty ) $checkbox = '<label class="screen-reader-text" for="cb-select-' . $user_object->ID . '">' . sprintf( __( 'Select %s' ), $user_object->user_login ) . '</label>' . "<input type='checkbox' name='users[]' id='user_{$user_object->ID}' class='$role' value='{$user_object->ID}' />"; } else { $edit = '<strong>' . $user_object->user_login . '</strong>'; } $role_name = isset( $wp_roles->role_names[$role] ) ? translate_user_role( $wp_roles->role_names[$role] ) : __( 'None' ); $avatar = get_avatar( $user_object->ID, 32 ); $r = "<tr id='user-$user_object->ID'$style>"; list( $columns, $hidden ) = $this->get_column_info(); foreach ( $columns as $column_name => $column_display_name ) { $class = "class=\"$column_name column-$column_name\""; $style = ''; if ( in_array( $column_name, $hidden ) ) $style = ' style="display:none;"'; $attributes = "$class$style"; switch ( $column_name ) { case 'cb': $r .= "<th scope='row' class='check-column'>$checkbox</th>"; break; case 'username': $r .= "<td $attributes>$avatar $edit</td>"; break; case 'name': $r .= "<td $attributes>$user_object->first_name $user_object->last_name</td>"; break; case 'email': $r .= "<td $attributes><a href='mailto:$email' title='" . esc_attr( sprintf( __( 'E-mail: %s' ), $email ) ) . "'>$email</a></td>"; break; case 'role': $r .= "<td $attributes>$role_name</td>"; break; case 'posts': $attributes = 'class="posts column-posts num"' . $style; $r .= "<td $attributes>"; if ( $numposts > 0 ) { $r .= "<a href='edit.php?author=$user_object->ID' title='" . esc_attr__( 'View posts by this author' ) . "' class='edit'>"; $r .= $numposts; $r .= '</a>'; } else { $r .= 0; } $r .= "</td>"; break; default: $r .= "<td $attributes>"; $r .= apply_filters( 'manage_users_custom_column', '', $column_name, $user_object->ID ); $r .= "</td>"; } } $r .= '</tr>'; return $r; } }
zyblog
trunk/zyblog/wp-admin/includes/class-wp-users-list-table.php
PHP
asf20
10,072
<?php /** * Posts List Table class. * * @package WordPress * @subpackage List_Table * @since 3.1.0 * @access private */ class WP_Posts_List_Table extends WP_List_Table { /** * Whether the items should be displayed hierarchically or linearly * * @since 3.1.0 * @var bool * @access protected */ var $hierarchical_display; /** * Holds the number of pending comments for each post * * @since 3.1.0 * @var int * @access protected */ var $comment_pending_count; /** * Holds the number of posts for this user * * @since 3.1.0 * @var int * @access private */ var $user_posts_count; /** * Holds the number of posts which are sticky. * * @since 3.1.0 * @var int * @access private */ var $sticky_posts_count = 0; function __construct( $args = array() ) { global $post_type_object, $wpdb; parent::__construct( array( 'plural' => 'posts', 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); $post_type = $this->screen->post_type; $post_type_object = get_post_type_object( $post_type ); if ( !current_user_can( $post_type_object->cap->edit_others_posts ) ) { $this->user_posts_count = $wpdb->get_var( $wpdb->prepare( " SELECT COUNT( 1 ) FROM $wpdb->posts WHERE post_type = %s AND post_status NOT IN ( 'trash', 'auto-draft' ) AND post_author = %d ", $post_type, get_current_user_id() ) ); if ( $this->user_posts_count && empty( $_REQUEST['post_status'] ) && empty( $_REQUEST['all_posts'] ) && empty( $_REQUEST['author'] ) && empty( $_REQUEST['show_sticky'] ) ) $_GET['author'] = get_current_user_id(); } if ( 'post' == $post_type && $sticky_posts = get_option( 'sticky_posts' ) ) { $sticky_posts = implode( ', ', array_map( 'absint', (array) $sticky_posts ) ); $this->sticky_posts_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT( 1 ) FROM $wpdb->posts WHERE post_type = %s AND post_status != 'trash' AND ID IN ($sticky_posts)", $post_type ) ); } } function ajax_user_can() { return current_user_can( get_post_type_object( $this->screen->post_type )->cap->edit_posts ); } function prepare_items() { global $avail_post_stati, $wp_query, $per_page, $mode; $avail_post_stati = wp_edit_posts_query(); $this->hierarchical_display = ( is_post_type_hierarchical( $this->screen->post_type ) && 'menu_order title' == $wp_query->query['orderby'] ); $total_items = $this->hierarchical_display ? $wp_query->post_count : $wp_query->found_posts; $post_type = $this->screen->post_type; $per_page = $this->get_items_per_page( 'edit_' . $post_type . '_per_page' ); $per_page = apply_filters( 'edit_posts_per_page', $per_page, $post_type ); if ( $this->hierarchical_display ) $total_pages = ceil( $total_items / $per_page ); else $total_pages = $wp_query->max_num_pages; $mode = empty( $_REQUEST['mode'] ) ? 'list' : $_REQUEST['mode']; $this->is_trash = isset( $_REQUEST['post_status'] ) && $_REQUEST['post_status'] == 'trash'; $this->set_pagination_args( array( 'total_items' => $total_items, 'total_pages' => $total_pages, 'per_page' => $per_page ) ); } function has_items() { return have_posts(); } function no_items() { if ( isset( $_REQUEST['post_status'] ) && 'trash' == $_REQUEST['post_status'] ) echo get_post_type_object( $this->screen->post_type )->labels->not_found_in_trash; else echo get_post_type_object( $this->screen->post_type )->labels->not_found; } function get_views() { global $locked_post_status, $avail_post_stati; $post_type = $this->screen->post_type; if ( !empty($locked_post_status) ) return array(); $status_links = array(); $num_posts = wp_count_posts( $post_type, 'readable' ); $class = ''; $allposts = ''; $current_user_id = get_current_user_id(); if ( $this->user_posts_count ) { if ( isset( $_GET['author'] ) && ( $_GET['author'] == $current_user_id ) ) $class = ' class="current"'; $status_links['mine'] = "<a href='edit.php?post_type=$post_type&author=$current_user_id'$class>" . sprintf( _nx( 'Mine <span class="count">(%s)</span>', 'Mine <span class="count">(%s)</span>', $this->user_posts_count, 'posts' ), number_format_i18n( $this->user_posts_count ) ) . '</a>'; $allposts = '&all_posts=1'; } $total_posts = array_sum( (array) $num_posts ); // Subtract post types that are not included in the admin all list. foreach ( get_post_stati( array('show_in_admin_all_list' => false) ) as $state ) $total_posts -= $num_posts->$state; $class = empty( $class ) && empty( $_REQUEST['post_status'] ) && empty( $_REQUEST['show_sticky'] ) ? ' class="current"' : ''; $status_links['all'] = "<a href='edit.php?post_type=$post_type{$allposts}'$class>" . sprintf( _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $total_posts, 'posts' ), number_format_i18n( $total_posts ) ) . '</a>'; foreach ( get_post_stati(array('show_in_admin_status_list' => true), 'objects') as $status ) { $class = ''; $status_name = $status->name; if ( !in_array( $status_name, $avail_post_stati ) ) continue; if ( empty( $num_posts->$status_name ) ) continue; if ( isset($_REQUEST['post_status']) && $status_name == $_REQUEST['post_status'] ) $class = ' class="current"'; $status_links[$status_name] = "<a href='edit.php?post_status=$status_name&amp;post_type=$post_type'$class>" . sprintf( translate_nooped_plural( $status->label_count, $num_posts->$status_name ), number_format_i18n( $num_posts->$status_name ) ) . '</a>'; } if ( ! empty( $this->sticky_posts_count ) ) { $class = ! empty( $_REQUEST['show_sticky'] ) ? ' class="current"' : ''; $sticky_link = array( 'sticky' => "<a href='edit.php?post_type=$post_type&amp;show_sticky=1'$class>" . sprintf( _nx( 'Sticky <span class="count">(%s)</span>', 'Sticky <span class="count">(%s)</span>', $this->sticky_posts_count, 'posts' ), number_format_i18n( $this->sticky_posts_count ) ) . '</a>' ); // Sticky comes after Publish, or if not listed, after All. $split = 1 + array_search( ( isset( $status_links['publish'] ) ? 'publish' : 'all' ), array_keys( $status_links ) ); $status_links = array_merge( array_slice( $status_links, 0, $split ), $sticky_link, array_slice( $status_links, $split ) ); } return $status_links; } function get_bulk_actions() { $actions = array(); if ( $this->is_trash ) $actions['untrash'] = __( 'Restore' ); else $actions['edit'] = __( 'Edit' ); if ( $this->is_trash || !EMPTY_TRASH_DAYS ) $actions['delete'] = __( 'Delete Permanently' ); else $actions['trash'] = __( 'Move to Trash' ); return $actions; } function extra_tablenav( $which ) { global $cat; ?> <div class="alignleft actions"> <?php if ( 'top' == $which && !is_singular() ) { $this->months_dropdown( $this->screen->post_type ); if ( is_object_in_taxonomy( $this->screen->post_type, 'category' ) ) { $dropdown_options = array( 'show_option_all' => __( 'View all categories' ), 'hide_empty' => 0, 'hierarchical' => 1, 'show_count' => 0, 'orderby' => 'name', 'selected' => $cat ); wp_dropdown_categories( $dropdown_options ); } do_action( 'restrict_manage_posts' ); submit_button( __( 'Filter' ), 'button', false, false, array( 'id' => 'post-query-submit' ) ); } if ( $this->is_trash && current_user_can( get_post_type_object( $this->screen->post_type )->cap->edit_others_posts ) ) { submit_button( __( 'Empty Trash' ), 'apply', 'delete_all', false ); } ?> </div> <?php } function current_action() { if ( isset( $_REQUEST['delete_all'] ) || isset( $_REQUEST['delete_all2'] ) ) return 'delete_all'; return parent::current_action(); } function pagination( $which ) { global $mode; parent::pagination( $which ); if ( 'top' == $which && ! is_post_type_hierarchical( $this->screen->post_type ) ) $this->view_switcher( $mode ); } function get_table_classes() { return array( 'widefat', 'fixed', is_post_type_hierarchical( $this->screen->post_type ) ? 'pages' : 'posts' ); } function get_columns() { $post_type = $this->screen->post_type; $posts_columns = array(); $posts_columns['cb'] = '<input type="checkbox" />'; /* translators: manage posts column name */ $posts_columns['title'] = _x( 'Title', 'column name' ); if ( post_type_supports( $post_type, 'author' ) ) $posts_columns['author'] = __( 'Author' ); $taxonomies = array(); $taxonomies = get_object_taxonomies( $post_type, 'objects' ); $taxonomies = wp_filter_object_list( $taxonomies, array( 'show_admin_column' => true ), 'and', 'name' ); $taxonomies = apply_filters( "manage_taxonomies_for_{$post_type}_columns", $taxonomies, $post_type ); $taxonomies = array_filter( $taxonomies, 'taxonomy_exists' ); foreach ( $taxonomies as $taxonomy ) { if ( 'category' == $taxonomy ) $column_key = 'categories'; elseif ( 'post_tag' == $taxonomy ) $column_key = 'tags'; else $column_key = 'taxonomy-' . $taxonomy; $posts_columns[ $column_key ] = get_taxonomy( $taxonomy )->labels->name; } $post_status = !empty( $_REQUEST['post_status'] ) ? $_REQUEST['post_status'] : 'all'; if ( post_type_supports( $post_type, 'comments' ) && !in_array( $post_status, array( 'pending', 'draft', 'future' ) ) ) $posts_columns['comments'] = '<span class="vers"><div title="' . esc_attr__( 'Comments' ) . '" class="comment-grey-bubble"></div></span>'; $posts_columns['date'] = __( 'Date' ); if ( 'page' == $post_type ) $posts_columns = apply_filters( 'manage_pages_columns', $posts_columns ); else $posts_columns = apply_filters( 'manage_posts_columns', $posts_columns, $post_type ); $posts_columns = apply_filters( "manage_{$post_type}_posts_columns", $posts_columns ); return $posts_columns; } function get_sortable_columns() { return array( 'title' => 'title', 'parent' => 'parent', 'comments' => 'comment_count', 'date' => array( 'date', true ) ); } function display_rows( $posts = array(), $level = 0 ) { global $wp_query, $per_page; if ( empty( $posts ) ) $posts = $wp_query->posts; add_filter( 'the_title', 'esc_html' ); if ( $this->hierarchical_display ) { $this->_display_rows_hierarchical( $posts, $this->get_pagenum(), $per_page ); } else { $this->_display_rows( $posts, $level ); } } function _display_rows( $posts, $level = 0 ) { global $mode; // Create array of post IDs. $post_ids = array(); foreach ( $posts as $a_post ) $post_ids[] = $a_post->ID; $this->comment_pending_count = get_pending_comments_num( $post_ids ); foreach ( $posts as $post ) $this->single_row( $post, $level ); } function _display_rows_hierarchical( $pages, $pagenum = 1, $per_page = 20 ) { global $wpdb; $level = 0; if ( ! $pages ) { $pages = get_pages( array( 'sort_column' => 'menu_order' ) ); if ( ! $pages ) return false; } /* * arrange pages into two parts: top level pages and children_pages * children_pages is two dimensional array, eg. * children_pages[10][] contains all sub-pages whose parent is 10. * It only takes O( N ) to arrange this and it takes O( 1 ) for subsequent lookup operations * If searching, ignore hierarchy and treat everything as top level */ if ( empty( $_REQUEST['s'] ) ) { $top_level_pages = array(); $children_pages = array(); foreach ( $pages as $page ) { // catch and repair bad pages if ( $page->post_parent == $page->ID ) { $page->post_parent = 0; $wpdb->update( $wpdb->posts, array( 'post_parent' => 0 ), array( 'ID' => $page->ID ) ); clean_post_cache( $page ); } if ( 0 == $page->post_parent ) $top_level_pages[] = $page; else $children_pages[ $page->post_parent ][] = $page; } $pages = &$top_level_pages; } $count = 0; $start = ( $pagenum - 1 ) * $per_page; $end = $start + $per_page; foreach ( $pages as $page ) { if ( $count >= $end ) break; if ( $count >= $start ) echo "\t" . $this->single_row( $page, $level ); $count++; if ( isset( $children_pages ) ) $this->_page_rows( $children_pages, $count, $page->ID, $level + 1, $pagenum, $per_page ); } // if it is the last pagenum and there are orphaned pages, display them with paging as well if ( isset( $children_pages ) && $count < $end ){ foreach ( $children_pages as $orphans ){ foreach ( $orphans as $op ) { if ( $count >= $end ) break; if ( $count >= $start ) echo "\t" . $this->single_row( $op, 0 ); $count++; } } } } /** * Given a top level page ID, display the nested hierarchy of sub-pages * together with paging support * * @since 3.1.0 (Standalone function exists since 2.6.0) * * @param unknown_type $children_pages * @param unknown_type $count * @param unknown_type $parent * @param unknown_type $level * @param unknown_type $pagenum * @param unknown_type $per_page */ function _page_rows( &$children_pages, &$count, $parent, $level, $pagenum, $per_page ) { if ( ! isset( $children_pages[$parent] ) ) return; $start = ( $pagenum - 1 ) * $per_page; $end = $start + $per_page; foreach ( $children_pages[$parent] as $page ) { if ( $count >= $end ) break; // If the page starts in a subtree, print the parents. if ( $count == $start && $page->post_parent > 0 ) { $my_parents = array(); $my_parent = $page->post_parent; while ( $my_parent ) { $my_parent = get_post( $my_parent ); $my_parents[] = $my_parent; if ( !$my_parent->post_parent ) break; $my_parent = $my_parent->post_parent; } $num_parents = count( $my_parents ); while ( $my_parent = array_pop( $my_parents ) ) { echo "\t" . $this->single_row( $my_parent, $level - $num_parents ); $num_parents--; } } if ( $count >= $start ) echo "\t" . $this->single_row( $page, $level ); $count++; $this->_page_rows( $children_pages, $count, $page->ID, $level + 1, $pagenum, $per_page ); } unset( $children_pages[$parent] ); //required in order to keep track of orphans } function single_row( $post, $level = 0 ) { global $mode; static $alternate; $global_post = get_post(); $GLOBALS['post'] = $post; setup_postdata( $post ); $edit_link = get_edit_post_link( $post->ID ); $title = _draft_or_post_title(); $post_type_object = get_post_type_object( $post->post_type ); $can_edit_post = current_user_can( $post_type_object->cap->edit_post, $post->ID ); $alternate = 'alternate' == $alternate ? '' : 'alternate'; $classes = $alternate . ' iedit author-' . ( get_current_user_id() == $post->post_author ? 'self' : 'other' ); ?> <tr id="post-<?php echo $post->ID; ?>" class="<?php echo implode( ' ', get_post_class( $classes, $post->ID ) ); ?>" valign="top"> <?php list( $columns, $hidden ) = $this->get_column_info(); foreach ( $columns as $column_name => $column_display_name ) { $class = "class=\"$column_name column-$column_name\""; $style = ''; if ( in_array( $column_name, $hidden ) ) $style = ' style="display:none;"'; $attributes = "$class$style"; switch ( $column_name ) { case 'cb': ?> <th scope="row" class="check-column"> <?php if ( $can_edit_post ) { ?> <label class="screen-reader-text" for="cb-select-<?php the_ID(); ?>"><?php printf( __( 'Select %s' ), $title ); ?></label> <input id="cb-select-<?php the_ID(); ?>" type="checkbox" name="post[]" value="<?php the_ID(); ?>" /> <?php } ?> </th> <?php break; case 'title': if ( $this->hierarchical_display ) { $attributes = 'class="post-title page-title column-title"' . $style; if ( 0 == $level && (int) $post->post_parent > 0 ) { //sent level 0 by accident, by default, or because we don't know the actual level $find_main_page = (int) $post->post_parent; while ( $find_main_page > 0 ) { $parent = get_post( $find_main_page ); if ( is_null( $parent ) ) break; $level++; $find_main_page = (int) $parent->post_parent; if ( !isset( $parent_name ) ) $parent_name = apply_filters( 'the_title', $parent->post_title, $parent->ID ); } } $pad = str_repeat( '&#8212; ', $level ); ?> <td <?php echo $attributes ?>><strong><?php if ( $can_edit_post && $post->post_status != 'trash' ) { ?><a class="row-title" href="<?php echo $edit_link; ?>" title="<?php echo esc_attr( sprintf( __( 'Edit &#8220;%s&#8221;' ), $title ) ); ?>"><?php echo $pad; echo $title ?></a><?php } else { echo $pad; echo $title; }; _post_states( $post ); echo isset( $parent_name ) ? ' | ' . $post_type_object->labels->parent_item_colon . ' ' . esc_html( $parent_name ) : ''; ?></strong> <?php } else { $attributes = 'class="post-title page-title column-title"' . $style; $pad = str_repeat( '&#8212; ', $level ); ?> <td <?php echo $attributes ?>><strong><?php if ( $can_edit_post && $post->post_status != 'trash' ) { ?><a class="row-title" href="<?php echo $edit_link; ?>" title="<?php echo esc_attr( sprintf( __( 'Edit &#8220;%s&#8221;' ), $title ) ); ?>"><?php echo $pad; echo $title ?></a><?php } else { echo $pad; echo $title; }; _post_states( $post ); ?></strong> <?php if ( 'excerpt' == $mode && current_user_can( 'read_post', $post->ID ) ) the_excerpt(); } $actions = array(); if ( $can_edit_post && 'trash' != $post->post_status ) { $actions['edit'] = '<a href="' . get_edit_post_link( $post->ID, true ) . '" title="' . esc_attr( __( 'Edit this item' ) ) . '">' . __( 'Edit' ) . '</a>'; $actions['inline hide-if-no-js'] = '<a href="#" class="editinline" title="' . esc_attr( __( 'Edit this item inline' ) ) . '">' . __( 'Quick&nbsp;Edit' ) . '</a>'; } if ( current_user_can( $post_type_object->cap->delete_post, $post->ID ) ) { if ( 'trash' == $post->post_status ) $actions['untrash'] = "<a title='" . esc_attr( __( 'Restore this item from the Trash' ) ) . "' href='" . wp_nonce_url( admin_url( sprintf( $post_type_object->_edit_link . '&amp;action=untrash', $post->ID ) ), 'untrash-post_' . $post->ID ) . "'>" . __( 'Restore' ) . "</a>"; elseif ( EMPTY_TRASH_DAYS ) $actions['trash'] = "<a class='submitdelete' title='" . esc_attr( __( 'Move this item to the Trash' ) ) . "' href='" . get_delete_post_link( $post->ID ) . "'>" . __( 'Trash' ) . "</a>"; if ( 'trash' == $post->post_status || !EMPTY_TRASH_DAYS ) $actions['delete'] = "<a class='submitdelete' title='" . esc_attr( __( 'Delete this item permanently' ) ) . "' href='" . get_delete_post_link( $post->ID, '', true ) . "'>" . __( 'Delete Permanently' ) . "</a>"; } if ( $post_type_object->public ) { if ( in_array( $post->post_status, array( 'pending', 'draft', 'future' ) ) ) { if ( $can_edit_post ) $actions['view'] = '<a href="' . esc_url( add_query_arg( 'preview', 'true', get_permalink( $post->ID ) ) ) . '" title="' . esc_attr( sprintf( __( 'Preview &#8220;%s&#8221;' ), $title ) ) . '" rel="permalink">' . __( 'Preview' ) . '</a>'; } elseif ( 'trash' != $post->post_status ) { $actions['view'] = '<a href="' . get_permalink( $post->ID ) . '" title="' . esc_attr( sprintf( __( 'View &#8220;%s&#8221;' ), $title ) ) . '" rel="permalink">' . __( 'View' ) . '</a>'; } } $actions = apply_filters( is_post_type_hierarchical( $post->post_type ) ? 'page_row_actions' : 'post_row_actions', $actions, $post ); echo $this->row_actions( $actions ); get_inline_data( $post ); echo '</td>'; break; case 'date': if ( '0000-00-00 00:00:00' == $post->post_date ) { $t_time = $h_time = __( 'Unpublished' ); $time_diff = 0; } else { $t_time = get_the_time( __( 'Y/m/d g:i:s A' ) ); $m_time = $post->post_date; $time = get_post_time( 'G', true, $post ); $time_diff = time() - $time; if ( $time_diff > 0 && $time_diff < DAY_IN_SECONDS ) $h_time = sprintf( __( '%s ago' ), human_time_diff( $time ) ); else $h_time = mysql2date( __( 'Y/m/d' ), $m_time ); } echo '<td ' . $attributes . '>'; if ( 'excerpt' == $mode ) echo apply_filters( 'post_date_column_time', $t_time, $post, $column_name, $mode ); else echo '<abbr title="' . $t_time . '">' . apply_filters( 'post_date_column_time', $h_time, $post, $column_name, $mode ) . '</abbr>'; echo '<br />'; if ( 'publish' == $post->post_status ) { _e( 'Published' ); } elseif ( 'future' == $post->post_status ) { if ( $time_diff > 0 ) echo '<strong class="attention">' . __( 'Missed schedule' ) . '</strong>'; else _e( 'Scheduled' ); } else { _e( 'Last Modified' ); } echo '</td>'; break; case 'comments': ?> <td <?php echo $attributes ?>><div class="post-com-count-wrapper"> <?php $pending_comments = isset( $this->comment_pending_count[$post->ID] ) ? $this->comment_pending_count[$post->ID] : 0; $this->comments_bubble( $post->ID, $pending_comments ); ?> </div></td> <?php break; case 'author': ?> <td <?php echo $attributes ?>><?php printf( '<a href="%s">%s</a>', esc_url( add_query_arg( array( 'post_type' => $post->post_type, 'author' => get_the_author_meta( 'ID' ) ), 'edit.php' )), get_the_author() ); ?></td> <?php break; default: if ( 'categories' == $column_name ) $taxonomy = 'category'; elseif ( 'tags' == $column_name ) $taxonomy = 'post_tag'; elseif ( 0 === strpos( $column_name, 'taxonomy-' ) ) $taxonomy = substr( $column_name, 9 ); else $taxonomy = false; if ( $taxonomy ) { $taxonomy_object = get_taxonomy( $taxonomy ); echo '<td ' . $attributes . '>'; if ( $terms = get_the_terms( $post->ID, $taxonomy ) ) { $out = array(); foreach ( $terms as $t ) { $posts_in_term_qv = array(); if ( 'post' != $post->post_type ) $posts_in_term_qv['post_type'] = $post->post_type; if ( $taxonomy_object->query_var ) { $posts_in_term_qv[ $taxonomy_object->query_var ] = $t->slug; } else { $posts_in_term_qv['taxonomy'] = $taxonomy; $posts_in_term_qv['term'] = $t->slug; } $out[] = sprintf( '<a href="%s">%s</a>', esc_url( add_query_arg( $posts_in_term_qv, 'edit.php' ) ), esc_html( sanitize_term_field( 'name', $t->name, $t->term_id, $taxonomy, 'display' ) ) ); } /* translators: used between list items, there is a space after the comma */ echo join( __( ', ' ), $out ); } else { echo '&#8212;'; } echo '</td>'; break; } ?> <td <?php echo $attributes ?>><?php if ( is_post_type_hierarchical( $post->post_type ) ) do_action( 'manage_pages_custom_column', $column_name, $post->ID ); else do_action( 'manage_posts_custom_column', $column_name, $post->ID ); do_action( "manage_{$post->post_type}_posts_custom_column", $column_name, $post->ID ); ?></td> <?php break; } } ?> </tr> <?php $GLOBALS['post'] = $global_post; } /** * Outputs the hidden row displayed when inline editing * * @since 3.1.0 */ function inline_edit() { global $mode; $screen = $this->screen; $post = get_default_post_to_edit( $screen->post_type ); $post_type_object = get_post_type_object( $screen->post_type ); $taxonomy_names = get_object_taxonomies( $screen->post_type ); $hierarchical_taxonomies = array(); $flat_taxonomies = array(); foreach ( $taxonomy_names as $taxonomy_name ) { $taxonomy = get_taxonomy( $taxonomy_name ); if ( !$taxonomy->show_ui ) continue; if ( $taxonomy->hierarchical ) $hierarchical_taxonomies[] = $taxonomy; else $flat_taxonomies[] = $taxonomy; } $m = ( isset( $mode ) && 'excerpt' == $mode ) ? 'excerpt' : 'list'; $can_publish = current_user_can( $post_type_object->cap->publish_posts ); $core_columns = array( 'cb' => true, 'date' => true, 'title' => true, 'categories' => true, 'tags' => true, 'comments' => true, 'author' => true ); ?> <form method="get" action=""><table style="display: none"><tbody id="inlineedit"> <?php $hclass = count( $hierarchical_taxonomies ) ? 'post' : 'page'; $bulk = 0; while ( $bulk < 2 ) { ?> <tr id="<?php echo $bulk ? 'bulk-edit' : 'inline-edit'; ?>" class="inline-edit-row inline-edit-row-<?php echo "$hclass inline-edit-" . $screen->post_type; echo $bulk ? " bulk-edit-row bulk-edit-row-$hclass bulk-edit-{$screen->post_type}" : " quick-edit-row quick-edit-row-$hclass inline-edit-{$screen->post_type}"; ?>" style="display: none"><td colspan="<?php echo $this->get_column_count(); ?>" class="colspanchange"> <fieldset class="inline-edit-col-left"><div class="inline-edit-col"> <h4><?php echo $bulk ? __( 'Bulk Edit' ) : __( 'Quick Edit' ); ?></h4> <?php if ( post_type_supports( $screen->post_type, 'title' ) ) : if ( $bulk ) : ?> <div id="bulk-title-div"> <div id="bulk-titles"></div> </div> <?php else : // $bulk ?> <label> <span class="title"><?php _e( 'Title' ); ?></span> <span class="input-text-wrap"><input type="text" name="post_title" class="ptitle" value="" /></span> </label> <label> <span class="title"><?php _e( 'Slug' ); ?></span> <span class="input-text-wrap"><input type="text" name="post_name" value="" /></span> </label> <?php endif; // $bulk endif; // post_type_supports title ?> <?php if ( !$bulk ) : ?> <label><span class="title"><?php _e( 'Date' ); ?></span></label> <div class="inline-edit-date"> <?php touch_time( 1, 1, 0, 1 ); ?> </div> <br class="clear" /> <?php endif; // $bulk if ( post_type_supports( $screen->post_type, 'author' ) ) : $authors_dropdown = ''; if ( is_super_admin() || current_user_can( $post_type_object->cap->edit_others_posts ) ) : $users_opt = array( 'hide_if_only_one_author' => false, 'who' => 'authors', 'name' => 'post_author', 'class'=> 'authors', 'multi' => 1, 'echo' => 0 ); if ( $bulk ) $users_opt['show_option_none'] = __( '&mdash; No Change &mdash;' ); if ( $authors = wp_dropdown_users( $users_opt ) ) : $authors_dropdown = '<label class="inline-edit-author">'; $authors_dropdown .= '<span class="title">' . __( 'Author' ) . '</span>'; $authors_dropdown .= $authors; $authors_dropdown .= '</label>'; endif; endif; // authors ?> <?php if ( !$bulk ) echo $authors_dropdown; endif; // post_type_supports author if ( !$bulk ) : ?> <div class="inline-edit-group"> <label class="alignleft"> <span class="title"><?php _e( 'Password' ); ?></span> <span class="input-text-wrap"><input type="text" name="post_password" class="inline-edit-password-input" value="" /></span> </label> <em style="margin:5px 10px 0 0" class="alignleft"> <?php /* translators: Between password field and private checkbox on post quick edit interface */ echo __( '&ndash;OR&ndash;' ); ?> </em> <label class="alignleft inline-edit-private"> <input type="checkbox" name="keep_private" value="private" /> <span class="checkbox-title"><?php echo __( 'Private' ); ?></span> </label> </div> <?php endif; ?> </div></fieldset> <?php if ( count( $hierarchical_taxonomies ) && !$bulk ) : ?> <fieldset class="inline-edit-col-center inline-edit-categories"><div class="inline-edit-col"> <?php foreach ( $hierarchical_taxonomies as $taxonomy ) : ?> <span class="title inline-edit-categories-label"><?php echo esc_html( $taxonomy->labels->name ) ?> <span class="catshow"><?php _e( '[more]' ); ?></span> <span class="cathide" style="display:none;"><?php _e( '[less]' ); ?></span> </span> <input type="hidden" name="<?php echo ( $taxonomy->name == 'category' ) ? 'post_category[]' : 'tax_input[' . esc_attr( $taxonomy->name ) . '][]'; ?>" value="0" /> <ul class="cat-checklist <?php echo esc_attr( $taxonomy->name )?>-checklist"> <?php wp_terms_checklist( null, array( 'taxonomy' => $taxonomy->name ) ) ?> </ul> <?php endforeach; //$hierarchical_taxonomies as $taxonomy ?> </div></fieldset> <?php endif; // count( $hierarchical_taxonomies ) && !$bulk ?> <fieldset class="inline-edit-col-right"><div class="inline-edit-col"> <?php if ( post_type_supports( $screen->post_type, 'author' ) && $bulk ) echo $authors_dropdown; if ( post_type_supports( $screen->post_type, 'page-attributes' ) ) : if ( $post_type_object->hierarchical ) : ?> <label> <span class="title"><?php _e( 'Parent' ); ?></span> <?php $dropdown_args = array( 'post_type' => $post_type_object->name, 'selected' => $post->post_parent, 'name' => 'post_parent', 'show_option_none' => __( 'Main Page (no parent)' ), 'option_none_value' => 0, 'sort_column' => 'menu_order, post_title', ); if ( $bulk ) $dropdown_args['show_option_no_change'] = __( '&mdash; No Change &mdash;' ); $dropdown_args = apply_filters( 'quick_edit_dropdown_pages_args', $dropdown_args ); wp_dropdown_pages( $dropdown_args ); ?> </label> <?php endif; // hierarchical if ( !$bulk ) : ?> <label> <span class="title"><?php _e( 'Order' ); ?></span> <span class="input-text-wrap"><input type="text" name="menu_order" class="inline-edit-menu-order-input" value="<?php echo $post->menu_order ?>" /></span> </label> <?php endif; // !$bulk if ( 'page' == $screen->post_type ) : ?> <label> <span class="title"><?php _e( 'Template' ); ?></span> <select name="page_template"> <?php if ( $bulk ) : ?> <option value="-1"><?php _e( '&mdash; No Change &mdash;' ); ?></option> <?php endif; // $bulk ?> <option value="default"><?php _e( 'Default Template' ); ?></option> <?php page_template_dropdown() ?> </select> </label> <?php endif; // page post_type endif; // page-attributes ?> <?php if ( count( $flat_taxonomies ) && !$bulk ) : ?> <?php foreach ( $flat_taxonomies as $taxonomy ) : ?> <?php if ( current_user_can( $taxonomy->cap->assign_terms ) ) : ?> <label class="inline-edit-tags"> <span class="title"><?php echo esc_html( $taxonomy->labels->name ) ?></span> <textarea cols="22" rows="1" name="tax_input[<?php echo esc_attr( $taxonomy->name )?>]" class="tax_input_<?php echo esc_attr( $taxonomy->name )?>"></textarea> </label> <?php endif; ?> <?php endforeach; //$flat_taxonomies as $taxonomy ?> <?php endif; // count( $flat_taxonomies ) && !$bulk ?> <?php if ( post_type_supports( $screen->post_type, 'comments' ) || post_type_supports( $screen->post_type, 'trackbacks' ) ) : if ( $bulk ) : ?> <div class="inline-edit-group"> <?php if ( post_type_supports( $screen->post_type, 'comments' ) ) : ?> <label class="alignleft"> <span class="title"><?php _e( 'Comments' ); ?></span> <select name="comment_status"> <option value=""><?php _e( '&mdash; No Change &mdash;' ); ?></option> <option value="open"><?php _e( 'Allow' ); ?></option> <option value="closed"><?php _e( 'Do not allow' ); ?></option> </select> </label> <?php endif; if ( post_type_supports( $screen->post_type, 'trackbacks' ) ) : ?> <label class="alignright"> <span class="title"><?php _e( 'Pings' ); ?></span> <select name="ping_status"> <option value=""><?php _e( '&mdash; No Change &mdash;' ); ?></option> <option value="open"><?php _e( 'Allow' ); ?></option> <option value="closed"><?php _e( 'Do not allow' ); ?></option> </select> </label> <?php endif; ?> </div> <?php else : // $bulk ?> <div class="inline-edit-group"> <?php if ( post_type_supports( $screen->post_type, 'comments' ) ) : ?> <label class="alignleft"> <input type="checkbox" name="comment_status" value="open" /> <span class="checkbox-title"><?php _e( 'Allow Comments' ); ?></span> </label> <?php endif; if ( post_type_supports( $screen->post_type, 'trackbacks' ) ) : ?> <label class="alignleft"> <input type="checkbox" name="ping_status" value="open" /> <span class="checkbox-title"><?php _e( 'Allow Pings' ); ?></span> </label> <?php endif; ?> </div> <?php endif; // $bulk endif; // post_type_supports comments or pings ?> <div class="inline-edit-group"> <label class="inline-edit-status alignleft"> <span class="title"><?php _e( 'Status' ); ?></span> <select name="_status"> <?php if ( $bulk ) : ?> <option value="-1"><?php _e( '&mdash; No Change &mdash;' ); ?></option> <?php endif; // $bulk ?> <?php if ( $can_publish ) : // Contributors only get "Unpublished" and "Pending Review" ?> <option value="publish"><?php _e( 'Published' ); ?></option> <option value="future"><?php _e( 'Scheduled' ); ?></option> <?php if ( $bulk ) : ?> <option value="private"><?php _e( 'Private' ) ?></option> <?php endif; // $bulk ?> <?php endif; ?> <option value="pending"><?php _e( 'Pending Review' ); ?></option> <option value="draft"><?php _e( 'Draft' ); ?></option> </select> </label> <?php if ( 'post' == $screen->post_type && $can_publish && current_user_can( $post_type_object->cap->edit_others_posts ) ) : ?> <?php if ( $bulk ) : ?> <label class="alignright"> <span class="title"><?php _e( 'Sticky' ); ?></span> <select name="sticky"> <option value="-1"><?php _e( '&mdash; No Change &mdash;' ); ?></option> <option value="sticky"><?php _e( 'Sticky' ); ?></option> <option value="unsticky"><?php _e( 'Not Sticky' ); ?></option> </select> </label> <?php else : // $bulk ?> <label class="alignleft"> <input type="checkbox" name="sticky" value="sticky" /> <span class="checkbox-title"><?php _e( 'Make this post sticky' ); ?></span> </label> <?php endif; // $bulk ?> <?php endif; // 'post' && $can_publish && current_user_can( 'edit_others_cap' ) ?> </div> <?php if ( post_type_supports( $screen->post_type, 'post-formats' ) && current_theme_supports( 'post-formats' ) ) : $post_formats = get_theme_support( 'post-formats' ); if ( isset( $post_formats[0] ) && is_array( $post_formats[0] ) ) : $all_post_formats = get_post_format_strings(); unset( $all_post_formats['standard'] ); ?> <div class="inline-edit-group"> <label class="alignleft" for="post_format"> <span class="title"><?php _ex( 'Format', 'post format' ); ?></span> <select name="post_format"> <?php if ( $bulk ) : ?> <option value="-1"><?php _e( '&mdash; No Change &mdash;' ); ?></option> <?php endif; ?> <option value="0"><?php _ex( 'Standard', 'Post format' ); ?></option> <?php foreach ( $all_post_formats as $slug => $format ) : $unsupported = ! in_array( $slug, $post_formats[0] ); if ( $bulk && $unsupported ) continue; ?> <option value="<?php echo esc_attr( $slug ); ?>"<?php if ( $unsupported ) echo ' class="unsupported"'; ?>><?php echo esc_html( $format ); ?></option> <?php endforeach; ?> </select></label> </div> <?php endif; ?> <?php endif; // post-formats ?> </div></fieldset> <?php list( $columns ) = $this->get_column_info(); foreach ( $columns as $column_name => $column_display_name ) { if ( isset( $core_columns[$column_name] ) ) continue; do_action( $bulk ? 'bulk_edit_custom_box' : 'quick_edit_custom_box', $column_name, $screen->post_type ); } ?> <p class="submit inline-edit-save"> <a accesskey="c" href="#inline-edit" title="<?php esc_attr_e( 'Cancel' ); ?>" class="button-secondary cancel alignleft"><?php _e( 'Cancel' ); ?></a> <?php if ( ! $bulk ) { wp_nonce_field( 'inlineeditnonce', '_inline_edit', false ); $update_text = __( 'Update' ); ?> <a accesskey="s" href="#inline-edit" title="<?php esc_attr_e( 'Update' ); ?>" class="button-primary save alignright"><?php echo esc_attr( $update_text ); ?></a> <span class="spinner"></span> <?php } else { submit_button( __( 'Update' ), 'button-primary alignright', 'bulk_edit', false, array( 'accesskey' => 's' ) ); } ?> <input type="hidden" name="post_view" value="<?php echo esc_attr( $m ); ?>" /> <input type="hidden" name="screen" value="<?php echo esc_attr( $screen->id ); ?>" /> <span class="error" style="display:none"></span> <br class="clear" /> </p> </td></tr> <?php $bulk++; } ?> </tbody></table></form> <?php } }
zyblog
trunk/zyblog/wp-admin/includes/class-wp-posts-list-table.php
PHP
asf20
36,573
<?php /** * A File upgrader class for WordPress. * * This set of classes are designed to be used to upgrade/install a local set of files on the filesystem via the Filesystem Abstraction classes. * * @link http://trac.wordpress.org/ticket/7875 consolidate plugin/theme/core upgrade/install functions * * @package WordPress * @subpackage Upgrader * @since 2.8.0 */ /** * WordPress Upgrader class for Upgrading/Installing a local set of files via the Filesystem Abstraction classes from a Zip file. * * @TODO More Detailed docs, for methods as well. * * @package WordPress * @subpackage Upgrader * @since 2.8.0 */ class WP_Upgrader { var $strings = array(); var $skin = null; var $result = array(); function __construct($skin = null) { if ( null == $skin ) $this->skin = new WP_Upgrader_Skin(); else $this->skin = $skin; } function init() { $this->skin->set_upgrader($this); $this->generic_strings(); } function generic_strings() { $this->strings['bad_request'] = __('Invalid Data provided.'); $this->strings['fs_unavailable'] = __('Could not access filesystem.'); $this->strings['fs_error'] = __('Filesystem error.'); $this->strings['fs_no_root_dir'] = __('Unable to locate WordPress Root directory.'); $this->strings['fs_no_content_dir'] = __('Unable to locate WordPress Content directory (wp-content).'); $this->strings['fs_no_plugins_dir'] = __('Unable to locate WordPress Plugin directory.'); $this->strings['fs_no_themes_dir'] = __('Unable to locate WordPress Theme directory.'); /* translators: %s: directory name */ $this->strings['fs_no_folder'] = __('Unable to locate needed folder (%s).'); $this->strings['download_failed'] = __('Download failed.'); $this->strings['installing_package'] = __('Installing the latest version&#8230;'); $this->strings['folder_exists'] = __('Destination folder already exists.'); $this->strings['mkdir_failed'] = __('Could not create directory.'); $this->strings['incompatible_archive'] = __('The package could not be installed.'); $this->strings['maintenance_start'] = __('Enabling Maintenance mode&#8230;'); $this->strings['maintenance_end'] = __('Disabling Maintenance mode&#8230;'); } function fs_connect( $directories = array() ) { global $wp_filesystem; if ( false === ($credentials = $this->skin->request_filesystem_credentials()) ) return false; if ( ! WP_Filesystem($credentials) ) { $error = true; if ( is_object($wp_filesystem) && $wp_filesystem->errors->get_error_code() ) $error = $wp_filesystem->errors; $this->skin->request_filesystem_credentials($error); //Failed to connect, Error and request again return false; } if ( ! is_object($wp_filesystem) ) return new WP_Error('fs_unavailable', $this->strings['fs_unavailable'] ); if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() ) return new WP_Error('fs_error', $this->strings['fs_error'], $wp_filesystem->errors); foreach ( (array)$directories as $dir ) { switch ( $dir ) { case ABSPATH: if ( ! $wp_filesystem->abspath() ) return new WP_Error('fs_no_root_dir', $this->strings['fs_no_root_dir']); break; case WP_CONTENT_DIR: if ( ! $wp_filesystem->wp_content_dir() ) return new WP_Error('fs_no_content_dir', $this->strings['fs_no_content_dir']); break; case WP_PLUGIN_DIR: if ( ! $wp_filesystem->wp_plugins_dir() ) return new WP_Error('fs_no_plugins_dir', $this->strings['fs_no_plugins_dir']); break; case WP_CONTENT_DIR . '/themes': if ( ! $wp_filesystem->find_folder(WP_CONTENT_DIR . '/themes') ) return new WP_Error('fs_no_themes_dir', $this->strings['fs_no_themes_dir']); break; default: if ( ! $wp_filesystem->find_folder($dir) ) return new WP_Error('fs_no_folder', sprintf($this->strings['fs_no_folder'], $dir)); break; } } return true; } //end fs_connect(); function download_package($package) { if ( ! preg_match('!^(http|https|ftp)://!i', $package) && file_exists($package) ) //Local file or remote? return $package; //must be a local file.. if ( empty($package) ) return new WP_Error('no_package', $this->strings['no_package']); $this->skin->feedback('downloading_package', $package); $download_file = download_url($package); if ( is_wp_error($download_file) ) return new WP_Error('download_failed', $this->strings['download_failed'], $download_file->get_error_message()); return $download_file; } function unpack_package($package, $delete_package = true) { global $wp_filesystem; $this->skin->feedback('unpack_package'); $upgrade_folder = $wp_filesystem->wp_content_dir() . 'upgrade/'; //Clean up contents of upgrade directory beforehand. $upgrade_files = $wp_filesystem->dirlist($upgrade_folder); if ( !empty($upgrade_files) ) { foreach ( $upgrade_files as $file ) $wp_filesystem->delete($upgrade_folder . $file['name'], true); } //We need a working directory $working_dir = $upgrade_folder . basename($package, '.zip'); // Clean up working directory if ( $wp_filesystem->is_dir($working_dir) ) $wp_filesystem->delete($working_dir, true); // Unzip package to working directory $result = unzip_file($package, $working_dir); //TODO optimizations, Copy when Move/Rename would suffice? // Once extracted, delete the package if required. if ( $delete_package ) unlink($package); if ( is_wp_error($result) ) { $wp_filesystem->delete($working_dir, true); if ( 'incompatible_archive' == $result->get_error_code() ) { return new WP_Error( 'incompatible_archive', $this->strings['incompatible_archive'], $result->get_error_data() ); } return $result; } return $working_dir; } function install_package($args = array()) { global $wp_filesystem; $defaults = array( 'source' => '', 'destination' => '', //Please always pass these 'clear_destination' => false, 'clear_working' => false, 'hook_extra' => array()); $args = wp_parse_args($args, $defaults); extract($args); @set_time_limit( 300 ); if ( empty($source) || empty($destination) ) return new WP_Error('bad_request', $this->strings['bad_request']); $this->skin->feedback('installing_package'); $res = apply_filters('upgrader_pre_install', true, $hook_extra); if ( is_wp_error($res) ) return $res; //Retain the Original source and destinations $remote_source = $source; $local_destination = $destination; $source_files = array_keys( $wp_filesystem->dirlist($remote_source) ); $remote_destination = $wp_filesystem->find_folder($local_destination); //Locate which directory to copy to the new folder, This is based on the actual folder holding the files. if ( 1 == count($source_files) && $wp_filesystem->is_dir( trailingslashit($source) . $source_files[0] . '/') ) //Only one folder? Then we want its contents. $source = trailingslashit($source) . trailingslashit($source_files[0]); elseif ( count($source_files) == 0 ) return new WP_Error( 'incompatible_archive', $this->strings['incompatible_archive'], __( 'The plugin contains no files.' ) ); //There are no files? else //Its only a single file, The upgrader will use the foldername of this file as the destination folder. foldername is based on zip filename. $source = trailingslashit($source); //Hook ability to change the source file location.. $source = apply_filters('upgrader_source_selection', $source, $remote_source, $this); if ( is_wp_error($source) ) return $source; //Has the source location changed? If so, we need a new source_files list. if ( $source !== $remote_source ) $source_files = array_keys( $wp_filesystem->dirlist($source) ); //Protection against deleting files in any important base directories. if ( in_array( $destination, array(ABSPATH, WP_CONTENT_DIR, WP_PLUGIN_DIR, WP_CONTENT_DIR . '/themes') ) ) { $remote_destination = trailingslashit($remote_destination) . trailingslashit(basename($source)); $destination = trailingslashit($destination) . trailingslashit(basename($source)); } if ( $clear_destination ) { //We're going to clear the destination if there's something there $this->skin->feedback('remove_old'); $removed = true; if ( $wp_filesystem->exists($remote_destination) ) $removed = $wp_filesystem->delete($remote_destination, true); $removed = apply_filters('upgrader_clear_destination', $removed, $local_destination, $remote_destination, $hook_extra); if ( is_wp_error($removed) ) return $removed; else if ( ! $removed ) return new WP_Error('remove_old_failed', $this->strings['remove_old_failed']); } elseif ( $wp_filesystem->exists($remote_destination) ) { //If we're not clearing the destination folder and something exists there already, Bail. //But first check to see if there are actually any files in the folder. $_files = $wp_filesystem->dirlist($remote_destination); if ( ! empty($_files) ) { $wp_filesystem->delete($remote_source, true); //Clear out the source files. return new WP_Error('folder_exists', $this->strings['folder_exists'], $remote_destination ); } } //Create destination if needed if ( !$wp_filesystem->exists($remote_destination) ) if ( !$wp_filesystem->mkdir($remote_destination, FS_CHMOD_DIR) ) return new WP_Error('mkdir_failed', $this->strings['mkdir_failed'], $remote_destination); // Copy new version of item into place. $result = copy_dir($source, $remote_destination); if ( is_wp_error($result) ) { if ( $clear_working ) $wp_filesystem->delete($remote_source, true); return $result; } //Clear the Working folder? if ( $clear_working ) $wp_filesystem->delete($remote_source, true); $destination_name = basename( str_replace($local_destination, '', $destination) ); if ( '.' == $destination_name ) $destination_name = ''; $this->result = compact('local_source', 'source', 'source_name', 'source_files', 'destination', 'destination_name', 'local_destination', 'remote_destination', 'clear_destination', 'delete_source_dir'); $res = apply_filters('upgrader_post_install', true, $hook_extra, $this->result); if ( is_wp_error($res) ) { $this->result = $res; return $res; } //Bombard the calling function will all the info which we've just used. return $this->result; } function run($options) { $defaults = array( 'package' => '', //Please always pass this. 'destination' => '', //And this 'clear_destination' => false, 'clear_working' => true, 'is_multi' => false, 'hook_extra' => array() //Pass any extra $hook_extra args here, this will be passed to any hooked filters. ); $options = wp_parse_args($options, $defaults); extract($options); //Connect to the Filesystem first. $res = $this->fs_connect( array(WP_CONTENT_DIR, $destination) ); if ( ! $res ) //Mainly for non-connected filesystem. return false; if ( is_wp_error($res) ) { $this->skin->error($res); return $res; } if ( !$is_multi ) // call $this->header separately if running multiple times $this->skin->header(); $this->skin->before(); //Download the package (Note, This just returns the filename of the file if the package is a local file) $download = $this->download_package( $package ); if ( is_wp_error($download) ) { $this->skin->error($download); $this->skin->after(); return $download; } $delete_package = ($download != $package); // Do not delete a "local" file //Unzips the file into a temporary directory $working_dir = $this->unpack_package( $download, $delete_package ); if ( is_wp_error($working_dir) ) { $this->skin->error($working_dir); $this->skin->after(); return $working_dir; } //With the given options, this installs it to the destination directory. $result = $this->install_package( array( 'source' => $working_dir, 'destination' => $destination, 'clear_destination' => $clear_destination, 'clear_working' => $clear_working, 'hook_extra' => $hook_extra ) ); $this->skin->set_result($result); if ( is_wp_error($result) ) { $this->skin->error($result); $this->skin->feedback('process_failed'); } else { //Install Succeeded $this->skin->feedback('process_success'); } $this->skin->after(); if ( !$is_multi ) $this->skin->footer(); return $result; } function maintenance_mode($enable = false) { global $wp_filesystem; $file = $wp_filesystem->abspath() . '.maintenance'; if ( $enable ) { $this->skin->feedback('maintenance_start'); // Create maintenance file to signal that we are upgrading $maintenance_string = '<?php $upgrading = ' . time() . '; ?>'; $wp_filesystem->delete($file); $wp_filesystem->put_contents($file, $maintenance_string, FS_CHMOD_FILE); } else if ( !$enable && $wp_filesystem->exists($file) ) { $this->skin->feedback('maintenance_end'); $wp_filesystem->delete($file); } } } /** * Plugin Upgrader class for WordPress Plugins, It is designed to upgrade/install plugins from a local zip, remote zip URL, or uploaded zip file. * * @TODO More Detailed docs, for methods as well. * * @package WordPress * @subpackage Upgrader * @since 2.8.0 */ class Plugin_Upgrader extends WP_Upgrader { var $result; var $bulk = false; var $show_before = ''; function upgrade_strings() { $this->strings['up_to_date'] = __('The plugin is at the latest version.'); $this->strings['no_package'] = __('Update package not available.'); $this->strings['downloading_package'] = __('Downloading update from <span class="code">%s</span>&#8230;'); $this->strings['unpack_package'] = __('Unpacking the update&#8230;'); $this->strings['remove_old'] = __('Removing the old version of the plugin&#8230;'); $this->strings['remove_old_failed'] = __('Could not remove the old plugin.'); $this->strings['process_failed'] = __('Plugin update failed.'); $this->strings['process_success'] = __('Plugin updated successfully.'); } function install_strings() { $this->strings['no_package'] = __('Install package not available.'); $this->strings['downloading_package'] = __('Downloading install package from <span class="code">%s</span>&#8230;'); $this->strings['unpack_package'] = __('Unpacking the package&#8230;'); $this->strings['installing_package'] = __('Installing the plugin&#8230;'); $this->strings['process_failed'] = __('Plugin install failed.'); $this->strings['process_success'] = __('Plugin installed successfully.'); } function install($package) { $this->init(); $this->install_strings(); add_filter('upgrader_source_selection', array(&$this, 'check_package') ); $this->run(array( 'package' => $package, 'destination' => WP_PLUGIN_DIR, 'clear_destination' => false, //Do not overwrite files. 'clear_working' => true, 'hook_extra' => array() )); remove_filter('upgrader_source_selection', array(&$this, 'check_package') ); if ( ! $this->result || is_wp_error($this->result) ) return $this->result; // Force refresh of plugin update information delete_site_transient('update_plugins'); wp_cache_delete( 'plugins', 'plugins' ); return true; } function upgrade($plugin) { $this->init(); $this->upgrade_strings(); $current = get_site_transient( 'update_plugins' ); if ( !isset( $current->response[ $plugin ] ) ) { $this->skin->before(); $this->skin->set_result(false); $this->skin->error('up_to_date'); $this->skin->after(); return false; } // Get the URL to the zip file $r = $current->response[ $plugin ]; add_filter('upgrader_pre_install', array(&$this, 'deactivate_plugin_before_upgrade'), 10, 2); add_filter('upgrader_clear_destination', array(&$this, 'delete_old_plugin'), 10, 4); //'source_selection' => array(&$this, 'source_selection'), //there's a trac ticket to move up the directory for zip's which are made a bit differently, useful for non-.org plugins. $this->run(array( 'package' => $r->package, 'destination' => WP_PLUGIN_DIR, 'clear_destination' => true, 'clear_working' => true, 'hook_extra' => array( 'plugin' => $plugin ) )); // Cleanup our hooks, in case something else does a upgrade on this connection. remove_filter('upgrader_pre_install', array(&$this, 'deactivate_plugin_before_upgrade')); remove_filter('upgrader_clear_destination', array(&$this, 'delete_old_plugin')); if ( ! $this->result || is_wp_error($this->result) ) return $this->result; // Force refresh of plugin update information delete_site_transient('update_plugins'); wp_cache_delete( 'plugins', 'plugins' ); } function bulk_upgrade($plugins) { $this->init(); $this->bulk = true; $this->upgrade_strings(); $current = get_site_transient( 'update_plugins' ); add_filter('upgrader_clear_destination', array(&$this, 'delete_old_plugin'), 10, 4); $this->skin->header(); // Connect to the Filesystem first. $res = $this->fs_connect( array(WP_CONTENT_DIR, WP_PLUGIN_DIR) ); if ( ! $res ) { $this->skin->footer(); return false; } $this->skin->bulk_header(); // Only start maintenance mode if running in Multisite OR the plugin is in use $maintenance = is_multisite(); // @TODO: This should only kick in for individual sites if at all possible. foreach ( $plugins as $plugin ) $maintenance = $maintenance || (is_plugin_active($plugin) && isset($current->response[ $plugin ]) ); // Only activate Maintenance mode if a plugin is active AND has an update available if ( $maintenance ) $this->maintenance_mode(true); $results = array(); $this->update_count = count($plugins); $this->update_current = 0; foreach ( $plugins as $plugin ) { $this->update_current++; $this->skin->plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, false, true); if ( !isset( $current->response[ $plugin ] ) ) { $this->skin->set_result(true); $this->skin->before(); $this->skin->feedback('up_to_date'); $this->skin->after(); $results[$plugin] = true; continue; } // Get the URL to the zip file $r = $current->response[ $plugin ]; $this->skin->plugin_active = is_plugin_active($plugin); $result = $this->run(array( 'package' => $r->package, 'destination' => WP_PLUGIN_DIR, 'clear_destination' => true, 'clear_working' => true, 'is_multi' => true, 'hook_extra' => array( 'plugin' => $plugin ) )); $results[$plugin] = $this->result; // Prevent credentials auth screen from displaying multiple times if ( false === $result ) break; } //end foreach $plugins $this->maintenance_mode(false); $this->skin->bulk_footer(); $this->skin->footer(); // Cleanup our hooks, in case something else does a upgrade on this connection. remove_filter('upgrader_clear_destination', array(&$this, 'delete_old_plugin')); // Force refresh of plugin update information delete_site_transient('update_plugins'); wp_cache_delete( 'plugins', 'plugins' ); return $results; } function check_package($source) { global $wp_filesystem; if ( is_wp_error($source) ) return $source; $working_directory = str_replace( $wp_filesystem->wp_content_dir(), trailingslashit(WP_CONTENT_DIR), $source); if ( ! is_dir($working_directory) ) // Sanity check, if the above fails, lets not prevent installation. return $source; // Check the folder contains at least 1 valid plugin. $plugins_found = false; foreach ( glob( $working_directory . '*.php' ) as $file ) { $info = get_plugin_data($file, false, false); if ( !empty( $info['Name'] ) ) { $plugins_found = true; break; } } if ( ! $plugins_found ) return new WP_Error( 'incompatible_archive', $this->strings['incompatible_archive'], __('No valid plugins were found.') ); return $source; } //return plugin info. function plugin_info() { if ( ! is_array($this->result) ) return false; if ( empty($this->result['destination_name']) ) return false; $plugin = get_plugins('/' . $this->result['destination_name']); //Ensure to pass with leading slash if ( empty($plugin) ) return false; $pluginfiles = array_keys($plugin); //Assume the requested plugin is the first in the list return $this->result['destination_name'] . '/' . $pluginfiles[0]; } //Hooked to pre_install function deactivate_plugin_before_upgrade($return, $plugin) { if ( is_wp_error($return) ) //Bypass. return $return; $plugin = isset($plugin['plugin']) ? $plugin['plugin'] : ''; if ( empty($plugin) ) return new WP_Error('bad_request', $this->strings['bad_request']); if ( is_plugin_active($plugin) ) { //Deactivate the plugin silently, Prevent deactivation hooks from running. deactivate_plugins($plugin, true); } } //Hooked to upgrade_clear_destination function delete_old_plugin($removed, $local_destination, $remote_destination, $plugin) { global $wp_filesystem; if ( is_wp_error($removed) ) return $removed; //Pass errors through. $plugin = isset($plugin['plugin']) ? $plugin['plugin'] : ''; if ( empty($plugin) ) return new WP_Error('bad_request', $this->strings['bad_request']); $plugins_dir = $wp_filesystem->wp_plugins_dir(); $this_plugin_dir = trailingslashit( dirname($plugins_dir . $plugin) ); if ( ! $wp_filesystem->exists($this_plugin_dir) ) //If its already vanished. return $removed; // If plugin is in its own directory, recursively delete the directory. if ( strpos($plugin, '/') && $this_plugin_dir != $plugins_dir ) //base check on if plugin includes directory separator AND that its not the root plugin folder $deleted = $wp_filesystem->delete($this_plugin_dir, true); else $deleted = $wp_filesystem->delete($plugins_dir . $plugin); if ( ! $deleted ) return new WP_Error('remove_old_failed', $this->strings['remove_old_failed']); return true; } } /** * Theme Upgrader class for WordPress Themes, It is designed to upgrade/install themes from a local zip, remote zip URL, or uploaded zip file. * * @TODO More Detailed docs, for methods as well. * * @package WordPress * @subpackage Upgrader * @since 2.8.0 */ class Theme_Upgrader extends WP_Upgrader { var $result; var $bulk = false; function upgrade_strings() { $this->strings['up_to_date'] = __('The theme is at the latest version.'); $this->strings['no_package'] = __('Update package not available.'); $this->strings['downloading_package'] = __('Downloading update from <span class="code">%s</span>&#8230;'); $this->strings['unpack_package'] = __('Unpacking the update&#8230;'); $this->strings['remove_old'] = __('Removing the old version of the theme&#8230;'); $this->strings['remove_old_failed'] = __('Could not remove the old theme.'); $this->strings['process_failed'] = __('Theme update failed.'); $this->strings['process_success'] = __('Theme updated successfully.'); } function install_strings() { $this->strings['no_package'] = __('Install package not available.'); $this->strings['downloading_package'] = __('Downloading install package from <span class="code">%s</span>&#8230;'); $this->strings['unpack_package'] = __('Unpacking the package&#8230;'); $this->strings['installing_package'] = __('Installing the theme&#8230;'); $this->strings['process_failed'] = __('Theme install failed.'); $this->strings['process_success'] = __('Theme installed successfully.'); /* translators: 1: theme name, 2: version */ $this->strings['process_success_specific'] = __('Successfully installed the theme <strong>%1$s %2$s</strong>.'); $this->strings['parent_theme_search'] = __('This theme requires a parent theme. Checking if it is installed&#8230;'); /* translators: 1: theme name, 2: version */ $this->strings['parent_theme_prepare_install'] = __('Preparing to install <strong>%1$s %2$s</strong>&#8230;'); /* translators: 1: theme name, 2: version */ $this->strings['parent_theme_currently_installed'] = __('The parent theme, <strong>%1$s %2$s</strong>, is currently installed.'); /* translators: 1: theme name, 2: version */ $this->strings['parent_theme_install_success'] = __('Successfully installed the parent theme, <strong>%1$s %2$s</strong>.'); $this->strings['parent_theme_not_found'] = __('<strong>The parent theme could not be found.</strong> You will need to install the parent theme, <strong>%s</strong>, before you can use this child theme.'); } function check_parent_theme_filter($install_result, $hook_extra, $child_result) { // Check to see if we need to install a parent theme $theme_info = $this->theme_info(); if ( ! $theme_info->parent() ) return $install_result; $this->skin->feedback( 'parent_theme_search' ); if ( ! $theme_info->parent()->errors() ) { $this->skin->feedback( 'parent_theme_currently_installed', $theme_info->parent()->display('Name'), $theme_info->parent()->display('Version') ); // We already have the theme, fall through. return $install_result; } // We don't have the parent theme, lets install it $api = themes_api('theme_information', array('slug' => $theme_info->get('Template'), 'fields' => array('sections' => false, 'tags' => false) ) ); //Save on a bit of bandwidth. if ( ! $api || is_wp_error($api) ) { $this->skin->feedback( 'parent_theme_not_found', $theme_info->get('Template') ); // Don't show activate or preview actions after install add_filter('install_theme_complete_actions', array(&$this, 'hide_activate_preview_actions') ); return $install_result; } // Backup required data we're going to override: $child_api = $this->skin->api; $child_success_message = $this->strings['process_success']; // Override them $this->skin->api = $api; $this->strings['process_success_specific'] = $this->strings['parent_theme_install_success'];//, $api->name, $api->version); $this->skin->feedback('parent_theme_prepare_install', $api->name, $api->version); add_filter('install_theme_complete_actions', '__return_false', 999); // Don't show any actions after installing the theme. // Install the parent theme $parent_result = $this->run( array( 'package' => $api->download_link, 'destination' => WP_CONTENT_DIR . '/themes', 'clear_destination' => false, //Do not overwrite files. 'clear_working' => true ) ); if ( is_wp_error($parent_result) ) add_filter('install_theme_complete_actions', array(&$this, 'hide_activate_preview_actions') ); // Start cleaning up after the parents installation remove_filter('install_theme_complete_actions', '__return_false', 999); // Reset child's result and data $this->result = $child_result; $this->skin->api = $child_api; $this->strings['process_success'] = $child_success_message; return $install_result; } function hide_activate_preview_actions($actions) { unset($actions['activate'], $actions['preview']); return $actions; } function install($package) { $this->init(); $this->install_strings(); add_filter('upgrader_source_selection', array(&$this, 'check_package') ); add_filter('upgrader_post_install', array(&$this, 'check_parent_theme_filter'), 10, 3); $options = array( 'package' => $package, 'destination' => WP_CONTENT_DIR . '/themes', 'clear_destination' => false, //Do not overwrite files. 'clear_working' => true ); $this->run($options); remove_filter('upgrader_source_selection', array(&$this, 'check_package') ); remove_filter('upgrader_post_install', array(&$this, 'check_parent_theme_filter'), 10, 3); if ( ! $this->result || is_wp_error($this->result) ) return $this->result; // Force refresh of theme update information wp_clean_themes_cache(); return true; } function upgrade($theme) { $this->init(); $this->upgrade_strings(); // Is an update available? $current = get_site_transient( 'update_themes' ); if ( !isset( $current->response[ $theme ] ) ) { $this->skin->before(); $this->skin->set_result(false); $this->skin->error('up_to_date'); $this->skin->after(); return false; } $r = $current->response[ $theme ]; add_filter('upgrader_pre_install', array(&$this, 'current_before'), 10, 2); add_filter('upgrader_post_install', array(&$this, 'current_after'), 10, 2); add_filter('upgrader_clear_destination', array(&$this, 'delete_old_theme'), 10, 4); $options = array( 'package' => $r['package'], 'destination' => WP_CONTENT_DIR . '/themes', 'clear_destination' => true, 'clear_working' => true, 'hook_extra' => array( 'theme' => $theme ) ); $this->run($options); remove_filter('upgrader_pre_install', array(&$this, 'current_before'), 10, 2); remove_filter('upgrader_post_install', array(&$this, 'current_after'), 10, 2); remove_filter('upgrader_clear_destination', array(&$this, 'delete_old_theme'), 10, 4); if ( ! $this->result || is_wp_error($this->result) ) return $this->result; // Force refresh of theme update information wp_clean_themes_cache(); return true; } function bulk_upgrade($themes) { $this->init(); $this->bulk = true; $this->upgrade_strings(); $current = get_site_transient( 'update_themes' ); add_filter('upgrader_pre_install', array(&$this, 'current_before'), 10, 2); add_filter('upgrader_post_install', array(&$this, 'current_after'), 10, 2); add_filter('upgrader_clear_destination', array(&$this, 'delete_old_theme'), 10, 4); $this->skin->header(); // Connect to the Filesystem first. $res = $this->fs_connect( array(WP_CONTENT_DIR) ); if ( ! $res ) { $this->skin->footer(); return false; } $this->skin->bulk_header(); // Only start maintenance mode if running in Multisite OR the theme is in use $maintenance = is_multisite(); // @TODO: This should only kick in for individual sites if at all possible. foreach ( $themes as $theme ) $maintenance = $maintenance || $theme == get_stylesheet() || $theme == get_template(); if ( $maintenance ) $this->maintenance_mode(true); $results = array(); $this->update_count = count($themes); $this->update_current = 0; foreach ( $themes as $theme ) { $this->update_current++; $this->skin->theme_info = $this->theme_info($theme); if ( !isset( $current->response[ $theme ] ) ) { $this->skin->set_result(true); $this->skin->before(); $this->skin->feedback('up_to_date'); $this->skin->after(); $results[$theme] = true; continue; } // Get the URL to the zip file $r = $current->response[ $theme ]; $options = array( 'package' => $r['package'], 'destination' => WP_CONTENT_DIR . '/themes', 'clear_destination' => true, 'clear_working' => true, 'hook_extra' => array( 'theme' => $theme ) ); $result = $this->run($options); $results[$theme] = $this->result; // Prevent credentials auth screen from displaying multiple times if ( false === $result ) break; } //end foreach $plugins $this->maintenance_mode(false); $this->skin->bulk_footer(); $this->skin->footer(); // Cleanup our hooks, in case something else does a upgrade on this connection. remove_filter('upgrader_pre_install', array(&$this, 'current_before'), 10, 2); remove_filter('upgrader_post_install', array(&$this, 'current_after'), 10, 2); remove_filter('upgrader_clear_destination', array(&$this, 'delete_old_theme'), 10, 4); // Force refresh of theme update information wp_clean_themes_cache(); return $results; } function check_package($source) { global $wp_filesystem; if ( is_wp_error($source) ) return $source; // Check the folder contains a valid theme $working_directory = str_replace( $wp_filesystem->wp_content_dir(), trailingslashit(WP_CONTENT_DIR), $source); if ( ! is_dir($working_directory) ) // Sanity check, if the above fails, lets not prevent installation. return $source; // A proper archive should have a style.css file in the single subdirectory if ( ! file_exists( $working_directory . 'style.css' ) ) return new WP_Error( 'incompatible_archive', $this->strings['incompatible_archive'], __('The theme is missing the <code>style.css</code> stylesheet.') ); $info = get_file_data( $working_directory . 'style.css', array( 'Name' => 'Theme Name', 'Template' => 'Template' ) ); if ( empty( $info['Name'] ) ) return new WP_Error( 'incompatible_archive', $this->strings['incompatible_archive'], __("The <code>style.css</code> stylesheet doesn't contain a valid theme header.") ); // If it's not a child theme, it must have at least an index.php to be legit. if ( empty( $info['Template'] ) && ! file_exists( $working_directory . 'index.php' ) ) return new WP_Error( 'incompatible_archive', $this->strings['incompatible_archive'], __('The theme is missing the <code>index.php</code> file.') ); return $source; } function current_before($return, $theme) { if ( is_wp_error($return) ) return $return; $theme = isset($theme['theme']) ? $theme['theme'] : ''; if ( $theme != get_stylesheet() ) //If not current return $return; //Change to maintenance mode now. if ( ! $this->bulk ) $this->maintenance_mode(true); return $return; } function current_after($return, $theme) { if ( is_wp_error($return) ) return $return; $theme = isset($theme['theme']) ? $theme['theme'] : ''; if ( $theme != get_stylesheet() ) // If not current return $return; // Ensure stylesheet name hasn't changed after the upgrade: if ( $theme == get_stylesheet() && $theme != $this->result['destination_name'] ) { wp_clean_themes_cache(); $stylesheet = $this->result['destination_name']; switch_theme( $stylesheet ); } //Time to remove maintenance mode if ( ! $this->bulk ) $this->maintenance_mode(false); return $return; } function delete_old_theme($removed, $local_destination, $remote_destination, $theme) { global $wp_filesystem; $theme = isset($theme['theme']) ? $theme['theme'] : ''; if ( is_wp_error($removed) || empty($theme) ) return $removed; //Pass errors through. $themes_dir = $wp_filesystem->wp_themes_dir(); if ( $wp_filesystem->exists( trailingslashit($themes_dir) . $theme ) ) if ( ! $wp_filesystem->delete( trailingslashit($themes_dir) . $theme, true ) ) return false; return true; } function theme_info($theme = null) { if ( empty($theme) ) { if ( !empty($this->result['destination_name']) ) $theme = $this->result['destination_name']; else return false; } return wp_get_theme( $theme, WP_CONTENT_DIR . '/themes/' ); } } /** * Core Upgrader class for WordPress. It allows for WordPress to upgrade itself in combination with the wp-admin/includes/update-core.php file * * @TODO More Detailed docs, for methods as well. * * @package WordPress * @subpackage Upgrader * @since 2.8.0 */ class Core_Upgrader extends WP_Upgrader { function upgrade_strings() { $this->strings['up_to_date'] = __('WordPress is at the latest version.'); $this->strings['no_package'] = __('Update package not available.'); $this->strings['downloading_package'] = __('Downloading update from <span class="code">%s</span>&#8230;'); $this->strings['unpack_package'] = __('Unpacking the update&#8230;'); $this->strings['copy_failed'] = __('Could not copy files.'); $this->strings['copy_failed_space'] = __('Could not copy files. You may have run out of disk space.' ); } function upgrade($current) { global $wp_filesystem, $wp_version; $this->init(); $this->upgrade_strings(); if ( !empty($feedback) ) add_filter('update_feedback', $feedback); // Is an update available? if ( !isset( $current->response ) || $current->response == 'latest' ) return new WP_Error('up_to_date', $this->strings['up_to_date']); $res = $this->fs_connect( array(ABSPATH, WP_CONTENT_DIR) ); if ( is_wp_error($res) ) return $res; $wp_dir = trailingslashit($wp_filesystem->abspath()); // If partial update is returned from the API, use that, unless we're doing a reinstall. // If we cross the new_bundled version number, then use the new_bundled zip. // Don't though if the constant is set to skip bundled items. // If the API returns a no_content zip, go with it. Finally, default to the full zip. if ( $current->packages->partial && 'reinstall' != $current->response && $wp_version == $current->partial_version ) $to_download = 'partial'; elseif ( $current->packages->new_bundled && version_compare( $wp_version, $current->new_bundled, '<' ) && ( ! defined( 'CORE_UPGRADE_SKIP_NEW_BUNDLED' ) || ! CORE_UPGRADE_SKIP_NEW_BUNDLED ) ) $to_download = 'new_bundled'; elseif ( $current->packages->no_content ) $to_download = 'no_content'; else $to_download = 'full'; $download = $this->download_package( $current->packages->$to_download ); if ( is_wp_error($download) ) return $download; $working_dir = $this->unpack_package( $download ); if ( is_wp_error($working_dir) ) return $working_dir; // Copy update-core.php from the new version into place. if ( !$wp_filesystem->copy($working_dir . '/wordpress/wp-admin/includes/update-core.php', $wp_dir . 'wp-admin/includes/update-core.php', true) ) { $wp_filesystem->delete($working_dir, true); return new WP_Error('copy_failed', $this->strings['copy_failed']); } $wp_filesystem->chmod($wp_dir . 'wp-admin/includes/update-core.php', FS_CHMOD_FILE); require(ABSPATH . 'wp-admin/includes/update-core.php'); if ( ! function_exists( 'update_core' ) ) return new WP_Error( 'copy_failed_space', $this->strings['copy_failed_space'] ); return update_core($working_dir, $wp_dir); } } /** * Generic Skin for the WordPress Upgrader classes. This skin is designed to be extended for specific purposes. * * @TODO More Detailed docs, for methods as well. * * @package WordPress * @subpackage Upgrader * @since 2.8.0 */ class WP_Upgrader_Skin { var $upgrader; var $done_header = false; var $result = false; function __construct($args = array()) { $defaults = array( 'url' => '', 'nonce' => '', 'title' => '', 'context' => false ); $this->options = wp_parse_args($args, $defaults); } function set_upgrader(&$upgrader) { if ( is_object($upgrader) ) $this->upgrader =& $upgrader; $this->add_strings(); } function add_strings() { } function set_result($result) { $this->result = $result; } function request_filesystem_credentials($error = false) { $url = $this->options['url']; $context = $this->options['context']; if ( !empty($this->options['nonce']) ) $url = wp_nonce_url($url, $this->options['nonce']); return request_filesystem_credentials($url, '', $error, $context); //Possible to bring inline, Leaving as is for now. } function header() { if ( $this->done_header ) return; $this->done_header = true; echo '<div class="wrap">'; echo screen_icon(); echo '<h2>' . $this->options['title'] . '</h2>'; } function footer() { echo '</div>'; } function error($errors) { if ( ! $this->done_header ) $this->header(); if ( is_string($errors) ) { $this->feedback($errors); } elseif ( is_wp_error($errors) && $errors->get_error_code() ) { foreach ( $errors->get_error_messages() as $message ) { if ( $errors->get_error_data() ) $this->feedback($message . ' ' . $errors->get_error_data() ); else $this->feedback($message); } } } function feedback($string) { if ( isset( $this->upgrader->strings[$string] ) ) $string = $this->upgrader->strings[$string]; if ( strpos($string, '%') !== false ) { $args = func_get_args(); $args = array_splice($args, 1); if ( !empty($args) ) $string = vsprintf($string, $args); } if ( empty($string) ) return; show_message($string); } function before() {} function after() {} } /** * Plugin Upgrader Skin for WordPress Plugin Upgrades. * * @TODO More Detailed docs, for methods as well. * * @package WordPress * @subpackage Upgrader * @since 2.8.0 */ class Plugin_Upgrader_Skin extends WP_Upgrader_Skin { var $plugin = ''; var $plugin_active = false; var $plugin_network_active = false; function __construct($args = array()) { $defaults = array( 'url' => '', 'plugin' => '', 'nonce' => '', 'title' => __('Update Plugin') ); $args = wp_parse_args($args, $defaults); $this->plugin = $args['plugin']; $this->plugin_active = is_plugin_active( $this->plugin ); $this->plugin_network_active = is_plugin_active_for_network( $this->plugin ); parent::__construct($args); } function after() { $this->plugin = $this->upgrader->plugin_info(); if ( !empty($this->plugin) && !is_wp_error($this->result) && $this->plugin_active ){ echo '<iframe style="border:0;overflow:hidden" width="100%" height="170px" src="' . wp_nonce_url('update.php?action=activate-plugin&networkwide=' . $this->plugin_network_active . '&plugin=' . $this->plugin, 'activate-plugin_' . $this->plugin) .'"></iframe>'; } $update_actions = array( 'activate_plugin' => '<a href="' . wp_nonce_url('plugins.php?action=activate&amp;plugin=' . $this->plugin, 'activate-plugin_' . $this->plugin) . '" title="' . esc_attr__('Activate this plugin') . '" target="_parent">' . __('Activate Plugin') . '</a>', 'plugins_page' => '<a href="' . self_admin_url('plugins.php') . '" title="' . esc_attr__('Go to plugins page') . '" target="_parent">' . __('Return to Plugins page') . '</a>' ); if ( $this->plugin_active || ! $this->result || is_wp_error( $this->result ) || ! current_user_can( 'activate_plugins' ) ) unset( $update_actions['activate_plugin'] ); $update_actions = apply_filters('update_plugin_complete_actions', $update_actions, $this->plugin); if ( ! empty($update_actions) ) $this->feedback(implode(' | ', (array)$update_actions)); } function before() { if ( $this->upgrader->show_before ) { echo $this->upgrader->show_before; $this->upgrader->show_before = ''; } } } /** * Plugin Upgrader Skin for WordPress Plugin Upgrades. * * @package WordPress * @subpackage Upgrader * @since 3.0.0 */ class Bulk_Upgrader_Skin extends WP_Upgrader_Skin { var $in_loop = false; var $error = false; function __construct($args = array()) { $defaults = array( 'url' => '', 'nonce' => '' ); $args = wp_parse_args($args, $defaults); parent::__construct($args); } function add_strings() { $this->upgrader->strings['skin_upgrade_start'] = __('The update process is starting. This process may take a while on some hosts, so please be patient.'); $this->upgrader->strings['skin_update_failed_error'] = __('An error occurred while updating %1$s: <strong>%2$s</strong>.'); $this->upgrader->strings['skin_update_failed'] = __('The update of %1$s failed.'); $this->upgrader->strings['skin_update_successful'] = __('%1$s updated successfully.').' <a onclick="%2$s" href="#" class="hide-if-no-js"><span>'.__('Show Details').'</span><span class="hidden">'.__('Hide Details').'</span>.</a>'; $this->upgrader->strings['skin_upgrade_end'] = __('All updates have been completed.'); } function feedback($string) { if ( isset( $this->upgrader->strings[$string] ) ) $string = $this->upgrader->strings[$string]; if ( strpos($string, '%') !== false ) { $args = func_get_args(); $args = array_splice($args, 1); if ( !empty($args) ) $string = vsprintf($string, $args); } if ( empty($string) ) return; if ( $this->in_loop ) echo "$string<br />\n"; else echo "<p>$string</p>\n"; } function header() { // Nothing, This will be displayed within a iframe. } function footer() { // Nothing, This will be displayed within a iframe. } function error($error) { if ( is_string($error) && isset( $this->upgrader->strings[$error] ) ) $this->error = $this->upgrader->strings[$error]; if ( is_wp_error($error) ) { foreach ( $error->get_error_messages() as $emessage ) { if ( $error->get_error_data() ) $messages[] = $emessage . ' ' . $error->get_error_data(); else $messages[] = $emessage; } $this->error = implode(', ', $messages); } echo '<script type="text/javascript">jQuery(\'.waiting-' . esc_js($this->upgrader->update_current) . '\').hide();</script>'; } function bulk_header() { $this->feedback('skin_upgrade_start'); } function bulk_footer() { $this->feedback('skin_upgrade_end'); } function before($title = '') { $this->in_loop = true; printf( '<h4>' . $this->upgrader->strings['skin_before_update_header'] . ' <span class="spinner waiting-' . $this->upgrader->update_current . '"></span></h4>', $title, $this->upgrader->update_current, $this->upgrader->update_count); echo '<script type="text/javascript">jQuery(\'.waiting-' . esc_js($this->upgrader->update_current) . '\').css("display", "inline-block");</script>'; echo '<div class="update-messages hide-if-js" id="progress-' . esc_attr($this->upgrader->update_current) . '"><p>'; $this->flush_output(); } function after($title = '') { echo '</p></div>'; if ( $this->error || ! $this->result ) { if ( $this->error ) echo '<div class="error"><p>' . sprintf($this->upgrader->strings['skin_update_failed_error'], $title, $this->error) . '</p></div>'; else echo '<div class="error"><p>' . sprintf($this->upgrader->strings['skin_update_failed'], $title) . '</p></div>'; echo '<script type="text/javascript">jQuery(\'#progress-' . esc_js($this->upgrader->update_current) . '\').show();</script>'; } if ( !empty($this->result) && !is_wp_error($this->result) ) { echo '<div class="updated"><p>' . sprintf($this->upgrader->strings['skin_update_successful'], $title, 'jQuery(\'#progress-' . esc_js($this->upgrader->update_current) . '\').toggle();jQuery(\'span\', this).toggle(); return false;') . '</p></div>'; echo '<script type="text/javascript">jQuery(\'.waiting-' . esc_js($this->upgrader->update_current) . '\').hide();</script>'; } $this->reset(); $this->flush_output(); } function reset() { $this->in_loop = false; $this->error = false; } function flush_output() { wp_ob_end_flush_all(); flush(); } } class Bulk_Plugin_Upgrader_Skin extends Bulk_Upgrader_Skin { var $plugin_info = array(); // Plugin_Upgrader::bulk() will fill this in. function __construct($args = array()) { parent::__construct($args); } function add_strings() { parent::add_strings(); $this->upgrader->strings['skin_before_update_header'] = __('Updating Plugin %1$s (%2$d/%3$d)'); } function before() { parent::before($this->plugin_info['Title']); } function after() { parent::after($this->plugin_info['Title']); } function bulk_footer() { parent::bulk_footer(); $update_actions = array( 'plugins_page' => '<a href="' . self_admin_url('plugins.php') . '" title="' . esc_attr__('Go to plugins page') . '" target="_parent">' . __('Return to Plugins page') . '</a>', 'updates_page' => '<a href="' . self_admin_url('update-core.php') . '" title="' . esc_attr__('Go to WordPress Updates page') . '" target="_parent">' . __('Return to WordPress Updates') . '</a>' ); if ( ! current_user_can( 'activate_plugins' ) ) unset( $update_actions['plugins_page'] ); $update_actions = apply_filters('update_bulk_plugins_complete_actions', $update_actions, $this->plugin_info); if ( ! empty($update_actions) ) $this->feedback(implode(' | ', (array)$update_actions)); } } class Bulk_Theme_Upgrader_Skin extends Bulk_Upgrader_Skin { var $theme_info = array(); // Theme_Upgrader::bulk() will fill this in. function __construct($args = array()) { parent::__construct($args); } function add_strings() { parent::add_strings(); $this->upgrader->strings['skin_before_update_header'] = __('Updating Theme %1$s (%2$d/%3$d)'); } function before() { parent::before( $this->theme_info->display('Name') ); } function after() { parent::after( $this->theme_info->display('Name') ); } function bulk_footer() { parent::bulk_footer(); $update_actions = array( 'themes_page' => '<a href="' . self_admin_url('themes.php') . '" title="' . esc_attr__('Go to themes page') . '" target="_parent">' . __('Return to Themes page') . '</a>', 'updates_page' => '<a href="' . self_admin_url('update-core.php') . '" title="' . esc_attr__('Go to WordPress Updates page') . '" target="_parent">' . __('Return to WordPress Updates') . '</a>' ); if ( ! current_user_can( 'switch_themes' ) && ! current_user_can( 'edit_theme_options' ) ) unset( $update_actions['themes_page'] ); $update_actions = apply_filters('update_bulk_theme_complete_actions', $update_actions, $this->theme_info ); if ( ! empty($update_actions) ) $this->feedback(implode(' | ', (array)$update_actions)); } } /** * Plugin Installer Skin for WordPress Plugin Installer. * * @TODO More Detailed docs, for methods as well. * * @package WordPress * @subpackage Upgrader * @since 2.8.0 */ class Plugin_Installer_Skin extends WP_Upgrader_Skin { var $api; var $type; function __construct($args = array()) { $defaults = array( 'type' => 'web', 'url' => '', 'plugin' => '', 'nonce' => '', 'title' => '' ); $args = wp_parse_args($args, $defaults); $this->type = $args['type']; $this->api = isset($args['api']) ? $args['api'] : array(); parent::__construct($args); } function before() { if ( !empty($this->api) ) $this->upgrader->strings['process_success'] = sprintf( __('Successfully installed the plugin <strong>%s %s</strong>.'), $this->api->name, $this->api->version); } function after() { $plugin_file = $this->upgrader->plugin_info(); $install_actions = array(); $from = isset($_GET['from']) ? stripslashes($_GET['from']) : 'plugins'; if ( 'import' == $from ) $install_actions['activate_plugin'] = '<a href="' . wp_nonce_url('plugins.php?action=activate&amp;from=import&amp;plugin=' . $plugin_file, 'activate-plugin_' . $plugin_file) . '" title="' . esc_attr__('Activate this plugin') . '" target="_parent">' . __('Activate Plugin &amp; Run Importer') . '</a>'; else $install_actions['activate_plugin'] = '<a href="' . wp_nonce_url('plugins.php?action=activate&amp;plugin=' . $plugin_file, 'activate-plugin_' . $plugin_file) . '" title="' . esc_attr__('Activate this plugin') . '" target="_parent">' . __('Activate Plugin') . '</a>'; if ( is_multisite() && current_user_can( 'manage_network_plugins' ) ) { $install_actions['network_activate'] = '<a href="' . wp_nonce_url('plugins.php?action=activate&amp;networkwide=1&amp;plugin=' . $plugin_file, 'activate-plugin_' . $plugin_file) . '" title="' . esc_attr__('Activate this plugin for all sites in this network') . '" target="_parent">' . __('Network Activate') . '</a>'; unset( $install_actions['activate_plugin'] ); } if ( 'import' == $from ) $install_actions['importers_page'] = '<a href="' . admin_url('import.php') . '" title="' . esc_attr__('Return to Importers') . '" target="_parent">' . __('Return to Importers') . '</a>'; else if ( $this->type == 'web' ) $install_actions['plugins_page'] = '<a href="' . self_admin_url('plugin-install.php') . '" title="' . esc_attr__('Return to Plugin Installer') . '" target="_parent">' . __('Return to Plugin Installer') . '</a>'; else $install_actions['plugins_page'] = '<a href="' . self_admin_url('plugins.php') . '" title="' . esc_attr__('Return to Plugins page') . '" target="_parent">' . __('Return to Plugins page') . '</a>'; if ( ! $this->result || is_wp_error($this->result) ) { unset( $install_actions['activate_plugin'], $install_actions['network_activate'] ); } elseif ( ! current_user_can( 'activate_plugins' ) ) { unset( $install_actions['activate_plugin'] ); } $install_actions = apply_filters('install_plugin_complete_actions', $install_actions, $this->api, $plugin_file); if ( ! empty($install_actions) ) $this->feedback(implode(' | ', (array)$install_actions)); } } /** * Theme Installer Skin for the WordPress Theme Installer. * * @TODO More Detailed docs, for methods as well. * * @package WordPress * @subpackage Upgrader * @since 2.8.0 */ class Theme_Installer_Skin extends WP_Upgrader_Skin { var $api; var $type; function __construct($args = array()) { $defaults = array( 'type' => 'web', 'url' => '', 'theme' => '', 'nonce' => '', 'title' => '' ); $args = wp_parse_args($args, $defaults); $this->type = $args['type']; $this->api = isset($args['api']) ? $args['api'] : array(); parent::__construct($args); } function before() { if ( !empty($this->api) ) $this->upgrader->strings['process_success'] = sprintf( $this->upgrader->strings['process_success_specific'], $this->api->name, $this->api->version); } function after() { if ( empty($this->upgrader->result['destination_name']) ) return; $theme_info = $this->upgrader->theme_info(); if ( empty( $theme_info ) ) return; $name = $theme_info->display('Name'); $stylesheet = $this->upgrader->result['destination_name']; $template = $theme_info->get_template(); $preview_link = add_query_arg( array( 'preview' => 1, 'template' => urlencode( $template ), 'stylesheet' => urlencode( $stylesheet ), ), trailingslashit( home_url() ) ); $activate_link = add_query_arg( array( 'action' => 'activate', 'template' => urlencode( $template ), 'stylesheet' => urlencode( $stylesheet ), ), admin_url('themes.php') ); $activate_link = wp_nonce_url( $activate_link, 'switch-theme_' . $stylesheet ); $install_actions = array(); $install_actions['preview'] = '<a href="' . esc_url( $preview_link ) . '" class="hide-if-customize" title="' . esc_attr( sprintf( __('Preview &#8220;%s&#8221;'), $name ) ) . '">' . __('Preview') . '</a>'; $install_actions['preview'] .= '<a href="' . wp_customize_url( $stylesheet ) . '" class="hide-if-no-customize load-customize" title="' . esc_attr( sprintf( __('Preview &#8220;%s&#8221;'), $name ) ) . '">' . __('Live Preview') . '</a>'; $install_actions['activate'] = '<a href="' . esc_url( $activate_link ) . '" class="activatelink" title="' . esc_attr( sprintf( __('Activate &#8220;%s&#8221;'), $name ) ) . '">' . __('Activate') . '</a>'; if ( is_network_admin() && current_user_can( 'manage_network_themes' ) ) $install_actions['network_enable'] = '<a href="' . esc_url( wp_nonce_url( 'themes.php?action=enable&amp;theme=' . urlencode( $stylesheet ), 'enable-theme_' . $stylesheet ) ) . '" title="' . esc_attr__( 'Enable this theme for all sites in this network' ) . '" target="_parent">' . __( 'Network Enable' ) . '</a>'; if ( $this->type == 'web' ) $install_actions['themes_page'] = '<a href="' . self_admin_url('theme-install.php') . '" title="' . esc_attr__('Return to Theme Installer') . '" target="_parent">' . __('Return to Theme Installer') . '</a>'; elseif ( current_user_can( 'switch_themes' ) || current_user_can( 'edit_theme_options' ) ) $install_actions['themes_page'] = '<a href="' . self_admin_url('themes.php') . '" title="' . esc_attr__('Themes page') . '" target="_parent">' . __('Return to Themes page') . '</a>'; if ( ! $this->result || is_wp_error($this->result) || is_network_admin() || ! current_user_can( 'switch_themes' ) ) unset( $install_actions['activate'], $install_actions['preview'] ); $install_actions = apply_filters('install_theme_complete_actions', $install_actions, $this->api, $stylesheet, $theme_info); if ( ! empty($install_actions) ) $this->feedback(implode(' | ', (array)$install_actions)); } } /** * Theme Upgrader Skin for WordPress Theme Upgrades. * * @TODO More Detailed docs, for methods as well. * * @package WordPress * @subpackage Upgrader * @since 2.8.0 */ class Theme_Upgrader_Skin extends WP_Upgrader_Skin { var $theme = ''; function __construct($args = array()) { $defaults = array( 'url' => '', 'theme' => '', 'nonce' => '', 'title' => __('Update Theme') ); $args = wp_parse_args($args, $defaults); $this->theme = $args['theme']; parent::__construct($args); } function after() { $update_actions = array(); if ( ! empty( $this->upgrader->result['destination_name'] ) && $theme_info = $this->upgrader->theme_info() ) { $name = $theme_info->display('Name'); $stylesheet = $this->upgrader->result['destination_name']; $template = $theme_info->get_template(); $preview_link = add_query_arg( array( 'preview' => 1, 'template' => urlencode( $template ), 'stylesheet' => urlencode( $stylesheet ), ), trailingslashit( home_url() ) ); $activate_link = add_query_arg( array( 'action' => 'activate', 'template' => urlencode( $template ), 'stylesheet' => urlencode( $stylesheet ), ), admin_url('themes.php') ); $activate_link = wp_nonce_url( $activate_link, 'switch-theme_' . $stylesheet ); if ( get_stylesheet() == $stylesheet ) { if ( current_user_can( 'edit_theme_options' ) ) $update_actions['preview'] = '<a href="' . wp_customize_url( $stylesheet ) . '" class="hide-if-no-customize load-customize" title="' . esc_attr( sprintf( __('Customize &#8220;%s&#8221;'), $name ) ) . '">' . __('Customize') . '</a>'; } elseif ( current_user_can( 'switch_themes' ) ) { $update_actions['preview'] = '<a href="' . esc_url( $preview_link ) . '" class="hide-if-customize" title="' . esc_attr( sprintf( __('Preview &#8220;%s&#8221;'), $name ) ) . '">' . __('Preview') . '</a>'; $update_actions['preview'] .= '<a href="' . wp_customize_url( $stylesheet ) . '" class="hide-if-no-customize load-customize" title="' . esc_attr( sprintf( __('Preview &#8220;%s&#8221;'), $name ) ) . '">' . __('Live Preview') . '</a>'; $update_actions['activate'] = '<a href="' . esc_url( $activate_link ) . '" class="activatelink" title="' . esc_attr( sprintf( __('Activate &#8220;%s&#8221;'), $name ) ) . '">' . __('Activate') . '</a>'; } if ( ! $this->result || is_wp_error( $this->result ) || is_network_admin() ) unset( $update_actions['preview'], $update_actions['activate'] ); } $update_actions['themes_page'] = '<a href="' . self_admin_url('themes.php') . '" title="' . esc_attr__('Return to Themes page') . '" target="_parent">' . __('Return to Themes page') . '</a>'; $update_actions = apply_filters('update_theme_complete_actions', $update_actions, $this->theme); if ( ! empty($update_actions) ) $this->feedback(implode(' | ', (array)$update_actions)); } } /** * Upgrade Skin helper for File uploads. This class handles the upload process and passes it as if its a local file to the Upgrade/Installer functions. * * @TODO More Detailed docs, for methods as well. * * @package WordPress * @subpackage Upgrader * @since 2.8.0 */ class File_Upload_Upgrader { var $package; var $filename; var $id = 0; function __construct($form, $urlholder) { if ( empty($_FILES[$form]['name']) && empty($_GET[$urlholder]) ) wp_die(__('Please select a file')); //Handle a newly uploaded file, Else assume its already been uploaded if ( ! empty($_FILES) ) { $overrides = array( 'test_form' => false, 'test_type' => false ); $file = wp_handle_upload( $_FILES[$form], $overrides ); if ( isset( $file['error'] ) ) wp_die( $file['error'] ); $this->filename = $_FILES[$form]['name']; $this->package = $file['file']; // Construct the object array $object = array( 'post_title' => $this->filename, 'post_content' => $file['url'], 'post_mime_type' => $file['type'], 'guid' => $file['url'], 'context' => 'upgrader', 'post_status' => 'private' ); // Save the data $this->id = wp_insert_attachment( $object, $file['file'] ); // schedule a cleanup for 2 hours from now in case of failed install wp_schedule_single_event( time() + 7200, 'upgrader_scheduled_cleanup', array( $this->id ) ); } elseif ( is_numeric( $_GET[$urlholder] ) ) { // Numeric Package = previously uploaded file, see above. $this->id = (int) $_GET[$urlholder]; $attachment = get_post( $this->id ); if ( empty($attachment) ) wp_die(__('Please select a file')); $this->filename = $attachment->post_title; $this->package = get_attached_file( $attachment->ID ); } else { // Else, It's set to something, Back compat for plugins using the old (pre-3.3) File_Uploader handler. if ( ! ( ( $uploads = wp_upload_dir() ) && false === $uploads['error'] ) ) wp_die( $uploads['error'] ); $this->filename = $_GET[$urlholder]; $this->package = $uploads['basedir'] . '/' . $this->filename; } } function cleanup() { if ( $this->id ) wp_delete_attachment( $this->id ); elseif ( file_exists( $this->package ) ) return @unlink( $this->package ); return true; } }
zyblog
trunk/zyblog/wp-admin/includes/class-wp-upgrader.php
PHP
asf20
60,747
<?php /** * WordPress Administration Media API. * * @package WordPress * @subpackage Administration */ /** * Defines the default media upload tabs * * @since 2.5.0 * * @return array default tabs */ function media_upload_tabs() { $_default_tabs = array( 'type' => __('From Computer'), // handler action suffix => tab text 'type_url' => __('From URL'), 'gallery' => __('Gallery'), 'library' => __('Media Library') ); return apply_filters('media_upload_tabs', $_default_tabs); } /** * Adds the gallery tab back to the tabs array if post has image attachments * * @since 2.5.0 * * @param array $tabs * @return array $tabs with gallery if post has image attachment */ function update_gallery_tab($tabs) { global $wpdb; if ( !isset($_REQUEST['post_id']) ) { unset($tabs['gallery']); return $tabs; } $post_id = intval($_REQUEST['post_id']); if ( $post_id ) $attachments = intval( $wpdb->get_var( $wpdb->prepare( "SELECT count(*) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' AND post_parent = %d", $post_id ) ) ); if ( empty($attachments) ) { unset($tabs['gallery']); return $tabs; } $tabs['gallery'] = sprintf(__('Gallery (%s)'), "<span id='attachments-count'>$attachments</span>"); return $tabs; } add_filter('media_upload_tabs', 'update_gallery_tab'); /** * {@internal Missing Short Description}} * * @since 2.5.0 */ function the_media_upload_tabs() { global $redir_tab; $tabs = media_upload_tabs(); $default = 'type'; if ( !empty($tabs) ) { echo "<ul id='sidemenu'>\n"; if ( isset($redir_tab) && array_key_exists($redir_tab, $tabs) ) $current = $redir_tab; elseif ( isset($_GET['tab']) && array_key_exists($_GET['tab'], $tabs) ) $current = $_GET['tab']; else $current = apply_filters('media_upload_default_tab', $default); foreach ( $tabs as $callback => $text ) { $class = ''; if ( $current == $callback ) $class = " class='current'"; $href = add_query_arg(array('tab' => $callback, 's' => false, 'paged' => false, 'post_mime_type' => false, 'm' => false)); $link = "<a href='" . esc_url($href) . "'$class>$text</a>"; echo "\t<li id='" . esc_attr("tab-$callback") . "'>$link</li>\n"; } echo "</ul>\n"; } } /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @param integer $id image attachment id * @param string $caption image caption * @param string $alt image alt attribute * @param string $title image title attribute * @param string $align image css alignment property * @param string $url image src url * @param string|bool $rel image rel attribute * @param string $size image size (thumbnail, medium, large, full or added with add_image_size() ) * @return string the html to insert into editor */ function get_image_send_to_editor($id, $caption, $title, $align, $url='', $rel = false, $size='medium', $alt = '') { $html = get_image_tag($id, $alt, '', $align, $size); $rel = $rel ? ' rel="attachment wp-att-' . esc_attr($id).'"' : ''; if ( $url ) $html = '<a href="' . esc_attr($url) . "\"$rel>$html</a>"; $html = apply_filters( 'image_send_to_editor', $html, $id, $caption, $title, $align, $url, $size, $alt ); return $html; } /** * Adds image shortcode with caption to editor * * @since 2.6.0 * * @param string $html * @param integer $id * @param string $caption image caption * @param string $alt image alt attribute * @param string $title image title attribute * @param string $align image css alignment property * @param string $url image src url * @param string $size image size (thumbnail, medium, large, full or added with add_image_size() ) * @return string */ function image_add_caption( $html, $id, $caption, $title, $align, $url, $size, $alt = '' ) { if ( empty($caption) || apply_filters( 'disable_captions', '' ) ) return $html; $id = ( 0 < (int) $id ) ? 'attachment_' . $id : ''; if ( ! preg_match( '/width=["\']([0-9]+)/', $html, $matches ) ) return $html; $width = $matches[1]; $caption = str_replace( array("\r\n", "\r"), "\n", $caption); $caption = preg_replace_callback( '/<[a-zA-Z0-9]+(?: [^<>]+>)*/', '_cleanup_image_add_caption', $caption ); // convert any remaining line breaks to <br> $caption = preg_replace( '/[ \n\t]*\n[ \t]*/', '<br />', $caption ); $html = preg_replace( '/(class=["\'][^\'"]*)align(none|left|right|center)\s?/', '$1', $html ); if ( empty($align) ) $align = 'none'; $shcode = '[caption id="' . $id . '" align="align' . $align . '" width="' . $width . '"]' . $html . ' ' . $caption . '[/caption]'; return apply_filters( 'image_add_caption_shortcode', $shcode, $html ); } add_filter( 'image_send_to_editor', 'image_add_caption', 20, 8 ); /** * Private preg_replace callback used in image_add_caption() * * @access private * @since 3.4.0 */ function _cleanup_image_add_caption( $matches ) { // remove any line breaks from inside the tags return preg_replace( '/[\r\n\t]+/', ' ', $matches[0] ); } /** * Adds image html to editor * * @since 2.5.0 * * @param string $html */ function media_send_to_editor($html) { ?> <script type="text/javascript"> /* <![CDATA[ */ var win = window.dialogArguments || opener || parent || top; win.send_to_editor('<?php echo addslashes($html); ?>'); /* ]]> */ </script> <?php exit; } /** * This handles the file upload POST itself, creating the attachment post. * * @since 2.5.0 * * @param string $file_id Index into the {@link $_FILES} array of the upload * @param int $post_id The post ID the media is associated with * @param array $post_data allows you to overwrite some of the attachment * @param array $overrides allows you to override the {@link wp_handle_upload()} behavior * @return int the ID of the attachment */ function media_handle_upload($file_id, $post_id, $post_data = array(), $overrides = array( 'test_form' => false )) { $time = current_time('mysql'); if ( $post = get_post($post_id) ) { if ( substr( $post->post_date, 0, 4 ) > 0 ) $time = $post->post_date; } $name = $_FILES[$file_id]['name']; $file = wp_handle_upload($_FILES[$file_id], $overrides, $time); if ( isset($file['error']) ) return new WP_Error( 'upload_error', $file['error'] ); $name_parts = pathinfo($name); $name = trim( substr( $name, 0, -(1 + strlen($name_parts['extension'])) ) ); $url = $file['url']; $type = $file['type']; $file = $file['file']; $title = $name; $content = ''; // use image exif/iptc data for title and caption defaults if possible if ( $image_meta = @wp_read_image_metadata($file) ) { if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) $title = $image_meta['title']; if ( trim( $image_meta['caption'] ) ) $content = $image_meta['caption']; } // Construct the attachment array $attachment = array_merge( array( 'post_mime_type' => $type, 'guid' => $url, 'post_parent' => $post_id, 'post_title' => $title, 'post_content' => $content, ), $post_data ); // This should never be set as it would then overwrite an existing attachment. if ( isset( $attachment['ID'] ) ) unset( $attachment['ID'] ); // Save the data $id = wp_insert_attachment($attachment, $file, $post_id); if ( !is_wp_error($id) ) { wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) ); } return $id; } /** * This handles a sideloaded file in the same way as an uploaded file is handled by {@link media_handle_upload()} * * @since 2.6.0 * * @param array $file_array Array similar to a {@link $_FILES} upload array * @param int $post_id The post ID the media is associated with * @param string $desc Description of the sideloaded file * @param array $post_data allows you to overwrite some of the attachment * @return int|object The ID of the attachment or a WP_Error on failure */ function media_handle_sideload($file_array, $post_id, $desc = null, $post_data = array()) { $overrides = array('test_form'=>false); $time = current_time( 'mysql' ); if ( $post = get_post( $post_id ) ) { if ( substr( $post->post_date, 0, 4 ) > 0 ) $time = $post->post_date; } $file = wp_handle_sideload( $file_array, $overrides, $time ); if ( isset($file['error']) ) return new WP_Error( 'upload_error', $file['error'] ); $url = $file['url']; $type = $file['type']; $file = $file['file']; $title = preg_replace('/\.[^.]+$/', '', basename($file)); $content = ''; // use image exif/iptc data for title and caption defaults if possible if ( $image_meta = @wp_read_image_metadata($file) ) { if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) $title = $image_meta['title']; if ( trim( $image_meta['caption'] ) ) $content = $image_meta['caption']; } if ( isset( $desc ) ) $title = $desc; // Construct the attachment array $attachment = array_merge( array( 'post_mime_type' => $type, 'guid' => $url, 'post_parent' => $post_id, 'post_title' => $title, 'post_content' => $content, ), $post_data ); // This should never be set as it would then overwrite an existing attachment. if ( isset( $attachment['ID'] ) ) unset( $attachment['ID'] ); // Save the attachment metadata $id = wp_insert_attachment($attachment, $file, $post_id); if ( !is_wp_error($id) ) wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) ); return $id; } /** * Adds the iframe to display content for the media upload page * * @since 2.5.0 * * @param array $content_func */ function wp_iframe($content_func /* ... */) { _wp_admin_html_begin(); ?> <title><?php bloginfo('name') ?> &rsaquo; <?php _e('Uploads'); ?> &#8212; <?php _e('WordPress'); ?></title> <?php wp_enqueue_style( 'colors' ); // Check callback name for 'media' if ( ( is_array( $content_func ) && ! empty( $content_func[1] ) && 0 === strpos( (string) $content_func[1], 'media' ) ) || ( ! is_array( $content_func ) && 0 === strpos( $content_func, 'media' ) ) ) wp_enqueue_style( 'media' ); wp_enqueue_style( 'ie' ); ?> <script type="text/javascript"> //<![CDATA[ addLoadEvent = function(func){if(typeof jQuery!="undefined")jQuery(document).ready(func);else if(typeof wpOnload!='function'){wpOnload=func;}else{var oldonload=wpOnload;wpOnload=function(){oldonload();func();}}}; var userSettings = {'url':'<?php echo SITECOOKIEPATH; ?>','uid':'<?php if ( ! isset($current_user) ) $current_user = wp_get_current_user(); echo $current_user->ID; ?>','time':'<?php echo time(); ?>'}; var ajaxurl = '<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>', pagenow = 'media-upload-popup', adminpage = 'media-upload-popup', isRtl = <?php echo (int) is_rtl(); ?>; //]]> </script> <?php do_action('admin_enqueue_scripts', 'media-upload-popup'); do_action('admin_print_styles-media-upload-popup'); do_action('admin_print_styles'); do_action('admin_print_scripts-media-upload-popup'); do_action('admin_print_scripts'); do_action('admin_head-media-upload-popup'); do_action('admin_head'); if ( is_string($content_func) ) do_action( "admin_head_{$content_func}" ); ?> </head> <body<?php if ( isset($GLOBALS['body_id']) ) echo ' id="' . $GLOBALS['body_id'] . '"'; ?> class="wp-core-ui no-js"> <script type="text/javascript"> document.body.className = document.body.className.replace('no-js', 'js'); </script> <?php $args = func_get_args(); $args = array_slice($args, 1); call_user_func_array($content_func, $args); do_action('admin_print_footer_scripts'); ?> <script type="text/javascript">if(typeof wpOnload=='function')wpOnload();</script> </body> </html> <?php } /** * Adds the media button to the editor * * @since 2.5.0 * * @param string $editor_id */ function media_buttons($editor_id = 'content') { $post = get_post(); if ( ! $post && ! empty( $GLOBALS['post_ID'] ) ) $post = $GLOBALS['post_ID']; wp_enqueue_media( array( 'post' => $post ) ); $img = '<span class="wp-media-buttons-icon"></span> '; echo '<a href="#" class="button insert-media add_media" data-editor="' . esc_attr( $editor_id ) . '" title="' . esc_attr__( 'Add Media' ) . '">' . $img . __( 'Add Media' ) . '</a>'; // Don't use this filter. Want to add a button? Use the media_buttons action. $legacy_filter = apply_filters('media_buttons_context', ''); // deprecated if ( $legacy_filter ) { // #WP22559. Close <a> if a plugin started by closing <a> to open their own <a> tag. if ( 0 === stripos( trim( $legacy_filter ), '</a>' ) ) $legacy_filter .= '</a>'; echo $legacy_filter; } } add_action( 'media_buttons', 'media_buttons' ); function get_upload_iframe_src( $type = null, $post_id = null, $tab = null ) { global $post_ID; if ( empty( $post_id ) ) $post_id = $post_ID; $upload_iframe_src = add_query_arg( 'post_id', (int) $post_id, admin_url('media-upload.php') ); if ( $type && 'media' != $type ) $upload_iframe_src = add_query_arg('type', $type, $upload_iframe_src); if ( ! empty( $tab ) ) $upload_iframe_src = add_query_arg('tab', $tab, $upload_iframe_src); $upload_iframe_src = apply_filters($type . '_upload_iframe_src', $upload_iframe_src); return add_query_arg('TB_iframe', true, $upload_iframe_src); } /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @return mixed void|object WP_Error on failure */ function media_upload_form_handler() { check_admin_referer('media-form'); $errors = null; if ( isset($_POST['send']) ) { $keys = array_keys($_POST['send']); $send_id = (int) array_shift($keys); } if ( !empty($_POST['attachments']) ) foreach ( $_POST['attachments'] as $attachment_id => $attachment ) { $post = $_post = get_post($attachment_id, ARRAY_A); $post_type_object = get_post_type_object( $post[ 'post_type' ] ); if ( !current_user_can( $post_type_object->cap->edit_post, $attachment_id ) ) continue; if ( isset($attachment['post_content']) ) $post['post_content'] = $attachment['post_content']; if ( isset($attachment['post_title']) ) $post['post_title'] = $attachment['post_title']; if ( isset($attachment['post_excerpt']) ) $post['post_excerpt'] = $attachment['post_excerpt']; if ( isset($attachment['menu_order']) ) $post['menu_order'] = $attachment['menu_order']; if ( isset($send_id) && $attachment_id == $send_id ) { if ( isset($attachment['post_parent']) ) $post['post_parent'] = $attachment['post_parent']; } $post = apply_filters('attachment_fields_to_save', $post, $attachment); if ( isset($attachment['image_alt']) ) { $image_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true); if ( $image_alt != stripslashes($attachment['image_alt']) ) { $image_alt = wp_strip_all_tags( stripslashes($attachment['image_alt']), true ); // update_meta expects slashed update_post_meta( $attachment_id, '_wp_attachment_image_alt', addslashes($image_alt) ); } } if ( isset($post['errors']) ) { $errors[$attachment_id] = $post['errors']; unset($post['errors']); } if ( $post != $_post ) wp_update_post($post); foreach ( get_attachment_taxonomies($post) as $t ) { if ( isset($attachment[$t]) ) wp_set_object_terms($attachment_id, array_map('trim', preg_split('/,+/', $attachment[$t])), $t, false); } } if ( isset($_POST['insert-gallery']) || isset($_POST['update-gallery']) ) { ?> <script type="text/javascript"> /* <![CDATA[ */ var win = window.dialogArguments || opener || parent || top; win.tb_remove(); /* ]]> */ </script> <?php exit; } if ( isset($send_id) ) { $attachment = stripslashes_deep( $_POST['attachments'][$send_id] ); $html = isset( $attachment['post_title'] ) ? $attachment['post_title'] : ''; if ( !empty($attachment['url']) ) { $rel = ''; if ( strpos($attachment['url'], 'attachment_id') || get_attachment_link($send_id) == $attachment['url'] ) $rel = " rel='attachment wp-att-" . esc_attr($send_id) . "'"; $html = "<a href='{$attachment['url']}'$rel>$html</a>"; } $html = apply_filters('media_send_to_editor', $html, $send_id, $attachment); return media_send_to_editor($html); } return $errors; } /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @return mixed */ function wp_media_upload_handler() { $errors = array(); $id = 0; if ( isset($_POST['html-upload']) && !empty($_FILES) ) { check_admin_referer('media-form'); // Upload File button was clicked $id = media_handle_upload('async-upload', $_REQUEST['post_id']); unset($_FILES); if ( is_wp_error($id) ) { $errors['upload_error'] = $id; $id = false; } } if ( !empty($_POST['insertonlybutton']) ) { $src = $_POST['src']; if ( !empty($src) && !strpos($src, '://') ) $src = "http://$src"; if ( isset( $_POST['media_type'] ) && 'image' != $_POST['media_type'] ) { $title = esc_html( stripslashes( $_POST['title'] ) ); if ( empty( $title ) ) $title = esc_html( basename( $src ) ); if ( $title && $src ) $html = "<a href='" . esc_url($src) . "'>$title</a>"; $type = 'file'; if ( ( $ext = preg_replace( '/^.+?\.([^.]+)$/', '$1', $src ) ) && ( $ext_type = wp_ext2type( $ext ) ) && ( 'audio' == $ext_type || 'video' == $ext_type ) ) $type = $ext_type; $html = apply_filters( $type . '_send_to_editor_url', $html, esc_url_raw( $src ), $title ); } else { $align = ''; $alt = esc_attr( stripslashes( $_POST['alt'] ) ); if ( isset($_POST['align']) ) { $align = esc_attr( stripslashes( $_POST['align'] ) ); $class = " class='align$align'"; } if ( !empty($src) ) $html = "<img src='" . esc_url($src) . "' alt='$alt'$class />"; $html = apply_filters( 'image_send_to_editor_url', $html, esc_url_raw( $src ), $alt, $align ); } return media_send_to_editor($html); } if ( !empty($_POST) ) { $return = media_upload_form_handler(); if ( is_string($return) ) return $return; if ( is_array($return) ) $errors = $return; } if ( isset($_POST['save']) ) { $errors['upload_notice'] = __('Saved.'); return media_upload_gallery(); } if ( isset($_GET['tab']) && $_GET['tab'] == 'type_url' ) { $type = 'image'; if ( isset( $_GET['type'] ) && in_array( $_GET['type'], array( 'video', 'audio', 'file' ) ) ) $type = $_GET['type']; return wp_iframe( 'media_upload_type_url_form', $type, $errors, $id ); } return wp_iframe( 'media_upload_type_form', 'image', $errors, $id ); } /** * Download an image from the specified URL and attach it to a post. * * @since 2.6.0 * * @param string $file The URL of the image to download * @param int $post_id The post ID the media is to be associated with * @param string $desc Optional. Description of the image * @return string|WP_Error Populated HTML img tag on success */ function media_sideload_image($file, $post_id, $desc = null) { if ( ! empty($file) ) { // Download file to temp location $tmp = download_url( $file ); // Set variables for storage // fix file filename for query strings preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches ); $file_array['name'] = basename($matches[0]); $file_array['tmp_name'] = $tmp; // If error storing temporarily, unlink if ( is_wp_error( $tmp ) ) { @unlink($file_array['tmp_name']); $file_array['tmp_name'] = ''; } // do the validation and storage stuff $id = media_handle_sideload( $file_array, $post_id, $desc ); // If error storing permanently, unlink if ( is_wp_error($id) ) { @unlink($file_array['tmp_name']); return $id; } $src = wp_get_attachment_url( $id ); } // Finally check to make sure the file has been saved, then return the html if ( ! empty($src) ) { $alt = isset($desc) ? esc_attr($desc) : ''; $html = "<img src='$src' alt='$alt' />"; return $html; } } /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @return unknown */ function media_upload_gallery() { $errors = array(); if ( !empty($_POST) ) { $return = media_upload_form_handler(); if ( is_string($return) ) return $return; if ( is_array($return) ) $errors = $return; } wp_enqueue_script('admin-gallery'); return wp_iframe( 'media_upload_gallery_form', $errors ); } /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @return unknown */ function media_upload_library() { $errors = array(); if ( !empty($_POST) ) { $return = media_upload_form_handler(); if ( is_string($return) ) return $return; if ( is_array($return) ) $errors = $return; } return wp_iframe( 'media_upload_library_form', $errors ); } /** * Retrieve HTML for the image alignment radio buttons with the specified one checked. * * @since 2.7.0 * * @param object $post * @param string $checked * @return string */ function image_align_input_fields( $post, $checked = '' ) { if ( empty($checked) ) $checked = get_user_setting('align', 'none'); $alignments = array('none' => __('None'), 'left' => __('Left'), 'center' => __('Center'), 'right' => __('Right')); if ( !array_key_exists( (string) $checked, $alignments ) ) $checked = 'none'; $out = array(); foreach ( $alignments as $name => $label ) { $name = esc_attr($name); $out[] = "<input type='radio' name='attachments[{$post->ID}][align]' id='image-align-{$name}-{$post->ID}' value='$name'". ( $checked == $name ? " checked='checked'" : "" ) . " /><label for='image-align-{$name}-{$post->ID}' class='align image-align-{$name}-label'>$label</label>"; } return join("\n", $out); } /** * Retrieve HTML for the size radio buttons with the specified one checked. * * @since 2.7.0 * * @param object $post * @param bool|string $check * @return array */ function image_size_input_fields( $post, $check = '' ) { // get a list of the actual pixel dimensions of each possible intermediate version of this image $size_names = apply_filters( 'image_size_names_choose', array('thumbnail' => __('Thumbnail'), 'medium' => __('Medium'), 'large' => __('Large'), 'full' => __('Full Size')) ); if ( empty($check) ) $check = get_user_setting('imgsize', 'medium'); foreach ( $size_names as $size => $label ) { $downsize = image_downsize($post->ID, $size); $checked = ''; // is this size selectable? $enabled = ( $downsize[3] || 'full' == $size ); $css_id = "image-size-{$size}-{$post->ID}"; // if this size is the default but that's not available, don't select it if ( $size == $check ) { if ( $enabled ) $checked = " checked='checked'"; else $check = ''; } elseif ( !$check && $enabled && 'thumbnail' != $size ) { // if $check is not enabled, default to the first available size that's bigger than a thumbnail $check = $size; $checked = " checked='checked'"; } $html = "<div class='image-size-item'><input type='radio' " . disabled( $enabled, false, false ) . "name='attachments[$post->ID][image-size]' id='{$css_id}' value='{$size}'$checked />"; $html .= "<label for='{$css_id}'>$label</label>"; // only show the dimensions if that choice is available if ( $enabled ) $html .= " <label for='{$css_id}' class='help'>" . sprintf( "(%d&nbsp;&times;&nbsp;%d)", $downsize[1], $downsize[2] ). "</label>"; $html .= '</div>'; $out[] = $html; } return array( 'label' => __('Size'), 'input' => 'html', 'html' => join("\n", $out), ); } /** * Retrieve HTML for the Link URL buttons with the default link type as specified. * * @since 2.7.0 * * @param object $post * @param string $url_type * @return string */ function image_link_input_fields($post, $url_type = '') { $file = wp_get_attachment_url($post->ID); $link = get_attachment_link($post->ID); if ( empty($url_type) ) $url_type = get_user_setting('urlbutton', 'post'); $url = ''; if ( $url_type == 'file' ) $url = $file; elseif ( $url_type == 'post' ) $url = $link; return " <input type='text' class='text urlfield' name='attachments[$post->ID][url]' value='" . esc_attr($url) . "' /><br /> <button type='button' class='button urlnone' data-link-url=''>" . __('None') . "</button> <button type='button' class='button urlfile' data-link-url='" . esc_attr($file) . "'>" . __('File URL') . "</button> <button type='button' class='button urlpost' data-link-url='" . esc_attr($link) . "'>" . __('Attachment Post URL') . "</button> "; } function wp_caption_input_textarea($edit_post) { // post data is already escaped $name = "attachments[{$edit_post->ID}][post_excerpt]"; return '<textarea name="' . $name . '" id="' . $name . '">' . $edit_post->post_excerpt . '</textarea>'; } /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @param array $form_fields * @param object $post * @return array */ function image_attachment_fields_to_edit($form_fields, $post) { return $form_fields; } /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @param array $form_fields * @param object $post {@internal $post not used}} * @return array */ function media_single_attachment_fields_to_edit( $form_fields, $post ) { unset($form_fields['url'], $form_fields['align'], $form_fields['image-size']); return $form_fields; } /** * {@internal Missing Short Description}} * * @since 2.8.0 * * @param array $form_fields * @param object $post {@internal $post not used}} * @return array */ function media_post_single_attachment_fields_to_edit( $form_fields, $post ) { unset($form_fields['image_url']); return $form_fields; } /** * Filters input from media_upload_form_handler() and assigns a default * post_title from the file name if none supplied. * * Illustrates the use of the attachment_fields_to_save filter * which can be used to add default values to any field before saving to DB. * * @since 2.5.0 * * @param object $post * @param array $attachment {@internal $attachment not used}} * @return array */ function image_attachment_fields_to_save($post, $attachment) { if ( substr($post['post_mime_type'], 0, 5) == 'image' ) { if ( strlen(trim($post['post_title'])) == 0 ) { $post['post_title'] = preg_replace('/\.\w+$/', '', basename($post['guid'])); $post['errors']['post_title']['errors'][] = __('Empty Title filled from filename.'); } } return $post; } add_filter('attachment_fields_to_save', 'image_attachment_fields_to_save', 10, 2); /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @param string $html * @param integer $attachment_id * @param array $attachment * @return array */ function image_media_send_to_editor($html, $attachment_id, $attachment) { $post = get_post($attachment_id); if ( substr($post->post_mime_type, 0, 5) == 'image' ) { $url = $attachment['url']; $align = !empty($attachment['align']) ? $attachment['align'] : 'none'; $size = !empty($attachment['image-size']) ? $attachment['image-size'] : 'medium'; $alt = !empty($attachment['image_alt']) ? $attachment['image_alt'] : ''; $rel = ( $url == get_attachment_link($attachment_id) ); return get_image_send_to_editor($attachment_id, $attachment['post_excerpt'], $attachment['post_title'], $align, $url, $rel, $size, $alt); } return $html; } add_filter('media_send_to_editor', 'image_media_send_to_editor', 10, 3); /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @param object $post * @param array $errors * @return array */ function get_attachment_fields_to_edit($post, $errors = null) { if ( is_int($post) ) $post = get_post($post); if ( is_array($post) ) $post = new WP_Post( (object) $post ); $image_url = wp_get_attachment_url($post->ID); $edit_post = sanitize_post($post, 'edit'); $form_fields = array( 'post_title' => array( 'label' => __('Title'), 'value' => $edit_post->post_title ), 'image_alt' => array(), 'post_excerpt' => array( 'label' => __('Caption'), 'input' => 'html', 'html' => wp_caption_input_textarea($edit_post) ), 'post_content' => array( 'label' => __('Description'), 'value' => $edit_post->post_content, 'input' => 'textarea' ), 'url' => array( 'label' => __('Link URL'), 'input' => 'html', 'html' => image_link_input_fields($post, get_option('image_default_link_type')), 'helps' => __('Enter a link URL or click above for presets.') ), 'menu_order' => array( 'label' => __('Order'), 'value' => $edit_post->menu_order ), 'image_url' => array( 'label' => __('File URL'), 'input' => 'html', 'html' => "<input type='text' class='text urlfield' readonly='readonly' name='attachments[$post->ID][url]' value='" . esc_attr($image_url) . "' /><br />", 'value' => wp_get_attachment_url($post->ID), 'helps' => __('Location of the uploaded file.') ) ); foreach ( get_attachment_taxonomies($post) as $taxonomy ) { $t = (array) get_taxonomy($taxonomy); if ( ! $t['public'] || ! $t['show_ui'] ) continue; if ( empty($t['label']) ) $t['label'] = $taxonomy; if ( empty($t['args']) ) $t['args'] = array(); $terms = get_object_term_cache($post->ID, $taxonomy); if ( false === $terms ) $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']); $values = array(); foreach ( $terms as $term ) $values[] = $term->slug; $t['value'] = join(', ', $values); $form_fields[$taxonomy] = $t; } // Merge default fields with their errors, so any key passed with the error (e.g. 'error', 'helps', 'value') will replace the default // The recursive merge is easily traversed with array casting: foreach( (array) $things as $thing ) $form_fields = array_merge_recursive($form_fields, (array) $errors); // This was formerly in image_attachment_fields_to_edit(). if ( substr($post->post_mime_type, 0, 5) == 'image' ) { $alt = get_post_meta($post->ID, '_wp_attachment_image_alt', true); if ( empty($alt) ) $alt = ''; $form_fields['post_title']['required'] = true; $form_fields['image_alt'] = array( 'value' => $alt, 'label' => __('Alternative Text'), 'helps' => __('Alt text for the image, e.g. &#8220;The Mona Lisa&#8221;') ); $form_fields['align'] = array( 'label' => __('Alignment'), 'input' => 'html', 'html' => image_align_input_fields($post, get_option('image_default_align')), ); $form_fields['image-size'] = image_size_input_fields( $post, get_option('image_default_size', 'medium') ); } else { unset( $form_fields['image_alt'] ); } $form_fields = apply_filters('attachment_fields_to_edit', $form_fields, $post); return $form_fields; } /** * Retrieve HTML for media items of post gallery. * * The HTML markup retrieved will be created for the progress of SWF Upload * component. Will also create link for showing and hiding the form to modify * the image attachment. * * @since 2.5.0 * * @param int $post_id Optional. Post ID. * @param array $errors Errors for attachment, if any. * @return string */ function get_media_items( $post_id, $errors ) { $attachments = array(); if ( $post_id ) { $post = get_post($post_id); if ( $post && $post->post_type == 'attachment' ) $attachments = array($post->ID => $post); else $attachments = get_children( array( 'post_parent' => $post_id, 'post_type' => 'attachment', 'orderby' => 'menu_order ASC, ID', 'order' => 'DESC') ); } else { if ( is_array($GLOBALS['wp_the_query']->posts) ) foreach ( $GLOBALS['wp_the_query']->posts as $attachment ) $attachments[$attachment->ID] = $attachment; } $output = ''; foreach ( (array) $attachments as $id => $attachment ) { if ( $attachment->post_status == 'trash' ) continue; if ( $item = get_media_item( $id, array( 'errors' => isset($errors[$id]) ? $errors[$id] : null) ) ) $output .= "\n<div id='media-item-$id' class='media-item child-of-$attachment->post_parent preloaded'><div class='progress hidden'><div class='bar'></div></div><div id='media-upload-error-$id' class='hidden'></div><div class='filename hidden'></div>$item\n</div>"; } return $output; } /** * Retrieve HTML form for modifying the image attachment. * * @since 2.5.0 * * @param int $attachment_id Attachment ID for modification. * @param string|array $args Optional. Override defaults. * @return string HTML form for attachment. */ function get_media_item( $attachment_id, $args = null ) { global $redir_tab; if ( ( $attachment_id = intval( $attachment_id ) ) && $thumb_url = wp_get_attachment_image_src( $attachment_id, 'thumbnail', true ) ) $thumb_url = $thumb_url[0]; else $thumb_url = false; $post = get_post( $attachment_id ); $current_post_id = !empty( $_GET['post_id'] ) ? (int) $_GET['post_id'] : 0; $default_args = array( 'errors' => null, 'send' => $current_post_id ? post_type_supports( get_post_type( $current_post_id ), 'editor' ) : true, 'delete' => true, 'toggle' => true, 'show_title' => true ); $args = wp_parse_args( $args, $default_args ); $args = apply_filters( 'get_media_item_args', $args ); extract( $args, EXTR_SKIP ); $toggle_on = __( 'Show' ); $toggle_off = __( 'Hide' ); $filename = esc_html( wp_basename( $post->guid ) ); $title = esc_attr( $post->post_title ); if ( $_tags = get_the_tags( $attachment_id ) ) { foreach ( $_tags as $tag ) $tags[] = $tag->name; $tags = esc_attr( join( ', ', $tags ) ); } $post_mime_types = get_post_mime_types(); $keys = array_keys( wp_match_mime_types( array_keys( $post_mime_types ), $post->post_mime_type ) ); $type = array_shift( $keys ); $type_html = "<input type='hidden' id='type-of-$attachment_id' value='" . esc_attr( $type ) . "' />"; $form_fields = get_attachment_fields_to_edit( $post, $errors ); if ( $toggle ) { $class = empty( $errors ) ? 'startclosed' : 'startopen'; $toggle_links = " <a class='toggle describe-toggle-on' href='#'>$toggle_on</a> <a class='toggle describe-toggle-off' href='#'>$toggle_off</a>"; } else { $class = ''; $toggle_links = ''; } $display_title = ( !empty( $title ) ) ? $title : $filename; // $title shouldn't ever be empty, but just in case $display_title = $show_title ? "<div class='filename new'><span class='title'>" . wp_html_excerpt( $display_title, 60 ) . "</span></div>" : ''; $gallery = ( ( isset( $_REQUEST['tab'] ) && 'gallery' == $_REQUEST['tab'] ) || ( isset( $redir_tab ) && 'gallery' == $redir_tab ) ); $order = ''; foreach ( $form_fields as $key => $val ) { if ( 'menu_order' == $key ) { if ( $gallery ) $order = "<div class='menu_order'> <input class='menu_order_input' type='text' id='attachments[$attachment_id][menu_order]' name='attachments[$attachment_id][menu_order]' value='" . esc_attr( $val['value'] ). "' /></div>"; else $order = "<input type='hidden' name='attachments[$attachment_id][menu_order]' value='" . esc_attr( $val['value'] ) . "' />"; unset( $form_fields['menu_order'] ); break; } } $media_dims = ''; $meta = wp_get_attachment_metadata( $post->ID ); if ( is_array( $meta ) && array_key_exists( 'width', $meta ) && array_key_exists( 'height', $meta ) ) $media_dims .= "<span id='media-dims-$post->ID'>{$meta['width']}&nbsp;&times;&nbsp;{$meta['height']}</span> "; $media_dims = apply_filters( 'media_meta', $media_dims, $post ); $image_edit_button = ''; if ( wp_attachment_is_image( $post->ID ) && wp_image_editor_supports( array( 'mime_type' => $post->post_mime_type ) ) ) { $nonce = wp_create_nonce( "image_editor-$post->ID" ); $image_edit_button = "<input type='button' id='imgedit-open-btn-$post->ID' onclick='imageEdit.open( $post->ID, \"$nonce\" )' class='button' value='" . esc_attr__( 'Edit Image' ) . "' /> <span class='spinner'></span>"; } $attachment_url = get_permalink( $attachment_id ); $item = " $type_html $toggle_links $order $display_title <table class='slidetoggle describe $class'> <thead class='media-item-info' id='media-head-$post->ID'> <tr valign='top'> <td class='A1B1' id='thumbnail-head-$post->ID'> <p><a href='$attachment_url' target='_blank'><img class='thumbnail' src='$thumb_url' alt='' /></a></p> <p>$image_edit_button</p> </td> <td> <p><strong>" . __('File name:') . "</strong> $filename</p> <p><strong>" . __('File type:') . "</strong> $post->post_mime_type</p> <p><strong>" . __('Upload date:') . "</strong> " . mysql2date( get_option('date_format'), $post->post_date ). '</p>'; if ( !empty( $media_dims ) ) $item .= "<p><strong>" . __('Dimensions:') . "</strong> $media_dims</p>\n"; $item .= "</td></tr>\n"; $item .= " </thead> <tbody> <tr><td colspan='2' class='imgedit-response' id='imgedit-response-$post->ID'></td></tr> <tr><td style='display:none' colspan='2' class='image-editor' id='image-editor-$post->ID'></td></tr>\n"; $defaults = array( 'input' => 'text', 'required' => false, 'value' => '', 'extra_rows' => array(), ); if ( $send ) $send = get_submit_button( __( 'Insert into Post' ), 'button', "send[$attachment_id]", false ); if ( $delete && current_user_can( 'delete_post', $attachment_id ) ) { if ( !EMPTY_TRASH_DAYS ) { $delete = "<a href='" . wp_nonce_url( "post.php?action=delete&amp;post=$attachment_id", 'delete-post_' . $attachment_id ) . "' id='del[$attachment_id]' class='delete-permanently'>" . __( 'Delete Permanently' ) . '</a>'; } elseif ( !MEDIA_TRASH ) { $delete = "<a href='#' class='del-link' onclick=\"document.getElementById('del_attachment_$attachment_id').style.display='block';return false;\">" . __( 'Delete' ) . "</a> <div id='del_attachment_$attachment_id' class='del-attachment' style='display:none;'><p>" . sprintf( __( 'You are about to delete <strong>%s</strong>.' ), $filename ) . "</p> <a href='" . wp_nonce_url( "post.php?action=delete&amp;post=$attachment_id", 'delete-post_' . $attachment_id ) . "' id='del[$attachment_id]' class='button'>" . __( 'Continue' ) . "</a> <a href='#' class='button' onclick=\"this.parentNode.style.display='none';return false;\">" . __( 'Cancel' ) . "</a> </div>"; } else { $delete = "<a href='" . wp_nonce_url( "post.php?action=trash&amp;post=$attachment_id", 'trash-post_' . $attachment_id ) . "' id='del[$attachment_id]' class='delete'>" . __( 'Move to Trash' ) . "</a> <a href='" . wp_nonce_url( "post.php?action=untrash&amp;post=$attachment_id", 'untrash-post_' . $attachment_id ) . "' id='undo[$attachment_id]' class='undo hidden'>" . __( 'Undo' ) . "</a>"; } } else { $delete = ''; } $thumbnail = ''; $calling_post_id = 0; if ( isset( $_GET['post_id'] ) ) $calling_post_id = absint( $_GET['post_id'] ); elseif ( isset( $_POST ) && count( $_POST ) ) // Like for async-upload where $_GET['post_id'] isn't set $calling_post_id = $post->post_parent; if ( 'image' == $type && $calling_post_id && current_theme_supports( 'post-thumbnails', get_post_type( $calling_post_id ) ) && post_type_supports( get_post_type( $calling_post_id ), 'thumbnail' ) && get_post_thumbnail_id( $calling_post_id ) != $attachment_id ) { $ajax_nonce = wp_create_nonce( "set_post_thumbnail-$calling_post_id" ); $thumbnail = "<a class='wp-post-thumbnail' id='wp-post-thumbnail-" . $attachment_id . "' href='#' onclick='WPSetAsThumbnail(\"$attachment_id\", \"$ajax_nonce\");return false;'>" . esc_html__( "Use as featured image" ) . "</a>"; } if ( ( $send || $thumbnail || $delete ) && !isset( $form_fields['buttons'] ) ) $form_fields['buttons'] = array( 'tr' => "\t\t<tr class='submit'><td></td><td class='savesend'>$send $thumbnail $delete</td></tr>\n" ); $hidden_fields = array(); foreach ( $form_fields as $id => $field ) { if ( $id[0] == '_' ) continue; if ( !empty( $field['tr'] ) ) { $item .= $field['tr']; continue; } $field = array_merge( $defaults, $field ); $name = "attachments[$attachment_id][$id]"; if ( $field['input'] == 'hidden' ) { $hidden_fields[$name] = $field['value']; continue; } $required = $field['required'] ? '<span class="alignright"><abbr title="required" class="required">*</abbr></span>' : ''; $aria_required = $field['required'] ? " aria-required='true' " : ''; $class = $id; $class .= $field['required'] ? ' form-required' : ''; $item .= "\t\t<tr class='$class'>\n\t\t\t<th valign='top' scope='row' class='label'><label for='$name'><span class='alignleft'>{$field['label']}</span>$required<br class='clear' /></label></th>\n\t\t\t<td class='field'>"; if ( !empty( $field[ $field['input'] ] ) ) $item .= $field[ $field['input'] ]; elseif ( $field['input'] == 'textarea' ) { if ( 'post_content' == $id && user_can_richedit() ) { // sanitize_post() skips the post_content when user_can_richedit $field['value'] = htmlspecialchars( $field['value'], ENT_QUOTES ); } // post_excerpt is already escaped by sanitize_post() in get_attachment_fields_to_edit() $item .= "<textarea id='$name' name='$name' $aria_required>" . $field['value'] . '</textarea>'; } else { $item .= "<input type='text' class='text' id='$name' name='$name' value='" . esc_attr( $field['value'] ) . "' $aria_required />"; } if ( !empty( $field['helps'] ) ) $item .= "<p class='help'>" . join( "</p>\n<p class='help'>", array_unique( (array) $field['helps'] ) ) . '</p>'; $item .= "</td>\n\t\t</tr>\n"; $extra_rows = array(); if ( !empty( $field['errors'] ) ) foreach ( array_unique( (array) $field['errors'] ) as $error ) $extra_rows['error'][] = $error; if ( !empty( $field['extra_rows'] ) ) foreach ( $field['extra_rows'] as $class => $rows ) foreach ( (array) $rows as $html ) $extra_rows[$class][] = $html; foreach ( $extra_rows as $class => $rows ) foreach ( $rows as $html ) $item .= "\t\t<tr><td></td><td class='$class'>$html</td></tr>\n"; } if ( !empty( $form_fields['_final'] ) ) $item .= "\t\t<tr class='final'><td colspan='2'>{$form_fields['_final']}</td></tr>\n"; $item .= "\t</tbody>\n"; $item .= "\t</table>\n"; foreach ( $hidden_fields as $name => $value ) $item .= "\t<input type='hidden' name='$name' id='$name' value='" . esc_attr( $value ) . "' />\n"; if ( $post->post_parent < 1 && isset( $_REQUEST['post_id'] ) ) { $parent = (int) $_REQUEST['post_id']; $parent_name = "attachments[$attachment_id][post_parent]"; $item .= "\t<input type='hidden' name='$parent_name' id='$parent_name' value='$parent' />\n"; } return $item; } function get_compat_media_markup( $attachment_id, $args = null ) { $post = get_post( $attachment_id ); $default_args = array( 'errors' => null, 'in_modal' => false, ); $user_can_edit = current_user_can( 'edit_post', $attachment_id ); $args = wp_parse_args( $args, $default_args ); $args = apply_filters( 'get_media_item_args', $args ); $form_fields = array(); if ( $args['in_modal'] ) { foreach ( get_attachment_taxonomies($post) as $taxonomy ) { $t = (array) get_taxonomy($taxonomy); if ( ! $t['public'] || ! $t['show_ui'] ) continue; if ( empty($t['label']) ) $t['label'] = $taxonomy; if ( empty($t['args']) ) $t['args'] = array(); $terms = get_object_term_cache($post->ID, $taxonomy); if ( false === $terms ) $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']); $values = array(); foreach ( $terms as $term ) $values[] = $term->slug; $t['value'] = join(', ', $values); $t['taxonomy'] = true; $form_fields[$taxonomy] = $t; } } // Merge default fields with their errors, so any key passed with the error (e.g. 'error', 'helps', 'value') will replace the default // The recursive merge is easily traversed with array casting: foreach( (array) $things as $thing ) $form_fields = array_merge_recursive($form_fields, (array) $args['errors'] ); $form_fields = apply_filters( 'attachment_fields_to_edit', $form_fields, $post ); unset( $form_fields['image-size'], $form_fields['align'], $form_fields['image_alt'], $form_fields['post_title'], $form_fields['post_excerpt'], $form_fields['post_content'], $form_fields['url'], $form_fields['menu_order'], $form_fields['image_url'] ); $media_meta = apply_filters( 'media_meta', '', $post ); $defaults = array( 'input' => 'text', 'required' => false, 'value' => '', 'extra_rows' => array(), 'show_in_edit' => true, 'show_in_modal' => true, ); $hidden_fields = array(); $item = ''; foreach ( $form_fields as $id => $field ) { if ( $id[0] == '_' ) continue; $name = "attachments[$attachment_id][$id]"; $id_attr = "attachments-$attachment_id-$id"; if ( !empty( $field['tr'] ) ) { $item .= $field['tr']; continue; } $field = array_merge( $defaults, $field ); if ( ( ! $field['show_in_edit'] && ! $args['in_modal'] ) || ( ! $field['show_in_modal'] && $args['in_modal'] ) ) continue; if ( $field['input'] == 'hidden' ) { $hidden_fields[$name] = $field['value']; continue; } $readonly = ! $user_can_edit && ! empty( $field['taxonomy'] ) ? " readonly='readonly' " : ''; $required = $field['required'] ? '<span class="alignright"><abbr title="required" class="required">*</abbr></span>' : ''; $aria_required = $field['required'] ? " aria-required='true' " : ''; $class = 'compat-field-' . $id; $class .= $field['required'] ? ' form-required' : ''; $item .= "\t\t<tr class='$class'>"; $item .= "\t\t\t<th valign='top' scope='row' class='label'><label for='$id_attr'><span class='alignleft'>{$field['label']}</span>$required<br class='clear' /></label>"; $item .= "</th>\n\t\t\t<td class='field'>"; if ( !empty( $field[ $field['input'] ] ) ) $item .= $field[ $field['input'] ]; elseif ( $field['input'] == 'textarea' ) { if ( 'post_content' == $id && user_can_richedit() ) { // sanitize_post() skips the post_content when user_can_richedit $field['value'] = htmlspecialchars( $field['value'], ENT_QUOTES ); } $item .= "<textarea id='$id_attr' name='$name' $aria_required>" . $field['value'] . '</textarea>'; } else { $item .= "<input type='text' class='text' id='$id_attr' name='$name' value='" . esc_attr( $field['value'] ) . "' $readonly $aria_required />"; } if ( !empty( $field['helps'] ) ) $item .= "<p class='help'>" . join( "</p>\n<p class='help'>", array_unique( (array) $field['helps'] ) ) . '</p>'; $item .= "</td>\n\t\t</tr>\n"; $extra_rows = array(); if ( !empty( $field['errors'] ) ) foreach ( array_unique( (array) $field['errors'] ) as $error ) $extra_rows['error'][] = $error; if ( !empty( $field['extra_rows'] ) ) foreach ( $field['extra_rows'] as $class => $rows ) foreach ( (array) $rows as $html ) $extra_rows[$class][] = $html; foreach ( $extra_rows as $class => $rows ) foreach ( $rows as $html ) $item .= "\t\t<tr><td></td><td class='$class'>$html</td></tr>\n"; } if ( !empty( $form_fields['_final'] ) ) $item .= "\t\t<tr class='final'><td colspan='2'>{$form_fields['_final']}</td></tr>\n"; if ( $item ) $item = '<table class="compat-attachment-fields">' . $item . '</table>'; foreach ( $hidden_fields as $hidden_field => $value ) { $item .= '<input type="hidden" name="' . esc_attr( $hidden_field ) . '" value="' . esc_attr( $value ) . '" />' . "\n"; } return array( 'item' => $item, 'meta' => $media_meta, ); } /** * {@internal Missing Short Description}} * * @since 2.5.0 */ function media_upload_header() { $post_id = isset( $_REQUEST['post_id'] ) ? intval( $_REQUEST['post_id'] ) : 0; echo '<script type="text/javascript">post_id = ' . $post_id . ";</script>\n"; if ( empty( $_GET['chromeless'] ) ) { echo '<div id="media-upload-header">'; the_media_upload_tabs(); echo '</div>'; } } /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @param unknown_type $errors */ function media_upload_form( $errors = null ) { global $type, $tab, $pagenow, $is_IE, $is_opera; if ( ! _device_can_upload() ) { echo '<p>' . __('The web browser on your device cannot be used to upload files. You may be able to use the <a href="http://wordpress.org/extend/mobile/">native app for your device</a> instead.') . '</p>'; return; } $upload_action_url = admin_url('async-upload.php'); $post_id = isset($_REQUEST['post_id']) ? intval($_REQUEST['post_id']) : 0; $_type = isset($type) ? $type : ''; $_tab = isset($tab) ? $tab : ''; $upload_size_unit = $max_upload_size = wp_max_upload_size(); $sizes = array( 'KB', 'MB', 'GB' ); for ( $u = -1; $upload_size_unit > 1024 && $u < count( $sizes ) - 1; $u++ ) { $upload_size_unit /= 1024; } if ( $u < 0 ) { $upload_size_unit = 0; $u = 0; } else { $upload_size_unit = (int) $upload_size_unit; } ?> <div id="media-upload-notice"><?php if (isset($errors['upload_notice']) ) echo $errors['upload_notice']; ?></div> <div id="media-upload-error"><?php if (isset($errors['upload_error']) && is_wp_error($errors['upload_error'])) echo $errors['upload_error']->get_error_message(); ?></div> <?php if ( is_multisite() && !is_upload_space_available() ) { do_action( 'upload_ui_over_quota' ); return; } do_action('pre-upload-ui'); $post_params = array( "post_id" => $post_id, "_wpnonce" => wp_create_nonce('media-form'), "type" => $_type, "tab" => $_tab, "short" => "1", ); $post_params = apply_filters( 'upload_post_params', $post_params ); // hook change! old name: 'swfupload_post_params' $plupload_init = array( 'runtimes' => 'html5,silverlight,flash,html4', 'browse_button' => 'plupload-browse-button', 'container' => 'plupload-upload-ui', 'drop_element' => 'drag-drop-area', 'file_data_name' => 'async-upload', 'multiple_queues' => true, 'max_file_size' => $max_upload_size . 'b', 'url' => $upload_action_url, 'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'), 'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'), 'filters' => array( array('title' => __( 'Allowed Files' ), 'extensions' => '*') ), 'multipart' => true, 'urlstream_upload' => true, 'multipart_params' => $post_params ); // Multi-file uploading doesn't currently work in iOS Safari, // single-file allows the built-in camera to be used as source for images if ( wp_is_mobile() ) $plupload_init['multi_selection'] = false; $plupload_init = apply_filters( 'plupload_init', $plupload_init ); ?> <script type="text/javascript"> <?php // Verify size is an int. If not return default value. $large_size_h = absint( get_option('large_size_h') ); if( !$large_size_h ) $large_size_h = 1024; $large_size_w = absint( get_option('large_size_w') ); if( !$large_size_w ) $large_size_w = 1024; ?> var resize_height = <?php echo $large_size_h; ?>, resize_width = <?php echo $large_size_w; ?>, wpUploaderInit = <?php echo json_encode($plupload_init); ?>; </script> <div id="plupload-upload-ui" class="hide-if-no-js"> <?php do_action('pre-plupload-upload-ui'); // hook change, old name: 'pre-flash-upload-ui' ?> <div id="drag-drop-area"> <div class="drag-drop-inside"> <p class="drag-drop-info"><?php _e('Drop files here'); ?></p> <p><?php _ex('or', 'Uploader: Drop files here - or - Select Files'); ?></p> <p class="drag-drop-buttons"><input id="plupload-browse-button" type="button" value="<?php esc_attr_e('Select Files'); ?>" class="button" /></p> </div> </div> <?php do_action('post-plupload-upload-ui'); // hook change, old name: 'post-flash-upload-ui' ?> </div> <div id="html-upload-ui" class="hide-if-js"> <?php do_action('pre-html-upload-ui'); ?> <p id="async-upload-wrap"> <label class="screen-reader-text" for="async-upload"><?php _e('Upload'); ?></label> <input type="file" name="async-upload" id="async-upload" /> <?php submit_button( __( 'Upload' ), 'button', 'html-upload', false ); ?> <a href="#" onclick="try{top.tb_remove();}catch(e){}; return false;"><?php _e('Cancel'); ?></a> </p> <div class="clear"></div> <?php do_action('post-html-upload-ui'); ?> </div> <span class="max-upload-size"><?php printf( __( 'Maximum upload file size: %d%s.' ), esc_html($upload_size_unit), esc_html($sizes[$u]) ); ?></span> <?php if ( ($is_IE || $is_opera) && $max_upload_size > 100 * 1024 * 1024 ) { ?> <span class="big-file-warning"><?php _e('Your browser has some limitations uploading large files with the multi-file uploader. Please use the browser uploader for files over 100MB.'); ?></span> <?php } do_action('post-upload-ui'); } /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @param string $type * @param object $errors * @param integer $id */ function media_upload_type_form($type = 'file', $errors = null, $id = null) { media_upload_header(); $post_id = isset( $_REQUEST['post_id'] )? intval( $_REQUEST['post_id'] ) : 0; $form_action_url = admin_url("media-upload.php?type=$type&tab=type&post_id=$post_id"); $form_action_url = apply_filters('media_upload_form_url', $form_action_url, $type); $form_class = 'media-upload-form type-form validate'; if ( get_user_setting('uploader') ) $form_class .= ' html-uploader'; ?> <form enctype="multipart/form-data" method="post" action="<?php echo esc_attr($form_action_url); ?>" class="<?php echo $form_class; ?>" id="<?php echo $type; ?>-form"> <?php submit_button( '', 'hidden', 'save', false ); ?> <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" /> <?php wp_nonce_field('media-form'); ?> <h3 class="media-title"><?php _e('Add media files from your computer'); ?></h3> <?php media_upload_form( $errors ); ?> <script type="text/javascript"> //<![CDATA[ jQuery(function($){ var preloaded = $(".media-item.preloaded"); if ( preloaded.length > 0 ) { preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');}); } updateMediaForm(); }); //]]> </script> <div id="media-items"><?php if ( $id ) { if ( !is_wp_error($id) ) { add_filter('attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2); echo get_media_items( $id, $errors ); } else { echo '<div id="media-upload-error">'.esc_html($id->get_error_message()).'</div></div>'; exit; } } ?></div> <p class="savebutton ml-submit"> <?php submit_button( __( 'Save all changes' ), 'button', 'save', false ); ?> </p> </form> <?php } /** * {@internal Missing Short Description}} * * @since 2.7.0 * * @param string $type * @param object $errors * @param integer $id */ function media_upload_type_url_form($type = null, $errors = null, $id = null) { if ( null === $type ) $type = 'image'; media_upload_header(); $post_id = isset( $_REQUEST['post_id'] ) ? intval( $_REQUEST['post_id'] ) : 0; $form_action_url = admin_url("media-upload.php?type=$type&tab=type&post_id=$post_id"); $form_action_url = apply_filters('media_upload_form_url', $form_action_url, $type); $form_class = 'media-upload-form type-form validate'; if ( get_user_setting('uploader') ) $form_class .= ' html-uploader'; ?> <form enctype="multipart/form-data" method="post" action="<?php echo esc_attr($form_action_url); ?>" class="<?php echo $form_class; ?>" id="<?php echo $type; ?>-form"> <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" /> <?php wp_nonce_field('media-form'); ?> <h3 class="media-title"><?php _e('Insert media from another website'); ?></h3> <script type="text/javascript"> //<![CDATA[ var addExtImage = { width : '', height : '', align : 'alignnone', insert : function() { var t = this, html, f = document.forms[0], cls, title = '', alt = '', caption = ''; if ( '' == f.src.value || '' == t.width ) return false; if ( f.alt.value ) alt = f.alt.value.replace(/'/g, '&#039;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); <?php if ( ! apply_filters( 'disable_captions', '' ) ) { ?> if ( f.caption.value ) { caption = f.caption.value.replace(/\r\n|\r/g, '\n'); caption = caption.replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(a){ return a.replace(/[\r\n\t]+/, ' '); }); caption = caption.replace(/\s*\n\s*/g, '<br />'); } <?php } ?> cls = caption ? '' : ' class="'+t.align+'"'; html = '<img alt="'+alt+'" src="'+f.src.value+'"'+cls+' width="'+t.width+'" height="'+t.height+'" />'; if ( f.url.value ) { url = f.url.value.replace(/'/g, '&#039;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); html = '<a href="'+url+'">'+html+'</a>'; } if ( caption ) html = '[caption id="" align="'+t.align+'" width="'+t.width+'"]'+html+caption+'[/caption]'; var win = window.dialogArguments || opener || parent || top; win.send_to_editor(html); return false; }, resetImageData : function() { var t = addExtImage; t.width = t.height = ''; document.getElementById('go_button').style.color = '#bbb'; if ( ! document.forms[0].src.value ) document.getElementById('status_img').innerHTML = '*'; else document.getElementById('status_img').innerHTML = '<img src="<?php echo esc_url( admin_url( 'images/no.png' ) ); ?>" alt="" />'; }, updateImageData : function() { var t = addExtImage; t.width = t.preloadImg.width; t.height = t.preloadImg.height; document.getElementById('go_button').style.color = '#333'; document.getElementById('status_img').innerHTML = '<img src="<?php echo esc_url( admin_url( 'images/yes.png' ) ); ?>" alt="" />'; }, getImageData : function() { if ( jQuery('table.describe').hasClass('not-image') ) return; var t = addExtImage, src = document.forms[0].src.value; if ( ! src ) { t.resetImageData(); return false; } document.getElementById('status_img').innerHTML = '<img src="<?php echo esc_url( admin_url( 'images/wpspin_light.gif' ) ); ?>" alt="" width="16" />'; t.preloadImg = new Image(); t.preloadImg.onload = t.updateImageData; t.preloadImg.onerror = t.resetImageData; t.preloadImg.src = src; } } jQuery(document).ready( function($) { $('.media-types input').click( function() { $('table.describe').toggleClass('not-image', $('#not-image').prop('checked') ); }); }); //]]> </script> <div id="media-items"> <div class="media-item media-blank"> <?php echo apply_filters( 'type_url_form_media', wp_media_insert_url_form( $type ) ); ?> </div> </div> </form> <?php } /** * Adds gallery form to upload iframe * * @since 2.5.0 * * @param array $errors */ function media_upload_gallery_form($errors) { global $redir_tab, $type; $redir_tab = 'gallery'; media_upload_header(); $post_id = intval($_REQUEST['post_id']); $form_action_url = admin_url("media-upload.php?type=$type&tab=gallery&post_id=$post_id"); $form_action_url = apply_filters('media_upload_form_url', $form_action_url, $type); $form_class = 'media-upload-form validate'; if ( get_user_setting('uploader') ) $form_class .= ' html-uploader'; ?> <script type="text/javascript"> <!-- jQuery(function($){ var preloaded = $(".media-item.preloaded"); if ( preloaded.length > 0 ) { preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');}); updateMediaForm(); } }); --> </script> <div id="sort-buttons" class="hide-if-no-js"> <span> <?php _e('All Tabs:'); ?> <a href="#" id="showall"><?php _e('Show'); ?></a> <a href="#" id="hideall" style="display:none;"><?php _e('Hide'); ?></a> </span> <?php _e('Sort Order:'); ?> <a href="#" id="asc"><?php _e('Ascending'); ?></a> | <a href="#" id="desc"><?php _e('Descending'); ?></a> | <a href="#" id="clear"><?php _ex('Clear', 'verb'); ?></a> </div> <form enctype="multipart/form-data" method="post" action="<?php echo esc_attr($form_action_url); ?>" class="<?php echo $form_class; ?>" id="gallery-form"> <?php wp_nonce_field('media-form'); ?> <?php //media_upload_form( $errors ); ?> <table class="widefat" cellspacing="0"> <thead><tr> <th><?php _e('Media'); ?></th> <th class="order-head"><?php _e('Order'); ?></th> <th class="actions-head"><?php _e('Actions'); ?></th> </tr></thead> </table> <div id="media-items"> <?php add_filter('attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2); ?> <?php echo get_media_items($post_id, $errors); ?> </div> <p class="ml-submit"> <?php submit_button( __( 'Save all changes' ), 'button savebutton', 'save', false, array( 'id' => 'save-all', 'style' => 'display: none;' ) ); ?> <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" /> <input type="hidden" name="type" value="<?php echo esc_attr( $GLOBALS['type'] ); ?>" /> <input type="hidden" name="tab" value="<?php echo esc_attr( $GLOBALS['tab'] ); ?>" /> </p> <div id="gallery-settings" style="display:none;"> <div class="title"><?php _e('Gallery Settings'); ?></div> <table id="basic" class="describe"><tbody> <tr> <th scope="row" class="label"> <label> <span class="alignleft"><?php _e('Link thumbnails to:'); ?></span> </label> </th> <td class="field"> <input type="radio" name="linkto" id="linkto-file" value="file" /> <label for="linkto-file" class="radio"><?php _e('Image File'); ?></label> <input type="radio" checked="checked" name="linkto" id="linkto-post" value="post" /> <label for="linkto-post" class="radio"><?php _e('Attachment Page'); ?></label> </td> </tr> <tr> <th scope="row" class="label"> <label> <span class="alignleft"><?php _e('Order images by:'); ?></span> </label> </th> <td class="field"> <select id="orderby" name="orderby"> <option value="menu_order" selected="selected"><?php _e('Menu order'); ?></option> <option value="title"><?php _e('Title'); ?></option> <option value="post_date"><?php _e('Date/Time'); ?></option> <option value="rand"><?php _e('Random'); ?></option> </select> </td> </tr> <tr> <th scope="row" class="label"> <label> <span class="alignleft"><?php _e('Order:'); ?></span> </label> </th> <td class="field"> <input type="radio" checked="checked" name="order" id="order-asc" value="asc" /> <label for="order-asc" class="radio"><?php _e('Ascending'); ?></label> <input type="radio" name="order" id="order-desc" value="desc" /> <label for="order-desc" class="radio"><?php _e('Descending'); ?></label> </td> </tr> <tr> <th scope="row" class="label"> <label> <span class="alignleft"><?php _e('Gallery columns:'); ?></span> </label> </th> <td class="field"> <select id="columns" name="columns"> <option value="1">1</option> <option value="2">2</option> <option value="3" selected="selected">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> </select> </td> </tr> </tbody></table> <p class="ml-submit"> <input type="button" class="button" style="display:none;" onMouseDown="wpgallery.update();" name="insert-gallery" id="insert-gallery" value="<?php esc_attr_e( 'Insert gallery' ); ?>" /> <input type="button" class="button" style="display:none;" onMouseDown="wpgallery.update();" name="update-gallery" id="update-gallery" value="<?php esc_attr_e( 'Update gallery settings' ); ?>" /> </p> </div> </form> <?php } /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @param array $errors */ function media_upload_library_form($errors) { global $wpdb, $wp_query, $wp_locale, $type, $tab, $post_mime_types; media_upload_header(); $post_id = isset( $_REQUEST['post_id'] ) ? intval( $_REQUEST['post_id'] ) : 0; $form_action_url = admin_url("media-upload.php?type=$type&tab=library&post_id=$post_id"); $form_action_url = apply_filters('media_upload_form_url', $form_action_url, $type); $form_class = 'media-upload-form validate'; if ( get_user_setting('uploader') ) $form_class .= ' html-uploader'; $_GET['paged'] = isset( $_GET['paged'] ) ? intval($_GET['paged']) : 0; if ( $_GET['paged'] < 1 ) $_GET['paged'] = 1; $start = ( $_GET['paged'] - 1 ) * 10; if ( $start < 1 ) $start = 0; add_filter( 'post_limits', create_function( '$a', "return 'LIMIT $start, 10';" ) ); list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query(); ?> <form id="filter" action="" method="get"> <input type="hidden" name="type" value="<?php echo esc_attr( $type ); ?>" /> <input type="hidden" name="tab" value="<?php echo esc_attr( $tab ); ?>" /> <input type="hidden" name="post_id" value="<?php echo (int) $post_id; ?>" /> <input type="hidden" name="post_mime_type" value="<?php echo isset( $_GET['post_mime_type'] ) ? esc_attr( $_GET['post_mime_type'] ) : ''; ?>" /> <input type="hidden" name="context" value="<?php echo isset( $_GET['context'] ) ? esc_attr( $_GET['context'] ) : ''; ?>" /> <p id="media-search" class="search-box"> <label class="screen-reader-text" for="media-search-input"><?php _e('Search Media');?>:</label> <input type="search" id="media-search-input" name="s" value="<?php the_search_query(); ?>" /> <?php submit_button( __( 'Search Media' ), 'button', '', false ); ?> </p> <ul class="subsubsub"> <?php $type_links = array(); $_num_posts = (array) wp_count_attachments(); $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts)); foreach ( $matches as $_type => $reals ) foreach ( $reals as $real ) if ( isset($num_posts[$_type]) ) $num_posts[$_type] += $_num_posts[$real]; else $num_posts[$_type] = $_num_posts[$real]; // If available type specified by media button clicked, filter by that type if ( empty($_GET['post_mime_type']) && !empty($num_posts[$type]) ) { $_GET['post_mime_type'] = $type; list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query(); } if ( empty($_GET['post_mime_type']) || $_GET['post_mime_type'] == 'all' ) $class = ' class="current"'; else $class = ''; $type_links[] = "<li><a href='" . esc_url(add_query_arg(array('post_mime_type'=>'all', 'paged'=>false, 'm'=>false))) . "'$class>".__('All Types')."</a>"; foreach ( $post_mime_types as $mime_type => $label ) { $class = ''; if ( !wp_match_mime_types($mime_type, $avail_post_mime_types) ) continue; if ( isset($_GET['post_mime_type']) && wp_match_mime_types($mime_type, $_GET['post_mime_type']) ) $class = ' class="current"'; $type_links[] = "<li><a href='" . esc_url(add_query_arg(array('post_mime_type'=>$mime_type, 'paged'=>false))) . "'$class>" . sprintf( translate_nooped_plural( $label[2], $num_posts[$mime_type] ), "<span id='$mime_type-counter'>" . number_format_i18n( $num_posts[$mime_type] ) . '</span>') . '</a>'; } echo implode(' | </li>', apply_filters( 'media_upload_mime_type_links', $type_links ) ) . '</li>'; unset($type_links); ?> </ul> <div class="tablenav"> <?php $page_links = paginate_links( array( 'base' => add_query_arg( 'paged', '%#%' ), 'format' => '', 'prev_text' => __('&laquo;'), 'next_text' => __('&raquo;'), 'total' => ceil($wp_query->found_posts / 10), 'current' => $_GET['paged'] )); if ( $page_links ) echo "<div class='tablenav-pages'>$page_links</div>"; ?> <div class="alignleft actions"> <?php $arc_query = "SELECT DISTINCT YEAR(post_date) AS yyear, MONTH(post_date) AS mmonth FROM $wpdb->posts WHERE post_type = 'attachment' ORDER BY post_date DESC"; $arc_result = $wpdb->get_results( $arc_query ); $month_count = count($arc_result); if ( $month_count && !( 1 == $month_count && 0 == $arc_result[0]->mmonth ) ) { ?> <select name='m'> <option<?php selected( @$_GET['m'], 0 ); ?> value='0'><?php _e('Show all dates'); ?></option> <?php foreach ($arc_result as $arc_row) { if ( $arc_row->yyear == 0 ) continue; $arc_row->mmonth = zeroise( $arc_row->mmonth, 2 ); if ( isset($_GET['m']) && ( $arc_row->yyear . $arc_row->mmonth == $_GET['m'] ) ) $default = ' selected="selected"'; else $default = ''; echo "<option$default value='" . esc_attr( $arc_row->yyear . $arc_row->mmonth ) . "'>"; echo esc_html( $wp_locale->get_month($arc_row->mmonth) . " $arc_row->yyear" ); echo "</option>\n"; } ?> </select> <?php } ?> <?php submit_button( __( 'Filter &#187;' ), 'button', 'post-query-submit', false ); ?> </div> <br class="clear" /> </div> </form> <form enctype="multipart/form-data" method="post" action="<?php echo esc_attr($form_action_url); ?>" class="<?php echo $form_class; ?>" id="library-form"> <?php wp_nonce_field('media-form'); ?> <?php //media_upload_form( $errors ); ?> <script type="text/javascript"> <!-- jQuery(function($){ var preloaded = $(".media-item.preloaded"); if ( preloaded.length > 0 ) { preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');}); updateMediaForm(); } }); --> </script> <div id="media-items"> <?php add_filter('attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2); ?> <?php echo get_media_items(null, $errors); ?> </div> <p class="ml-submit"> <?php submit_button( __( 'Save all changes' ), 'button savebutton', 'save', false ); ?> <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" /> </p> </form> <?php } /** * Creates the form for external url * * @since 2.7.0 * * @param string $default_view * @return string the form html */ function wp_media_insert_url_form( $default_view = 'image' ) { if ( !apply_filters( 'disable_captions', '' ) ) { $caption = ' <tr class="image-only"> <th valign="top" scope="row" class="label"> <label for="caption"><span class="alignleft">' . __('Image Caption') . '</span></label> </th> <td class="field"><textarea id="caption" name="caption"></textarea></td> </tr> '; } else { $caption = ''; } $default_align = get_option('image_default_align'); if ( empty($default_align) ) $default_align = 'none'; if ( 'image' == $default_view ) { $view = 'image-only'; $table_class = ''; } else { $view = $table_class = 'not-image'; } return ' <p class="media-types"><label><input type="radio" name="media_type" value="image" id="image-only"' . checked( 'image-only', $view, false ) . ' /> ' . __( 'Image' ) . '</label> &nbsp; &nbsp; <label><input type="radio" name="media_type" value="generic" id="not-image"' . checked( 'not-image', $view, false ) . ' /> ' . __( 'Audio, Video, or Other File' ) . '</label></p> <table class="describe ' . $table_class . '"><tbody> <tr> <th valign="top" scope="row" class="label" style="width:130px;"> <label for="src"><span class="alignleft">' . __('URL') . '</span></label> <span class="alignright"><abbr id="status_img" title="required" class="required">*</abbr></span> </th> <td class="field"><input id="src" name="src" value="" type="text" aria-required="true" onblur="addExtImage.getImageData()" /></td> </tr> <tr> <th valign="top" scope="row" class="label"> <label for="title"><span class="alignleft">' . __('Title') . '</span></label> <span class="alignright"><abbr title="required" class="required">*</abbr></span> </th> <td class="field"><input id="title" name="title" value="" type="text" aria-required="true" /></td> </tr> <tr class="not-image"><td></td><td><p class="help">' . __('Link text, e.g. &#8220;Ransom Demands (PDF)&#8221;') . '</p></td></tr> <tr class="image-only"> <th valign="top" scope="row" class="label"> <label for="alt"><span class="alignleft">' . __('Alternative Text') . '</span></label> </th> <td class="field"><input id="alt" name="alt" value="" type="text" aria-required="true" /> <p class="help">' . __('Alt text for the image, e.g. &#8220;The Mona Lisa&#8221;') . '</p></td> </tr> ' . $caption . ' <tr class="align image-only"> <th valign="top" scope="row" class="label"><p><label for="align">' . __('Alignment') . '</label></p></th> <td class="field"> <input name="align" id="align-none" value="none" onclick="addExtImage.align=\'align\'+this.value" type="radio"' . ($default_align == 'none' ? ' checked="checked"' : '').' /> <label for="align-none" class="align image-align-none-label">' . __('None') . '</label> <input name="align" id="align-left" value="left" onclick="addExtImage.align=\'align\'+this.value" type="radio"' . ($default_align == 'left' ? ' checked="checked"' : '').' /> <label for="align-left" class="align image-align-left-label">' . __('Left') . '</label> <input name="align" id="align-center" value="center" onclick="addExtImage.align=\'align\'+this.value" type="radio"' . ($default_align == 'center' ? ' checked="checked"' : '').' /> <label for="align-center" class="align image-align-center-label">' . __('Center') . '</label> <input name="align" id="align-right" value="right" onclick="addExtImage.align=\'align\'+this.value" type="radio"' . ($default_align == 'right' ? ' checked="checked"' : '').' /> <label for="align-right" class="align image-align-right-label">' . __('Right') . '</label> </td> </tr> <tr class="image-only"> <th valign="top" scope="row" class="label"> <label for="url"><span class="alignleft">' . __('Link Image To:') . '</span></label> </th> <td class="field"><input id="url" name="url" value="" type="text" /><br /> <button type="button" class="button" value="" onclick="document.forms[0].url.value=null">' . __('None') . '</button> <button type="button" class="button" value="" onclick="document.forms[0].url.value=document.forms[0].src.value">' . __('Link to image') . '</button> <p class="help">' . __('Enter a link URL or click above for presets.') . '</p></td> </tr> <tr class="image-only"> <td></td> <td> <input type="button" class="button" id="go_button" style="color:#bbb;" onclick="addExtImage.insert()" value="' . esc_attr__('Insert into Post') . '" /> </td> </tr> <tr class="not-image"> <td></td> <td> ' . get_submit_button( __( 'Insert into Post' ), 'button', 'insertonlybutton', false ) . ' </td> </tr> </tbody></table> '; } /** * Displays the multi-file uploader message. * * @since 2.6.0 */ function media_upload_flash_bypass() { $browser_uploader = admin_url( 'media-new.php?browser-uploader' ); if ( $post = get_post() ) $browser_uploader .= '&amp;post_id=' . intval( $post->ID ); elseif ( ! empty( $GLOBALS['post_ID'] ) ) $browser_uploader .= '&amp;post_id=' . intval( $GLOBALS['post_ID'] ); ?> <p class="upload-flash-bypass"> <?php printf( __( 'You are using the multi-file uploader. Problems? Try the <a href="%1$s" target="%2$s">browser uploader</a> instead.' ), $browser_uploader, '_blank' ); ?> </p> <?php } add_action('post-plupload-upload-ui', 'media_upload_flash_bypass'); /** * Displays the browser's built-in uploader message. * * @since 2.6.0 */ function media_upload_html_bypass() { ?> <p class="upload-html-bypass hide-if-no-js"> <?php _e('You are using the browser&#8217;s built-in file uploader. The WordPress uploader includes multiple file selection and drag and drop capability. <a href="#">Switch to the multi-file uploader</a>.'); ?> </p> <?php } add_action('post-html-upload-ui', 'media_upload_html_bypass'); /** * Used to display a "After a file has been uploaded..." help message. * * @since 3.3.0 */ function media_upload_text_after() {} /** * Displays the checkbox to scale images. * * @since 3.3.0 */ function media_upload_max_image_resize() { $checked = get_user_setting('upload_resize') ? ' checked="true"' : ''; $a = $end = ''; if ( current_user_can( 'manage_options' ) ) { $a = '<a href="' . esc_url( admin_url( 'options-media.php' ) ) . '" target="_blank">'; $end = '</a>'; } ?> <p class="hide-if-no-js"><label> <input name="image_resize" type="checkbox" id="image_resize" value="true"<?php echo $checked; ?> /> <?php /* translators: %1$s is link start tag, %2$s is link end tag, %3$d is width, %4$d is height*/ printf( __( 'Scale images to match the large size selected in %1$simage options%2$s (%3$d &times; %4$d).' ), $a, $end, (int) get_option( 'large_size_w', '1024' ), (int) get_option( 'large_size_h', '1024' ) ); ?> </label></p> <?php } /** * Displays the out of storage quota message in Multisite. * * @since 3.5.0 */ function multisite_over_quota_message() { echo '<p>' . sprintf( __( 'Sorry, you have used all of your storage quota of %s MB.' ), get_space_allowed() ) . '</p>'; } /** * Displays the image and editor in the post editor * * @since 3.5.0 */ function edit_form_image_editor() { $post = get_post(); $open = isset( $_GET['image-editor'] ); if ( $open ) require_once ABSPATH . 'wp-admin/includes/image-edit.php'; $thumb_url = false; if ( $attachment_id = intval( $post->ID ) ) $thumb_url = wp_get_attachment_image_src( $attachment_id, array( 900, 450 ), true ); $filename = esc_html( basename( $post->guid ) ); $title = esc_attr( $post->post_title ); $alt_text = get_post_meta( $post->ID, '_wp_attachment_image_alt', true ); $att_url = wp_get_attachment_url( $post->ID ); if ( wp_attachment_is_image( $post->ID ) ) : $image_edit_button = ''; if ( wp_image_editor_supports( array( 'mime_type' => $post->post_mime_type ) ) ) { $nonce = wp_create_nonce( "image_editor-$post->ID" ); $image_edit_button = "<input type='button' id='imgedit-open-btn-$post->ID' onclick='imageEdit.open( $post->ID, \"$nonce\" )' class='button' value='" . esc_attr__( 'Edit Image' ) . "' /> <span class='spinner'></span>"; } ?> <div class="wp_attachment_holder"> <div class="imgedit-response" id="imgedit-response-<?php echo $attachment_id; ?>"></div> <div<?php if ( $open ) echo ' style="display:none"'; ?> class="wp_attachment_image" id="media-head-<?php echo $attachment_id; ?>"> <p id="thumbnail-head-<?php echo $attachment_id; ?>"><img class="thumbnail" src="<?php echo set_url_scheme( $thumb_url[0] ); ?>" style="max-width:100%" alt="" /></p> <p><?php echo $image_edit_button; ?></p> </div> <div<?php if ( ! $open ) echo ' style="display:none"'; ?> class="image-editor" id="image-editor-<?php echo $attachment_id; ?>"> <?php if ( $open ) wp_image_editor( $attachment_id ); ?> </div> </div> <?php endif; ?> <div class="wp_attachment_details"> <p> <label for="attachment_caption"><strong><?php _e( 'Caption' ); ?></strong></label><br /> <textarea class="widefat" name="excerpt" id="attachment_caption"><?php echo $post->post_excerpt; ?></textarea> </p> <?php if ( 'image' === substr( $post->post_mime_type, 0, 5 ) ) : ?> <p> <label for="attachment_alt"><strong><?php _e( 'Alternative Text' ); ?></strong></label><br /> <input type="text" class="widefat" name="_wp_attachment_image_alt" id="attachment_alt" value="<?php echo esc_attr( $alt_text ); ?>" /> </p> <?php endif; ?> <?php $quicktags_settings = array( 'buttons' => 'strong,em,link,block,del,ins,img,ul,ol,li,code,spell,close' ); $editor_args = array( 'textarea_name' => 'content', 'textarea_rows' => 5, 'media_buttons' => false, 'tinymce' => false, 'quicktags' => $quicktags_settings, ); ?> <label for="content"><strong><?php _e( 'Description' ); ?></strong></label> <?php wp_editor( $post->post_content, 'attachment_content', $editor_args ); ?> </div> <?php $extras = get_compat_media_markup( $post->ID ); echo $extras['item']; echo '<input type="hidden" id="image-edit-context" value="edit-attachment" />' . "\n"; } /** * Displays non-editable attachment metadata in the publish metabox * * @since 3.5.0 */ function attachment_submitbox_metadata() { $post = get_post(); $filename = esc_html( basename( $post->guid ) ); $media_dims = ''; $meta = wp_get_attachment_metadata( $post->ID ); if ( is_array( $meta ) && array_key_exists( 'width', $meta ) && array_key_exists( 'height', $meta ) ) $media_dims .= "<span id='media-dims-$post->ID'>{$meta['width']}&nbsp;&times;&nbsp;{$meta['height']}</span> "; $media_dims = apply_filters( 'media_meta', $media_dims, $post ); $att_url = wp_get_attachment_url( $post->ID ); ?> <div class="misc-pub-section"> <label for="attachment_url"><?php _e( 'File URL:' ); ?></label> <input type="text" class="widefat urlfield" readonly="readonly" name="attachment_url" value="<?php echo esc_attr($att_url); ?>" /> </div> <div class="misc-pub-section"> <?php _e( 'File name:' ); ?> <strong><?php echo $filename; ?></strong> </div> <div class="misc-pub-section"> <?php _e( 'File type:' ); ?> <strong><?php if ( preg_match( '/^.*?\.(\w+)$/', get_attached_file( $post->ID ), $matches ) ) echo esc_html( strtoupper( $matches[1] ) ); else echo strtoupper( str_replace( 'image/', '', $post->post_mime_type ) ); ?></strong> </div> <?php if ( $media_dims ) : ?> <div class="misc-pub-section"> <?php _e( 'Dimensions:' ); ?> <strong><?php echo $media_dims; ?></strong> </div> <?php endif; } add_filter( 'async_upload_image', 'get_media_item', 10, 2 ); add_filter( 'async_upload_audio', 'get_media_item', 10, 2 ); add_filter( 'async_upload_video', 'get_media_item', 10, 2 ); add_filter( 'async_upload_file', 'get_media_item', 10, 2 ); add_action( 'media_upload_image', 'wp_media_upload_handler' ); add_action( 'media_upload_audio', 'wp_media_upload_handler' ); add_action( 'media_upload_video', 'wp_media_upload_handler' ); add_action( 'media_upload_file', 'wp_media_upload_handler' ); add_filter( 'media_upload_gallery', 'media_upload_gallery' ); add_filter( 'media_upload_library', 'media_upload_library' ); add_action( 'attachment_submitbox_misc_actions', 'attachment_submitbox_metadata' );
zyblog
trunk/zyblog/wp-admin/includes/media.php
PHP
asf20
80,953
<?php /** * WordPress Upgrade API * * Most of the functions are pluggable and can be overwritten * * @package WordPress * @subpackage Administration */ /** Include user install customize script. */ if ( file_exists(WP_CONTENT_DIR . '/install.php') ) require (WP_CONTENT_DIR . '/install.php'); /** WordPress Administration API */ require_once(ABSPATH . 'wp-admin/includes/admin.php'); /** WordPress Schema API */ require_once(ABSPATH . 'wp-admin/includes/schema.php'); if ( !function_exists('wp_install') ) : /** * Installs the blog * * {@internal Missing Long Description}} * * @since 2.1.0 * * @param string $blog_title Blog title. * @param string $user_name User's username. * @param string $user_email User's email. * @param bool $public Whether blog is public. * @param null $deprecated Optional. Not used. * @param string $user_password Optional. User's chosen password. Will default to a random password. * @return array Array keys 'url', 'user_id', 'password', 'password_message'. */ function wp_install( $blog_title, $user_name, $user_email, $public, $deprecated = '', $user_password = '' ) { if ( !empty( $deprecated ) ) _deprecated_argument( __FUNCTION__, '2.6' ); wp_check_mysql_version(); wp_cache_flush(); make_db_current_silent(); populate_options(); populate_roles(); update_option('blogname', $blog_title); update_option('admin_email', $user_email); update_option('blog_public', $public); $guessurl = wp_guess_url(); update_option('siteurl', $guessurl); // If not a public blog, don't ping. if ( ! $public ) update_option('default_pingback_flag', 0); // Create default user. If the user already exists, the user tables are // being shared among blogs. Just set the role in that case. $user_id = username_exists($user_name); $user_password = trim($user_password); $email_password = false; if ( !$user_id && empty($user_password) ) { $user_password = wp_generate_password( 12, false ); $message = __('<strong><em>Note that password</em></strong> carefully! It is a <em>random</em> password that was generated just for you.'); $user_id = wp_create_user($user_name, $user_password, $user_email); update_user_option($user_id, 'default_password_nag', true, true); $email_password = true; } else if ( !$user_id ) { // Password has been provided $message = '<em>'.__('Your chosen password.').'</em>'; $user_id = wp_create_user($user_name, $user_password, $user_email); } else { $message = __('User already exists. Password inherited.'); } $user = new WP_User($user_id); $user->set_role('administrator'); wp_install_defaults($user_id); flush_rewrite_rules(); wp_new_blog_notification($blog_title, $guessurl, $user_id, ($email_password ? $user_password : __('The password you chose during the install.') ) ); wp_cache_flush(); return array('url' => $guessurl, 'user_id' => $user_id, 'password' => $user_password, 'password_message' => $message); } endif; if ( !function_exists('wp_install_defaults') ) : /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 2.1.0 * * @param int $user_id User ID. */ function wp_install_defaults($user_id) { global $wpdb, $wp_rewrite, $current_site, $table_prefix; // Default category $cat_name = __('Uncategorized'); /* translators: Default category slug */ $cat_slug = sanitize_title(_x('Uncategorized', 'Default category slug')); if ( global_terms_enabled() ) { $cat_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = %s", $cat_slug ) ); if ( $cat_id == null ) { $wpdb->insert( $wpdb->sitecategories, array('cat_ID' => 0, 'cat_name' => $cat_name, 'category_nicename' => $cat_slug, 'last_updated' => current_time('mysql', true)) ); $cat_id = $wpdb->insert_id; } update_option('default_category', $cat_id); } else { $cat_id = 1; } $wpdb->insert( $wpdb->terms, array('term_id' => $cat_id, 'name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0) ); $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $cat_id, 'taxonomy' => 'category', 'description' => '', 'parent' => 0, 'count' => 1)); $cat_tt_id = $wpdb->insert_id; // First post $now = date('Y-m-d H:i:s'); $now_gmt = gmdate('Y-m-d H:i:s'); $first_post_guid = get_option('home') . '/?p=1'; if ( is_multisite() ) { $first_post = get_site_option( 'first_post' ); if ( empty($first_post) ) $first_post = stripslashes( __( 'Welcome to <a href="SITE_URL">SITE_NAME</a>. This is your first post. Edit or delete it, then start blogging!' ) ); $first_post = str_replace( "SITE_URL", esc_url( network_home_url() ), $first_post ); $first_post = str_replace( "SITE_NAME", $current_site->site_name, $first_post ); } else { $first_post = __('Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!'); } $wpdb->insert( $wpdb->posts, array( 'post_author' => $user_id, 'post_date' => $now, 'post_date_gmt' => $now_gmt, 'post_content' => $first_post, 'post_excerpt' => '', 'post_title' => __('Hello world!'), /* translators: Default post slug */ 'post_name' => sanitize_title( _x('hello-world', 'Default post slug') ), 'post_modified' => $now, 'post_modified_gmt' => $now_gmt, 'guid' => $first_post_guid, 'comment_count' => 1, 'to_ping' => '', 'pinged' => '', 'post_content_filtered' => '' )); $wpdb->insert( $wpdb->term_relationships, array('term_taxonomy_id' => $cat_tt_id, 'object_id' => 1) ); // Default comment $first_comment_author = __('Mr WordPress'); $first_comment_url = 'http://wordpress.org/'; $first_comment = __('Hi, this is a comment. To delete a comment, just log in and view the post&#039;s comments. There you will have the option to edit or delete them.'); if ( is_multisite() ) { $first_comment_author = get_site_option( 'first_comment_author', $first_comment_author ); $first_comment_url = get_site_option( 'first_comment_url', network_home_url() ); $first_comment = get_site_option( 'first_comment', $first_comment ); } $wpdb->insert( $wpdb->comments, array( 'comment_post_ID' => 1, 'comment_author' => $first_comment_author, 'comment_author_email' => '', 'comment_author_url' => $first_comment_url, 'comment_date' => $now, 'comment_date_gmt' => $now_gmt, 'comment_content' => $first_comment )); // First Page $first_page = sprintf( __( "This is an example page. It's different from a blog post because it will stay in one place and will show up in your site navigation (in most themes). Most people start with an About page that introduces them to potential site visitors. It might say something like this: <blockquote>Hi there! I'm a bike messenger by day, aspiring actor by night, and this is my blog. I live in Los Angeles, have a great dog named Jack, and I like pi&#241;a coladas. (And gettin' caught in the rain.)</blockquote> ...or something like this: <blockquote>The XYZ Doohickey Company was founded in 1971, and has been providing quality doohickeys to the public ever since. Located in Gotham City, XYZ employs over 2,000 people and does all kinds of awesome things for the Gotham community.</blockquote> As a new WordPress user, you should go to <a href=\"%s\">your dashboard</a> to delete this page and create new pages for your content. Have fun!" ), admin_url() ); if ( is_multisite() ) $first_page = get_site_option( 'first_page', $first_page ); $first_post_guid = get_option('home') . '/?page_id=2'; $wpdb->insert( $wpdb->posts, array( 'post_author' => $user_id, 'post_date' => $now, 'post_date_gmt' => $now_gmt, 'post_content' => $first_page, 'post_excerpt' => '', 'post_title' => __( 'Sample Page' ), /* translators: Default page slug */ 'post_name' => __( 'sample-page' ), 'post_modified' => $now, 'post_modified_gmt' => $now_gmt, 'guid' => $first_post_guid, 'post_type' => 'page', 'to_ping' => '', 'pinged' => '', 'post_content_filtered' => '' )); $wpdb->insert( $wpdb->postmeta, array( 'post_id' => 2, 'meta_key' => '_wp_page_template', 'meta_value' => 'default' ) ); // Set up default widgets for default theme. update_option( 'widget_search', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) ); update_option( 'widget_recent-posts', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) ); update_option( 'widget_recent-comments', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) ); update_option( 'widget_archives', array ( 2 => array ( 'title' => '', 'count' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) ); update_option( 'widget_categories', array ( 2 => array ( 'title' => '', 'count' => 0, 'hierarchical' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) ); update_option( 'widget_meta', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) ); update_option( 'sidebars_widgets', array ( 'wp_inactive_widgets' => array ( ), 'sidebar-1' => array ( 0 => 'search-2', 1 => 'recent-posts-2', 2 => 'recent-comments-2', 3 => 'archives-2', 4 => 'categories-2', 5 => 'meta-2', ), 'sidebar-2' => array ( ), 'sidebar-3' => array ( ), 'array_version' => 3 ) ); if ( ! is_multisite() ) update_user_meta( $user_id, 'show_welcome_panel', 1 ); elseif ( ! is_super_admin( $user_id ) && ! metadata_exists( 'user', $user_id, 'show_welcome_panel' ) ) update_user_meta( $user_id, 'show_welcome_panel', 2 ); if ( is_multisite() ) { // Flush rules to pick up the new page. $wp_rewrite->init(); $wp_rewrite->flush_rules(); $user = new WP_User($user_id); $wpdb->update( $wpdb->options, array('option_value' => $user->user_email), array('option_name' => 'admin_email') ); // Remove all perms except for the login user. $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'user_level') ); $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'capabilities') ); // Delete any caps that snuck into the previously active blog. (Hardcoded to blog 1 for now.) TODO: Get previous_blog_id. if ( !is_super_admin( $user_id ) && $user_id != 1 ) $wpdb->delete( $wpdb->usermeta, array( 'user_id' => $user_id , 'meta_key' => $wpdb->base_prefix.'1_capabilities' ) ); } } endif; if ( !function_exists('wp_new_blog_notification') ) : /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 2.1.0 * * @param string $blog_title Blog title. * @param string $blog_url Blog url. * @param int $user_id User ID. * @param string $password User's Password. */ function wp_new_blog_notification($blog_title, $blog_url, $user_id, $password) { $user = new WP_User( $user_id ); $email = $user->user_email; $name = $user->user_login; $message = sprintf(__("Your new WordPress site has been successfully set up at: %1\$s You can log in to the administrator account with the following information: Username: %2\$s Password: %3\$s We hope you enjoy your new site. Thanks! --The WordPress Team http://wordpress.org/ "), $blog_url, $name, $password); @wp_mail($email, __('New WordPress Site'), $message); } endif; if ( !function_exists('wp_upgrade') ) : /** * Run WordPress Upgrade functions. * * {@internal Missing Long Description}} * * @since 2.1.0 * * @return null */ function wp_upgrade() { global $wp_current_db_version, $wp_db_version, $wpdb; $wp_current_db_version = __get_option('db_version'); // We are up-to-date. Nothing to do. if ( $wp_db_version == $wp_current_db_version ) return; if ( ! is_blog_installed() ) return; wp_check_mysql_version(); wp_cache_flush(); pre_schema_upgrade(); make_db_current_silent(); upgrade_all(); if ( is_multisite() && is_main_site() ) upgrade_network(); wp_cache_flush(); if ( is_multisite() ) { if ( $wpdb->get_row( "SELECT blog_id FROM {$wpdb->blog_versions} WHERE blog_id = '{$wpdb->blogid}'" ) ) $wpdb->query( "UPDATE {$wpdb->blog_versions} SET db_version = '{$wp_db_version}' WHERE blog_id = '{$wpdb->blogid}'" ); else $wpdb->query( "INSERT INTO {$wpdb->blog_versions} ( `blog_id` , `db_version` , `last_updated` ) VALUES ( '{$wpdb->blogid}', '{$wp_db_version}', NOW());" ); } } endif; /** * Functions to be called in install and upgrade scripts. * * {@internal Missing Long Description}} * * @since 1.0.1 */ function upgrade_all() { global $wp_current_db_version, $wp_db_version; $wp_current_db_version = __get_option('db_version'); // We are up-to-date. Nothing to do. if ( $wp_db_version == $wp_current_db_version ) return; // If the version is not set in the DB, try to guess the version. if ( empty($wp_current_db_version) ) { $wp_current_db_version = 0; // If the template option exists, we have 1.5. $template = __get_option('template'); if ( !empty($template) ) $wp_current_db_version = 2541; } if ( $wp_current_db_version < 6039 ) upgrade_230_options_table(); populate_options(); if ( $wp_current_db_version < 2541 ) { upgrade_100(); upgrade_101(); upgrade_110(); upgrade_130(); } if ( $wp_current_db_version < 3308 ) upgrade_160(); if ( $wp_current_db_version < 4772 ) upgrade_210(); if ( $wp_current_db_version < 4351 ) upgrade_old_slugs(); if ( $wp_current_db_version < 5539 ) upgrade_230(); if ( $wp_current_db_version < 6124 ) upgrade_230_old_tables(); if ( $wp_current_db_version < 7499 ) upgrade_250(); if ( $wp_current_db_version < 7935 ) upgrade_252(); if ( $wp_current_db_version < 8201 ) upgrade_260(); if ( $wp_current_db_version < 8989 ) upgrade_270(); if ( $wp_current_db_version < 10360 ) upgrade_280(); if ( $wp_current_db_version < 11958 ) upgrade_290(); if ( $wp_current_db_version < 15260 ) upgrade_300(); if ( $wp_current_db_version < 19389 ) upgrade_330(); if ( $wp_current_db_version < 20080 ) upgrade_340(); if ( $wp_current_db_version < 22422 ) upgrade_350(); maybe_disable_link_manager(); maybe_disable_automattic_widgets(); update_option( 'db_version', $wp_db_version ); update_option( 'db_upgraded', true ); } /** * Execute changes made in WordPress 1.0. * * @since 1.0.0 */ function upgrade_100() { global $wpdb; // Get the title and ID of every post, post_name to check if it already has a value $posts = $wpdb->get_results("SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''"); if ($posts) { foreach($posts as $post) { if ('' == $post->post_name) { $newtitle = sanitize_title($post->post_title); $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_name = %s WHERE ID = %d", $newtitle, $post->ID) ); } } } $categories = $wpdb->get_results("SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories"); foreach ($categories as $category) { if ('' == $category->category_nicename) { $newtitle = sanitize_title($category->cat_name); $wpdb>update( $wpdb->categories, array('category_nicename' => $newtitle), array('cat_ID' => $category->cat_ID) ); } } $wpdb->query("UPDATE $wpdb->options SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/') WHERE option_name LIKE 'links_rating_image%' AND option_value LIKE 'wp-links/links-images/%'"); $done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat"); if ($done_ids) : foreach ($done_ids as $done_id) : $done_posts[] = $done_id->post_id; endforeach; $catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')'; else: $catwhere = ''; endif; $allposts = $wpdb->get_results("SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere"); if ($allposts) : foreach ($allposts as $post) { // Check to see if it's already been imported $cat = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->post2cat WHERE post_id = %d AND category_id = %d", $post->ID, $post->post_category) ); if (!$cat && 0 != $post->post_category) { // If there's no result $wpdb->insert( $wpdb->post2cat, array('post_id' => $post->ID, 'category_id' => $post->post_category) ); } } endif; } /** * Execute changes made in WordPress 1.0.1. * * @since 1.0.1 */ function upgrade_101() { global $wpdb; // Clean up indices, add a few add_clean_index($wpdb->posts, 'post_name'); add_clean_index($wpdb->posts, 'post_status'); add_clean_index($wpdb->categories, 'category_nicename'); add_clean_index($wpdb->comments, 'comment_approved'); add_clean_index($wpdb->comments, 'comment_post_ID'); add_clean_index($wpdb->links , 'link_category'); add_clean_index($wpdb->links , 'link_visible'); } /** * Execute changes made in WordPress 1.2. * * @since 1.2.0 */ function upgrade_110() { global $wpdb; // Set user_nicename. $users = $wpdb->get_results("SELECT ID, user_nickname, user_nicename FROM $wpdb->users"); foreach ($users as $user) { if ('' == $user->user_nicename) { $newname = sanitize_title($user->user_nickname); $wpdb->update( $wpdb->users, array('user_nicename' => $newname), array('ID' => $user->ID) ); } } $users = $wpdb->get_results("SELECT ID, user_pass from $wpdb->users"); foreach ($users as $row) { if (!preg_match('/^[A-Fa-f0-9]{32}$/', $row->user_pass)) { $wpdb->update( $wpdb->users, array('user_pass' => md5($row->user_pass)), array('ID' => $row->ID) ); } } // Get the GMT offset, we'll use that later on $all_options = get_alloptions_110(); $time_difference = $all_options->time_difference; $server_time = time()+date('Z'); $weblogger_time = $server_time + $time_difference * HOUR_IN_SECONDS; $gmt_time = time(); $diff_gmt_server = ($gmt_time - $server_time) / HOUR_IN_SECONDS; $diff_weblogger_server = ($weblogger_time - $server_time) / HOUR_IN_SECONDS; $diff_gmt_weblogger = $diff_gmt_server - $diff_weblogger_server; $gmt_offset = -$diff_gmt_weblogger; // Add a gmt_offset option, with value $gmt_offset add_option('gmt_offset', $gmt_offset); // Check if we already set the GMT fields (if we did, then // MAX(post_date_gmt) can't be '0000-00-00 00:00:00' // <michel_v> I just slapped myself silly for not thinking about it earlier $got_gmt_fields = ! ($wpdb->get_var("SELECT MAX(post_date_gmt) FROM $wpdb->posts") == '0000-00-00 00:00:00'); if (!$got_gmt_fields) { // Add or subtract time to all dates, to get GMT dates $add_hours = intval($diff_gmt_weblogger); $add_minutes = intval(60 * ($diff_gmt_weblogger - $add_hours)); $wpdb->query("UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)"); $wpdb->query("UPDATE $wpdb->posts SET post_modified = post_date"); $wpdb->query("UPDATE $wpdb->posts SET post_modified_gmt = DATE_ADD(post_modified, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE) WHERE post_modified != '0000-00-00 00:00:00'"); $wpdb->query("UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)"); $wpdb->query("UPDATE $wpdb->users SET user_registered = DATE_ADD(user_registered, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)"); } } /** * Execute changes made in WordPress 1.5. * * @since 1.5.0 */ function upgrade_130() { global $wpdb; // Remove extraneous backslashes. $posts = $wpdb->get_results("SELECT ID, post_title, post_content, post_excerpt, guid, post_date, post_name, post_status, post_author FROM $wpdb->posts"); if ($posts) { foreach($posts as $post) { $post_content = addslashes(deslash($post->post_content)); $post_title = addslashes(deslash($post->post_title)); $post_excerpt = addslashes(deslash($post->post_excerpt)); if ( empty($post->guid) ) $guid = get_permalink($post->ID); else $guid = $post->guid; $wpdb->update( $wpdb->posts, compact('post_title', 'post_content', 'post_excerpt', 'guid'), array('ID' => $post->ID) ); } } // Remove extraneous backslashes. $comments = $wpdb->get_results("SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments"); if ($comments) { foreach($comments as $comment) { $comment_content = deslash($comment->comment_content); $comment_author = deslash($comment->comment_author); $wpdb->update($wpdb->comments, compact('comment_content', 'comment_author'), array('comment_ID' => $comment->comment_ID) ); } } // Remove extraneous backslashes. $links = $wpdb->get_results("SELECT link_id, link_name, link_description FROM $wpdb->links"); if ($links) { foreach($links as $link) { $link_name = deslash($link->link_name); $link_description = deslash($link->link_description); $wpdb->update( $wpdb->links, compact('link_name', 'link_description'), array('link_id' => $link->link_id) ); } } $active_plugins = __get_option('active_plugins'); // If plugins are not stored in an array, they're stored in the old // newline separated format. Convert to new format. if ( !is_array( $active_plugins ) ) { $active_plugins = explode("\n", trim($active_plugins)); update_option('active_plugins', $active_plugins); } // Obsolete tables $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optionvalues'); $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiontypes'); $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroups'); $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroup_options'); // Update comments table to use comment_type $wpdb->query("UPDATE $wpdb->comments SET comment_type='trackback', comment_content = REPLACE(comment_content, '<trackback />', '') WHERE comment_content LIKE '<trackback />%'"); $wpdb->query("UPDATE $wpdb->comments SET comment_type='pingback', comment_content = REPLACE(comment_content, '<pingback />', '') WHERE comment_content LIKE '<pingback />%'"); // Some versions have multiple duplicate option_name rows with the same values $options = $wpdb->get_results("SELECT option_name, COUNT(option_name) AS dupes FROM `$wpdb->options` GROUP BY option_name"); foreach ( $options as $option ) { if ( 1 != $option->dupes ) { // Could this be done in the query? $limit = $option->dupes - 1; $dupe_ids = $wpdb->get_col( $wpdb->prepare("SELECT option_id FROM $wpdb->options WHERE option_name = %s LIMIT %d", $option->option_name, $limit) ); if ( $dupe_ids ) { $dupe_ids = join($dupe_ids, ','); $wpdb->query("DELETE FROM $wpdb->options WHERE option_id IN ($dupe_ids)"); } } } make_site_theme(); } /** * Execute changes made in WordPress 2.0. * * @since 2.0.0 */ function upgrade_160() { global $wpdb, $wp_current_db_version; populate_roles_160(); $users = $wpdb->get_results("SELECT * FROM $wpdb->users"); foreach ( $users as $user ) : if ( !empty( $user->user_firstname ) ) update_user_meta( $user->ID, 'first_name', $wpdb->escape($user->user_firstname) ); if ( !empty( $user->user_lastname ) ) update_user_meta( $user->ID, 'last_name', $wpdb->escape($user->user_lastname) ); if ( !empty( $user->user_nickname ) ) update_user_meta( $user->ID, 'nickname', $wpdb->escape($user->user_nickname) ); if ( !empty( $user->user_level ) ) update_user_meta( $user->ID, $wpdb->prefix . 'user_level', $user->user_level ); if ( !empty( $user->user_icq ) ) update_user_meta( $user->ID, 'icq', $wpdb->escape($user->user_icq) ); if ( !empty( $user->user_aim ) ) update_user_meta( $user->ID, 'aim', $wpdb->escape($user->user_aim) ); if ( !empty( $user->user_msn ) ) update_user_meta( $user->ID, 'msn', $wpdb->escape($user->user_msn) ); if ( !empty( $user->user_yim ) ) update_user_meta( $user->ID, 'yim', $wpdb->escape($user->user_icq) ); if ( !empty( $user->user_description ) ) update_user_meta( $user->ID, 'description', $wpdb->escape($user->user_description) ); if ( isset( $user->user_idmode ) ): $idmode = $user->user_idmode; if ($idmode == 'nickname') $id = $user->user_nickname; if ($idmode == 'login') $id = $user->user_login; if ($idmode == 'firstname') $id = $user->user_firstname; if ($idmode == 'lastname') $id = $user->user_lastname; if ($idmode == 'namefl') $id = $user->user_firstname.' '.$user->user_lastname; if ($idmode == 'namelf') $id = $user->user_lastname.' '.$user->user_firstname; if (!$idmode) $id = $user->user_nickname; $wpdb->update( $wpdb->users, array('display_name' => $id), array('ID' => $user->ID) ); endif; // FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set. $caps = get_user_meta( $user->ID, $wpdb->prefix . 'capabilities'); if ( empty($caps) || defined('RESET_CAPS') ) { $level = get_user_meta($user->ID, $wpdb->prefix . 'user_level', true); $role = translate_level_to_role($level); update_user_meta( $user->ID, $wpdb->prefix . 'capabilities', array($role => true) ); } endforeach; $old_user_fields = array( 'user_firstname', 'user_lastname', 'user_icq', 'user_aim', 'user_msn', 'user_yim', 'user_idmode', 'user_ip', 'user_domain', 'user_browser', 'user_description', 'user_nickname', 'user_level' ); $wpdb->hide_errors(); foreach ( $old_user_fields as $old ) $wpdb->query("ALTER TABLE $wpdb->users DROP $old"); $wpdb->show_errors(); // populate comment_count field of posts table $comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" ); if ( is_array( $comments ) ) foreach ($comments as $comment) $wpdb->update( $wpdb->posts, array('comment_count' => $comment->c), array('ID' => $comment->comment_post_ID) ); // Some alpha versions used a post status of object instead of attachment and put // the mime type in post_type instead of post_mime_type. if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) { $objects = $wpdb->get_results("SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'"); foreach ($objects as $object) { $wpdb->update( $wpdb->posts, array( 'post_status' => 'attachment', 'post_mime_type' => $object->post_type, 'post_type' => ''), array( 'ID' => $object->ID ) ); $meta = get_post_meta($object->ID, 'imagedata', true); if ( ! empty($meta['file']) ) update_attached_file( $object->ID, $meta['file'] ); } } } /** * Execute changes made in WordPress 2.1. * * @since 2.1.0 */ function upgrade_210() { global $wpdb, $wp_current_db_version; if ( $wp_current_db_version < 3506 ) { // Update status and type. $posts = $wpdb->get_results("SELECT ID, post_status FROM $wpdb->posts"); if ( ! empty($posts) ) foreach ($posts as $post) { $status = $post->post_status; $type = 'post'; if ( 'static' == $status ) { $status = 'publish'; $type = 'page'; } else if ( 'attachment' == $status ) { $status = 'inherit'; $type = 'attachment'; } $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID) ); } } if ( $wp_current_db_version < 3845 ) { populate_roles_210(); } if ( $wp_current_db_version < 3531 ) { // Give future posts a post_status of future. $now = gmdate('Y-m-d H:i:59'); $wpdb->query ("UPDATE $wpdb->posts SET post_status = 'future' WHERE post_status = 'publish' AND post_date_gmt > '$now'"); $posts = $wpdb->get_results("SELECT ID, post_date FROM $wpdb->posts WHERE post_status ='future'"); if ( !empty($posts) ) foreach ( $posts as $post ) wp_schedule_single_event(mysql2date('U', $post->post_date, false), 'publish_future_post', array($post->ID)); } } /** * Execute changes made in WordPress 2.3. * * @since 2.3.0 */ function upgrade_230() { global $wp_current_db_version, $wpdb; if ( $wp_current_db_version < 5200 ) { populate_roles_230(); } // Convert categories to terms. $tt_ids = array(); $have_tags = false; $categories = $wpdb->get_results("SELECT * FROM $wpdb->categories ORDER BY cat_ID"); foreach ($categories as $category) { $term_id = (int) $category->cat_ID; $name = $category->cat_name; $description = $category->category_description; $slug = $category->category_nicename; $parent = $category->category_parent; $term_group = 0; // Associate terms with the same slug in a term group and make slugs unique. if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) { $term_group = $exists[0]->term_group; $id = $exists[0]->term_id; $num = 2; do { $alt_slug = $slug . "-$num"; $num++; $slug_check = $wpdb->get_var( $wpdb->prepare("SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug) ); } while ( $slug_check ); $slug = $alt_slug; if ( empty( $term_group ) ) { $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms GROUP BY term_group") + 1; $wpdb->query( $wpdb->prepare("UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $id) ); } } $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES (%d, %s, %s, %d)", $term_id, $name, $slug, $term_group) ); $count = 0; if ( !empty($category->category_count) ) { $count = (int) $category->category_count; $taxonomy = 'category'; $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ( %d, %s, %s, %d, %d)", $term_id, $taxonomy, $description, $parent, $count) ); $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id; } if ( !empty($category->link_count) ) { $count = (int) $category->link_count; $taxonomy = 'link_category'; $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ( %d, %s, %s, %d, %d)", $term_id, $taxonomy, $description, $parent, $count) ); $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id; } if ( !empty($category->tag_count) ) { $have_tags = true; $count = (int) $category->tag_count; $taxonomy = 'post_tag'; $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') ); $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id; } if ( empty($count) ) { $count = 0; $taxonomy = 'category'; $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') ); $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id; } } $select = 'post_id, category_id'; if ( $have_tags ) $select .= ', rel_type'; $posts = $wpdb->get_results("SELECT $select FROM $wpdb->post2cat GROUP BY post_id, category_id"); foreach ( $posts as $post ) { $post_id = (int) $post->post_id; $term_id = (int) $post->category_id; $taxonomy = 'category'; if ( !empty($post->rel_type) && 'tag' == $post->rel_type) $taxonomy = 'tag'; $tt_id = $tt_ids[$term_id][$taxonomy]; if ( empty($tt_id) ) continue; $wpdb->insert( $wpdb->term_relationships, array('object_id' => $post_id, 'term_taxonomy_id' => $tt_id) ); } // < 3570 we used linkcategories. >= 3570 we used categories and link2cat. if ( $wp_current_db_version < 3570 ) { // Create link_category terms for link categories. Create a map of link cat IDs // to link_category terms. $link_cat_id_map = array(); $default_link_cat = 0; $tt_ids = array(); $link_cats = $wpdb->get_results("SELECT cat_id, cat_name FROM " . $wpdb->prefix . 'linkcategories'); foreach ( $link_cats as $category) { $cat_id = (int) $category->cat_id; $term_id = 0; $name = $wpdb->escape($category->cat_name); $slug = sanitize_title($name); $term_group = 0; // Associate terms with the same slug in a term group and make slugs unique. if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) { $term_group = $exists[0]->term_group; $term_id = $exists[0]->term_id; } if ( empty($term_id) ) { $wpdb->insert( $wpdb->terms, compact('name', 'slug', 'term_group') ); $term_id = (int) $wpdb->insert_id; } $link_cat_id_map[$cat_id] = $term_id; $default_link_cat = $term_id; $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $term_id, 'taxonomy' => 'link_category', 'description' => '', 'parent' => 0, 'count' => 0) ); $tt_ids[$term_id] = (int) $wpdb->insert_id; } // Associate links to cats. $links = $wpdb->get_results("SELECT link_id, link_category FROM $wpdb->links"); if ( !empty($links) ) foreach ( $links as $link ) { if ( 0 == $link->link_category ) continue; if ( ! isset($link_cat_id_map[$link->link_category]) ) continue; $term_id = $link_cat_id_map[$link->link_category]; $tt_id = $tt_ids[$term_id]; if ( empty($tt_id) ) continue; $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link->link_id, 'term_taxonomy_id' => $tt_id) ); } // Set default to the last category we grabbed during the upgrade loop. update_option('default_link_category', $default_link_cat); } else { $links = $wpdb->get_results("SELECT link_id, category_id FROM $wpdb->link2cat GROUP BY link_id, category_id"); foreach ( $links as $link ) { $link_id = (int) $link->link_id; $term_id = (int) $link->category_id; $taxonomy = 'link_category'; $tt_id = $tt_ids[$term_id][$taxonomy]; if ( empty($tt_id) ) continue; $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link_id, 'term_taxonomy_id' => $tt_id) ); } } if ( $wp_current_db_version < 4772 ) { // Obsolete linkcategories table $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'linkcategories'); } // Recalculate all counts $terms = $wpdb->get_results("SELECT term_taxonomy_id, taxonomy FROM $wpdb->term_taxonomy"); foreach ( (array) $terms as $term ) { if ( ('post_tag' == $term->taxonomy) || ('category' == $term->taxonomy) ) $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type = 'post' AND term_taxonomy_id = %d", $term->term_taxonomy_id) ); else $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term->term_taxonomy_id) ); $wpdb->update( $wpdb->term_taxonomy, array('count' => $count), array('term_taxonomy_id' => $term->term_taxonomy_id) ); } } /** * Remove old options from the database. * * @since 2.3.0 */ function upgrade_230_options_table() { global $wpdb; $old_options_fields = array( 'option_can_override', 'option_type', 'option_width', 'option_height', 'option_description', 'option_admin_level' ); $wpdb->hide_errors(); foreach ( $old_options_fields as $old ) $wpdb->query("ALTER TABLE $wpdb->options DROP $old"); $wpdb->show_errors(); } /** * Remove old categories, link2cat, and post2cat database tables. * * @since 2.3.0 */ function upgrade_230_old_tables() { global $wpdb; $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'categories'); $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'link2cat'); $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'post2cat'); } /** * Upgrade old slugs made in version 2.2. * * @since 2.2.0 */ function upgrade_old_slugs() { // upgrade people who were using the Redirect Old Slugs plugin global $wpdb; $wpdb->query("UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'"); } /** * Execute changes made in WordPress 2.5.0. * * @since 2.5.0 */ function upgrade_250() { global $wp_current_db_version; if ( $wp_current_db_version < 6689 ) { populate_roles_250(); } } /** * Execute changes made in WordPress 2.5.2. * * @since 2.5.2 */ function upgrade_252() { global $wpdb; $wpdb->query("UPDATE $wpdb->users SET user_activation_key = ''"); } /** * Execute changes made in WordPress 2.6. * * @since 2.6.0 */ function upgrade_260() { global $wp_current_db_version; if ( $wp_current_db_version < 8000 ) populate_roles_260(); } /** * Execute changes made in WordPress 2.7. * * @since 2.7.0 */ function upgrade_270() { global $wpdb, $wp_current_db_version; if ( $wp_current_db_version < 8980 ) populate_roles_270(); // Update post_date for unpublished posts with empty timestamp if ( $wp_current_db_version < 8921 ) $wpdb->query( "UPDATE $wpdb->posts SET post_date = post_modified WHERE post_date = '0000-00-00 00:00:00'" ); } /** * Execute changes made in WordPress 2.8. * * @since 2.8.0 */ function upgrade_280() { global $wp_current_db_version, $wpdb; if ( $wp_current_db_version < 10360 ) populate_roles_280(); if ( is_multisite() ) { $start = 0; while( $rows = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options ORDER BY option_id LIMIT $start, 20" ) ) { foreach( $rows as $row ) { $value = $row->option_value; if ( !@unserialize( $value ) ) $value = stripslashes( $value ); if ( $value !== $row->option_value ) { update_option( $row->option_name, $value ); } } $start += 20; } refresh_blog_details( $wpdb->blogid ); } } /** * Execute changes made in WordPress 2.9. * * @since 2.9.0 */ function upgrade_290() { global $wp_current_db_version; if ( $wp_current_db_version < 11958 ) { // Previously, setting depth to 1 would redundantly disable threading, but now 2 is the minimum depth to avoid confusion if ( get_option( 'thread_comments_depth' ) == '1' ) { update_option( 'thread_comments_depth', 2 ); update_option( 'thread_comments', 0 ); } } } /** * Execute changes made in WordPress 3.0. * * @since 3.0.0 */ function upgrade_300() { global $wp_current_db_version, $wpdb; if ( $wp_current_db_version < 15093 ) populate_roles_300(); if ( $wp_current_db_version < 14139 && is_multisite() && is_main_site() && ! defined( 'MULTISITE' ) && get_site_option( 'siteurl' ) === false ) add_site_option( 'siteurl', '' ); // 3.0 screen options key name changes. if ( is_main_site() && !defined('DO_NOT_UPGRADE_GLOBAL_TABLES') ) { $prefix = like_escape($wpdb->base_prefix); $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key LIKE '{$prefix}%meta-box-hidden%' OR meta_key LIKE '{$prefix}%closedpostboxes%' OR meta_key LIKE '{$prefix}%manage-%-columns-hidden%' OR meta_key LIKE '{$prefix}%meta-box-order%' OR meta_key LIKE '{$prefix}%metaboxorder%' OR meta_key LIKE '{$prefix}%screen_layout%' OR meta_key = 'manageedittagscolumnshidden' OR meta_key='managecategoriescolumnshidden' OR meta_key = 'manageedit-tagscolumnshidden' OR meta_key = 'manageeditcolumnshidden' OR meta_key = 'categories_per_page' OR meta_key = 'edit_tags_per_page'" ); } } /** * Execute changes made in WordPress 3.3. * * @since 3.3.0 */ function upgrade_330() { global $wp_current_db_version, $wpdb, $wp_registered_widgets, $sidebars_widgets; if ( $wp_current_db_version < 19061 && is_main_site() && ! defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) { $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('show_admin_bar_admin', 'plugins_last_view')" ); } if ( $wp_current_db_version >= 11548 ) return; $sidebars_widgets = get_option( 'sidebars_widgets', array() ); $_sidebars_widgets = array(); if ( isset($sidebars_widgets['wp_inactive_widgets']) || empty($sidebars_widgets) ) $sidebars_widgets['array_version'] = 3; elseif ( !isset($sidebars_widgets['array_version']) ) $sidebars_widgets['array_version'] = 1; switch ( $sidebars_widgets['array_version'] ) { case 1 : foreach ( (array) $sidebars_widgets as $index => $sidebar ) if ( is_array($sidebar) ) foreach ( (array) $sidebar as $i => $name ) { $id = strtolower($name); if ( isset($wp_registered_widgets[$id]) ) { $_sidebars_widgets[$index][$i] = $id; continue; } $id = sanitize_title($name); if ( isset($wp_registered_widgets[$id]) ) { $_sidebars_widgets[$index][$i] = $id; continue; } $found = false; foreach ( $wp_registered_widgets as $widget_id => $widget ) { if ( strtolower($widget['name']) == strtolower($name) ) { $_sidebars_widgets[$index][$i] = $widget['id']; $found = true; break; } elseif ( sanitize_title($widget['name']) == sanitize_title($name) ) { $_sidebars_widgets[$index][$i] = $widget['id']; $found = true; break; } } if ( $found ) continue; unset($_sidebars_widgets[$index][$i]); } $_sidebars_widgets['array_version'] = 2; $sidebars_widgets = $_sidebars_widgets; unset($_sidebars_widgets); case 2 : $sidebars_widgets = retrieve_widgets(); $sidebars_widgets['array_version'] = 3; update_option( 'sidebars_widgets', $sidebars_widgets ); } } /** * Execute changes made in WordPress 3.4. * * @since 3.4.0 */ function upgrade_340() { global $wp_current_db_version, $wpdb; if ( $wp_current_db_version < 19798 ) { $wpdb->hide_errors(); $wpdb->query( "ALTER TABLE $wpdb->options DROP COLUMN blog_id" ); $wpdb->show_errors(); } if ( $wp_current_db_version < 19799 ) { $wpdb->hide_errors(); $wpdb->query("ALTER TABLE $wpdb->comments DROP INDEX comment_approved"); $wpdb->show_errors(); } if ( $wp_current_db_version < 20022 && is_main_site() && ! defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) { $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key = 'themes_last_view'" ); } if ( $wp_current_db_version < 20080 ) { if ( 'yes' == $wpdb->get_var( "SELECT autoload FROM $wpdb->options WHERE option_name = 'uninstall_plugins'" ) ) { $uninstall_plugins = get_option( 'uninstall_plugins' ); delete_option( 'uninstall_plugins' ); add_option( 'uninstall_plugins', $uninstall_plugins, null, 'no' ); } } } /** * Execute changes made in WordPress 3.5. * * @since 3.5.0 */ function upgrade_350() { global $wp_current_db_version, $wpdb; if ( $wp_current_db_version < 22006 && $wpdb->get_var( "SELECT link_id FROM $wpdb->links LIMIT 1" ) ) update_option( 'link_manager_enabled', 1 ); // Previously set to 0 by populate_options() if ( $wp_current_db_version < 21811 && is_main_site() && ! defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) { $meta_keys = array(); foreach ( array_merge( get_post_types(), get_taxonomies() ) as $name ) { if ( false !== strpos( $name, '-' ) ) $meta_keys[] = 'edit_' . str_replace( '-', '_', $name ) . '_per_page'; } if ( $meta_keys ) { $meta_keys = implode( "', '", $meta_keys ); $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('$meta_keys')" ); } } if ( $wp_current_db_version < 22422 && $term = get_term_by( 'slug', 'post-format-standard', 'post_format' ) ) wp_delete_term( $term->term_id, 'post_format' ); } /** * Execute network level changes * * @since 3.0.0 */ function upgrade_network() { global $wp_current_db_version, $wpdb; // 2.8 if ( $wp_current_db_version < 11549 ) { $wpmu_sitewide_plugins = get_site_option( 'wpmu_sitewide_plugins' ); $active_sitewide_plugins = get_site_option( 'active_sitewide_plugins' ); if ( $wpmu_sitewide_plugins ) { if ( !$active_sitewide_plugins ) $sitewide_plugins = (array) $wpmu_sitewide_plugins; else $sitewide_plugins = array_merge( (array) $active_sitewide_plugins, (array) $wpmu_sitewide_plugins ); update_site_option( 'active_sitewide_plugins', $sitewide_plugins ); } delete_site_option( 'wpmu_sitewide_plugins' ); delete_site_option( 'deactivated_sitewide_plugins' ); $start = 0; while( $rows = $wpdb->get_results( "SELECT meta_key, meta_value FROM {$wpdb->sitemeta} ORDER BY meta_id LIMIT $start, 20" ) ) { foreach( $rows as $row ) { $value = $row->meta_value; if ( !@unserialize( $value ) ) $value = stripslashes( $value ); if ( $value !== $row->meta_value ) { update_site_option( $row->meta_key, $value ); } } $start += 20; } } // 3.0 if ( $wp_current_db_version < 13576 ) update_site_option( 'global_terms_enabled', '1' ); // 3.3 if ( $wp_current_db_version < 19390 ) update_site_option( 'initial_db_version', $wp_current_db_version ); if ( $wp_current_db_version < 19470 ) { if ( false === get_site_option( 'active_sitewide_plugins' ) ) update_site_option( 'active_sitewide_plugins', array() ); } // 3.4 if ( $wp_current_db_version < 20148 ) { // 'allowedthemes' keys things by stylesheet. 'allowed_themes' keyed things by name. $allowedthemes = get_site_option( 'allowedthemes' ); $allowed_themes = get_site_option( 'allowed_themes' ); if ( false === $allowedthemes && is_array( $allowed_themes ) && $allowed_themes ) { $converted = array(); $themes = wp_get_themes(); foreach ( $themes as $stylesheet => $theme_data ) { if ( isset( $allowed_themes[ $theme_data->get('Name') ] ) ) $converted[ $stylesheet ] = true; } update_site_option( 'allowedthemes', $converted ); delete_site_option( 'allowed_themes' ); } } // 3.5 if ( $wp_current_db_version < 21823 ) update_site_option( 'ms_files_rewriting', '1' ); } // The functions we use to actually do stuff // General /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 1.0.0 * * @param string $table_name Database table name to create. * @param string $create_ddl SQL statement to create table. * @return bool If table already exists or was created by function. */ function maybe_create_table($table_name, $create_ddl) { global $wpdb; if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name ) return true; //didn't find it try to create it. $q = $wpdb->query($create_ddl); // we cannot directly tell that whether this succeeded! if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name ) return true; return false; } /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 1.0.1 * * @param string $table Database table name. * @param string $index Index name to drop. * @return bool True, when finished. */ function drop_index($table, $index) { global $wpdb; $wpdb->hide_errors(); $wpdb->query("ALTER TABLE `$table` DROP INDEX `$index`"); // Now we need to take out all the extra ones we may have created for ($i = 0; $i < 25; $i++) { $wpdb->query("ALTER TABLE `$table` DROP INDEX `{$index}_$i`"); } $wpdb->show_errors(); return true; } /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 1.0.1 * * @param string $table Database table name. * @param string $index Database table index column. * @return bool True, when done with execution. */ function add_clean_index($table, $index) { global $wpdb; drop_index($table, $index); $wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )"); return true; } /** ** maybe_add_column() ** Add column to db table if it doesn't exist. ** Returns: true if already exists or on successful completion ** false on error */ function maybe_add_column($table_name, $column_name, $create_ddl) { global $wpdb; foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) { if ($column == $column_name) { return true; } } //didn't find it try to create it. $q = $wpdb->query($create_ddl); // we cannot directly tell that whether this succeeded! foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) { if ($column == $column_name) { return true; } } return false; } /** * Retrieve all options as it was for 1.2. * * @since 1.2.0 * * @return array List of options. */ function get_alloptions_110() { global $wpdb; $all_options = new stdClass; if ( $options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" ) ) { foreach ( $options as $option ) { if ( 'siteurl' == $option->option_name || 'home' == $option->option_name || 'category_base' == $option->option_name ) $option->option_value = untrailingslashit( $option->option_value ); $all_options->{$option->option_name} = stripslashes( $option->option_value ); } } return $all_options; } /** * Version of get_option that is private to install/upgrade. * * @since 1.5.1 * @access private * * @param string $setting Option name. * @return mixed */ function __get_option($setting) { global $wpdb; if ( $setting == 'home' && defined( 'WP_HOME' ) ) return untrailingslashit( WP_HOME ); if ( $setting == 'siteurl' && defined( 'WP_SITEURL' ) ) return untrailingslashit( WP_SITEURL ); $option = $wpdb->get_var( $wpdb->prepare("SELECT option_value FROM $wpdb->options WHERE option_name = %s", $setting ) ); if ( 'home' == $setting && '' == $option ) return __get_option( 'siteurl' ); if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting || 'tag_base' == $setting ) $option = untrailingslashit( $option ); @ $kellogs = unserialize( $option ); if ( $kellogs !== false ) return $kellogs; else return $option; } /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 1.5.0 * * @param string $content * @return string */ function deslash($content) { // Note: \\\ inside a regex denotes a single backslash. // Replace one or more backslashes followed by a single quote with // a single quote. $content = preg_replace("/\\\+'/", "'", $content); // Replace one or more backslashes followed by a double quote with // a double quote. $content = preg_replace('/\\\+"/', '"', $content); // Replace one or more backslashes with one backslash. $content = preg_replace("/\\\+/", "\\", $content); return $content; } /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 1.5.0 * * @param unknown_type $queries * @param unknown_type $execute * @return unknown */ function dbDelta( $queries = '', $execute = true ) { global $wpdb; if ( in_array( $queries, array( '', 'all', 'blog', 'global', 'ms_global' ), true ) ) $queries = wp_get_db_schema( $queries ); // Separate individual queries into an array if ( !is_array($queries) ) { $queries = explode( ';', $queries ); $queries = array_filter( $queries ); } $queries = apply_filters( 'dbdelta_queries', $queries ); $cqueries = array(); // Creation Queries $iqueries = array(); // Insertion Queries $for_update = array(); // Create a tablename index for an array ($cqueries) of queries foreach($queries as $qry) { if (preg_match("|CREATE TABLE ([^ ]*)|", $qry, $matches)) { $cqueries[ trim( $matches[1], '`' ) ] = $qry; $for_update[$matches[1]] = 'Created table '.$matches[1]; } else if (preg_match("|CREATE DATABASE ([^ ]*)|", $qry, $matches)) { array_unshift($cqueries, $qry); } else if (preg_match("|INSERT INTO ([^ ]*)|", $qry, $matches)) { $iqueries[] = $qry; } else if (preg_match("|UPDATE ([^ ]*)|", $qry, $matches)) { $iqueries[] = $qry; } else { // Unrecognized query type } } $cqueries = apply_filters( 'dbdelta_create_queries', $cqueries ); $iqueries = apply_filters( 'dbdelta_insert_queries', $iqueries ); $global_tables = $wpdb->tables( 'global' ); foreach ( $cqueries as $table => $qry ) { // Upgrade global tables only for the main site. Don't upgrade at all if DO_NOT_UPGRADE_GLOBAL_TABLES is defined. if ( in_array( $table, $global_tables ) && ( !is_main_site() || defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) ) continue; // Fetch the table column structure from the database $wpdb->suppress_errors(); $tablefields = $wpdb->get_results("DESCRIBE {$table};"); $wpdb->suppress_errors( false ); if ( ! $tablefields ) continue; // Clear the field and index arrays $cfields = $indices = array(); // Get all of the field names in the query from between the parens preg_match("|\((.*)\)|ms", $qry, $match2); $qryline = trim($match2[1]); // Separate field lines into an array $flds = explode("\n", $qryline); //echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($cqueries, true)."</pre><hr/>"; // For every field line specified in the query foreach ($flds as $fld) { // Extract the field name preg_match("|^([^ ]*)|", trim($fld), $fvals); $fieldname = trim( $fvals[1], '`' ); // Verify the found field name $validfield = true; switch (strtolower($fieldname)) { case '': case 'primary': case 'index': case 'fulltext': case 'unique': case 'key': $validfield = false; $indices[] = trim(trim($fld), ", \n"); break; } $fld = trim($fld); // If it's a valid field, add it to the field array if ($validfield) { $cfields[strtolower($fieldname)] = trim($fld, ", \n"); } } // For every field in the table foreach ($tablefields as $tablefield) { // If the table field exists in the field array... if (array_key_exists(strtolower($tablefield->Field), $cfields)) { // Get the field type from the query preg_match("|".$tablefield->Field." ([^ ]*( unsigned)?)|i", $cfields[strtolower($tablefield->Field)], $matches); $fieldtype = $matches[1]; // Is actual field type different from the field type in query? if ($tablefield->Type != $fieldtype) { // Add a query to change the column type $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN {$tablefield->Field} " . $cfields[strtolower($tablefield->Field)]; $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}"; } // Get the default value from the array //echo "{$cfields[strtolower($tablefield->Field)]}<br>"; if (preg_match("| DEFAULT '(.*)'|i", $cfields[strtolower($tablefield->Field)], $matches)) { $default_value = $matches[1]; if ($tablefield->Default != $default_value) { // Add a query to change the column's default value $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN {$tablefield->Field} SET DEFAULT '{$default_value}'"; $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}"; } } // Remove the field from the array (so it's not added) unset($cfields[strtolower($tablefield->Field)]); } else { // This field exists in the table, but not in the creation queries? } } // For every remaining field specified for the table foreach ($cfields as $fieldname => $fielddef) { // Push a query line into $cqueries that adds the field to that table $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef"; $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname; } // Index stuff goes here // Fetch the table index structure from the database $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};"); if ($tableindices) { // Clear the index array unset($index_ary); // For every index in the table foreach ($tableindices as $tableindex) { // Add the index to the index data array $keyname = $tableindex->Key_name; $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part); $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false; } // For each actual index in the index array foreach ($index_ary as $index_name => $index_data) { // Build a create string to compare to the query $index_string = ''; if ($index_name == 'PRIMARY') { $index_string .= 'PRIMARY '; } else if($index_data['unique']) { $index_string .= 'UNIQUE '; } $index_string .= 'KEY '; if ($index_name != 'PRIMARY') { $index_string .= $index_name; } $index_columns = ''; // For each column in the index foreach ($index_data['columns'] as $column_data) { if ($index_columns != '') $index_columns .= ','; // Add the field to the column list string $index_columns .= $column_data['fieldname']; if ($column_data['subpart'] != '') { $index_columns .= '('.$column_data['subpart'].')'; } } // Add the column list to the index create string $index_string .= ' ('.$index_columns.')'; if (!(($aindex = array_search($index_string, $indices)) === false)) { unset($indices[$aindex]); //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br />Found index:".$index_string."</pre>\n"; } //else echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br /><b>Did not find index:</b>".$index_string."<br />".print_r($indices, true)."</pre>\n"; } } // For every remaining index specified for the table foreach ( (array) $indices as $index ) { // Push a query line into $cqueries that adds the index to that table $cqueries[] = "ALTER TABLE {$table} ADD $index"; $for_update[$table.'.'.$fieldname] = 'Added index '.$table.' '.$index; } // Remove the original table creation query from processing unset( $cqueries[ $table ], $for_update[ $table ] ); } $allqueries = array_merge($cqueries, $iqueries); if ($execute) { foreach ($allqueries as $query) { //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($query, true)."</pre>\n"; $wpdb->query($query); } } return $for_update; } /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 1.5.0 */ function make_db_current( $tables = 'all' ) { $alterations = dbDelta( $tables ); echo "<ol>\n"; foreach($alterations as $alteration) echo "<li>$alteration</li>\n"; echo "</ol>\n"; } /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 1.5.0 */ function make_db_current_silent( $tables = 'all' ) { $alterations = dbDelta( $tables ); } /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 1.5.0 * * @param unknown_type $theme_name * @param unknown_type $template * @return unknown */ function make_site_theme_from_oldschool($theme_name, $template) { $home_path = get_home_path(); $site_dir = WP_CONTENT_DIR . "/themes/$template"; if (! file_exists("$home_path/index.php")) return false; // Copy files from the old locations to the site theme. // TODO: This does not copy arbitrary include dependencies. Only the // standard WP files are copied. $files = array('index.php' => 'index.php', 'wp-layout.css' => 'style.css', 'wp-comments.php' => 'comments.php', 'wp-comments-popup.php' => 'comments-popup.php'); foreach ($files as $oldfile => $newfile) { if ($oldfile == 'index.php') $oldpath = $home_path; else $oldpath = ABSPATH; if ($oldfile == 'index.php') { // Check to make sure it's not a new index $index = implode('', file("$oldpath/$oldfile")); if (strpos($index, 'WP_USE_THEMES') !== false) { if (! @copy(WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME . '/index.php', "$site_dir/$newfile")) return false; continue; // Don't copy anything } } if (! @copy("$oldpath/$oldfile", "$site_dir/$newfile")) return false; chmod("$site_dir/$newfile", 0777); // Update the blog header include in each file. $lines = explode("\n", implode('', file("$site_dir/$newfile"))); if ($lines) { $f = fopen("$site_dir/$newfile", 'w'); foreach ($lines as $line) { if (preg_match('/require.*wp-blog-header/', $line)) $line = '//' . $line; // Update stylesheet references. $line = str_replace("<?php echo __get_option('siteurl'); ?>/wp-layout.css", "<?php bloginfo('stylesheet_url'); ?>", $line); // Update comments template inclusion. $line = str_replace("<?php include(ABSPATH . 'wp-comments.php'); ?>", "<?php comments_template(); ?>", $line); fwrite($f, "{$line}\n"); } fclose($f); } } // Add a theme header. $header = "/*\nTheme Name: $theme_name\nTheme URI: " . __get_option('siteurl') . "\nDescription: A theme automatically created by the update.\nVersion: 1.0\nAuthor: Moi\n*/\n"; $stylelines = file_get_contents("$site_dir/style.css"); if ($stylelines) { $f = fopen("$site_dir/style.css", 'w'); fwrite($f, $header); fwrite($f, $stylelines); fclose($f); } return true; } /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 1.5.0 * * @param unknown_type $theme_name * @param unknown_type $template * @return unknown */ function make_site_theme_from_default($theme_name, $template) { $site_dir = WP_CONTENT_DIR . "/themes/$template"; $default_dir = WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME; // Copy files from the default theme to the site theme. //$files = array('index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css'); $theme_dir = @ opendir($default_dir); if ($theme_dir) { while(($theme_file = readdir( $theme_dir )) !== false) { if (is_dir("$default_dir/$theme_file")) continue; if (! @copy("$default_dir/$theme_file", "$site_dir/$theme_file")) return; chmod("$site_dir/$theme_file", 0777); } } @closedir($theme_dir); // Rewrite the theme header. $stylelines = explode("\n", implode('', file("$site_dir/style.css"))); if ($stylelines) { $f = fopen("$site_dir/style.css", 'w'); foreach ($stylelines as $line) { if (strpos($line, 'Theme Name:') !== false) $line = 'Theme Name: ' . $theme_name; elseif (strpos($line, 'Theme URI:') !== false) $line = 'Theme URI: ' . __get_option('url'); elseif (strpos($line, 'Description:') !== false) $line = 'Description: Your theme.'; elseif (strpos($line, 'Version:') !== false) $line = 'Version: 1'; elseif (strpos($line, 'Author:') !== false) $line = 'Author: You'; fwrite($f, $line . "\n"); } fclose($f); } // Copy the images. umask(0); if (! mkdir("$site_dir/images", 0777)) { return false; } $images_dir = @ opendir("$default_dir/images"); if ($images_dir) { while(($image = readdir($images_dir)) !== false) { if (is_dir("$default_dir/images/$image")) continue; if (! @copy("$default_dir/images/$image", "$site_dir/images/$image")) return; chmod("$site_dir/images/$image", 0777); } } @closedir($images_dir); } // Create a site theme from the default theme. /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 1.5.0 * * @return unknown */ function make_site_theme() { // Name the theme after the blog. $theme_name = __get_option('blogname'); $template = sanitize_title($theme_name); $site_dir = WP_CONTENT_DIR . "/themes/$template"; // If the theme already exists, nothing to do. if ( is_dir($site_dir)) { return false; } // We must be able to write to the themes dir. if (! is_writable(WP_CONTENT_DIR . "/themes")) { return false; } umask(0); if (! mkdir($site_dir, 0777)) { return false; } if (file_exists(ABSPATH . 'wp-layout.css')) { if (! make_site_theme_from_oldschool($theme_name, $template)) { // TODO: rm -rf the site theme directory. return false; } } else { if (! make_site_theme_from_default($theme_name, $template)) // TODO: rm -rf the site theme directory. return false; } // Make the new site theme active. $current_template = __get_option('template'); if ($current_template == WP_DEFAULT_THEME) { update_option('template', $template); update_option('stylesheet', $template); } return $template; } /** * Translate user level to user role name. * * @since 2.0.0 * * @param int $level User level. * @return string User role name. */ function translate_level_to_role($level) { switch ($level) { case 10: case 9: case 8: return 'administrator'; case 7: case 6: case 5: return 'editor'; case 4: case 3: case 2: return 'author'; case 1: return 'contributor'; case 0: return 'subscriber'; } } /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 2.1.0 */ function wp_check_mysql_version() { global $wpdb; $result = $wpdb->check_database_version(); if ( is_wp_error( $result ) ) die( $result->get_error_message() ); } /** * Disables the Automattic widgets plugin, which was merged into core. * * @since 2.2.0 */ function maybe_disable_automattic_widgets() { $plugins = __get_option( 'active_plugins' ); foreach ( (array) $plugins as $plugin ) { if ( basename( $plugin ) == 'widgets.php' ) { array_splice( $plugins, array_search( $plugin, $plugins ), 1 ); update_option( 'active_plugins', $plugins ); break; } } } /** * Disables the Link Manager on upgrade, if at the time of upgrade, no links exist in the DB. * * @since 3.5.0 */ function maybe_disable_link_manager() { global $wp_current_db_version, $wpdb; if ( $wp_current_db_version >= 22006 && get_option( 'link_manager_enabled' ) && ! $wpdb->get_var( "SELECT link_id FROM $wpdb->links LIMIT 1" ) ) update_option( 'link_manager_enabled', 0 ); } /** * Runs before the schema is upgraded. * * @since 2.9.0 */ function pre_schema_upgrade() { global $wp_current_db_version, $wp_db_version, $wpdb; // Upgrade versions prior to 2.9 if ( $wp_current_db_version < 11557 ) { // Delete duplicate options. Keep the option with the highest option_id. $wpdb->query("DELETE o1 FROM $wpdb->options AS o1 JOIN $wpdb->options AS o2 USING (`option_name`) WHERE o2.option_id > o1.option_id"); // Drop the old primary key and add the new. $wpdb->query("ALTER TABLE $wpdb->options DROP PRIMARY KEY, ADD PRIMARY KEY(option_id)"); // Drop the old option_name index. dbDelta() doesn't do the drop. $wpdb->query("ALTER TABLE $wpdb->options DROP INDEX option_name"); } } /** * Install global terms. * * @since 3.0.0 * */ if ( !function_exists( 'install_global_terms' ) ) : function install_global_terms() { global $wpdb, $charset_collate; $ms_queries = " CREATE TABLE $wpdb->sitecategories ( cat_ID bigint(20) NOT NULL auto_increment, cat_name varchar(55) NOT NULL default '', category_nicename varchar(200) NOT NULL default '', last_updated timestamp NOT NULL, PRIMARY KEY (cat_ID), KEY category_nicename (category_nicename), KEY last_updated (last_updated) ) $charset_collate; "; // now create tables dbDelta( $ms_queries ); } endif;
zyblog
trunk/zyblog/wp-admin/includes/upgrade.php
PHP
asf20
66,303
<?php /** * WordPress FTP Sockets Filesystem. * * @package WordPress * @subpackage Filesystem */ /** * WordPress Filesystem Class for implementing FTP Sockets. * * @since 2.5 * @package WordPress * @subpackage Filesystem * @uses WP_Filesystem_Base Extends class */ class WP_Filesystem_ftpsockets extends WP_Filesystem_Base { var $ftp = false; var $errors = null; var $options = array(); function __construct($opt = '') { $this->method = 'ftpsockets'; $this->errors = new WP_Error(); //Check if possible to use ftp functions. if ( ! @include_once ABSPATH . 'wp-admin/includes/class-ftp.php' ) return false; $this->ftp = new ftp(); //Set defaults: if ( empty($opt['port']) ) $this->options['port'] = 21; else $this->options['port'] = $opt['port']; if ( empty($opt['hostname']) ) $this->errors->add('empty_hostname', __('FTP hostname is required')); else $this->options['hostname'] = $opt['hostname']; if ( ! empty($opt['base']) ) $this->wp_base = $opt['base']; // Check if the options provided are OK. if ( empty ($opt['username']) ) $this->errors->add('empty_username', __('FTP username is required')); else $this->options['username'] = $opt['username']; if ( empty ($opt['password']) ) $this->errors->add('empty_password', __('FTP password is required')); else $this->options['password'] = $opt['password']; } function connect() { if ( ! $this->ftp ) return false; $this->ftp->setTimeout(FS_CONNECT_TIMEOUT); if ( ! $this->ftp->SetServer($this->options['hostname'], $this->options['port']) ) { $this->errors->add('connect', sprintf(__('Failed to connect to FTP Server %1$s:%2$s'), $this->options['hostname'], $this->options['port'])); return false; } if ( ! $this->ftp->connect() ) { $this->errors->add('connect', sprintf(__('Failed to connect to FTP Server %1$s:%2$s'), $this->options['hostname'], $this->options['port'])); return false; } if ( ! $this->ftp->login($this->options['username'], $this->options['password']) ) { $this->errors->add('auth', sprintf(__('Username/Password incorrect for %s'), $this->options['username'])); return false; } $this->ftp->SetType(FTP_AUTOASCII); $this->ftp->Passive(true); $this->ftp->setTimeout(FS_TIMEOUT); return true; } function get_contents($file, $type = '', $resumepos = 0) { if ( ! $this->exists($file) ) return false; if ( empty($type) ) $type = FTP_AUTOASCII; $this->ftp->SetType($type); $temp = wp_tempnam( $file ); if ( ! $temphandle = fopen($temp, 'w+') ) return false; if ( ! $this->ftp->fget($temphandle, $file) ) { fclose($temphandle); unlink($temp); return ''; //Blank document, File does exist, Its just blank. } fseek($temphandle, 0); //Skip back to the start of the file being written to $contents = ''; while ( ! feof($temphandle) ) $contents .= fread($temphandle, 8192); fclose($temphandle); unlink($temp); return $contents; } function get_contents_array($file) { return explode("\n", $this->get_contents($file) ); } function put_contents($file, $contents, $mode = false ) { $temp = wp_tempnam( $file ); if ( ! $temphandle = @fopen($temp, 'w+') ) { unlink($temp); return false; } fwrite($temphandle, $contents); fseek($temphandle, 0); //Skip back to the start of the file being written to $type = $this->is_binary($contents) ? FTP_BINARY : FTP_ASCII; $this->ftp->SetType($type); $ret = $this->ftp->fput($file, $temphandle); fclose($temphandle); unlink($temp); $this->chmod($file, $mode); return $ret; } function cwd() { $cwd = $this->ftp->pwd(); if ( $cwd ) $cwd = trailingslashit($cwd); return $cwd; } function chdir($file) { return $this->ftp->chdir($file); } function chgrp($file, $group, $recursive = false ) { return false; } function chmod($file, $mode = false, $recursive = false ) { if ( ! $mode ) { if ( $this->is_file($file) ) $mode = FS_CHMOD_FILE; elseif ( $this->is_dir($file) ) $mode = FS_CHMOD_DIR; else return false; } // chmod any sub-objects if recursive. if ( $recursive && $this->is_dir($file) ) { $filelist = $this->dirlist($file); foreach ( (array)$filelist as $filename => $filemeta ) $this->chmod($file . '/' . $filename, $mode, $recursive); } // chmod the file or directory return $this->ftp->chmod($file, $mode); } function chown($file, $owner, $recursive = false ) { return false; } function owner($file) { $dir = $this->dirlist($file); return $dir[$file]['owner']; } function getchmod($file) { $dir = $this->dirlist($file); return $dir[$file]['permsn']; } function group($file) { $dir = $this->dirlist($file); return $dir[$file]['group']; } function copy($source, $destination, $overwrite = false, $mode = false) { if ( ! $overwrite && $this->exists($destination) ) return false; $content = $this->get_contents($source); if ( false === $content ) return false; return $this->put_contents($destination, $content, $mode); } function move($source, $destination, $overwrite = false ) { return $this->ftp->rename($source, $destination); } function delete($file, $recursive = false, $type = false) { if ( empty($file) ) return false; if ( 'f' == $type || $this->is_file($file) ) return $this->ftp->delete($file); if ( !$recursive ) return $this->ftp->rmdir($file); return $this->ftp->mdel($file); } function exists($file) { return $this->ftp->is_exists($file); } function is_file($file) { if ( $this->is_dir($file) ) return false; if ( $this->exists($file) ) return true; return false; } function is_dir($path) { $cwd = $this->cwd(); if ( $this->chdir($path) ) { $this->chdir($cwd); return true; } return false; } function is_readable($file) { //Get dir list, Check if the file is writable by the current user?? return true; } function is_writable($file) { //Get dir list, Check if the file is writable by the current user?? return true; } function atime($file) { return false; } function mtime($file) { return $this->ftp->mdtm($file); } function size($file) { return $this->ftp->filesize($file); } function touch($file, $time = 0, $atime = 0 ) { return false; } function mkdir($path, $chmod = false, $chown = false, $chgrp = false ) { $path = untrailingslashit($path); if ( empty($path) ) return false; if ( ! $this->ftp->mkdir($path) ) return false; if ( ! $chmod ) $chmod = FS_CHMOD_DIR; $this->chmod($path, $chmod); if ( $chown ) $this->chown($path, $chown); if ( $chgrp ) $this->chgrp($path, $chgrp); return true; } function rmdir($path, $recursive = false ) { $this->delete($path, $recursive); } function dirlist($path = '.', $include_hidden = true, $recursive = false ) { if ( $this->is_file($path) ) { $limit_file = basename($path); $path = dirname($path) . '/'; } else { $limit_file = false; } $list = $this->ftp->dirlist($path); if ( empty($list) && !$this->exists($path) ) return false; $ret = array(); foreach ( $list as $struc ) { if ( '.' == $struc['name'] || '..' == $struc['name'] ) continue; if ( ! $include_hidden && '.' == $struc['name'][0] ) continue; if ( $limit_file && $struc['name'] != $limit_file ) continue; if ( 'd' == $struc['type'] ) { if ( $recursive ) $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $include_hidden, $recursive); else $struc['files'] = array(); } // Replace symlinks formatted as "source -> target" with just the source name if ( $struc['islink'] ) $struc['name'] = preg_replace( '/(\s*->\s*.*)$/', '', $struc['name'] ); $ret[ $struc['name'] ] = $struc; } return $ret; } function __destruct() { $this->ftp->quit(); } }
zyblog
trunk/zyblog/wp-admin/includes/class-wp-filesystem-ftpsockets.php
PHP
asf20
7,865
<?php /** * WordPress Administration Update API * * @package WordPress * @subpackage Administration */ // The admin side of our 1.1 update system /** * Selects the first update version from the update_core option * * @return object the response from the API */ function get_preferred_from_update_core() { $updates = get_core_updates(); if ( !is_array( $updates ) ) return false; if ( empty( $updates ) ) return (object)array('response' => 'latest'); return $updates[0]; } /** * Get available core updates * * @param array $options Set $options['dismissed'] to true to show dismissed upgrades too, * set $options['available'] to false to skip not-dismissed updates. * @return array Array of the update objects */ function get_core_updates( $options = array() ) { $options = array_merge( array('available' => true, 'dismissed' => false ), $options ); $dismissed = get_site_option( 'dismissed_update_core' ); if ( !is_array( $dismissed ) ) $dismissed = array(); $from_api = get_site_transient( 'update_core' ); if ( empty($from_api) ) return false; if ( !isset( $from_api->updates ) || !is_array( $from_api->updates ) ) return false; $updates = $from_api->updates; if ( !is_array( $updates ) ) return false; $result = array(); foreach($updates as $update) { if ( array_key_exists( $update->current.'|'.$update->locale, $dismissed ) ) { if ( $options['dismissed'] ) { $update->dismissed = true; $result[]= $update; } } else { if ( $options['available'] ) { $update->dismissed = false; $result[]= $update; } } } return $result; } function dismiss_core_update( $update ) { $dismissed = get_site_option( 'dismissed_update_core' ); $dismissed[ $update->current.'|'.$update->locale ] = true; return update_site_option( 'dismissed_update_core', $dismissed ); } function undismiss_core_update( $version, $locale ) { $dismissed = get_site_option( 'dismissed_update_core' ); $key = $version.'|'.$locale; if ( !isset( $dismissed[$key] ) ) return false; unset( $dismissed[$key] ); return update_site_option( 'dismissed_update_core', $dismissed ); } function find_core_update( $version, $locale ) { $from_api = get_site_transient( 'update_core' ); if ( !is_array( $from_api->updates ) ) return false; $updates = $from_api->updates; foreach($updates as $update) { if ( $update->current == $version && $update->locale == $locale ) return $update; } return false; } function core_update_footer( $msg = '' ) { if ( !current_user_can('update_core') ) return sprintf( __( 'Version %s' ), get_bloginfo( 'version', 'display' ) ); $cur = get_preferred_from_update_core(); if ( ! is_object( $cur ) ) $cur = new stdClass; if ( ! isset( $cur->current ) ) $cur->current = ''; if ( ! isset( $cur->url ) ) $cur->url = ''; if ( ! isset( $cur->response ) ) $cur->response = ''; switch ( $cur->response ) { case 'development' : return sprintf( __( 'You are using a development version (%1$s). Cool! Please <a href="%2$s">stay updated</a>.' ), get_bloginfo( 'version', 'display' ), network_admin_url( 'update-core.php' ) ); break; case 'upgrade' : return sprintf( '<strong>'.__( '<a href="%1$s">Get Version %2$s</a>' ).'</strong>', network_admin_url( 'update-core.php' ), $cur->current); break; case 'latest' : default : return sprintf( __( 'Version %s' ), get_bloginfo( 'version', 'display' ) ); break; } } add_filter( 'update_footer', 'core_update_footer' ); function update_nag() { if ( is_multisite() && !current_user_can('update_core') ) return false; global $pagenow; if ( 'update-core.php' == $pagenow ) return; $cur = get_preferred_from_update_core(); if ( ! isset( $cur->response ) || $cur->response != 'upgrade' ) return false; if ( current_user_can('update_core') ) { $msg = sprintf( __('<a href="http://codex.wordpress.org/Version_%1$s">WordPress %1$s</a> is available! <a href="%2$s">Please update now</a>.'), $cur->current, network_admin_url( 'update-core.php' ) ); } else { $msg = sprintf( __('<a href="http://codex.wordpress.org/Version_%1$s">WordPress %1$s</a> is available! Please notify the site administrator.'), $cur->current ); } echo "<div class='update-nag'>$msg</div>"; } add_action( 'admin_notices', 'update_nag', 3 ); add_action( 'network_admin_notices', 'update_nag', 3 ); // Called directly from dashboard function update_right_now_message() { $msg = sprintf( __( 'You are using <span class="b">WordPress %s</span>.' ), get_bloginfo( 'version', 'display' ) ); if ( current_user_can('update_core') ) { $cur = get_preferred_from_update_core(); if ( isset( $cur->response ) && $cur->response == 'upgrade' ) $msg .= " <a href='" . network_admin_url( 'update-core.php' ) . "' class='button'>" . sprintf( __('Update to %s'), $cur->current ? $cur->current : __( 'Latest' ) ) . '</a>'; } echo "<span id='wp-version-message'>$msg</span>"; } function get_plugin_updates() { $all_plugins = get_plugins(); $upgrade_plugins = array(); $current = get_site_transient( 'update_plugins' ); foreach ( (array)$all_plugins as $plugin_file => $plugin_data) { if ( isset( $current->response[ $plugin_file ] ) ) { $upgrade_plugins[ $plugin_file ] = (object) $plugin_data; $upgrade_plugins[ $plugin_file ]->update = $current->response[ $plugin_file ]; } } return $upgrade_plugins; } function wp_plugin_update_rows() { if ( !current_user_can('update_plugins' ) ) return; $plugins = get_site_transient( 'update_plugins' ); if ( isset($plugins->response) && is_array($plugins->response) ) { $plugins = array_keys( $plugins->response ); foreach( $plugins as $plugin_file ) { add_action( "after_plugin_row_$plugin_file", 'wp_plugin_update_row', 10, 2 ); } } } add_action( 'admin_init', 'wp_plugin_update_rows' ); function wp_plugin_update_row( $file, $plugin_data ) { $current = get_site_transient( 'update_plugins' ); if ( !isset( $current->response[ $file ] ) ) return false; $r = $current->response[ $file ]; $plugins_allowedtags = array('a' => array('href' => array(),'title' => array()),'abbr' => array('title' => array()),'acronym' => array('title' => array()),'code' => array(),'em' => array(),'strong' => array()); $plugin_name = wp_kses( $plugin_data['Name'], $plugins_allowedtags ); $details_url = self_admin_url('plugin-install.php?tab=plugin-information&plugin=' . $r->slug . '&section=changelog&TB_iframe=true&width=600&height=800'); $wp_list_table = _get_list_table('WP_Plugins_List_Table'); if ( is_network_admin() || !is_multisite() ) { echo '<tr class="plugin-update-tr"><td colspan="' . $wp_list_table->get_column_count() . '" class="plugin-update colspanchange"><div class="update-message">'; if ( ! current_user_can('update_plugins') ) printf( __('There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a>.'), $plugin_name, esc_url($details_url), esc_attr($plugin_name), $r->new_version ); else if ( empty($r->package) ) printf( __('There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a>. <em>Automatic update is unavailable for this plugin.</em>'), $plugin_name, esc_url($details_url), esc_attr($plugin_name), $r->new_version ); else printf( __('There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a> or <a href="%5$s">update now</a>.'), $plugin_name, esc_url($details_url), esc_attr($plugin_name), $r->new_version, wp_nonce_url( self_admin_url('update.php?action=upgrade-plugin&plugin=') . $file, 'upgrade-plugin_' . $file) ); do_action( "in_plugin_update_message-$file", $plugin_data, $r ); echo '</div></td></tr>'; } } function wp_update_plugin($plugin, $feedback = '') { if ( !empty($feedback) ) add_filter('update_feedback', $feedback); include ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; $upgrader = new Plugin_Upgrader(); return $upgrader->upgrade($plugin); } function get_theme_updates() { $themes = wp_get_themes(); $current = get_site_transient('update_themes'); if ( ! isset( $current->response ) ) return array(); $update_themes = array(); foreach ( $current->response as $stylesheet => $data ) { $update_themes[ $stylesheet ] = wp_get_theme( $stylesheet ); $update_themes[ $stylesheet ]->update = $data; } return $update_themes; } function wp_update_theme($theme, $feedback = '') { if ( !empty($feedback) ) add_filter('update_feedback', $feedback); include ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; $upgrader = new Theme_Upgrader(); return $upgrader->upgrade($theme); } function wp_theme_update_rows() { if ( !current_user_can('update_themes' ) ) return; $themes = get_site_transient( 'update_themes' ); if ( isset($themes->response) && is_array($themes->response) ) { $themes = array_keys( $themes->response ); foreach( $themes as $theme ) { add_action( "after_theme_row_$theme", 'wp_theme_update_row', 10, 2 ); } } } add_action( 'admin_init', 'wp_theme_update_rows' ); function wp_theme_update_row( $theme_key, $theme ) { $current = get_site_transient( 'update_themes' ); if ( !isset( $current->response[ $theme_key ] ) ) return false; $r = $current->response[ $theme_key ]; $themes_allowedtags = array('a' => array('href' => array(),'title' => array()),'abbr' => array('title' => array()),'acronym' => array('title' => array()),'code' => array(),'em' => array(),'strong' => array()); $theme_name = wp_kses( $theme['Name'], $themes_allowedtags ); $details_url = add_query_arg( array( 'TB_iframe' => 'true', 'width' => 1024, 'height' => 800 ), $current->response[ $theme_key ]['url'] ); $wp_list_table = _get_list_table('WP_MS_Themes_List_Table'); echo '<tr class="plugin-update-tr"><td colspan="' . $wp_list_table->get_column_count() . '" class="plugin-update colspanchange"><div class="update-message">'; if ( ! current_user_can('update_themes') ) printf( __('There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a>.'), $theme['Name'], esc_url($details_url), esc_attr($theme['Name']), $r->new_version ); else if ( empty( $r['package'] ) ) printf( __('There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a>. <em>Automatic update is unavailable for this theme.</em>'), $theme['Name'], esc_url($details_url), esc_attr($theme['Name']), $r['new_version'] ); else printf( __('There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a> or <a href="%5$s">update now</a>.'), $theme['Name'], esc_url($details_url), esc_attr($theme['Name']), $r['new_version'], wp_nonce_url( self_admin_url('update.php?action=upgrade-theme&theme=') . $theme_key, 'upgrade-theme_' . $theme_key) ); do_action( "in_theme_update_message-$theme_key", $theme, $r ); echo '</div></td></tr>'; } function wp_update_core($current, $feedback = '') { if ( !empty($feedback) ) add_filter('update_feedback', $feedback); include ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; $upgrader = new Core_Upgrader(); return $upgrader->upgrade($current); } function maintenance_nag() { global $upgrading; if ( ! isset( $upgrading ) ) return false; if ( current_user_can('update_core') ) $msg = sprintf( __('An automated WordPress update has failed to complete - <a href="%s">please attempt the update again now</a>.'), 'update-core.php' ); else $msg = __('An automated WordPress update has failed to complete! Please notify the site administrator.'); echo "<div class='update-nag'>$msg</div>"; } add_action( 'admin_notices', 'maintenance_nag' );
zyblog
trunk/zyblog/wp-admin/includes/update.php
PHP
asf20
11,739
<?php // -------------------------------------------------------------------------------- // PhpConcept Library - Zip Module 2.8.2 // -------------------------------------------------------------------------------- // License GNU/LGPL - Vincent Blavet - August 2009 // http://www.phpconcept.net // -------------------------------------------------------------------------------- // // Presentation : // PclZip is a PHP library that manage ZIP archives. // So far tests show that archives generated by PclZip are readable by // WinZip application and other tools. // // Description : // See readme.txt and http://www.phpconcept.net // // Warning : // This library and the associated files are non commercial, non professional // work. // It should not have unexpected results. However if any damage is caused by // this software the author can not be responsible. // The use of this software is at the risk of the user. // // -------------------------------------------------------------------------------- // $Id: pclzip.lib.php,v 1.60 2009/09/30 21:01:04 vblavet Exp $ // -------------------------------------------------------------------------------- // ----- Constants if (!defined('PCLZIP_READ_BLOCK_SIZE')) { define( 'PCLZIP_READ_BLOCK_SIZE', 2048 ); } // ----- File list separator // In version 1.x of PclZip, the separator for file list is a space // (which is not a very smart choice, specifically for windows paths !). // A better separator should be a comma (,). This constant gives you the // abilty to change that. // However notice that changing this value, may have impact on existing // scripts, using space separated filenames. // Recommanded values for compatibility with older versions : //define( 'PCLZIP_SEPARATOR', ' ' ); // Recommanded values for smart separation of filenames. if (!defined('PCLZIP_SEPARATOR')) { define( 'PCLZIP_SEPARATOR', ',' ); } // ----- Error configuration // 0 : PclZip Class integrated error handling // 1 : PclError external library error handling. By enabling this // you must ensure that you have included PclError library. // [2,...] : reserved for futur use if (!defined('PCLZIP_ERROR_EXTERNAL')) { define( 'PCLZIP_ERROR_EXTERNAL', 0 ); } // ----- Optional static temporary directory // By default temporary files are generated in the script current // path. // If defined : // - MUST BE terminated by a '/'. // - MUST be a valid, already created directory // Samples : // define( 'PCLZIP_TEMPORARY_DIR', '/temp/' ); // define( 'PCLZIP_TEMPORARY_DIR', 'C:/Temp/' ); if (!defined('PCLZIP_TEMPORARY_DIR')) { define( 'PCLZIP_TEMPORARY_DIR', '' ); } // ----- Optional threshold ratio for use of temporary files // Pclzip sense the size of the file to add/extract and decide to // use or not temporary file. The algorythm is looking for // memory_limit of PHP and apply a ratio. // threshold = memory_limit * ratio. // Recommended values are under 0.5. Default 0.47. // Samples : // define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.5 ); if (!defined('PCLZIP_TEMPORARY_FILE_RATIO')) { define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.47 ); } // -------------------------------------------------------------------------------- // ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED ***** // -------------------------------------------------------------------------------- // ----- Global variables $g_pclzip_version = "2.8.2"; // ----- Error codes // -1 : Unable to open file in binary write mode // -2 : Unable to open file in binary read mode // -3 : Invalid parameters // -4 : File does not exist // -5 : Filename is too long (max. 255) // -6 : Not a valid zip file // -7 : Invalid extracted file size // -8 : Unable to create directory // -9 : Invalid archive extension // -10 : Invalid archive format // -11 : Unable to delete file (unlink) // -12 : Unable to rename file (rename) // -13 : Invalid header checksum // -14 : Invalid archive size define( 'PCLZIP_ERR_USER_ABORTED', 2 ); define( 'PCLZIP_ERR_NO_ERROR', 0 ); define( 'PCLZIP_ERR_WRITE_OPEN_FAIL', -1 ); define( 'PCLZIP_ERR_READ_OPEN_FAIL', -2 ); define( 'PCLZIP_ERR_INVALID_PARAMETER', -3 ); define( 'PCLZIP_ERR_MISSING_FILE', -4 ); define( 'PCLZIP_ERR_FILENAME_TOO_LONG', -5 ); define( 'PCLZIP_ERR_INVALID_ZIP', -6 ); define( 'PCLZIP_ERR_BAD_EXTRACTED_FILE', -7 ); define( 'PCLZIP_ERR_DIR_CREATE_FAIL', -8 ); define( 'PCLZIP_ERR_BAD_EXTENSION', -9 ); define( 'PCLZIP_ERR_BAD_FORMAT', -10 ); define( 'PCLZIP_ERR_DELETE_FILE_FAIL', -11 ); define( 'PCLZIP_ERR_RENAME_FILE_FAIL', -12 ); define( 'PCLZIP_ERR_BAD_CHECKSUM', -13 ); define( 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14 ); define( 'PCLZIP_ERR_MISSING_OPTION_VALUE', -15 ); define( 'PCLZIP_ERR_INVALID_OPTION_VALUE', -16 ); define( 'PCLZIP_ERR_ALREADY_A_DIRECTORY', -17 ); define( 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18 ); define( 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19 ); define( 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', -20 ); define( 'PCLZIP_ERR_DIRECTORY_RESTRICTION', -21 ); // ----- Options values define( 'PCLZIP_OPT_PATH', 77001 ); define( 'PCLZIP_OPT_ADD_PATH', 77002 ); define( 'PCLZIP_OPT_REMOVE_PATH', 77003 ); define( 'PCLZIP_OPT_REMOVE_ALL_PATH', 77004 ); define( 'PCLZIP_OPT_SET_CHMOD', 77005 ); define( 'PCLZIP_OPT_EXTRACT_AS_STRING', 77006 ); define( 'PCLZIP_OPT_NO_COMPRESSION', 77007 ); define( 'PCLZIP_OPT_BY_NAME', 77008 ); define( 'PCLZIP_OPT_BY_INDEX', 77009 ); define( 'PCLZIP_OPT_BY_EREG', 77010 ); define( 'PCLZIP_OPT_BY_PREG', 77011 ); define( 'PCLZIP_OPT_COMMENT', 77012 ); define( 'PCLZIP_OPT_ADD_COMMENT', 77013 ); define( 'PCLZIP_OPT_PREPEND_COMMENT', 77014 ); define( 'PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015 ); define( 'PCLZIP_OPT_REPLACE_NEWER', 77016 ); define( 'PCLZIP_OPT_STOP_ON_ERROR', 77017 ); // Having big trouble with crypt. Need to multiply 2 long int // which is not correctly supported by PHP ... //define( 'PCLZIP_OPT_CRYPT', 77018 ); define( 'PCLZIP_OPT_EXTRACT_DIR_RESTRICTION', 77019 ); define( 'PCLZIP_OPT_TEMP_FILE_THRESHOLD', 77020 ); define( 'PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD', 77020 ); // alias define( 'PCLZIP_OPT_TEMP_FILE_ON', 77021 ); define( 'PCLZIP_OPT_ADD_TEMP_FILE_ON', 77021 ); // alias define( 'PCLZIP_OPT_TEMP_FILE_OFF', 77022 ); define( 'PCLZIP_OPT_ADD_TEMP_FILE_OFF', 77022 ); // alias // ----- File description attributes define( 'PCLZIP_ATT_FILE_NAME', 79001 ); define( 'PCLZIP_ATT_FILE_NEW_SHORT_NAME', 79002 ); define( 'PCLZIP_ATT_FILE_NEW_FULL_NAME', 79003 ); define( 'PCLZIP_ATT_FILE_MTIME', 79004 ); define( 'PCLZIP_ATT_FILE_CONTENT', 79005 ); define( 'PCLZIP_ATT_FILE_COMMENT', 79006 ); // ----- Call backs values define( 'PCLZIP_CB_PRE_EXTRACT', 78001 ); define( 'PCLZIP_CB_POST_EXTRACT', 78002 ); define( 'PCLZIP_CB_PRE_ADD', 78003 ); define( 'PCLZIP_CB_POST_ADD', 78004 ); /* For futur use define( 'PCLZIP_CB_PRE_LIST', 78005 ); define( 'PCLZIP_CB_POST_LIST', 78006 ); define( 'PCLZIP_CB_PRE_DELETE', 78007 ); define( 'PCLZIP_CB_POST_DELETE', 78008 ); */ // -------------------------------------------------------------------------------- // Class : PclZip // Description : // PclZip is the class that represent a Zip archive. // The public methods allow the manipulation of the archive. // Attributes : // Attributes must not be accessed directly. // Methods : // PclZip() : Object creator // create() : Creates the Zip archive // listContent() : List the content of the Zip archive // extract() : Extract the content of the archive // properties() : List the properties of the archive // -------------------------------------------------------------------------------- class PclZip { // ----- Filename of the zip file var $zipname = ''; // ----- File descriptor of the zip file var $zip_fd = 0; // ----- Internal error handling var $error_code = 1; var $error_string = ''; // ----- Current status of the magic_quotes_runtime // This value store the php configuration for magic_quotes // The class can then disable the magic_quotes and reset it after var $magic_quotes_status; // -------------------------------------------------------------------------------- // Function : PclZip() // Description : // Creates a PclZip object and set the name of the associated Zip archive // filename. // Note that no real action is taken, if the archive does not exist it is not // created. Use create() for that. // -------------------------------------------------------------------------------- function PclZip($p_zipname) { // ----- Tests the zlib if (!function_exists('gzopen')) { die('Abort '.basename(__FILE__).' : Missing zlib extensions'); } // ----- Set the attributes $this->zipname = $p_zipname; $this->zip_fd = 0; $this->magic_quotes_status = -1; // ----- Return return; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : // create($p_filelist, $p_add_dir="", $p_remove_dir="") // create($p_filelist, $p_option, $p_option_value, ...) // Description : // This method supports two different synopsis. The first one is historical. // This method creates a Zip Archive. The Zip file is created in the // filesystem. The files and directories indicated in $p_filelist // are added in the archive. See the parameters description for the // supported format of $p_filelist. // When a directory is in the list, the directory and its content is added // in the archive. // In this synopsis, the function takes an optional variable list of // options. See bellow the supported options. // Parameters : // $p_filelist : An array containing file or directory names, or // a string containing one filename or one directory name, or // a string containing a list of filenames and/or directory // names separated by spaces. // $p_add_dir : A path to add before the real path of the archived file, // in order to have it memorized in the archive. // $p_remove_dir : A path to remove from the real path of the file to archive, // in order to have a shorter path memorized in the archive. // When $p_add_dir and $p_remove_dir are set, $p_remove_dir // is removed first, before $p_add_dir is added. // Options : // PCLZIP_OPT_ADD_PATH : // PCLZIP_OPT_REMOVE_PATH : // PCLZIP_OPT_REMOVE_ALL_PATH : // PCLZIP_OPT_COMMENT : // PCLZIP_CB_PRE_ADD : // PCLZIP_CB_POST_ADD : // Return Values : // 0 on failure, // The list of the added files, with a status of the add action. // (see PclZip::listContent() for list entry format) // -------------------------------------------------------------------------------- function create($p_filelist) { $v_result=1; // ----- Reset the error handler $this->privErrorReset(); // ----- Set default values $v_options = array(); $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; // ----- Look for variable options arguments $v_size = func_num_args(); // ----- Look for arguments if ($v_size > 1) { // ----- Get the arguments $v_arg_list = func_get_args(); // ----- Remove from the options list the first argument array_shift($v_arg_list); $v_size--; // ----- Look for first arg if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { // ----- Parse the options $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array (PCLZIP_OPT_REMOVE_PATH => 'optional', PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', PCLZIP_OPT_ADD_PATH => 'optional', PCLZIP_CB_PRE_ADD => 'optional', PCLZIP_CB_POST_ADD => 'optional', PCLZIP_OPT_NO_COMPRESSION => 'optional', PCLZIP_OPT_COMMENT => 'optional', PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', PCLZIP_OPT_TEMP_FILE_ON => 'optional', PCLZIP_OPT_TEMP_FILE_OFF => 'optional' //, PCLZIP_OPT_CRYPT => 'optional' )); if ($v_result != 1) { return 0; } } // ----- Look for 2 args // Here we need to support the first historic synopsis of the // method. else { // ----- Get the first argument $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0]; // ----- Look for the optional second argument if ($v_size == 2) { $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; } else if ($v_size > 2) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); return 0; } } } // ----- Look for default option values $this->privOptionDefaultThreshold($v_options); // ----- Init $v_string_list = array(); $v_att_list = array(); $v_filedescr_list = array(); $p_result_list = array(); // ----- Look if the $p_filelist is really an array if (is_array($p_filelist)) { // ----- Look if the first element is also an array // This will mean that this is a file description entry if (isset($p_filelist[0]) && is_array($p_filelist[0])) { $v_att_list = $p_filelist; } // ----- The list is a list of string names else { $v_string_list = $p_filelist; } } // ----- Look if the $p_filelist is a string else if (is_string($p_filelist)) { // ----- Create a list from the string $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); } // ----- Invalid variable type for $p_filelist else { PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist"); return 0; } // ----- Reformat the string list if (sizeof($v_string_list) != 0) { foreach ($v_string_list as $v_string) { if ($v_string != '') { $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; } else { } } } // ----- For each file in the list check the attributes $v_supported_attributes = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' ,PCLZIP_ATT_FILE_MTIME => 'optional' ,PCLZIP_ATT_FILE_CONTENT => 'optional' ,PCLZIP_ATT_FILE_COMMENT => 'optional' ); foreach ($v_att_list as $v_entry) { $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes); if ($v_result != 1) { return 0; } } // ----- Expand the filelist (expand directories) $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); if ($v_result != 1) { return 0; } // ----- Call the create fct $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options); if ($v_result != 1) { return 0; } // ----- Return return $p_result_list; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : // add($p_filelist, $p_add_dir="", $p_remove_dir="") // add($p_filelist, $p_option, $p_option_value, ...) // Description : // This method supports two synopsis. The first one is historical. // This methods add the list of files in an existing archive. // If a file with the same name already exists, it is added at the end of the // archive, the first one is still present. // If the archive does not exist, it is created. // Parameters : // $p_filelist : An array containing file or directory names, or // a string containing one filename or one directory name, or // a string containing a list of filenames and/or directory // names separated by spaces. // $p_add_dir : A path to add before the real path of the archived file, // in order to have it memorized in the archive. // $p_remove_dir : A path to remove from the real path of the file to archive, // in order to have a shorter path memorized in the archive. // When $p_add_dir and $p_remove_dir are set, $p_remove_dir // is removed first, before $p_add_dir is added. // Options : // PCLZIP_OPT_ADD_PATH : // PCLZIP_OPT_REMOVE_PATH : // PCLZIP_OPT_REMOVE_ALL_PATH : // PCLZIP_OPT_COMMENT : // PCLZIP_OPT_ADD_COMMENT : // PCLZIP_OPT_PREPEND_COMMENT : // PCLZIP_CB_PRE_ADD : // PCLZIP_CB_POST_ADD : // Return Values : // 0 on failure, // The list of the added files, with a status of the add action. // (see PclZip::listContent() for list entry format) // -------------------------------------------------------------------------------- function add($p_filelist) { $v_result=1; // ----- Reset the error handler $this->privErrorReset(); // ----- Set default values $v_options = array(); $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; // ----- Look for variable options arguments $v_size = func_num_args(); // ----- Look for arguments if ($v_size > 1) { // ----- Get the arguments $v_arg_list = func_get_args(); // ----- Remove form the options list the first argument array_shift($v_arg_list); $v_size--; // ----- Look for first arg if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { // ----- Parse the options $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array (PCLZIP_OPT_REMOVE_PATH => 'optional', PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', PCLZIP_OPT_ADD_PATH => 'optional', PCLZIP_CB_PRE_ADD => 'optional', PCLZIP_CB_POST_ADD => 'optional', PCLZIP_OPT_NO_COMPRESSION => 'optional', PCLZIP_OPT_COMMENT => 'optional', PCLZIP_OPT_ADD_COMMENT => 'optional', PCLZIP_OPT_PREPEND_COMMENT => 'optional', PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', PCLZIP_OPT_TEMP_FILE_ON => 'optional', PCLZIP_OPT_TEMP_FILE_OFF => 'optional' //, PCLZIP_OPT_CRYPT => 'optional' )); if ($v_result != 1) { return 0; } } // ----- Look for 2 args // Here we need to support the first historic synopsis of the // method. else { // ----- Get the first argument $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0]; // ----- Look for the optional second argument if ($v_size == 2) { $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; } else if ($v_size > 2) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); // ----- Return return 0; } } } // ----- Look for default option values $this->privOptionDefaultThreshold($v_options); // ----- Init $v_string_list = array(); $v_att_list = array(); $v_filedescr_list = array(); $p_result_list = array(); // ----- Look if the $p_filelist is really an array if (is_array($p_filelist)) { // ----- Look if the first element is also an array // This will mean that this is a file description entry if (isset($p_filelist[0]) && is_array($p_filelist[0])) { $v_att_list = $p_filelist; } // ----- The list is a list of string names else { $v_string_list = $p_filelist; } } // ----- Look if the $p_filelist is a string else if (is_string($p_filelist)) { // ----- Create a list from the string $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); } // ----- Invalid variable type for $p_filelist else { PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist"); return 0; } // ----- Reformat the string list if (sizeof($v_string_list) != 0) { foreach ($v_string_list as $v_string) { $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; } } // ----- For each file in the list check the attributes $v_supported_attributes = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' ,PCLZIP_ATT_FILE_MTIME => 'optional' ,PCLZIP_ATT_FILE_CONTENT => 'optional' ,PCLZIP_ATT_FILE_COMMENT => 'optional' ); foreach ($v_att_list as $v_entry) { $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes); if ($v_result != 1) { return 0; } } // ----- Expand the filelist (expand directories) $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); if ($v_result != 1) { return 0; } // ----- Call the create fct $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options); if ($v_result != 1) { return 0; } // ----- Return return $p_result_list; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : listContent() // Description : // This public method, gives the list of the files and directories, with their // properties. // The properties of each entries in the list are (used also in other functions) : // filename : Name of the file. For a create or add action it is the filename // given by the user. For an extract function it is the filename // of the extracted file. // stored_filename : Name of the file / directory stored in the archive. // size : Size of the stored file. // compressed_size : Size of the file's data compressed in the archive // (without the headers overhead) // mtime : Last known modification date of the file (UNIX timestamp) // comment : Comment associated with the file // folder : true | false // index : index of the file in the archive // status : status of the action (depending of the action) : // Values are : // ok : OK ! // filtered : the file / dir is not extracted (filtered by user) // already_a_directory : the file can not be extracted because a // directory with the same name already exists // write_protected : the file can not be extracted because a file // with the same name already exists and is // write protected // newer_exist : the file was not extracted because a newer file exists // path_creation_fail : the file is not extracted because the folder // does not exist and can not be created // write_error : the file was not extracted because there was a // error while writing the file // read_error : the file was not extracted because there was a error // while reading the file // invalid_header : the file was not extracted because of an archive // format error (bad file header) // Note that each time a method can continue operating when there // is an action error on a file, the error is only logged in the file status. // Return Values : // 0 on an unrecoverable failure, // The list of the files in the archive. // -------------------------------------------------------------------------------- function listContent() { $v_result=1; // ----- Reset the error handler $this->privErrorReset(); // ----- Check archive if (!$this->privCheckFormat()) { return(0); } // ----- Call the extracting fct $p_list = array(); if (($v_result = $this->privList($p_list)) != 1) { unset($p_list); return(0); } // ----- Return return $p_list; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : // extract($p_path="./", $p_remove_path="") // extract([$p_option, $p_option_value, ...]) // Description : // This method supports two synopsis. The first one is historical. // This method extract all the files / directories from the archive to the // folder indicated in $p_path. // If you want to ignore the 'root' part of path of the memorized files // you can indicate this in the optional $p_remove_path parameter. // By default, if a newer file with the same name already exists, the // file is not extracted. // // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append // at the end of the path value of PCLZIP_OPT_PATH. // Parameters : // $p_path : Path where the files and directories are to be extracted // $p_remove_path : First part ('root' part) of the memorized path // (if any similar) to remove while extracting. // Options : // PCLZIP_OPT_PATH : // PCLZIP_OPT_ADD_PATH : // PCLZIP_OPT_REMOVE_PATH : // PCLZIP_OPT_REMOVE_ALL_PATH : // PCLZIP_CB_PRE_EXTRACT : // PCLZIP_CB_POST_EXTRACT : // Return Values : // 0 or a negative value on failure, // The list of the extracted files, with a status of the action. // (see PclZip::listContent() for list entry format) // -------------------------------------------------------------------------------- function extract() { $v_result=1; // ----- Reset the error handler $this->privErrorReset(); // ----- Check archive if (!$this->privCheckFormat()) { return(0); } // ----- Set default values $v_options = array(); // $v_path = "./"; $v_path = ''; $v_remove_path = ""; $v_remove_all_path = false; // ----- Look for variable options arguments $v_size = func_num_args(); // ----- Default values for option $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; // ----- Look for arguments if ($v_size > 0) { // ----- Get the arguments $v_arg_list = func_get_args(); // ----- Look for first arg if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { // ----- Parse the options $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array (PCLZIP_OPT_PATH => 'optional', PCLZIP_OPT_REMOVE_PATH => 'optional', PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', PCLZIP_OPT_ADD_PATH => 'optional', PCLZIP_CB_PRE_EXTRACT => 'optional', PCLZIP_CB_POST_EXTRACT => 'optional', PCLZIP_OPT_SET_CHMOD => 'optional', PCLZIP_OPT_BY_NAME => 'optional', PCLZIP_OPT_BY_EREG => 'optional', PCLZIP_OPT_BY_PREG => 'optional', PCLZIP_OPT_BY_INDEX => 'optional', PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional', PCLZIP_OPT_REPLACE_NEWER => 'optional' ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', PCLZIP_OPT_TEMP_FILE_ON => 'optional', PCLZIP_OPT_TEMP_FILE_OFF => 'optional' )); if ($v_result != 1) { return 0; } // ----- Set the arguments if (isset($v_options[PCLZIP_OPT_PATH])) { $v_path = $v_options[PCLZIP_OPT_PATH]; } if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; } if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; } if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { // ----- Check for '/' in last path char if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { $v_path .= '/'; } $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; } } // ----- Look for 2 args // Here we need to support the first historic synopsis of the // method. else { // ----- Get the first argument $v_path = $v_arg_list[0]; // ----- Look for the optional second argument if ($v_size == 2) { $v_remove_path = $v_arg_list[1]; } else if ($v_size > 2) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); // ----- Return return 0; } } } // ----- Look for default option values $this->privOptionDefaultThreshold($v_options); // ----- Trace // ----- Call the extracting fct $p_list = array(); $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options); if ($v_result < 1) { unset($p_list); return(0); } // ----- Return return $p_list; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : // extractByIndex($p_index, $p_path="./", $p_remove_path="") // extractByIndex($p_index, [$p_option, $p_option_value, ...]) // Description : // This method supports two synopsis. The first one is historical. // This method is doing a partial extract of the archive. // The extracted files or folders are identified by their index in the // archive (from 0 to n). // Note that if the index identify a folder, only the folder entry is // extracted, not all the files included in the archive. // Parameters : // $p_index : A single index (integer) or a string of indexes of files to // extract. The form of the string is "0,4-6,8-12" with only numbers // and '-' for range or ',' to separate ranges. No spaces or ';' // are allowed. // $p_path : Path where the files and directories are to be extracted // $p_remove_path : First part ('root' part) of the memorized path // (if any similar) to remove while extracting. // Options : // PCLZIP_OPT_PATH : // PCLZIP_OPT_ADD_PATH : // PCLZIP_OPT_REMOVE_PATH : // PCLZIP_OPT_REMOVE_ALL_PATH : // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and // not as files. // The resulting content is in a new field 'content' in the file // structure. // This option must be used alone (any other options are ignored). // PCLZIP_CB_PRE_EXTRACT : // PCLZIP_CB_POST_EXTRACT : // Return Values : // 0 on failure, // The list of the extracted files, with a status of the action. // (see PclZip::listContent() for list entry format) // -------------------------------------------------------------------------------- //function extractByIndex($p_index, options...) function extractByIndex($p_index) { $v_result=1; // ----- Reset the error handler $this->privErrorReset(); // ----- Check archive if (!$this->privCheckFormat()) { return(0); } // ----- Set default values $v_options = array(); // $v_path = "./"; $v_path = ''; $v_remove_path = ""; $v_remove_all_path = false; // ----- Look for variable options arguments $v_size = func_num_args(); // ----- Default values for option $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; // ----- Look for arguments if ($v_size > 1) { // ----- Get the arguments $v_arg_list = func_get_args(); // ----- Remove form the options list the first argument array_shift($v_arg_list); $v_size--; // ----- Look for first arg if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { // ----- Parse the options $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array (PCLZIP_OPT_PATH => 'optional', PCLZIP_OPT_REMOVE_PATH => 'optional', PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', PCLZIP_OPT_ADD_PATH => 'optional', PCLZIP_CB_PRE_EXTRACT => 'optional', PCLZIP_CB_POST_EXTRACT => 'optional', PCLZIP_OPT_SET_CHMOD => 'optional', PCLZIP_OPT_REPLACE_NEWER => 'optional' ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', PCLZIP_OPT_TEMP_FILE_ON => 'optional', PCLZIP_OPT_TEMP_FILE_OFF => 'optional' )); if ($v_result != 1) { return 0; } // ----- Set the arguments if (isset($v_options[PCLZIP_OPT_PATH])) { $v_path = $v_options[PCLZIP_OPT_PATH]; } if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; } if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; } if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { // ----- Check for '/' in last path char if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { $v_path .= '/'; } $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; } if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) { $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; } else { } } // ----- Look for 2 args // Here we need to support the first historic synopsis of the // method. else { // ----- Get the first argument $v_path = $v_arg_list[0]; // ----- Look for the optional second argument if ($v_size == 2) { $v_remove_path = $v_arg_list[1]; } else if ($v_size > 2) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); // ----- Return return 0; } } } // ----- Trace // ----- Trick // Here I want to reuse extractByRule(), so I need to parse the $p_index // with privParseOptions() $v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index); $v_options_trick = array(); $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, array (PCLZIP_OPT_BY_INDEX => 'optional' )); if ($v_result != 1) { return 0; } $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX]; // ----- Look for default option values $this->privOptionDefaultThreshold($v_options); // ----- Call the extracting fct if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) { return(0); } // ----- Return return $p_list; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : // delete([$p_option, $p_option_value, ...]) // Description : // This method removes files from the archive. // If no parameters are given, then all the archive is emptied. // Parameters : // None or optional arguments. // Options : // PCLZIP_OPT_BY_INDEX : // PCLZIP_OPT_BY_NAME : // PCLZIP_OPT_BY_EREG : // PCLZIP_OPT_BY_PREG : // Return Values : // 0 on failure, // The list of the files which are still present in the archive. // (see PclZip::listContent() for list entry format) // -------------------------------------------------------------------------------- function delete() { $v_result=1; // ----- Reset the error handler $this->privErrorReset(); // ----- Check archive if (!$this->privCheckFormat()) { return(0); } // ----- Set default values $v_options = array(); // ----- Look for variable options arguments $v_size = func_num_args(); // ----- Look for arguments if ($v_size > 0) { // ----- Get the arguments $v_arg_list = func_get_args(); // ----- Parse the options $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array (PCLZIP_OPT_BY_NAME => 'optional', PCLZIP_OPT_BY_EREG => 'optional', PCLZIP_OPT_BY_PREG => 'optional', PCLZIP_OPT_BY_INDEX => 'optional' )); if ($v_result != 1) { return 0; } } // ----- Magic quotes trick $this->privDisableMagicQuotes(); // ----- Call the delete fct $v_list = array(); if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) { $this->privSwapBackMagicQuotes(); unset($v_list); return(0); } // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); // ----- Return return $v_list; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : deleteByIndex() // Description : // ***** Deprecated ***** // delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered. // -------------------------------------------------------------------------------- function deleteByIndex($p_index) { $p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index); // ----- Return return $p_list; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : properties() // Description : // This method gives the properties of the archive. // The properties are : // nb : Number of files in the archive // comment : Comment associated with the archive file // status : not_exist, ok // Parameters : // None // Return Values : // 0 on failure, // An array with the archive properties. // -------------------------------------------------------------------------------- function properties() { // ----- Reset the error handler $this->privErrorReset(); // ----- Magic quotes trick $this->privDisableMagicQuotes(); // ----- Check archive if (!$this->privCheckFormat()) { $this->privSwapBackMagicQuotes(); return(0); } // ----- Default properties $v_prop = array(); $v_prop['comment'] = ''; $v_prop['nb'] = 0; $v_prop['status'] = 'not_exist'; // ----- Look if file exists if (@is_file($this->zipname)) { // ----- Open the zip file if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) { $this->privSwapBackMagicQuotes(); // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); // ----- Return return 0; } // ----- Read the central directory informations $v_central_dir = array(); if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { $this->privSwapBackMagicQuotes(); return 0; } // ----- Close the zip file $this->privCloseFd(); // ----- Set the user attributes $v_prop['comment'] = $v_central_dir['comment']; $v_prop['nb'] = $v_central_dir['entries']; $v_prop['status'] = 'ok'; } // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); // ----- Return return $v_prop; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : duplicate() // Description : // This method creates an archive by copying the content of an other one. If // the archive already exist, it is replaced by the new one without any warning. // Parameters : // $p_archive : The filename of a valid archive, or // a valid PclZip object. // Return Values : // 1 on success. // 0 or a negative value on error (error code). // -------------------------------------------------------------------------------- function duplicate($p_archive) { $v_result = 1; // ----- Reset the error handler $this->privErrorReset(); // ----- Look if the $p_archive is a PclZip object if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) { // ----- Duplicate the archive $v_result = $this->privDuplicate($p_archive->zipname); } // ----- Look if the $p_archive is a string (so a filename) else if (is_string($p_archive)) { // ----- Check that $p_archive is a valid zip file // TBC : Should also check the archive format if (!is_file($p_archive)) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'"); $v_result = PCLZIP_ERR_MISSING_FILE; } else { // ----- Duplicate the archive $v_result = $this->privDuplicate($p_archive); } } // ----- Invalid variable else { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); $v_result = PCLZIP_ERR_INVALID_PARAMETER; } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : merge() // Description : // This method merge the $p_archive_to_add archive at the end of the current // one ($this). // If the archive ($this) does not exist, the merge becomes a duplicate. // If the $p_archive_to_add archive does not exist, the merge is a success. // Parameters : // $p_archive_to_add : It can be directly the filename of a valid zip archive, // or a PclZip object archive. // Return Values : // 1 on success, // 0 or negative values on error (see below). // -------------------------------------------------------------------------------- function merge($p_archive_to_add) { $v_result = 1; // ----- Reset the error handler $this->privErrorReset(); // ----- Check archive if (!$this->privCheckFormat()) { return(0); } // ----- Look if the $p_archive_to_add is a PclZip object if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) { // ----- Merge the archive $v_result = $this->privMerge($p_archive_to_add); } // ----- Look if the $p_archive_to_add is a string (so a filename) else if (is_string($p_archive_to_add)) { // ----- Create a temporary archive $v_object_archive = new PclZip($p_archive_to_add); // ----- Merge the archive $v_result = $this->privMerge($v_object_archive); } // ----- Invalid variable else { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); $v_result = PCLZIP_ERR_INVALID_PARAMETER; } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : errorCode() // Description : // Parameters : // -------------------------------------------------------------------------------- function errorCode() { if (PCLZIP_ERROR_EXTERNAL == 1) { return(PclErrorCode()); } else { return($this->error_code); } } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : errorName() // Description : // Parameters : // -------------------------------------------------------------------------------- function errorName($p_with_code=false) { $v_name = array ( PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR', PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL', PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL', PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER', PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE', PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG', PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP', PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE', PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL', PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION', PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT', PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL', PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL', PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM', PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE', PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE', PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION' ,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE' ,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION' ); if (isset($v_name[$this->error_code])) { $v_value = $v_name[$this->error_code]; } else { $v_value = 'NoName'; } if ($p_with_code) { return($v_value.' ('.$this->error_code.')'); } else { return($v_value); } } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : errorInfo() // Description : // Parameters : // -------------------------------------------------------------------------------- function errorInfo($p_full=false) { if (PCLZIP_ERROR_EXTERNAL == 1) { return(PclErrorString()); } else { if ($p_full) { return($this->errorName(true)." : ".$this->error_string); } else { return($this->error_string." [code ".$this->error_code."]"); } } } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS ***** // ***** ***** // ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY ***** // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privCheckFormat() // Description : // This method check that the archive exists and is a valid zip archive. // Several level of check exists. (futur) // Parameters : // $p_level : Level of check. Default 0. // 0 : Check the first bytes (magic codes) (default value)) // 1 : 0 + Check the central directory (futur) // 2 : 1 + Check each file header (futur) // Return Values : // true on success, // false on error, the error code is set. // -------------------------------------------------------------------------------- function privCheckFormat($p_level=0) { $v_result = true; // ----- Reset the file system cache clearstatcache(); // ----- Reset the error handler $this->privErrorReset(); // ----- Look if the file exits if (!is_file($this->zipname)) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'"); return(false); } // ----- Check that the file is readeable if (!is_readable($this->zipname)) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'"); return(false); } // ----- Check the magic code // TBC // ----- Check the central header // TBC // ----- Check each file header // TBC // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privParseOptions() // Description : // This internal methods reads the variable list of arguments ($p_options_list, // $p_size) and generate an array with the options and values ($v_result_list). // $v_requested_options contains the options that can be present and those that // must be present. // $v_requested_options is an array, with the option value as key, and 'optional', // or 'mandatory' as value. // Parameters : // See above. // Return Values : // 1 on success. // 0 on failure. // -------------------------------------------------------------------------------- function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false) { $v_result=1; // ----- Read the options $i=0; while ($i<$p_size) { // ----- Check if the option is supported if (!isset($v_requested_options[$p_options_list[$i]])) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method"); // ----- Return return PclZip::errorCode(); } // ----- Look for next option switch ($p_options_list[$i]) { // ----- Look for options that request a path value case PCLZIP_OPT_PATH : case PCLZIP_OPT_REMOVE_PATH : case PCLZIP_OPT_ADD_PATH : // ----- Check the number of parameters if (($i+1) >= $p_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Get the value $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); $i++; break; case PCLZIP_OPT_TEMP_FILE_THRESHOLD : // ----- Check the number of parameters if (($i+1) >= $p_size) { PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); return PclZip::errorCode(); } // ----- Check for incompatible options if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); return PclZip::errorCode(); } // ----- Check the value $v_value = $p_options_list[$i+1]; if ((!is_integer($v_value)) || ($v_value<0)) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'"); return PclZip::errorCode(); } // ----- Get the value (and convert it in bytes) $v_result_list[$p_options_list[$i]] = $v_value*1048576; $i++; break; case PCLZIP_OPT_TEMP_FILE_ON : // ----- Check for incompatible options if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); return PclZip::errorCode(); } $v_result_list[$p_options_list[$i]] = true; break; case PCLZIP_OPT_TEMP_FILE_OFF : // ----- Check for incompatible options if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'"); return PclZip::errorCode(); } // ----- Check for incompatible options if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'"); return PclZip::errorCode(); } $v_result_list[$p_options_list[$i]] = true; break; case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION : // ----- Check the number of parameters if (($i+1) >= $p_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Get the value if ( is_string($p_options_list[$i+1]) && ($p_options_list[$i+1] != '')) { $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); $i++; } else { } break; // ----- Look for options that request an array of string for value case PCLZIP_OPT_BY_NAME : // ----- Check the number of parameters if (($i+1) >= $p_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Get the value if (is_string($p_options_list[$i+1])) { $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1]; } else if (is_array($p_options_list[$i+1])) { $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; } else { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } $i++; break; // ----- Look for options that request an EREG or PREG expression case PCLZIP_OPT_BY_EREG : // ereg() is deprecated starting with PHP 5.3. Move PCLZIP_OPT_BY_EREG // to PCLZIP_OPT_BY_PREG $p_options_list[$i] = PCLZIP_OPT_BY_PREG; case PCLZIP_OPT_BY_PREG : //case PCLZIP_OPT_CRYPT : // ----- Check the number of parameters if (($i+1) >= $p_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Get the value if (is_string($p_options_list[$i+1])) { $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; } else { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } $i++; break; // ----- Look for options that takes a string case PCLZIP_OPT_COMMENT : case PCLZIP_OPT_ADD_COMMENT : case PCLZIP_OPT_PREPEND_COMMENT : // ----- Check the number of parameters if (($i+1) >= $p_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" .PclZipUtilOptionText($p_options_list[$i]) ."'"); // ----- Return return PclZip::errorCode(); } // ----- Get the value if (is_string($p_options_list[$i+1])) { $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; } else { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '" .PclZipUtilOptionText($p_options_list[$i]) ."'"); // ----- Return return PclZip::errorCode(); } $i++; break; // ----- Look for options that request an array of index case PCLZIP_OPT_BY_INDEX : // ----- Check the number of parameters if (($i+1) >= $p_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Get the value $v_work_list = array(); if (is_string($p_options_list[$i+1])) { // ----- Remove spaces $p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', ''); // ----- Parse items $v_work_list = explode(",", $p_options_list[$i+1]); } else if (is_integer($p_options_list[$i+1])) { $v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1]; } else if (is_array($p_options_list[$i+1])) { $v_work_list = $p_options_list[$i+1]; } else { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Reduce the index list // each index item in the list must be a couple with a start and // an end value : [0,3], [5-5], [8-10], ... // ----- Check the format of each item $v_sort_flag=false; $v_sort_value=0; for ($j=0; $j<sizeof($v_work_list); $j++) { // ----- Explode the item $v_item_list = explode("-", $v_work_list[$j]); $v_size_item_list = sizeof($v_item_list); // ----- TBC : Here we might check that each item is a // real integer ... // ----- Look for single value if ($v_size_item_list == 1) { // ----- Set the option value $v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0]; $v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[0]; } elseif ($v_size_item_list == 2) { // ----- Set the option value $v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0]; $v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[1]; } else { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Too many values in index range for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Look for list sort if ($v_result_list[$p_options_list[$i]][$j]['start'] < $v_sort_value) { $v_sort_flag=true; // ----- TBC : An automatic sort should be writen ... // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Invalid order of index range for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } $v_sort_value = $v_result_list[$p_options_list[$i]][$j]['start']; } // ----- Sort the items if ($v_sort_flag) { // TBC : To Be Completed } // ----- Next option $i++; break; // ----- Look for options that request no value case PCLZIP_OPT_REMOVE_ALL_PATH : case PCLZIP_OPT_EXTRACT_AS_STRING : case PCLZIP_OPT_NO_COMPRESSION : case PCLZIP_OPT_EXTRACT_IN_OUTPUT : case PCLZIP_OPT_REPLACE_NEWER : case PCLZIP_OPT_STOP_ON_ERROR : $v_result_list[$p_options_list[$i]] = true; break; // ----- Look for options that request an octal value case PCLZIP_OPT_SET_CHMOD : // ----- Check the number of parameters if (($i+1) >= $p_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Get the value $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; $i++; break; // ----- Look for options that request a call-back case PCLZIP_CB_PRE_EXTRACT : case PCLZIP_CB_POST_EXTRACT : case PCLZIP_CB_PRE_ADD : case PCLZIP_CB_POST_ADD : /* for futur use case PCLZIP_CB_PRE_DELETE : case PCLZIP_CB_POST_DELETE : case PCLZIP_CB_PRE_LIST : case PCLZIP_CB_POST_LIST : */ // ----- Check the number of parameters if (($i+1) >= $p_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Get the value $v_function_name = $p_options_list[$i+1]; // ----- Check that the value is a valid existing function if (!function_exists($v_function_name)) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Set the attribute $v_result_list[$p_options_list[$i]] = $v_function_name; $i++; break; default : // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Unknown parameter '" .$p_options_list[$i]."'"); // ----- Return return PclZip::errorCode(); } // ----- Next options $i++; } // ----- Look for mandatory options if ($v_requested_options !== false) { for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { // ----- Look for mandatory option if ($v_requested_options[$key] == 'mandatory') { // ----- Look if present if (!isset($v_result_list[$key])) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); // ----- Return return PclZip::errorCode(); } } } } // ----- Look for default values if (!isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privOptionDefaultThreshold() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privOptionDefaultThreshold(&$p_options) { $v_result=1; if (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) || isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) { return $v_result; } // ----- Get 'memory_limit' configuration value $v_memory_limit = ini_get('memory_limit'); $v_memory_limit = trim($v_memory_limit); $last = strtolower(substr($v_memory_limit, -1)); if($last == 'g') //$v_memory_limit = $v_memory_limit*1024*1024*1024; $v_memory_limit = $v_memory_limit*1073741824; if($last == 'm') //$v_memory_limit = $v_memory_limit*1024*1024; $v_memory_limit = $v_memory_limit*1048576; if($last == 'k') $v_memory_limit = $v_memory_limit*1024; $p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit*PCLZIP_TEMPORARY_FILE_RATIO); // ----- Sanity check : No threshold if value lower than 1M if ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) { unset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privFileDescrParseAtt() // Description : // Parameters : // Return Values : // 1 on success. // 0 on failure. // -------------------------------------------------------------------------------- function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options=false) { $v_result=1; // ----- For each file in the list check the attributes foreach ($p_file_list as $v_key => $v_value) { // ----- Check if the option is supported if (!isset($v_requested_options[$v_key])) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file"); // ----- Return return PclZip::errorCode(); } // ----- Look for attribute switch ($v_key) { case PCLZIP_ATT_FILE_NAME : if (!is_string($v_value)) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); return PclZip::errorCode(); } $p_filedescr['filename'] = PclZipUtilPathReduction($v_value); if ($p_filedescr['filename'] == '') { PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".PclZipUtilOptionText($v_key)."'"); return PclZip::errorCode(); } break; case PCLZIP_ATT_FILE_NEW_SHORT_NAME : if (!is_string($v_value)) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); return PclZip::errorCode(); } $p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value); if ($p_filedescr['new_short_name'] == '') { PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".PclZipUtilOptionText($v_key)."'"); return PclZip::errorCode(); } break; case PCLZIP_ATT_FILE_NEW_FULL_NAME : if (!is_string($v_value)) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); return PclZip::errorCode(); } $p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value); if ($p_filedescr['new_full_name'] == '') { PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".PclZipUtilOptionText($v_key)."'"); return PclZip::errorCode(); } break; // ----- Look for options that takes a string case PCLZIP_ATT_FILE_COMMENT : if (!is_string($v_value)) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); return PclZip::errorCode(); } $p_filedescr['comment'] = $v_value; break; case PCLZIP_ATT_FILE_MTIME : if (!is_integer($v_value)) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".PclZipUtilOptionText($v_key)."'"); return PclZip::errorCode(); } $p_filedescr['mtime'] = $v_value; break; case PCLZIP_ATT_FILE_CONTENT : $p_filedescr['content'] = $v_value; break; default : // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Unknown parameter '".$v_key."'"); // ----- Return return PclZip::errorCode(); } // ----- Look for mandatory options if ($v_requested_options !== false) { for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { // ----- Look for mandatory option if ($v_requested_options[$key] == 'mandatory') { // ----- Look if present if (!isset($p_file_list[$key])) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); return PclZip::errorCode(); } } } } // end foreach } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privFileDescrExpand() // Description : // This method look for each item of the list to see if its a file, a folder // or a string to be added as file. For any other type of files (link, other) // just ignore the item. // Then prepare the information that will be stored for that file. // When its a folder, expand the folder with all the files that are in that // folder (recursively). // Parameters : // Return Values : // 1 on success. // 0 on failure. // -------------------------------------------------------------------------------- function privFileDescrExpand(&$p_filedescr_list, &$p_options) { $v_result=1; // ----- Create a result list $v_result_list = array(); // ----- Look each entry for ($i=0; $i<sizeof($p_filedescr_list); $i++) { // ----- Get filedescr $v_descr = $p_filedescr_list[$i]; // ----- Reduce the filename $v_descr['filename'] = PclZipUtilTranslateWinPath($v_descr['filename'], false); $v_descr['filename'] = PclZipUtilPathReduction($v_descr['filename']); // ----- Look for real file or folder if (file_exists($v_descr['filename'])) { if (@is_file($v_descr['filename'])) { $v_descr['type'] = 'file'; } else if (@is_dir($v_descr['filename'])) { $v_descr['type'] = 'folder'; } else if (@is_link($v_descr['filename'])) { // skip continue; } else { // skip continue; } } // ----- Look for string added as file else if (isset($v_descr['content'])) { $v_descr['type'] = 'virtual_file'; } // ----- Missing file else { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '".$v_descr['filename']."' does not exist"); // ----- Return return PclZip::errorCode(); } // ----- Calculate the stored filename $this->privCalculateStoredFilename($v_descr, $p_options); // ----- Add the descriptor in result list $v_result_list[sizeof($v_result_list)] = $v_descr; // ----- Look for folder if ($v_descr['type'] == 'folder') { // ----- List of items in folder $v_dirlist_descr = array(); $v_dirlist_nb = 0; if ($v_folder_handler = @opendir($v_descr['filename'])) { while (($v_item_handler = @readdir($v_folder_handler)) !== false) { // ----- Skip '.' and '..' if (($v_item_handler == '.') || ($v_item_handler == '..')) { continue; } // ----- Compose the full filename $v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'].'/'.$v_item_handler; // ----- Look for different stored filename // Because the name of the folder was changed, the name of the // files/sub-folders also change if (($v_descr['stored_filename'] != $v_descr['filename']) && (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) { if ($v_descr['stored_filename'] != '') { $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'].'/'.$v_item_handler; } else { $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler; } } $v_dirlist_nb++; } @closedir($v_folder_handler); } else { // TBC : unable to open folder in read mode } // ----- Expand each element of the list if ($v_dirlist_nb != 0) { // ----- Expand if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) { return $v_result; } // ----- Concat the resulting list $v_result_list = array_merge($v_result_list, $v_dirlist_descr); } else { } // ----- Free local array unset($v_dirlist_descr); } } // ----- Get the result list $p_filedescr_list = $v_result_list; // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privCreate() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privCreate($p_filedescr_list, &$p_result_list, &$p_options) { $v_result=1; $v_list_detail = array(); // ----- Magic quotes trick $this->privDisableMagicQuotes(); // ----- Open the file in write mode if (($v_result = $this->privOpenFd('wb')) != 1) { // ----- Return return $v_result; } // ----- Add the list of files $v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options); // ----- Close $this->privCloseFd(); // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privAdd() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privAdd($p_filedescr_list, &$p_result_list, &$p_options) { $v_result=1; $v_list_detail = array(); // ----- Look if the archive exists or is empty if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0)) { // ----- Do a create $v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options); // ----- Return return $v_result; } // ----- Magic quotes trick $this->privDisableMagicQuotes(); // ----- Open the zip file if (($v_result=$this->privOpenFd('rb')) != 1) { // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); // ----- Return return $v_result; } // ----- Read the central directory informations $v_central_dir = array(); if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Go to beginning of File @rewind($this->zip_fd); // ----- Creates a temporay file $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; // ----- Open the temporary file in write mode if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); // ----- Return return PclZip::errorCode(); } // ----- Copy the files from the archive to the temporary file // TBC : Here I should better append the file and go back to erase the central dir $v_size = $v_central_dir['offset']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = fread($this->zip_fd, $v_read_size); @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Swap the file descriptor // Here is a trick : I swap the temporary fd with the zip fd, in order to use // the following methods on the temporary fil and not the real archive $v_swap = $this->zip_fd; $this->zip_fd = $v_zip_temp_fd; $v_zip_temp_fd = $v_swap; // ----- Add the files $v_header_list = array(); if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) { fclose($v_zip_temp_fd); $this->privCloseFd(); @unlink($v_zip_temp_name); $this->privSwapBackMagicQuotes(); // ----- Return return $v_result; } // ----- Store the offset of the central dir $v_offset = @ftell($this->zip_fd); // ----- Copy the block of file headers from the old archive $v_size = $v_central_dir['size']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($v_zip_temp_fd, $v_read_size); @fwrite($this->zip_fd, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Create the Central Dir files header for ($i=0, $v_count=0; $i<sizeof($v_header_list); $i++) { // ----- Create the file header if ($v_header_list[$i]['status'] == 'ok') { if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) { fclose($v_zip_temp_fd); $this->privCloseFd(); @unlink($v_zip_temp_name); $this->privSwapBackMagicQuotes(); // ----- Return return $v_result; } $v_count++; } // ----- Transform the header to a 'usable' info $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); } // ----- Zip file comment $v_comment = $v_central_dir['comment']; if (isset($p_options[PCLZIP_OPT_COMMENT])) { $v_comment = $p_options[PCLZIP_OPT_COMMENT]; } if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) { $v_comment = $v_comment.$p_options[PCLZIP_OPT_ADD_COMMENT]; } if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) { $v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT].$v_comment; } // ----- Calculate the size of the central header $v_size = @ftell($this->zip_fd)-$v_offset; // ----- Create the central dir footer if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1) { // ----- Reset the file list unset($v_header_list); $this->privSwapBackMagicQuotes(); // ----- Return return $v_result; } // ----- Swap back the file descriptor $v_swap = $this->zip_fd; $this->zip_fd = $v_zip_temp_fd; $v_zip_temp_fd = $v_swap; // ----- Close $this->privCloseFd(); // ----- Close the temporary file @fclose($v_zip_temp_fd); // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); // ----- Delete the zip file // TBC : I should test the result ... @unlink($this->zipname); // ----- Rename the temporary file // TBC : I should test the result ... //@rename($v_zip_temp_name, $this->zipname); PclZipUtilRename($v_zip_temp_name, $this->zipname); // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privOpenFd() // Description : // Parameters : // -------------------------------------------------------------------------------- function privOpenFd($p_mode) { $v_result=1; // ----- Look if already open if ($this->zip_fd != 0) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open'); // ----- Return return PclZip::errorCode(); } // ----- Open the zip file if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode'); // ----- Return return PclZip::errorCode(); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privCloseFd() // Description : // Parameters : // -------------------------------------------------------------------------------- function privCloseFd() { $v_result=1; if ($this->zip_fd != 0) @fclose($this->zip_fd); $this->zip_fd = 0; // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privAddList() // Description : // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is // different from the real path of the file. This is usefull if you want to have PclTar // running in any directory, and memorize relative path from an other directory. // Parameters : // $p_list : An array containing the file or directory names to add in the tar // $p_result_list : list of added files with their properties (specially the status field) // $p_add_dir : Path to add in the filename path archived // $p_remove_dir : Path to remove in the filename path archived // Return Values : // -------------------------------------------------------------------------------- // function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options) function privAddList($p_filedescr_list, &$p_result_list, &$p_options) { $v_result=1; // ----- Add the files $v_header_list = array(); if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) { // ----- Return return $v_result; } // ----- Store the offset of the central dir $v_offset = @ftell($this->zip_fd); // ----- Create the Central Dir files header for ($i=0,$v_count=0; $i<sizeof($v_header_list); $i++) { // ----- Create the file header if ($v_header_list[$i]['status'] == 'ok') { if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) { // ----- Return return $v_result; } $v_count++; } // ----- Transform the header to a 'usable' info $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); } // ----- Zip file comment $v_comment = ''; if (isset($p_options[PCLZIP_OPT_COMMENT])) { $v_comment = $p_options[PCLZIP_OPT_COMMENT]; } // ----- Calculate the size of the central header $v_size = @ftell($this->zip_fd)-$v_offset; // ----- Create the central dir footer if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1) { // ----- Reset the file list unset($v_header_list); // ----- Return return $v_result; } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privAddFileList() // Description : // Parameters : // $p_filedescr_list : An array containing the file description // or directory names to add in the zip // $p_result_list : list of added files with their properties (specially the status field) // Return Values : // -------------------------------------------------------------------------------- function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options) { $v_result=1; $v_header = array(); // ----- Recuperate the current number of elt in list $v_nb = sizeof($p_result_list); // ----- Loop on the files for ($j=0; ($j<sizeof($p_filedescr_list)) && ($v_result==1); $j++) { // ----- Format the filename $p_filedescr_list[$j]['filename'] = PclZipUtilTranslateWinPath($p_filedescr_list[$j]['filename'], false); // ----- Skip empty file names // TBC : Can this be possible ? not checked in DescrParseAtt ? if ($p_filedescr_list[$j]['filename'] == "") { continue; } // ----- Check the filename if ( ($p_filedescr_list[$j]['type'] != 'virtual_file') && (!file_exists($p_filedescr_list[$j]['filename']))) { PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '".$p_filedescr_list[$j]['filename']."' does not exist"); return PclZip::errorCode(); } // ----- Look if it is a file or a dir with no all path remove option // or a dir with all its path removed // if ( (is_file($p_filedescr_list[$j]['filename'])) // || ( is_dir($p_filedescr_list[$j]['filename']) if ( ($p_filedescr_list[$j]['type'] == 'file') || ($p_filedescr_list[$j]['type'] == 'virtual_file') || ( ($p_filedescr_list[$j]['type'] == 'folder') && ( !isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]) || !$p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) ) { // ----- Add the file $v_result = $this->privAddFile($p_filedescr_list[$j], $v_header, $p_options); if ($v_result != 1) { return $v_result; } // ----- Store the file infos $p_result_list[$v_nb++] = $v_header; } } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privAddFile() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privAddFile($p_filedescr, &$p_header, &$p_options) { $v_result=1; // ----- Working variable $p_filename = $p_filedescr['filename']; // TBC : Already done in the fileAtt check ... ? if ($p_filename == "") { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)"); // ----- Return return PclZip::errorCode(); } // ----- Look for a stored different filename /* TBC : Removed if (isset($p_filedescr['stored_filename'])) { $v_stored_filename = $p_filedescr['stored_filename']; } else { $v_stored_filename = $p_filedescr['stored_filename']; } */ // ----- Set the file properties clearstatcache(); $p_header['version'] = 20; $p_header['version_extracted'] = 10; $p_header['flag'] = 0; $p_header['compression'] = 0; $p_header['crc'] = 0; $p_header['compressed_size'] = 0; $p_header['filename_len'] = strlen($p_filename); $p_header['extra_len'] = 0; $p_header['disk'] = 0; $p_header['internal'] = 0; $p_header['offset'] = 0; $p_header['filename'] = $p_filename; // TBC : Removed $p_header['stored_filename'] = $v_stored_filename; $p_header['stored_filename'] = $p_filedescr['stored_filename']; $p_header['extra'] = ''; $p_header['status'] = 'ok'; $p_header['index'] = -1; // ----- Look for regular file if ($p_filedescr['type']=='file') { $p_header['external'] = 0x00000000; $p_header['size'] = filesize($p_filename); } // ----- Look for regular folder else if ($p_filedescr['type']=='folder') { $p_header['external'] = 0x00000010; $p_header['mtime'] = filemtime($p_filename); $p_header['size'] = filesize($p_filename); } // ----- Look for virtual file else if ($p_filedescr['type'] == 'virtual_file') { $p_header['external'] = 0x00000000; $p_header['size'] = strlen($p_filedescr['content']); } // ----- Look for filetime if (isset($p_filedescr['mtime'])) { $p_header['mtime'] = $p_filedescr['mtime']; } else if ($p_filedescr['type'] == 'virtual_file') { $p_header['mtime'] = time(); } else { $p_header['mtime'] = filemtime($p_filename); } // ------ Look for file comment if (isset($p_filedescr['comment'])) { $p_header['comment_len'] = strlen($p_filedescr['comment']); $p_header['comment'] = $p_filedescr['comment']; } else { $p_header['comment_len'] = 0; $p_header['comment'] = ''; } // ----- Look for pre-add callback if (isset($p_options[PCLZIP_CB_PRE_ADD])) { // ----- Generate a local information $v_local_header = array(); $this->privConvertHeader2FileInfo($p_header, $v_local_header); // ----- Call the callback // Here I do not use call_user_func() because I need to send a reference to the // header. $v_result = $p_options[PCLZIP_CB_PRE_ADD](PCLZIP_CB_PRE_ADD, $v_local_header); if ($v_result == 0) { // ----- Change the file status $p_header['status'] = "skipped"; $v_result = 1; } // ----- Update the informations // Only some fields can be modified if ($p_header['stored_filename'] != $v_local_header['stored_filename']) { $p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']); } } // ----- Look for empty stored filename if ($p_header['stored_filename'] == "") { $p_header['status'] = "filtered"; } // ----- Check the path length if (strlen($p_header['stored_filename']) > 0xFF) { $p_header['status'] = 'filename_too_long'; } // ----- Look if no error, or file not skipped if ($p_header['status'] == 'ok') { // ----- Look for a file if ($p_filedescr['type'] == 'file') { // ----- Look for using temporary file to zip if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])) ) ) { $v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options); if ($v_result < PCLZIP_ERR_NO_ERROR) { return $v_result; } } // ----- Use "in memory" zip algo else { // ----- Open the source file if (($v_file = @fopen($p_filename, "rb")) == 0) { PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); return PclZip::errorCode(); } // ----- Read the file content $v_content = @fread($v_file, $p_header['size']); // ----- Close the file @fclose($v_file); // ----- Calculate the CRC $p_header['crc'] = @crc32($v_content); // ----- Look for no compression if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { // ----- Set header parameters $p_header['compressed_size'] = $p_header['size']; $p_header['compression'] = 0; } // ----- Look for normal compression else { // ----- Compress the content $v_content = @gzdeflate($v_content); // ----- Set header parameters $p_header['compressed_size'] = strlen($v_content); $p_header['compression'] = 8; } // ----- Call the header generation if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { @fclose($v_file); return $v_result; } // ----- Write the compressed (or not) content @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); } } // ----- Look for a virtual file (a file from string) else if ($p_filedescr['type'] == 'virtual_file') { $v_content = $p_filedescr['content']; // ----- Calculate the CRC $p_header['crc'] = @crc32($v_content); // ----- Look for no compression if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { // ----- Set header parameters $p_header['compressed_size'] = $p_header['size']; $p_header['compression'] = 0; } // ----- Look for normal compression else { // ----- Compress the content $v_content = @gzdeflate($v_content); // ----- Set header parameters $p_header['compressed_size'] = strlen($v_content); $p_header['compression'] = 8; } // ----- Call the header generation if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { @fclose($v_file); return $v_result; } // ----- Write the compressed (or not) content @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); } // ----- Look for a directory else if ($p_filedescr['type'] == 'folder') { // ----- Look for directory last '/' if (@substr($p_header['stored_filename'], -1) != '/') { $p_header['stored_filename'] .= '/'; } // ----- Set the file properties $p_header['size'] = 0; //$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked $p_header['external'] = 0x00000010; // Value for a folder : to be checked // ----- Call the header generation if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { return $v_result; } } } // ----- Look for post-add callback if (isset($p_options[PCLZIP_CB_POST_ADD])) { // ----- Generate a local information $v_local_header = array(); $this->privConvertHeader2FileInfo($p_header, $v_local_header); // ----- Call the callback // Here I do not use call_user_func() because I need to send a reference to the // header. $v_result = $p_options[PCLZIP_CB_POST_ADD](PCLZIP_CB_POST_ADD, $v_local_header); if ($v_result == 0) { // ----- Ignored $v_result = 1; } // ----- Update the informations // Nothing can be modified } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privAddFileUsingTempFile() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options) { $v_result=PCLZIP_ERR_NO_ERROR; // ----- Working variable $p_filename = $p_filedescr['filename']; // ----- Open the source file if (($v_file = @fopen($p_filename, "rb")) == 0) { PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); return PclZip::errorCode(); } // ----- Creates a compressed temporary file $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) { fclose($v_file); PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); return PclZip::errorCode(); } // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks $v_size = filesize($p_filename); while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($v_file, $v_read_size); //$v_binary_data = pack('a'.$v_read_size, $v_buffer); @gzputs($v_file_compressed, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Close the file @fclose($v_file); @gzclose($v_file_compressed); // ----- Check the minimum file size if (filesize($v_gzip_temp_name) < 18) { PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \''.$v_gzip_temp_name.'\' has invalid filesize - should be minimum 18 bytes'); return PclZip::errorCode(); } // ----- Extract the compressed attributes if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) { PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); return PclZip::errorCode(); } // ----- Read the gzip file header $v_binary_data = @fread($v_file_compressed, 10); $v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data); // ----- Check some parameters $v_data_header['os'] = bin2hex($v_data_header['os']); // ----- Read the gzip file footer @fseek($v_file_compressed, filesize($v_gzip_temp_name)-8); $v_binary_data = @fread($v_file_compressed, 8); $v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data); // ----- Set the attributes $p_header['compression'] = ord($v_data_header['cm']); //$p_header['mtime'] = $v_data_header['mtime']; $p_header['crc'] = $v_data_footer['crc']; $p_header['compressed_size'] = filesize($v_gzip_temp_name)-18; // ----- Close the file @fclose($v_file_compressed); // ----- Call the header generation if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { return $v_result; } // ----- Add the compressed data if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) { PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); return PclZip::errorCode(); } // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks fseek($v_file_compressed, 10); $v_size = $p_header['compressed_size']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($v_file_compressed, $v_read_size); //$v_binary_data = pack('a'.$v_read_size, $v_buffer); @fwrite($this->zip_fd, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Close the file @fclose($v_file_compressed); // ----- Unlink the temporary file @unlink($v_gzip_temp_name); // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privCalculateStoredFilename() // Description : // Based on file descriptor properties and global options, this method // calculate the filename that will be stored in the archive. // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privCalculateStoredFilename(&$p_filedescr, &$p_options) { $v_result=1; // ----- Working variables $p_filename = $p_filedescr['filename']; if (isset($p_options[PCLZIP_OPT_ADD_PATH])) { $p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH]; } else { $p_add_dir = ''; } if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) { $p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH]; } else { $p_remove_dir = ''; } if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { $p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH]; } else { $p_remove_all_dir = 0; } // ----- Look for full name change if (isset($p_filedescr['new_full_name'])) { // ----- Remove drive letter if any $v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']); } // ----- Look for path and/or short name change else { // ----- Look for short name change // Its when we cahnge just the filename but not the path if (isset($p_filedescr['new_short_name'])) { $v_path_info = pathinfo($p_filename); $v_dir = ''; if ($v_path_info['dirname'] != '') { $v_dir = $v_path_info['dirname'].'/'; } $v_stored_filename = $v_dir.$p_filedescr['new_short_name']; } else { // ----- Calculate the stored filename $v_stored_filename = $p_filename; } // ----- Look for all path to remove if ($p_remove_all_dir) { $v_stored_filename = basename($p_filename); } // ----- Look for partial path remove else if ($p_remove_dir != "") { if (substr($p_remove_dir, -1) != '/') $p_remove_dir .= "/"; if ( (substr($p_filename, 0, 2) == "./") || (substr($p_remove_dir, 0, 2) == "./")) { if ( (substr($p_filename, 0, 2) == "./") && (substr($p_remove_dir, 0, 2) != "./")) { $p_remove_dir = "./".$p_remove_dir; } if ( (substr($p_filename, 0, 2) != "./") && (substr($p_remove_dir, 0, 2) == "./")) { $p_remove_dir = substr($p_remove_dir, 2); } } $v_compare = PclZipUtilPathInclusion($p_remove_dir, $v_stored_filename); if ($v_compare > 0) { if ($v_compare == 2) { $v_stored_filename = ""; } else { $v_stored_filename = substr($v_stored_filename, strlen($p_remove_dir)); } } } // ----- Remove drive letter if any $v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename); // ----- Look for path to add if ($p_add_dir != "") { if (substr($p_add_dir, -1) == "/") $v_stored_filename = $p_add_dir.$v_stored_filename; else $v_stored_filename = $p_add_dir."/".$v_stored_filename; } } // ----- Filename (reduce the path of stored name) $v_stored_filename = PclZipUtilPathReduction($v_stored_filename); $p_filedescr['stored_filename'] = $v_stored_filename; // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privWriteFileHeader() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privWriteFileHeader(&$p_header) { $v_result=1; // ----- Store the offset position of the file $p_header['offset'] = ftell($this->zip_fd); // ----- Transform UNIX mtime to DOS format mdate/mtime $v_date = getdate($p_header['mtime']); $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; // ----- Packed data $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, $p_header['version_extracted'], $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], $p_header['compressed_size'], $p_header['size'], strlen($p_header['stored_filename']), $p_header['extra_len']); // ----- Write the first 148 bytes of the header in the archive fputs($this->zip_fd, $v_binary_data, 30); // ----- Write the variable fields if (strlen($p_header['stored_filename']) != 0) { fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); } if ($p_header['extra_len'] != 0) { fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privWriteCentralFileHeader() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privWriteCentralFileHeader(&$p_header) { $v_result=1; // TBC //for(reset($p_header); $key = key($p_header); next($p_header)) { //} // ----- Transform UNIX mtime to DOS format mdate/mtime $v_date = getdate($p_header['mtime']); $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; // ----- Packed data $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, $p_header['version'], $p_header['version_extracted'], $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], $p_header['compressed_size'], $p_header['size'], strlen($p_header['stored_filename']), $p_header['extra_len'], $p_header['comment_len'], $p_header['disk'], $p_header['internal'], $p_header['external'], $p_header['offset']); // ----- Write the 42 bytes of the header in the zip file fputs($this->zip_fd, $v_binary_data, 46); // ----- Write the variable fields if (strlen($p_header['stored_filename']) != 0) { fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); } if ($p_header['extra_len'] != 0) { fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); } if ($p_header['comment_len'] != 0) { fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privWriteCentralHeader() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment) { $v_result=1; // ----- Packed data $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, $p_nb_entries, $p_size, $p_offset, strlen($p_comment)); // ----- Write the 22 bytes of the header in the zip file fputs($this->zip_fd, $v_binary_data, 22); // ----- Write the variable fields if (strlen($p_comment) != 0) { fputs($this->zip_fd, $p_comment, strlen($p_comment)); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privList() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privList(&$p_list) { $v_result=1; // ----- Magic quotes trick $this->privDisableMagicQuotes(); // ----- Open the zip file if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) { // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); // ----- Return return PclZip::errorCode(); } // ----- Read the central directory informations $v_central_dir = array(); if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Go to beginning of Central Dir @rewind($this->zip_fd); if (@fseek($this->zip_fd, $v_central_dir['offset'])) { $this->privSwapBackMagicQuotes(); // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return return PclZip::errorCode(); } // ----- Read each entry for ($i=0; $i<$v_central_dir['entries']; $i++) { // ----- Read the file header if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) { $this->privSwapBackMagicQuotes(); return $v_result; } $v_header['index'] = $i; // ----- Get the only interesting attributes $this->privConvertHeader2FileInfo($v_header, $p_list[$i]); unset($v_header); } // ----- Close the zip file $this->privCloseFd(); // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privConvertHeader2FileInfo() // Description : // This function takes the file informations from the central directory // entries and extract the interesting parameters that will be given back. // The resulting file infos are set in the array $p_info // $p_info['filename'] : Filename with full path. Given by user (add), // extracted in the filesystem (extract). // $p_info['stored_filename'] : Stored filename in the archive. // $p_info['size'] = Size of the file. // $p_info['compressed_size'] = Compressed size of the file. // $p_info['mtime'] = Last modification date of the file. // $p_info['comment'] = Comment associated with the file. // $p_info['folder'] = true/false : indicates if the entry is a folder or not. // $p_info['status'] = status of the action on the file. // $p_info['crc'] = CRC of the file content. // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privConvertHeader2FileInfo($p_header, &$p_info) { $v_result=1; // ----- Get the interesting attributes $v_temp_path = PclZipUtilPathReduction($p_header['filename']); $p_info['filename'] = $v_temp_path; $v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']); $p_info['stored_filename'] = $v_temp_path; $p_info['size'] = $p_header['size']; $p_info['compressed_size'] = $p_header['compressed_size']; $p_info['mtime'] = $p_header['mtime']; $p_info['comment'] = $p_header['comment']; $p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010); $p_info['index'] = $p_header['index']; $p_info['status'] = $p_header['status']; $p_info['crc'] = $p_header['crc']; // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privExtractByRule() // Description : // Extract a file or directory depending of rules (by index, by name, ...) // Parameters : // $p_file_list : An array where will be placed the properties of each // extracted file // $p_path : Path to add while writing the extracted files // $p_remove_path : Path to remove (from the file memorized path) while writing the // extracted files. If the path does not match the file path, // the file is extracted with its memorized path. // $p_remove_path does not apply to 'list' mode. // $p_path and $p_remove_path are commulative. // Return Values : // 1 on success,0 or less on error (see error code list) // -------------------------------------------------------------------------------- function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) { $v_result=1; // ----- Magic quotes trick $this->privDisableMagicQuotes(); // ----- Check the path if ( ($p_path == "") || ( (substr($p_path, 0, 1) != "/") && (substr($p_path, 0, 3) != "../") && (substr($p_path,1,2)!=":/"))) $p_path = "./".$p_path; // ----- Reduce the path last (and duplicated) '/' if (($p_path != "./") && ($p_path != "/")) { // ----- Look for the path end '/' while (substr($p_path, -1) == "/") { $p_path = substr($p_path, 0, strlen($p_path)-1); } } // ----- Look for path to remove format (should end by /) if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) { $p_remove_path .= '/'; } $p_remove_path_size = strlen($p_remove_path); // ----- Open the zip file if (($v_result = $this->privOpenFd('rb')) != 1) { $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Read the central directory informations $v_central_dir = array(); if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Start at beginning of Central Dir $v_pos_entry = $v_central_dir['offset']; // ----- Read each entry $j_start = 0; for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) { // ----- Read next Central dir entry @rewind($this->zip_fd); if (@fseek($this->zip_fd, $v_pos_entry)) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return return PclZip::errorCode(); } // ----- Read the file header $v_header = array(); if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Store the index $v_header['index'] = $i; // ----- Store the file position $v_pos_entry = ftell($this->zip_fd); // ----- Look for the specific extract rules $v_extract = false; // ----- Look for extract by name rule if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { // ----- Look if the filename is in the list for ($j=0; ($j<sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_extract); $j++) { // ----- Look for a directory if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") { // ----- Look if the directory is in the filename path if ( (strlen($v_header['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { $v_extract = true; } } // ----- Look for a filename elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { $v_extract = true; } } } // ----- Look for extract by ereg rule // ereg() is deprecated with PHP 5.3 /* else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) { $v_extract = true; } } */ // ----- Look for extract by preg rule else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) { $v_extract = true; } } // ----- Look for extract by index rule else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { // ----- Look if the index is in the list for ($j=$j_start; ($j<sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_extract); $j++) { if (($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { $v_extract = true; } if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { $j_start = $j+1; } if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { break; } } } // ----- Look for no rule, which means extract all the archive else { $v_extract = true; } // ----- Check compression method if ( ($v_extract) && ( ($v_header['compression'] != 8) && ($v_header['compression'] != 0))) { $v_header['status'] = 'unsupported_compression'; // ----- Look for PCLZIP_OPT_STOP_ON_ERROR if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { $this->privSwapBackMagicQuotes(); PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, "Filename '".$v_header['stored_filename']."' is " ."compressed by an unsupported compression " ."method (".$v_header['compression'].") "); return PclZip::errorCode(); } } // ----- Check encrypted files if (($v_extract) && (($v_header['flag'] & 1) == 1)) { $v_header['status'] = 'unsupported_encryption'; // ----- Look for PCLZIP_OPT_STOP_ON_ERROR if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { $this->privSwapBackMagicQuotes(); PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, "Unsupported encryption for " ." filename '".$v_header['stored_filename'] ."'"); return PclZip::errorCode(); } } // ----- Look for real extraction if (($v_extract) && ($v_header['status'] != 'ok')) { $v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++]); if ($v_result != 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } $v_extract = false; } // ----- Look for real extraction if ($v_extract) { // ----- Go to the file position @rewind($this->zip_fd); if (@fseek($this->zip_fd, $v_header['offset'])) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return return PclZip::errorCode(); } // ----- Look for extraction as string if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) { $v_string = ''; // ----- Extracting the file $v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options); if ($v_result1 < 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result1; } // ----- Get the only interesting attributes if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Set the file content $p_file_list[$v_nb_extracted]['content'] = $v_string; // ----- Next extracted file $v_nb_extracted++; // ----- Look for user callback abort if ($v_result1 == 2) { break; } } // ----- Look for extraction in standard output elseif ( (isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) { // ----- Extracting the file in standard output $v_result1 = $this->privExtractFileInOutput($v_header, $p_options); if ($v_result1 < 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result1; } // ----- Get the only interesting attributes if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Look for user callback abort if ($v_result1 == 2) { break; } } // ----- Look for normal extraction else { // ----- Extracting the file $v_result1 = $this->privExtractFile($v_header, $p_path, $p_remove_path, $p_remove_all_path, $p_options); if ($v_result1 < 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result1; } // ----- Get the only interesting attributes if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Look for user callback abort if ($v_result1 == 2) { break; } } } } // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privExtractFile() // Description : // Parameters : // Return Values : // // 1 : ... ? // PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback // -------------------------------------------------------------------------------- function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) { $v_result=1; // ----- Read the file header if (($v_result = $this->privReadFileHeader($v_header)) != 1) { // ----- Return return $v_result; } // ----- Check that the file header is coherent with $p_entry info if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { // TBC } // ----- Look for all path to remove if ($p_remove_all_path == true) { // ----- Look for folder entry that not need to be extracted if (($p_entry['external']&0x00000010)==0x00000010) { $p_entry['status'] = "filtered"; return $v_result; } // ----- Get the basename of the path $p_entry['filename'] = basename($p_entry['filename']); } // ----- Look for path to remove else if ($p_remove_path != "") { if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) { // ----- Change the file status $p_entry['status'] = "filtered"; // ----- Return return $v_result; } $p_remove_path_size = strlen($p_remove_path); if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) { // ----- Remove the path $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size); } } // ----- Add the path if ($p_path != '') { $p_entry['filename'] = $p_path."/".$p_entry['filename']; } // ----- Check a base_dir_restriction if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) { $v_inclusion = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION], $p_entry['filename']); if ($v_inclusion == 0) { PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, "Filename '".$p_entry['filename']."' is " ."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION"); return PclZip::errorCode(); } } // ----- Look for pre-extract callback if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { // ----- Generate a local information $v_local_header = array(); $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Call the callback // Here I do not use call_user_func() because I need to send a reference to the // header. $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); if ($v_result == 0) { // ----- Change the file status $p_entry['status'] = "skipped"; $v_result = 1; } // ----- Look for abort result if ($v_result == 2) { // ----- This status is internal and will be changed in 'skipped' $p_entry['status'] = "aborted"; $v_result = PCLZIP_ERR_USER_ABORTED; } // ----- Update the informations // Only some fields can be modified $p_entry['filename'] = $v_local_header['filename']; } // ----- Look if extraction should be done if ($p_entry['status'] == 'ok') { // ----- Look for specific actions while the file exist if (file_exists($p_entry['filename'])) { // ----- Look if file is a directory if (is_dir($p_entry['filename'])) { // ----- Change the file status $p_entry['status'] = "already_a_directory"; // ----- Look for PCLZIP_OPT_STOP_ON_ERROR // For historical reason first PclZip implementation does not stop // when this kind of error occurs. if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, "Filename '".$p_entry['filename']."' is " ."already used by an existing directory"); return PclZip::errorCode(); } } // ----- Look if file is write protected else if (!is_writeable($p_entry['filename'])) { // ----- Change the file status $p_entry['status'] = "write_protected"; // ----- Look for PCLZIP_OPT_STOP_ON_ERROR // For historical reason first PclZip implementation does not stop // when this kind of error occurs. if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, "Filename '".$p_entry['filename']."' exists " ."and is write protected"); return PclZip::errorCode(); } } // ----- Look if the extracted file is older else if (filemtime($p_entry['filename']) > $p_entry['mtime']) { // ----- Change the file status if ( (isset($p_options[PCLZIP_OPT_REPLACE_NEWER])) && ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) { } else { $p_entry['status'] = "newer_exist"; // ----- Look for PCLZIP_OPT_STOP_ON_ERROR // For historical reason first PclZip implementation does not stop // when this kind of error occurs. if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, "Newer version of '".$p_entry['filename']."' exists " ."and option PCLZIP_OPT_REPLACE_NEWER is not selected"); return PclZip::errorCode(); } } } else { } } // ----- Check the directory availability and create it if necessary else { if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) $v_dir_to_check = $p_entry['filename']; else if (!strstr($p_entry['filename'], "/")) $v_dir_to_check = ""; else $v_dir_to_check = dirname($p_entry['filename']); if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) { // ----- Change the file status $p_entry['status'] = "path_creation_fail"; // ----- Return //return $v_result; $v_result = 1; } } } // ----- Look if extraction should be done if ($p_entry['status'] == 'ok') { // ----- Do the extraction (if not a folder) if (!(($p_entry['external']&0x00000010)==0x00000010)) { // ----- Look for not compressed file if ($p_entry['compression'] == 0) { // ----- Opening destination file if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { // ----- Change the file status $p_entry['status'] = "write_error"; // ----- Return return $v_result; } // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks $v_size = $p_entry['compressed_size']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($this->zip_fd, $v_read_size); /* Try to speed up the code $v_binary_data = pack('a'.$v_read_size, $v_buffer); @fwrite($v_dest_file, $v_binary_data, $v_read_size); */ @fwrite($v_dest_file, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Closing the destination file fclose($v_dest_file); // ----- Change the file mtime touch($p_entry['filename'], $p_entry['mtime']); } else { // ----- TBC // Need to be finished if (($p_entry['flag'] & 1) == 1) { PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.'); return PclZip::errorCode(); } // ----- Look for using temporary file to unzip if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])) ) ) { $v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options); if ($v_result < PCLZIP_ERR_NO_ERROR) { return $v_result; } } // ----- Look for extract in memory else { // ----- Read the compressed file in a buffer (one shot) $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); // ----- Decompress the file $v_file_content = @gzinflate($v_buffer); unset($v_buffer); if ($v_file_content === FALSE) { // ----- Change the file status // TBC $p_entry['status'] = "error"; return $v_result; } // ----- Opening destination file if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { // ----- Change the file status $p_entry['status'] = "write_error"; return $v_result; } // ----- Write the uncompressed data @fwrite($v_dest_file, $v_file_content, $p_entry['size']); unset($v_file_content); // ----- Closing the destination file @fclose($v_dest_file); } // ----- Change the file mtime @touch($p_entry['filename'], $p_entry['mtime']); } // ----- Look for chmod option if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) { // ----- Change the mode of the file @chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]); } } } // ----- Change abort status if ($p_entry['status'] == "aborted") { $p_entry['status'] = "skipped"; } // ----- Look for post-extract callback elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { // ----- Generate a local information $v_local_header = array(); $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Call the callback // Here I do not use call_user_func() because I need to send a reference to the // header. $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); // ----- Look for abort result if ($v_result == 2) { $v_result = PCLZIP_ERR_USER_ABORTED; } } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privExtractFileUsingTempFile() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privExtractFileUsingTempFile(&$p_entry, &$p_options) { $v_result=1; // ----- Creates a temporary file $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) { fclose($v_file); PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); return PclZip::errorCode(); } // ----- Write gz file format header $v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3)); @fwrite($v_dest_file, $v_binary_data, 10); // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks $v_size = $p_entry['compressed_size']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($this->zip_fd, $v_read_size); //$v_binary_data = pack('a'.$v_read_size, $v_buffer); @fwrite($v_dest_file, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Write gz file format footer $v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']); @fwrite($v_dest_file, $v_binary_data, 8); // ----- Close the temporary file @fclose($v_dest_file); // ----- Opening destination file if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { $p_entry['status'] = "write_error"; return $v_result; } // ----- Open the temporary gz file if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) { @fclose($v_dest_file); $p_entry['status'] = "read_error"; PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); return PclZip::errorCode(); } // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks $v_size = $p_entry['size']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @gzread($v_src_file, $v_read_size); //$v_binary_data = pack('a'.$v_read_size, $v_buffer); @fwrite($v_dest_file, $v_buffer, $v_read_size); $v_size -= $v_read_size; } @fclose($v_dest_file); @gzclose($v_src_file); // ----- Delete the temporary file @unlink($v_gzip_temp_name); // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privExtractFileInOutput() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privExtractFileInOutput(&$p_entry, &$p_options) { $v_result=1; // ----- Read the file header if (($v_result = $this->privReadFileHeader($v_header)) != 1) { return $v_result; } // ----- Check that the file header is coherent with $p_entry info if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { // TBC } // ----- Look for pre-extract callback if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { // ----- Generate a local information $v_local_header = array(); $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Call the callback // Here I do not use call_user_func() because I need to send a reference to the // header. // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); if ($v_result == 0) { // ----- Change the file status $p_entry['status'] = "skipped"; $v_result = 1; } // ----- Look for abort result if ($v_result == 2) { // ----- This status is internal and will be changed in 'skipped' $p_entry['status'] = "aborted"; $v_result = PCLZIP_ERR_USER_ABORTED; } // ----- Update the informations // Only some fields can be modified $p_entry['filename'] = $v_local_header['filename']; } // ----- Trace // ----- Look if extraction should be done if ($p_entry['status'] == 'ok') { // ----- Do the extraction (if not a folder) if (!(($p_entry['external']&0x00000010)==0x00000010)) { // ----- Look for not compressed file if ($p_entry['compressed_size'] == $p_entry['size']) { // ----- Read the file in a buffer (one shot) $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); // ----- Send the file to the output echo $v_buffer; unset($v_buffer); } else { // ----- Read the compressed file in a buffer (one shot) $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); // ----- Decompress the file $v_file_content = gzinflate($v_buffer); unset($v_buffer); // ----- Send the file to the output echo $v_file_content; unset($v_file_content); } } } // ----- Change abort status if ($p_entry['status'] == "aborted") { $p_entry['status'] = "skipped"; } // ----- Look for post-extract callback elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { // ----- Generate a local information $v_local_header = array(); $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Call the callback // Here I do not use call_user_func() because I need to send a reference to the // header. $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); // ----- Look for abort result if ($v_result == 2) { $v_result = PCLZIP_ERR_USER_ABORTED; } } return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privExtractFileAsString() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privExtractFileAsString(&$p_entry, &$p_string, &$p_options) { $v_result=1; // ----- Read the file header $v_header = array(); if (($v_result = $this->privReadFileHeader($v_header)) != 1) { // ----- Return return $v_result; } // ----- Check that the file header is coherent with $p_entry info if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { // TBC } // ----- Look for pre-extract callback if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { // ----- Generate a local information $v_local_header = array(); $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Call the callback // Here I do not use call_user_func() because I need to send a reference to the // header. $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); if ($v_result == 0) { // ----- Change the file status $p_entry['status'] = "skipped"; $v_result = 1; } // ----- Look for abort result if ($v_result == 2) { // ----- This status is internal and will be changed in 'skipped' $p_entry['status'] = "aborted"; $v_result = PCLZIP_ERR_USER_ABORTED; } // ----- Update the informations // Only some fields can be modified $p_entry['filename'] = $v_local_header['filename']; } // ----- Look if extraction should be done if ($p_entry['status'] == 'ok') { // ----- Do the extraction (if not a folder) if (!(($p_entry['external']&0x00000010)==0x00000010)) { // ----- Look for not compressed file // if ($p_entry['compressed_size'] == $p_entry['size']) if ($p_entry['compression'] == 0) { // ----- Reading the file $p_string = @fread($this->zip_fd, $p_entry['compressed_size']); } else { // ----- Reading the file $v_data = @fread($this->zip_fd, $p_entry['compressed_size']); // ----- Decompress the file if (($p_string = @gzinflate($v_data)) === FALSE) { // TBC } } // ----- Trace } else { // TBC : error : can not extract a folder in a string } } // ----- Change abort status if ($p_entry['status'] == "aborted") { $p_entry['status'] = "skipped"; } // ----- Look for post-extract callback elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { // ----- Generate a local information $v_local_header = array(); $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Swap the content to header $v_local_header['content'] = $p_string; $p_string = ''; // ----- Call the callback // Here I do not use call_user_func() because I need to send a reference to the // header. $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); // ----- Swap back the content to header $p_string = $v_local_header['content']; unset($v_local_header['content']); // ----- Look for abort result if ($v_result == 2) { $v_result = PCLZIP_ERR_USER_ABORTED; } } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privReadFileHeader() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privReadFileHeader(&$p_header) { $v_result=1; // ----- Read the 4 bytes signature $v_binary_data = @fread($this->zip_fd, 4); $v_data = unpack('Vid', $v_binary_data); // ----- Check signature if ($v_data['id'] != 0x04034b50) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); // ----- Return return PclZip::errorCode(); } // ----- Read the first 42 bytes of the header $v_binary_data = fread($this->zip_fd, 26); // ----- Look for invalid block size if (strlen($v_binary_data) != 26) { $p_header['filename'] = ""; $p_header['status'] = "invalid_header"; // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); // ----- Return return PclZip::errorCode(); } // ----- Extract the values $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data); // ----- Get filename $p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']); // ----- Get extra_fields if ($v_data['extra_len'] != 0) { $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']); } else { $p_header['extra'] = ''; } // ----- Extract properties $p_header['version_extracted'] = $v_data['version']; $p_header['compression'] = $v_data['compression']; $p_header['size'] = $v_data['size']; $p_header['compressed_size'] = $v_data['compressed_size']; $p_header['crc'] = $v_data['crc']; $p_header['flag'] = $v_data['flag']; $p_header['filename_len'] = $v_data['filename_len']; // ----- Recuperate date in UNIX format $p_header['mdate'] = $v_data['mdate']; $p_header['mtime'] = $v_data['mtime']; if ($p_header['mdate'] && $p_header['mtime']) { // ----- Extract time $v_hour = ($p_header['mtime'] & 0xF800) >> 11; $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; $v_seconde = ($p_header['mtime'] & 0x001F)*2; // ----- Extract date $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; $v_month = ($p_header['mdate'] & 0x01E0) >> 5; $v_day = $p_header['mdate'] & 0x001F; // ----- Get UNIX date format $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); } else { $p_header['mtime'] = time(); } // TBC //for(reset($v_data); $key = key($v_data); next($v_data)) { //} // ----- Set the stored filename $p_header['stored_filename'] = $p_header['filename']; // ----- Set the status field $p_header['status'] = "ok"; // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privReadCentralFileHeader() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privReadCentralFileHeader(&$p_header) { $v_result=1; // ----- Read the 4 bytes signature $v_binary_data = @fread($this->zip_fd, 4); $v_data = unpack('Vid', $v_binary_data); // ----- Check signature if ($v_data['id'] != 0x02014b50) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); // ----- Return return PclZip::errorCode(); } // ----- Read the first 42 bytes of the header $v_binary_data = fread($this->zip_fd, 42); // ----- Look for invalid block size if (strlen($v_binary_data) != 42) { $p_header['filename'] = ""; $p_header['status'] = "invalid_header"; // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); // ----- Return return PclZip::errorCode(); } // ----- Extract the values $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data); // ----- Get filename if ($p_header['filename_len'] != 0) $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']); else $p_header['filename'] = ''; // ----- Get extra if ($p_header['extra_len'] != 0) $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']); else $p_header['extra'] = ''; // ----- Get comment if ($p_header['comment_len'] != 0) $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']); else $p_header['comment'] = ''; // ----- Extract properties // ----- Recuperate date in UNIX format //if ($p_header['mdate'] && $p_header['mtime']) // TBC : bug : this was ignoring time with 0/0/0 if (1) { // ----- Extract time $v_hour = ($p_header['mtime'] & 0xF800) >> 11; $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; $v_seconde = ($p_header['mtime'] & 0x001F)*2; // ----- Extract date $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; $v_month = ($p_header['mdate'] & 0x01E0) >> 5; $v_day = $p_header['mdate'] & 0x001F; // ----- Get UNIX date format $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); } else { $p_header['mtime'] = time(); } // ----- Set the stored filename $p_header['stored_filename'] = $p_header['filename']; // ----- Set default status to ok $p_header['status'] = 'ok'; // ----- Look if it is a directory if (substr($p_header['filename'], -1) == '/') { //$p_header['external'] = 0x41FF0010; $p_header['external'] = 0x00000010; } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privCheckFileHeaders() // Description : // Parameters : // Return Values : // 1 on success, // 0 on error; // -------------------------------------------------------------------------------- function privCheckFileHeaders(&$p_local_header, &$p_central_header) { $v_result=1; // ----- Check the static values // TBC if ($p_local_header['filename'] != $p_central_header['filename']) { } if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) { } if ($p_local_header['flag'] != $p_central_header['flag']) { } if ($p_local_header['compression'] != $p_central_header['compression']) { } if ($p_local_header['mtime'] != $p_central_header['mtime']) { } if ($p_local_header['filename_len'] != $p_central_header['filename_len']) { } // ----- Look for flag bit 3 if (($p_local_header['flag'] & 8) == 8) { $p_local_header['size'] = $p_central_header['size']; $p_local_header['compressed_size'] = $p_central_header['compressed_size']; $p_local_header['crc'] = $p_central_header['crc']; } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privReadEndCentralDir() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privReadEndCentralDir(&$p_central_dir) { $v_result=1; // ----- Go to the end of the zip file $v_size = filesize($this->zipname); @fseek($this->zip_fd, $v_size); if (@ftell($this->zip_fd) != $v_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\''); // ----- Return return PclZip::errorCode(); } // ----- First try : look if this is an archive with no commentaries (most of the time) // in this case the end of central dir is at 22 bytes of the file end $v_found = 0; if ($v_size > 26) { @fseek($this->zip_fd, $v_size-22); if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22)) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); // ----- Return return PclZip::errorCode(); } // ----- Read for bytes $v_binary_data = @fread($this->zip_fd, 4); $v_data = @unpack('Vid', $v_binary_data); // ----- Check signature if ($v_data['id'] == 0x06054b50) { $v_found = 1; } $v_pos = ftell($this->zip_fd); } // ----- Go back to the maximum possible size of the Central Dir End Record if (!$v_found) { $v_maximum_size = 65557; // 0xFFFF + 22; if ($v_maximum_size > $v_size) $v_maximum_size = $v_size; @fseek($this->zip_fd, $v_size-$v_maximum_size); if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size)) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); // ----- Return return PclZip::errorCode(); } // ----- Read byte per byte in order to find the signature $v_pos = ftell($this->zip_fd); $v_bytes = 0x00000000; while ($v_pos < $v_size) { // ----- Read a byte $v_byte = @fread($this->zip_fd, 1); // ----- Add the byte //$v_bytes = ($v_bytes << 8) | Ord($v_byte); // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number // Otherwise on systems where we have 64bit integers the check below for the magic number will fail. $v_bytes = ( ($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte); // ----- Compare the bytes if ($v_bytes == 0x504b0506) { $v_pos++; break; } $v_pos++; } // ----- Look if not found end of central dir if ($v_pos == $v_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature"); // ----- Return return PclZip::errorCode(); } } // ----- Read the first 18 bytes of the header $v_binary_data = fread($this->zip_fd, 18); // ----- Look for invalid block size if (strlen($v_binary_data) != 18) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data)); // ----- Return return PclZip::errorCode(); } // ----- Extract the values $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); // ----- Check the global size if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { // ----- Removed in release 2.2 see readme file // The check of the file size is a little too strict. // Some bugs where found when a zip is encrypted/decrypted with 'crypt'. // While decrypted, zip has training 0 bytes if (0) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'The central dir is not at the end of the archive.' .' Some trailing bytes exists after the archive.'); // ----- Return return PclZip::errorCode(); } } // ----- Get comment if ($v_data['comment_size'] != 0) { $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']); } else $p_central_dir['comment'] = ''; $p_central_dir['entries'] = $v_data['entries']; $p_central_dir['disk_entries'] = $v_data['disk_entries']; $p_central_dir['offset'] = $v_data['offset']; $p_central_dir['size'] = $v_data['size']; $p_central_dir['disk'] = $v_data['disk']; $p_central_dir['disk_start'] = $v_data['disk_start']; // TBC //for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) { //} // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privDeleteByRule() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privDeleteByRule(&$p_result_list, &$p_options) { $v_result=1; $v_list_detail = array(); // ----- Open the zip file if (($v_result=$this->privOpenFd('rb')) != 1) { // ----- Return return $v_result; } // ----- Read the central directory informations $v_central_dir = array(); if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { $this->privCloseFd(); return $v_result; } // ----- Go to beginning of File @rewind($this->zip_fd); // ----- Scan all the files // ----- Start at beginning of Central Dir $v_pos_entry = $v_central_dir['offset']; @rewind($this->zip_fd); if (@fseek($this->zip_fd, $v_pos_entry)) { // ----- Close the zip file $this->privCloseFd(); // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return return PclZip::errorCode(); } // ----- Read each entry $v_header_list = array(); $j_start = 0; for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) { // ----- Read the file header $v_header_list[$v_nb_extracted] = array(); if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) { // ----- Close the zip file $this->privCloseFd(); return $v_result; } // ----- Store the index $v_header_list[$v_nb_extracted]['index'] = $i; // ----- Look for the specific extract rules $v_found = false; // ----- Look for extract by name rule if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { // ----- Look if the filename is in the list for ($j=0; ($j<sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_found); $j++) { // ----- Look for a directory if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") { // ----- Look if the directory is in the filename path if ( (strlen($v_header_list[$v_nb_extracted]['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { $v_found = true; } elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) { $v_found = true; } } // ----- Look for a filename elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { $v_found = true; } } } // ----- Look for extract by ereg rule // ereg() is deprecated with PHP 5.3 /* else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { $v_found = true; } } */ // ----- Look for extract by preg rule else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { $v_found = true; } } // ----- Look for extract by index rule else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { // ----- Look if the index is in the list for ($j=$j_start; ($j<sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_found); $j++) { if (($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { $v_found = true; } if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { $j_start = $j+1; } if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { break; } } } else { $v_found = true; } // ----- Look for deletion if ($v_found) { unset($v_header_list[$v_nb_extracted]); } else { $v_nb_extracted++; } } // ----- Look if something need to be deleted if ($v_nb_extracted > 0) { // ----- Creates a temporay file $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; // ----- Creates a temporary zip archive $v_temp_zip = new PclZip($v_zip_temp_name); // ----- Open the temporary zip file in write mode if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) { $this->privCloseFd(); // ----- Return return $v_result; } // ----- Look which file need to be kept for ($i=0; $i<sizeof($v_header_list); $i++) { // ----- Calculate the position of the header @rewind($this->zip_fd); if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) { // ----- Close the zip file $this->privCloseFd(); $v_temp_zip->privCloseFd(); @unlink($v_zip_temp_name); // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return return PclZip::errorCode(); } // ----- Read the file header $v_local_header = array(); if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) { // ----- Close the zip file $this->privCloseFd(); $v_temp_zip->privCloseFd(); @unlink($v_zip_temp_name); // ----- Return return $v_result; } // ----- Check that local file header is same as central file header if ($this->privCheckFileHeaders($v_local_header, $v_header_list[$i]) != 1) { // TBC } unset($v_local_header); // ----- Write the file header if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) { // ----- Close the zip file $this->privCloseFd(); $v_temp_zip->privCloseFd(); @unlink($v_zip_temp_name); // ----- Return return $v_result; } // ----- Read/write the data block if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) { // ----- Close the zip file $this->privCloseFd(); $v_temp_zip->privCloseFd(); @unlink($v_zip_temp_name); // ----- Return return $v_result; } } // ----- Store the offset of the central dir $v_offset = @ftell($v_temp_zip->zip_fd); // ----- Re-Create the Central Dir files header for ($i=0; $i<sizeof($v_header_list); $i++) { // ----- Create the file header if (($v_result = $v_temp_zip->privWriteCentralFileHeader($v_header_list[$i])) != 1) { $v_temp_zip->privCloseFd(); $this->privCloseFd(); @unlink($v_zip_temp_name); // ----- Return return $v_result; } // ----- Transform the header to a 'usable' info $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); } // ----- Zip file comment $v_comment = ''; if (isset($p_options[PCLZIP_OPT_COMMENT])) { $v_comment = $p_options[PCLZIP_OPT_COMMENT]; } // ----- Calculate the size of the central header $v_size = @ftell($v_temp_zip->zip_fd)-$v_offset; // ----- Create the central dir footer if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) { // ----- Reset the file list unset($v_header_list); $v_temp_zip->privCloseFd(); $this->privCloseFd(); @unlink($v_zip_temp_name); // ----- Return return $v_result; } // ----- Close $v_temp_zip->privCloseFd(); $this->privCloseFd(); // ----- Delete the zip file // TBC : I should test the result ... @unlink($this->zipname); // ----- Rename the temporary file // TBC : I should test the result ... //@rename($v_zip_temp_name, $this->zipname); PclZipUtilRename($v_zip_temp_name, $this->zipname); // ----- Destroy the temporary archive unset($v_temp_zip); } // ----- Remove every files : reset the file else if ($v_central_dir['entries'] != 0) { $this->privCloseFd(); if (($v_result = $this->privOpenFd('wb')) != 1) { return $v_result; } if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) { return $v_result; } $this->privCloseFd(); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privDirCheck() // Description : // Check if a directory exists, if not it creates it and all the parents directory // which may be useful. // Parameters : // $p_dir : Directory path to check. // Return Values : // 1 : OK // -1 : Unable to create directory // -------------------------------------------------------------------------------- function privDirCheck($p_dir, $p_is_dir=false) { $v_result = 1; // ----- Remove the final '/' if (($p_is_dir) && (substr($p_dir, -1)=='/')) { $p_dir = substr($p_dir, 0, strlen($p_dir)-1); } // ----- Check the directory availability if ((is_dir($p_dir)) || ($p_dir == "")) { return 1; } // ----- Extract parent directory $p_parent_dir = dirname($p_dir); // ----- Just a check if ($p_parent_dir != $p_dir) { // ----- Look for parent directory if ($p_parent_dir != "") { if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) { return $v_result; } } } // ----- Create the directory if (!@mkdir($p_dir, 0777)) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'"); // ----- Return return PclZip::errorCode(); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privMerge() // Description : // If $p_archive_to_add does not exist, the function exit with a success result. // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privMerge(&$p_archive_to_add) { $v_result=1; // ----- Look if the archive_to_add exists if (!is_file($p_archive_to_add->zipname)) { // ----- Nothing to merge, so merge is a success $v_result = 1; // ----- Return return $v_result; } // ----- Look if the archive exists if (!is_file($this->zipname)) { // ----- Do a duplicate $v_result = $this->privDuplicate($p_archive_to_add->zipname); // ----- Return return $v_result; } // ----- Open the zip file if (($v_result=$this->privOpenFd('rb')) != 1) { // ----- Return return $v_result; } // ----- Read the central directory informations $v_central_dir = array(); if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { $this->privCloseFd(); return $v_result; } // ----- Go to beginning of File @rewind($this->zip_fd); // ----- Open the archive_to_add file if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1) { $this->privCloseFd(); // ----- Return return $v_result; } // ----- Read the central directory informations $v_central_dir_to_add = array(); if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) { $this->privCloseFd(); $p_archive_to_add->privCloseFd(); return $v_result; } // ----- Go to beginning of File @rewind($p_archive_to_add->zip_fd); // ----- Creates a temporay file $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; // ----- Open the temporary file in write mode if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) { $this->privCloseFd(); $p_archive_to_add->privCloseFd(); PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); // ----- Return return PclZip::errorCode(); } // ----- Copy the files from the archive to the temporary file // TBC : Here I should better append the file and go back to erase the central dir $v_size = $v_central_dir['offset']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = fread($this->zip_fd, $v_read_size); @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Copy the files from the archive_to_add into the temporary file $v_size = $v_central_dir_to_add['offset']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size); @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Store the offset of the central dir $v_offset = @ftell($v_zip_temp_fd); // ----- Copy the block of file headers from the old archive $v_size = $v_central_dir['size']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($this->zip_fd, $v_read_size); @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Copy the block of file headers from the archive_to_add $v_size = $v_central_dir_to_add['size']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size); @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Merge the file comments $v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment']; // ----- Calculate the size of the (new) central header $v_size = @ftell($v_zip_temp_fd)-$v_offset; // ----- Swap the file descriptor // Here is a trick : I swap the temporary fd with the zip fd, in order to use // the following methods on the temporary fil and not the real archive fd $v_swap = $this->zip_fd; $this->zip_fd = $v_zip_temp_fd; $v_zip_temp_fd = $v_swap; // ----- Create the central dir footer if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) { $this->privCloseFd(); $p_archive_to_add->privCloseFd(); @fclose($v_zip_temp_fd); $this->zip_fd = null; // ----- Reset the file list unset($v_header_list); // ----- Return return $v_result; } // ----- Swap back the file descriptor $v_swap = $this->zip_fd; $this->zip_fd = $v_zip_temp_fd; $v_zip_temp_fd = $v_swap; // ----- Close $this->privCloseFd(); $p_archive_to_add->privCloseFd(); // ----- Close the temporary file @fclose($v_zip_temp_fd); // ----- Delete the zip file // TBC : I should test the result ... @unlink($this->zipname); // ----- Rename the temporary file // TBC : I should test the result ... //@rename($v_zip_temp_name, $this->zipname); PclZipUtilRename($v_zip_temp_name, $this->zipname); // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privDuplicate() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privDuplicate($p_archive_filename) { $v_result=1; // ----- Look if the $p_archive_filename exists if (!is_file($p_archive_filename)) { // ----- Nothing to duplicate, so duplicate is a success. $v_result = 1; // ----- Return return $v_result; } // ----- Open the zip file if (($v_result=$this->privOpenFd('wb')) != 1) { // ----- Return return $v_result; } // ----- Open the temporary file in write mode if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) { $this->privCloseFd(); PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode'); // ----- Return return PclZip::errorCode(); } // ----- Copy the files from the archive to the temporary file // TBC : Here I should better append the file and go back to erase the central dir $v_size = filesize($p_archive_filename); while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = fread($v_zip_temp_fd, $v_read_size); @fwrite($this->zip_fd, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Close $this->privCloseFd(); // ----- Close the temporary file @fclose($v_zip_temp_fd); // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privErrorLog() // Description : // Parameters : // -------------------------------------------------------------------------------- function privErrorLog($p_error_code=0, $p_error_string='') { if (PCLZIP_ERROR_EXTERNAL == 1) { PclError($p_error_code, $p_error_string); } else { $this->error_code = $p_error_code; $this->error_string = $p_error_string; } } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privErrorReset() // Description : // Parameters : // -------------------------------------------------------------------------------- function privErrorReset() { if (PCLZIP_ERROR_EXTERNAL == 1) { PclErrorReset(); } else { $this->error_code = 0; $this->error_string = ''; } } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privDisableMagicQuotes() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privDisableMagicQuotes() { $v_result=1; // ----- Look if function exists if ( (!function_exists("get_magic_quotes_runtime")) || (!function_exists("set_magic_quotes_runtime"))) { return $v_result; } // ----- Look if already done if ($this->magic_quotes_status != -1) { return $v_result; } // ----- Get and memorize the magic_quote value $this->magic_quotes_status = @get_magic_quotes_runtime(); // ----- Disable magic_quotes if ($this->magic_quotes_status == 1) { @set_magic_quotes_runtime(0); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privSwapBackMagicQuotes() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privSwapBackMagicQuotes() { $v_result=1; // ----- Look if function exists if ( (!function_exists("get_magic_quotes_runtime")) || (!function_exists("set_magic_quotes_runtime"))) { return $v_result; } // ----- Look if something to do if ($this->magic_quotes_status != -1) { return $v_result; } // ----- Swap back magic_quotes if ($this->magic_quotes_status == 1) { @set_magic_quotes_runtime($this->magic_quotes_status); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- } // End of class // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : PclZipUtilPathReduction() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function PclZipUtilPathReduction($p_dir) { $v_result = ""; // ----- Look for not empty path if ($p_dir != "") { // ----- Explode path by directory names $v_list = explode("/", $p_dir); // ----- Study directories from last to first $v_skip = 0; for ($i=sizeof($v_list)-1; $i>=0; $i--) { // ----- Look for current path if ($v_list[$i] == ".") { // ----- Ignore this directory // Should be the first $i=0, but no check is done } else if ($v_list[$i] == "..") { $v_skip++; } else if ($v_list[$i] == "") { // ----- First '/' i.e. root slash if ($i == 0) { $v_result = "/".$v_result; if ($v_skip > 0) { // ----- It is an invalid path, so the path is not modified // TBC $v_result = $p_dir; $v_skip = 0; } } // ----- Last '/' i.e. indicates a directory else if ($i == (sizeof($v_list)-1)) { $v_result = $v_list[$i]; } // ----- Double '/' inside the path else { // ----- Ignore only the double '//' in path, // but not the first and last '/' } } else { // ----- Look for item to skip if ($v_skip > 0) { $v_skip--; } else { $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:""); } } } // ----- Look for skip if ($v_skip > 0) { while ($v_skip > 0) { $v_result = '../'.$v_result; $v_skip--; } } } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : PclZipUtilPathInclusion() // Description : // This function indicates if the path $p_path is under the $p_dir tree. Or, // said in an other way, if the file or sub-dir $p_path is inside the dir // $p_dir. // The function indicates also if the path is exactly the same as the dir. // This function supports path with duplicated '/' like '//', but does not // support '.' or '..' statements. // Parameters : // Return Values : // 0 if $p_path is not inside directory $p_dir // 1 if $p_path is inside directory $p_dir // 2 if $p_path is exactly the same as $p_dir // -------------------------------------------------------------------------------- function PclZipUtilPathInclusion($p_dir, $p_path) { $v_result = 1; // ----- Look for path beginning by ./ if ( ($p_dir == '.') || ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) { $p_dir = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_dir, 1); } if ( ($p_path == '.') || ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) { $p_path = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_path, 1); } // ----- Explode dir and path by directory separator $v_list_dir = explode("/", $p_dir); $v_list_dir_size = sizeof($v_list_dir); $v_list_path = explode("/", $p_path); $v_list_path_size = sizeof($v_list_path); // ----- Study directories paths $i = 0; $j = 0; while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) { // ----- Look for empty dir (path reduction) if ($v_list_dir[$i] == '') { $i++; continue; } if ($v_list_path[$j] == '') { $j++; continue; } // ----- Compare the items if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ( $v_list_path[$j] != '')) { $v_result = 0; } // ----- Next items $i++; $j++; } // ----- Look if everything seems to be the same if ($v_result) { // ----- Skip all the empty items while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++; while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++; if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { // ----- There are exactly the same $v_result = 2; } else if ($i < $v_list_dir_size) { // ----- The path is shorter than the dir $v_result = 0; } } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : PclZipUtilCopyBlock() // Description : // Parameters : // $p_mode : read/write compression mode // 0 : src & dest normal // 1 : src gzip, dest normal // 2 : src normal, dest gzip // 3 : src & dest gzip // Return Values : // -------------------------------------------------------------------------------- function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0) { $v_result = 1; if ($p_mode==0) { while ($p_size != 0) { $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($p_src, $v_read_size); @fwrite($p_dest, $v_buffer, $v_read_size); $p_size -= $v_read_size; } } else if ($p_mode==1) { while ($p_size != 0) { $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @gzread($p_src, $v_read_size); @fwrite($p_dest, $v_buffer, $v_read_size); $p_size -= $v_read_size; } } else if ($p_mode==2) { while ($p_size != 0) { $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($p_src, $v_read_size); @gzwrite($p_dest, $v_buffer, $v_read_size); $p_size -= $v_read_size; } } else if ($p_mode==3) { while ($p_size != 0) { $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @gzread($p_src, $v_read_size); @gzwrite($p_dest, $v_buffer, $v_read_size); $p_size -= $v_read_size; } } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : PclZipUtilRename() // Description : // This function tries to do a simple rename() function. If it fails, it // tries to copy the $p_src file in a new $p_dest file and then unlink the // first one. // Parameters : // $p_src : Old filename // $p_dest : New filename // Return Values : // 1 on success, 0 on failure. // -------------------------------------------------------------------------------- function PclZipUtilRename($p_src, $p_dest) { $v_result = 1; // ----- Try to rename the files if (!@rename($p_src, $p_dest)) { // ----- Try to copy & unlink the src if (!@copy($p_src, $p_dest)) { $v_result = 0; } else if (!@unlink($p_src)) { $v_result = 0; } } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : PclZipUtilOptionText() // Description : // Translate option value in text. Mainly for debug purpose. // Parameters : // $p_option : the option value. // Return Values : // The option text value. // -------------------------------------------------------------------------------- function PclZipUtilOptionText($p_option) { $v_list = get_defined_constants(); for (reset($v_list); $v_key = key($v_list); next($v_list)) { $v_prefix = substr($v_key, 0, 10); if (( ($v_prefix == 'PCLZIP_OPT') || ($v_prefix == 'PCLZIP_CB_') || ($v_prefix == 'PCLZIP_ATT')) && ($v_list[$v_key] == $p_option)) { return $v_key; } } $v_result = 'Unknown'; return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : PclZipUtilTranslateWinPath() // Description : // Translate windows path by replacing '\' by '/' and optionally removing // drive letter. // Parameters : // $p_path : path to translate. // $p_remove_disk_letter : true | false // Return Values : // The path translated. // -------------------------------------------------------------------------------- function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true) { if (stristr(php_uname(), 'windows')) { // ----- Look for potential disk letter if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) { $p_path = substr($p_path, $v_position+1); } // ----- Change potential windows directory separator if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { $p_path = strtr($p_path, '\\', '/'); } } return $p_path; } // -------------------------------------------------------------------------------- ?>
zyblog
trunk/zyblog/wp-admin/includes/class-pclzip.php
PHP
asf20
195,618
<?php /** * WordPress Theme Install Administration API * * @package WordPress * @subpackage Administration */ $themes_allowedtags = array('a' => array('href' => array(), 'title' => array(), 'target' => array()), 'abbr' => array('title' => array()), 'acronym' => array('title' => array()), 'code' => array(), 'pre' => array(), 'em' => array(), 'strong' => array(), 'div' => array(), 'p' => array(), 'ul' => array(), 'ol' => array(), 'li' => array(), 'h1' => array(), 'h2' => array(), 'h3' => array(), 'h4' => array(), 'h5' => array(), 'h6' => array(), 'img' => array('src' => array(), 'class' => array(), 'alt' => array()) ); $theme_field_defaults = array( 'description' => true, 'sections' => false, 'tested' => true, 'requires' => true, 'rating' => true, 'downloaded' => true, 'downloadlink' => true, 'last_updated' => true, 'homepage' => true, 'tags' => true, 'num_ratings' => true ); /** * Retrieve list of WordPress theme features (aka theme tags) * * @since 2.8.0 * * @deprecated since 3.1.0 Use get_theme_feature_list() instead. * * @return array */ function install_themes_feature_list( ) { if ( !$cache = get_transient( 'wporg_theme_feature_list' ) ) set_transient( 'wporg_theme_feature_list', array( ), 10800); if ( $cache ) return $cache; $feature_list = themes_api( 'feature_list', array( ) ); if ( is_wp_error( $feature_list ) ) return $features; set_transient( 'wporg_theme_feature_list', $feature_list, 10800 ); return $feature_list; } /** * Display search form for searching themes. * * @since 2.8.0 */ function install_theme_search_form( $type_selector = true ) { $type = isset( $_REQUEST['type'] ) ? stripslashes( $_REQUEST['type'] ) : 'term'; $term = isset( $_REQUEST['s'] ) ? stripslashes( $_REQUEST['s'] ) : ''; if ( ! $type_selector ) echo '<p class="install-help">' . __( 'Search for themes by keyword.' ) . '</p>'; ?> <form id="search-themes" method="get" action=""> <input type="hidden" name="tab" value="search" /> <?php if ( $type_selector ) : ?> <label class="screen-reader-text" for="typeselector"><?php _e('Type of search'); ?></label> <select name="type" id="typeselector"> <option value="term" <?php selected('term', $type) ?>><?php _e('Keyword'); ?></option> <option value="author" <?php selected('author', $type) ?>><?php _e('Author'); ?></option> <option value="tag" <?php selected('tag', $type) ?>><?php _ex('Tag', 'Theme Installer'); ?></option> </select> <label class="screen-reader-text" for="s"><?php switch ( $type ) { case 'term': _e( 'Search by keyword' ); break; case 'author': _e( 'Search by author' ); break; case 'tag': _e( 'Search by tag' ); break; } ?></label> <?php else : ?> <label class="screen-reader-text" for="s"><?php _e('Search by keyword'); ?></label> <?php endif; ?> <input type="search" name="s" id="s" size="30" value="<?php echo esc_attr($term) ?>" autofocus="autofocus" /> <?php submit_button( __( 'Search' ), 'button', 'search', false ); ?> </form> <?php } /** * Display tags filter for themes. * * @since 2.8.0 */ function install_themes_dashboard() { install_theme_search_form( false ); ?> <h4><?php _e('Feature Filter') ?></h4> <p class="install-help"><?php _e( 'Find a theme based on specific features.' ); ?></p> <form method="get" action=""> <input type="hidden" name="tab" value="search" /> <?php $feature_list = get_theme_feature_list( ); echo '<div class="feature-filter">'; foreach ( (array) $feature_list as $feature_name => $features ) { $feature_name = esc_html( $feature_name ); echo '<div class="feature-name">' . $feature_name . '</div>'; echo '<ol class="feature-group">'; foreach ( $features as $feature => $feature_name ) { $feature_name = esc_html( $feature_name ); $feature = esc_attr($feature); ?> <li> <input type="checkbox" name="features[]" id="feature-id-<?php echo $feature; ?>" value="<?php echo $feature; ?>" /> <label for="feature-id-<?php echo $feature; ?>"><?php echo $feature_name; ?></label> </li> <?php } ?> </ol> <br class="clear" /> <?php } ?> </div> <br class="clear" /> <?php submit_button( __( 'Find Themes' ), 'button', 'search' ); ?> </form> <?php } add_action('install_themes_dashboard', 'install_themes_dashboard'); function install_themes_upload($page = 1) { ?> <h4><?php _e('Install a theme in .zip format'); ?></h4> <p class="install-help"><?php _e('If you have a theme in a .zip format, you may install it by uploading it here.'); ?></p> <form method="post" enctype="multipart/form-data" class="wp-upload-form" action="<?php echo self_admin_url('update.php?action=upload-theme'); ?>"> <?php wp_nonce_field( 'theme-upload'); ?> <input type="file" name="themezip" /> <?php submit_button( __( 'Install Now' ), 'button', 'install-theme-submit', false ); ?> </form> <?php } add_action('install_themes_upload', 'install_themes_upload', 10, 1); /** * Prints a theme on the Install Themes pages. * * @deprecated 3.4.0 */ function display_theme( $theme ) { _deprecated_function( __FUNCTION__, '3.4' ); global $wp_list_table; return $wp_list_table->single_row( $theme ); } /** * Display theme content based on theme list. * * @since 2.8.0 */ function display_themes() { global $wp_list_table; $wp_list_table->display(); } add_action('install_themes_search', 'display_themes'); add_action('install_themes_featured', 'display_themes'); add_action('install_themes_new', 'display_themes'); add_action('install_themes_updated', 'display_themes'); /** * Display theme information in dialog box form. * * @since 2.8.0 */ function install_theme_information() { global $tab, $themes_allowedtags, $wp_list_table; $theme = themes_api( 'theme_information', array( 'slug' => stripslashes( $_REQUEST['theme'] ) ) ); if ( is_wp_error( $theme ) ) wp_die( $theme ); iframe_header( __('Theme Install') ); $wp_list_table->theme_installer_single( $theme ); iframe_footer(); exit; } add_action('install_themes_pre_theme-information', 'install_theme_information');
zyblog
trunk/zyblog/wp-admin/includes/theme-install.php
PHP
asf20
6,007
<?php /** * Terms List Table class. * * @package WordPress * @subpackage List_Table * @since 3.1.0 * @access private */ class WP_Terms_List_Table extends WP_List_Table { var $callback_args; function __construct( $args = array() ) { global $post_type, $taxonomy, $action, $tax; parent::__construct( array( 'plural' => 'tags', 'singular' => 'tag', 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); $action = $this->screen->action; $post_type = $this->screen->post_type; $taxonomy = $this->screen->taxonomy; if ( empty( $taxonomy ) ) $taxonomy = 'post_tag'; if ( ! taxonomy_exists( $taxonomy ) ) wp_die( __( 'Invalid taxonomy' ) ); $tax = get_taxonomy( $taxonomy ); // @todo Still needed? Maybe just the show_ui part. if ( empty( $post_type ) || !in_array( $post_type, get_post_types( array( 'show_ui' => true ) ) ) ) $post_type = 'post'; } function ajax_user_can() { return current_user_can( get_taxonomy( $this->screen->taxonomy )->cap->manage_terms ); } function prepare_items() { $tags_per_page = $this->get_items_per_page( 'edit_' . $this->screen->taxonomy . '_per_page' ); if ( 'post_tag' == $this->screen->taxonomy ) { $tags_per_page = apply_filters( 'edit_tags_per_page', $tags_per_page ); $tags_per_page = apply_filters( 'tagsperpage', $tags_per_page ); // Old filter } elseif ( 'category' == $this->screen->taxonomy ) { $tags_per_page = apply_filters( 'edit_categories_per_page', $tags_per_page ); // Old filter } $search = !empty( $_REQUEST['s'] ) ? trim( stripslashes( $_REQUEST['s'] ) ) : ''; $args = array( 'search' => $search, 'page' => $this->get_pagenum(), 'number' => $tags_per_page, ); if ( !empty( $_REQUEST['orderby'] ) ) $args['orderby'] = trim( stripslashes( $_REQUEST['orderby'] ) ); if ( !empty( $_REQUEST['order'] ) ) $args['order'] = trim( stripslashes( $_REQUEST['order'] ) ); $this->callback_args = $args; $this->set_pagination_args( array( 'total_items' => wp_count_terms( $this->screen->taxonomy, compact( 'search' ) ), 'per_page' => $tags_per_page, ) ); } function has_items() { // todo: populate $this->items in prepare_items() return true; } function get_bulk_actions() { $actions = array(); $actions['delete'] = __( 'Delete' ); return $actions; } function current_action() { if ( isset( $_REQUEST['action'] ) && isset( $_REQUEST['delete_tags'] ) && ( 'delete' == $_REQUEST['action'] || 'delete' == $_REQUEST['action2'] ) ) return 'bulk-delete'; return parent::current_action(); } function get_columns() { $columns = array( 'cb' => '<input type="checkbox" />', 'name' => _x( 'Name', 'term name' ), 'description' => __( 'Description' ), 'slug' => __( 'Slug' ), ); if ( 'link_category' == $this->screen->taxonomy ) { $columns['links'] = __( 'Links' ); } else { $post_type_object = get_post_type_object( $this->screen->post_type ); $columns['posts'] = $post_type_object ? $post_type_object->labels->name : __( 'Posts' ); } return $columns; } function get_sortable_columns() { return array( 'name' => 'name', 'description' => 'description', 'slug' => 'slug', 'posts' => 'count', 'links' => 'count' ); } function display_rows_or_placeholder() { $taxonomy = $this->screen->taxonomy; $args = wp_parse_args( $this->callback_args, array( 'page' => 1, 'number' => 20, 'search' => '', 'hide_empty' => 0 ) ); extract( $args, EXTR_SKIP ); $args['offset'] = $offset = ( $page - 1 ) * $number; // convert it to table rows $out = ''; $count = 0; $terms = array(); if ( is_taxonomy_hierarchical( $taxonomy ) && !isset( $orderby ) ) { // We'll need the full set of terms then. $args['number'] = $args['offset'] = 0; $terms = get_terms( $taxonomy, $args ); if ( !empty( $search ) ) // Ignore children on searches. $children = array(); else $children = _get_term_hierarchy( $taxonomy ); // Some funky recursion to get the job done( Paging & parents mainly ) is contained within, Skip it for non-hierarchical taxonomies for performance sake $out .= $this->_rows( $taxonomy, $terms, $children, $offset, $number, $count ); } else { $terms = get_terms( $taxonomy, $args ); foreach ( $terms as $term ) $out .= $this->single_row( $term, 0, $taxonomy ); $count = $number; // Only displaying a single page. } if ( empty( $terms ) ) { list( $columns, $hidden ) = $this->get_column_info(); echo '<tr class="no-items"><td class="colspanchange" colspan="' . $this->get_column_count() . '">'; $this->no_items(); echo '</td></tr>'; } else { echo $out; } } function _rows( $taxonomy, $terms, &$children, $start = 0, $per_page = 20, &$count, $parent = 0, $level = 0 ) { $end = $start + $per_page; $output = ''; foreach ( $terms as $key => $term ) { if ( $count >= $end ) break; if ( $term->parent != $parent && empty( $_REQUEST['s'] ) ) continue; // If the page starts in a subtree, print the parents. if ( $count == $start && $term->parent > 0 && empty( $_REQUEST['s'] ) ) { $my_parents = $parent_ids = array(); $p = $term->parent; while ( $p ) { $my_parent = get_term( $p, $taxonomy ); $my_parents[] = $my_parent; $p = $my_parent->parent; if ( in_array( $p, $parent_ids ) ) // Prevent parent loops. break; $parent_ids[] = $p; } unset( $parent_ids ); $num_parents = count( $my_parents ); while ( $my_parent = array_pop( $my_parents ) ) { $output .= "\t" . $this->single_row( $my_parent, $level - $num_parents, $taxonomy ); $num_parents--; } } if ( $count >= $start ) $output .= "\t" . $this->single_row( $term, $level, $taxonomy ); ++$count; unset( $terms[$key] ); if ( isset( $children[$term->term_id] ) && empty( $_REQUEST['s'] ) ) $output .= $this->_rows( $taxonomy, $terms, $children, $start, $per_page, $count, $term->term_id, $level + 1 ); } return $output; } function single_row( $tag, $level = 0 ) { static $row_class = ''; $row_class = ( $row_class == '' ? ' class="alternate"' : '' ); $this->level = $level; echo '<tr id="tag-' . $tag->term_id . '"' . $row_class . '>'; echo $this->single_row_columns( $tag ); echo '</tr>'; } function column_cb( $tag ) { $default_term = get_option( 'default_' . $this->screen->taxonomy ); if ( current_user_can( get_taxonomy( $this->screen->taxonomy )->cap->delete_terms ) && $tag->term_id != $default_term ) return '<label class="screen-reader-text" for="cb-select-' . $tag->term_id . '">' . sprintf( __( 'Select %s' ), $tag->name ) . '</label>' . '<input type="checkbox" name="delete_tags[]" value="' . $tag->term_id . '" id="cb-select-' . $tag->term_id . '" />'; return '&nbsp;'; } function column_name( $tag ) { $taxonomy = $this->screen->taxonomy; $tax = get_taxonomy( $taxonomy ); $default_term = get_option( 'default_' . $taxonomy ); $pad = str_repeat( '&#8212; ', max( 0, $this->level ) ); $name = apply_filters( 'term_name', $pad . ' ' . $tag->name, $tag ); $qe_data = get_term( $tag->term_id, $taxonomy, OBJECT, 'edit' ); $edit_link = esc_url( get_edit_term_link( $tag->term_id, $taxonomy, $this->screen->post_type ) ); $out = '<strong><a class="row-title" href="' . $edit_link . '" title="' . esc_attr( sprintf( __( 'Edit &#8220;%s&#8221;' ), $name ) ) . '">' . $name . '</a></strong><br />'; $actions = array(); if ( current_user_can( $tax->cap->edit_terms ) ) { $actions['edit'] = '<a href="' . $edit_link . '">' . __( 'Edit' ) . '</a>'; $actions['inline hide-if-no-js'] = '<a href="#" class="editinline">' . __( 'Quick&nbsp;Edit' ) . '</a>'; } if ( current_user_can( $tax->cap->delete_terms ) && $tag->term_id != $default_term ) $actions['delete'] = "<a class='delete-tag' href='" . wp_nonce_url( "edit-tags.php?action=delete&amp;taxonomy=$taxonomy&amp;tag_ID=$tag->term_id", 'delete-tag_' . $tag->term_id ) . "'>" . __( 'Delete' ) . "</a>"; $actions['view'] = '<a href="' . get_term_link( $tag ) . '">' . __( 'View' ) . '</a>'; $actions = apply_filters( 'tag_row_actions', $actions, $tag ); $actions = apply_filters( "{$taxonomy}_row_actions", $actions, $tag ); $out .= $this->row_actions( $actions ); $out .= '<div class="hidden" id="inline_' . $qe_data->term_id . '">'; $out .= '<div class="name">' . $qe_data->name . '</div>'; $out .= '<div class="slug">' . apply_filters( 'editable_slug', $qe_data->slug ) . '</div>'; $out .= '<div class="parent">' . $qe_data->parent . '</div></div>'; return $out; } function column_description( $tag ) { return $tag->description; } function column_slug( $tag ) { return apply_filters( 'editable_slug', $tag->slug ); } function column_posts( $tag ) { $count = number_format_i18n( $tag->count ); $tax = get_taxonomy( $this->screen->taxonomy ); $ptype_object = get_post_type_object( $this->screen->post_type ); if ( ! $ptype_object->show_ui ) return $count; if ( $tax->query_var ) { $args = array( $tax->query_var => $tag->slug ); } else { $args = array( 'taxonomy' => $tax->name, 'term' => $tag->slug ); } if ( 'post' != $this->screen->post_type ) $args['post_type'] = $this->screen->post_type; if ( 'attachment' == $this->screen->post_type ) return "<a href='" . esc_url ( add_query_arg( $args, 'upload.php' ) ) . "'>$count</a>"; return "<a href='" . esc_url ( add_query_arg( $args, 'edit.php' ) ) . "'>$count</a>"; } function column_links( $tag ) { $count = number_format_i18n( $tag->count ); if ( $count ) $count = "<a href='link-manager.php?cat_id=$tag->term_id'>$count</a>"; return $count; } function column_default( $tag, $column_name ) { return apply_filters( "manage_{$this->screen->taxonomy}_custom_column", '', $column_name, $tag->term_id ); } /** * Outputs the hidden row displayed when inline editing * * @since 3.1.0 */ function inline_edit() { $tax = get_taxonomy( $this->screen->taxonomy ); if ( ! current_user_can( $tax->cap->edit_terms ) ) return; ?> <form method="get" action=""><table style="display: none"><tbody id="inlineedit"> <tr id="inline-edit" class="inline-edit-row" style="display: none"><td colspan="<?php echo $this->get_column_count(); ?>" class="colspanchange"> <fieldset><div class="inline-edit-col"> <h4><?php _e( 'Quick Edit' ); ?></h4> <label> <span class="title"><?php _ex( 'Name', 'term name' ); ?></span> <span class="input-text-wrap"><input type="text" name="name" class="ptitle" value="" /></span> </label> <?php if ( !global_terms_enabled() ) { ?> <label> <span class="title"><?php _e( 'Slug' ); ?></span> <span class="input-text-wrap"><input type="text" name="slug" class="ptitle" value="" /></span> </label> <?php } ?> </div></fieldset> <?php $core_columns = array( 'cb' => true, 'description' => true, 'name' => true, 'slug' => true, 'posts' => true ); list( $columns ) = $this->get_column_info(); foreach ( $columns as $column_name => $column_display_name ) { if ( isset( $core_columns[$column_name] ) ) continue; do_action( 'quick_edit_custom_box', $column_name, 'edit-tags', $this->screen->taxonomy ); } ?> <p class="inline-edit-save submit"> <a accesskey="c" href="#inline-edit" title="<?php esc_attr_e( 'Cancel' ); ?>" class="cancel button-secondary alignleft"><?php _e( 'Cancel' ); ?></a> <?php $update_text = $tax->labels->update_item; ?> <a accesskey="s" href="#inline-edit" title="<?php echo esc_attr( $update_text ); ?>" class="save button-primary alignright"><?php echo $update_text; ?></a> <span class="spinner"></span> <span class="error" style="display:none;"></span> <?php wp_nonce_field( 'taxinlineeditnonce', '_inline_edit', false ); ?> <input type="hidden" name="taxonomy" value="<?php echo esc_attr( $this->screen->taxonomy ); ?>" /> <input type="hidden" name="post_type" value="<?php echo esc_attr( $this->screen->post_type ); ?>" /> <br class="clear" /> </p> </td></tr> </tbody></table></form> <?php } }
zyblog
trunk/zyblog/wp-admin/includes/class-wp-terms-list-table.php
PHP
asf20
12,205
<?php /** * Deprecated admin functions from past WordPress versions. You shouldn't use these * functions and look for the alternatives instead. The functions will be removed * in a later version. * * @package WordPress * @subpackage Deprecated */ /* * Deprecated functions come here to die. */ /** * @since 2.1 * @deprecated 2.1 * @deprecated Use wp_editor(). * @see wp_editor() */ function tinymce_include() { _deprecated_function( __FUNCTION__, '2.1', 'wp_editor()' ); wp_tiny_mce(); } /** * Unused Admin function. * * @since 2.0 * @deprecated 2.5 * */ function documentation_link() { _deprecated_function( __FUNCTION__, '2.5' ); return; } /** * Calculates the new dimensions for a downsampled image. * * @since 2.0.0 * @deprecated 3.0.0 * @deprecated Use wp_constrain_dimensions() * @see wp_constrain_dimensions() * * @param int $width Current width of the image * @param int $height Current height of the image * @param int $wmax Maximum wanted width * @param int $hmax Maximum wanted height * @return array Shrunk dimensions (width, height). */ function wp_shrink_dimensions( $width, $height, $wmax = 128, $hmax = 96 ) { _deprecated_function( __FUNCTION__, '3.0', 'wp_constrain_dimensions()' ); return wp_constrain_dimensions( $width, $height, $wmax, $hmax ); } /** * Calculated the new dimensions for a downsampled image. * * @since 2.0.0 * @deprecated 3.5.0 * @deprecated Use wp_constrain_dimensions() * @see wp_constrain_dimensions() * * @param int $width Current width of the image * @param int $height Current height of the image * @return array Shrunk dimensions (width, height). */ function get_udims( $width, $height ) { _deprecated_function( __FUNCTION__, '3.5', 'wp_constrain_dimensions()' ); return wp_constrain_dimensions( $width, $height, 128, 96 ); } /** * {@internal Missing Short Description}} * * @since 0.71 * @deprecated 2.6.0 * @deprecated Use wp_category_checklist() * @see wp_category_checklist() * * @param unknown_type $default * @param unknown_type $parent * @param unknown_type $popular_ids */ function dropdown_categories( $default = 0, $parent = 0, $popular_ids = array() ) { _deprecated_function( __FUNCTION__, '2.6', 'wp_category_checklist()' ); global $post_ID; wp_category_checklist( $post_ID ); } /** * {@internal Missing Short Description}} * * @since 2.1.0 * @deprecated 2.6.0 * @deprecated Use wp_link_category_checklist() * @see wp_link_category_checklist() * * @param unknown_type $default */ function dropdown_link_categories( $default = 0 ) { _deprecated_function( __FUNCTION__, '2.6', 'wp_link_category_checklist()' ); global $link_id; wp_link_category_checklist( $link_id ); } /** * {@internal Missing Short Description}} * * @since 1.2.0 * @deprecated 3.0.0 * @deprecated Use wp_dropdown_categories() * @see wp_dropdown_categories() * * @param unknown_type $currentcat * @param unknown_type $currentparent * @param unknown_type $parent * @param unknown_type $level * @param unknown_type $categories * @return unknown */ function wp_dropdown_cats( $currentcat = 0, $currentparent = 0, $parent = 0, $level = 0, $categories = 0 ) { _deprecated_function( __FUNCTION__, '3.0', 'wp_dropdown_categories()' ); if (!$categories ) $categories = get_categories( array('hide_empty' => 0) ); if ( $categories ) { foreach ( $categories as $category ) { if ( $currentcat != $category->term_id && $parent == $category->parent) { $pad = str_repeat( '&#8211; ', $level ); $category->name = esc_html( $category->name ); echo "\n\t<option value='$category->term_id'"; if ( $currentparent == $category->term_id ) echo " selected='selected'"; echo ">$pad$category->name</option>"; wp_dropdown_cats( $currentcat, $currentparent, $category->term_id, $level +1, $categories ); } } } else { return false; } } /** * Register a setting and its sanitization callback * * @since 2.7.0 * @deprecated 3.0.0 * @deprecated Use register_setting() * @see register_setting() * * @param string $option_group A settings group name. Should correspond to a whitelisted option key name. * Default whitelisted option key names include "general," "discussion," and "reading," among others. * @param string $option_name The name of an option to sanitize and save. * @param unknown_type $sanitize_callback A callback function that sanitizes the option's value. * @return unknown */ function add_option_update_handler( $option_group, $option_name, $sanitize_callback = '' ) { _deprecated_function( __FUNCTION__, '3.0', 'register_setting()' ); return register_setting( $option_group, $option_name, $sanitize_callback ); } /** * Unregister a setting * * @since 2.7.0 * @deprecated 3.0.0 * @deprecated Use unregister_setting() * @see unregister_setting() * * @param unknown_type $option_group * @param unknown_type $option_name * @param unknown_type $sanitize_callback * @return unknown */ function remove_option_update_handler( $option_group, $option_name, $sanitize_callback = '' ) { _deprecated_function( __FUNCTION__, '3.0', 'unregister_setting()' ); return unregister_setting( $option_group, $option_name, $sanitize_callback ); } /** * Determines the language to use for CodePress syntax highlighting. * * @since 2.8.0 * @deprecated 3.0.0 * * @param string $filename **/ function codepress_get_lang( $filename ) { _deprecated_function( __FUNCTION__, '3.0' ); return; } /** * Adds Javascript required to make CodePress work on the theme/plugin editors. * * @since 2.8.0 * @deprecated 3.0.0 **/ function codepress_footer_js() { _deprecated_function( __FUNCTION__, '3.0' ); return; } /** * Determine whether to use CodePress. * * @since 2.8 * @deprecated 3.0.0 **/ function use_codepress() { _deprecated_function( __FUNCTION__, '3.0' ); return; } /** * @deprecated 3.1.0 * * @return array List of user IDs. */ function get_author_user_ids() { _deprecated_function( __FUNCTION__, '3.1', 'get_users()' ); global $wpdb; if ( !is_multisite() ) $level_key = $wpdb->get_blog_prefix() . 'user_level'; else $level_key = $wpdb->get_blog_prefix() . 'capabilities'; // wpmu site admins don't have user_levels return $wpdb->get_col( $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s AND meta_value != '0'", $level_key) ); } /** * @deprecated 3.1.0 * * @param int $user_id User ID. * @return array|bool List of editable authors. False if no editable users. */ function get_editable_authors( $user_id ) { _deprecated_function( __FUNCTION__, '3.1', 'get_users()' ); global $wpdb; $editable = get_editable_user_ids( $user_id ); if ( !$editable ) { return false; } else { $editable = join(',', $editable); $authors = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($editable) ORDER BY display_name" ); } return apply_filters('get_editable_authors', $authors); } /** * @deprecated 3.1.0 * * @param int $user_id User ID. * @param bool $exclude_zeros Optional, default is true. Whether to exclude zeros. * @return unknown */ function get_editable_user_ids( $user_id, $exclude_zeros = true, $post_type = 'post' ) { _deprecated_function( __FUNCTION__, '3.1', 'get_users()' ); global $wpdb; if ( ! $user = get_userdata( $user_id ) ) return array(); $post_type_obj = get_post_type_object($post_type); if ( ! $user->has_cap($post_type_obj->cap->edit_others_posts) ) { if ( $user->has_cap($post_type_obj->cap->edit_posts) || ! $exclude_zeros ) return array($user->ID); else return array(); } if ( !is_multisite() ) $level_key = $wpdb->get_blog_prefix() . 'user_level'; else $level_key = $wpdb->get_blog_prefix() . 'capabilities'; // wpmu site admins don't have user_levels $query = $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s", $level_key); if ( $exclude_zeros ) $query .= " AND meta_value != '0'"; return $wpdb->get_col( $query ); } /** * @deprecated 3.1.0 */ function get_nonauthor_user_ids() { _deprecated_function( __FUNCTION__, '3.1', 'get_users()' ); global $wpdb; if ( !is_multisite() ) $level_key = $wpdb->get_blog_prefix() . 'user_level'; else $level_key = $wpdb->get_blog_prefix() . 'capabilities'; // wpmu site admins don't have user_levels return $wpdb->get_col( $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s AND meta_value = '0'", $level_key) ); } if ( !class_exists('WP_User_Search') ) : /** * WordPress User Search class. * * @since 2.1.0 * @deprecated 3.1.0 */ class WP_User_Search { /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var unknown_type */ var $results; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var unknown_type */ var $search_term; /** * Page number. * * @since 2.1.0 * @access private * @var int */ var $page; /** * Role name that users have. * * @since 2.5.0 * @access private * @var string */ var $role; /** * Raw page number. * * @since 2.1.0 * @access private * @var int|bool */ var $raw_page; /** * Amount of users to display per page. * * @since 2.1.0 * @access public * @var int */ var $users_per_page = 50; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var unknown_type */ var $first_user; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var int */ var $last_user; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var string */ var $query_limit; /** * {@internal Missing Description}} * * @since 3.0.0 * @access private * @var string */ var $query_orderby; /** * {@internal Missing Description}} * * @since 3.0.0 * @access private * @var string */ var $query_from; /** * {@internal Missing Description}} * * @since 3.0.0 * @access private * @var string */ var $query_where; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var int */ var $total_users_for_query = 0; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var bool */ var $too_many_total_users = false; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var unknown_type */ var $search_errors; /** * {@internal Missing Description}} * * @since 2.7.0 * @access private * @var unknown_type */ var $paging_text; /** * PHP4 Constructor - Sets up the object properties. * * @since 2.1.0 * * @param string $search_term Search terms string. * @param int $page Optional. Page ID. * @param string $role Role name. * @return WP_User_Search */ function WP_User_Search ($search_term = '', $page = '', $role = '') { _deprecated_function( __FUNCTION__, '3.1', 'WP_User_Query' ); $this->search_term = stripslashes( $search_term ); $this->raw_page = ( '' == $page ) ? false : (int) $page; $this->page = (int) ( '' == $page ) ? 1 : $page; $this->role = $role; $this->prepare_query(); $this->query(); $this->prepare_vars_for_template_usage(); $this->do_paging(); } /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 2.1.0 * @access public */ function prepare_query() { global $wpdb; $this->first_user = ($this->page - 1) * $this->users_per_page; $this->query_limit = $wpdb->prepare(" LIMIT %d, %d", $this->first_user, $this->users_per_page); $this->query_orderby = ' ORDER BY user_login'; $search_sql = ''; if ( $this->search_term ) { $searches = array(); $search_sql = 'AND ('; foreach ( array('user_login', 'user_nicename', 'user_email', 'user_url', 'display_name') as $col ) $searches[] = $wpdb->prepare( $col . ' LIKE %s', '%' . like_escape($this->search_term) . '%' ); $search_sql .= implode(' OR ', $searches); $search_sql .= ')'; } $this->query_from = " FROM $wpdb->users"; $this->query_where = " WHERE 1=1 $search_sql"; if ( $this->role ) { $this->query_from .= " INNER JOIN $wpdb->usermeta ON $wpdb->users.ID = $wpdb->usermeta.user_id"; $this->query_where .= $wpdb->prepare(" AND $wpdb->usermeta.meta_key = '{$wpdb->prefix}capabilities' AND $wpdb->usermeta.meta_value LIKE %s", '%' . $this->role . '%'); } elseif ( is_multisite() ) { $level_key = $wpdb->prefix . 'capabilities'; // wpmu site admins don't have user_levels $this->query_from .= ", $wpdb->usermeta"; $this->query_where .= " AND $wpdb->users.ID = $wpdb->usermeta.user_id AND meta_key = '{$level_key}'"; } do_action_ref_array( 'pre_user_search', array( &$this ) ); } /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 2.1.0 * @access public */ function query() { global $wpdb; $this->results = $wpdb->get_col("SELECT DISTINCT($wpdb->users.ID)" . $this->query_from . $this->query_where . $this->query_orderby . $this->query_limit); if ( $this->results ) $this->total_users_for_query = $wpdb->get_var("SELECT COUNT(DISTINCT($wpdb->users.ID))" . $this->query_from . $this->query_where); // no limit else $this->search_errors = new WP_Error('no_matching_users_found', __('No matching users were found!')); } /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 2.1.0 * @access public */ function prepare_vars_for_template_usage() { $this->search_term = stripslashes($this->search_term); // done with DB, from now on we want slashes gone } /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 2.1.0 * @access public */ function do_paging() { if ( $this->total_users_for_query > $this->users_per_page ) { // have to page the results $args = array(); if( ! empty($this->search_term) ) $args['usersearch'] = urlencode($this->search_term); if( ! empty($this->role) ) $args['role'] = urlencode($this->role); $this->paging_text = paginate_links( array( 'total' => ceil($this->total_users_for_query / $this->users_per_page), 'current' => $this->page, 'base' => 'users.php?%_%', 'format' => 'userspage=%#%', 'add_args' => $args ) ); if ( $this->paging_text ) { $this->paging_text = sprintf( '<span class="displaying-num">' . __( 'Displaying %s&#8211;%s of %s' ) . '</span>%s', number_format_i18n( ( $this->page - 1 ) * $this->users_per_page + 1 ), number_format_i18n( min( $this->page * $this->users_per_page, $this->total_users_for_query ) ), number_format_i18n( $this->total_users_for_query ), $this->paging_text ); } } } /** * {@internal Missing Short Description}} * * {@internal Missing Long Description}} * * @since 2.1.0 * @access public * * @return unknown */ function get_results() { return (array) $this->results; } /** * Displaying paging text. * * @see do_paging() Builds paging text. * * @since 2.1.0 * @access public */ function page_links() { echo $this->paging_text; } /** * Whether paging is enabled. * * @see do_paging() Builds paging text. * * @since 2.1.0 * @access public * * @return bool */ function results_are_paged() { if ( $this->paging_text ) return true; return false; } /** * Whether there are search terms. * * @since 2.1.0 * @access public * * @return bool */ function is_search() { if ( $this->search_term ) return true; return false; } } endif; /** * Retrieve editable posts from other users. * * @deprecated 3.1.0 * * @param int $user_id User ID to not retrieve posts from. * @param string $type Optional, defaults to 'any'. Post type to retrieve, can be 'draft' or 'pending'. * @return array List of posts from others. */ function get_others_unpublished_posts($user_id, $type='any') { _deprecated_function( __FUNCTION__, '3.1' ); global $wpdb; $editable = get_editable_user_ids( $user_id ); if ( in_array($type, array('draft', 'pending')) ) $type_sql = " post_status = '$type' "; else $type_sql = " ( post_status = 'draft' OR post_status = 'pending' ) "; $dir = ( 'pending' == $type ) ? 'ASC' : 'DESC'; if ( !$editable ) { $other_unpubs = ''; } else { $editable = join(',', $editable); $other_unpubs = $wpdb->get_results( $wpdb->prepare("SELECT ID, post_title, post_author FROM $wpdb->posts WHERE post_type = 'post' AND $type_sql AND post_author IN ($editable) AND post_author != %d ORDER BY post_modified $dir", $user_id) ); } return apply_filters('get_others_drafts', $other_unpubs); } /** * Retrieve drafts from other users. * * @deprecated 3.1.0 * * @param int $user_id User ID. * @return array List of drafts from other users. */ function get_others_drafts($user_id) { _deprecated_function( __FUNCTION__, '3.1' ); return get_others_unpublished_posts($user_id, 'draft'); } /** * Retrieve pending review posts from other users. * * @deprecated 3.1.0 * * @param int $user_id User ID. * @return array List of posts with pending review post type from other users. */ function get_others_pending($user_id) { _deprecated_function( __FUNCTION__, '3.1' ); return get_others_unpublished_posts($user_id, 'pending'); } /** * Output the QuickPress dashboard widget. * * @since 3.0.0 * @deprecated 3.2.0 * @deprecated Use wp_dashboard_quick_press() * @see wp_dashboard_quick_press() */ function wp_dashboard_quick_press_output() { _deprecated_function( __FUNCTION__, '3.2', 'wp_dashboard_quick_press()' ); wp_dashboard_quick_press(); } /** * @since 2.7.0 * @deprecated 3.3 * @deprecated Use wp_editor() * @see wp_editor() */ function wp_tiny_mce( $teeny = false, $settings = false ) { _deprecated_function( __FUNCTION__, '3.3', 'wp_editor()' ); static $num = 1; if ( ! class_exists('_WP_Editors' ) ) require_once( ABSPATH . WPINC . '/class-wp-editor.php' ); $editor_id = 'content' . $num++; $set = array( 'teeny' => $teeny, 'tinymce' => $settings ? $settings : true, 'quicktags' => false ); $set = _WP_Editors::parse_settings($editor_id, $set); _WP_Editors::editor_settings($editor_id, $set); } /** * @deprecated 3.3.0 * @deprecated Use wp_editor() * @see wp_editor() */ function wp_preload_dialogs() { _deprecated_function( __FUNCTION__, '3.3', 'wp_editor()' ); } /** * @deprecated 3.3.0 * @deprecated Use wp_editor() * @see wp_editor() */ function wp_print_editor_js() { _deprecated_function( __FUNCTION__, '3.3', 'wp_editor()' ); } /** * @deprecated 3.3.0 * @deprecated Use wp_editor() * @see wp_editor() */ function wp_quicktags() { _deprecated_function( __FUNCTION__, '3.3', 'wp_editor()' ); } /** * Returns the screen layout options. * * @since 2.8.0 * @deprecated 3.3.0 * @deprecated Use $current_screen->render_screen_layout() * @see WP_Screen::render_screen_layout() */ function screen_layout( $screen ) { _deprecated_function( __FUNCTION__, '3.3', '$current_screen->render_screen_layout()' ); $current_screen = get_current_screen(); if ( ! $current_screen ) return ''; ob_start(); $current_screen->render_screen_layout(); return ob_get_clean(); } /** * Returns the screen's per-page options. * * @since 2.8.0 * @deprecated 3.3.0 * @deprecated Use $current_screen->render_per_page_options() * @see WP_Screen::render_per_page_options() */ function screen_options( $screen ) { _deprecated_function( __FUNCTION__, '3.3', '$current_screen->render_per_page_options()' ); $current_screen = get_current_screen(); if ( ! $current_screen ) return ''; ob_start(); $current_screen->render_per_page_options(); return ob_get_clean(); } /** * Renders the screen's help. * * @since 2.7.0 * @deprecated 3.3.0 * @deprecated Use $current_screen->render_screen_meta() * @see WP_Screen::render_screen_meta() */ function screen_meta( $screen ) { $current_screen = get_current_screen(); $current_screen->render_screen_meta(); } /** * Favorite actions were deprecated in version 3.2. Use the admin bar instead. * * @since 2.7.0 * @deprecated 3.2.0 */ function favorite_actions() { _deprecated_function( __FUNCTION__, '3.2', 'WP_Admin_Bar' ); } function media_upload_image() { __deprecated_function( __FUNCTION__, '3.3', 'wp_media_upload_handler()' ); return wp_media_upload_handler(); } function media_upload_audio() { __deprecated_function( __FUNCTION__, '3.3', 'wp_media_upload_handler()' ); return wp_media_upload_handler(); } function media_upload_video() { __deprecated_function( __FUNCTION__, '3.3', 'wp_media_upload_handler()' ); return wp_media_upload_handler(); } function media_upload_file() { __deprecated_function( __FUNCTION__, '3.3', 'wp_media_upload_handler()' ); return wp_media_upload_handler(); } function type_url_form_image() { __deprecated_function( __FUNCTION__, '3.3', "wp_media_insert_url_form('image')" ); return wp_media_insert_url_form( 'image' ); } function type_url_form_audio() { __deprecated_function( __FUNCTION__, '3.3', "wp_media_insert_url_form('audio')" ); return wp_media_insert_url_form( 'audio' ); } function type_url_form_video() { __deprecated_function( __FUNCTION__, '3.3', "wp_media_insert_url_form('video')" ); return wp_media_insert_url_form( 'video' ); } function type_url_form_file() { __deprecated_function( __FUNCTION__, '3.3', "wp_media_insert_url_form('file')" ); return wp_media_insert_url_form( 'file' ); } /** * Add contextual help text for a page. * * Creates an 'Overview' help tab. * * @since 2.7.0 * @deprecated 3.3.0 * @deprecated Use get_current_screen()->add_help_tab() * @see WP_Screen * * @param string $screen The handle for the screen to add help to. This is usually the hook name returned by the add_*_page() functions. * @param string $help The content of an 'Overview' help tab. */ function add_contextual_help( $screen, $help ) { _deprecated_function( __FUNCTION__, '3.3', 'get_current_screen()->add_help_tab()' ); if ( is_string( $screen ) ) $screen = convert_to_screen( $screen ); WP_Screen::add_old_compat_help( $screen, $help ); } /** * Get the allowed themes for the current blog. * * @since 3.0.0 * @deprecated 3.4.0 * @deprecated Use wp_get_themes() * @see wp_get_themes() * * @return array $themes Array of allowed themes. */ function get_allowed_themes() { _deprecated_function( __FUNCTION__, '3.4', "wp_get_themes( array( 'allowed' => true ) )" ); $themes = wp_get_themes( array( 'allowed' => true ) ); $wp_themes = array(); foreach ( $themes as $theme ) { $wp_themes[ $theme->get('Name') ] = $theme; } return $wp_themes; } /** * {@internal Missing Short Description}} * * @since 1.5.0 * * @return unknown */ function get_broken_themes() { _deprecated_function( __FUNCTION__, '3.4', "wp_get_themes( array( 'errors' => true )" ); $themes = wp_get_themes( array( 'errors' => true ) ); $broken = array(); foreach ( $themes as $theme ) { $name = $theme->get('Name'); $broken[ $name ] = array( 'Name' => $name, 'Title' => $name, 'Description' => $theme->errors()->get_error_message(), ); } return $broken; } /** * {@internal Missing Short Description}} * * @since 2.0.0 * * @return unknown */ function current_theme_info() { _deprecated_function( __FUNCTION__, '3.4', 'wp_get_theme()' ); return wp_get_theme(); } /** * This was once used to display an 'Insert into Post' button. Now it is deprecated and stubbed. * * @deprecated 3.5.0 */ function _insert_into_post_button( $type ) { _deprecated_function( __FUNCTION__, '3.5' ); } /** * This was once used to display a media button. Now it is deprecated and stubbed. * * @deprecated 3.5.0 */ function _media_button($title, $icon, $type, $id) { _deprecated_function( __FUNCTION__, '3.5' ); } /** * Get an existing post and format it for editing. * * @since 2.0.0 * @deprecated 3.5.0 * * @param int $id * @return object */ function get_post_to_edit( $id ) { _deprecated_function( __FUNCTION__, '3.5', 'get_post()' ); return get_post( $id, OBJECT, 'edit' ); } /** * Get the default page information to use. * * @since 2.5.0 * @deprecated 3.5.0 * @deprecated Use get_default_post_to_edit() * * @return WP_Post Post object containing all the default post data as attributes */ function get_default_page_to_edit() { _deprecated_function( __FUNCTION__, '3.5', "get_default_post_to_edit( 'page' )" ); $page = get_default_post_to_edit(); $page->post_type = 'page'; return $page; } /** * This was once used to create a thumbnail from an Image given a maximum side size. * * @since 1.2.0 * @deprecated 3.5.0 * @deprecated Use image_resize() * @see image_resize() * * @param mixed $file Filename of the original image, Or attachment id. * @param int $max_side Maximum length of a single side for the thumbnail. * @param mixed $deprecated Never used. * @return string Thumbnail path on success, Error string on failure. */ function wp_create_thumbnail( $file, $max_side, $deprecated = '' ) { _deprecated_function( __FUNCTION__, '3.5', 'image_resize' ); return apply_filters( 'wp_create_thumbnail', image_resize( $file, $max_side, $max_side ) ); }
zyblog
trunk/zyblog/wp-admin/includes/deprecated.php
PHP
asf20
25,245
<?php /** * WordPress FTP Filesystem. * * @package WordPress * @subpackage Filesystem */ /** * WordPress Filesystem Class for implementing FTP. * * @since 2.5 * @package WordPress * @subpackage Filesystem * @uses WP_Filesystem_Base Extends class */ class WP_Filesystem_FTPext extends WP_Filesystem_Base { var $link; var $errors = null; var $options = array(); function __construct($opt='') { $this->method = 'ftpext'; $this->errors = new WP_Error(); //Check if possible to use ftp functions. if ( ! extension_loaded('ftp') ) { $this->errors->add('no_ftp_ext', __('The ftp PHP extension is not available')); return false; } // Set defaults: //This Class uses the timeout on a per-connection basis, Others use it on a per-action basis. if ( ! defined('FS_TIMEOUT') ) define('FS_TIMEOUT', 240); if ( empty($opt['port']) ) $this->options['port'] = 21; else $this->options['port'] = $opt['port']; if ( empty($opt['hostname']) ) $this->errors->add('empty_hostname', __('FTP hostname is required')); else $this->options['hostname'] = $opt['hostname']; if ( ! empty($opt['base']) ) $this->wp_base = $opt['base']; // Check if the options provided are OK. if ( empty($opt['username']) ) $this->errors->add('empty_username', __('FTP username is required')); else $this->options['username'] = $opt['username']; if ( empty($opt['password']) ) $this->errors->add('empty_password', __('FTP password is required')); else $this->options['password'] = $opt['password']; $this->options['ssl'] = false; if ( isset($opt['connection_type']) && 'ftps' == $opt['connection_type'] ) $this->options['ssl'] = true; } function connect() { if ( isset($this->options['ssl']) && $this->options['ssl'] && function_exists('ftp_ssl_connect') ) $this->link = @ftp_ssl_connect($this->options['hostname'], $this->options['port'], FS_CONNECT_TIMEOUT); else $this->link = @ftp_connect($this->options['hostname'], $this->options['port'], FS_CONNECT_TIMEOUT); if ( ! $this->link ) { $this->errors->add('connect', sprintf(__('Failed to connect to FTP Server %1$s:%2$s'), $this->options['hostname'], $this->options['port'])); return false; } if ( ! @ftp_login($this->link,$this->options['username'], $this->options['password']) ) { $this->errors->add('auth', sprintf(__('Username/Password incorrect for %s'), $this->options['username'])); return false; } //Set the Connection to use Passive FTP @ftp_pasv( $this->link, true ); if ( @ftp_get_option($this->link, FTP_TIMEOUT_SEC) < FS_TIMEOUT ) @ftp_set_option($this->link, FTP_TIMEOUT_SEC, FS_TIMEOUT); return true; } function get_contents($file, $type = '', $resumepos = 0 ) { if ( empty($type) ) $type = FTP_BINARY; $tempfile = wp_tempnam($file); $temp = fopen($tempfile, 'w+'); if ( ! $temp ) return false; if ( ! @ftp_fget($this->link, $temp, $file, $type, $resumepos) ) return false; fseek($temp, 0); //Skip back to the start of the file being written to $contents = ''; while ( ! feof($temp) ) $contents .= fread($temp, 8192); fclose($temp); unlink($tempfile); return $contents; } function get_contents_array($file) { return explode("\n", $this->get_contents($file)); } function put_contents($file, $contents, $mode = false ) { $tempfile = wp_tempnam($file); $temp = fopen($tempfile, 'w+'); if ( ! $temp ) return false; fwrite($temp, $contents); fseek($temp, 0); //Skip back to the start of the file being written to $type = $this->is_binary($contents) ? FTP_BINARY : FTP_ASCII; $ret = @ftp_fput($this->link, $file, $temp, $type); fclose($temp); unlink($tempfile); $this->chmod($file, $mode); return $ret; } function cwd() { $cwd = @ftp_pwd($this->link); if ( $cwd ) $cwd = trailingslashit($cwd); return $cwd; } function chdir($dir) { return @ftp_chdir($this->link, $dir); } function chgrp($file, $group, $recursive = false ) { return false; } function chmod($file, $mode = false, $recursive = false) { if ( ! $mode ) { if ( $this->is_file($file) ) $mode = FS_CHMOD_FILE; elseif ( $this->is_dir($file) ) $mode = FS_CHMOD_DIR; else return false; } // chmod any sub-objects if recursive. if ( $recursive && $this->is_dir($file) ) { $filelist = $this->dirlist($file); foreach ( (array)$filelist as $filename => $filemeta ) $this->chmod($file . '/' . $filename, $mode, $recursive); } // chmod the file or directory if ( ! function_exists('ftp_chmod') ) return (bool)@ftp_site($this->link, sprintf('CHMOD %o %s', $mode, $file)); return (bool)@ftp_chmod($this->link, $mode, $file); } function chown($file, $owner, $recursive = false ) { return false; } function owner($file) { $dir = $this->dirlist($file); return $dir[$file]['owner']; } function getchmod($file) { $dir = $this->dirlist($file); return $dir[$file]['permsn']; } function group($file) { $dir = $this->dirlist($file); return $dir[$file]['group']; } function copy($source, $destination, $overwrite = false, $mode = false) { if ( ! $overwrite && $this->exists($destination) ) return false; $content = $this->get_contents($source); if ( false === $content) return false; return $this->put_contents($destination, $content, $mode); } function move($source, $destination, $overwrite = false) { return ftp_rename($this->link, $source, $destination); } function delete($file, $recursive = false, $type = false) { if ( empty($file) ) return false; if ( 'f' == $type || $this->is_file($file) ) return @ftp_delete($this->link, $file); if ( !$recursive ) return @ftp_rmdir($this->link, $file); $filelist = $this->dirlist( trailingslashit($file) ); if ( !empty($filelist) ) foreach ( $filelist as $delete_file ) $this->delete( trailingslashit($file) . $delete_file['name'], $recursive, $delete_file['type'] ); return @ftp_rmdir($this->link, $file); } function exists($file) { $list = @ftp_nlist($this->link, $file); return !empty($list); //empty list = no file, so invert. } function is_file($file) { return $this->exists($file) && !$this->is_dir($file); } function is_dir($path) { $cwd = $this->cwd(); $result = @ftp_chdir($this->link, trailingslashit($path) ); if ( $result && $path == $this->cwd() || $this->cwd() != $cwd ) { @ftp_chdir($this->link, $cwd); return true; } return false; } function is_readable($file) { //Get dir list, Check if the file is readable by the current user?? return true; } function is_writable($file) { //Get dir list, Check if the file is writable by the current user?? return true; } function atime($file) { return false; } function mtime($file) { return ftp_mdtm($this->link, $file); } function size($file) { return ftp_size($this->link, $file); } function touch($file, $time = 0, $atime = 0) { return false; } function mkdir($path, $chmod = false, $chown = false, $chgrp = false) { $path = untrailingslashit($path); if ( empty($path) ) return false; if ( !@ftp_mkdir($this->link, $path) ) return false; $this->chmod($path, $chmod); if ( $chown ) $this->chown($path, $chown); if ( $chgrp ) $this->chgrp($path, $chgrp); return true; } function rmdir($path, $recursive = false) { return $this->delete($path, $recursive); } function parselisting($line) { static $is_windows; if ( is_null($is_windows) ) $is_windows = stripos( ftp_systype($this->link), 'win') !== false; if ( $is_windows && preg_match('/([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|<DIR>) +(.+)/', $line, $lucifer) ) { $b = array(); if ( $lucifer[3] < 70 ) $lucifer[3] +=2000; else $lucifer[3] += 1900; // 4digit year fix $b['isdir'] = ( $lucifer[7] == '<DIR>'); if ( $b['isdir'] ) $b['type'] = 'd'; else $b['type'] = 'f'; $b['size'] = $lucifer[7]; $b['month'] = $lucifer[1]; $b['day'] = $lucifer[2]; $b['year'] = $lucifer[3]; $b['hour'] = $lucifer[4]; $b['minute'] = $lucifer[5]; $b['time'] = @mktime($lucifer[4] + (strcasecmp($lucifer[6], "PM") == 0 ? 12 : 0), $lucifer[5], 0, $lucifer[1], $lucifer[2], $lucifer[3]); $b['am/pm'] = $lucifer[6]; $b['name'] = $lucifer[8]; } elseif ( !$is_windows && $lucifer = preg_split('/[ ]/', $line, 9, PREG_SPLIT_NO_EMPTY)) { //echo $line."\n"; $lcount = count($lucifer); if ( $lcount < 8 ) return ''; $b = array(); $b['isdir'] = $lucifer[0]{0} === 'd'; $b['islink'] = $lucifer[0]{0} === 'l'; if ( $b['isdir'] ) $b['type'] = 'd'; elseif ( $b['islink'] ) $b['type'] = 'l'; else $b['type'] = 'f'; $b['perms'] = $lucifer[0]; $b['number'] = $lucifer[1]; $b['owner'] = $lucifer[2]; $b['group'] = $lucifer[3]; $b['size'] = $lucifer[4]; if ( $lcount == 8 ) { sscanf($lucifer[5], '%d-%d-%d', $b['year'], $b['month'], $b['day']); sscanf($lucifer[6], '%d:%d', $b['hour'], $b['minute']); $b['time'] = @mktime($b['hour'], $b['minute'], 0, $b['month'], $b['day'], $b['year']); $b['name'] = $lucifer[7]; } else { $b['month'] = $lucifer[5]; $b['day'] = $lucifer[6]; if ( preg_match('/([0-9]{2}):([0-9]{2})/', $lucifer[7], $l2) ) { $b['year'] = date("Y"); $b['hour'] = $l2[1]; $b['minute'] = $l2[2]; } else { $b['year'] = $lucifer[7]; $b['hour'] = 0; $b['minute'] = 0; } $b['time'] = strtotime( sprintf('%d %s %d %02d:%02d', $b['day'], $b['month'], $b['year'], $b['hour'], $b['minute']) ); $b['name'] = $lucifer[8]; } } // Replace symlinks formatted as "source -> target" with just the source name if ( $b['islink'] ) $b['name'] = preg_replace( '/(\s*->\s*.*)$/', '', $b['name'] ); return $b; } function dirlist($path = '.', $include_hidden = true, $recursive = false) { if ( $this->is_file($path) ) { $limit_file = basename($path); $path = dirname($path) . '/'; } else { $limit_file = false; } $pwd = @ftp_pwd($this->link); if ( ! @ftp_chdir($this->link, $path) ) // Cant change to folder = folder doesn't exist return false; $list = @ftp_rawlist($this->link, '-a', false); @ftp_chdir($this->link, $pwd); if ( empty($list) ) // Empty array = non-existent folder (real folder will show . at least) return false; $dirlist = array(); foreach ( $list as $k => $v ) { $entry = $this->parselisting($v); if ( empty($entry) ) continue; if ( '.' == $entry['name'] || '..' == $entry['name'] ) continue; if ( ! $include_hidden && '.' == $entry['name'][0] ) continue; if ( $limit_file && $entry['name'] != $limit_file) continue; $dirlist[ $entry['name'] ] = $entry; } $ret = array(); foreach ( (array)$dirlist as $struc ) { if ( 'd' == $struc['type'] ) { if ( $recursive ) $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $include_hidden, $recursive); else $struc['files'] = array(); } $ret[ $struc['name'] ] = $struc; } return $ret; } function __destruct() { if ( $this->link ) ftp_close($this->link); } }
zyblog
trunk/zyblog/wp-admin/includes/class-wp-filesystem-ftpext.php
PHP
asf20
11,140
<?php /** * Multisite Users List Table class. * * @package WordPress * @subpackage List_Table * @since 3.1.0 * @access private */ class WP_MS_Users_List_Table extends WP_List_Table { function ajax_user_can() { return current_user_can( 'manage_network_users' ); } function prepare_items() { global $usersearch, $role, $wpdb, $mode; $usersearch = isset( $_REQUEST['s'] ) ? $_REQUEST['s'] : ''; $users_per_page = $this->get_items_per_page( 'users_network_per_page' ); $role = isset( $_REQUEST['role'] ) ? $_REQUEST['role'] : ''; $paged = $this->get_pagenum(); $args = array( 'number' => $users_per_page, 'offset' => ( $paged-1 ) * $users_per_page, 'search' => $usersearch, 'blog_id' => 0, 'fields' => 'all_with_meta' ); if ( wp_is_large_network( 'users' ) ) $args['search'] = ltrim( $args['search'], '*' ); if ( $role == 'super' ) { $logins = implode( "', '", get_super_admins() ); $args['include'] = $wpdb->get_col( "SELECT ID FROM $wpdb->users WHERE user_login IN ('$logins')" ); } // If the network is large and a search is not being performed, show only the latest users with no paging in order // to avoid expensive count queries. if ( !$usersearch && wp_is_large_network( 'users' ) ) { if ( !isset($_REQUEST['orderby']) ) $_GET['orderby'] = $_REQUEST['orderby'] = 'id'; if ( !isset($_REQUEST['order']) ) $_GET['order'] = $_REQUEST['order'] = 'DESC'; $args['count_total'] = false; } if ( isset( $_REQUEST['orderby'] ) ) $args['orderby'] = $_REQUEST['orderby']; if ( isset( $_REQUEST['order'] ) ) $args['order'] = $_REQUEST['order']; $mode = empty( $_REQUEST['mode'] ) ? 'list' : $_REQUEST['mode']; // Query the user IDs for this page $wp_user_search = new WP_User_Query( $args ); $this->items = $wp_user_search->get_results(); $this->set_pagination_args( array( 'total_items' => $wp_user_search->get_total(), 'per_page' => $users_per_page, ) ); } function get_bulk_actions() { $actions = array(); if ( current_user_can( 'delete_users' ) ) $actions['delete'] = __( 'Delete' ); $actions['spam'] = _x( 'Mark as Spam', 'user' ); $actions['notspam'] = _x( 'Not Spam', 'user' ); return $actions; } function no_items() { _e( 'No users found.' ); } function get_views() { global $wp_roles, $role; $total_users = get_user_count(); $super_admins = get_super_admins(); $total_admins = count( $super_admins ); $current_role = false; $class = $role != 'super' ? ' class="current"' : ''; $role_links = array(); $role_links['all'] = "<a href='" . network_admin_url('users.php') . "'$class>" . sprintf( _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $total_users, 'users' ), number_format_i18n( $total_users ) ) . '</a>'; $class = $role == 'super' ? ' class="current"' : ''; $role_links['super'] = "<a href='" . network_admin_url('users.php?role=super') . "'$class>" . sprintf( _n( 'Super Admin <span class="count">(%s)</span>', 'Super Admins <span class="count">(%s)</span>', $total_admins ), number_format_i18n( $total_admins ) ) . '</a>'; return $role_links; } function pagination( $which ) { global $mode; parent::pagination ( $which ); if ( 'top' == $which ) $this->view_switcher( $mode ); } function get_columns() { $users_columns = array( 'cb' => '<input type="checkbox" />', 'username' => __( 'Username' ), 'name' => __( 'Name' ), 'email' => __( 'E-mail' ), 'registered' => _x( 'Registered', 'user' ), 'blogs' => __( 'Sites' ) ); $users_columns = apply_filters( 'wpmu_users_columns', $users_columns ); return $users_columns; } function get_sortable_columns() { return array( 'username' => 'login', 'name' => 'name', 'email' => 'email', 'registered' => 'id', ); } function display_rows() { global $current_site, $mode; $alt = ''; $super_admins = get_super_admins(); foreach ( $this->items as $user ) { $alt = ( 'alternate' == $alt ) ? '' : 'alternate'; $status_list = array( 'spam' => 'site-spammed', 'deleted' => 'site-deleted' ); foreach ( $status_list as $status => $col ) { if ( $user->$status ) $alt .= " $col"; } ?> <tr class="<?php echo $alt; ?>"> <?php list( $columns, $hidden ) = $this->get_column_info(); foreach ( $columns as $column_name => $column_display_name ) : $class = "class='$column_name column-$column_name'"; $style = ''; if ( in_array( $column_name, $hidden ) ) $style = ' style="display:none;"'; $attributes = "$class$style"; switch ( $column_name ) { case 'cb': ?> <th scope="row" class="check-column"> <label class="screen-reader-text" for="blog_<?php echo $user->ID; ?>"><?php echo sprintf( __( 'Select %s' ), $user->user_login ); ?></label> <input type="checkbox" id="blog_<?php echo $user->ID ?>" name="allusers[]" value="<?php echo esc_attr( $user->ID ) ?>" /> </th> <?php break; case 'username': $avatar = get_avatar( $user->user_email, 32 ); $edit_link = esc_url( add_query_arg( 'wp_http_referer', urlencode( stripslashes( $_SERVER['REQUEST_URI'] ) ), get_edit_user_link( $user->ID ) ) ); echo "<td $attributes>"; ?> <?php echo $avatar; ?><strong><a href="<?php echo $edit_link; ?>" class="edit"><?php echo stripslashes( $user->user_login ); ?></a><?php if ( in_array( $user->user_login, $super_admins ) ) echo ' - ' . __( 'Super Admin' ); ?></strong> <br/> <?php $actions = array(); $actions['edit'] = '<a href="' . $edit_link . '">' . __( 'Edit' ) . '</a>'; if ( current_user_can( 'delete_user', $user->ID ) && ! in_array( $user->user_login, $super_admins ) ) { $actions['delete'] = '<a href="' . $delete = esc_url( network_admin_url( add_query_arg( '_wp_http_referer', urlencode( stripslashes( $_SERVER['REQUEST_URI'] ) ), wp_nonce_url( 'users.php', 'deleteuser' ) . '&amp;action=deleteuser&amp;id=' . $user->ID ) ) ) . '" class="delete">' . __( 'Delete' ) . '</a>'; } $actions = apply_filters( 'ms_user_row_actions', $actions, $user ); echo $this->row_actions( $actions ); ?> </td> <?php break; case 'name': echo "<td $attributes>$user->first_name $user->last_name</td>"; break; case 'email': echo "<td $attributes><a href='mailto:$user->user_email'>$user->user_email</a></td>"; break; case 'registered': if ( 'list' == $mode ) $date = 'Y/m/d'; else $date = 'Y/m/d \<\b\r \/\> g:i:s a'; echo "<td $attributes>" . mysql2date( $date, $user->user_registered ) . "</td>"; break; case 'blogs': $blogs = get_blogs_of_user( $user->ID, true ); echo "<td $attributes>"; if ( is_array( $blogs ) ) { foreach ( (array) $blogs as $key => $val ) { if ( !can_edit_network( $val->site_id ) ) continue; $path = ( $val->path == '/' ) ? '' : $val->path; echo '<span class="site-' . $val->site_id . '" >'; echo '<a href="'. esc_url( network_admin_url( 'site-info.php?id=' . $val->userblog_id ) ) .'">' . str_replace( '.' . $current_site->domain, '', $val->domain . $path ) . '</a>'; echo ' <small class="row-actions">'; $actions = array(); $actions['edit'] = '<a href="'. esc_url( network_admin_url( 'site-info.php?id=' . $val->userblog_id ) ) .'">' . __( 'Edit' ) . '</a>'; $class = ''; if ( get_blog_status( $val->userblog_id, 'spam' ) == 1 ) $class .= 'site-spammed '; if ( get_blog_status( $val->userblog_id, 'mature' ) == 1 ) $class .= 'site-mature '; if ( get_blog_status( $val->userblog_id, 'deleted' ) == 1 ) $class .= 'site-deleted '; if ( get_blog_status( $val->userblog_id, 'archived' ) == 1 ) $class .= 'site-archived '; $actions['view'] = '<a class="' . $class . '" href="' . esc_url( get_home_url( $val->userblog_id ) ) . '">' . __( 'View' ) . '</a>'; $actions = apply_filters('ms_user_list_site_actions', $actions, $val->userblog_id); $i=0; $action_count = count( $actions ); foreach ( $actions as $action => $link ) { ++$i; ( $i == $action_count ) ? $sep = '' : $sep = ' | '; echo "<span class='$action'>$link$sep</span>"; } echo '</small></span><br/>'; } } ?> </td> <?php break; default: echo "<td $attributes>"; echo apply_filters( 'manage_users_custom_column', '', $column_name, $user->ID ); echo "</td>"; break; } endforeach ?> </tr> <?php } } }
zyblog
trunk/zyblog/wp-admin/includes/class-wp-ms-users-list-table.php
PHP
asf20
8,813
<?php /** * Create HTML list of nav menu input items. * * @package WordPress * @since 3.0.0 * @uses Walker_Nav_Menu */ class Walker_Nav_Menu_Edit extends Walker_Nav_Menu { /** * @see Walker_Nav_Menu::start_lvl() * @since 3.0.0 * * @param string $output Passed by reference. */ function start_lvl(&$output) {} /** * @see Walker_Nav_Menu::end_lvl() * @since 3.0.0 * * @param string $output Passed by reference. */ function end_lvl(&$output) { } /** * @see Walker::start_el() * @since 3.0.0 * * @param string $output Passed by reference. Used to append additional content. * @param object $item Menu item data object. * @param int $depth Depth of menu item. Used for padding. * @param object $args */ function start_el(&$output, $item, $depth, $args) { global $_wp_nav_menu_max_depth; $_wp_nav_menu_max_depth = $depth > $_wp_nav_menu_max_depth ? $depth : $_wp_nav_menu_max_depth; $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; ob_start(); $item_id = esc_attr( $item->ID ); $removed_args = array( 'action', 'customlink-tab', 'edit-menu-item', 'menu-item', 'page-tab', '_wpnonce', ); $original_title = ''; if ( 'taxonomy' == $item->type ) { $original_title = get_term_field( 'name', $item->object_id, $item->object, 'raw' ); if ( is_wp_error( $original_title ) ) $original_title = false; } elseif ( 'post_type' == $item->type ) { $original_object = get_post( $item->object_id ); $original_title = $original_object->post_title; } $classes = array( 'menu-item menu-item-depth-' . $depth, 'menu-item-' . esc_attr( $item->object ), 'menu-item-edit-' . ( ( isset( $_GET['edit-menu-item'] ) && $item_id == $_GET['edit-menu-item'] ) ? 'active' : 'inactive'), ); $title = $item->title; if ( ! empty( $item->_invalid ) ) { $classes[] = 'menu-item-invalid'; /* translators: %s: title of menu item which is invalid */ $title = sprintf( __( '%s (Invalid)' ), $item->title ); } elseif ( isset( $item->post_status ) && 'draft' == $item->post_status ) { $classes[] = 'pending'; /* translators: %s: title of menu item in draft status */ $title = sprintf( __('%s (Pending)'), $item->title ); } $title = empty( $item->label ) ? $title : $item->label; ?> <li id="menu-item-<?php echo $item_id; ?>" class="<?php echo implode(' ', $classes ); ?>"> <dl class="menu-item-bar"> <dt class="menu-item-handle"> <span class="item-title"><?php echo esc_html( $title ); ?></span> <span class="item-controls"> <span class="item-type"><?php echo esc_html( $item->type_label ); ?></span> <span class="item-order hide-if-js"> <a href="<?php echo wp_nonce_url( add_query_arg( array( 'action' => 'move-up-menu-item', 'menu-item' => $item_id, ), remove_query_arg($removed_args, admin_url( 'nav-menus.php' ) ) ), 'move-menu_item' ); ?>" class="item-move-up"><abbr title="<?php esc_attr_e('Move up'); ?>">&#8593;</abbr></a> | <a href="<?php echo wp_nonce_url( add_query_arg( array( 'action' => 'move-down-menu-item', 'menu-item' => $item_id, ), remove_query_arg($removed_args, admin_url( 'nav-menus.php' ) ) ), 'move-menu_item' ); ?>" class="item-move-down"><abbr title="<?php esc_attr_e('Move down'); ?>">&#8595;</abbr></a> </span> <a class="item-edit" id="edit-<?php echo $item_id; ?>" title="<?php esc_attr_e('Edit Menu Item'); ?>" href="<?php echo ( isset( $_GET['edit-menu-item'] ) && $item_id == $_GET['edit-menu-item'] ) ? admin_url( 'nav-menus.php' ) : add_query_arg( 'edit-menu-item', $item_id, remove_query_arg( $removed_args, admin_url( 'nav-menus.php#menu-item-settings-' . $item_id ) ) ); ?>"><?php _e( 'Edit Menu Item' ); ?></a> </span> </dt> </dl> <div class="menu-item-settings" id="menu-item-settings-<?php echo $item_id; ?>"> <?php if( 'custom' == $item->type ) : ?> <p class="field-url description description-wide"> <label for="edit-menu-item-url-<?php echo $item_id; ?>"> <?php _e( 'URL' ); ?><br /> <input type="text" id="edit-menu-item-url-<?php echo $item_id; ?>" class="widefat code edit-menu-item-url" name="menu-item-url[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $item->url ); ?>" /> </label> </p> <?php endif; ?> <p class="description description-thin"> <label for="edit-menu-item-title-<?php echo $item_id; ?>"> <?php _e( 'Navigation Label' ); ?><br /> <input type="text" id="edit-menu-item-title-<?php echo $item_id; ?>" class="widefat edit-menu-item-title" name="menu-item-title[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $item->title ); ?>" /> </label> </p> <p class="description description-thin"> <label for="edit-menu-item-attr-title-<?php echo $item_id; ?>"> <?php _e( 'Title Attribute' ); ?><br /> <input type="text" id="edit-menu-item-attr-title-<?php echo $item_id; ?>" class="widefat edit-menu-item-attr-title" name="menu-item-attr-title[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $item->post_excerpt ); ?>" /> </label> </p> <p class="field-link-target description"> <label for="edit-menu-item-target-<?php echo $item_id; ?>"> <input type="checkbox" id="edit-menu-item-target-<?php echo $item_id; ?>" value="_blank" name="menu-item-target[<?php echo $item_id; ?>]"<?php checked( $item->target, '_blank' ); ?> /> <?php _e( 'Open link in a new window/tab' ); ?> </label> </p> <p class="field-css-classes description description-thin"> <label for="edit-menu-item-classes-<?php echo $item_id; ?>"> <?php _e( 'CSS Classes (optional)' ); ?><br /> <input type="text" id="edit-menu-item-classes-<?php echo $item_id; ?>" class="widefat code edit-menu-item-classes" name="menu-item-classes[<?php echo $item_id; ?>]" value="<?php echo esc_attr( implode(' ', $item->classes ) ); ?>" /> </label> </p> <p class="field-xfn description description-thin"> <label for="edit-menu-item-xfn-<?php echo $item_id; ?>"> <?php _e( 'Link Relationship (XFN)' ); ?><br /> <input type="text" id="edit-menu-item-xfn-<?php echo $item_id; ?>" class="widefat code edit-menu-item-xfn" name="menu-item-xfn[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $item->xfn ); ?>" /> </label> </p> <p class="field-description description description-wide"> <label for="edit-menu-item-description-<?php echo $item_id; ?>"> <?php _e( 'Description' ); ?><br /> <textarea id="edit-menu-item-description-<?php echo $item_id; ?>" class="widefat edit-menu-item-description" rows="3" cols="20" name="menu-item-description[<?php echo $item_id; ?>]"><?php echo esc_html( $item->description ); // textarea_escaped ?></textarea> <span class="description"><?php _e('The description will be displayed in the menu if the current theme supports it.'); ?></span> </label> </p> <div class="menu-item-actions description-wide submitbox"> <?php if( 'custom' != $item->type && $original_title !== false ) : ?> <p class="link-to-original"> <?php printf( __('Original: %s'), '<a href="' . esc_attr( $item->url ) . '">' . esc_html( $original_title ) . '</a>' ); ?> </p> <?php endif; ?> <a class="item-delete submitdelete deletion" id="delete-<?php echo $item_id; ?>" href="<?php echo wp_nonce_url( add_query_arg( array( 'action' => 'delete-menu-item', 'menu-item' => $item_id, ), remove_query_arg($removed_args, admin_url( 'nav-menus.php' ) ) ), 'delete-menu_item_' . $item_id ); ?>"><?php _e('Remove'); ?></a> <span class="meta-sep"> | </span> <a class="item-cancel submitcancel" id="cancel-<?php echo $item_id; ?>" href="<?php echo esc_url( add_query_arg( array('edit-menu-item' => $item_id, 'cancel' => time()), remove_query_arg( $removed_args, admin_url( 'nav-menus.php' ) ) ) ); ?>#menu-item-settings-<?php echo $item_id; ?>"><?php _e('Cancel'); ?></a> </div> <input class="menu-item-data-db-id" type="hidden" name="menu-item-db-id[<?php echo $item_id; ?>]" value="<?php echo $item_id; ?>" /> <input class="menu-item-data-object-id" type="hidden" name="menu-item-object-id[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $item->object_id ); ?>" /> <input class="menu-item-data-object" type="hidden" name="menu-item-object[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $item->object ); ?>" /> <input class="menu-item-data-parent-id" type="hidden" name="menu-item-parent-id[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $item->menu_item_parent ); ?>" /> <input class="menu-item-data-position" type="hidden" name="menu-item-position[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $item->menu_order ); ?>" /> <input class="menu-item-data-type" type="hidden" name="menu-item-type[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $item->type ); ?>" /> </div><!-- .menu-item-settings--> <ul class="menu-item-transport"></ul> <?php $output .= ob_get_clean(); } } /** * Create HTML list of nav menu input items. * * @package WordPress * @since 3.0.0 * @uses Walker_Nav_Menu */ class Walker_Nav_Menu_Checklist extends Walker_Nav_Menu { function __construct( $fields = false ) { if ( $fields ) { $this->db_fields = $fields; } } function start_lvl( &$output, $depth ) { $indent = str_repeat( "\t", $depth ); $output .= "\n$indent<ul class='children'>\n"; } function end_lvl( &$output, $depth ) { $indent = str_repeat( "\t", $depth ); $output .= "\n$indent</ul>"; } /** * @see Walker::start_el() * @since 3.0.0 * * @param string $output Passed by reference. Used to append additional content. * @param object $item Menu item data object. * @param int $depth Depth of menu item. Used for padding. * @param object $args */ function start_el(&$output, $item, $depth, $args) { global $_nav_menu_placeholder; $_nav_menu_placeholder = ( 0 > $_nav_menu_placeholder ) ? intval($_nav_menu_placeholder) - 1 : -1; $possible_object_id = isset( $item->post_type ) && 'nav_menu_item' == $item->post_type ? $item->object_id : $_nav_menu_placeholder; $possible_db_id = ( ! empty( $item->ID ) ) && ( 0 < $possible_object_id ) ? (int) $item->ID : 0; $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $output .= $indent . '<li>'; $output .= '<label class="menu-item-title">'; $output .= '<input type="checkbox" class="menu-item-checkbox'; if ( property_exists( $item, 'front_or_home' ) && $item->front_or_home ) { $title = sprintf( _x( 'Home: %s', 'nav menu front page title' ), $item->post_title ); $output .= ' add-to-top'; } $output .= '" name="menu-item[' . $possible_object_id . '][menu-item-object-id]" value="'. esc_attr( $item->object_id ) .'" /> '; $output .= isset( $title ) ? esc_html( $title ) : esc_html( $item->title ); $output .= '</label>'; // Menu item hidden fields $output .= '<input type="hidden" class="menu-item-db-id" name="menu-item[' . $possible_object_id . '][menu-item-db-id]" value="' . $possible_db_id . '" />'; $output .= '<input type="hidden" class="menu-item-object" name="menu-item[' . $possible_object_id . '][menu-item-object]" value="'. esc_attr( $item->object ) .'" />'; $output .= '<input type="hidden" class="menu-item-parent-id" name="menu-item[' . $possible_object_id . '][menu-item-parent-id]" value="'. esc_attr( $item->menu_item_parent ) .'" />'; $output .= '<input type="hidden" class="menu-item-type" name="menu-item[' . $possible_object_id . '][menu-item-type]" value="'. esc_attr( $item->type ) .'" />'; $output .= '<input type="hidden" class="menu-item-title" name="menu-item[' . $possible_object_id . '][menu-item-title]" value="'. esc_attr( $item->title ) .'" />'; $output .= '<input type="hidden" class="menu-item-url" name="menu-item[' . $possible_object_id . '][menu-item-url]" value="'. esc_attr( $item->url ) .'" />'; $output .= '<input type="hidden" class="menu-item-target" name="menu-item[' . $possible_object_id . '][menu-item-target]" value="'. esc_attr( $item->target ) .'" />'; $output .= '<input type="hidden" class="menu-item-attr_title" name="menu-item[' . $possible_object_id . '][menu-item-attr_title]" value="'. esc_attr( $item->attr_title ) .'" />'; $output .= '<input type="hidden" class="menu-item-classes" name="menu-item[' . $possible_object_id . '][menu-item-classes]" value="'. esc_attr( implode( ' ', $item->classes ) ) .'" />'; $output .= '<input type="hidden" class="menu-item-xfn" name="menu-item[' . $possible_object_id . '][menu-item-xfn]" value="'. esc_attr( $item->xfn ) .'" />'; } } /** * Prints the appropriate response to a menu quick search. * * @since 3.0.0 * * @param array $request The unsanitized request values. */ function _wp_ajax_menu_quick_search( $request = array() ) { $args = array(); $type = isset( $request['type'] ) ? $request['type'] : ''; $object_type = isset( $request['object_type'] ) ? $request['object_type'] : ''; $query = isset( $request['q'] ) ? $request['q'] : ''; $response_format = isset( $request['response-format'] ) && in_array( $request['response-format'], array( 'json', 'markup' ) ) ? $request['response-format'] : 'json'; if ( 'markup' == $response_format ) { $args['walker'] = new Walker_Nav_Menu_Checklist; } if ( 'get-post-item' == $type ) { if ( post_type_exists( $object_type ) ) { if ( isset( $request['ID'] ) ) { $object_id = (int) $request['ID']; if ( 'markup' == $response_format ) { echo walk_nav_menu_tree( array_map('wp_setup_nav_menu_item', array( get_post( $object_id ) ) ), 0, (object) $args ); } elseif ( 'json' == $response_format ) { $post_obj = get_post( $object_id ); echo json_encode( array( 'ID' => $object_id, 'post_title' => get_the_title( $object_id ), 'post_type' => get_post_type( $object_id ), ) ); echo "\n"; } } } elseif ( taxonomy_exists( $object_type ) ) { if ( isset( $request['ID'] ) ) { $object_id = (int) $request['ID']; if ( 'markup' == $response_format ) { echo walk_nav_menu_tree( array_map('wp_setup_nav_menu_item', array( get_term( $object_id, $object_type ) ) ), 0, (object) $args ); } elseif ( 'json' == $response_format ) { $post_obj = get_term( $object_id, $object_type ); echo json_encode( array( 'ID' => $object_id, 'post_title' => $post_obj->name, 'post_type' => $object_type, ) ); echo "\n"; } } } } elseif ( preg_match('/quick-search-(posttype|taxonomy)-([a-zA-Z_-]*\b)/', $type, $matches) ) { if ( 'posttype' == $matches[1] && get_post_type_object( $matches[2] ) ) { query_posts(array( 'posts_per_page' => 10, 'post_type' => $matches[2], 's' => $query, )); if ( ! have_posts() ) return; while ( have_posts() ) { the_post(); if ( 'markup' == $response_format ) { $var_by_ref = get_the_ID(); echo walk_nav_menu_tree( array_map('wp_setup_nav_menu_item', array( get_post( $var_by_ref ) ) ), 0, (object) $args ); } elseif ( 'json' == $response_format ) { echo json_encode( array( 'ID' => get_the_ID(), 'post_title' => get_the_title(), 'post_type' => get_post_type(), ) ); echo "\n"; } } } elseif ( 'taxonomy' == $matches[1] ) { $terms = get_terms( $matches[2], array( 'name__like' => $query, 'number' => 10, )); if ( empty( $terms ) || is_wp_error( $terms ) ) return; foreach( (array) $terms as $term ) { if ( 'markup' == $response_format ) { echo walk_nav_menu_tree( array_map('wp_setup_nav_menu_item', array( $term ) ), 0, (object) $args ); } elseif ( 'json' == $response_format ) { echo json_encode( array( 'ID' => $term->term_id, 'post_title' => $term->name, 'post_type' => $matches[2], ) ); echo "\n"; } } } } } /** * Register nav menu metaboxes and advanced menu items * * @since 3.0.0 **/ function wp_nav_menu_setup() { // Register meta boxes if ( wp_get_nav_menus() ) add_meta_box( 'nav-menu-theme-locations', __( 'Theme Locations' ), 'wp_nav_menu_locations_meta_box' , 'nav-menus', 'side', 'default' ); add_meta_box( 'add-custom-links', __('Custom Links'), 'wp_nav_menu_item_link_meta_box', 'nav-menus', 'side', 'default' ); wp_nav_menu_post_type_meta_boxes(); wp_nav_menu_taxonomy_meta_boxes(); // Register advanced menu items (columns) add_filter( 'manage_nav-menus_columns', 'wp_nav_menu_manage_columns'); // If first time editing, disable advanced items by default. if( false === get_user_option( 'managenav-menuscolumnshidden' ) ) { $user = wp_get_current_user(); update_user_option($user->ID, 'managenav-menuscolumnshidden', array( 0 => 'link-target', 1 => 'css-classes', 2 => 'xfn', 3 => 'description', ), true); } } /** * Limit the amount of meta boxes to just links, pages and cats for first time users. * * @since 3.0.0 **/ function wp_initial_nav_menu_meta_boxes() { global $wp_meta_boxes; if ( get_user_option( 'metaboxhidden_nav-menus' ) !== false || ! is_array($wp_meta_boxes) ) return; $initial_meta_boxes = array( 'nav-menu-theme-locations', 'add-custom-links', 'add-page', 'add-category' ); $hidden_meta_boxes = array(); foreach ( array_keys($wp_meta_boxes['nav-menus']) as $context ) { foreach ( array_keys($wp_meta_boxes['nav-menus'][$context]) as $priority ) { foreach ( $wp_meta_boxes['nav-menus'][$context][$priority] as $box ) { if ( in_array( $box['id'], $initial_meta_boxes ) ) { unset( $box['id'] ); } else { $hidden_meta_boxes[] = $box['id']; } } } } $user = wp_get_current_user(); update_user_option( $user->ID, 'metaboxhidden_nav-menus', $hidden_meta_boxes, true ); } /** * Creates metaboxes for any post type menu item. * * @since 3.0.0 */ function wp_nav_menu_post_type_meta_boxes() { $post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'object' ); if ( ! $post_types ) return; foreach ( $post_types as $post_type ) { $post_type = apply_filters( 'nav_menu_meta_box_object', $post_type ); if ( $post_type ) { $id = $post_type->name; add_meta_box( "add-{$id}", $post_type->labels->name, 'wp_nav_menu_item_post_type_meta_box', 'nav-menus', 'side', 'default', $post_type ); } } } /** * Creates metaboxes for any taxonomy menu item. * * @since 3.0.0 */ function wp_nav_menu_taxonomy_meta_boxes() { $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'object' ); if ( !$taxonomies ) return; foreach ( $taxonomies as $tax ) { $tax = apply_filters( 'nav_menu_meta_box_object', $tax ); if ( $tax ) { $id = $tax->name; add_meta_box( "add-{$id}", $tax->labels->name, 'wp_nav_menu_item_taxonomy_meta_box', 'nav-menus', 'side', 'default', $tax ); } } } /** * Displays a metabox for the nav menu theme locations. * * @since 3.0.0 */ function wp_nav_menu_locations_meta_box() { global $nav_menu_selected_id; if ( ! current_theme_supports( 'menus' ) ) { // We must only support widgets. Leave a message and bail. echo '<p class="howto">' . __('The current theme does not natively support menus, but you can use the &#8220;Custom Menu&#8221; widget to add any menus you create here to the theme&#8217;s sidebar.') . '</p>'; return; } $locations = get_registered_nav_menus(); $menus = wp_get_nav_menus(); $menu_locations = get_nav_menu_locations(); $num_locations = count( array_keys($locations) ); echo '<p class="howto">' . sprintf( _n('Your theme supports %s menu. Select which menu you would like to use.', 'Your theme supports %s menus. Select which menu appears in each location.', $num_locations ), number_format_i18n($num_locations) ) . '</p>'; foreach ( $locations as $location => $description ) { ?> <p> <label class="howto" for="locations-<?php echo $location; ?>"> <span><?php echo $description; ?></span> <select name="menu-locations[<?php echo $location; ?>]" id="locations-<?php echo $location; ?>"> <option value="0"></option> <?php foreach ( $menus as $menu ) : ?> <option<?php selected( isset( $menu_locations[ $location ] ) && $menu_locations[ $location ] == $menu->term_id ); ?> value="<?php echo $menu->term_id; ?>"><?php $truncated_name = wp_html_excerpt( $menu->name, 40 ); echo $truncated_name == $menu->name ? $menu->name : trim( $truncated_name ) . '&hellip;'; ?></option> <?php endforeach; ?> </select> </label> </p> <?php } ?> <p class="button-controls"> <?php submit_button( __( 'Save' ), 'primary right', 'nav-menu-locations', false, disabled( $nav_menu_selected_id, 0, false ) ); ?> <span class="spinner"></span> </p> <?php } /** * Displays a metabox for the custom links menu item. * * @since 3.0.0 */ function wp_nav_menu_item_link_meta_box() { global $_nav_menu_placeholder, $nav_menu_selected_id; $_nav_menu_placeholder = 0 > $_nav_menu_placeholder ? $_nav_menu_placeholder - 1 : -1; $current_tab = 'create'; if ( isset( $_REQUEST['customlink-tab'] ) && in_array( $_REQUEST['customlink-tab'], array('create', 'all') ) ) { $current_tab = $_REQUEST['customlink-tab']; } $removed_args = array( 'action', 'customlink-tab', 'edit-menu-item', 'menu-item', 'page-tab', '_wpnonce', ); ?> <div class="customlinkdiv" id="customlinkdiv"> <input type="hidden" value="custom" name="menu-item[<?php echo $_nav_menu_placeholder; ?>][menu-item-type]" /> <p id="menu-item-url-wrap"> <label class="howto" for="custom-menu-item-url"> <span><?php _e('URL'); ?></span> <input id="custom-menu-item-url" name="menu-item[<?php echo $_nav_menu_placeholder; ?>][menu-item-url]" type="text" class="code menu-item-textbox" value="http://" /> </label> </p> <p id="menu-item-name-wrap"> <label class="howto" for="custom-menu-item-name"> <span><?php _e('Label'); ?></span> <input id="custom-menu-item-name" name="menu-item[<?php echo $_nav_menu_placeholder; ?>][menu-item-title]" type="text" class="regular-text menu-item-textbox input-with-default-title" title="<?php esc_attr_e('Menu Item'); ?>" /> </label> </p> <p class="button-controls"> <span class="add-to-menu"> <input type="submit"<?php disabled( $nav_menu_selected_id, 0 ); ?> class="button-secondary submit-add-to-menu right" value="<?php esc_attr_e('Add to Menu'); ?>" name="add-custom-menu-item" id="submit-customlinkdiv" /> <span class="spinner"></span> </span> </p> </div><!-- /.customlinkdiv --> <?php } /** * Displays a metabox for a post type menu item. * * @since 3.0.0 * * @param string $object Not used. * @param string $post_type The post type object. */ function wp_nav_menu_item_post_type_meta_box( $object, $post_type ) { global $_nav_menu_placeholder, $nav_menu_selected_id; $post_type_name = $post_type['args']->name; // paginate browsing for large numbers of post objects $per_page = 50; $pagenum = isset( $_REQUEST[$post_type_name . '-tab'] ) && isset( $_REQUEST['paged'] ) ? absint( $_REQUEST['paged'] ) : 1; $offset = 0 < $pagenum ? $per_page * ( $pagenum - 1 ) : 0; $args = array( 'offset' => $offset, 'order' => 'ASC', 'orderby' => 'title', 'posts_per_page' => $per_page, 'post_type' => $post_type_name, 'suppress_filters' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false ); if ( isset( $post_type['args']->_default_query ) ) $args = array_merge($args, (array) $post_type['args']->_default_query ); // @todo transient caching of these results with proper invalidation on updating of a post of this type $get_posts = new WP_Query; $posts = $get_posts->query( $args ); if ( ! $get_posts->post_count ) { echo '<p>' . __( 'No items.' ) . '</p>'; return; } $post_type_object = get_post_type_object($post_type_name); $num_pages = $get_posts->max_num_pages; $page_links = paginate_links( array( 'base' => add_query_arg( array( $post_type_name . '-tab' => 'all', 'paged' => '%#%', 'item-type' => 'post_type', 'item-object' => $post_type_name, ) ), 'format' => '', 'prev_text' => __('&laquo;'), 'next_text' => __('&raquo;'), 'total' => $num_pages, 'current' => $pagenum )); if ( !$posts ) $error = '<li id="error">'. $post_type['args']->labels->not_found .'</li>'; $db_fields = false; if ( is_post_type_hierarchical( $post_type_name ) ) { $db_fields = array( 'parent' => 'post_parent', 'id' => 'ID' ); } $walker = new Walker_Nav_Menu_Checklist( $db_fields ); $current_tab = 'most-recent'; if ( isset( $_REQUEST[$post_type_name . '-tab'] ) && in_array( $_REQUEST[$post_type_name . '-tab'], array('all', 'search') ) ) { $current_tab = $_REQUEST[$post_type_name . '-tab']; } if ( ! empty( $_REQUEST['quick-search-posttype-' . $post_type_name] ) ) { $current_tab = 'search'; } $removed_args = array( 'action', 'customlink-tab', 'edit-menu-item', 'menu-item', 'page-tab', '_wpnonce', ); ?> <div id="posttype-<?php echo $post_type_name; ?>" class="posttypediv"> <ul id="posttype-<?php echo $post_type_name; ?>-tabs" class="posttype-tabs add-menu-item-tabs"> <li <?php echo ( 'most-recent' == $current_tab ? ' class="tabs"' : '' ); ?>><a class="nav-tab-link" href="<?php if ( $nav_menu_selected_id ) echo esc_url(add_query_arg($post_type_name . '-tab', 'most-recent', remove_query_arg($removed_args))); ?>#tabs-panel-posttype-<?php echo $post_type_name; ?>-most-recent"><?php _e('Most Recent'); ?></a></li> <li <?php echo ( 'all' == $current_tab ? ' class="tabs"' : '' ); ?>><a class="nav-tab-link" href="<?php if ( $nav_menu_selected_id ) echo esc_url(add_query_arg($post_type_name . '-tab', 'all', remove_query_arg($removed_args))); ?>#<?php echo $post_type_name; ?>-all"><?php _e('View All'); ?></a></li> <li <?php echo ( 'search' == $current_tab ? ' class="tabs"' : '' ); ?>><a class="nav-tab-link" href="<?php if ( $nav_menu_selected_id ) echo esc_url(add_query_arg($post_type_name . '-tab', 'search', remove_query_arg($removed_args))); ?>#tabs-panel-posttype-<?php echo $post_type_name; ?>-search"><?php _e('Search'); ?></a></li> </ul> <div id="tabs-panel-posttype-<?php echo $post_type_name; ?>-most-recent" class="tabs-panel <?php echo ( 'most-recent' == $current_tab ? 'tabs-panel-active' : 'tabs-panel-inactive' ); ?>"> <ul id="<?php echo $post_type_name; ?>checklist-most-recent" class="categorychecklist form-no-clear"> <?php $recent_args = array_merge( $args, array( 'orderby' => 'post_date', 'order' => 'DESC', 'posts_per_page' => 15 ) ); $most_recent = $get_posts->query( $recent_args ); $args['walker'] = $walker; echo walk_nav_menu_tree( array_map('wp_setup_nav_menu_item', $most_recent), 0, (object) $args ); ?> </ul> </div><!-- /.tabs-panel --> <div class="tabs-panel <?php echo ( 'search' == $current_tab ? 'tabs-panel-active' : 'tabs-panel-inactive' ); ?>" id="tabs-panel-posttype-<?php echo $post_type_name; ?>-search"> <?php if ( isset( $_REQUEST['quick-search-posttype-' . $post_type_name] ) ) { $searched = esc_attr( $_REQUEST['quick-search-posttype-' . $post_type_name] ); $search_results = get_posts( array( 's' => $searched, 'post_type' => $post_type_name, 'fields' => 'all', 'order' => 'DESC', ) ); } else { $searched = ''; $search_results = array(); } ?> <p class="quick-search-wrap"> <input type="search" class="quick-search input-with-default-title" title="<?php esc_attr_e('Search'); ?>" value="<?php echo $searched; ?>" name="quick-search-posttype-<?php echo $post_type_name; ?>" /> <span class="spinner"></span> <?php submit_button( __( 'Search' ), 'button-small quick-search-submit button-secondary hide-if-js', 'submit', false, array( 'id' => 'submit-quick-search-posttype-' . $post_type_name ) ); ?> </p> <ul id="<?php echo $post_type_name; ?>-search-checklist" data-wp-lists="list:<?php echo $post_type_name?>" class="categorychecklist form-no-clear"> <?php if ( ! empty( $search_results ) && ! is_wp_error( $search_results ) ) : ?> <?php $args['walker'] = $walker; echo walk_nav_menu_tree( array_map('wp_setup_nav_menu_item', $search_results), 0, (object) $args ); ?> <?php elseif ( is_wp_error( $search_results ) ) : ?> <li><?php echo $search_results->get_error_message(); ?></li> <?php elseif ( ! empty( $searched ) ) : ?> <li><?php _e('No results found.'); ?></li> <?php endif; ?> </ul> </div><!-- /.tabs-panel --> <div id="<?php echo $post_type_name; ?>-all" class="tabs-panel tabs-panel-view-all <?php echo ( 'all' == $current_tab ? 'tabs-panel-active' : 'tabs-panel-inactive' ); ?>"> <?php if ( ! empty( $page_links ) ) : ?> <div class="add-menu-item-pagelinks"> <?php echo $page_links; ?> </div> <?php endif; ?> <ul id="<?php echo $post_type_name; ?>checklist" data-wp-lists="list:<?php echo $post_type_name?>" class="categorychecklist form-no-clear"> <?php $args['walker'] = $walker; // if we're dealing with pages, let's put a checkbox for the front page at the top of the list if ( 'page' == $post_type_name ) { $front_page = 'page' == get_option('show_on_front') ? (int) get_option( 'page_on_front' ) : 0; if ( ! empty( $front_page ) ) { $front_page_obj = get_post( $front_page ); $front_page_obj->front_or_home = true; array_unshift( $posts, $front_page_obj ); } else { $_nav_menu_placeholder = ( 0 > $_nav_menu_placeholder ) ? intval($_nav_menu_placeholder) - 1 : -1; array_unshift( $posts, (object) array( 'front_or_home' => true, 'ID' => 0, 'object_id' => $_nav_menu_placeholder, 'post_content' => '', 'post_excerpt' => '', 'post_parent' => '', 'post_title' => _x('Home', 'nav menu home label'), 'post_type' => 'nav_menu_item', 'type' => 'custom', 'url' => home_url('/'), ) ); } } $posts = apply_filters( 'nav_menu_items_'.$post_type_name, $posts, $args, $post_type ); $checkbox_items = walk_nav_menu_tree( array_map('wp_setup_nav_menu_item', $posts), 0, (object) $args ); if ( 'all' == $current_tab && ! empty( $_REQUEST['selectall'] ) ) { $checkbox_items = preg_replace('/(type=(.)checkbox(\2))/', '$1 checked=$2checked$2', $checkbox_items); } echo $checkbox_items; ?> </ul> <?php if ( ! empty( $page_links ) ) : ?> <div class="add-menu-item-pagelinks"> <?php echo $page_links; ?> </div> <?php endif; ?> </div><!-- /.tabs-panel --> <p class="button-controls"> <span class="list-controls"> <a href="<?php echo esc_url(add_query_arg( array( $post_type_name . '-tab' => 'all', 'selectall' => 1, ), remove_query_arg($removed_args) )); ?>#posttype-<?php echo $post_type_name; ?>" class="select-all"><?php _e('Select All'); ?></a> </span> <span class="add-to-menu"> <input type="submit"<?php disabled( $nav_menu_selected_id, 0 ); ?> class="button-secondary submit-add-to-menu right" value="<?php esc_attr_e('Add to Menu'); ?>" name="add-post-type-menu-item" id="submit-posttype-<?php echo $post_type_name; ?>" /> <span class="spinner"></span> </span> </p> </div><!-- /.posttypediv --> <?php } /** * Displays a metabox for a taxonomy menu item. * * @since 3.0.0 * * @param string $object Not used. * @param string $taxonomy The taxonomy object. */ function wp_nav_menu_item_taxonomy_meta_box( $object, $taxonomy ) { global $nav_menu_selected_id; $taxonomy_name = $taxonomy['args']->name; // paginate browsing for large numbers of objects $per_page = 50; $pagenum = isset( $_REQUEST[$taxonomy_name . '-tab'] ) && isset( $_REQUEST['paged'] ) ? absint( $_REQUEST['paged'] ) : 1; $offset = 0 < $pagenum ? $per_page * ( $pagenum - 1 ) : 0; $args = array( 'child_of' => 0, 'exclude' => '', 'hide_empty' => false, 'hierarchical' => 1, 'include' => '', 'number' => $per_page, 'offset' => $offset, 'order' => 'ASC', 'orderby' => 'name', 'pad_counts' => false, ); $terms = get_terms( $taxonomy_name, $args ); if ( ! $terms || is_wp_error($terms) ) { echo '<p>' . __( 'No items.' ) . '</p>'; return; } $num_pages = ceil( wp_count_terms( $taxonomy_name , array_merge( $args, array('number' => '', 'offset' => '') ) ) / $per_page ); $page_links = paginate_links( array( 'base' => add_query_arg( array( $taxonomy_name . '-tab' => 'all', 'paged' => '%#%', 'item-type' => 'taxonomy', 'item-object' => $taxonomy_name, ) ), 'format' => '', 'prev_text' => __('&laquo;'), 'next_text' => __('&raquo;'), 'total' => $num_pages, 'current' => $pagenum )); $db_fields = false; if ( is_taxonomy_hierarchical( $taxonomy_name ) ) { $db_fields = array( 'parent' => 'parent', 'id' => 'term_id' ); } $walker = new Walker_Nav_Menu_Checklist( $db_fields ); $current_tab = 'most-used'; if ( isset( $_REQUEST[$taxonomy_name . '-tab'] ) && in_array( $_REQUEST[$taxonomy_name . '-tab'], array('all', 'most-used', 'search') ) ) { $current_tab = $_REQUEST[$taxonomy_name . '-tab']; } if ( ! empty( $_REQUEST['quick-search-taxonomy-' . $taxonomy_name] ) ) { $current_tab = 'search'; } $removed_args = array( 'action', 'customlink-tab', 'edit-menu-item', 'menu-item', 'page-tab', '_wpnonce', ); ?> <div id="taxonomy-<?php echo $taxonomy_name; ?>" class="taxonomydiv"> <ul id="taxonomy-<?php echo $taxonomy_name; ?>-tabs" class="taxonomy-tabs add-menu-item-tabs"> <li <?php echo ( 'most-used' == $current_tab ? ' class="tabs"' : '' ); ?>><a class="nav-tab-link" href="<?php if ( $nav_menu_selected_id ) echo esc_url(add_query_arg($taxonomy_name . '-tab', 'most-used', remove_query_arg($removed_args))); ?>#tabs-panel-<?php echo $taxonomy_name; ?>-pop"><?php _e('Most Used'); ?></a></li> <li <?php echo ( 'all' == $current_tab ? ' class="tabs"' : '' ); ?>><a class="nav-tab-link" href="<?php if ( $nav_menu_selected_id ) echo esc_url(add_query_arg($taxonomy_name . '-tab', 'all', remove_query_arg($removed_args))); ?>#tabs-panel-<?php echo $taxonomy_name; ?>-all"><?php _e('View All'); ?></a></li> <li <?php echo ( 'search' == $current_tab ? ' class="tabs"' : '' ); ?>><a class="nav-tab-link" href="<?php if ( $nav_menu_selected_id ) echo esc_url(add_query_arg($taxonomy_name . '-tab', 'search', remove_query_arg($removed_args))); ?>#tabs-panel-search-taxonomy-<?php echo $taxonomy_name; ?>"><?php _e('Search'); ?></a></li> </ul> <div id="tabs-panel-<?php echo $taxonomy_name; ?>-pop" class="tabs-panel <?php echo ( 'most-used' == $current_tab ? 'tabs-panel-active' : 'tabs-panel-inactive' ); ?>"> <ul id="<?php echo $taxonomy_name; ?>checklist-pop" class="categorychecklist form-no-clear" > <?php $popular_terms = get_terms( $taxonomy_name, array( 'orderby' => 'count', 'order' => 'DESC', 'number' => 10, 'hierarchical' => false ) ); $args['walker'] = $walker; echo walk_nav_menu_tree( array_map('wp_setup_nav_menu_item', $popular_terms), 0, (object) $args ); ?> </ul> </div><!-- /.tabs-panel --> <div id="tabs-panel-<?php echo $taxonomy_name; ?>-all" class="tabs-panel tabs-panel-view-all <?php echo ( 'all' == $current_tab ? 'tabs-panel-active' : 'tabs-panel-inactive' ); ?>"> <?php if ( ! empty( $page_links ) ) : ?> <div class="add-menu-item-pagelinks"> <?php echo $page_links; ?> </div> <?php endif; ?> <ul id="<?php echo $taxonomy_name; ?>checklist" data-wp-lists="list:<?php echo $taxonomy_name?>" class="categorychecklist form-no-clear"> <?php $args['walker'] = $walker; echo walk_nav_menu_tree( array_map('wp_setup_nav_menu_item', $terms), 0, (object) $args ); ?> </ul> <?php if ( ! empty( $page_links ) ) : ?> <div class="add-menu-item-pagelinks"> <?php echo $page_links; ?> </div> <?php endif; ?> </div><!-- /.tabs-panel --> <div class="tabs-panel <?php echo ( 'search' == $current_tab ? 'tabs-panel-active' : 'tabs-panel-inactive' ); ?>" id="tabs-panel-search-taxonomy-<?php echo $taxonomy_name; ?>"> <?php if ( isset( $_REQUEST['quick-search-taxonomy-' . $taxonomy_name] ) ) { $searched = esc_attr( $_REQUEST['quick-search-taxonomy-' . $taxonomy_name] ); $search_results = get_terms( $taxonomy_name, array( 'name__like' => $searched, 'fields' => 'all', 'orderby' => 'count', 'order' => 'DESC', 'hierarchical' => false ) ); } else { $searched = ''; $search_results = array(); } ?> <p class="quick-search-wrap"> <input type="search" class="quick-search input-with-default-title" title="<?php esc_attr_e('Search'); ?>" value="<?php echo $searched; ?>" name="quick-search-taxonomy-<?php echo $taxonomy_name; ?>" /> <span class="spinner"></span> <?php submit_button( __( 'Search' ), 'button-small quick-search-submit button-secondary hide-if-js', 'submit', false, array( 'id' => 'submit-quick-search-taxonomy-' . $taxonomy_name ) ); ?> </p> <ul id="<?php echo $taxonomy_name; ?>-search-checklist" data-wp-lists="list:<?php echo $taxonomy_name?>" class="categorychecklist form-no-clear"> <?php if ( ! empty( $search_results ) && ! is_wp_error( $search_results ) ) : ?> <?php $args['walker'] = $walker; echo walk_nav_menu_tree( array_map('wp_setup_nav_menu_item', $search_results), 0, (object) $args ); ?> <?php elseif ( is_wp_error( $search_results ) ) : ?> <li><?php echo $search_results->get_error_message(); ?></li> <?php elseif ( ! empty( $searched ) ) : ?> <li><?php _e('No results found.'); ?></li> <?php endif; ?> </ul> </div><!-- /.tabs-panel --> <p class="button-controls"> <span class="list-controls"> <a href="<?php echo esc_url(add_query_arg( array( $taxonomy_name . '-tab' => 'all', 'selectall' => 1, ), remove_query_arg($removed_args) )); ?>#taxonomy-<?php echo $taxonomy_name; ?>" class="select-all"><?php _e('Select All'); ?></a> </span> <span class="add-to-menu"> <input type="submit"<?php disabled( $nav_menu_selected_id, 0 ); ?> class="button-secondary submit-add-to-menu right" value="<?php esc_attr_e('Add to Menu'); ?>" name="add-taxonomy-menu-item" id="submit-taxonomy-<?php echo $taxonomy_name; ?>" /> <span class="spinner"></span> </span> </p> </div><!-- /.taxonomydiv --> <?php } /** * Save posted nav menu item data. * * @since 3.0.0 * * @param int $menu_id The menu ID for which to save this item. $menu_id of 0 makes a draft, orphaned menu item. * @param array $menu_data The unsanitized posted menu item data. * @return array The database IDs of the items saved */ function wp_save_nav_menu_items( $menu_id = 0, $menu_data = array() ) { $menu_id = (int) $menu_id; $items_saved = array(); if ( 0 == $menu_id || is_nav_menu( $menu_id ) ) { // Loop through all the menu items' POST values foreach( (array) $menu_data as $_possible_db_id => $_item_object_data ) { if ( empty( $_item_object_data['menu-item-object-id'] ) && // checkbox is not checked ( ! isset( $_item_object_data['menu-item-type'] ) || // and item type either isn't set in_array( $_item_object_data['menu-item-url'], array( 'http://', '' ) ) || // or URL is the default ! ( 'custom' == $_item_object_data['menu-item-type'] && ! isset( $_item_object_data['menu-item-db-id'] ) ) || // or it's not a custom menu item (but not the custom home page) ! empty( $_item_object_data['menu-item-db-id'] ) // or it *is* a custom menu item that already exists ) ) { continue; // then this potential menu item is not getting added to this menu } // if this possible menu item doesn't actually have a menu database ID yet if ( empty( $_item_object_data['menu-item-db-id'] ) || ( 0 > $_possible_db_id ) || $_possible_db_id != $_item_object_data['menu-item-db-id'] ) { $_actual_db_id = 0; } else { $_actual_db_id = (int) $_item_object_data['menu-item-db-id']; } $args = array( 'menu-item-db-id' => ( isset( $_item_object_data['menu-item-db-id'] ) ? $_item_object_data['menu-item-db-id'] : '' ), 'menu-item-object-id' => ( isset( $_item_object_data['menu-item-object-id'] ) ? $_item_object_data['menu-item-object-id'] : '' ), 'menu-item-object' => ( isset( $_item_object_data['menu-item-object'] ) ? $_item_object_data['menu-item-object'] : '' ), 'menu-item-parent-id' => ( isset( $_item_object_data['menu-item-parent-id'] ) ? $_item_object_data['menu-item-parent-id'] : '' ), 'menu-item-position' => ( isset( $_item_object_data['menu-item-position'] ) ? $_item_object_data['menu-item-position'] : '' ), 'menu-item-type' => ( isset( $_item_object_data['menu-item-type'] ) ? $_item_object_data['menu-item-type'] : '' ), 'menu-item-title' => ( isset( $_item_object_data['menu-item-title'] ) ? $_item_object_data['menu-item-title'] : '' ), 'menu-item-url' => ( isset( $_item_object_data['menu-item-url'] ) ? $_item_object_data['menu-item-url'] : '' ), 'menu-item-description' => ( isset( $_item_object_data['menu-item-description'] ) ? $_item_object_data['menu-item-description'] : '' ), 'menu-item-attr-title' => ( isset( $_item_object_data['menu-item-attr-title'] ) ? $_item_object_data['menu-item-attr-title'] : '' ), 'menu-item-target' => ( isset( $_item_object_data['menu-item-target'] ) ? $_item_object_data['menu-item-target'] : '' ), 'menu-item-classes' => ( isset( $_item_object_data['menu-item-classes'] ) ? $_item_object_data['menu-item-classes'] : '' ), 'menu-item-xfn' => ( isset( $_item_object_data['menu-item-xfn'] ) ? $_item_object_data['menu-item-xfn'] : '' ), ); $items_saved[] = wp_update_nav_menu_item( $menu_id, $_actual_db_id, $args ); } } return $items_saved; } /** * Adds custom arguments to some of the meta box object types. * * @since 3.0.0 * * @access private * * @param object $object The post type or taxonomy meta-object. * @return object The post type of taxonomy object. */ function _wp_nav_menu_meta_box_object( $object = null ) { if ( isset( $object->name ) ) { if ( 'page' == $object->name ) { $object->_default_query = array( 'orderby' => 'menu_order title', 'post_status' => 'publish', ); // posts should show only published items } elseif ( 'post' == $object->name ) { $object->_default_query = array( 'post_status' => 'publish', ); // cats should be in reverse chronological order } elseif ( 'category' == $object->name ) { $object->_default_query = array( 'orderby' => 'id', 'order' => 'DESC', ); // custom post types should show only published items } else { $object->_default_query = array( 'post_status' => 'publish', ); } } return $object; } /** * Returns the menu formatted to edit. * * @since 3.0.0 * * @param string $menu_id The ID of the menu to format. * @return string|WP_Error $output The menu formatted to edit or error object on failure. */ function wp_get_nav_menu_to_edit( $menu_id = 0 ) { $menu = wp_get_nav_menu_object( $menu_id ); // If the menu exists, get its items. if ( is_nav_menu( $menu ) ) { $menu_items = wp_get_nav_menu_items( $menu->term_id, array('post_status' => 'any') ); $result = '<div id="menu-instructions" class="post-body-plain'; $result .= ( ! empty($menu_items) ) ? ' menu-instructions-inactive">' : '">'; $result .= '<p>' . __('Select menu items (pages, categories, links) from the boxes at left to begin building your custom menu.') . '</p>'; $result .= '</div>'; if( empty($menu_items) ) return $result . ' <ul class="menu" id="menu-to-edit"> </ul>'; $walker_class_name = apply_filters( 'wp_edit_nav_menu_walker', 'Walker_Nav_Menu_Edit', $menu_id ); if ( class_exists( $walker_class_name ) ) $walker = new $walker_class_name; else return new WP_Error( 'menu_walker_not_exist', sprintf( __('The Walker class named <strong>%s</strong> does not exist.'), $walker_class_name ) ); $some_pending_menu_items = $some_invalid_menu_items = false; foreach( (array) $menu_items as $menu_item ) { if ( isset( $menu_item->post_status ) && 'draft' == $menu_item->post_status ) $some_pending_menu_items = true; if ( ! empty( $menu_item->_invalid ) ) $some_invalid_menu_items = true; } if ( $some_pending_menu_items ) $result .= '<div class="updated inline"><p>' . __('Click Save Menu to make pending menu items public.') . '</p></div>'; if ( $some_invalid_menu_items ) $result .= '<div class="error inline"><p>' . __('There are some invalid menu items. Please check or delete them.') . '</p></div>'; $result .= '<ul class="menu" id="menu-to-edit"> '; $result .= walk_nav_menu_tree( array_map('wp_setup_nav_menu_item', $menu_items), 0, (object) array('walker' => $walker ) ); $result .= ' </ul> '; return $result; } elseif ( is_wp_error( $menu ) ) { return $menu; } } /** * Returns the columns for the nav menus page. * * @since 3.0.0 * * @return string|WP_Error $output The menu formatted to edit or error object on failure. */ function wp_nav_menu_manage_columns() { return array( '_title' => __('Show advanced menu properties'), 'cb' => '<input type="checkbox" />', 'link-target' => __('Link Target'), 'css-classes' => __('CSS Classes'), 'xfn' => __('Link Relationship (XFN)'), 'description' => __('Description'), ); } /** * Deletes orphaned draft menu items * * @access private * @since 3.0.0 * */ function _wp_delete_orphaned_draft_menu_items() { global $wpdb; $delete_timestamp = time() - ( DAY_IN_SECONDS * EMPTY_TRASH_DAYS ); // delete orphaned draft menu items $menu_items_to_delete = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts AS p LEFT JOIN $wpdb->postmeta AS m ON p.ID = m.post_id WHERE post_type = 'nav_menu_item' AND post_status = 'draft' AND meta_key = '_menu_item_orphaned' AND meta_value < '%d'", $delete_timestamp ) ); foreach( (array) $menu_items_to_delete as $menu_item_id ) wp_delete_post( $menu_item_id, true ); } add_action('admin_head-nav-menus.php', '_wp_delete_orphaned_draft_menu_items');
zyblog
trunk/zyblog/wp-admin/includes/nav-menu.php
PHP
asf20
46,471
<?php /** * MS Themes List Table class. * * @package WordPress * @subpackage List_Table * @since 3.1.0 * @access private */ class WP_MS_Themes_List_Table extends WP_List_Table { var $site_id; var $is_site_themes; function __construct( $args = array() ) { global $status, $page; parent::__construct( array( 'plural' => 'themes', 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); $status = isset( $_REQUEST['theme_status'] ) ? $_REQUEST['theme_status'] : 'all'; if ( !in_array( $status, array( 'all', 'enabled', 'disabled', 'upgrade', 'search', 'broken' ) ) ) $status = 'all'; $page = $this->get_pagenum(); $this->is_site_themes = ( 'site-themes-network' == $this->screen->id ) ? true : false; if ( $this->is_site_themes ) $this->site_id = isset( $_REQUEST['id'] ) ? intval( $_REQUEST['id'] ) : 0; } function get_table_classes() { return array( 'widefat', 'plugins' ); // todo: remove and add CSS for .themes } function ajax_user_can() { if ( $this->is_site_themes ) return current_user_can( 'manage_sites' ); else return current_user_can( 'manage_network_themes' ); } function prepare_items() { global $status, $totals, $page, $orderby, $order, $s; wp_reset_vars( array( 'orderby', 'order', 's' ) ); $themes = array( 'all' => apply_filters( 'all_themes', wp_get_themes() ), 'search' => array(), 'enabled' => array(), 'disabled' => array(), 'upgrade' => array(), 'broken' => $this->is_site_themes ? array() : wp_get_themes( array( 'errors' => true ) ), ); if ( $this->is_site_themes ) { $themes_per_page = $this->get_items_per_page( 'site_themes_network_per_page' ); $allowed_where = 'site'; } else { $themes_per_page = $this->get_items_per_page( 'themes_network_per_page' ); $allowed_where = 'network'; } $maybe_update = current_user_can( 'update_themes' ) && ! $this->is_site_themes && $current = get_site_transient( 'update_themes' ); foreach ( (array) $themes['all'] as $key => $theme ) { if ( $this->is_site_themes && $theme->is_allowed( 'network' ) ) { unset( $themes['all'][ $key ] ); continue; } if ( $maybe_update && isset( $current->response[ $key ] ) ) { $themes['all'][ $key ]->update = true; $themes['upgrade'][ $key ] = $themes['all'][ $key ]; } $filter = $theme->is_allowed( $allowed_where, $this->site_id ) ? 'enabled' : 'disabled'; $themes[ $filter ][ $key ] = $themes['all'][ $key ]; } if ( $s ) { $status = 'search'; $themes['search'] = array_filter( array_merge( $themes['all'], $themes['broken'] ), array( &$this, '_search_callback' ) ); } $totals = array(); foreach ( $themes as $type => $list ) $totals[ $type ] = count( $list ); if ( empty( $themes[ $status ] ) && !in_array( $status, array( 'all', 'search' ) ) ) $status = 'all'; $this->items = $themes[ $status ]; WP_Theme::sort_by_name( $this->items ); $this->has_items = ! empty( $themes['all'] ); $total_this_page = $totals[ $status ]; if ( $orderby ) { $orderby = ucfirst( $orderby ); $order = strtoupper( $order ); if ( $orderby == 'Name' ) { if ( 'ASC' == $order ) $this->items = array_reverse( $this->items ); } else { uasort( $this->items, array( &$this, '_order_callback' ) ); } } $start = ( $page - 1 ) * $themes_per_page; if ( $total_this_page > $themes_per_page ) $this->items = array_slice( $this->items, $start, $themes_per_page, true ); $this->set_pagination_args( array( 'total_items' => $total_this_page, 'per_page' => $themes_per_page, ) ); } function _search_callback( $theme ) { static $term; if ( is_null( $term ) ) $term = stripslashes( $_REQUEST['s'] ); foreach ( array( 'Name', 'Description', 'Author', 'Author', 'AuthorURI' ) as $field ) { // Don't mark up; Do translate. if ( false !== stripos( $theme->display( $field, false, true ), $term ) ) return true; } if ( false !== stripos( $theme->get_stylesheet(), $term ) ) return true; if ( false !== stripos( $theme->get_template(), $term ) ) return true; return false; } // Not used by any core columns. function _order_callback( $theme_a, $theme_b ) { global $orderby, $order; $a = $theme_a[ $orderby ]; $b = $theme_b[ $orderby ]; if ( $a == $b ) return 0; if ( 'DESC' == $order ) return ( $a < $b ) ? 1 : -1; else return ( $a < $b ) ? -1 : 1; } function no_items() { if ( ! $this->has_items ) _e( 'No themes found.' ); else _e( 'You do not appear to have any themes available at this time.' ); } function get_columns() { global $status; return array( 'cb' => '<input type="checkbox" />', 'name' => __( 'Theme' ), 'description' => __( 'Description' ), ); } function get_sortable_columns() { return array( 'name' => 'name', ); } function get_views() { global $totals, $status; $status_links = array(); foreach ( $totals as $type => $count ) { if ( !$count ) continue; switch ( $type ) { case 'all': $text = _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $count, 'themes' ); break; case 'enabled': $text = _n( 'Enabled <span class="count">(%s)</span>', 'Enabled <span class="count">(%s)</span>', $count ); break; case 'disabled': $text = _n( 'Disabled <span class="count">(%s)</span>', 'Disabled <span class="count">(%s)</span>', $count ); break; case 'upgrade': $text = _n( 'Update Available <span class="count">(%s)</span>', 'Update Available <span class="count">(%s)</span>', $count ); break; case 'broken' : $text = _n( 'Broken <span class="count">(%s)</span>', 'Broken <span class="count">(%s)</span>', $count ); break; } if ( $this->is_site_themes ) $url = 'site-themes.php?id=' . $this->site_id; else $url = 'themes.php'; if ( 'search' != $type ) { $status_links[$type] = sprintf( "<a href='%s' %s>%s</a>", esc_url( add_query_arg('theme_status', $type, $url) ), ( $type == $status ) ? ' class="current"' : '', sprintf( $text, number_format_i18n( $count ) ) ); } } return $status_links; } function get_bulk_actions() { global $status; $actions = array(); if ( 'enabled' != $status ) $actions['enable-selected'] = $this->is_site_themes ? __( 'Enable' ) : __( 'Network Enable' ); if ( 'disabled' != $status ) $actions['disable-selected'] = $this->is_site_themes ? __( 'Disable' ) : __( 'Network Disable' ); if ( ! $this->is_site_themes ) { if ( current_user_can( 'update_themes' ) ) $actions['update-selected'] = __( 'Update' ); if ( current_user_can( 'delete_themes' ) ) $actions['delete-selected'] = __( 'Delete' ); } return $actions; } function display_rows() { foreach ( $this->items as $key => $theme ) $this->single_row( $key, $theme ); } function single_row( $key, $theme ) { global $status, $page, $s, $totals; $context = $status; if ( $this->is_site_themes ) { $url = "site-themes.php?id={$this->site_id}&amp;"; $allowed = $theme->is_allowed( 'site', $this->site_id ); } else { $url = 'themes.php?'; $allowed = $theme->is_allowed( 'network' ); } // preorder $actions = array( 'enable' => '', 'disable' => '', 'edit' => '', 'delete' => '' ); $stylesheet = $theme->get_stylesheet(); $theme_key = urlencode( $stylesheet ); if ( ! $allowed ) { if ( ! $theme->errors() ) $actions['enable'] = '<a href="' . esc_url( wp_nonce_url($url . 'action=enable&amp;theme=' . $theme_key . '&amp;paged=' . $page . '&amp;s=' . $s, 'enable-theme_' . $stylesheet ) ) . '" title="' . esc_attr__('Enable this theme') . '" class="edit">' . ( $this->is_site_themes ? __( 'Enable' ) : __( 'Network Enable' ) ) . '</a>'; } else { $actions['disable'] = '<a href="' . esc_url( wp_nonce_url($url . 'action=disable&amp;theme=' . $theme_key . '&amp;paged=' . $page . '&amp;s=' . $s, 'disable-theme_' . $stylesheet ) ) . '" title="' . esc_attr__('Disable this theme') . '">' . ( $this->is_site_themes ? __( 'Disable' ) : __( 'Network Disable' ) ) . '</a>'; } if ( current_user_can('edit_themes') ) $actions['edit'] = '<a href="' . esc_url('theme-editor.php?theme=' . $theme_key ) . '" title="' . esc_attr__('Open this theme in the Theme Editor') . '" class="edit">' . __('Edit') . '</a>'; if ( ! $allowed && current_user_can( 'delete_themes' ) && ! $this->is_site_themes && $stylesheet != get_option( 'stylesheet' ) && $stylesheet != get_option( 'template' ) ) $actions['delete'] = '<a href="' . esc_url( wp_nonce_url( 'themes.php?action=delete-selected&amp;checked[]=' . $theme_key . '&amp;theme_status=' . $context . '&amp;paged=' . $page . '&amp;s=' . $s, 'bulk-themes' ) ) . '" title="' . esc_attr__( 'Delete this theme' ) . '" class="delete">' . __( 'Delete' ) . '</a>'; $actions = apply_filters( 'theme_action_links', array_filter( $actions ), $stylesheet, $theme, $context ); $actions = apply_filters( "theme_action_links_$stylesheet", $actions, $stylesheet, $theme, $context ); $class = ! $allowed ? 'inactive' : 'active'; $checkbox_id = "checkbox_" . md5( $theme->get('Name') ); $checkbox = "<input type='checkbox' name='checked[]' value='" . esc_attr( $stylesheet ) . "' id='" . $checkbox_id . "' /><label class='screen-reader-text' for='" . $checkbox_id . "' >" . __('Select') . " " . $theme->display('Name') . "</label>"; $id = sanitize_html_class( $theme->get_stylesheet() ); if ( ! empty( $totals['upgrade'] ) && ! empty( $theme->update ) ) $class .= ' update'; echo "<tr id='$id' class='$class'>"; list( $columns, $hidden ) = $this->get_column_info(); foreach ( $columns as $column_name => $column_display_name ) { $style = ''; if ( in_array( $column_name, $hidden ) ) $style = ' style="display:none;"'; switch ( $column_name ) { case 'cb': echo "<th scope='row' class='check-column'>$checkbox</th>"; break; case 'name': echo "<td class='theme-title'$style><strong>" . $theme->display('Name') . "</strong>"; echo $this->row_actions( $actions, true ); echo "</td>"; break; case 'description': echo "<td class='column-description desc'$style>"; if ( $theme->errors() ) { $pre = $status == 'broken' ? '' : __( 'Broken Theme:' ) . ' '; echo '<p><strong class="attention">' . $pre . $theme->errors()->get_error_message() . '</strong></p>'; } echo "<div class='theme-description'><p>" . $theme->display( 'Description' ) . "</p></div> <div class='$class second theme-version-author-uri'>"; $theme_meta = array(); if ( $theme->get('Version') ) $theme_meta[] = sprintf( __( 'Version %s' ), $theme->display('Version') ); $theme_meta[] = sprintf( __( 'By %s' ), $theme->display('Author') ); if ( $theme->get('ThemeURI') ) $theme_meta[] = '<a href="' . $theme->display('ThemeURI') . '" title="' . esc_attr__( 'Visit theme homepage' ) . '">' . __( 'Visit Theme Site' ) . '</a>'; $theme_meta = apply_filters( 'theme_row_meta', $theme_meta, $stylesheet, $theme, $status ); echo implode( ' | ', $theme_meta ); echo "</div></td>"; break; default: echo "<td class='$column_name column-$column_name'$style>"; do_action( 'manage_themes_custom_column', $column_name, $stylesheet, $theme ); echo "</td>"; } } echo "</tr>"; if ( $this->is_site_themes ) remove_action( "after_theme_row_$stylesheet", 'wp_theme_update_row' ); do_action( 'after_theme_row', $stylesheet, $theme, $status ); do_action( "after_theme_row_$stylesheet", $stylesheet, $theme, $status ); } }
zyblog
trunk/zyblog/wp-admin/includes/class-wp-ms-themes-list-table.php
PHP
asf20
11,709
<?php /** * PemFTP - A Ftp implementation in pure PHP * * @package PemFTP * @since 2.5 * * @version 1.0 * @copyright Alexey Dotsenko * @author Alexey Dotsenko * @link http://www.phpclasses.org/browse/package/1743.html Site * @license LGPL License http://www.opensource.org/licenses/lgpl-license.html */ /** * FTP implementation using fsockopen to connect. * * @package PemFTP * @subpackage Pure * @since 2.5 * * @version 1.0 * @copyright Alexey Dotsenko * @author Alexey Dotsenko * @link http://www.phpclasses.org/browse/package/1743.html Site * @license LGPL License http://www.opensource.org/licenses/lgpl-license.html */ class ftp extends ftp_base { function ftp($verb=FALSE, $le=FALSE) { $this->__construct($verb, $le); } function __construct($verb=FALSE, $le=FALSE) { parent::__construct(false, $verb, $le); } // <!-- --------------------------------------------------------------------------------------- --> // <!-- Private functions --> // <!-- --------------------------------------------------------------------------------------- --> function _settimeout($sock) { if(!@stream_set_timeout($sock, $this->_timeout)) { $this->PushError('_settimeout','socket set send timeout'); $this->_quit(); return FALSE; } return TRUE; } function _connect($host, $port) { $this->SendMSG("Creating socket"); $sock = @fsockopen($host, $port, $errno, $errstr, $this->_timeout); if (!$sock) { $this->PushError('_connect','socket connect failed', $errstr." (".$errno.")"); return FALSE; } $this->_connected=true; return $sock; } function _readmsg($fnction="_readmsg"){ if(!$this->_connected) { $this->PushError($fnction, 'Connect first'); return FALSE; } $result=true; $this->_message=""; $this->_code=0; $go=true; do { $tmp=@fgets($this->_ftp_control_sock, 512); if($tmp===false) { $go=$result=false; $this->PushError($fnction,'Read failed'); } else { $this->_message.=$tmp; if(preg_match("/^([0-9]{3})(-(.*[".CRLF."]{1,2})+\\1)? [^".CRLF."]+[".CRLF."]{1,2}$/", $this->_message, $regs)) $go=false; } } while($go); if($this->LocalEcho) echo "GET < ".rtrim($this->_message, CRLF).CRLF; $this->_code=(int)$regs[1]; return $result; } function _exec($cmd, $fnction="_exec") { if(!$this->_ready) { $this->PushError($fnction,'Connect first'); return FALSE; } if($this->LocalEcho) echo "PUT > ",$cmd,CRLF; $status=@fputs($this->_ftp_control_sock, $cmd.CRLF); if($status===false) { $this->PushError($fnction,'socket write failed'); return FALSE; } $this->_lastaction=time(); if(!$this->_readmsg($fnction)) return FALSE; return TRUE; } function _data_prepare($mode=FTP_ASCII) { if(!$this->_settype($mode)) return FALSE; if($this->_passive) { if(!$this->_exec("PASV", "pasv")) { $this->_data_close(); return FALSE; } if(!$this->_checkCode()) { $this->_data_close(); return FALSE; } $ip_port = explode(",", ereg_replace("^.+ \\(?([0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]+,[0-9]+)\\)?.*".CRLF."$", "\\1", $this->_message)); $this->_datahost=$ip_port[0].".".$ip_port[1].".".$ip_port[2].".".$ip_port[3]; $this->_dataport=(((int)$ip_port[4])<<8) + ((int)$ip_port[5]); $this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport); $this->_ftp_data_sock=@fsockopen($this->_datahost, $this->_dataport, $errno, $errstr, $this->_timeout); if(!$this->_ftp_data_sock) { $this->PushError("_data_prepare","fsockopen fails", $errstr." (".$errno.")"); $this->_data_close(); return FALSE; } else $this->_ftp_data_sock; } else { $this->SendMSG("Only passive connections available!"); return FALSE; } return TRUE; } function _data_read($mode=FTP_ASCII, $fp=NULL) { if(is_resource($fp)) $out=0; else $out=""; if(!$this->_passive) { $this->SendMSG("Only passive connections available!"); return FALSE; } while (!feof($this->_ftp_data_sock)) { $block=fread($this->_ftp_data_sock, $this->_ftp_buff_size); if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_local], $block); if(is_resource($fp)) $out+=fwrite($fp, $block, strlen($block)); else $out.=$block; } return $out; } function _data_write($mode=FTP_ASCII, $fp=NULL) { if(is_resource($fp)) $out=0; else $out=""; if(!$this->_passive) { $this->SendMSG("Only passive connections available!"); return FALSE; } if(is_resource($fp)) { while(!feof($fp)) { $block=fread($fp, $this->_ftp_buff_size); if(!$this->_data_write_block($mode, $block)) return false; } } elseif(!$this->_data_write_block($mode, $fp)) return false; return TRUE; } function _data_write_block($mode, $block) { if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_remote], $block); do { if(($t=@fwrite($this->_ftp_data_sock, $block))===FALSE) { $this->PushError("_data_write","Can't write to socket"); return FALSE; } $block=substr($block, $t); } while(!empty($block)); return true; } function _data_close() { @fclose($this->_ftp_data_sock); $this->SendMSG("Disconnected data from remote host"); return TRUE; } function _quit($force=FALSE) { if($this->_connected or $force) { @fclose($this->_ftp_control_sock); $this->_connected=false; $this->SendMSG("Socket closed"); } } } ?>
zyblog
trunk/zyblog/wp-admin/includes/class-ftp-pure.php
PHP
asf20
5,489
<?php /** * WordPress Direct Filesystem. * * @package WordPress * @subpackage Filesystem */ /** * WordPress Filesystem Class for direct PHP file and folder manipulation. * * @since 2.5 * @package WordPress * @subpackage Filesystem * @uses WP_Filesystem_Base Extends class */ class WP_Filesystem_Direct extends WP_Filesystem_Base { var $errors = null; /** * constructor * * @param mixed $arg ignored argument */ function __construct($arg) { $this->method = 'direct'; $this->errors = new WP_Error(); } /** * connect filesystem. * * @return bool Returns true on success or false on failure (always true for WP_Filesystem_Direct). */ function connect() { return true; } /** * Reads entire file into a string * * @param string $file Name of the file to read. * @return string|bool The function returns the read data or false on failure. */ function get_contents($file) { return @file_get_contents($file); } /** * Reads entire file into an array * * @param string $file Path to the file. * @return array|bool the file contents in an array or false on failure. */ function get_contents_array($file) { return @file($file); } /** * Write a string to a file * * @param string $file Remote path to the file where to write the data. * @param string $contents The data to write. * @param int $mode (optional) The file permissions as octal number, usually 0644. * @return bool False upon failure. */ function put_contents($file, $contents, $mode = false ) { if ( ! ($fp = @fopen($file, 'w')) ) return false; @fwrite($fp, $contents); @fclose($fp); $this->chmod($file, $mode); return true; } /** * Gets the current working directory * * @return string|bool the current working directory on success, or false on failure. */ function cwd() { return @getcwd(); } /** * Change directory * * @param string $dir The new current directory. * @return bool Returns true on success or false on failure. */ function chdir($dir) { return @chdir($dir); } /** * Changes file group * * @param string $file Path to the file. * @param mixed $group A group name or number. * @param bool $recursive (optional) If set True changes file group recursively. Defaults to False. * @return bool Returns true on success or false on failure. */ function chgrp($file, $group, $recursive = false) { if ( ! $this->exists($file) ) return false; if ( ! $recursive ) return @chgrp($file, $group); if ( ! $this->is_dir($file) ) return @chgrp($file, $group); //Is a directory, and we want recursive $file = trailingslashit($file); $filelist = $this->dirlist($file); foreach ($filelist as $filename) $this->chgrp($file . $filename, $group, $recursive); return true; } /** * Changes filesystem permissions * * @param string $file Path to the file. * @param int $mode (optional) The permissions as octal number, usually 0644 for files, 0755 for dirs. * @param bool $recursive (optional) If set True changes file group recursively. Defaults to False. * @return bool Returns true on success or false on failure. */ function chmod($file, $mode = false, $recursive = false) { if ( ! $mode ) { if ( $this->is_file($file) ) $mode = FS_CHMOD_FILE; elseif ( $this->is_dir($file) ) $mode = FS_CHMOD_DIR; else return false; } if ( ! $recursive || ! $this->is_dir($file) ) return @chmod($file, $mode); //Is a directory, and we want recursive $file = trailingslashit($file); $filelist = $this->dirlist($file); foreach ( (array)$filelist as $filename => $filemeta) $this->chmod($file . $filename, $mode, $recursive); return true; } /** * Changes file owner * * @param string $file Path to the file. * @param mixed $owner A user name or number. * @param bool $recursive (optional) If set True changes file owner recursively. Defaults to False. * @return bool Returns true on success or false on failure. */ function chown($file, $owner, $recursive = false) { if ( ! $this->exists($file) ) return false; if ( ! $recursive ) return @chown($file, $owner); if ( ! $this->is_dir($file) ) return @chown($file, $owner); //Is a directory, and we want recursive $filelist = $this->dirlist($file); foreach ($filelist as $filename) { $this->chown($file . '/' . $filename, $owner, $recursive); } return true; } /** * Gets file owner * * @param string $file Path to the file. * @return string Username of the user. */ function owner($file) { $owneruid = @fileowner($file); if ( ! $owneruid ) return false; if ( ! function_exists('posix_getpwuid') ) return $owneruid; $ownerarray = posix_getpwuid($owneruid); return $ownerarray['name']; } /** * Gets file permissions * * FIXME does not handle errors in fileperms() * * @param string $file Path to the file. * @return string Mode of the file (last 4 digits). */ function getchmod($file) { return substr(decoct(@fileperms($file)),3); } function group($file) { $gid = @filegroup($file); if ( ! $gid ) return false; if ( ! function_exists('posix_getgrgid') ) return $gid; $grouparray = posix_getgrgid($gid); return $grouparray['name']; } function copy($source, $destination, $overwrite = false, $mode = false) { if ( ! $overwrite && $this->exists($destination) ) return false; $rtval = copy($source, $destination); if ( $mode ) $this->chmod($destination, $mode); return $rtval; } function move($source, $destination, $overwrite = false) { if ( ! $overwrite && $this->exists($destination) ) return false; // try using rename first. if that fails (for example, source is read only) try copy if ( @rename($source, $destination) ) return true; if ( $this->copy($source, $destination, $overwrite) && $this->exists($destination) ) { $this->delete($source); return true; } else { return false; } } function delete($file, $recursive = false, $type = false) { if ( empty($file) ) //Some filesystems report this as /, which can cause non-expected recursive deletion of all files in the filesystem. return false; $file = str_replace('\\', '/', $file); //for win32, occasional problems deleting files otherwise if ( 'f' == $type || $this->is_file($file) ) return @unlink($file); if ( ! $recursive && $this->is_dir($file) ) return @rmdir($file); //At this point its a folder, and we're in recursive mode $file = trailingslashit($file); $filelist = $this->dirlist($file, true); $retval = true; if ( is_array($filelist) ) //false if no files, So check first. foreach ($filelist as $filename => $fileinfo) if ( ! $this->delete($file . $filename, $recursive, $fileinfo['type']) ) $retval = false; if ( file_exists($file) && ! @rmdir($file) ) $retval = false; return $retval; } function exists($file) { return @file_exists($file); } function is_file($file) { return @is_file($file); } function is_dir($path) { return @is_dir($path); } function is_readable($file) { return @is_readable($file); } function is_writable($file) { return @is_writable($file); } function atime($file) { return @fileatime($file); } function mtime($file) { return @filemtime($file); } function size($file) { return @filesize($file); } function touch($file, $time = 0, $atime = 0) { if ($time == 0) $time = time(); if ($atime == 0) $atime = time(); return @touch($file, $time, $atime); } function mkdir($path, $chmod = false, $chown = false, $chgrp = false) { // safe mode fails with a trailing slash under certain PHP versions. $path = untrailingslashit($path); if ( empty($path) ) return false; if ( ! $chmod ) $chmod = FS_CHMOD_DIR; if ( ! @mkdir($path) ) return false; $this->chmod($path, $chmod); if ( $chown ) $this->chown($path, $chown); if ( $chgrp ) $this->chgrp($path, $chgrp); return true; } function rmdir($path, $recursive = false) { return $this->delete($path, $recursive); } function dirlist($path, $include_hidden = true, $recursive = false) { if ( $this->is_file($path) ) { $limit_file = basename($path); $path = dirname($path); } else { $limit_file = false; } if ( ! $this->is_dir($path) ) return false; $dir = @dir($path); if ( ! $dir ) return false; $ret = array(); while (false !== ($entry = $dir->read()) ) { $struc = array(); $struc['name'] = $entry; if ( '.' == $struc['name'] || '..' == $struc['name'] ) continue; if ( ! $include_hidden && '.' == $struc['name'][0] ) continue; if ( $limit_file && $struc['name'] != $limit_file) continue; $struc['perms'] = $this->gethchmod($path.'/'.$entry); $struc['permsn'] = $this->getnumchmodfromh($struc['perms']); $struc['number'] = false; $struc['owner'] = $this->owner($path.'/'.$entry); $struc['group'] = $this->group($path.'/'.$entry); $struc['size'] = $this->size($path.'/'.$entry); $struc['lastmodunix']= $this->mtime($path.'/'.$entry); $struc['lastmod'] = date('M j',$struc['lastmodunix']); $struc['time'] = date('h:i:s',$struc['lastmodunix']); $struc['type'] = $this->is_dir($path.'/'.$entry) ? 'd' : 'f'; if ( 'd' == $struc['type'] ) { if ( $recursive ) $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $include_hidden, $recursive); else $struc['files'] = array(); } $ret[ $struc['name'] ] = $struc; } $dir->close(); unset($dir); return $ret; } }
zyblog
trunk/zyblog/wp-admin/includes/class-wp-filesystem-direct.php
PHP
asf20
9,558
<?php /** * Media Library List Table class. * * @package WordPress * @subpackage List_Table * @since 3.1.0 * @access private */ class WP_Media_List_Table extends WP_List_Table { function __construct( $args = array() ) { $this->detached = isset( $_REQUEST['detached'] ) || isset( $_REQUEST['find_detached'] ); parent::__construct( array( 'plural' => 'media', 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); } function ajax_user_can() { return current_user_can('upload_files'); } function prepare_items() { global $lost, $wpdb, $wp_query, $post_mime_types, $avail_post_mime_types; $q = $_REQUEST; if ( !empty( $lost ) ) $q['post__in'] = implode( ',', $lost ); list( $post_mime_types, $avail_post_mime_types ) = wp_edit_attachments_query( $q ); $this->is_trash = isset( $_REQUEST['status'] ) && 'trash' == $_REQUEST['status']; $this->set_pagination_args( array( 'total_items' => $wp_query->found_posts, 'total_pages' => $wp_query->max_num_pages, 'per_page' => $wp_query->query_vars['posts_per_page'], ) ); } function get_views() { global $wpdb, $post_mime_types, $avail_post_mime_types; $type_links = array(); $_num_posts = (array) wp_count_attachments(); $_total_posts = array_sum($_num_posts) - $_num_posts['trash']; if ( !isset( $total_orphans ) ) $total_orphans = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' AND post_parent < 1" ); $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts)); foreach ( $matches as $type => $reals ) foreach ( $reals as $real ) $num_posts[$type] = ( isset( $num_posts[$type] ) ) ? $num_posts[$type] + $_num_posts[$real] : $_num_posts[$real]; $class = ( empty($_GET['post_mime_type']) && !$this->detached && !isset($_GET['status']) ) ? ' class="current"' : ''; $type_links['all'] = "<a href='upload.php'$class>" . sprintf( _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $_total_posts, 'uploaded files' ), number_format_i18n( $_total_posts ) ) . '</a>'; foreach ( $post_mime_types as $mime_type => $label ) { $class = ''; if ( !wp_match_mime_types($mime_type, $avail_post_mime_types) ) continue; if ( !empty($_GET['post_mime_type']) && wp_match_mime_types($mime_type, $_GET['post_mime_type']) ) $class = ' class="current"'; if ( !empty( $num_posts[$mime_type] ) ) $type_links[$mime_type] = "<a href='upload.php?post_mime_type=$mime_type'$class>" . sprintf( translate_nooped_plural( $label[2], $num_posts[$mime_type] ), number_format_i18n( $num_posts[$mime_type] )) . '</a>'; } $type_links['detached'] = '<a href="upload.php?detached=1"' . ( $this->detached ? ' class="current"' : '' ) . '>' . sprintf( _nx( 'Unattached <span class="count">(%s)</span>', 'Unattached <span class="count">(%s)</span>', $total_orphans, 'detached files' ), number_format_i18n( $total_orphans ) ) . '</a>'; if ( !empty($_num_posts['trash']) ) $type_links['trash'] = '<a href="upload.php?status=trash"' . ( (isset($_GET['status']) && $_GET['status'] == 'trash' ) ? ' class="current"' : '') . '>' . sprintf( _nx( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>', $_num_posts['trash'], 'uploaded files' ), number_format_i18n( $_num_posts['trash'] ) ) . '</a>'; return $type_links; } function get_bulk_actions() { $actions = array(); $actions['delete'] = __( 'Delete Permanently' ); if ( $this->detached ) $actions['attach'] = __( 'Attach to a post' ); return $actions; } function extra_tablenav( $which ) { ?> <div class="alignleft actions"> <?php if ( 'top' == $which && !is_singular() && !$this->detached && !$this->is_trash ) { $this->months_dropdown( 'attachment' ); do_action( 'restrict_manage_posts' ); submit_button( __( 'Filter' ), 'button', false, false, array( 'id' => 'post-query-submit' ) ); } if ( $this->detached ) { submit_button( __( 'Scan for lost attachments' ), 'secondary', 'find_detached', false ); } elseif ( $this->is_trash && current_user_can( 'edit_others_posts' ) ) { submit_button( __( 'Empty Trash' ), 'apply', 'delete_all', false ); } ?> </div> <?php } function current_action() { if ( isset( $_REQUEST['find_detached'] ) ) return 'find_detached'; if ( isset( $_REQUEST['found_post_id'] ) && isset( $_REQUEST['media'] ) ) return 'attach'; if ( isset( $_REQUEST['delete_all'] ) || isset( $_REQUEST['delete_all2'] ) ) return 'delete_all'; return parent::current_action(); } function has_items() { return have_posts(); } function no_items() { _e( 'No media attachments found.' ); } function get_columns() { $posts_columns = array(); $posts_columns['cb'] = '<input type="checkbox" />'; $posts_columns['icon'] = ''; /* translators: column name */ $posts_columns['title'] = _x( 'File', 'column name' ); $posts_columns['author'] = __( 'Author' ); $taxonomies = array(); $taxonomies = get_taxonomies_for_attachments( 'objects' ); $taxonomies = wp_filter_object_list( $taxonomies, array( 'show_admin_column' => true ), 'and', 'name' ); $taxonomies = apply_filters( 'manage_taxonomies_for_attachment_columns', $taxonomies, 'attachment' ); $taxonomies = array_filter( $taxonomies, 'taxonomy_exists' ); foreach ( $taxonomies as $taxonomy ) { if ( 'category' == $taxonomy ) $column_key = 'categories'; elseif ( 'post_tag' == $taxonomy ) $column_key = 'tags'; else $column_key = 'taxonomy-' . $taxonomy; $posts_columns[ $column_key ] = get_taxonomy( $taxonomy )->labels->name; } /* translators: column name */ if ( !$this->detached ) { $posts_columns['parent'] = _x( 'Uploaded to', 'column name' ); if ( post_type_supports( 'attachment', 'comments' ) ) $posts_columns['comments'] = '<span class="vers"><div title="' . esc_attr__( 'Comments' ) . '" class="comment-grey-bubble"></div></span>'; } /* translators: column name */ $posts_columns['date'] = _x( 'Date', 'column name' ); $posts_columns = apply_filters( 'manage_media_columns', $posts_columns, $this->detached ); return $posts_columns; } function get_sortable_columns() { return array( 'title' => 'title', 'author' => 'author', 'parent' => 'parent', 'comments' => 'comment_count', 'date' => array( 'date', true ), ); } function display_rows() { global $post, $id; add_filter( 'the_title','esc_html' ); $alt = ''; while ( have_posts() ) : the_post(); $user_can_edit = current_user_can( 'edit_post', $post->ID ); if ( $this->is_trash && $post->post_status != 'trash' || !$this->is_trash && $post->post_status == 'trash' ) continue; $alt = ( 'alternate' == $alt ) ? '' : 'alternate'; $post_owner = ( get_current_user_id() == $post->post_author ) ? 'self' : 'other'; $att_title = _draft_or_post_title(); ?> <tr id='post-<?php echo $id; ?>' class='<?php echo trim( $alt . ' author-' . $post_owner . ' status-' . $post->post_status ); ?>' valign="top"> <?php list( $columns, $hidden ) = $this->get_column_info(); foreach ( $columns as $column_name => $column_display_name ) { $class = "class='$column_name column-$column_name'"; $style = ''; if ( in_array( $column_name, $hidden ) ) $style = ' style="display:none;"'; $attributes = $class . $style; switch ( $column_name ) { case 'cb': ?> <th scope="row" class="check-column"> <?php if ( $user_can_edit ) { ?> <label class="screen-reader-text" for="cb-select-<?php the_ID(); ?>"><?php echo sprintf( __( 'Select %s' ), $att_title );?></label> <input type="checkbox" name="media[]" id="cb-select-<?php the_ID(); ?>" value="<?php the_ID(); ?>" /> <?php } ?> </th> <?php break; case 'icon': $attributes = 'class="column-icon media-icon"' . $style; ?> <td <?php echo $attributes ?>><?php if ( $thumb = wp_get_attachment_image( $post->ID, array( 80, 60 ), true ) ) { if ( $this->is_trash || ! $user_can_edit ) { echo $thumb; } else { ?> <a href="<?php echo get_edit_post_link( $post->ID, true ); ?>" title="<?php echo esc_attr( sprintf( __( 'Edit &#8220;%s&#8221;' ), $att_title ) ); ?>"> <?php echo $thumb; ?> </a> <?php } } ?> </td> <?php break; case 'title': ?> <td <?php echo $attributes ?>><strong> <?php if ( $this->is_trash || ! $user_can_edit ) { echo $att_title; } else { ?> <a href="<?php echo get_edit_post_link( $post->ID, true ); ?>" title="<?php echo esc_attr( sprintf( __( 'Edit &#8220;%s&#8221;' ), $att_title ) ); ?>"> <?php echo $att_title; ?></a> <?php }; _media_states( $post ); ?></strong> <p> <?php if ( preg_match( '/^.*?\.(\w+)$/', get_attached_file( $post->ID ), $matches ) ) echo esc_html( strtoupper( $matches[1] ) ); else echo strtoupper( str_replace( 'image/', '', get_post_mime_type() ) ); ?> </p> <?php echo $this->row_actions( $this->_get_row_actions( $post, $att_title ) ); ?> </td> <?php break; case 'author': ?> <td <?php echo $attributes ?>><?php the_author() ?></td> <?php break; case 'desc': ?> <td <?php echo $attributes ?>><?php echo has_excerpt() ? $post->post_excerpt : ''; ?></td> <?php break; case 'date': if ( '0000-00-00 00:00:00' == $post->post_date ) { $h_time = __( 'Unpublished' ); } else { $m_time = $post->post_date; $time = get_post_time( 'G', true, $post, false ); if ( ( abs( $t_diff = time() - $time ) ) < DAY_IN_SECONDS ) { if ( $t_diff < 0 ) $h_time = sprintf( __( '%s from now' ), human_time_diff( $time ) ); else $h_time = sprintf( __( '%s ago' ), human_time_diff( $time ) ); } else { $h_time = mysql2date( __( 'Y/m/d' ), $m_time ); } } ?> <td <?php echo $attributes ?>><?php echo $h_time ?></td> <?php break; case 'parent': if ( $post->post_parent > 0 ) { if ( get_post( $post->post_parent ) ) { $title =_draft_or_post_title( $post->post_parent ); } ?> <td <?php echo $attributes ?>><strong> <?php if( current_user_can( 'edit_post', $post->post_parent ) ) { ?> <a href="<?php echo get_edit_post_link( $post->post_parent ); ?>"> <?php echo $title ?></a><?php } else { echo $title; } ?></strong>, <?php echo get_the_time( __( 'Y/m/d' ) ); ?> </td> <?php } else { ?> <td <?php echo $attributes ?>><?php _e( '(Unattached)' ); ?><br /> <?php if( $user_can_edit ) {?> <a class="hide-if-no-js" onclick="findPosts.open( 'media[]','<?php echo $post->ID ?>' ); return false;" href="#the-list"> <?php _e( 'Attach' ); ?></a> <?php } ?></td> <?php } break; case 'comments': $attributes = 'class="comments column-comments num"' . $style; ?> <td <?php echo $attributes ?>> <div class="post-com-count-wrapper"> <?php $pending_comments = get_pending_comments_num( $post->ID ); $this->comments_bubble( $post->ID, $pending_comments ); ?> </div> </td> <?php break; default: if ( 'categories' == $column_name ) $taxonomy = 'category'; elseif ( 'tags' == $column_name ) $taxonomy = 'post_tag'; elseif ( 0 === strpos( $column_name, 'taxonomy-' ) ) $taxonomy = substr( $column_name, 9 ); else $taxonomy = false; if ( $taxonomy ) { $taxonomy_object = get_taxonomy( $taxonomy ); echo '<td ' . $attributes . '>'; if ( $terms = get_the_terms( $post->ID, $taxonomy ) ) { $out = array(); foreach ( $terms as $t ) { $posts_in_term_qv = array(); $posts_in_term_qv['taxonomy'] = $taxonomy; $posts_in_term_qv['term'] = $t->slug; $out[] = sprintf( '<a href="%s">%s</a>', esc_url( add_query_arg( $posts_in_term_qv, 'upload.php' ) ), esc_html( sanitize_term_field( 'name', $t->name, $t->term_id, $taxonomy, 'display' ) ) ); } /* translators: used between list items, there is a space after the comma */ echo join( __( ', ' ), $out ); } else { echo '&#8212;'; } echo '</td>'; break; } ?> <td <?php echo $attributes ?>> <?php do_action( 'manage_media_custom_column', $column_name, $id ); ?> </td> <?php break; } } ?> </tr> <?php endwhile; } function _get_row_actions( $post, $att_title ) { $actions = array(); if ( $this->detached ) { if ( current_user_can( 'edit_post', $post->ID ) ) $actions['edit'] = '<a href="' . get_edit_post_link( $post->ID, true ) . '">' . __( 'Edit' ) . '</a>'; if ( current_user_can( 'delete_post', $post->ID ) ) if ( EMPTY_TRASH_DAYS && MEDIA_TRASH ) { $actions['trash'] = "<a class='submitdelete' href='" . wp_nonce_url( "post.php?action=trash&amp;post=$post->ID", 'trash-post_' . $post->ID ) . "'>" . __( 'Trash' ) . "</a>"; } else { $delete_ays = !MEDIA_TRASH ? " onclick='return showNotice.warn();'" : ''; $actions['delete'] = "<a class='submitdelete'$delete_ays href='" . wp_nonce_url( "post.php?action=delete&amp;post=$post->ID", 'delete-post_' . $post->ID ) . "'>" . __( 'Delete Permanently' ) . "</a>"; } $actions['view'] = '<a href="' . get_permalink( $post->ID ) . '" title="' . esc_attr( sprintf( __( 'View &#8220;%s&#8221;' ), $att_title ) ) . '" rel="permalink">' . __( 'View' ) . '</a>'; if ( current_user_can( 'edit_post', $post->ID ) ) $actions['attach'] = '<a href="#the-list" onclick="findPosts.open( \'media[]\',\''.$post->ID.'\' );return false;" class="hide-if-no-js">'.__( 'Attach' ).'</a>'; } else { if ( current_user_can( 'edit_post', $post->ID ) && !$this->is_trash ) $actions['edit'] = '<a href="' . get_edit_post_link( $post->ID, true ) . '">' . __( 'Edit' ) . '</a>'; if ( current_user_can( 'delete_post', $post->ID ) ) { if ( $this->is_trash ) $actions['untrash'] = "<a class='submitdelete' href='" . wp_nonce_url( "post.php?action=untrash&amp;post=$post->ID", 'untrash-post_' . $post->ID ) . "'>" . __( 'Restore' ) . "</a>"; elseif ( EMPTY_TRASH_DAYS && MEDIA_TRASH ) $actions['trash'] = "<a class='submitdelete' href='" . wp_nonce_url( "post.php?action=trash&amp;post=$post->ID", 'trash-post_' . $post->ID ) . "'>" . __( 'Trash' ) . "</a>"; if ( $this->is_trash || !EMPTY_TRASH_DAYS || !MEDIA_TRASH ) { $delete_ays = ( !$this->is_trash && !MEDIA_TRASH ) ? " onclick='return showNotice.warn();'" : ''; $actions['delete'] = "<a class='submitdelete'$delete_ays href='" . wp_nonce_url( "post.php?action=delete&amp;post=$post->ID", 'delete-post_' . $post->ID ) . "'>" . __( 'Delete Permanently' ) . "</a>"; } } if ( !$this->is_trash ) { $title =_draft_or_post_title( $post->post_parent ); $actions['view'] = '<a href="' . get_permalink( $post->ID ) . '" title="' . esc_attr( sprintf( __( 'View &#8220;%s&#8221;' ), $title ) ) . '" rel="permalink">' . __( 'View' ) . '</a>'; } } $actions = apply_filters( 'media_row_actions', $actions, $post, $this->detached ); return $actions; } }
zyblog
trunk/zyblog/wp-admin/includes/class-wp-media-list-table.php
PHP
asf20
14,887
<?php /** * WordPress Post Administration API. * * @package WordPress * @subpackage Administration */ /** * Rename $_POST data from form names to DB post columns. * * Manipulates $_POST directly. * * @package WordPress * @since 2.6.0 * * @param bool $update Are we updating a pre-existing post? * @param array $post_data Array of post data. Defaults to the contents of $_POST. * @return object|bool WP_Error on failure, true on success. */ function _wp_translate_postdata( $update = false, $post_data = null ) { if ( empty($post_data) ) $post_data = &$_POST; if ( $update ) $post_data['ID'] = (int) $post_data['post_ID']; $ptype = get_post_type_object( $post_data['post_type'] ); if ( $update && ! current_user_can( $ptype->cap->edit_post, $post_data['ID'] ) ) { if ( 'page' == $post_data['post_type'] ) return new WP_Error( 'edit_others_pages', __( 'You are not allowed to edit pages as this user.' ) ); else return new WP_Error( 'edit_others_posts', __( 'You are not allowed to edit posts as this user.' ) ); } elseif ( ! $update && ! current_user_can( $ptype->cap->create_posts ) ) { if ( 'page' == $post_data['post_type'] ) return new WP_Error( 'edit_others_pages', __( 'You are not allowed to create pages as this user.' ) ); else return new WP_Error( 'edit_others_posts', __( 'You are not allowed to create posts as this user.' ) ); } if ( isset( $post_data['content'] ) ) $post_data['post_content'] = $post_data['content']; if ( isset( $post_data['excerpt'] ) ) $post_data['post_excerpt'] = $post_data['excerpt']; if ( isset( $post_data['parent_id'] ) ) $post_data['post_parent'] = (int) $post_data['parent_id']; if ( isset($post_data['trackback_url']) ) $post_data['to_ping'] = $post_data['trackback_url']; if ( !isset($post_data['user_ID']) ) $post_data['user_ID'] = $GLOBALS['user_ID']; if (!empty ( $post_data['post_author_override'] ) ) { $post_data['post_author'] = (int) $post_data['post_author_override']; } else { if (!empty ( $post_data['post_author'] ) ) { $post_data['post_author'] = (int) $post_data['post_author']; } else { $post_data['post_author'] = (int) $post_data['user_ID']; } } if ( ! $update && isset( $post_data['user_ID'] ) && ( $post_data['post_author'] != $post_data['user_ID'] ) && ! current_user_can( $ptype->cap->edit_others_posts ) ) { if ( 'page' == $post_data['post_type'] ) return new WP_Error( 'edit_others_pages', __( 'You are not allowed to create pages as this user.' ) ); else return new WP_Error( 'edit_others_posts', __( 'You are not allowed to create posts as this user.' ) ); } // What to do based on which button they pressed if ( isset($post_data['saveasdraft']) && '' != $post_data['saveasdraft'] ) $post_data['post_status'] = 'draft'; if ( isset($post_data['saveasprivate']) && '' != $post_data['saveasprivate'] ) $post_data['post_status'] = 'private'; if ( isset($post_data['publish']) && ( '' != $post_data['publish'] ) && ( !isset($post_data['post_status']) || $post_data['post_status'] != 'private' ) ) $post_data['post_status'] = 'publish'; if ( isset($post_data['advanced']) && '' != $post_data['advanced'] ) $post_data['post_status'] = 'draft'; if ( isset($post_data['pending']) && '' != $post_data['pending'] ) $post_data['post_status'] = 'pending'; if ( isset( $post_data['ID'] ) ) $post_id = $post_data['ID']; else $post_id = false; $previous_status = $post_id ? get_post_field( 'post_status', $post_id ) : false; // Posts 'submitted for approval' present are submitted to $_POST the same as if they were being published. // Change status from 'publish' to 'pending' if user lacks permissions to publish or to resave published posts. if ( isset($post_data['post_status']) && ('publish' == $post_data['post_status'] && !current_user_can( $ptype->cap->publish_posts )) ) if ( $previous_status != 'publish' || !current_user_can( 'edit_post', $post_id ) ) $post_data['post_status'] = 'pending'; if ( ! isset($post_data['post_status']) ) $post_data['post_status'] = $previous_status; if (!isset( $post_data['comment_status'] )) $post_data['comment_status'] = 'closed'; if (!isset( $post_data['ping_status'] )) $post_data['ping_status'] = 'closed'; foreach ( array('aa', 'mm', 'jj', 'hh', 'mn') as $timeunit ) { if ( !empty( $post_data['hidden_' . $timeunit] ) && $post_data['hidden_' . $timeunit] != $post_data[$timeunit] ) { $post_data['edit_date'] = '1'; break; } } if ( !empty( $post_data['edit_date'] ) ) { $aa = $post_data['aa']; $mm = $post_data['mm']; $jj = $post_data['jj']; $hh = $post_data['hh']; $mn = $post_data['mn']; $ss = $post_data['ss']; $aa = ($aa <= 0 ) ? date('Y') : $aa; $mm = ($mm <= 0 ) ? date('n') : $mm; $jj = ($jj > 31 ) ? 31 : $jj; $jj = ($jj <= 0 ) ? date('j') : $jj; $hh = ($hh > 23 ) ? $hh -24 : $hh; $mn = ($mn > 59 ) ? $mn -60 : $mn; $ss = ($ss > 59 ) ? $ss -60 : $ss; $post_data['post_date'] = sprintf( "%04d-%02d-%02d %02d:%02d:%02d", $aa, $mm, $jj, $hh, $mn, $ss ); $valid_date = wp_checkdate( $mm, $jj, $aa, $post_data['post_date'] ); if ( !$valid_date ) { return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) ); } $post_data['post_date_gmt'] = get_gmt_from_date( $post_data['post_date'] ); } return $post_data; } /** * Update an existing post with values provided in $_POST. * * @since 1.5.0 * * @param array $post_data Optional. * @return int Post ID. */ function edit_post( $post_data = null ) { if ( empty($post_data) ) $post_data = &$_POST; // Clear out any data in internal vars. unset( $post_data['filter'] ); $post_ID = (int) $post_data['post_ID']; $post = get_post( $post_ID ); $post_data['post_type'] = $post->post_type; $post_data['post_mime_type'] = $post->post_mime_type; $ptype = get_post_type_object($post_data['post_type']); if ( !current_user_can( $ptype->cap->edit_post, $post_ID ) ) { if ( 'page' == $post_data['post_type'] ) wp_die( __('You are not allowed to edit this page.' )); else wp_die( __('You are not allowed to edit this post.' )); } $post_data = _wp_translate_postdata( true, $post_data ); if ( is_wp_error($post_data) ) wp_die( $post_data->get_error_message() ); if ( ( empty( $post_data['action'] ) || 'autosave' != $post_data['action'] ) && 'auto-draft' == $post_data['post_status'] ) { $post_data['post_status'] = 'draft'; } if ( isset($post_data['visibility']) ) { switch ( $post_data['visibility'] ) { case 'public' : $post_data['post_password'] = ''; break; case 'password' : unset( $post_data['sticky'] ); break; case 'private' : $post_data['post_status'] = 'private'; $post_data['post_password'] = ''; unset( $post_data['sticky'] ); break; } } // Post Formats if ( isset( $post_data['post_format'] ) ) { if ( current_theme_supports( 'post-formats', $post_data['post_format'] ) ) set_post_format( $post_ID, $post_data['post_format'] ); elseif ( '0' == $post_data['post_format'] ) set_post_format( $post_ID, false ); } // Meta Stuff if ( isset($post_data['meta']) && $post_data['meta'] ) { foreach ( $post_data['meta'] as $key => $value ) { if ( !$meta = get_post_meta_by_id( $key ) ) continue; if ( $meta->post_id != $post_ID ) continue; if ( is_protected_meta( $value['key'], 'post' ) || ! current_user_can( 'edit_post_meta', $post_ID, $value['key'] ) ) continue; update_meta( $key, $value['key'], $value['value'] ); } } if ( isset($post_data['deletemeta']) && $post_data['deletemeta'] ) { foreach ( $post_data['deletemeta'] as $key => $value ) { if ( !$meta = get_post_meta_by_id( $key ) ) continue; if ( $meta->post_id != $post_ID ) continue; if ( is_protected_meta( $meta->meta_key, 'post' ) || ! current_user_can( 'delete_post_meta', $post_ID, $meta->meta_key ) ) continue; delete_meta( $key ); } } // Attachment stuff if ( 'attachment' == $post_data['post_type'] ) { if ( isset( $post_data[ '_wp_attachment_image_alt' ] ) ) { $image_alt = get_post_meta( $post_ID, '_wp_attachment_image_alt', true ); if ( $image_alt != stripslashes( $post_data['_wp_attachment_image_alt'] ) ) { $image_alt = wp_strip_all_tags( stripslashes( $post_data['_wp_attachment_image_alt'] ), true ); // update_meta expects slashed update_post_meta( $post_ID, '_wp_attachment_image_alt', addslashes( $image_alt ) ); } } $attachment_data = isset( $post_data['attachments'][ $post_ID ] ) ? $post_data['attachments'][ $post_ID ] : array(); $post_data = apply_filters( 'attachment_fields_to_save', $post_data, $attachment_data ); } add_meta( $post_ID ); update_post_meta( $post_ID, '_edit_last', $GLOBALS['current_user']->ID ); wp_update_post( $post_data ); // Now that we have an ID we can fix any attachment anchor hrefs _fix_attachment_links( $post_ID ); wp_set_post_lock( $post_ID ); if ( current_user_can( $ptype->cap->edit_others_posts ) ) { if ( ! empty( $post_data['sticky'] ) ) stick_post( $post_ID ); else unstick_post( $post_ID ); } return $post_ID; } /** * Process the post data for the bulk editing of posts. * * Updates all bulk edited posts/pages, adding (but not removing) tags and * categories. Skips pages when they would be their own parent or child. * * @since 2.7.0 * * @param array $post_data Optional, the array of post data to process if not provided will use $_POST superglobal. * @return array */ function bulk_edit_posts( $post_data = null ) { global $wpdb; if ( empty($post_data) ) $post_data = &$_POST; if ( isset($post_data['post_type']) ) $ptype = get_post_type_object($post_data['post_type']); else $ptype = get_post_type_object('post'); if ( !current_user_can( $ptype->cap->edit_posts ) ) { if ( 'page' == $ptype->name ) wp_die( __('You are not allowed to edit pages.')); else wp_die( __('You are not allowed to edit posts.')); } if ( -1 == $post_data['_status'] ) { $post_data['post_status'] = null; unset($post_data['post_status']); } else { $post_data['post_status'] = $post_data['_status']; } unset($post_data['_status']); $post_IDs = array_map( 'intval', (array) $post_data['post'] ); $reset = array( 'post_author', 'post_status', 'post_password', 'post_parent', 'page_template', 'comment_status', 'ping_status', 'keep_private', 'tax_input', 'post_category', 'sticky' ); foreach ( $reset as $field ) { if ( isset($post_data[$field]) && ( '' == $post_data[$field] || -1 == $post_data[$field] ) ) unset($post_data[$field]); } if ( isset($post_data['post_category']) ) { if ( is_array($post_data['post_category']) && ! empty($post_data['post_category']) ) $new_cats = array_map( 'absint', $post_data['post_category'] ); else unset($post_data['post_category']); } $tax_input = array(); if ( isset($post_data['tax_input'])) { foreach ( $post_data['tax_input'] as $tax_name => $terms ) { if ( empty($terms) ) continue; if ( is_taxonomy_hierarchical( $tax_name ) ) { $tax_input[ $tax_name ] = array_map( 'absint', $terms ); } else { $comma = _x( ',', 'tag delimiter' ); if ( ',' !== $comma ) $terms = str_replace( $comma, ',', $terms ); $tax_input[ $tax_name ] = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) ); } } } if ( isset($post_data['post_parent']) && ($parent = (int) $post_data['post_parent']) ) { $pages = $wpdb->get_results("SELECT ID, post_parent FROM $wpdb->posts WHERE post_type = 'page'"); $children = array(); for ( $i = 0; $i < 50 && $parent > 0; $i++ ) { $children[] = $parent; foreach ( $pages as $page ) { if ( $page->ID == $parent ) { $parent = $page->post_parent; break; } } } } if ( isset( $post_data['post_format'] ) ) { if ( '0' == $post_data['post_format'] ) $post_data['post_format'] = false; // don't change the post format if it's not supported or not '0' (standard) elseif ( ! current_theme_supports( 'post-formats', $post_data['post_format'] ) ) unset( $post_data['post_format'] ); } $updated = $skipped = $locked = array(); foreach ( $post_IDs as $post_ID ) { $post_type_object = get_post_type_object( get_post_type( $post_ID ) ); if ( !isset( $post_type_object ) || ( isset($children) && in_array($post_ID, $children) ) || !current_user_can( $post_type_object->cap->edit_post, $post_ID ) ) { $skipped[] = $post_ID; continue; } if ( wp_check_post_lock( $post_ID ) ) { $locked[] = $post_ID; continue; } $post = get_post( $post_ID ); $tax_names = get_object_taxonomies( $post ); foreach ( $tax_names as $tax_name ) { $taxonomy_obj = get_taxonomy($tax_name); if ( isset( $tax_input[$tax_name]) && current_user_can( $taxonomy_obj->cap->assign_terms ) ) $new_terms = $tax_input[$tax_name]; else $new_terms = array(); if ( $taxonomy_obj->hierarchical ) $current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array('fields' => 'ids') ); else $current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array('fields' => 'names') ); $post_data['tax_input'][$tax_name] = array_merge( $current_terms, $new_terms ); } if ( isset($new_cats) && in_array( 'category', $tax_names ) ) { $cats = (array) wp_get_post_categories($post_ID); $post_data['post_category'] = array_unique( array_merge($cats, $new_cats) ); unset( $post_data['tax_input']['category'] ); } $post_data['post_mime_type'] = $post->post_mime_type; $post_data['guid'] = $post->guid; $post_data['ID'] = $post_ID; $updated[] = wp_update_post( $post_data ); if ( isset( $post_data['sticky'] ) && current_user_can( $ptype->cap->edit_others_posts ) ) { if ( 'sticky' == $post_data['sticky'] ) stick_post( $post_ID ); else unstick_post( $post_ID ); } if ( isset( $post_data['post_format'] ) ) set_post_format( $post_ID, $post_data['post_format'] ); } return array( 'updated' => $updated, 'skipped' => $skipped, 'locked' => $locked ); } /** * Default post information to use when populating the "Write Post" form. * * @since 2.0.0 * * @param string $post_type A post type string, defaults to 'post'. * @return WP_Post Post object containing all the default post data as attributes */ function get_default_post_to_edit( $post_type = 'post', $create_in_db = false ) { global $wpdb; $post_title = ''; if ( !empty( $_REQUEST['post_title'] ) ) $post_title = esc_html( stripslashes( $_REQUEST['post_title'] )); $post_content = ''; if ( !empty( $_REQUEST['content'] ) ) $post_content = esc_html( stripslashes( $_REQUEST['content'] )); $post_excerpt = ''; if ( !empty( $_REQUEST['excerpt'] ) ) $post_excerpt = esc_html( stripslashes( $_REQUEST['excerpt'] )); if ( $create_in_db ) { $post_id = wp_insert_post( array( 'post_title' => __( 'Auto Draft' ), 'post_type' => $post_type, 'post_status' => 'auto-draft' ) ); $post = get_post( $post_id ); if ( current_theme_supports( 'post-formats' ) && post_type_supports( $post->post_type, 'post-formats' ) && get_option( 'default_post_format' ) ) set_post_format( $post, get_option( 'default_post_format' ) ); } else { $post = new stdClass; $post->ID = 0; $post->post_author = ''; $post->post_date = ''; $post->post_date_gmt = ''; $post->post_password = ''; $post->post_type = $post_type; $post->post_status = 'draft'; $post->to_ping = ''; $post->pinged = ''; $post->comment_status = get_option( 'default_comment_status' ); $post->ping_status = get_option( 'default_ping_status' ); $post->post_pingback = get_option( 'default_pingback_flag' ); $post->post_category = get_option( 'default_category' ); $post->page_template = 'default'; $post->post_parent = 0; $post->menu_order = 0; $post = new WP_Post( $post ); } $post->post_content = apply_filters( 'default_content', $post_content, $post ); $post->post_title = apply_filters( 'default_title', $post_title, $post ); $post->post_excerpt = apply_filters( 'default_excerpt', $post_excerpt, $post ); $post->post_name = ''; return $post; } /** * Determine if a post exists based on title, content, and date * * @since 2.0.0 * * @param string $title Post title * @param string $content Optional post content * @param string $date Optional post date * @return int Post ID if post exists, 0 otherwise. */ function post_exists($title, $content = '', $date = '') { global $wpdb; $post_title = stripslashes( sanitize_post_field( 'post_title', $title, 0, 'db' ) ); $post_content = stripslashes( sanitize_post_field( 'post_content', $content, 0, 'db' ) ); $post_date = stripslashes( sanitize_post_field( 'post_date', $date, 0, 'db' ) ); $query = "SELECT ID FROM $wpdb->posts WHERE 1=1"; $args = array(); if ( !empty ( $date ) ) { $query .= ' AND post_date = %s'; $args[] = $post_date; } if ( !empty ( $title ) ) { $query .= ' AND post_title = %s'; $args[] = $post_title; } if ( !empty ( $content ) ) { $query .= 'AND post_content = %s'; $args[] = $post_content; } if ( !empty ( $args ) ) return (int) $wpdb->get_var( $wpdb->prepare($query, $args) ); return 0; } /** * Creates a new post from the "Write Post" form using $_POST information. * * @since 2.1.0 * * @return unknown */ function wp_write_post() { global $user_ID; if ( isset($_POST['post_type']) ) $ptype = get_post_type_object($_POST['post_type']); else $ptype = get_post_type_object('post'); if ( !current_user_can( $ptype->cap->edit_posts ) ) { if ( 'page' == $ptype->name ) return new WP_Error( 'edit_pages', __( 'You are not allowed to create pages on this site.' ) ); else return new WP_Error( 'edit_posts', __( 'You are not allowed to create posts or drafts on this site.' ) ); } $_POST['post_mime_type'] = ''; // Clear out any data in internal vars. unset( $_POST['filter'] ); // Edit don't write if we have a post id. if ( isset( $_POST['post_ID'] ) ) return edit_post(); $translated = _wp_translate_postdata( false ); if ( is_wp_error($translated) ) return $translated; if ( isset($_POST['visibility']) ) { switch ( $_POST['visibility'] ) { case 'public' : $_POST['post_password'] = ''; break; case 'password' : unset( $_POST['sticky'] ); break; case 'private' : $_POST['post_status'] = 'private'; $_POST['post_password'] = ''; unset( $_POST['sticky'] ); break; } } // Create the post. $post_ID = wp_insert_post( $_POST ); if ( is_wp_error( $post_ID ) ) return $post_ID; if ( empty($post_ID) ) return 0; add_meta( $post_ID ); add_post_meta( $post_ID, '_edit_last', $GLOBALS['current_user']->ID ); // Now that we have an ID we can fix any attachment anchor hrefs _fix_attachment_links( $post_ID ); wp_set_post_lock( $post_ID ); return $post_ID; } /** * Calls wp_write_post() and handles the errors. * * @since 2.0.0 * @uses wp_write_post() * @uses is_wp_error() * @uses wp_die() * @return unknown */ function write_post() { $result = wp_write_post(); if ( is_wp_error( $result ) ) wp_die( $result->get_error_message() ); else return $result; } // // Post Meta // /** * {@internal Missing Short Description}} * * @since 1.2.0 * * @param unknown_type $post_ID * @return unknown */ function add_meta( $post_ID ) { global $wpdb; $post_ID = (int) $post_ID; $metakeyselect = isset($_POST['metakeyselect']) ? stripslashes( trim( $_POST['metakeyselect'] ) ) : ''; $metakeyinput = isset($_POST['metakeyinput']) ? stripslashes( trim( $_POST['metakeyinput'] ) ) : ''; $metavalue = isset($_POST['metavalue']) ? $_POST['metavalue'] : ''; if ( is_string( $metavalue ) ) $metavalue = trim( $metavalue ); if ( ('0' === $metavalue || ! empty ( $metavalue ) ) && ( ( ( '#NONE#' != $metakeyselect ) && !empty ( $metakeyselect) ) || !empty ( $metakeyinput ) ) ) { // We have a key/value pair. If both the select and the // input for the key have data, the input takes precedence: if ( '#NONE#' != $metakeyselect ) $metakey = $metakeyselect; if ( $metakeyinput ) $metakey = $metakeyinput; // default if ( is_protected_meta( $metakey, 'post' ) || ! current_user_can( 'add_post_meta', $post_ID, $metakey ) ) return false; $metakey = esc_sql( $metakey ); return add_post_meta( $post_ID, $metakey, $metavalue ); } return false; } // add_meta /** * {@internal Missing Short Description}} * * @since 1.2.0 * * @param unknown_type $mid * @return unknown */ function delete_meta( $mid ) { return delete_metadata_by_mid( 'post' , $mid ); } /** * Get a list of previously defined keys. * * @since 1.2.0 * * @return unknown */ function get_meta_keys() { global $wpdb; $keys = $wpdb->get_col( " SELECT meta_key FROM $wpdb->postmeta GROUP BY meta_key ORDER BY meta_key" ); return $keys; } /** * {@internal Missing Short Description}} * * @since 2.1.0 * * @param unknown_type $mid * @return unknown */ function get_post_meta_by_id( $mid ) { return get_metadata_by_mid( 'post', $mid ); } /** * {@internal Missing Short Description}} * * Some postmeta stuff. * * @since 1.2.0 * * @param unknown_type $postid * @return unknown */ function has_meta( $postid ) { global $wpdb; return $wpdb->get_results( $wpdb->prepare("SELECT meta_key, meta_value, meta_id, post_id FROM $wpdb->postmeta WHERE post_id = %d ORDER BY meta_key,meta_id", $postid), ARRAY_A ); } /** * {@internal Missing Short Description}} * * @since 1.2.0 * * @param unknown_type $meta_id * @param unknown_type $meta_key Expect Slashed * @param unknown_type $meta_value Expect Slashed * @return unknown */ function update_meta( $meta_id, $meta_key, $meta_value ) { $meta_key = stripslashes( $meta_key ); $meta_value = stripslashes_deep( $meta_value ); return update_metadata_by_mid( 'post', $meta_id, $meta_value, $meta_key ); } // // Private // /** * Replace hrefs of attachment anchors with up-to-date permalinks. * * @since 2.3.0 * @access private * * @param unknown_type $post_ID * @return unknown */ function _fix_attachment_links( $post_ID ) { $post = get_post( $post_ID, ARRAY_A ); $content = $post['post_content']; // quick sanity check, don't run if no pretty permalinks or post is not published if ( !get_option('permalink_structure') || $post['post_status'] != 'publish' ) return; // Short if there aren't any links or no '?attachment_id=' strings (strpos cannot be zero) if ( !strpos($content, '?attachment_id=') || !preg_match_all( '/<a ([^>]+)>[\s\S]+?<\/a>/', $content, $link_matches ) ) return; $site_url = get_bloginfo('url'); $site_url = substr( $site_url, (int) strpos($site_url, '://') ); // remove the http(s) $replace = ''; foreach ( $link_matches[1] as $key => $value ) { if ( !strpos($value, '?attachment_id=') || !strpos($value, 'wp-att-') || !preg_match( '/href=(["\'])[^"\']*\?attachment_id=(\d+)[^"\']*\\1/', $value, $url_match ) || !preg_match( '/rel=["\'][^"\']*wp-att-(\d+)/', $value, $rel_match ) ) continue; $quote = $url_match[1]; // the quote (single or double) $url_id = (int) $url_match[2]; $rel_id = (int) $rel_match[1]; if ( !$url_id || !$rel_id || $url_id != $rel_id || strpos($url_match[0], $site_url) === false ) continue; $link = $link_matches[0][$key]; $replace = str_replace( $url_match[0], 'href=' . $quote . get_attachment_link( $url_id ) . $quote, $link ); $content = str_replace( $link, $replace, $content ); } if ( $replace ) { $post['post_content'] = $content; // Escape data pulled from DB. $post = add_magic_quotes($post); return wp_update_post($post); } } /** * Move child posts to a new parent. * * @since 2.3.0 * @access private * * @param unknown_type $old_ID * @param unknown_type $new_ID * @return unknown */ function _relocate_children( $old_ID, $new_ID ) { global $wpdb; $old_ID = (int) $old_ID; $new_ID = (int) $new_ID; $children = $wpdb->get_col( $wpdb->prepare(" SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_temp_parent' AND meta_value = %d", $old_ID) ); foreach ( $children as $child_id ) { $wpdb->update($wpdb->posts, array('post_parent' => $new_ID), array('ID' => $child_id) ); delete_post_meta($child_id, '_wp_attachment_temp_parent'); } } /** * Get all the possible statuses for a post_type * * @since 2.5.0 * * @param string $type The post_type you want the statuses for * @return array As array of all the statuses for the supplied post type */ function get_available_post_statuses($type = 'post') { $stati = wp_count_posts($type); return array_keys(get_object_vars($stati)); } /** * Run the wp query to fetch the posts for listing on the edit posts page * * @since 2.5.0 * * @param array|bool $q Array of query variables to use to build the query or false to use $_GET superglobal. * @return array */ function wp_edit_posts_query( $q = false ) { if ( false === $q ) $q = $_GET; $q['m'] = isset($q['m']) ? (int) $q['m'] : 0; $q['cat'] = isset($q['cat']) ? (int) $q['cat'] : 0; $post_stati = get_post_stati(); if ( isset($q['post_type']) && in_array( $q['post_type'], get_post_types() ) ) $post_type = $q['post_type']; else $post_type = 'post'; $avail_post_stati = get_available_post_statuses($post_type); if ( isset($q['post_status']) && in_array( $q['post_status'], $post_stati ) ) { $post_status = $q['post_status']; $perm = 'readable'; } if ( isset($q['orderby']) ) $orderby = $q['orderby']; elseif ( isset($q['post_status']) && in_array($q['post_status'], array('pending', 'draft')) ) $orderby = 'modified'; if ( isset($q['order']) ) $order = $q['order']; elseif ( isset($q['post_status']) && 'pending' == $q['post_status'] ) $order = 'ASC'; $per_page = 'edit_' . $post_type . '_per_page'; $posts_per_page = (int) get_user_option( $per_page ); if ( empty( $posts_per_page ) || $posts_per_page < 1 ) $posts_per_page = 20; $posts_per_page = apply_filters( $per_page, $posts_per_page ); $posts_per_page = apply_filters( 'edit_posts_per_page', $posts_per_page, $post_type ); $query = compact('post_type', 'post_status', 'perm', 'order', 'orderby', 'posts_per_page'); // Hierarchical types require special args. if ( is_post_type_hierarchical( $post_type ) && !isset($orderby) ) { $query['orderby'] = 'menu_order title'; $query['order'] = 'asc'; $query['posts_per_page'] = -1; $query['posts_per_archive_page'] = -1; } if ( ! empty( $q['show_sticky'] ) ) $query['post__in'] = (array) get_option( 'sticky_posts' ); wp( $query ); return $avail_post_stati; } /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @param unknown_type $type * @return unknown */ function get_available_post_mime_types($type = 'attachment') { global $wpdb; $types = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_mime_type FROM $wpdb->posts WHERE post_type = %s", $type)); return $types; } /** * Executes a query for attachments. An array of WP_Query arguments * can be passed in, which will override the arguments set by this function. * * @since 2.5.0 * @uses apply_filters() Calls 'upload_per_page' on posts_per_page argument * * @param array|bool $q Array of query variables to use to build the query or false to use $_GET superglobal. * @return array */ function wp_edit_attachments_query( $q = false ) { if ( false === $q ) $q = $_GET; $q['m'] = isset( $q['m'] ) ? (int) $q['m'] : 0; $q['cat'] = isset( $q['cat'] ) ? (int) $q['cat'] : 0; $q['post_type'] = 'attachment'; $post_type = get_post_type_object( 'attachment' ); $states = 'inherit'; if ( current_user_can( $post_type->cap->read_private_posts ) ) $states .= ',private'; $q['post_status'] = isset( $q['status'] ) && 'trash' == $q['status'] ? 'trash' : $states; $media_per_page = (int) get_user_option( 'upload_per_page' ); if ( empty( $media_per_page ) || $media_per_page < 1 ) $media_per_page = 20; $q['posts_per_page'] = apply_filters( 'upload_per_page', $media_per_page ); $post_mime_types = get_post_mime_types(); $avail_post_mime_types = get_available_post_mime_types('attachment'); if ( isset($q['post_mime_type']) && !array_intersect( (array) $q['post_mime_type'], array_keys($post_mime_types) ) ) unset($q['post_mime_type']); if ( isset($q['detached']) ) add_filter('posts_where', '_edit_attachments_query_helper'); wp( $q ); if ( isset($q['detached']) ) remove_filter('posts_where', '_edit_attachments_query_helper'); return array($post_mime_types, $avail_post_mime_types); } function _edit_attachments_query_helper($where) { global $wpdb; return $where .= " AND {$wpdb->posts}.post_parent < 1"; } /** * Returns the list of classes to be used by a metabox * * @uses get_user_option() * @since 2.5.0 * * @param unknown_type $id * @param unknown_type $page * @return unknown */ function postbox_classes( $id, $page ) { if ( isset( $_GET['edit'] ) && $_GET['edit'] == $id ) { $classes = array( '' ); } elseif ( $closed = get_user_option('closedpostboxes_'.$page ) ) { if ( !is_array( $closed ) ) { $classes = array( '' ); } else { $classes = in_array( $id, $closed ) ? array( 'closed' ) : array( '' ); } } else { $classes = array( '' ); } $classes = apply_filters( "postbox_classes_{$page}_{$id}", $classes ); return implode( ' ', $classes ); } /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @param int|object $id Post ID or post object. * @param string $title (optional) Title * @param string $name (optional) Name * @return array With two entries of type string */ function get_sample_permalink($id, $title = null, $name = null) { $post = get_post($id); if ( !$post->ID ) return array('', ''); $ptype = get_post_type_object($post->post_type); $original_status = $post->post_status; $original_date = $post->post_date; $original_name = $post->post_name; // Hack: get_permalink would return ugly permalink for // drafts, so we will fake, that our post is published if ( in_array($post->post_status, array('draft', 'pending')) ) { $post->post_status = 'publish'; $post->post_name = sanitize_title($post->post_name ? $post->post_name : $post->post_title, $post->ID); } // If the user wants to set a new name -- override the current one // Note: if empty name is supplied -- use the title instead, see #6072 if ( !is_null($name) ) $post->post_name = sanitize_title($name ? $name : $title, $post->ID); $post->post_name = wp_unique_post_slug($post->post_name, $post->ID, $post->post_status, $post->post_type, $post->post_parent); $post->filter = 'sample'; $permalink = get_permalink($post, true); // Replace custom post_type Token with generic pagename token for ease of use. $permalink = str_replace("%$post->post_type%", '%pagename%', $permalink); // Handle page hierarchy if ( $ptype->hierarchical ) { $uri = get_page_uri($post); $uri = untrailingslashit($uri); $uri = strrev( stristr( strrev( $uri ), '/' ) ); $uri = untrailingslashit($uri); $uri = apply_filters( 'editable_slug', $uri ); if ( !empty($uri) ) $uri .= '/'; $permalink = str_replace('%pagename%', "{$uri}%pagename%", $permalink); } $permalink = array($permalink, apply_filters('editable_slug', $post->post_name)); $post->post_status = $original_status; $post->post_date = $original_date; $post->post_name = $original_name; unset($post->filter); return $permalink; } /** * Returns the HTML of the sample permalink slug editor. * * @since 2.5.0 * * @param int|object $id Post ID or post object. * @param string $new_title Optional. New title. * @param string $new_slug Optional. New slug. * @return string The HTML of the sample permalink slug editor. */ function get_sample_permalink_html( $id, $new_title = null, $new_slug = null ) { global $wpdb; $post = get_post($id); list($permalink, $post_name) = get_sample_permalink($post->ID, $new_title, $new_slug); if ( 'publish' == get_post_status( $post ) ) { $ptype = get_post_type_object($post->post_type); $view_post = $ptype->labels->view_item; $title = __('Click to edit this part of the permalink'); } else { $title = __('Temporary permalink. Click to edit this part.'); } if ( false === strpos($permalink, '%postname%') && false === strpos($permalink, '%pagename%') ) { $return = '<strong>' . __('Permalink:') . "</strong>\n" . '<span id="sample-permalink" tabindex="-1">' . $permalink . "</span>\n"; if ( '' == get_option( 'permalink_structure' ) && current_user_can( 'manage_options' ) && !( 'page' == get_option('show_on_front') && $id == get_option('page_on_front') ) ) $return .= '<span id="change-permalinks"><a href="options-permalink.php" class="button button-small" target="_blank">' . __('Change Permalinks') . "</a></span>\n"; if ( isset( $view_post ) ) $return .= "<span id='view-post-btn'><a href='$permalink' class='button button-small'>$view_post</a></span>\n"; $return = apply_filters('get_sample_permalink_html', $return, $id, $new_title, $new_slug); return $return; } if ( function_exists('mb_strlen') ) { if ( mb_strlen($post_name) > 30 ) { $post_name_abridged = mb_substr($post_name, 0, 14). '&hellip;' . mb_substr($post_name, -14); } else { $post_name_abridged = $post_name; } } else { if ( strlen($post_name) > 30 ) { $post_name_abridged = substr($post_name, 0, 14). '&hellip;' . substr($post_name, -14); } else { $post_name_abridged = $post_name; } } $post_name_html = '<span id="editable-post-name" title="' . $title . '">' . $post_name_abridged . '</span>'; $display_link = str_replace(array('%pagename%','%postname%'), $post_name_html, $permalink); $view_link = str_replace(array('%pagename%','%postname%'), $post_name, $permalink); $return = '<strong>' . __('Permalink:') . "</strong>\n"; $return .= '<span id="sample-permalink" tabindex="-1">' . $display_link . "</span>\n"; $return .= '&lrm;'; // Fix bi-directional text display defect in RTL languages. $return .= '<span id="edit-slug-buttons"><a href="#post_name" class="edit-slug button button-small hide-if-no-js" onclick="editPermalink(' . $id . '); return false;">' . __('Edit') . "</a></span>\n"; $return .= '<span id="editable-post-name-full">' . $post_name . "</span>\n"; if ( isset($view_post) ) $return .= "<span id='view-post-btn'><a href='$view_link' class='button button-small'>$view_post</a></span>\n"; $return = apply_filters('get_sample_permalink_html', $return, $id, $new_title, $new_slug); return $return; } /** * Output HTML for the post thumbnail meta-box. * * @since 2.9.0 * * @param int $thumbnail_id ID of the attachment used for thumbnail * @param mixed $post The post ID or object associated with the thumbnail, defaults to global $post. * @return string html */ function _wp_post_thumbnail_html( $thumbnail_id = null, $post = null ) { global $content_width, $_wp_additional_image_sizes; $post = get_post( $post ); $upload_iframe_src = esc_url( get_upload_iframe_src('image', $post->ID ) ); $set_thumbnail_link = '<p class="hide-if-no-js"><a title="' . esc_attr__( 'Set featured image' ) . '" href="%s" id="set-post-thumbnail" class="thickbox">%s</a></p>'; $content = sprintf( $set_thumbnail_link, $upload_iframe_src, esc_html__( 'Set featured image' ) ); if ( $thumbnail_id && get_post( $thumbnail_id ) ) { $old_content_width = $content_width; $content_width = 266; if ( !isset( $_wp_additional_image_sizes['post-thumbnail'] ) ) $thumbnail_html = wp_get_attachment_image( $thumbnail_id, array( $content_width, $content_width ) ); else $thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'post-thumbnail' ); if ( !empty( $thumbnail_html ) ) { $ajax_nonce = wp_create_nonce( 'set_post_thumbnail-' . $post->ID ); $content = sprintf( $set_thumbnail_link, $upload_iframe_src, $thumbnail_html ); $content .= '<p class="hide-if-no-js"><a href="#" id="remove-post-thumbnail" onclick="WPRemoveThumbnail(\'' . $ajax_nonce . '\');return false;">' . esc_html__( 'Remove featured image' ) . '</a></p>'; } $content_width = $old_content_width; } return apply_filters( 'admin_post_thumbnail_html', $content, $post->ID ); } /** * Check to see if the post is currently being edited by another user. * * @since 2.5.0 * * @param int $post_id ID of the post to check for editing * @return bool|int False: not locked or locked by current user. Int: user ID of user with lock. */ function wp_check_post_lock( $post_id ) { if ( !$post = get_post( $post_id ) ) return false; if ( !$lock = get_post_meta( $post->ID, '_edit_lock', true ) ) return false; $lock = explode( ':', $lock ); $time = $lock[0]; $user = isset( $lock[1] ) ? $lock[1] : get_post_meta( $post->ID, '_edit_last', true ); $time_window = apply_filters( 'wp_check_post_lock_window', AUTOSAVE_INTERVAL * 2 ); if ( $time && $time > time() - $time_window && $user != get_current_user_id() ) return $user; return false; } /** * Mark the post as currently being edited by the current user * * @since 2.5.0 * * @param int $post_id ID of the post to being edited * @return bool|array Returns false if the post doesn't exist of there is no current user, or * an array of the lock time and the user ID. */ function wp_set_post_lock( $post_id ) { if ( !$post = get_post( $post_id ) ) return false; if ( 0 == ($user_id = get_current_user_id()) ) return false; $now = time(); $lock = "$now:$user_id"; update_post_meta( $post->ID, '_edit_lock', $lock ); return array( $now, $user_id ); } /** * Outputs the notice message to say that someone else is editing this post at the moment. * * @since 2.8.5 * @return none */ function _admin_notice_post_locked() { $post = get_post(); $lock = explode( ':', get_post_meta( $post->ID, '_edit_lock', true ) ); $user = isset( $lock[1] ) ? $lock[1] : get_post_meta( $post->ID, '_edit_last', true ); $last_user = get_userdata( $user ); $last_user_name = $last_user ? $last_user->display_name : __('Somebody'); switch ($post->post_type) { case 'post': $message = __( 'Warning: %s is currently editing this post' ); break; case 'page': $message = __( 'Warning: %s is currently editing this page' ); break; default: $message = __( 'Warning: %s is currently editing this.' ); } $message = sprintf( $message, esc_html( $last_user_name ) ); echo "<div class='error'><p>$message</p></div>"; } /** * Creates autosave data for the specified post from $_POST data. * * @package WordPress * @subpackage Post_Revisions * @since 2.6.0 * * @uses _wp_translate_postdata() * @uses _wp_post_revision_fields() * * @return unknown */ function wp_create_post_autosave( $post_id ) { $translated = _wp_translate_postdata( true ); if ( is_wp_error( $translated ) ) return $translated; // Only store one autosave. If there is already an autosave, overwrite it. if ( $old_autosave = wp_get_post_autosave( $post_id ) ) { $new_autosave = _wp_post_revision_fields( $_POST, true ); $new_autosave['ID'] = $old_autosave->ID; $new_autosave['post_author'] = get_current_user_id(); return wp_update_post( $new_autosave ); } // _wp_put_post_revision() expects unescaped. $_POST = stripslashes_deep($_POST); // Otherwise create the new autosave as a special post revision return _wp_put_post_revision( $_POST, true ); } /** * Save draft or manually autosave for showing preview. * * @package WordPress * @since 2.7.0 * * @uses get_post_status() * @uses edit_post() * @uses get_post() * @uses current_user_can() * @uses wp_die() * @uses wp_create_post_autosave() * @uses add_query_arg() * @uses wp_create_nonce() * * @return str URL to redirect to show the preview */ function post_preview() { $post_ID = (int) $_POST['post_ID']; $status = get_post_status( $post_ID ); if ( 'auto-draft' == $status ) wp_die( __('Preview not available. Please save as a draft first.') ); if ( isset($_POST['catslist']) ) $_POST['post_category'] = explode(",", $_POST['catslist']); if ( isset($_POST['tags_input']) ) $_POST['tags_input'] = explode(",", $_POST['tags_input']); if ( $_POST['post_type'] == 'page' || empty($_POST['post_category']) ) unset($_POST['post_category']); $_POST['ID'] = $post_ID; $post = get_post($post_ID); if ( 'page' == $post->post_type ) { if ( !current_user_can('edit_page', $post_ID) ) wp_die(__('You are not allowed to edit this page.')); } else { if ( !current_user_can('edit_post', $post_ID) ) wp_die(__('You are not allowed to edit this post.')); } if ( 'draft' == $post->post_status ) { $id = edit_post(); } else { // Non drafts are not overwritten. The autosave is stored in a special post revision. $id = wp_create_post_autosave( $post->ID ); if ( ! is_wp_error($id) ) $id = $post->ID; } if ( is_wp_error($id) ) wp_die( $id->get_error_message() ); if ( $_POST['post_status'] == 'draft' ) { $url = add_query_arg( 'preview', 'true', get_permalink($id) ); } else { $nonce = wp_create_nonce('post_preview_' . $id); $url = add_query_arg( array( 'preview' => 'true', 'preview_id' => $id, 'preview_nonce' => $nonce ), get_permalink($id) ); } return $url; }
zyblog
trunk/zyblog/wp-admin/includes/post.php
PHP
asf20
41,151
<?php /** * PemFTP - A Ftp implementation in pure PHP * * @package PemFTP * @since 2.5 * * @version 1.0 * @copyright Alexey Dotsenko * @author Alexey Dotsenko * @link http://www.phpclasses.org/browse/package/1743.html Site * @license LGPL License http://www.opensource.org/licenses/lgpl-license.html */ /** * Defines the newline characters, if not defined already. * * This can be redefined. * * @since 2.5 * @var string */ if(!defined('CRLF')) define('CRLF',"\r\n"); /** * Sets whatever to autodetect ASCII mode. * * This can be redefined. * * @since 2.5 * @var int */ if(!defined("FTP_AUTOASCII")) define("FTP_AUTOASCII", -1); /** * * This can be redefined. * @since 2.5 * @var int */ if(!defined("FTP_BINARY")) define("FTP_BINARY", 1); /** * * This can be redefined. * @since 2.5 * @var int */ if(!defined("FTP_ASCII")) define("FTP_ASCII", 0); /** * Whether to force FTP. * * This can be redefined. * * @since 2.5 * @var bool */ if(!defined('FTP_FORCE')) define('FTP_FORCE', true); /** * @since 2.5 * @var string */ define('FTP_OS_Unix','u'); /** * @since 2.5 * @var string */ define('FTP_OS_Windows','w'); /** * @since 2.5 * @var string */ define('FTP_OS_Mac','m'); /** * PemFTP base class * */ class ftp_base { /* Public variables */ var $LocalEcho; var $Verbose; var $OS_local; var $OS_remote; /* Private variables */ var $_lastaction; var $_errors; var $_type; var $_umask; var $_timeout; var $_passive; var $_host; var $_fullhost; var $_port; var $_datahost; var $_dataport; var $_ftp_control_sock; var $_ftp_data_sock; var $_ftp_temp_sock; var $_ftp_buff_size; var $_login; var $_password; var $_connected; var $_ready; var $_code; var $_message; var $_can_restore; var $_port_available; var $_curtype; var $_features; var $_error_array; var $AuthorizedTransferMode; var $OS_FullName; var $_eol_code; var $AutoAsciiExt; /* Constructor */ function ftp_base($port_mode=FALSE) { $this->__construct($port_mode); } function __construct($port_mode=FALSE, $verb=FALSE, $le=FALSE) { $this->LocalEcho=$le; $this->Verbose=$verb; $this->_lastaction=NULL; $this->_error_array=array(); $this->_eol_code=array(FTP_OS_Unix=>"\n", FTP_OS_Mac=>"\r", FTP_OS_Windows=>"\r\n"); $this->AuthorizedTransferMode=array(FTP_AUTOASCII, FTP_ASCII, FTP_BINARY); $this->OS_FullName=array(FTP_OS_Unix => 'UNIX', FTP_OS_Windows => 'WINDOWS', FTP_OS_Mac => 'MACOS'); $this->AutoAsciiExt=array("ASP","BAT","C","CPP","CSS","CSV","JS","H","HTM","HTML","SHTML","INI","LOG","PHP3","PHTML","PL","PERL","SH","SQL","TXT"); $this->_port_available=($port_mode==TRUE); $this->SendMSG("Staring FTP client class".($this->_port_available?"":" without PORT mode support")); $this->_connected=FALSE; $this->_ready=FALSE; $this->_can_restore=FALSE; $this->_code=0; $this->_message=""; $this->_ftp_buff_size=4096; $this->_curtype=NULL; $this->SetUmask(0022); $this->SetType(FTP_AUTOASCII); $this->SetTimeout(30); $this->Passive(!$this->_port_available); $this->_login="anonymous"; $this->_password="anon@ftp.com"; $this->_features=array(); $this->OS_local=FTP_OS_Unix; $this->OS_remote=FTP_OS_Unix; $this->features=array(); if(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $this->OS_local=FTP_OS_Windows; elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'MAC') $this->OS_local=FTP_OS_Mac; } // <!-- --------------------------------------------------------------------------------------- --> // <!-- Public functions --> // <!-- --------------------------------------------------------------------------------------- --> function parselisting($line) { $is_windows = ($this->OS_remote == FTP_OS_Windows); if ($is_windows && preg_match("/([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|<DIR>) +(.+)/",$line,$lucifer)) { $b = array(); if ($lucifer[3]<70) { $lucifer[3]+=2000; } else { $lucifer[3]+=1900; } // 4digit year fix $b['isdir'] = ($lucifer[7]=="<DIR>"); if ( $b['isdir'] ) $b['type'] = 'd'; else $b['type'] = 'f'; $b['size'] = $lucifer[7]; $b['month'] = $lucifer[1]; $b['day'] = $lucifer[2]; $b['year'] = $lucifer[3]; $b['hour'] = $lucifer[4]; $b['minute'] = $lucifer[5]; $b['time'] = @mktime($lucifer[4]+(strcasecmp($lucifer[6],"PM")==0?12:0),$lucifer[5],0,$lucifer[1],$lucifer[2],$lucifer[3]); $b['am/pm'] = $lucifer[6]; $b['name'] = $lucifer[8]; } else if (!$is_windows && $lucifer=preg_split("/[ ]/",$line,9,PREG_SPLIT_NO_EMPTY)) { //echo $line."\n"; $lcount=count($lucifer); if ($lcount<8) return ''; $b = array(); $b['isdir'] = $lucifer[0]{0} === "d"; $b['islink'] = $lucifer[0]{0} === "l"; if ( $b['isdir'] ) $b['type'] = 'd'; elseif ( $b['islink'] ) $b['type'] = 'l'; else $b['type'] = 'f'; $b['perms'] = $lucifer[0]; $b['number'] = $lucifer[1]; $b['owner'] = $lucifer[2]; $b['group'] = $lucifer[3]; $b['size'] = $lucifer[4]; if ($lcount==8) { sscanf($lucifer[5],"%d-%d-%d",$b['year'],$b['month'],$b['day']); sscanf($lucifer[6],"%d:%d",$b['hour'],$b['minute']); $b['time'] = @mktime($b['hour'],$b['minute'],0,$b['month'],$b['day'],$b['year']); $b['name'] = $lucifer[7]; } else { $b['month'] = $lucifer[5]; $b['day'] = $lucifer[6]; if (preg_match("/([0-9]{2}):([0-9]{2})/",$lucifer[7],$l2)) { $b['year'] = date("Y"); $b['hour'] = $l2[1]; $b['minute'] = $l2[2]; } else { $b['year'] = $lucifer[7]; $b['hour'] = 0; $b['minute'] = 0; } $b['time'] = strtotime(sprintf("%d %s %d %02d:%02d",$b['day'],$b['month'],$b['year'],$b['hour'],$b['minute'])); $b['name'] = $lucifer[8]; } } return $b; } function SendMSG($message = "", $crlf=true) { if ($this->Verbose) { echo $message.($crlf?CRLF:""); flush(); } return TRUE; } function SetType($mode=FTP_AUTOASCII) { if(!in_array($mode, $this->AuthorizedTransferMode)) { $this->SendMSG("Wrong type"); return FALSE; } $this->_type=$mode; $this->SendMSG("Transfer type: ".($this->_type==FTP_BINARY?"binary":($this->_type==FTP_ASCII?"ASCII":"auto ASCII") ) ); return TRUE; } function _settype($mode=FTP_ASCII) { if($this->_ready) { if($mode==FTP_BINARY) { if($this->_curtype!=FTP_BINARY) { if(!$this->_exec("TYPE I", "SetType")) return FALSE; $this->_curtype=FTP_BINARY; } } elseif($this->_curtype!=FTP_ASCII) { if(!$this->_exec("TYPE A", "SetType")) return FALSE; $this->_curtype=FTP_ASCII; } } else return FALSE; return TRUE; } function Passive($pasv=NULL) { if(is_null($pasv)) $this->_passive=!$this->_passive; else $this->_passive=$pasv; if(!$this->_port_available and !$this->_passive) { $this->SendMSG("Only passive connections available!"); $this->_passive=TRUE; return FALSE; } $this->SendMSG("Passive mode ".($this->_passive?"on":"off")); return TRUE; } function SetServer($host, $port=21, $reconnect=true) { if(!is_long($port)) { $this->verbose=true; $this->SendMSG("Incorrect port syntax"); return FALSE; } else { $ip=@gethostbyname($host); $dns=@gethostbyaddr($host); if(!$ip) $ip=$host; if(!$dns) $dns=$host; // Validate the IPAddress PHP4 returns -1 for invalid, PHP5 false // -1 === "255.255.255.255" which is the broadcast address which is also going to be invalid $ipaslong = ip2long($ip); if ( ($ipaslong == false) || ($ipaslong === -1) ) { $this->SendMSG("Wrong host name/address \"".$host."\""); return FALSE; } $this->_host=$ip; $this->_fullhost=$dns; $this->_port=$port; $this->_dataport=$port-1; } $this->SendMSG("Host \"".$this->_fullhost."(".$this->_host."):".$this->_port."\""); if($reconnect){ if($this->_connected) { $this->SendMSG("Reconnecting"); if(!$this->quit(FTP_FORCE)) return FALSE; if(!$this->connect()) return FALSE; } } return TRUE; } function SetUmask($umask=0022) { $this->_umask=$umask; umask($this->_umask); $this->SendMSG("UMASK 0".decoct($this->_umask)); return TRUE; } function SetTimeout($timeout=30) { $this->_timeout=$timeout; $this->SendMSG("Timeout ".$this->_timeout); if($this->_connected) if(!$this->_settimeout($this->_ftp_control_sock)) return FALSE; return TRUE; } function connect($server=NULL) { if(!empty($server)) { if(!$this->SetServer($server)) return false; } if($this->_ready) return true; $this->SendMsg('Local OS : '.$this->OS_FullName[$this->OS_local]); if(!($this->_ftp_control_sock = $this->_connect($this->_host, $this->_port))) { $this->SendMSG("Error : Cannot connect to remote host \"".$this->_fullhost." :".$this->_port."\""); return FALSE; } $this->SendMSG("Connected to remote host \"".$this->_fullhost.":".$this->_port."\". Waiting for greeting."); do { if(!$this->_readmsg()) return FALSE; if(!$this->_checkCode()) return FALSE; $this->_lastaction=time(); } while($this->_code<200); $this->_ready=true; $syst=$this->systype(); if(!$syst) $this->SendMSG("Can't detect remote OS"); else { if(preg_match("/win|dos|novell/i", $syst[0])) $this->OS_remote=FTP_OS_Windows; elseif(preg_match("/os/i", $syst[0])) $this->OS_remote=FTP_OS_Mac; elseif(preg_match("/(li|u)nix/i", $syst[0])) $this->OS_remote=FTP_OS_Unix; else $this->OS_remote=FTP_OS_Mac; $this->SendMSG("Remote OS: ".$this->OS_FullName[$this->OS_remote]); } if(!$this->features()) $this->SendMSG("Can't get features list. All supported - disabled"); else $this->SendMSG("Supported features: ".implode(", ", array_keys($this->_features))); return TRUE; } function quit($force=false) { if($this->_ready) { if(!$this->_exec("QUIT") and !$force) return FALSE; if(!$this->_checkCode() and !$force) return FALSE; $this->_ready=false; $this->SendMSG("Session finished"); } $this->_quit(); return TRUE; } function login($user=NULL, $pass=NULL) { if(!is_null($user)) $this->_login=$user; else $this->_login="anonymous"; if(!is_null($pass)) $this->_password=$pass; else $this->_password="anon@anon.com"; if(!$this->_exec("USER ".$this->_login, "login")) return FALSE; if(!$this->_checkCode()) return FALSE; if($this->_code!=230) { if(!$this->_exec((($this->_code==331)?"PASS ":"ACCT ").$this->_password, "login")) return FALSE; if(!$this->_checkCode()) return FALSE; } $this->SendMSG("Authentication succeeded"); if(empty($this->_features)) { if(!$this->features()) $this->SendMSG("Can't get features list. All supported - disabled"); else $this->SendMSG("Supported features: ".implode(", ", array_keys($this->_features))); } return TRUE; } function pwd() { if(!$this->_exec("PWD", "pwd")) return FALSE; if(!$this->_checkCode()) return FALSE; return ereg_replace("^[0-9]{3} \"(.+)\".+", "\\1", $this->_message); } function cdup() { if(!$this->_exec("CDUP", "cdup")) return FALSE; if(!$this->_checkCode()) return FALSE; return true; } function chdir($pathname) { if(!$this->_exec("CWD ".$pathname, "chdir")) return FALSE; if(!$this->_checkCode()) return FALSE; return TRUE; } function rmdir($pathname) { if(!$this->_exec("RMD ".$pathname, "rmdir")) return FALSE; if(!$this->_checkCode()) return FALSE; return TRUE; } function mkdir($pathname) { if(!$this->_exec("MKD ".$pathname, "mkdir")) return FALSE; if(!$this->_checkCode()) return FALSE; return TRUE; } function rename($from, $to) { if(!$this->_exec("RNFR ".$from, "rename")) return FALSE; if(!$this->_checkCode()) return FALSE; if($this->_code==350) { if(!$this->_exec("RNTO ".$to, "rename")) return FALSE; if(!$this->_checkCode()) return FALSE; } else return FALSE; return TRUE; } function filesize($pathname) { if(!isset($this->_features["SIZE"])) { $this->PushError("filesize", "not supported by server"); return FALSE; } if(!$this->_exec("SIZE ".$pathname, "filesize")) return FALSE; if(!$this->_checkCode()) return FALSE; return ereg_replace("^[0-9]{3} ([0-9]+)".CRLF, "\\1", $this->_message); } function abort() { if(!$this->_exec("ABOR", "abort")) return FALSE; if(!$this->_checkCode()) { if($this->_code!=426) return FALSE; if(!$this->_readmsg("abort")) return FALSE; if(!$this->_checkCode()) return FALSE; } return true; } function mdtm($pathname) { if(!isset($this->_features["MDTM"])) { $this->PushError("mdtm", "not supported by server"); return FALSE; } if(!$this->_exec("MDTM ".$pathname, "mdtm")) return FALSE; if(!$this->_checkCode()) return FALSE; $mdtm = ereg_replace("^[0-9]{3} ([0-9]+)".CRLF, "\\1", $this->_message); $date = sscanf($mdtm, "%4d%2d%2d%2d%2d%2d"); $timestamp = mktime($date[3], $date[4], $date[5], $date[1], $date[2], $date[0]); return $timestamp; } function systype() { if(!$this->_exec("SYST", "systype")) return FALSE; if(!$this->_checkCode()) return FALSE; $DATA = explode(" ", $this->_message); return array($DATA[1], $DATA[3]); } function delete($pathname) { if(!$this->_exec("DELE ".$pathname, "delete")) return FALSE; if(!$this->_checkCode()) return FALSE; return TRUE; } function site($command, $fnction="site") { if(!$this->_exec("SITE ".$command, $fnction)) return FALSE; if(!$this->_checkCode()) return FALSE; return TRUE; } function chmod($pathname, $mode) { if(!$this->site( sprintf('CHMOD %o %s', $mode, $pathname), "chmod")) return FALSE; return TRUE; } function restore($from) { if(!isset($this->_features["REST"])) { $this->PushError("restore", "not supported by server"); return FALSE; } if($this->_curtype!=FTP_BINARY) { $this->PushError("restore", "can't restore in ASCII mode"); return FALSE; } if(!$this->_exec("REST ".$from, "resore")) return FALSE; if(!$this->_checkCode()) return FALSE; return TRUE; } function features() { if(!$this->_exec("FEAT", "features")) return FALSE; if(!$this->_checkCode()) return FALSE; $f=preg_split("/[".CRLF."]+/", preg_replace("/[0-9]{3}[ -].*[".CRLF."]+/", "", $this->_message), -1, PREG_SPLIT_NO_EMPTY); $this->_features=array(); foreach($f as $k=>$v) { $v=explode(" ", trim($v)); $this->_features[array_shift($v)]=$v; } return true; } function rawlist($pathname="", $arg="") { return $this->_list(($arg?" ".$arg:"").($pathname?" ".$pathname:""), "LIST", "rawlist"); } function nlist($pathname="") { return $this->_list(($arg?" ".$arg:"").($pathname?" ".$pathname:""), "NLST", "nlist"); } function is_exists($pathname) { return $this->file_exists($pathname); } function file_exists($pathname) { $exists=true; if(!$this->_exec("RNFR ".$pathname, "rename")) $exists=FALSE; else { if(!$this->_checkCode()) $exists=FALSE; $this->abort(); } if($exists) $this->SendMSG("Remote file ".$pathname." exists"); else $this->SendMSG("Remote file ".$pathname." does not exist"); return $exists; } function fget($fp, $remotefile,$rest=0) { if($this->_can_restore and $rest!=0) fseek($fp, $rest); $pi=pathinfo($remotefile); if($this->_type==FTP_ASCII or ($this->_type==FTP_AUTOASCII and in_array(strtoupper($pi["extension"]), $this->AutoAsciiExt))) $mode=FTP_ASCII; else $mode=FTP_BINARY; if(!$this->_data_prepare($mode)) { return FALSE; } if($this->_can_restore and $rest!=0) $this->restore($rest); if(!$this->_exec("RETR ".$remotefile, "get")) { $this->_data_close(); return FALSE; } if(!$this->_checkCode()) { $this->_data_close(); return FALSE; } $out=$this->_data_read($mode, $fp); $this->_data_close(); if(!$this->_readmsg()) return FALSE; if(!$this->_checkCode()) return FALSE; return $out; } function get($remotefile, $localfile=NULL, $rest=0) { if(is_null($localfile)) $localfile=$remotefile; if (@file_exists($localfile)) $this->SendMSG("Warning : local file will be overwritten"); $fp = @fopen($localfile, "w"); if (!$fp) { $this->PushError("get","can't open local file", "Cannot create \"".$localfile."\""); return FALSE; } if($this->_can_restore and $rest!=0) fseek($fp, $rest); $pi=pathinfo($remotefile); if($this->_type==FTP_ASCII or ($this->_type==FTP_AUTOASCII and in_array(strtoupper($pi["extension"]), $this->AutoAsciiExt))) $mode=FTP_ASCII; else $mode=FTP_BINARY; if(!$this->_data_prepare($mode)) { fclose($fp); return FALSE; } if($this->_can_restore and $rest!=0) $this->restore($rest); if(!$this->_exec("RETR ".$remotefile, "get")) { $this->_data_close(); fclose($fp); return FALSE; } if(!$this->_checkCode()) { $this->_data_close(); fclose($fp); return FALSE; } $out=$this->_data_read($mode, $fp); fclose($fp); $this->_data_close(); if(!$this->_readmsg()) return FALSE; if(!$this->_checkCode()) return FALSE; return $out; } function fput($remotefile, $fp) { if($this->_can_restore and $rest!=0) fseek($fp, $rest); $pi=pathinfo($remotefile); if($this->_type==FTP_ASCII or ($this->_type==FTP_AUTOASCII and in_array(strtoupper($pi["extension"]), $this->AutoAsciiExt))) $mode=FTP_ASCII; else $mode=FTP_BINARY; if(!$this->_data_prepare($mode)) { return FALSE; } if($this->_can_restore and $rest!=0) $this->restore($rest); if(!$this->_exec("STOR ".$remotefile, "put")) { $this->_data_close(); return FALSE; } if(!$this->_checkCode()) { $this->_data_close(); return FALSE; } $ret=$this->_data_write($mode, $fp); $this->_data_close(); if(!$this->_readmsg()) return FALSE; if(!$this->_checkCode()) return FALSE; return $ret; } function put($localfile, $remotefile=NULL, $rest=0) { if(is_null($remotefile)) $remotefile=$localfile; if (!file_exists($localfile)) { $this->PushError("put","can't open local file", "No such file or directory \"".$localfile."\""); return FALSE; } $fp = @fopen($localfile, "r"); if (!$fp) { $this->PushError("put","can't open local file", "Cannot read file \"".$localfile."\""); return FALSE; } if($this->_can_restore and $rest!=0) fseek($fp, $rest); $pi=pathinfo($localfile); if($this->_type==FTP_ASCII or ($this->_type==FTP_AUTOASCII and in_array(strtoupper($pi["extension"]), $this->AutoAsciiExt))) $mode=FTP_ASCII; else $mode=FTP_BINARY; if(!$this->_data_prepare($mode)) { fclose($fp); return FALSE; } if($this->_can_restore and $rest!=0) $this->restore($rest); if(!$this->_exec("STOR ".$remotefile, "put")) { $this->_data_close(); fclose($fp); return FALSE; } if(!$this->_checkCode()) { $this->_data_close(); fclose($fp); return FALSE; } $ret=$this->_data_write($mode, $fp); fclose($fp); $this->_data_close(); if(!$this->_readmsg()) return FALSE; if(!$this->_checkCode()) return FALSE; return $ret; } function mput($local=".", $remote=NULL, $continious=false) { $local=realpath($local); if(!@file_exists($local)) { $this->PushError("mput","can't open local folder", "Cannot stat folder \"".$local."\""); return FALSE; } if(!is_dir($local)) return $this->put($local, $remote); if(empty($remote)) $remote="."; elseif(!$this->file_exists($remote) and !$this->mkdir($remote)) return FALSE; if($handle = opendir($local)) { $list=array(); while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") $list[]=$file; } closedir($handle); } else { $this->PushError("mput","can't open local folder", "Cannot read folder \"".$local."\""); return FALSE; } if(empty($list)) return TRUE; $ret=true; foreach($list as $el) { if(is_dir($local."/".$el)) $t=$this->mput($local."/".$el, $remote."/".$el); else $t=$this->put($local."/".$el, $remote."/".$el); if(!$t) { $ret=FALSE; if(!$continious) break; } } return $ret; } function mget($remote, $local=".", $continious=false) { $list=$this->rawlist($remote, "-lA"); if($list===false) { $this->PushError("mget","can't read remote folder list", "Can't read remote folder \"".$remote."\" contents"); return FALSE; } if(empty($list)) return true; if(!@file_exists($local)) { if(!@mkdir($local)) { $this->PushError("mget","can't create local folder", "Cannot create folder \"".$local."\""); return FALSE; } } foreach($list as $k=>$v) { $list[$k]=$this->parselisting($v); if($list[$k]["name"]=="." or $list[$k]["name"]=="..") unset($list[$k]); } $ret=true; foreach($list as $el) { if($el["type"]=="d") { if(!$this->mget($remote."/".$el["name"], $local."/".$el["name"], $continious)) { $this->PushError("mget", "can't copy folder", "Can't copy remote folder \"".$remote."/".$el["name"]."\" to local \"".$local."/".$el["name"]."\""); $ret=false; if(!$continious) break; } } else { if(!$this->get($remote."/".$el["name"], $local."/".$el["name"])) { $this->PushError("mget", "can't copy file", "Can't copy remote file \"".$remote."/".$el["name"]."\" to local \"".$local."/".$el["name"]."\""); $ret=false; if(!$continious) break; } } @chmod($local."/".$el["name"], $el["perms"]); $t=strtotime($el["date"]); if($t!==-1 and $t!==false) @touch($local."/".$el["name"], $t); } return $ret; } function mdel($remote, $continious=false) { $list=$this->rawlist($remote, "-la"); if($list===false) { $this->PushError("mdel","can't read remote folder list", "Can't read remote folder \"".$remote."\" contents"); return false; } foreach($list as $k=>$v) { $list[$k]=$this->parselisting($v); if($list[$k]["name"]=="." or $list[$k]["name"]=="..") unset($list[$k]); } $ret=true; foreach($list as $el) { if ( empty($el) ) continue; if($el["type"]=="d") { if(!$this->mdel($remote."/".$el["name"], $continious)) { $ret=false; if(!$continious) break; } } else { if (!$this->delete($remote."/".$el["name"])) { $this->PushError("mdel", "can't delete file", "Can't delete remote file \"".$remote."/".$el["name"]."\""); $ret=false; if(!$continious) break; } } } if(!$this->rmdir($remote)) { $this->PushError("mdel", "can't delete folder", "Can't delete remote folder \"".$remote."/".$el["name"]."\""); $ret=false; } return $ret; } function mmkdir($dir, $mode = 0777) { if(empty($dir)) return FALSE; if($this->is_exists($dir) or $dir == "/" ) return TRUE; if(!$this->mmkdir(dirname($dir), $mode)) return false; $r=$this->mkdir($dir, $mode); $this->chmod($dir,$mode); return $r; } function glob($pattern, $handle=NULL) { $path=$output=null; if(PHP_OS=='WIN32') $slash='\\'; else $slash='/'; $lastpos=strrpos($pattern,$slash); if(!($lastpos===false)) { $path=substr($pattern,0,-$lastpos-1); $pattern=substr($pattern,$lastpos); } else $path=getcwd(); if(is_array($handle) and !empty($handle)) { while($dir=each($handle)) { if($this->glob_pattern_match($pattern,$dir)) $output[]=$dir; } } else { $handle=@opendir($path); if($handle===false) return false; while($dir=readdir($handle)) { if($this->glob_pattern_match($pattern,$dir)) $output[]=$dir; } closedir($handle); } if(is_array($output)) return $output; return false; } function glob_pattern_match($pattern,$string) { $out=null; $chunks=explode(';',$pattern); foreach($chunks as $pattern) { $escape=array('$','^','.','{','}','(',')','[',']','|'); while(strpos($pattern,'**')!==false) $pattern=str_replace('**','*',$pattern); foreach($escape as $probe) $pattern=str_replace($probe,"\\$probe",$pattern); $pattern=str_replace('?*','*', str_replace('*?','*', str_replace('*',".*", str_replace('?','.{1,1}',$pattern)))); $out[]=$pattern; } if(count($out)==1) return($this->glob_regexp("^$out[0]$",$string)); else { foreach($out as $tester) if($this->my_regexp("^$tester$",$string)) return true; } return false; } function glob_regexp($pattern,$probe) { $sensitive=(PHP_OS!='WIN32'); return ($sensitive? ereg($pattern,$probe): eregi($pattern,$probe) ); } function dirlist($remote) { $list=$this->rawlist($remote, "-la"); if($list===false) { $this->PushError("dirlist","can't read remote folder list", "Can't read remote folder \"".$remote."\" contents"); return false; } $dirlist = array(); foreach($list as $k=>$v) { $entry=$this->parselisting($v); if ( empty($entry) ) continue; if($entry["name"]=="." or $entry["name"]=="..") continue; $dirlist[$entry['name']] = $entry; } return $dirlist; } // <!-- --------------------------------------------------------------------------------------- --> // <!-- Private functions --> // <!-- --------------------------------------------------------------------------------------- --> function _checkCode() { return ($this->_code<400 and $this->_code>0); } function _list($arg="", $cmd="LIST", $fnction="_list") { if(!$this->_data_prepare()) return false; if(!$this->_exec($cmd.$arg, $fnction)) { $this->_data_close(); return FALSE; } if(!$this->_checkCode()) { $this->_data_close(); return FALSE; } $out=""; if($this->_code<200) { $out=$this->_data_read(); $this->_data_close(); if(!$this->_readmsg()) return FALSE; if(!$this->_checkCode()) return FALSE; if($out === FALSE ) return FALSE; $out=preg_split("/[".CRLF."]+/", $out, -1, PREG_SPLIT_NO_EMPTY); // $this->SendMSG(implode($this->_eol_code[$this->OS_local], $out)); } return $out; } // <!-- --------------------------------------------------------------------------------------- --> // <!-- Partie : gestion des erreurs --> // <!-- --------------------------------------------------------------------------------------- --> // Gnre une erreur pour traitement externe la classe function PushError($fctname,$msg,$desc=false){ $error=array(); $error['time']=time(); $error['fctname']=$fctname; $error['msg']=$msg; $error['desc']=$desc; if($desc) $tmp=' ('.$desc.')'; else $tmp=''; $this->SendMSG($fctname.': '.$msg.$tmp); return(array_push($this->_error_array,$error)); } // Rcupre une erreur externe function PopError(){ if(count($this->_error_array)) return(array_pop($this->_error_array)); else return(false); } } $mod_sockets = extension_loaded( 'sockets' ); if ( ! $mod_sockets && function_exists( 'dl' ) && is_callable( 'dl' ) ) { $prefix = ( PHP_SHLIB_SUFFIX == 'dll' ) ? 'php_' : ''; @dl( $prefix . 'sockets.' . PHP_SHLIB_SUFFIX ); $mod_sockets = extension_loaded( 'sockets' ); } require_once "class-ftp-" . ( $mod_sockets ? "sockets" : "pure" ) . ".php"; ?>
zyblog
trunk/zyblog/wp-admin/includes/class-ftp.php
PHP
asf20
26,858
<?php /** * Template WordPress Administration API. * * A Big Mess. Also some neat functions that are nicely written. * * @package WordPress * @subpackage Administration */ // // Category Checklists // /** * Walker to output an unordered list of category checkbox <input> elements. * * @see Walker * @see wp_category_checklist() * @see wp_terms_checklist() * @since 2.5.1 */ class Walker_Category_Checklist extends Walker { var $tree_type = 'category'; var $db_fields = array ('parent' => 'parent', 'id' => 'term_id'); //TODO: decouple this function start_lvl( &$output, $depth = 0, $args = array() ) { $indent = str_repeat("\t", $depth); $output .= "$indent<ul class='children'>\n"; } function end_lvl( &$output, $depth = 0, $args = array() ) { $indent = str_repeat("\t", $depth); $output .= "$indent</ul>\n"; } function start_el( &$output, $category, $depth, $args, $id = 0 ) { extract($args); if ( empty($taxonomy) ) $taxonomy = 'category'; if ( $taxonomy == 'category' ) $name = 'post_category'; else $name = 'tax_input['.$taxonomy.']'; $class = in_array( $category->term_id, $popular_cats ) ? ' class="popular-category"' : ''; $output .= "\n<li id='{$taxonomy}-{$category->term_id}'$class>" . '<label class="selectit"><input value="' . $category->term_id . '" type="checkbox" name="'.$name.'[]" id="in-'.$taxonomy.'-' . $category->term_id . '"' . checked( in_array( $category->term_id, $selected_cats ), true, false ) . disabled( empty( $args['disabled'] ), false, false ) . ' /> ' . esc_html( apply_filters('the_category', $category->name )) . '</label>'; } function end_el( &$output, $category, $depth = 0, $args = array() ) { $output .= "</li>\n"; } } /** * Output an unordered list of checkbox <input> elements labelled * with category names. * * @see wp_terms_checklist() * @since 2.5.1 * * @param int $post_id Mark categories associated with this post as checked. $selected_cats must not be an array. * @param int $descendants_and_self ID of the category to output along with its descendents. * @param bool|array $selected_cats List of categories to mark as checked. * @param bool|array $popular_cats Override the list of categories that receive the "popular-category" class. * @param object $walker Walker object to use to build the output. * @param bool $checked_ontop Move checked items out of the hierarchy and to the top of the list. */ function wp_category_checklist( $post_id = 0, $descendants_and_self = 0, $selected_cats = false, $popular_cats = false, $walker = null, $checked_ontop = true ) { wp_terms_checklist( $post_id, array( 'taxonomy' => 'category', 'descendants_and_self' => $descendants_and_self, 'selected_cats' => $selected_cats, 'popular_cats' => $popular_cats, 'walker' => $walker, 'checked_ontop' => $checked_ontop ) ); } /** * Output an unordered list of checkbox <input> elements labelled * with term names. Taxonomy independent version of wp_category_checklist(). * * @since 3.0.0 * * @param int $post_id * @param array $args */ function wp_terms_checklist($post_id = 0, $args = array()) { $defaults = array( 'descendants_and_self' => 0, 'selected_cats' => false, 'popular_cats' => false, 'walker' => null, 'taxonomy' => 'category', 'checked_ontop' => true ); $args = apply_filters( 'wp_terms_checklist_args', $args, $post_id ); extract( wp_parse_args($args, $defaults), EXTR_SKIP ); if ( empty($walker) || !is_a($walker, 'Walker') ) $walker = new Walker_Category_Checklist; $descendants_and_self = (int) $descendants_and_self; $args = array('taxonomy' => $taxonomy); $tax = get_taxonomy($taxonomy); $args['disabled'] = !current_user_can($tax->cap->assign_terms); if ( is_array( $selected_cats ) ) $args['selected_cats'] = $selected_cats; elseif ( $post_id ) $args['selected_cats'] = wp_get_object_terms($post_id, $taxonomy, array_merge($args, array('fields' => 'ids'))); else $args['selected_cats'] = array(); if ( is_array( $popular_cats ) ) $args['popular_cats'] = $popular_cats; else $args['popular_cats'] = get_terms( $taxonomy, array( 'fields' => 'ids', 'orderby' => 'count', 'order' => 'DESC', 'number' => 10, 'hierarchical' => false ) ); if ( $descendants_and_self ) { $categories = (array) get_terms($taxonomy, array( 'child_of' => $descendants_and_self, 'hierarchical' => 0, 'hide_empty' => 0 ) ); $self = get_term( $descendants_and_self, $taxonomy ); array_unshift( $categories, $self ); } else { $categories = (array) get_terms($taxonomy, array('get' => 'all')); } if ( $checked_ontop ) { // Post process $categories rather than adding an exclude to the get_terms() query to keep the query the same across all posts (for any query cache) $checked_categories = array(); $keys = array_keys( $categories ); foreach( $keys as $k ) { if ( in_array( $categories[$k]->term_id, $args['selected_cats'] ) ) { $checked_categories[] = $categories[$k]; unset( $categories[$k] ); } } // Put checked cats on top echo call_user_func_array(array(&$walker, 'walk'), array($checked_categories, 0, $args)); } // Then the rest of them echo call_user_func_array(array(&$walker, 'walk'), array($categories, 0, $args)); } /** * Retrieve a list of the most popular terms from the specified taxonomy. * * If the $echo argument is true then the elements for a list of checkbox * <input> elements labelled with the names of the selected terms is output. * If the $post_ID global isn't empty then the terms associated with that * post will be marked as checked. * * @since 2.5.0 * * @param string $taxonomy Taxonomy to retrieve terms from. * @param int $default Unused. * @param int $number Number of terms to retrieve. Defaults to 10. * @param bool $echo Optionally output the list as well. Defaults to true. * @return array List of popular term IDs. */ function wp_popular_terms_checklist( $taxonomy, $default = 0, $number = 10, $echo = true ) { $post = get_post(); if ( $post && $post->ID ) $checked_terms = wp_get_object_terms($post->ID, $taxonomy, array('fields'=>'ids')); else $checked_terms = array(); $terms = get_terms( $taxonomy, array( 'orderby' => 'count', 'order' => 'DESC', 'number' => $number, 'hierarchical' => false ) ); $tax = get_taxonomy($taxonomy); if ( ! current_user_can($tax->cap->assign_terms) ) $disabled = 'disabled="disabled"'; else $disabled = ''; $popular_ids = array(); foreach ( (array) $terms as $term ) { $popular_ids[] = $term->term_id; if ( !$echo ) // hack for AJAX use continue; $id = "popular-$taxonomy-$term->term_id"; $checked = in_array( $term->term_id, $checked_terms ) ? 'checked="checked"' : ''; ?> <li id="<?php echo $id; ?>" class="popular-category"> <label class="selectit"> <input id="in-<?php echo $id; ?>" type="checkbox" <?php echo $checked; ?> value="<?php echo (int) $term->term_id; ?>" <?php echo $disabled ?>/> <?php echo esc_html( apply_filters( 'the_category', $term->name ) ); ?> </label> </li> <?php } return $popular_ids; } /** * {@internal Missing Short Description}} * * @since 2.5.1 * * @param unknown_type $link_id */ function wp_link_category_checklist( $link_id = 0 ) { $default = 1; if ( $link_id ) { $checked_categories = wp_get_link_cats( $link_id ); // No selected categories, strange if ( ! count( $checked_categories ) ) $checked_categories[] = $default; } else { $checked_categories[] = $default; } $categories = get_terms( 'link_category', array( 'orderby' => 'name', 'hide_empty' => 0 ) ); if ( empty( $categories ) ) return; foreach ( $categories as $category ) { $cat_id = $category->term_id; $name = esc_html( apply_filters( 'the_category', $category->name ) ); $checked = in_array( $cat_id, $checked_categories ) ? ' checked="checked"' : ''; echo '<li id="link-category-', $cat_id, '"><label for="in-link-category-', $cat_id, '" class="selectit"><input value="', $cat_id, '" type="checkbox" name="link_category[]" id="in-link-category-', $cat_id, '"', $checked, '/> ', $name, "</label></li>"; } } // adds hidden fields with the data for use in the inline editor for posts and pages /** * {@internal Missing Short Description}} * * @since 2.7.0 * * @param unknown_type $post */ function get_inline_data($post) { $post_type_object = get_post_type_object($post->post_type); if ( ! current_user_can($post_type_object->cap->edit_post, $post->ID) ) return; $title = esc_textarea( trim( $post->post_title ) ); echo ' <div class="hidden" id="inline_' . $post->ID . '"> <div class="post_title">' . $title . '</div> <div class="post_name">' . apply_filters('editable_slug', $post->post_name) . '</div> <div class="post_author">' . $post->post_author . '</div> <div class="comment_status">' . esc_html( $post->comment_status ) . '</div> <div class="ping_status">' . esc_html( $post->ping_status ) . '</div> <div class="_status">' . esc_html( $post->post_status ) . '</div> <div class="jj">' . mysql2date( 'd', $post->post_date, false ) . '</div> <div class="mm">' . mysql2date( 'm', $post->post_date, false ) . '</div> <div class="aa">' . mysql2date( 'Y', $post->post_date, false ) . '</div> <div class="hh">' . mysql2date( 'H', $post->post_date, false ) . '</div> <div class="mn">' . mysql2date( 'i', $post->post_date, false ) . '</div> <div class="ss">' . mysql2date( 's', $post->post_date, false ) . '</div> <div class="post_password">' . esc_html( $post->post_password ) . '</div>'; if ( $post_type_object->hierarchical ) echo '<div class="post_parent">' . $post->post_parent . '</div>'; if ( $post->post_type == 'page' ) echo '<div class="page_template">' . esc_html( get_post_meta( $post->ID, '_wp_page_template', true ) ) . '</div>'; if ( post_type_supports( $post->post_type, 'page-attributes' ) ) echo '<div class="menu_order">' . $post->menu_order . '</div>'; $taxonomy_names = get_object_taxonomies( $post->post_type ); foreach ( $taxonomy_names as $taxonomy_name) { $taxonomy = get_taxonomy( $taxonomy_name ); if ( $taxonomy->hierarchical && $taxonomy->show_ui ) { echo '<div class="post_category" id="' . $taxonomy_name . '_' . $post->ID . '">' . implode( ',', wp_get_object_terms( $post->ID, $taxonomy_name, array( 'fields' => 'ids' ) ) ) . '</div>'; } elseif ( $taxonomy->show_ui ) { echo '<div class="tags_input" id="'.$taxonomy_name.'_'.$post->ID.'">' . esc_html( str_replace( ',', ', ', get_terms_to_edit( $post->ID, $taxonomy_name ) ) ) . '</div>'; } } if ( !$post_type_object->hierarchical ) echo '<div class="sticky">' . (is_sticky($post->ID) ? 'sticky' : '') . '</div>'; if ( post_type_supports( $post->post_type, 'post-formats' ) ) echo '<div class="post_format">' . esc_html( get_post_format( $post->ID ) ) . '</div>'; echo '</div>'; } /** * {@internal Missing Short Description}} * * @since 2.7.0 * * @param unknown_type $position * @param unknown_type $checkbox * @param unknown_type $mode */ function wp_comment_reply($position = '1', $checkbox = false, $mode = 'single', $table_row = true) { // allow plugin to replace the popup content $content = apply_filters( 'wp_comment_reply', '', array('position' => $position, 'checkbox' => $checkbox, 'mode' => $mode) ); if ( ! empty($content) ) { echo $content; return; } if ( $mode == 'single' ) { $wp_list_table = _get_list_table('WP_Post_Comments_List_Table'); } else { $wp_list_table = _get_list_table('WP_Comments_List_Table'); } ?> <form method="get" action=""> <?php if ( $table_row ) : ?> <table style="display:none;"><tbody id="com-reply"><tr id="replyrow" style="display:none;"><td colspan="<?php echo $wp_list_table->get_column_count(); ?>" class="colspanchange"> <?php else : ?> <div id="com-reply" style="display:none;"><div id="replyrow" style="display:none;"> <?php endif; ?> <div id="replyhead" style="display:none;"><h5><?php _e( 'Reply to Comment' ); ?></h5></div> <div id="addhead" style="display:none;"><h5><?php _e('Add new Comment'); ?></h5></div> <div id="edithead" style="display:none;"> <div class="inside"> <label for="author"><?php _e('Name') ?></label> <input type="text" name="newcomment_author" size="50" value="" id="author" /> </div> <div class="inside"> <label for="author-email"><?php _e('E-mail') ?></label> <input type="text" name="newcomment_author_email" size="50" value="" id="author-email" /> </div> <div class="inside"> <label for="author-url"><?php _e('URL') ?></label> <input type="text" id="author-url" name="newcomment_author_url" size="103" value="" /> </div> <div style="clear:both;"></div> </div> <div id="replycontainer"> <?php $quicktags_settings = array( 'buttons' => 'strong,em,link,block,del,ins,img,ul,ol,li,code,spell,close' ); wp_editor( '', 'replycontent', array( 'media_buttons' => false, 'tinymce' => false, 'quicktags' => $quicktags_settings ) ); ?> </div> <p id="replysubmit" class="submit"> <a href="#comments-form" class="save button-primary alignright"> <span id="addbtn" style="display:none;"><?php _e('Add Comment'); ?></span> <span id="savebtn" style="display:none;"><?php _e('Update Comment'); ?></span> <span id="replybtn" style="display:none;"><?php _e('Submit Reply'); ?></span></a> <a href="#comments-form" class="cancel button-secondary alignleft"><?php _e('Cancel'); ?></a> <span class="waiting spinner"></span> <span class="error" style="display:none;"></span> <br class="clear" /> </p> <input type="hidden" name="user_ID" id="user_ID" value="<?php echo get_current_user_id(); ?>" /> <input type="hidden" name="action" id="action" value="" /> <input type="hidden" name="comment_ID" id="comment_ID" value="" /> <input type="hidden" name="comment_post_ID" id="comment_post_ID" value="" /> <input type="hidden" name="status" id="status" value="" /> <input type="hidden" name="position" id="position" value="<?php echo $position; ?>" /> <input type="hidden" name="checkbox" id="checkbox" value="<?php echo $checkbox ? 1 : 0; ?>" /> <input type="hidden" name="mode" id="mode" value="<?php echo esc_attr($mode); ?>" /> <?php wp_nonce_field( 'replyto-comment', '_ajax_nonce-replyto-comment', false ); if ( current_user_can( 'unfiltered_html' ) ) wp_nonce_field( 'unfiltered-html-comment', '_wp_unfiltered_html_comment', false ); ?> <?php if ( $table_row ) : ?> </td></tr></tbody></table> <?php else : ?> </div></div> <?php endif; ?> </form> <?php } /** * Output 'undo move to trash' text for comments * * @since 2.9.0 */ function wp_comment_trashnotice() { ?> <div class="hidden" id="trash-undo-holder"> <div class="trash-undo-inside"><?php printf(__('Comment by %s moved to the trash.'), '<strong></strong>'); ?> <span class="undo untrash"><a href="#"><?php _e('Undo'); ?></a></span></div> </div> <div class="hidden" id="spam-undo-holder"> <div class="spam-undo-inside"><?php printf(__('Comment by %s marked as spam.'), '<strong></strong>'); ?> <span class="undo unspam"><a href="#"><?php _e('Undo'); ?></a></span></div> </div> <?php } /** * {@internal Missing Short Description}} * * @since 1.2.0 * * @param unknown_type $meta */ function list_meta( $meta ) { // Exit if no meta if ( ! $meta ) { echo ' <table id="list-table" style="display: none;"> <thead> <tr> <th class="left">' . _x( 'Name', 'meta name' ) . '</th> <th>' . __( 'Value' ) . '</th> </tr> </thead> <tbody id="the-list" data-wp-lists="list:meta"> <tr><td></td></tr> </tbody> </table>'; //TBODY needed for list-manipulation JS return; } $count = 0; ?> <table id="list-table"> <thead> <tr> <th class="left"><?php _ex( 'Name', 'meta name' ) ?></th> <th><?php _e( 'Value' ) ?></th> </tr> </thead> <tbody id='the-list' data-wp-lists='list:meta'> <?php foreach ( $meta as $entry ) echo _list_meta_row( $entry, $count ); ?> </tbody> </table> <?php } /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @param unknown_type $entry * @param unknown_type $count * @return unknown */ function _list_meta_row( $entry, &$count ) { static $update_nonce = false; if ( is_protected_meta( $entry['meta_key'], 'post' ) ) return; if ( !$update_nonce ) $update_nonce = wp_create_nonce( 'add-meta' ); $r = ''; ++ $count; if ( $count % 2 ) $style = 'alternate'; else $style = ''; if ( is_serialized( $entry['meta_value'] ) ) { if ( is_serialized_string( $entry['meta_value'] ) ) { // this is a serialized string, so we should display it $entry['meta_value'] = maybe_unserialize( $entry['meta_value'] ); } else { // this is a serialized array/object so we should NOT display it --$count; return; } } $entry['meta_key'] = esc_attr($entry['meta_key']); $entry['meta_value'] = esc_textarea( $entry['meta_value'] ); // using a <textarea /> $entry['meta_id'] = (int) $entry['meta_id']; $delete_nonce = wp_create_nonce( 'delete-meta_' . $entry['meta_id'] ); $r .= "\n\t<tr id='meta-{$entry['meta_id']}' class='$style'>"; $r .= "\n\t\t<td class='left'><label class='screen-reader-text' for='meta[{$entry['meta_id']}][key]'>" . __( 'Key' ) . "</label><input name='meta[{$entry['meta_id']}][key]' id='meta[{$entry['meta_id']}][key]' type='text' size='20' value='{$entry['meta_key']}' />"; $r .= "\n\t\t<div class='submit'>"; $r .= get_submit_button( __( 'Delete' ), 'deletemeta small', "deletemeta[{$entry['meta_id']}]", false, array( 'data-wp-lists' => "delete:the-list:meta-{$entry['meta_id']}::_ajax_nonce=$delete_nonce" ) ); $r .= "\n\t\t"; $r .= get_submit_button( __( 'Update' ), 'updatemeta small', "meta-{$entry['meta_id']}-submit", false, array( 'data-wp-lists' => "add:the-list:meta-{$entry['meta_id']}::_ajax_nonce-add-meta=$update_nonce" ) ); $r .= "</div>"; $r .= wp_nonce_field( 'change-meta', '_ajax_nonce', false, false ); $r .= "</td>"; $r .= "\n\t\t<td><label class='screen-reader-text' for='meta[{$entry['meta_id']}][value]'>" . __( 'Value' ) . "</label><textarea name='meta[{$entry['meta_id']}][value]' id='meta[{$entry['meta_id']}][value]' rows='2' cols='30'>{$entry['meta_value']}</textarea></td>\n\t</tr>"; return $r; } /** * {@internal Missing Short Description}} * * @since 1.2.0 */ function meta_form() { global $wpdb; $limit = (int) apply_filters( 'postmeta_form_limit', 30 ); $keys = $wpdb->get_col( " SELECT meta_key FROM $wpdb->postmeta GROUP BY meta_key HAVING meta_key NOT LIKE '\_%' ORDER BY meta_key LIMIT $limit" ); if ( $keys ) natcasesort($keys); ?> <p><strong><?php _e( 'Add New Custom Field:' ) ?></strong></p> <table id="newmeta"> <thead> <tr> <th class="left"><label for="metakeyselect"><?php _ex( 'Name', 'meta name' ) ?></label></th> <th><label for="metavalue"><?php _e( 'Value' ) ?></label></th> </tr> </thead> <tbody> <tr> <td id="newmetaleft" class="left"> <?php if ( $keys ) { ?> <select id="metakeyselect" name="metakeyselect"> <option value="#NONE#"><?php _e( '&mdash; Select &mdash;' ); ?></option> <?php foreach ( $keys as $key ) { echo "\n<option value='" . esc_attr($key) . "'>" . esc_html($key) . "</option>"; } ?> </select> <input class="hide-if-js" type="text" id="metakeyinput" name="metakeyinput" value="" /> <a href="#postcustomstuff" class="hide-if-no-js" onclick="jQuery('#metakeyinput, #metakeyselect, #enternew, #cancelnew').toggle();return false;"> <span id="enternew"><?php _e('Enter new'); ?></span> <span id="cancelnew" class="hidden"><?php _e('Cancel'); ?></span></a> <?php } else { ?> <input type="text" id="metakeyinput" name="metakeyinput" value="" /> <?php } ?> </td> <td><textarea id="metavalue" name="metavalue" rows="2" cols="25"></textarea></td> </tr> <tr><td colspan="2"> <div class="submit"> <?php submit_button( __( 'Add Custom Field' ), 'secondary', 'addmeta', false, array( 'id' => 'newmeta-submit', 'data-wp-lists' => 'add:the-list:newmeta' ) ); ?> </div> <?php wp_nonce_field( 'add-meta', '_ajax_nonce-add-meta', false ); ?> </td></tr> </tbody> </table> <?php } /** * {@internal Missing Short Description}} * * @since 0.71 * * @param unknown_type $edit * @param unknown_type $for_post * @param unknown_type $tab_index * @param unknown_type $multi */ function touch_time( $edit = 1, $for_post = 1, $tab_index = 0, $multi = 0 ) { global $wp_locale, $comment; $post = get_post(); if ( $for_post ) $edit = ! ( in_array($post->post_status, array('draft', 'pending') ) && (!$post->post_date_gmt || '0000-00-00 00:00:00' == $post->post_date_gmt ) ); $tab_index_attribute = ''; if ( (int) $tab_index > 0 ) $tab_index_attribute = " tabindex=\"$tab_index\""; // echo '<label for="timestamp" style="display: block;"><input type="checkbox" class="checkbox" name="edit_date" value="1" id="timestamp"'.$tab_index_attribute.' /> '.__( 'Edit timestamp' ).'</label><br />'; $time_adj = current_time('timestamp'); $post_date = ($for_post) ? $post->post_date : $comment->comment_date; $jj = ($edit) ? mysql2date( 'd', $post_date, false ) : gmdate( 'd', $time_adj ); $mm = ($edit) ? mysql2date( 'm', $post_date, false ) : gmdate( 'm', $time_adj ); $aa = ($edit) ? mysql2date( 'Y', $post_date, false ) : gmdate( 'Y', $time_adj ); $hh = ($edit) ? mysql2date( 'H', $post_date, false ) : gmdate( 'H', $time_adj ); $mn = ($edit) ? mysql2date( 'i', $post_date, false ) : gmdate( 'i', $time_adj ); $ss = ($edit) ? mysql2date( 's', $post_date, false ) : gmdate( 's', $time_adj ); $cur_jj = gmdate( 'd', $time_adj ); $cur_mm = gmdate( 'm', $time_adj ); $cur_aa = gmdate( 'Y', $time_adj ); $cur_hh = gmdate( 'H', $time_adj ); $cur_mn = gmdate( 'i', $time_adj ); $month = "<select " . ( $multi ? '' : 'id="mm" ' ) . "name=\"mm\"$tab_index_attribute>\n"; for ( $i = 1; $i < 13; $i = $i +1 ) { $monthnum = zeroise($i, 2); $month .= "\t\t\t" . '<option value="' . $monthnum . '"'; if ( $i == $mm ) $month .= ' selected="selected"'; /* translators: 1: month number (01, 02, etc.), 2: month abbreviation */ $month .= '>' . sprintf( __( '%1$s-%2$s' ), $monthnum, $wp_locale->get_month_abbrev( $wp_locale->get_month( $i ) ) ) . "</option>\n"; } $month .= '</select>'; $day = '<input type="text" ' . ( $multi ? '' : 'id="jj" ' ) . 'name="jj" value="' . $jj . '" size="2" maxlength="2"' . $tab_index_attribute . ' autocomplete="off" />'; $year = '<input type="text" ' . ( $multi ? '' : 'id="aa" ' ) . 'name="aa" value="' . $aa . '" size="4" maxlength="4"' . $tab_index_attribute . ' autocomplete="off" />'; $hour = '<input type="text" ' . ( $multi ? '' : 'id="hh" ' ) . 'name="hh" value="' . $hh . '" size="2" maxlength="2"' . $tab_index_attribute . ' autocomplete="off" />'; $minute = '<input type="text" ' . ( $multi ? '' : 'id="mn" ' ) . 'name="mn" value="' . $mn . '" size="2" maxlength="2"' . $tab_index_attribute . ' autocomplete="off" />'; echo '<div class="timestamp-wrap">'; /* translators: 1: month input, 2: day input, 3: year input, 4: hour input, 5: minute input */ printf(__('%1$s%2$s, %3$s @ %4$s : %5$s'), $month, $day, $year, $hour, $minute); echo '</div><input type="hidden" id="ss" name="ss" value="' . $ss . '" />'; if ( $multi ) return; echo "\n\n"; foreach ( array('mm', 'jj', 'aa', 'hh', 'mn') as $timeunit ) { echo '<input type="hidden" id="hidden_' . $timeunit . '" name="hidden_' . $timeunit . '" value="' . $$timeunit . '" />' . "\n"; $cur_timeunit = 'cur_' . $timeunit; echo '<input type="hidden" id="'. $cur_timeunit . '" name="'. $cur_timeunit . '" value="' . $$cur_timeunit . '" />' . "\n"; } ?> <p> <a href="#edit_timestamp" class="save-timestamp hide-if-no-js button"><?php _e('OK'); ?></a> <a href="#edit_timestamp" class="cancel-timestamp hide-if-no-js"><?php _e('Cancel'); ?></a> </p> <?php } /** * {@internal Missing Short Description}} * * @since 1.5.0 * * @param unknown_type $default */ function page_template_dropdown( $default = '' ) { $templates = get_page_templates(); ksort( $templates ); foreach (array_keys( $templates ) as $template ) : if ( $default == $templates[$template] ) $selected = " selected='selected'"; else $selected = ''; echo "\n\t<option value='".$templates[$template]."' $selected>$template</option>"; endforeach; } /** * {@internal Missing Short Description}} * * @since 1.5.0 * * @param unknown_type $default * @param unknown_type $parent * @param unknown_type $level * @return unknown */ function parent_dropdown( $default = 0, $parent = 0, $level = 0 ) { global $wpdb; $post = get_post(); $items = $wpdb->get_results( $wpdb->prepare("SELECT ID, post_parent, post_title FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'page' ORDER BY menu_order", $parent) ); if ( $items ) { foreach ( $items as $item ) { // A page cannot be its own parent. if ( $post->ID && $item->ID == $post->ID ) continue; $pad = str_repeat( '&nbsp;', $level * 3 ); if ( $item->ID == $default) $current = ' selected="selected"'; else $current = ''; echo "\n\t<option class='level-$level' value='$item->ID'$current>$pad " . esc_html($item->post_title) . "</option>"; parent_dropdown( $default, $item->ID, $level +1 ); } } else { return false; } } /** * {@internal Missing Short Description}} * * @since 2.0.0 * * @param unknown_type $id * @return unknown */ function the_attachment_links( $id = false ) { $id = (int) $id; $post = get_post( $id ); if ( $post->post_type != 'attachment' ) return false; $icon = wp_get_attachment_image( $post->ID, 'thumbnail', true ); $attachment_data = wp_get_attachment_metadata( $id ); $thumb = isset( $attachment_data['thumb'] ); ?> <form id="the-attachment-links"> <table> <col /> <col class="widefat" /> <tr> <th scope="row"><?php _e( 'URL' ) ?></th> <td><textarea rows="1" cols="40" type="text" class="attachmentlinks" readonly="readonly"><?php echo esc_textarea( wp_get_attachment_url() ); ?></textarea></td> </tr> <?php if ( $icon ) : ?> <tr> <th scope="row"><?php $thumb ? _e( 'Thumbnail linked to file' ) : _e( 'Image linked to file' ); ?></th> <td><textarea rows="1" cols="40" type="text" class="attachmentlinks" readonly="readonly"><a href="<?php echo wp_get_attachment_url(); ?>"><?php echo $icon ?></a></textarea></td> </tr> <tr> <th scope="row"><?php $thumb ? _e( 'Thumbnail linked to page' ) : _e( 'Image linked to page' ); ?></th> <td><textarea rows="1" cols="40" type="text" class="attachmentlinks" readonly="readonly"><a href="<?php echo get_attachment_link( $post->ID ) ?>" rel="attachment wp-att-<?php echo $post->ID; ?>"><?php echo $icon ?></a></textarea></td> </tr> <?php else : ?> <tr> <th scope="row"><?php _e( 'Link to file' ) ?></th> <td><textarea rows="1" cols="40" type="text" class="attachmentlinks" readonly="readonly"><a href="<?php echo wp_get_attachment_url(); ?>" class="attachmentlink"><?php echo basename( wp_get_attachment_url() ); ?></a></textarea></td> </tr> <tr> <th scope="row"><?php _e( 'Link to page' ) ?></th> <td><textarea rows="1" cols="40" type="text" class="attachmentlinks" readonly="readonly"><a href="<?php echo get_attachment_link( $post->ID ) ?>" rel="attachment wp-att-<?php echo $post->ID ?>"><?php the_title(); ?></a></textarea></td> </tr> <?php endif; ?> </table> </form> <?php } /** * Print out <option> html elements for role selectors * * @since 2.1.0 * * @param string $selected slug for the role that should be already selected */ function wp_dropdown_roles( $selected = false ) { $p = ''; $r = ''; $editable_roles = get_editable_roles(); foreach ( $editable_roles as $role => $details ) { $name = translate_user_role($details['name'] ); if ( $selected == $role ) // preselect specified role $p = "\n\t<option selected='selected' value='" . esc_attr($role) . "'>$name</option>"; else $r .= "\n\t<option value='" . esc_attr($role) . "'>$name</option>"; } echo $p . $r; } /** * Outputs the form used by the importers to accept the data to be imported * * @since 2.0.0 * * @param string $action The action attribute for the form. */ function wp_import_upload_form( $action ) { $bytes = apply_filters( 'import_upload_size_limit', wp_max_upload_size() ); $size = wp_convert_bytes_to_hr( $bytes ); $upload_dir = wp_upload_dir(); if ( ! empty( $upload_dir['error'] ) ) : ?><div class="error"><p><?php _e('Before you can upload your import file, you will need to fix the following error:'); ?></p> <p><strong><?php echo $upload_dir['error']; ?></strong></p></div><?php else : ?> <form enctype="multipart/form-data" id="import-upload-form" method="post" class="wp-upload-form" action="<?php echo esc_attr(wp_nonce_url($action, 'import-upload')); ?>"> <p> <label for="upload"><?php _e( 'Choose a file from your computer:' ); ?></label> (<?php printf( __('Maximum size: %s' ), $size ); ?>) <input type="file" id="upload" name="import" size="25" /> <input type="hidden" name="action" value="save" /> <input type="hidden" name="max_file_size" value="<?php echo $bytes; ?>" /> </p> <?php submit_button( __('Upload file and import'), 'button' ); ?> </form> <?php endif; } /** * Add a meta box to an edit form. * * @since 2.5.0 * * @param string $id String for use in the 'id' attribute of tags. * @param string $title Title of the meta box. * @param string $callback Function that fills the box with the desired content. The function should echo its output. * @param string|object $screen Optional. The screen on which to show the box (post, page, link). Defaults to current screen. * @param string $context Optional. The context within the page where the boxes should show ('normal', 'advanced'). * @param string $priority Optional. The priority within the context where the boxes should show ('high', 'low'). */ function add_meta_box( $id, $title, $callback, $screen = null, $context = 'advanced', $priority = 'default', $callback_args = null ) { global $wp_meta_boxes; if ( empty( $screen ) ) $screen = get_current_screen(); elseif ( is_string( $screen ) ) $screen = convert_to_screen( $screen ); $page = $screen->id; if ( !isset($wp_meta_boxes) ) $wp_meta_boxes = array(); if ( !isset($wp_meta_boxes[$page]) ) $wp_meta_boxes[$page] = array(); if ( !isset($wp_meta_boxes[$page][$context]) ) $wp_meta_boxes[$page][$context] = array(); foreach ( array_keys($wp_meta_boxes[$page]) as $a_context ) { foreach ( array('high', 'core', 'default', 'low') as $a_priority ) { if ( !isset($wp_meta_boxes[$page][$a_context][$a_priority][$id]) ) continue; // If a core box was previously added or removed by a plugin, don't add. if ( 'core' == $priority ) { // If core box previously deleted, don't add if ( false === $wp_meta_boxes[$page][$a_context][$a_priority][$id] ) return; // If box was added with default priority, give it core priority to maintain sort order if ( 'default' == $a_priority ) { $wp_meta_boxes[$page][$a_context]['core'][$id] = $wp_meta_boxes[$page][$a_context]['default'][$id]; unset($wp_meta_boxes[$page][$a_context]['default'][$id]); } return; } // If no priority given and id already present, use existing priority if ( empty($priority) ) { $priority = $a_priority; // else if we're adding to the sorted priority, we don't know the title or callback. Grab them from the previously added context/priority. } elseif ( 'sorted' == $priority ) { $title = $wp_meta_boxes[$page][$a_context][$a_priority][$id]['title']; $callback = $wp_meta_boxes[$page][$a_context][$a_priority][$id]['callback']; $callback_args = $wp_meta_boxes[$page][$a_context][$a_priority][$id]['args']; } // An id can be in only one priority and one context if ( $priority != $a_priority || $context != $a_context ) unset($wp_meta_boxes[$page][$a_context][$a_priority][$id]); } } if ( empty($priority) ) $priority = 'low'; if ( !isset($wp_meta_boxes[$page][$context][$priority]) ) $wp_meta_boxes[$page][$context][$priority] = array(); $wp_meta_boxes[$page][$context][$priority][$id] = array('id' => $id, 'title' => $title, 'callback' => $callback, 'args' => $callback_args); } /** * Meta-Box template function * * @since 2.5.0 * * @param string|object $screen Screen identifier * @param string $context box context * @param mixed $object gets passed to the box callback function as first parameter * @return int number of meta_boxes */ function do_meta_boxes( $screen, $context, $object ) { global $wp_meta_boxes; static $already_sorted = false; if ( empty( $screen ) ) $screen = get_current_screen(); elseif ( is_string( $screen ) ) $screen = convert_to_screen( $screen ); $page = $screen->id; $hidden = get_hidden_meta_boxes( $screen ); printf('<div id="%s-sortables" class="meta-box-sortables">', htmlspecialchars($context)); $i = 0; do { // Grab the ones the user has manually sorted. Pull them out of their previous context/priority and into the one the user chose if ( !$already_sorted && $sorted = get_user_option( "meta-box-order_$page" ) ) { foreach ( $sorted as $box_context => $ids ) { foreach ( explode(',', $ids ) as $id ) { if ( $id && 'dashboard_browser_nag' !== $id ) add_meta_box( $id, null, null, $screen, $box_context, 'sorted' ); } } } $already_sorted = true; if ( !isset($wp_meta_boxes) || !isset($wp_meta_boxes[$page]) || !isset($wp_meta_boxes[$page][$context]) ) break; foreach ( array('high', 'sorted', 'core', 'default', 'low') as $priority ) { if ( isset($wp_meta_boxes[$page][$context][$priority]) ) { foreach ( (array) $wp_meta_boxes[$page][$context][$priority] as $box ) { if ( false == $box || ! $box['title'] ) continue; $i++; $style = ''; $hidden_class = in_array($box['id'], $hidden) ? ' hide-if-js' : ''; echo '<div id="' . $box['id'] . '" class="postbox ' . postbox_classes($box['id'], $page) . $hidden_class . '" ' . '>' . "\n"; if ( 'dashboard_browser_nag' != $box['id'] ) echo '<div class="handlediv" title="' . esc_attr__('Click to toggle') . '"><br /></div>'; echo "<h3 class='hndle'><span>{$box['title']}</span></h3>\n"; echo '<div class="inside">' . "\n"; call_user_func($box['callback'], $object, $box); echo "</div>\n"; echo "</div>\n"; } } } } while(0); echo "</div>"; return $i; } /** * Remove a meta box from an edit form. * * @since 2.6.0 * * @param string $id String for use in the 'id' attribute of tags. * @param string|object $screen The screen on which to show the box (post, page, link). * @param string $context The context within the page where the boxes should show ('normal', 'advanced'). */ function remove_meta_box($id, $screen, $context) { global $wp_meta_boxes; if ( empty( $screen ) ) $screen = get_current_screen(); elseif ( is_string( $screen ) ) $screen = convert_to_screen( $screen ); $page = $screen->id; if ( !isset($wp_meta_boxes) ) $wp_meta_boxes = array(); if ( !isset($wp_meta_boxes[$page]) ) $wp_meta_boxes[$page] = array(); if ( !isset($wp_meta_boxes[$page][$context]) ) $wp_meta_boxes[$page][$context] = array(); foreach ( array('high', 'core', 'default', 'low') as $priority ) $wp_meta_boxes[$page][$context][$priority][$id] = false; } /** * Add a new section to a settings page. * * Part of the Settings API. Use this to define new settings sections for an admin page. * Show settings sections in your admin page callback function with do_settings_sections(). * Add settings fields to your section with add_settings_field() * * The $callback argument should be the name of a function that echoes out any * content you want to show at the top of the settings section before the actual * fields. It can output nothing if you want. * * @since 2.7.0 * * @global $wp_settings_sections Storage array of all settings sections added to admin pages * * @param string $id Slug-name to identify the section. Used in the 'id' attribute of tags. * @param string $title Formatted title of the section. Shown as the heading for the section. * @param string $callback Function that echos out any content at the top of the section (between heading and fields). * @param string $page The slug-name of the settings page on which to show the section. Built-in pages include 'general', 'reading', 'writing', 'discussion', 'media', etc. Create your own using add_options_page(); */ function add_settings_section($id, $title, $callback, $page) { global $wp_settings_sections; if ( 'misc' == $page ) { _deprecated_argument( __FUNCTION__, '3.0', sprintf( __( 'The "%s" options group has been removed. Use another settings group.' ), 'misc' ) ); $page = 'general'; } if ( 'privacy' == $page ) { _deprecated_argument( __FUNCTION__, '3.5', sprintf( __( 'The "%s" options group has been removed. Use another settings group.' ), 'privacy' ) ); $page = 'reading'; } if ( !isset($wp_settings_sections) ) $wp_settings_sections = array(); if ( !isset($wp_settings_sections[$page]) ) $wp_settings_sections[$page] = array(); if ( !isset($wp_settings_sections[$page][$id]) ) $wp_settings_sections[$page][$id] = array(); $wp_settings_sections[$page][$id] = array('id' => $id, 'title' => $title, 'callback' => $callback); } /** * Add a new field to a section of a settings page * * Part of the Settings API. Use this to define a settings field that will show * as part of a settings section inside a settings page. The fields are shown using * do_settings_fields() in do_settings-sections() * * The $callback argument should be the name of a function that echoes out the * html input tags for this setting field. Use get_option() to retrieve existing * values to show. * * @since 2.7.0 * * @global $wp_settings_fields Storage array of settings fields and info about their pages/sections * * @param string $id Slug-name to identify the field. Used in the 'id' attribute of tags. * @param string $title Formatted title of the field. Shown as the label for the field during output. * @param string $callback Function that fills the field with the desired form inputs. The function should echo its output. * @param string $page The slug-name of the settings page on which to show the section (general, reading, writing, ...). * @param string $section The slug-name of the section of the settings page in which to show the box (default, ...). * @param array $args Additional arguments */ function add_settings_field($id, $title, $callback, $page, $section = 'default', $args = array()) { global $wp_settings_fields; if ( 'misc' == $page ) { _deprecated_argument( __FUNCTION__, '3.0', __( 'The miscellaneous options group has been removed. Use another settings group.' ) ); $page = 'general'; } if ( 'privacy' == $page ) { _deprecated_argument( __FUNCTION__, '3.5', __( 'The privacy options group has been removed. Use another settings group.' ) ); $page = 'reading'; } if ( !isset($wp_settings_fields) ) $wp_settings_fields = array(); if ( !isset($wp_settings_fields[$page]) ) $wp_settings_fields[$page] = array(); if ( !isset($wp_settings_fields[$page][$section]) ) $wp_settings_fields[$page][$section] = array(); $wp_settings_fields[$page][$section][$id] = array('id' => $id, 'title' => $title, 'callback' => $callback, 'args' => $args); } /** * Prints out all settings sections added to a particular settings page * * Part of the Settings API. Use this in a settings page callback function * to output all the sections and fields that were added to that $page with * add_settings_section() and add_settings_field() * * @global $wp_settings_sections Storage array of all settings sections added to admin pages * @global $wp_settings_fields Storage array of settings fields and info about their pages/sections * @since 2.7.0 * * @param string $page The slug name of the page whos settings sections you want to output */ function do_settings_sections( $page ) { global $wp_settings_sections, $wp_settings_fields; if ( ! isset( $wp_settings_sections ) || !isset( $wp_settings_sections[$page] ) ) return; foreach ( (array) $wp_settings_sections[$page] as $section ) { if ( $section['title'] ) echo "<h3>{$section['title']}</h3>\n"; if ( $section['callback'] ) call_user_func( $section['callback'], $section ); if ( ! isset( $wp_settings_fields ) || !isset( $wp_settings_fields[$page] ) || !isset( $wp_settings_fields[$page][$section['id']] ) ) continue; echo '<table class="form-table">'; do_settings_fields( $page, $section['id'] ); echo '</table>'; } } /** * Print out the settings fields for a particular settings section * * Part of the Settings API. Use this in a settings page to output * a specific section. Should normally be called by do_settings_sections() * rather than directly. * * @global $wp_settings_fields Storage array of settings fields and their pages/sections * * @since 2.7.0 * * @param string $page Slug title of the admin page who's settings fields you want to show. * @param section $section Slug title of the settings section who's fields you want to show. */ function do_settings_fields($page, $section) { global $wp_settings_fields; if ( !isset($wp_settings_fields) || !isset($wp_settings_fields[$page]) || !isset($wp_settings_fields[$page][$section]) ) return; foreach ( (array) $wp_settings_fields[$page][$section] as $field ) { echo '<tr valign="top">'; if ( !empty($field['args']['label_for']) ) echo '<th scope="row"><label for="' . esc_attr( $field['args']['label_for'] ) . '">' . $field['title'] . '</label></th>'; else echo '<th scope="row">' . $field['title'] . '</th>'; echo '<td>'; call_user_func($field['callback'], $field['args']); echo '</td>'; echo '</tr>'; } } /** * Register a settings error to be displayed to the user * * Part of the Settings API. Use this to show messages to users about settings validation * problems, missing settings or anything else. * * Settings errors should be added inside the $sanitize_callback function defined in * register_setting() for a given setting to give feedback about the submission. * * By default messages will show immediately after the submission that generated the error. * Additional calls to settings_errors() can be used to show errors even when the settings * page is first accessed. * * @since 3.0.0 * * @global array $wp_settings_errors Storage array of errors registered during this pageload * * @param string $setting Slug title of the setting to which this error applies * @param string $code Slug-name to identify the error. Used as part of 'id' attribute in HTML output. * @param string $message The formatted message text to display to the user (will be shown inside styled <div> and <p>) * @param string $type The type of message it is, controls HTML class. Use 'error' or 'updated'. */ function add_settings_error( $setting, $code, $message, $type = 'error' ) { global $wp_settings_errors; if ( !isset($wp_settings_errors) ) $wp_settings_errors = array(); $new_error = array( 'setting' => $setting, 'code' => $code, 'message' => $message, 'type' => $type ); $wp_settings_errors[] = $new_error; } /** * Fetch settings errors registered by add_settings_error() * * Checks the $wp_settings_errors array for any errors declared during the current * pageload and returns them. * * If changes were just submitted ($_GET['settings-updated']) and settings errors were saved * to the 'settings_errors' transient then those errors will be returned instead. This * is used to pass errors back across pageloads. * * Use the $sanitize argument to manually re-sanitize the option before returning errors. * This is useful if you have errors or notices you want to show even when the user * hasn't submitted data (i.e. when they first load an options page, or in admin_notices action hook) * * @since 3.0.0 * * @global array $wp_settings_errors Storage array of errors registered during this pageload * * @param string $setting Optional slug title of a specific setting who's errors you want. * @param boolean $sanitize Whether to re-sanitize the setting value before returning errors. * @return array Array of settings errors */ function get_settings_errors( $setting = '', $sanitize = false ) { global $wp_settings_errors; // If $sanitize is true, manually re-run the sanitizisation for this option // This allows the $sanitize_callback from register_setting() to run, adding // any settings errors you want to show by default. if ( $sanitize ) sanitize_option( $setting, get_option( $setting ) ); // If settings were passed back from options.php then use them if ( isset( $_GET['settings-updated'] ) && $_GET['settings-updated'] && get_transient( 'settings_errors' ) ) { $wp_settings_errors = array_merge( (array) $wp_settings_errors, get_transient( 'settings_errors' ) ); delete_transient( 'settings_errors' ); } // Check global in case errors have been added on this pageload if ( ! count( $wp_settings_errors ) ) return array(); // Filter the results to those of a specific setting if one was set if ( $setting ) { $setting_errors = array(); foreach ( (array) $wp_settings_errors as $key => $details ) { if ( $setting == $details['setting'] ) $setting_errors[] = $wp_settings_errors[$key]; } return $setting_errors; } return $wp_settings_errors; } /** * Display settings errors registered by add_settings_error() * * Part of the Settings API. Outputs a <div> for each error retrieved by get_settings_errors(). * * This is called automatically after a settings page based on the Settings API is submitted. * Errors should be added during the validation callback function for a setting defined in register_setting() * * The $sanitize option is passed into get_settings_errors() and will re-run the setting sanitization * on its current value. * * The $hide_on_update option will cause errors to only show when the settings page is first loaded. * if the user has already saved new values it will be hidden to avoid repeating messages already * shown in the default error reporting after submission. This is useful to show general errors like missing * settings when the user arrives at the settings page. * * @since 3.0.0 * * @param string $setting Optional slug title of a specific setting who's errors you want. * @param boolean $sanitize Whether to re-sanitize the setting value before returning errors. * @param boolean $hide_on_update If set to true errors will not be shown if the settings page has already been submitted. */ function settings_errors( $setting = '', $sanitize = false, $hide_on_update = false ) { if ( $hide_on_update && ! empty( $_GET['settings-updated'] ) ) return; $settings_errors = get_settings_errors( $setting, $sanitize ); if ( empty( $settings_errors ) ) return; $output = ''; foreach ( $settings_errors as $key => $details ) { $css_id = 'setting-error-' . $details['code']; $css_class = $details['type'] . ' settings-error'; $output .= "<div id='$css_id' class='$css_class'> \n"; $output .= "<p><strong>{$details['message']}</strong></p>"; $output .= "</div> \n"; } echo $output; } /** * {@internal Missing Short Description}} * * @since 2.7.0 * * @param unknown_type $found_action */ function find_posts_div($found_action = '') { ?> <div id="find-posts" class="find-box" style="display:none;"> <div id="find-posts-head" class="find-box-head"><?php _e('Find Posts or Pages'); ?></div> <div class="find-box-inside"> <div class="find-box-search"> <?php if ( $found_action ) { ?> <input type="hidden" name="found_action" value="<?php echo esc_attr($found_action); ?>" /> <?php } ?> <input type="hidden" name="affected" id="affected" value="" /> <?php wp_nonce_field( 'find-posts', '_ajax_nonce', false ); ?> <label class="screen-reader-text" for="find-posts-input"><?php _e( 'Search' ); ?></label> <input type="text" id="find-posts-input" name="ps" value="" /> <span class="spinner"></span> <input type="button" id="find-posts-search" value="<?php esc_attr_e( 'Search' ); ?>" class="button" /> </div> <div id="find-posts-response"></div> </div> <div class="find-box-buttons"> <input id="find-posts-close" type="button" class="button alignleft" value="<?php esc_attr_e('Close'); ?>" /> <?php submit_button( __( 'Select' ), 'button-primary alignright', 'find-posts-submit', false ); ?> </div> </div> <?php } /** * Display the post password. * * The password is passed through {@link esc_attr()} to ensure that it * is safe for placing in an html attribute. * * @uses attr * @since 2.7.0 */ function the_post_password() { $post = get_post(); if ( isset( $post->post_password ) ) echo esc_attr( $post->post_password ); } /** * Get the post title. * * The post title is fetched and if it is blank then a default string is * returned. * * @since 2.7.0 * @param mixed $post Post id or object. If not supplied the global $post is used. * @return string The post title if set */ function _draft_or_post_title( $post = 0 ) { $title = get_the_title( $post ); if ( empty( $title ) ) $title = __( '(no title)' ); return $title; } /** * Display the search query. * * A simple wrapper to display the "s" parameter in a GET URI. This function * should only be used when {@link the_search_query()} cannot. * * @uses attr * @since 2.7.0 * */ function _admin_search_query() { echo isset($_REQUEST['s']) ? esc_attr( stripslashes( $_REQUEST['s'] ) ) : ''; } /** * Generic Iframe header for use with Thickbox * * @since 2.7.0 * @param string $title Title of the Iframe page. * @param bool $limit_styles Limit styles to colour-related styles only (unless others are enqueued). * */ function iframe_header( $title = '', $limit_styles = false ) { show_admin_bar( false ); global $hook_suffix, $current_user, $admin_body_class, $wp_locale; $admin_body_class = preg_replace('/[^a-z0-9_-]+/i', '-', $hook_suffix); $current_screen = get_current_screen(); @header( 'Content-Type: ' . get_option( 'html_type' ) . '; charset=' . get_option( 'blog_charset' ) ); _wp_admin_html_begin(); ?> <title><?php bloginfo('name') ?> &rsaquo; <?php echo $title ?> &#8212; <?php _e('WordPress'); ?></title> <?php wp_enqueue_style( 'colors' ); ?> <script type="text/javascript"> //<![CDATA[ addLoadEvent = function(func){if(typeof jQuery!="undefined")jQuery(document).ready(func);else if(typeof wpOnload!='function'){wpOnload=func;}else{var oldonload=wpOnload;wpOnload=function(){oldonload();func();}}}; function tb_close(){var win=window.dialogArguments||opener||parent||top;win.tb_remove();} var userSettings = { 'url': '<?php echo SITECOOKIEPATH; ?>', 'uid': '<?php if ( ! isset($current_user) ) $current_user = wp_get_current_user(); echo $current_user->ID; ?>', 'time':'<?php echo time() ?>' }, ajaxurl = '<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>', pagenow = '<?php echo $current_screen->id; ?>', typenow = '<?php echo $current_screen->post_type; ?>', adminpage = '<?php echo $admin_body_class; ?>', thousandsSeparator = '<?php echo addslashes( $wp_locale->number_format['thousands_sep'] ); ?>', decimalPoint = '<?php echo addslashes( $wp_locale->number_format['decimal_point'] ); ?>', isRtl = <?php echo (int) is_rtl(); ?>; //]]> </script> <?php do_action('admin_enqueue_scripts', $hook_suffix); do_action("admin_print_styles-$hook_suffix"); do_action('admin_print_styles'); do_action("admin_print_scripts-$hook_suffix"); do_action('admin_print_scripts'); do_action("admin_head-$hook_suffix"); do_action('admin_head'); $admin_body_class .= ' locale-' . sanitize_html_class( strtolower( str_replace( '_', '-', get_locale() ) ) ); ?> </head> <body<?php if ( isset($GLOBALS['body_id']) ) echo ' id="' . $GLOBALS['body_id'] . '"'; ?> class="wp-admin wp-core-ui no-js iframe <?php echo apply_filters( 'admin_body_class', '' ) . ' ' . $admin_body_class; ?>"> <script type="text/javascript"> //<![CDATA[ (function(){ var c = document.body.className; c = c.replace(/no-js/, 'js'); document.body.className = c; })(); //]]> </script> <?php } /** * Generic Iframe footer for use with Thickbox * * @since 2.7.0 * */ function iframe_footer() { //We're going to hide any footer output on iframe pages, but run the hooks anyway since they output Javascript or other needed content. ?> <div class="hidden"> <?php do_action('admin_footer', ''); do_action('admin_print_footer_scripts'); ?> </div> <script type="text/javascript">if(typeof wpOnload=="function")wpOnload();</script> </body> </html> <?php } function _post_states($post) { $post_states = array(); if ( isset( $_REQUEST['post_status'] ) ) $post_status = $_REQUEST['post_status']; else $post_status = ''; if ( !empty($post->post_password) ) $post_states['protected'] = __('Password protected'); if ( 'private' == $post->post_status && 'private' != $post_status ) $post_states['private'] = __('Private'); if ( 'draft' == $post->post_status && 'draft' != $post_status ) $post_states['draft'] = __('Draft'); if ( 'pending' == $post->post_status && 'pending' != $post_status ) /* translators: post state */ $post_states['pending'] = _x('Pending', 'post state'); if ( is_sticky($post->ID) ) $post_states['sticky'] = __('Sticky'); $post_states = apply_filters( 'display_post_states', $post_states ); if ( ! empty($post_states) ) { $state_count = count($post_states); $i = 0; echo ' - '; foreach ( $post_states as $state ) { ++$i; ( $i == $state_count ) ? $sep = '' : $sep = ', '; echo "<span class='post-state'>$state$sep</span>"; } } if ( get_post_format( $post->ID ) ) echo ' - <span class="post-state-format">' . get_post_format_string( get_post_format( $post->ID ) ) . '</span>'; } function _media_states( $post ) { $media_states = array(); $stylesheet = get_option('stylesheet'); if ( current_theme_supports( 'custom-header') ) { $meta_header = get_post_meta($post->ID, '_wp_attachment_is_custom_header', true ); if ( ! empty( $meta_header ) && $meta_header == $stylesheet ) $media_states[] = __( 'Header Image' ); } if ( current_theme_supports( 'custom-background') ) { $meta_background = get_post_meta($post->ID, '_wp_attachment_is_custom_background', true ); if ( ! empty( $meta_background ) && $meta_background == $stylesheet ) $media_states[] = __( 'Background Image' ); } $media_states = apply_filters( 'display_media_states', $media_states ); if ( ! empty( $media_states ) ) { $state_count = count( $media_states ); $i = 0; echo ' - '; foreach ( $media_states as $state ) { ++$i; ( $i == $state_count ) ? $sep = '' : $sep = ', '; echo "<span class='post-state'>$state$sep</span>"; } } } /** * Test support for compressing JavaScript from PHP * * Outputs JavaScript that tests if compression from PHP works as expected * and sets an option with the result. Has no effect when the current user * is not an administrator. To run the test again the option 'can_compress_scripts' * has to be deleted. * * @since 2.8.0 */ function compression_test() { ?> <script type="text/javascript"> /* <![CDATA[ */ var testCompression = { get : function(test) { var x; if ( window.XMLHttpRequest ) { x = new XMLHttpRequest(); } else { try{x=new ActiveXObject('Msxml2.XMLHTTP');}catch(e){try{x=new ActiveXObject('Microsoft.XMLHTTP');}catch(e){};} } if (x) { x.onreadystatechange = function() { var r, h; if ( x.readyState == 4 ) { r = x.responseText.substr(0, 18); h = x.getResponseHeader('Content-Encoding'); testCompression.check(r, h, test); } } x.open('GET', ajaxurl + '?action=wp-compression-test&test='+test+'&'+(new Date()).getTime(), true); x.send(''); } }, check : function(r, h, test) { if ( ! r && ! test ) this.get(1); if ( 1 == test ) { if ( h && ( h.match(/deflate/i) || h.match(/gzip/i) ) ) this.get('no'); else this.get(2); return; } if ( 2 == test ) { if ( '"wpCompressionTest' == r ) this.get('yes'); else this.get('no'); } } }; testCompression.check(); /* ]]> */ </script> <?php } /** * Echos a submit button, with provided text and appropriate class * * @since 3.1.0 * * @param string $text The text of the button (defaults to 'Save Changes') * @param string $type The type of button. One of: primary, secondary, delete * @param string $name The HTML name of the submit button. Defaults to "submit". If no id attribute * is given in $other_attributes below, $name will be used as the button's id. * @param bool $wrap True if the output button should be wrapped in a paragraph tag, * false otherwise. Defaults to true * @param array|string $other_attributes Other attributes that should be output with the button, * mapping attributes to their values, such as array( 'tabindex' => '1' ). * These attributes will be output as attribute="value", such as tabindex="1". * Defaults to no other attributes. Other attributes can also be provided as a * string such as 'tabindex="1"', though the array format is typically cleaner. */ function submit_button( $text = null, $type = 'primary', $name = 'submit', $wrap = true, $other_attributes = null ) { echo get_submit_button( $text, $type, $name, $wrap, $other_attributes ); } /** * Returns a submit button, with provided text and appropriate class * * @since 3.1.0 * * @param string $text The text of the button (defaults to 'Save Changes') * @param string $type The type of button. One of: primary, secondary, delete * @param string $name The HTML name of the submit button. Defaults to "submit". If no id attribute * is given in $other_attributes below, $name will be used as the button's id. * @param bool $wrap True if the output button should be wrapped in a paragraph tag, * false otherwise. Defaults to true * @param array|string $other_attributes Other attributes that should be output with the button, * mapping attributes to their values, such as array( 'tabindex' => '1' ). * These attributes will be output as attribute="value", such as tabindex="1". * Defaults to no other attributes. Other attributes can also be provided as a * string such as 'tabindex="1"', though the array format is typically cleaner. */ function get_submit_button( $text = null, $type = 'primary large', $name = 'submit', $wrap = true, $other_attributes = null ) { if ( ! is_array( $type ) ) $type = explode( ' ', $type ); $button_shorthand = array( 'primary', 'small', 'large' ); $classes = array( 'button' ); foreach ( $type as $t ) { if ( 'secondary' === $t || 'button-secondary' === $t ) continue; $classes[] = in_array( $t, $button_shorthand ) ? 'button-' . $t : $t; } $class = implode( ' ', array_unique( $classes ) ); if ( 'delete' === $type ) $class = 'button-secondary delete'; $text = $text ? $text : __( 'Save Changes' ); // Default the id attribute to $name unless an id was specifically provided in $other_attributes $id = $name; if ( is_array( $other_attributes ) && isset( $other_attributes['id'] ) ) { $id = $other_attributes['id']; unset( $other_attributes['id'] ); } $attributes = ''; if ( is_array( $other_attributes ) ) { foreach ( $other_attributes as $attribute => $value ) { $attributes .= $attribute . '="' . esc_attr( $value ) . '" '; // Trailing space is important } } else if ( !empty( $other_attributes ) ) { // Attributes provided as a string $attributes = $other_attributes; } $button = '<input type="submit" name="' . esc_attr( $name ) . '" id="' . esc_attr( $id ) . '" class="' . esc_attr( $class ); $button .= '" value="' . esc_attr( $text ) . '" ' . $attributes . ' />'; if ( $wrap ) { $button = '<p class="submit">' . $button . '</p>'; } return $button; } function _wp_admin_html_begin() { $admin_html_class = ( is_admin_bar_showing() ) ? 'wp-toolbar' : ''; ?> <!DOCTYPE html> <!--[if IE 8]> <html xmlns="http://www.w3.org/1999/xhtml" class="ie8 <?php echo $admin_html_class; ?>" <?php do_action('admin_xml_ns'); ?> <?php language_attributes(); ?>> <![endif]--> <!--[if !(IE 8) ]><!--> <html xmlns="http://www.w3.org/1999/xhtml" class="<?php echo $admin_html_class; ?>" <?php do_action('admin_xml_ns'); ?> <?php language_attributes(); ?>> <!--<![endif]--> <head> <meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php echo get_option('blog_charset'); ?>" /> <?php } final class WP_Internal_Pointers { /** * Initializes the new feature pointers. * * @since 3.3.0 * * All pointers can be disabled using the following: * remove_action( 'admin_enqueue_scripts', array( 'WP_Internal_Pointers', 'enqueue_scripts' ) ); * * Individual pointers (e.g. wp330_toolbar) can be disabled using the following: * remove_action( 'admin_print_footer_scripts', array( 'WP_Internal_Pointers', 'pointer_wp330_toolbar' ) ); */ public static function enqueue_scripts( $hook_suffix ) { /* * Register feature pointers * Format: array( hook_suffix => pointer_id ) */ $registered_pointers = array( 'index.php' => 'wp330_toolbar', 'post-new.php' => 'wp350_media', 'post.php' => 'wp350_media', 'themes.php' => array( 'wp330_saving_widgets', 'wp340_customize_current_theme_link' ), 'appearance_page_custom-header' => 'wp340_choose_image_from_library', 'appearance_page_custom-background' => 'wp340_choose_image_from_library', ); // Check if screen related pointer is registered if ( empty( $registered_pointers[ $hook_suffix ] ) ) return; $pointers = (array) $registered_pointers[ $hook_suffix ]; $caps_required = array( 'wp330_saving_widgets' => array( 'edit_theme_options', 'switch_themes' ), 'wp340_customize_current_theme_link' => array( 'edit_theme_options' ), 'wp340_choose_image_from_library' => array( 'edit_theme_options' ), 'wp350_media' => array( 'upload_files' ), ); // Get dismissed pointers $dismissed = explode( ',', (string) get_user_meta( get_current_user_id(), 'dismissed_wp_pointers', true ) ); $got_pointers = false; foreach ( array_diff( $pointers, $dismissed ) as $pointer ) { if ( isset( $caps_required[ $pointer ] ) ) { foreach ( $caps_required[ $pointer ] as $cap ) { if ( ! current_user_can( $cap ) ) continue 2; } } // Bind pointer print function add_action( 'admin_print_footer_scripts', array( 'WP_Internal_Pointers', 'pointer_' . $pointer ) ); $got_pointers = true; } if ( ! $got_pointers ) return; // Add pointers script and style to queue wp_enqueue_style( 'wp-pointer' ); wp_enqueue_script( 'wp-pointer' ); } /** * Print the pointer javascript data. * * @since 3.3.0 * * @param string $pointer_id The pointer ID. * @param string $selector The HTML elements, on which the pointer should be attached. * @param array $args Arguments to be passed to the pointer JS (see wp-pointer.js). */ private static function print_js( $pointer_id, $selector, $args ) { if ( empty( $pointer_id ) || empty( $selector ) || empty( $args ) || empty( $args['content'] ) ) return; ?> <script type="text/javascript"> //<![CDATA[ (function($){ var options = <?php echo json_encode( $args ); ?>, setup; if ( ! options ) return; options = $.extend( options, { close: function() { $.post( ajaxurl, { pointer: '<?php echo $pointer_id; ?>', action: 'dismiss-wp-pointer' }); } }); setup = function() { $('<?php echo $selector; ?>').pointer( options ).pointer('open'); }; if ( options.position && options.position.defer_loading ) $(window).bind( 'load.wp-pointers', setup ); else $(document).ready( setup ); })( jQuery ); //]]> </script> <?php } public static function pointer_wp330_toolbar() { $content = '<h3>' . __( 'New Feature: Toolbar' ) . '</h3>'; $content .= '<p>' . __( 'We&#8217;ve combined the admin bar and the old Dashboard header into one persistent toolbar. Hover over the toolbar items to see what&#8217;s new.' ) . '</p>'; if ( is_multisite() && is_super_admin() ) $content .= '<p>' . __( 'Network Admin is now located in the My Sites menu.' ) . '</p>'; WP_Internal_Pointers::print_js( 'wp330_toolbar', '#wpadminbar', array( 'content' => $content, 'position' => array( 'edge' => 'top', 'align' => 'center' ), ) ); } /** * Print 'Updated Media Uploader' for 3.3.0. * * @since 3.3.0 */ public static function pointer_wp330_media_uploader() {} /** * Print 'New Feature: Saving Widgets' for 3.3.0. * * @since 3.3.0 */ public static function pointer_wp330_saving_widgets() { $content = '<h3>' . __( 'New Feature: Saving Widgets' ) . '</h3>'; $content .= '<p>' . __( 'If you change your mind and revert to your previous theme, we&#8217;ll put the widgets back the way you had them.' ) . '</p>'; WP_Internal_Pointers::print_js( 'wp330_saving_widgets', '#message2', array( 'content' => $content, 'position' => array( 'edge' => 'top', 'align' => is_rtl() ? 'right' : 'left' ), ) ); } /** * Print 'New Feature: Current Theme Customize Link' for 3.4.0. * * @since 3.4.0 */ public static function pointer_wp340_customize_current_theme_link() { $content = '<h3>' . __( 'New Feature: Customizer' ) . '</h3>'; $content .= '<p>' . __( 'Click Customize to change the header, background, title and menus of the current theme, all in one place.' ) . '</p>'; $content .= '<p>' . __( 'Click the Live Preview links in the Available Themes list below to customize and preview another theme before activating it.' ) . '</p>'; WP_Internal_Pointers::print_js( 'wp340_customize_current_theme_link', '#customize-current-theme-link', array( 'content' => $content, 'position' => array( 'edge' => 'top', 'align' => is_rtl() ? 'right' : 'left', 'offset' => is_rtl() ? '32 0' : '-32 0' ), ) ); } /** * Print 'New Feature: Choose Image from Library' for 3.4.0. * * @since 3.4.0 */ public static function pointer_wp340_choose_image_from_library() { $content = '<h3>' . __( 'New Feature: Choose Image from Library' ) . '</h3>'; $content .= '<p>' . __( 'Want to use an image you uploaded earlier? Select it from your media library instead of uploading it again.' ) . '</p>'; WP_Internal_Pointers::print_js( 'wp340_choose_image_from_library', '#choose-from-library-link', array( 'content' => $content, 'position' => array( 'edge' => 'top', 'align' => is_rtl() ? 'right' : 'left', 'defer_loading' => true ), ) ); } public static function pointer_wp350_media() { $content = '<h3>' . __( 'New Media Manager' ) . '</h3>'; $content .= '<p>' . __( 'Uploading files and creating image galleries has a whole new look. Check it out!' ) . '</p>'; self::print_js( 'wp350_media', '.insert-media', array( 'content' => $content, 'position' => array( 'edge' => is_rtl() ? 'right' : 'left', 'align' => 'center' ), ) ); } /** * Prevents new users from seeing existing 'new feature' pointers. * * @since 3.3.0 */ public static function dismiss_pointers_for_new_users( $user_id ) { add_user_meta( $user_id, 'dismissed_wp_pointers', 'wp330_toolbar,wp330_saving_widgets,wp340_choose_image_from_library,wp340_customize_current_theme_link,wp350_media' ); } } add_action( 'admin_enqueue_scripts', array( 'WP_Internal_Pointers', 'enqueue_scripts' ) ); add_action( 'user_register', array( 'WP_Internal_Pointers', 'dismiss_pointers_for_new_users' ) ); /** * Convert a screen string to a screen object * * @since 3.0.0 * * @param string $hook_name The hook name (also known as the hook suffix) used to determine the screen. * @return WP_Screen Screen object. */ function convert_to_screen( $hook_name ) { if ( ! class_exists( 'WP_Screen' ) ) { _doing_it_wrong( 'convert_to_screen(), add_meta_box()', __( "Likely direct inclusion of wp-admin/includes/template.php in order to use add_meta_box(). This is very wrong. Hook the add_meta_box() call into the add_meta_boxes action instead." ), '3.3' ); return (object) array( 'id' => '_invalid', 'base' => '_are_belong_to_us' ); } return WP_Screen::get( $hook_name ); }
zyblog
trunk/zyblog/wp-admin/includes/template.php
PHP
asf20
68,382
<?php /** * WordPress Administration Importer API. * * @package WordPress * @subpackage Administration */ /** * Retrieve list of importers. * * @since 2.0.0 * * @return array */ function get_importers() { global $wp_importers; if ( is_array($wp_importers) ) uasort($wp_importers, create_function('$a, $b', 'return strcmp($a[0], $b[0]);')); return $wp_importers; } /** * Register importer for WordPress. * * @since 2.0.0 * * @param string $id Importer tag. Used to uniquely identify importer. * @param string $name Importer name and title. * @param string $description Importer description. * @param callback $callback Callback to run. * @return WP_Error Returns WP_Error when $callback is WP_Error. */ function register_importer( $id, $name, $description, $callback ) { global $wp_importers; if ( is_wp_error( $callback ) ) return $callback; $wp_importers[$id] = array ( $name, $description, $callback ); } /** * Cleanup importer. * * Removes attachment based on ID. * * @since 2.0.0 * * @param string $id Importer ID. */ function wp_import_cleanup( $id ) { wp_delete_attachment( $id ); } /** * Handle importer uploading and add attachment. * * @since 2.0.0 * * @return array Uploaded file's details on success, error message on failure */ function wp_import_handle_upload() { if ( !isset($_FILES['import']) ) { $file['error'] = __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini.' ); return $file; } $overrides = array( 'test_form' => false, 'test_type' => false ); $_FILES['import']['name'] .= '.txt'; $file = wp_handle_upload( $_FILES['import'], $overrides ); if ( isset( $file['error'] ) ) return $file; $url = $file['url']; $type = $file['type']; $file = $file['file']; $filename = basename( $file ); // Construct the object array $object = array( 'post_title' => $filename, 'post_content' => $url, 'post_mime_type' => $type, 'guid' => $url, 'context' => 'import', 'post_status' => 'private' ); // Save the data $id = wp_insert_attachment( $object, $file ); // schedule a cleanup for one day from now in case of failed import or missing wp_import_cleanup() call wp_schedule_single_event( time() + DAY_IN_SECONDS, 'importer_scheduled_cleanup', array( $id ) ); return array( 'file' => $file, 'id' => $id ); } /** * Returns a list from WordPress.org of popular importer plugins. * * @since 3.5.0 * * @return array Importers with metadata for each. */ function wp_get_popular_importers() { include ABSPATH . WPINC . '/version.php'; // include an unmodified $wp_version $locale = get_locale(); $popular_importers = get_site_transient( 'popular_importers_' . $locale ); if ( ! $popular_importers ) { $url = add_query_arg( 'locale', get_locale(), 'http://api.wordpress.org/core/importers/1.0/' ); $options = array( 'user-agent' => 'WordPress/' . $wp_version . '; ' . home_url() ); $popular_importers = maybe_unserialize( wp_remote_retrieve_body( wp_remote_get( $url, $options ) ) ); if ( is_array( $popular_importers ) ) set_site_transient( 'popular_importers_' . $locale, $popular_importers, 2 * DAY_IN_SECONDS ); else $popular_importers = false; } if ( is_array( $popular_importers ) ) { // If the data was received as translated, return it as-is. if ( $popular_importers['translated'] ) return $popular_importers['importers']; foreach ( $popular_importers['importers'] as &$importer ) { $importer['description'] = translate( $importer['description'] ); if ( $importer['name'] != 'WordPress' ) $importer['name'] = translate( $importer['name'] ); } return $popular_importers['importers']; } return array( // slug => name, description, plugin slug, and register_importer() slug 'blogger' => array( 'name' => __( 'Blogger' ), 'description' => __( 'Install the Blogger importer to import posts, comments, and users from a Blogger blog.' ), 'plugin-slug' => 'blogger-importer', 'importer-id' => 'blogger', ), 'wpcat2tag' => array( 'name' => __( 'Categories and Tags Converter' ), 'description' => __( 'Install the category/tag converter to convert existing categories to tags or tags to categories, selectively.' ), 'plugin-slug' => 'wpcat2tag-importer', 'importer-id' => 'wp-cat2tag', ), 'livejournal' => array( 'name' => __( 'LiveJournal' ), 'description' => __( 'Install the LiveJournal importer to import posts from LiveJournal using their API.' ), 'plugin-slug' => 'livejournal-importer', 'importer-id' => 'livejournal', ), 'movabletype' => array( 'name' => __( 'Movable Type and TypePad' ), 'description' => __( 'Install the Movable Type importer to import posts and comments from a Movable Type or TypePad blog.' ), 'plugin-slug' => 'movabletype-importer', 'importer-id' => 'mt', ), 'opml' => array( 'name' => __( 'Blogroll' ), 'description' => __( 'Install the blogroll importer to import links in OPML format.' ), 'plugin-slug' => 'opml-importer', 'importer-id' => 'opml', ), 'rss' => array( 'name' => __( 'RSS' ), 'description' => __( 'Install the RSS importer to import posts from an RSS feed.' ), 'plugin-slug' => 'rss-importer', 'importer-id' => 'rss', ), 'tumblr' => array( 'name' => __( 'Tumblr' ), 'description' => __( 'Install the Tumblr importer to import posts &amp; media from Tumblr using their API.' ), 'plugin-slug' => 'tumblr-importer', 'importer-id' => 'tumblr', ), 'wordpress' => array( 'name' => 'WordPress', 'description' => __( 'Install the WordPress importer to import posts, pages, comments, custom fields, categories, and tags from a WordPress export file.' ), 'plugin-slug' => 'wordpress-importer', 'importer-id' => 'wordpress', ), ); }
zyblog
trunk/zyblog/wp-admin/includes/import.php
PHP
asf20
5,913
<?php /** * PemFTP - A Ftp implementation in pure PHP * * @package PemFTP * @since 2.5 * * @version 1.0 * @copyright Alexey Dotsenko * @author Alexey Dotsenko * @link http://www.phpclasses.org/browse/package/1743.html Site * @license LGPL License http://www.opensource.org/licenses/lgpl-license.html */ /** * Socket Based FTP implementation * * @package PemFTP * @subpackage Socket * @since 2.5 * * @version 1.0 * @copyright Alexey Dotsenko * @author Alexey Dotsenko * @link http://www.phpclasses.org/browse/package/1743.html Site * @license LGPL License http://www.opensource.org/licenses/lgpl-license.html */ class ftp extends ftp_base { function ftp($verb=FALSE, $le=FALSE) { $this->__construct($verb, $le); } function __construct($verb=FALSE, $le=FALSE) { parent::__construct(true, $verb, $le); } // <!-- --------------------------------------------------------------------------------------- --> // <!-- Private functions --> // <!-- --------------------------------------------------------------------------------------- --> function _settimeout($sock) { if(!@socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>$this->_timeout, "usec"=>0))) { $this->PushError('_connect','socket set receive timeout',socket_strerror(socket_last_error($sock))); @socket_close($sock); return FALSE; } if(!@socket_set_option($sock, SOL_SOCKET , SO_SNDTIMEO, array("sec"=>$this->_timeout, "usec"=>0))) { $this->PushError('_connect','socket set send timeout',socket_strerror(socket_last_error($sock))); @socket_close($sock); return FALSE; } return true; } function _connect($host, $port) { $this->SendMSG("Creating socket"); if(!($sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { $this->PushError('_connect','socket create failed',socket_strerror(socket_last_error($sock))); return FALSE; } if(!$this->_settimeout($sock)) return FALSE; $this->SendMSG("Connecting to \"".$host.":".$port."\""); if (!($res = @socket_connect($sock, $host, $port))) { $this->PushError('_connect','socket connect failed',socket_strerror(socket_last_error($sock))); @socket_close($sock); return FALSE; } $this->_connected=true; return $sock; } function _readmsg($fnction="_readmsg"){ if(!$this->_connected) { $this->PushError($fnction,'Connect first'); return FALSE; } $result=true; $this->_message=""; $this->_code=0; $go=true; do { $tmp=@socket_read($this->_ftp_control_sock, 4096, PHP_BINARY_READ); if($tmp===false) { $go=$result=false; $this->PushError($fnction,'Read failed', socket_strerror(socket_last_error($this->_ftp_control_sock))); } else { $this->_message.=$tmp; $go = !preg_match("/^([0-9]{3})(-.+\\1)? [^".CRLF."]+".CRLF."$/Us", $this->_message, $regs); } } while($go); if($this->LocalEcho) echo "GET < ".rtrim($this->_message, CRLF).CRLF; $this->_code=(int)$regs[1]; return $result; } function _exec($cmd, $fnction="_exec") { if(!$this->_ready) { $this->PushError($fnction,'Connect first'); return FALSE; } if($this->LocalEcho) echo "PUT > ",$cmd,CRLF; $status=@socket_write($this->_ftp_control_sock, $cmd.CRLF); if($status===false) { $this->PushError($fnction,'socket write failed', socket_strerror(socket_last_error($this->stream))); return FALSE; } $this->_lastaction=time(); if(!$this->_readmsg($fnction)) return FALSE; return TRUE; } function _data_prepare($mode=FTP_ASCII) { if(!$this->_settype($mode)) return FALSE; $this->SendMSG("Creating data socket"); $this->_ftp_data_sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($this->_ftp_data_sock < 0) { $this->PushError('_data_prepare','socket create failed',socket_strerror(socket_last_error($this->_ftp_data_sock))); return FALSE; } if(!$this->_settimeout($this->_ftp_data_sock)) { $this->_data_close(); return FALSE; } if($this->_passive) { if(!$this->_exec("PASV", "pasv")) { $this->_data_close(); return FALSE; } if(!$this->_checkCode()) { $this->_data_close(); return FALSE; } $ip_port = explode(",", ereg_replace("^.+ \\(?([0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]+,[0-9]+)\\)?.*".CRLF."$", "\\1", $this->_message)); $this->_datahost=$ip_port[0].".".$ip_port[1].".".$ip_port[2].".".$ip_port[3]; $this->_dataport=(((int)$ip_port[4])<<8) + ((int)$ip_port[5]); $this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport); if(!@socket_connect($this->_ftp_data_sock, $this->_datahost, $this->_dataport)) { $this->PushError("_data_prepare","socket_connect", socket_strerror(socket_last_error($this->_ftp_data_sock))); $this->_data_close(); return FALSE; } else $this->_ftp_temp_sock=$this->_ftp_data_sock; } else { if(!@socket_getsockname($this->_ftp_control_sock, $addr, $port)) { $this->PushError("_data_prepare","can't get control socket information", socket_strerror(socket_last_error($this->_ftp_control_sock))); $this->_data_close(); return FALSE; } if(!@socket_bind($this->_ftp_data_sock,$addr)){ $this->PushError("_data_prepare","can't bind data socket", socket_strerror(socket_last_error($this->_ftp_data_sock))); $this->_data_close(); return FALSE; } if(!@socket_listen($this->_ftp_data_sock)) { $this->PushError("_data_prepare","can't listen data socket", socket_strerror(socket_last_error($this->_ftp_data_sock))); $this->_data_close(); return FALSE; } if(!@socket_getsockname($this->_ftp_data_sock, $this->_datahost, $this->_dataport)) { $this->PushError("_data_prepare","can't get data socket information", socket_strerror(socket_last_error($this->_ftp_data_sock))); $this->_data_close(); return FALSE; } if(!$this->_exec('PORT '.str_replace('.',',',$this->_datahost.'.'.($this->_dataport>>8).'.'.($this->_dataport&0x00FF)), "_port")) { $this->_data_close(); return FALSE; } if(!$this->_checkCode()) { $this->_data_close(); return FALSE; } } return TRUE; } function _data_read($mode=FTP_ASCII, $fp=NULL) { $NewLine=$this->_eol_code[$this->OS_local]; if(is_resource($fp)) $out=0; else $out=""; if(!$this->_passive) { $this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport); $this->_ftp_temp_sock=socket_accept($this->_ftp_data_sock); if($this->_ftp_temp_sock===FALSE) { $this->PushError("_data_read","socket_accept", socket_strerror(socket_last_error($this->_ftp_temp_sock))); $this->_data_close(); return FALSE; } } while(($block=@socket_read($this->_ftp_temp_sock, $this->_ftp_buff_size, PHP_BINARY_READ))!==false) { if($block==="") break; if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_local], $block); if(is_resource($fp)) $out+=fwrite($fp, $block, strlen($block)); else $out.=$block; } return $out; } function _data_write($mode=FTP_ASCII, $fp=NULL) { $NewLine=$this->_eol_code[$this->OS_local]; if(is_resource($fp)) $out=0; else $out=""; if(!$this->_passive) { $this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport); $this->_ftp_temp_sock=socket_accept($this->_ftp_data_sock); if($this->_ftp_temp_sock===FALSE) { $this->PushError("_data_write","socket_accept", socket_strerror(socket_last_error($this->_ftp_temp_sock))); $this->_data_close(); return false; } } if(is_resource($fp)) { while(!feof($fp)) { $block=fread($fp, $this->_ftp_buff_size); if(!$this->_data_write_block($mode, $block)) return false; } } elseif(!$this->_data_write_block($mode, $fp)) return false; return true; } function _data_write_block($mode, $block) { if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_remote], $block); do { if(($t=@socket_write($this->_ftp_temp_sock, $block))===FALSE) { $this->PushError("_data_write","socket_write", socket_strerror(socket_last_error($this->_ftp_temp_sock))); $this->_data_close(); return FALSE; } $block=substr($block, $t); } while(!empty($block)); return true; } function _data_close() { @socket_close($this->_ftp_temp_sock); @socket_close($this->_ftp_data_sock); $this->SendMSG("Disconnected data from remote host"); return TRUE; } function _quit() { if($this->_connected) { @socket_close($this->_ftp_control_sock); $this->_connected=false; $this->SendMSG("Socket closed"); } } } ?>
zyblog
trunk/zyblog/wp-admin/includes/class-ftp-sockets.php
PHP
asf20
8,544
<?php /* Continent and city translations for timezone selection. * This file is not included anywhere. It exists solely for use by xgettext. */ __('Africa', 'continents-cities'); __('Abidjan', 'continents-cities'); __('Accra', 'continents-cities'); __('Addis Ababa', 'continents-cities'); __('Algiers', 'continents-cities'); __('Asmara', 'continents-cities'); __('Asmera', 'continents-cities'); __('Bamako', 'continents-cities'); __('Bangui', 'continents-cities'); __('Banjul', 'continents-cities'); __('Bissau', 'continents-cities'); __('Blantyre', 'continents-cities'); __('Brazzaville', 'continents-cities'); __('Bujumbura', 'continents-cities'); __('Cairo', 'continents-cities'); __('Casablanca', 'continents-cities'); __('Ceuta', 'continents-cities'); __('Conakry', 'continents-cities'); __('Dakar', 'continents-cities'); __('Dar es Salaam', 'continents-cities'); __('Djibouti', 'continents-cities'); __('Douala', 'continents-cities'); __('El Aaiun', 'continents-cities'); __('Freetown', 'continents-cities'); __('Gaborone', 'continents-cities'); __('Harare', 'continents-cities'); __('Johannesburg', 'continents-cities'); __('Kampala', 'continents-cities'); __('Khartoum', 'continents-cities'); __('Kigali', 'continents-cities'); __('Kinshasa', 'continents-cities'); __('Lagos', 'continents-cities'); __('Libreville', 'continents-cities'); __('Lome', 'continents-cities'); __('Luanda', 'continents-cities'); __('Lubumbashi', 'continents-cities'); __('Lusaka', 'continents-cities'); __('Malabo', 'continents-cities'); __('Maputo', 'continents-cities'); __('Maseru', 'continents-cities'); __('Mbabane', 'continents-cities'); __('Mogadishu', 'continents-cities'); __('Monrovia', 'continents-cities'); __('Nairobi', 'continents-cities'); __('Ndjamena', 'continents-cities'); __('Niamey', 'continents-cities'); __('Nouakchott', 'continents-cities'); __('Ouagadougou', 'continents-cities'); __('Porto-Novo', 'continents-cities'); __('Sao Tome', 'continents-cities'); __('Timbuktu', 'continents-cities'); __('Tripoli', 'continents-cities'); __('Tunis', 'continents-cities'); __('Windhoek', 'continents-cities'); __('America', 'continents-cities'); __('Adak', 'continents-cities'); __('Anchorage', 'continents-cities'); __('Anguilla', 'continents-cities'); __('Antigua', 'continents-cities'); __('Araguaina', 'continents-cities'); __('Argentina', 'continents-cities'); __('Buenos Aires', 'continents-cities'); __('Catamarca', 'continents-cities'); __('ComodRivadavia', 'continents-cities'); __('Cordoba', 'continents-cities'); __('Jujuy', 'continents-cities'); __('La Rioja', 'continents-cities'); __('Mendoza', 'continents-cities'); __('Rio Gallegos', 'continents-cities'); __('San Juan', 'continents-cities'); __('San Luis', 'continents-cities'); __('Tucuman', 'continents-cities'); __('Ushuaia', 'continents-cities'); __('Aruba', 'continents-cities'); __('Asuncion', 'continents-cities'); __('Atikokan', 'continents-cities'); __('Atka', 'continents-cities'); __('Bahia', 'continents-cities'); __('Barbados', 'continents-cities'); __('Belem', 'continents-cities'); __('Belize', 'continents-cities'); __('Blanc-Sablon', 'continents-cities'); __('Boa Vista', 'continents-cities'); __('Bogota', 'continents-cities'); __('Boise', 'continents-cities'); __('Cambridge Bay', 'continents-cities'); __('Campo Grande', 'continents-cities'); __('Cancun', 'continents-cities'); __('Caracas', 'continents-cities'); __('Cayenne', 'continents-cities'); __('Cayman', 'continents-cities'); __('Chicago', 'continents-cities'); __('Chihuahua', 'continents-cities'); __('Coral Harbour', 'continents-cities'); __('Costa Rica', 'continents-cities'); __('Cuiaba', 'continents-cities'); __('Curacao', 'continents-cities'); __('Danmarkshavn', 'continents-cities'); __('Dawson', 'continents-cities'); __('Dawson Creek', 'continents-cities'); __('Denver', 'continents-cities'); __('Detroit', 'continents-cities'); __('Dominica', 'continents-cities'); __('Edmonton', 'continents-cities'); __('Eirunepe', 'continents-cities'); __('El Salvador', 'continents-cities'); __('Ensenada', 'continents-cities'); __('Fort Wayne', 'continents-cities'); __('Fortaleza', 'continents-cities'); __('Glace Bay', 'continents-cities'); __('Godthab', 'continents-cities'); __('Goose Bay', 'continents-cities'); __('Grand Turk', 'continents-cities'); __('Grenada', 'continents-cities'); __('Guadeloupe', 'continents-cities'); __('Guatemala', 'continents-cities'); __('Guayaquil', 'continents-cities'); __('Guyana', 'continents-cities'); __('Halifax', 'continents-cities'); __('Havana', 'continents-cities'); __('Hermosillo', 'continents-cities'); __('Indiana', 'continents-cities'); __('Indianapolis', 'continents-cities'); __('Knox', 'continents-cities'); __('Marengo', 'continents-cities'); __('Petersburg', 'continents-cities'); __('Tell City', 'continents-cities'); __('Vevay', 'continents-cities'); __('Vincennes', 'continents-cities'); __('Winamac', 'continents-cities'); __('Inuvik', 'continents-cities'); __('Iqaluit', 'continents-cities'); __('Jamaica', 'continents-cities'); __('Juneau', 'continents-cities'); __('Kentucky', 'continents-cities'); __('Louisville', 'continents-cities'); __('Monticello', 'continents-cities'); __('Knox IN', 'continents-cities'); __('La Paz', 'continents-cities'); __('Lima', 'continents-cities'); __('Los Angeles', 'continents-cities'); __('Maceio', 'continents-cities'); __('Managua', 'continents-cities'); __('Manaus', 'continents-cities'); __('Marigot', 'continents-cities'); __('Martinique', 'continents-cities'); __('Mazatlan', 'continents-cities'); __('Menominee', 'continents-cities'); __('Merida', 'continents-cities'); __('Mexico City', 'continents-cities'); __('Miquelon', 'continents-cities'); __('Moncton', 'continents-cities'); __('Monterrey', 'continents-cities'); __('Montevideo', 'continents-cities'); __('Montreal', 'continents-cities'); __('Montserrat', 'continents-cities'); __('Nassau', 'continents-cities'); __('New York', 'continents-cities'); __('Nipigon', 'continents-cities'); __('Nome', 'continents-cities'); __('Noronha', 'continents-cities'); __('North Dakota', 'continents-cities'); __('Center', 'continents-cities'); __('New Salem', 'continents-cities'); __('Panama', 'continents-cities'); __('Pangnirtung', 'continents-cities'); __('Paramaribo', 'continents-cities'); __('Phoenix', 'continents-cities'); __('Port-au-Prince', 'continents-cities'); __('Port of Spain', 'continents-cities'); __('Porto Acre', 'continents-cities'); __('Porto Velho', 'continents-cities'); __('Puerto Rico', 'continents-cities'); __('Rainy River', 'continents-cities'); __('Rankin Inlet', 'continents-cities'); __('Recife', 'continents-cities'); __('Regina', 'continents-cities'); __('Resolute', 'continents-cities'); __('Rio Branco', 'continents-cities'); __('Rosario', 'continents-cities'); __('Santiago', 'continents-cities'); __('Santo Domingo', 'continents-cities'); __('Sao Paulo', 'continents-cities'); __('Scoresbysund', 'continents-cities'); __('Shiprock', 'continents-cities'); __('St Barthelemy', 'continents-cities'); __('St Johns', 'continents-cities'); __('St Kitts', 'continents-cities'); __('St Lucia', 'continents-cities'); __('St Thomas', 'continents-cities'); __('St Vincent', 'continents-cities'); __('Swift Current', 'continents-cities'); __('Tegucigalpa', 'continents-cities'); __('Thule', 'continents-cities'); __('Thunder Bay', 'continents-cities'); __('Tijuana', 'continents-cities'); __('Toronto', 'continents-cities'); __('Tortola', 'continents-cities'); __('Vancouver', 'continents-cities'); __('Virgin', 'continents-cities'); __('Whitehorse', 'continents-cities'); __('Winnipeg', 'continents-cities'); __('Yakutat', 'continents-cities'); __('Yellowknife', 'continents-cities'); __('Antarctica', 'continents-cities'); __('Casey', 'continents-cities'); __('Davis', 'continents-cities'); __('DumontDUrville', 'continents-cities'); __('Mawson', 'continents-cities'); __('McMurdo', 'continents-cities'); __('Palmer', 'continents-cities'); __('Rothera', 'continents-cities'); __('South Pole', 'continents-cities'); __('Syowa', 'continents-cities'); __('Vostok', 'continents-cities'); __('Arctic', 'continents-cities'); __('Longyearbyen', 'continents-cities'); __('Asia', 'continents-cities'); __('Aden', 'continents-cities'); __('Almaty', 'continents-cities'); __('Amman', 'continents-cities'); __('Anadyr', 'continents-cities'); __('Aqtau', 'continents-cities'); __('Aqtobe', 'continents-cities'); __('Ashgabat', 'continents-cities'); __('Ashkhabad', 'continents-cities'); __('Baghdad', 'continents-cities'); __('Bahrain', 'continents-cities'); __('Baku', 'continents-cities'); __('Bangkok', 'continents-cities'); __('Beirut', 'continents-cities'); __('Bishkek', 'continents-cities'); __('Brunei', 'continents-cities'); __('Calcutta', 'continents-cities'); __('Choibalsan', 'continents-cities'); __('Chongqing', 'continents-cities'); __('Chungking', 'continents-cities'); __('Colombo', 'continents-cities'); __('Dacca', 'continents-cities'); __('Damascus', 'continents-cities'); __('Dhaka', 'continents-cities'); __('Dili', 'continents-cities'); __('Dubai', 'continents-cities'); __('Dushanbe', 'continents-cities'); __('Gaza', 'continents-cities'); __('Harbin', 'continents-cities'); __('Ho Chi Minh', 'continents-cities'); __('Hong Kong', 'continents-cities'); __('Hovd', 'continents-cities'); __('Irkutsk', 'continents-cities'); __('Istanbul', 'continents-cities'); __('Jakarta', 'continents-cities'); __('Jayapura', 'continents-cities'); __('Jerusalem', 'continents-cities'); __('Kabul', 'continents-cities'); __('Kamchatka', 'continents-cities'); __('Karachi', 'continents-cities'); __('Kashgar', 'continents-cities'); __('Katmandu', 'continents-cities'); __('Kolkata', 'continents-cities'); __('Krasnoyarsk', 'continents-cities'); __('Kuala Lumpur', 'continents-cities'); __('Kuching', 'continents-cities'); __('Kuwait', 'continents-cities'); __('Macao', 'continents-cities'); __('Macau', 'continents-cities'); __('Magadan', 'continents-cities'); __('Makassar', 'continents-cities'); __('Manila', 'continents-cities'); __('Muscat', 'continents-cities'); __('Nicosia', 'continents-cities'); __('Novosibirsk', 'continents-cities'); __('Omsk', 'continents-cities'); __('Oral', 'continents-cities'); __('Phnom Penh', 'continents-cities'); __('Pontianak', 'continents-cities'); __('Pyongyang', 'continents-cities'); __('Qatar', 'continents-cities'); __('Qyzylorda', 'continents-cities'); __('Rangoon', 'continents-cities'); __('Riyadh', 'continents-cities'); __('Saigon', 'continents-cities'); __('Sakhalin', 'continents-cities'); __('Samarkand', 'continents-cities'); __('Seoul', 'continents-cities'); __('Shanghai', 'continents-cities'); __('Singapore', 'continents-cities'); __('Taipei', 'continents-cities'); __('Tashkent', 'continents-cities'); __('Tbilisi', 'continents-cities'); __('Tehran', 'continents-cities'); __('Tel Aviv', 'continents-cities'); __('Thimbu', 'continents-cities'); __('Thimphu', 'continents-cities'); __('Tokyo', 'continents-cities'); __('Ujung Pandang', 'continents-cities'); __('Ulaanbaatar', 'continents-cities'); __('Ulan Bator', 'continents-cities'); __('Urumqi', 'continents-cities'); __('Vientiane', 'continents-cities'); __('Vladivostok', 'continents-cities'); __('Yakutsk', 'continents-cities'); __('Yekaterinburg', 'continents-cities'); __('Yerevan', 'continents-cities'); __('Atlantic', 'continents-cities'); __('Azores', 'continents-cities'); __('Bermuda', 'continents-cities'); __('Canary', 'continents-cities'); __('Cape Verde', 'continents-cities'); __('Faeroe', 'continents-cities'); __('Faroe', 'continents-cities'); __('Jan Mayen', 'continents-cities'); __('Madeira', 'continents-cities'); __('Reykjavik', 'continents-cities'); __('South Georgia', 'continents-cities'); __('St Helena', 'continents-cities'); __('Stanley', 'continents-cities'); __('Australia', 'continents-cities'); __('ACT', 'continents-cities'); __('Adelaide', 'continents-cities'); __('Brisbane', 'continents-cities'); __('Broken Hill', 'continents-cities'); __('Canberra', 'continents-cities'); __('Currie', 'continents-cities'); __('Darwin', 'continents-cities'); __('Eucla', 'continents-cities'); __('Hobart', 'continents-cities'); __('LHI', 'continents-cities'); __('Lindeman', 'continents-cities'); __('Lord Howe', 'continents-cities'); __('Melbourne', 'continents-cities'); __('North', 'continents-cities'); __('NSW', 'continents-cities'); __('Perth', 'continents-cities'); __('Queensland', 'continents-cities'); __('South', 'continents-cities'); __('Sydney', 'continents-cities'); __('Tasmania', 'continents-cities'); __('Victoria', 'continents-cities'); __('West', 'continents-cities'); __('Yancowinna', 'continents-cities'); __('Etc', 'continents-cities'); __('GMT', 'continents-cities'); __('GMT+0', 'continents-cities'); __('GMT+1', 'continents-cities'); __('GMT+10', 'continents-cities'); __('GMT+11', 'continents-cities'); __('GMT+12', 'continents-cities'); __('GMT+2', 'continents-cities'); __('GMT+3', 'continents-cities'); __('GMT+4', 'continents-cities'); __('GMT+5', 'continents-cities'); __('GMT+6', 'continents-cities'); __('GMT+7', 'continents-cities'); __('GMT+8', 'continents-cities'); __('GMT+9', 'continents-cities'); __('GMT-0', 'continents-cities'); __('GMT-1', 'continents-cities'); __('GMT-10', 'continents-cities'); __('GMT-11', 'continents-cities'); __('GMT-12', 'continents-cities'); __('GMT-13', 'continents-cities'); __('GMT-14', 'continents-cities'); __('GMT-2', 'continents-cities'); __('GMT-3', 'continents-cities'); __('GMT-4', 'continents-cities'); __('GMT-5', 'continents-cities'); __('GMT-6', 'continents-cities'); __('GMT-7', 'continents-cities'); __('GMT-8', 'continents-cities'); __('GMT-9', 'continents-cities'); __('GMT0', 'continents-cities'); __('Greenwich', 'continents-cities'); __('UCT', 'continents-cities'); __('Universal', 'continents-cities'); __('UTC', 'continents-cities'); __('Zulu', 'continents-cities'); __('Europe', 'continents-cities'); __('Amsterdam', 'continents-cities'); __('Andorra', 'continents-cities'); __('Athens', 'continents-cities'); __('Belfast', 'continents-cities'); __('Belgrade', 'continents-cities'); __('Berlin', 'continents-cities'); __('Bratislava', 'continents-cities'); __('Brussels', 'continents-cities'); __('Bucharest', 'continents-cities'); __('Budapest', 'continents-cities'); __('Chisinau', 'continents-cities'); __('Copenhagen', 'continents-cities'); __('Dublin', 'continents-cities'); __('Gibraltar', 'continents-cities'); __('Guernsey', 'continents-cities'); __('Helsinki', 'continents-cities'); __('Isle of Man', 'continents-cities'); __('Jersey', 'continents-cities'); __('Kaliningrad', 'continents-cities'); __('Kiev', 'continents-cities'); __('Lisbon', 'continents-cities'); __('Ljubljana', 'continents-cities'); __('London', 'continents-cities'); __('Luxembourg', 'continents-cities'); __('Madrid', 'continents-cities'); __('Malta', 'continents-cities'); __('Mariehamn', 'continents-cities'); __('Minsk', 'continents-cities'); __('Monaco', 'continents-cities'); __('Moscow', 'continents-cities'); __('Oslo', 'continents-cities'); __('Paris', 'continents-cities'); __('Podgorica', 'continents-cities'); __('Prague', 'continents-cities'); __('Riga', 'continents-cities'); __('Rome', 'continents-cities'); __('Samara', 'continents-cities'); __('San Marino', 'continents-cities'); __('Sarajevo', 'continents-cities'); __('Simferopol', 'continents-cities'); __('Skopje', 'continents-cities'); __('Sofia', 'continents-cities'); __('Stockholm', 'continents-cities'); __('Tallinn', 'continents-cities'); __('Tirane', 'continents-cities'); __('Tiraspol', 'continents-cities'); __('Uzhgorod', 'continents-cities'); __('Vaduz', 'continents-cities'); __('Vatican', 'continents-cities'); __('Vienna', 'continents-cities'); __('Vilnius', 'continents-cities'); __('Volgograd', 'continents-cities'); __('Warsaw', 'continents-cities'); __('Zagreb', 'continents-cities'); __('Zaporozhye', 'continents-cities'); __('Zurich', 'continents-cities'); __('Indian', 'continents-cities'); __('Antananarivo', 'continents-cities'); __('Chagos', 'continents-cities'); __('Christmas', 'continents-cities'); __('Cocos', 'continents-cities'); __('Comoro', 'continents-cities'); __('Kerguelen', 'continents-cities'); __('Mahe', 'continents-cities'); __('Maldives', 'continents-cities'); __('Mauritius', 'continents-cities'); __('Mayotte', 'continents-cities'); __('Reunion', 'continents-cities'); __('Pacific', 'continents-cities'); __('Apia', 'continents-cities'); __('Auckland', 'continents-cities'); __('Chatham', 'continents-cities'); __('Easter', 'continents-cities'); __('Efate', 'continents-cities'); __('Enderbury', 'continents-cities'); __('Fakaofo', 'continents-cities'); __('Fiji', 'continents-cities'); __('Funafuti', 'continents-cities'); __('Galapagos', 'continents-cities'); __('Gambier', 'continents-cities'); __('Guadalcanal', 'continents-cities'); __('Guam', 'continents-cities'); __('Honolulu', 'continents-cities'); __('Johnston', 'continents-cities'); __('Kiritimati', 'continents-cities'); __('Kosrae', 'continents-cities'); __('Kwajalein', 'continents-cities'); __('Majuro', 'continents-cities'); __('Marquesas', 'continents-cities'); __('Midway', 'continents-cities'); __('Nauru', 'continents-cities'); __('Niue', 'continents-cities'); __('Norfolk', 'continents-cities'); __('Noumea', 'continents-cities'); __('Pago Pago', 'continents-cities'); __('Palau', 'continents-cities'); __('Pitcairn', 'continents-cities'); __('Ponape', 'continents-cities'); __('Port Moresby', 'continents-cities'); __('Rarotonga', 'continents-cities'); __('Saipan', 'continents-cities'); __('Samoa', 'continents-cities'); __('Tahiti', 'continents-cities'); __('Tarawa', 'continents-cities'); __('Tongatapu', 'continents-cities'); __('Truk', 'continents-cities'); __('Wake', 'continents-cities'); __('Wallis', 'continents-cities'); __('Yap', 'continents-cities');
zyblog
trunk/zyblog/wp-admin/includes/continents-cities.php
PHP
asf20
17,877
<?php /** * WordPress Widgets Administration API * * @package WordPress * @subpackage Administration */ /** * Display list of the available widgets. * * @since 2.5.0 */ function wp_list_widgets() { global $wp_registered_widgets, $sidebars_widgets, $wp_registered_widget_controls; $sort = $wp_registered_widgets; usort( $sort, '_sort_name_callback' ); $done = array(); foreach ( $sort as $widget ) { if ( in_array( $widget['callback'], $done, true ) ) // We already showed this multi-widget continue; $sidebar = is_active_widget( $widget['callback'], $widget['id'], false, false ); $done[] = $widget['callback']; if ( ! isset( $widget['params'][0] ) ) $widget['params'][0] = array(); $args = array( 'widget_id' => $widget['id'], 'widget_name' => $widget['name'], '_display' => 'template' ); if ( isset($wp_registered_widget_controls[$widget['id']]['id_base']) && isset($widget['params'][0]['number']) ) { $id_base = $wp_registered_widget_controls[$widget['id']]['id_base']; $args['_temp_id'] = "$id_base-__i__"; $args['_multi_num'] = next_widget_id_number($id_base); $args['_add'] = 'multi'; } else { $args['_add'] = 'single'; if ( $sidebar ) $args['_hide'] = '1'; } $args = wp_list_widget_controls_dynamic_sidebar( array( 0 => $args, 1 => $widget['params'][0] ) ); call_user_func_array( 'wp_widget_control', $args ); } } /** * Callback to sort array by a 'name' key. * * @since 3.1.0 * @access private */ function _sort_name_callback( $a, $b ) { return strnatcasecmp( $a['name'], $b['name'] ); } /** * Show the widgets and their settings for a sidebar. * Used in the the admin widget config screen. * * @since 2.5.0 * * @param string $sidebar id slug of the sidebar */ function wp_list_widget_controls( $sidebar ) { add_filter( 'dynamic_sidebar_params', 'wp_list_widget_controls_dynamic_sidebar' ); echo "<div id='$sidebar' class='widgets-sortables'>\n"; $description = wp_sidebar_description( $sidebar ); if ( !empty( $description ) ) { echo "<div class='sidebar-description'>\n"; echo "\t<p class='description'>$description</p>"; echo "</div>\n"; } dynamic_sidebar( $sidebar ); echo "</div>\n"; } /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @param array $params * @return array */ function wp_list_widget_controls_dynamic_sidebar( $params ) { global $wp_registered_widgets; static $i = 0; $i++; $widget_id = $params[0]['widget_id']; $id = isset($params[0]['_temp_id']) ? $params[0]['_temp_id'] : $widget_id; $hidden = isset($params[0]['_hide']) ? ' style="display:none;"' : ''; $params[0]['before_widget'] = "<div id='widget-{$i}_{$id}' class='widget'$hidden>"; $params[0]['after_widget'] = "</div>"; $params[0]['before_title'] = "%BEG_OF_TITLE%"; // deprecated $params[0]['after_title'] = "%END_OF_TITLE%"; // deprecated if ( is_callable( $wp_registered_widgets[$widget_id]['callback'] ) ) { $wp_registered_widgets[$widget_id]['_callback'] = $wp_registered_widgets[$widget_id]['callback']; $wp_registered_widgets[$widget_id]['callback'] = 'wp_widget_control'; } return $params; } function next_widget_id_number($id_base) { global $wp_registered_widgets; $number = 1; foreach ( $wp_registered_widgets as $widget_id => $widget ) { if ( preg_match( '/' . $id_base . '-([0-9]+)$/', $widget_id, $matches ) ) $number = max($number, $matches[1]); } $number++; return $number; } /** * Meta widget used to display the control form for a widget. * * Called from dynamic_sidebar(). * * @since 2.5.0 * * @param array $sidebar_args * @return array */ function wp_widget_control( $sidebar_args ) { global $wp_registered_widgets, $wp_registered_widget_controls, $sidebars_widgets; $widget_id = $sidebar_args['widget_id']; $sidebar_id = isset($sidebar_args['id']) ? $sidebar_args['id'] : false; $key = $sidebar_id ? array_search( $widget_id, $sidebars_widgets[$sidebar_id] ) : '-1'; // position of widget in sidebar $control = isset($wp_registered_widget_controls[$widget_id]) ? $wp_registered_widget_controls[$widget_id] : array(); $widget = $wp_registered_widgets[$widget_id]; $id_format = $widget['id']; $widget_number = isset($control['params'][0]['number']) ? $control['params'][0]['number'] : ''; $id_base = isset($control['id_base']) ? $control['id_base'] : $widget_id; $multi_number = isset($sidebar_args['_multi_num']) ? $sidebar_args['_multi_num'] : ''; $add_new = isset($sidebar_args['_add']) ? $sidebar_args['_add'] : ''; $query_arg = array( 'editwidget' => $widget['id'] ); if ( $add_new ) { $query_arg['addnew'] = 1; if ( $multi_number ) { $query_arg['num'] = $multi_number; $query_arg['base'] = $id_base; } } else { $query_arg['sidebar'] = $sidebar_id; $query_arg['key'] = $key; } // We aren't showing a widget control, we're outputting a template for a multi-widget control if ( isset($sidebar_args['_display']) && 'template' == $sidebar_args['_display'] && $widget_number ) { // number == -1 implies a template where id numbers are replaced by a generic '__i__' $control['params'][0]['number'] = -1; // with id_base widget id's are constructed like {$id_base}-{$id_number} if ( isset($control['id_base']) ) $id_format = $control['id_base'] . '-__i__'; } $wp_registered_widgets[$widget_id]['callback'] = $wp_registered_widgets[$widget_id]['_callback']; unset($wp_registered_widgets[$widget_id]['_callback']); $widget_title = esc_html( strip_tags( $sidebar_args['widget_name'] ) ); $has_form = 'noform'; echo $sidebar_args['before_widget']; ?> <div class="widget-top"> <div class="widget-title-action"> <a class="widget-action hide-if-no-js" href="#available-widgets"></a> <a class="widget-control-edit hide-if-js" href="<?php echo esc_url( add_query_arg( $query_arg ) ); ?>"> <span class="edit"><?php _ex( 'Edit', 'widget' ); ?></span> <span class="add"><?php _ex( 'Add', 'widget' ); ?></span> <span class="screen-reader-text"><?php echo $widget_title; ?></span> </a> </div> <div class="widget-title"><h4><?php echo $widget_title ?><span class="in-widget-title"></span></h4></div> </div> <div class="widget-inside"> <form action="" method="post"> <div class="widget-content"> <?php if ( isset($control['callback']) ) $has_form = call_user_func_array( $control['callback'], $control['params'] ); else echo "\t\t<p>" . __('There are no options for this widget.') . "</p>\n"; ?> </div> <input type="hidden" name="widget-id" class="widget-id" value="<?php echo esc_attr($id_format); ?>" /> <input type="hidden" name="id_base" class="id_base" value="<?php echo esc_attr($id_base); ?>" /> <input type="hidden" name="widget-width" class="widget-width" value="<?php if (isset( $control['width'] )) echo esc_attr($control['width']); ?>" /> <input type="hidden" name="widget-height" class="widget-height" value="<?php if (isset( $control['height'] )) echo esc_attr($control['height']); ?>" /> <input type="hidden" name="widget_number" class="widget_number" value="<?php echo esc_attr($widget_number); ?>" /> <input type="hidden" name="multi_number" class="multi_number" value="<?php echo esc_attr($multi_number); ?>" /> <input type="hidden" name="add_new" class="add_new" value="<?php echo esc_attr($add_new); ?>" /> <div class="widget-control-actions"> <div class="alignleft"> <a class="widget-control-remove" href="#remove"><?php _e('Delete'); ?></a> | <a class="widget-control-close" href="#close"><?php _e('Close'); ?></a> </div> <div class="alignright<?php if ( 'noform' === $has_form ) echo ' widget-control-noform'; ?>"> <?php submit_button( __( 'Save' ), 'button-primary widget-control-save right', 'savewidget', false, array( 'id' => 'widget-' . esc_attr( $id_format ) . '-savewidget' ) ); ?> <span class="spinner"></span> </div> <br class="clear" /> </div> </form> </div> <div class="widget-description"> <?php echo ( $widget_description = wp_widget_description($widget_id) ) ? "$widget_description\n" : "$widget_title\n"; ?> </div> <?php echo $sidebar_args['after_widget']; return $sidebar_args; }
zyblog
trunk/zyblog/wp-admin/includes/widgets.php
PHP
asf20
8,104
<?php /** * WordPress Bookmark Administration API * * @package WordPress * @subpackage Administration */ /** * Add a link to using values provided in $_POST. * * @since 2.0.0 * * @return int|WP_Error Value 0 or WP_Error on failure. The link ID on success. */ function add_link() { return edit_link(); } /** * Update or insert a link using values provided in $_POST. * * @since 2.0.0 * * @param int $link_id Optional. ID of the link to edit. * @return int|WP_Error Value 0 or WP_Error on failure. The link ID on success. */ function edit_link( $link_id = 0 ) { if ( !current_user_can( 'manage_links' ) ) wp_die( __( 'Cheatin&#8217; uh?' ) ); $_POST['link_url'] = esc_html( $_POST['link_url'] ); $_POST['link_url'] = esc_url($_POST['link_url']); $_POST['link_name'] = esc_html( $_POST['link_name'] ); $_POST['link_image'] = esc_html( $_POST['link_image'] ); $_POST['link_rss'] = esc_url($_POST['link_rss']); if ( !isset($_POST['link_visible']) || 'N' != $_POST['link_visible'] ) $_POST['link_visible'] = 'Y'; if ( !empty( $link_id ) ) { $_POST['link_id'] = $link_id; return wp_update_link( $_POST ); } else { return wp_insert_link( $_POST ); } } /** * Retrieve the default link for editing. * * @since 2.0.0 * * @return object Default link */ function get_default_link_to_edit() { $link = new stdClass; if ( isset( $_GET['linkurl'] ) ) $link->link_url = esc_url( $_GET['linkurl'] ); else $link->link_url = ''; if ( isset( $_GET['name'] ) ) $link->link_name = esc_attr( $_GET['name'] ); else $link->link_name = ''; $link->link_visible = 'Y'; return $link; } /** * Delete link specified from database * * @since 2.0.0 * * @param int $link_id ID of the link to delete * @return bool True */ function wp_delete_link( $link_id ) { global $wpdb; do_action( 'delete_link', $link_id ); wp_delete_object_term_relationships( $link_id, 'link_category' ); $wpdb->delete( $wpdb->links, array( 'link_id' => $link_id ) ); do_action( 'deleted_link', $link_id ); clean_bookmark_cache( $link_id ); return true; } /** * Retrieves the link categories associated with the link specified. * * @since 2.1.0 * * @param int $link_id Link ID to look up * @return array The requested link's categories */ function wp_get_link_cats( $link_id = 0 ) { $cats = wp_get_object_terms( $link_id, 'link_category', array('fields' => 'ids') ); return array_unique( $cats ); } /** * Retrieve link data based on ID. * * @since 2.0.0 * * @param int $link_id ID of link to retrieve * @return object Link for editing */ function get_link_to_edit( $link_id ) { return get_bookmark( $link_id, OBJECT, 'edit' ); } /** * This function inserts/updates links into/in the database. * * @since 2.0.0 * * @param array $linkdata Elements that make up the link to insert. * @param bool $wp_error Optional. If true return WP_Error object on failure. * @return int|WP_Error Value 0 or WP_Error on failure. The link ID on success. */ function wp_insert_link( $linkdata, $wp_error = false ) { global $wpdb; $defaults = array( 'link_id' => 0, 'link_name' => '', 'link_url' => '', 'link_rating' => 0 ); $linkdata = wp_parse_args( $linkdata, $defaults ); $linkdata = sanitize_bookmark( $linkdata, 'db' ); extract( stripslashes_deep( $linkdata ), EXTR_SKIP ); $update = false; if ( !empty( $link_id ) ) $update = true; if ( trim( $link_name ) == '' ) { if ( trim( $link_url ) != '' ) { $link_name = $link_url; } else { return 0; } } if ( trim( $link_url ) == '' ) return 0; if ( empty( $link_rating ) ) $link_rating = 0; if ( empty( $link_image ) ) $link_image = ''; if ( empty( $link_target ) ) $link_target = ''; if ( empty( $link_visible ) ) $link_visible = 'Y'; if ( empty( $link_owner ) ) $link_owner = get_current_user_id(); if ( empty( $link_notes ) ) $link_notes = ''; if ( empty( $link_description ) ) $link_description = ''; if ( empty( $link_rss ) ) $link_rss = ''; if ( empty( $link_rel ) ) $link_rel = ''; // Make sure we set a valid category if ( ! isset( $link_category ) || 0 == count( $link_category ) || !is_array( $link_category ) ) { $link_category = array( get_option( 'default_link_category' ) ); } if ( $update ) { if ( false === $wpdb->update( $wpdb->links, compact('link_url', 'link_name', 'link_image', 'link_target', 'link_description', 'link_visible', 'link_rating', 'link_rel', 'link_notes', 'link_rss'), compact('link_id') ) ) { if ( $wp_error ) return new WP_Error( 'db_update_error', __( 'Could not update link in the database' ), $wpdb->last_error ); else return 0; } } else { if ( false === $wpdb->insert( $wpdb->links, compact('link_url', 'link_name', 'link_image', 'link_target', 'link_description', 'link_visible', 'link_owner', 'link_rating', 'link_rel', 'link_notes', 'link_rss') ) ) { if ( $wp_error ) return new WP_Error( 'db_insert_error', __( 'Could not insert link into the database' ), $wpdb->last_error ); else return 0; } $link_id = (int) $wpdb->insert_id; } wp_set_link_cats( $link_id, $link_category ); if ( $update ) do_action( 'edit_link', $link_id ); else do_action( 'add_link', $link_id ); clean_bookmark_cache( $link_id ); return $link_id; } /** * Update link with the specified link categories. * * @since 2.1.0 * * @param int $link_id ID of link to update * @param array $link_categories Array of categories to */ function wp_set_link_cats( $link_id = 0, $link_categories = array() ) { // If $link_categories isn't already an array, make it one: if ( !is_array( $link_categories ) || 0 == count( $link_categories ) ) $link_categories = array( get_option( 'default_link_category' ) ); $link_categories = array_map( 'intval', $link_categories ); $link_categories = array_unique( $link_categories ); wp_set_object_terms( $link_id, $link_categories, 'link_category' ); clean_bookmark_cache( $link_id ); } /** * Update a link in the database. * * @since 2.0.0 * * @param array $linkdata Link data to update. * @return int|WP_Error Value 0 or WP_Error on failure. The updated link ID on success. */ function wp_update_link( $linkdata ) { $link_id = (int) $linkdata['link_id']; $link = get_bookmark( $link_id, ARRAY_A ); // Escape data pulled from DB. $link = add_magic_quotes( $link ); // Passed link category list overwrites existing category list if not empty. if ( isset( $linkdata['link_category'] ) && is_array( $linkdata['link_category'] ) && 0 != count( $linkdata['link_category'] ) ) $link_cats = $linkdata['link_category']; else $link_cats = $link['link_category']; // Merge old and new fields with new fields overwriting old ones. $linkdata = array_merge( $link, $linkdata ); $linkdata['link_category'] = $link_cats; return wp_insert_link( $linkdata ); } /** * @since 3.5.0 * @access private */ function wp_link_manager_disabled_message() { global $pagenow; if ( 'link-manager.php' != $pagenow && 'link-add.php' != $pagenow && 'link.php' != $pagenow ) return; add_filter( 'pre_option_link_manager_enabled', '__return_true', 100 ); $really_can_manage_links = current_user_can( 'manage_links' ); remove_filter( 'pre_option_link_manager_enabled', '__return_true', 100 ); if ( $really_can_manage_links && current_user_can( 'install_plugins' ) ) { $link = network_admin_url( 'plugin-install.php?tab=search&amp;s=Link+Manager' ); wp_die( sprintf( __( 'If you are looking to use the link manager, please install the <a href="%s">Link Manager</a> plugin.' ), $link ) ); } wp_die( __( 'You do not have sufficient permissions to edit the links for this site.' ) ); } add_action( 'admin_page_access_denied', 'wp_link_manager_disabled_message' );
zyblog
trunk/zyblog/wp-admin/includes/bookmark.php
PHP
asf20
7,752
<?php /** * WordPress Administration Screen API. * * @package WordPress * @subpackage Administration */ /** * Get the column headers for a screen * * @since 2.7.0 * * @param string|WP_Screen $screen The screen you want the headers for * @return array Containing the headers in the format id => UI String */ function get_column_headers( $screen ) { if ( is_string( $screen ) ) $screen = convert_to_screen( $screen ); static $column_headers = array(); if ( ! isset( $column_headers[ $screen->id ] ) ) $column_headers[ $screen->id ] = apply_filters( 'manage_' . $screen->id . '_columns', array() ); return $column_headers[ $screen->id ]; } /** * Get a list of hidden columns. * * @since 2.7.0 * * @param string|WP_Screen $screen The screen you want the hidden columns for * @return array */ function get_hidden_columns( $screen ) { if ( is_string( $screen ) ) $screen = convert_to_screen( $screen ); return (array) get_user_option( 'manage' . $screen->id . 'columnshidden' ); } /** * Prints the meta box preferences for screen meta. * * @since 2.7.0 * * @param string|WP_Screen $screen */ function meta_box_prefs( $screen ) { global $wp_meta_boxes; if ( is_string( $screen ) ) $screen = convert_to_screen( $screen ); if ( empty($wp_meta_boxes[$screen->id]) ) return; $hidden = get_hidden_meta_boxes($screen); foreach ( array_keys($wp_meta_boxes[$screen->id]) as $context ) { foreach ( array_keys($wp_meta_boxes[$screen->id][$context]) as $priority ) { foreach ( $wp_meta_boxes[$screen->id][$context][$priority] as $box ) { if ( false == $box || ! $box['title'] ) continue; // Submit box cannot be hidden if ( 'submitdiv' == $box['id'] || 'linksubmitdiv' == $box['id'] ) continue; $box_id = $box['id']; echo '<label for="' . $box_id . '-hide">'; echo '<input class="hide-postbox-tog" name="' . $box_id . '-hide" type="checkbox" id="' . $box_id . '-hide" value="' . $box_id . '"' . (! in_array($box_id, $hidden) ? ' checked="checked"' : '') . ' />'; echo "{$box['title']}</label>\n"; } } } } /** * Get Hidden Meta Boxes * * @since 2.7.0 * * @param string|WP_Screen $screen Screen identifier * @return array Hidden Meta Boxes */ function get_hidden_meta_boxes( $screen ) { if ( is_string( $screen ) ) $screen = convert_to_screen( $screen ); $hidden = get_user_option( "metaboxhidden_{$screen->id}" ); $use_defaults = ! is_array( $hidden ); // Hide slug boxes by default if ( $use_defaults ) { $hidden = array(); if ( 'post' == $screen->base ) { if ( 'post' == $screen->post_type || 'page' == $screen->post_type || 'attachment' == $screen->post_type ) $hidden = array('slugdiv', 'trackbacksdiv', 'postcustom', 'postexcerpt', 'commentstatusdiv', 'commentsdiv', 'authordiv', 'revisionsdiv'); else $hidden = array( 'slugdiv' ); } $hidden = apply_filters( 'default_hidden_meta_boxes', $hidden, $screen ); } return apply_filters( 'hidden_meta_boxes', $hidden, $screen, $use_defaults ); } /** * Register and configure an admin screen option * * @since 3.1.0 * * @param string $option An option name. * @param mixed $args Option-dependent arguments. */ function add_screen_option( $option, $args = array() ) { $current_screen = get_current_screen(); if ( ! $current_screen ) return; $current_screen->add_option( $option, $args ); } /** * Displays a screen icon. * * @uses get_screen_icon() * @since 2.7.0 * * @param string|WP_Screen $screen Optional. Accepts a screen object (and defaults to the current screen object) * which it uses to determine an icon HTML ID. Or, if a string is provided, it is used to form the icon HTML ID. */ function screen_icon( $screen = '' ) { echo get_screen_icon( $screen ); } /** * Gets a screen icon. * * @since 3.2.0 * * @param string|WP_Screen $screen Optional. Accepts a screen object (and defaults to the current screen object) * which it uses to determine an icon HTML ID. Or, if a string is provided, it is used to form the icon HTML ID. * @return string HTML for the screen icon. */ function get_screen_icon( $screen = '' ) { if ( empty( $screen ) ) $screen = get_current_screen(); elseif ( is_string( $screen ) ) $icon_id = $screen; $class = 'icon32'; if ( empty( $icon_id ) ) { if ( ! empty( $screen->parent_base ) ) $icon_id = $screen->parent_base; else $icon_id = $screen->base; if ( 'page' == $screen->post_type ) $icon_id = 'edit-pages'; if ( $screen->post_type ) $class .= ' ' . sanitize_html_class( 'icon32-posts-' . $screen->post_type ); } return '<div id="icon-' . esc_attr( $icon_id ) . '" class="' . $class . '"><br /></div>'; } /** * Get the current screen object * * @since 3.1.0 * * @return WP_Screen Current screen object */ function get_current_screen() { global $current_screen; if ( ! isset( $current_screen ) ) return null; return $current_screen; } /** * Set the current screen object * * @since 3.0.0 * @uses $current_screen * * @param mixed $hook_name Optional. The hook name (also known as the hook suffix) used to determine the screen, * or an existing screen object. */ function set_current_screen( $hook_name = '' ) { WP_Screen::get( $hook_name )->set_current_screen(); } /** * A class representing the admin screen. * * @since 3.3.0 * @access public */ final class WP_Screen { /** * Any action associated with the screen. 'add' for *-add.php and *-new.php screens. Empty otherwise. * * @since 3.3.0 * @var string * @access public */ public $action; /** * The base type of the screen. This is typically the same as $id but with any post types and taxonomies stripped. * For example, for an $id of 'edit-post' the base is 'edit'. * * @since 3.3.0 * @var string * @access public */ public $base; /** * The number of columns to display. Access with get_columns(). * * @since 3.4.0 * @var int * @access private */ private $columns = 0; /** * The unique ID of the screen. * * @since 3.3.0 * @var string * @access public */ public $id; /** * Which admin the screen is in. network | user | site | false * * @since 3.5.0 * @var string * @access protected */ protected $in_admin; /** * Whether the screen is in the network admin. * * Deprecated. Use in_admin() instead. * * @since 3.3.0 * @deprecated 3.5.0 * @var bool * @access public */ public $is_network; /** * Whether the screen is in the user admin. * * Deprecated. Use in_admin() instead. * * @since 3.3.0 * @deprecated 3.5.0 * @var bool * @access public */ public $is_user; /** * The base menu parent. * This is derived from $parent_file by removing the query string and any .php extension. * $parent_file values of 'edit.php?post_type=page' and 'edit.php?post_type=post' have a $parent_base of 'edit'. * * @since 3.3.0 * @var string * @access public */ public $parent_base; /** * The parent_file for the screen per the admin menu system. * Some $parent_file values are 'edit.php?post_type=page', 'edit.php', and 'options-general.php'. * * @since 3.3.0 * @var string * @access public */ public $parent_file; /** * The post type associated with the screen, if any. * The 'edit.php?post_type=page' screen has a post type of 'page'. * The 'edit-tags.php?taxonomy=$taxonomy&post_type=page' screen has a post type of 'page'. * * @since 3.3.0 * @var string * @access public */ public $post_type; /** * The taxonomy associated with the screen, if any. * The 'edit-tags.php?taxonomy=category' screen has a taxonomy of 'category'. * @since 3.3.0 * @var string * @access public */ public $taxonomy; /** * The help tab data associated with the screen, if any. * * @since 3.3.0 * @var array * @access private */ private $_help_tabs = array(); /** * The help sidebar data associated with screen, if any. * * @since 3.3.0 * @var string * @access private */ private $_help_sidebar = ''; /** * Stores old string-based help. */ private static $_old_compat_help = array(); /** * The screen options associated with screen, if any. * * @since 3.3.0 * @var array * @access private */ private $_options = array(); /** * The screen object registry. * * @since 3.3.0 * @var array * @access private */ private static $_registry = array(); /** * Stores the result of the public show_screen_options function. * * @since 3.3.0 * @var bool * @access private */ private $_show_screen_options; /** * Stores the 'screen_settings' section of screen options. * * @since 3.3.0 * @var string * @access private */ private $_screen_settings; /** * Fetches a screen object. * * @since 3.3.0 * @access public * * @param string $hook_name Optional. The hook name (also known as the hook suffix) used to determine the screen. * Defaults to the current $hook_suffix global. * @return WP_Screen Screen object. */ public static function get( $hook_name = '' ) { if ( is_a( $hook_name, 'WP_Screen' ) ) return $hook_name; $post_type = $taxonomy = null; $in_admin = false; $action = ''; if ( $hook_name ) $id = $hook_name; else $id = $GLOBALS['hook_suffix']; // For those pesky meta boxes. if ( $hook_name && post_type_exists( $hook_name ) ) { $post_type = $id; $id = 'post'; // changes later. ends up being $base. } else { if ( '.php' == substr( $id, -4 ) ) $id = substr( $id, 0, -4 ); if ( 'post-new' == $id || 'link-add' == $id || 'media-new' == $id || 'user-new' == $id ) { $id = substr( $id, 0, -4 ); $action = 'add'; } } if ( ! $post_type && $hook_name ) { if ( '-network' == substr( $id, -8 ) ) { $id = substr( $id, 0, -8 ); $in_admin = 'network'; } elseif ( '-user' == substr( $id, -5 ) ) { $id = substr( $id, 0, -5 ); $in_admin = 'user'; } $id = sanitize_key( $id ); if ( 'edit-comments' != $id && 'edit-tags' != $id && 'edit-' == substr( $id, 0, 5 ) ) { $maybe = substr( $id, 5 ); if ( taxonomy_exists( $maybe ) ) { $id = 'edit-tags'; $taxonomy = $maybe; } elseif ( post_type_exists( $maybe ) ) { $id = 'edit'; $post_type = $maybe; } } if ( ! $in_admin ) $in_admin = 'site'; } else { if ( defined( 'WP_NETWORK_ADMIN' ) && WP_NETWORK_ADMIN ) $in_admin = 'network'; elseif ( defined( 'WP_USER_ADMIN' ) && WP_USER_ADMIN ) $in_admin = 'user'; else $in_admin = 'site'; } if ( 'index' == $id ) $id = 'dashboard'; elseif ( 'front' == $id ) $in_admin = false; $base = $id; // If this is the current screen, see if we can be more accurate for post types and taxonomies. if ( ! $hook_name ) { if ( isset( $_REQUEST['post_type'] ) ) $post_type = post_type_exists( $_REQUEST['post_type'] ) ? $_REQUEST['post_type'] : false; if ( isset( $_REQUEST['taxonomy'] ) ) $taxonomy = taxonomy_exists( $_REQUEST['taxonomy'] ) ? $_REQUEST['taxonomy'] : false; switch ( $base ) { case 'post' : if ( isset( $_GET['post'] ) ) $post_id = (int) $_GET['post']; elseif ( isset( $_POST['post_ID'] ) ) $post_id = (int) $_POST['post_ID']; else $post_id = 0; if ( $post_id ) { $post = get_post( $post_id ); if ( $post ) $post_type = $post->post_type; } break; case 'edit-tags' : if ( null === $post_type && is_object_in_taxonomy( 'post', $taxonomy ? $taxonomy : 'post_tag' ) ) $post_type = 'post'; break; } } switch ( $base ) { case 'post' : if ( null === $post_type ) $post_type = 'post'; $id = $post_type; break; case 'edit' : if ( null === $post_type ) $post_type = 'post'; $id .= '-' . $post_type; break; case 'edit-tags' : if ( null === $taxonomy ) $taxonomy = 'post_tag'; // The edit-tags ID does not contain the post type. Look for it in the request. if ( null === $post_type ) { $post_type = 'post'; if ( isset( $_REQUEST['post_type'] ) && post_type_exists( $_REQUEST['post_type'] ) ) $post_type = $_REQUEST['post_type']; } $id = 'edit-' . $taxonomy; break; } if ( 'network' == $in_admin ) { $id .= '-network'; $base .= '-network'; } elseif ( 'user' == $in_admin ) { $id .= '-user'; $base .= '-user'; } if ( isset( self::$_registry[ $id ] ) ) { $screen = self::$_registry[ $id ]; if ( $screen === get_current_screen() ) return $screen; } else { $screen = new WP_Screen(); $screen->id = $id; } $screen->base = $base; $screen->action = $action; $screen->post_type = (string) $post_type; $screen->taxonomy = (string) $taxonomy; $screen->is_user = ( 'user' == $in_admin ); $screen->is_network = ( 'network' == $in_admin ); $screen->in_admin = $in_admin; self::$_registry[ $id ] = $screen; return $screen; } /** * Makes the screen object the current screen. * * @see set_current_screen() * @since 3.3.0 */ function set_current_screen() { global $current_screen, $taxnow, $typenow; $current_screen = $this; $taxnow = $this->taxonomy; $typenow = $this->post_type; do_action( 'current_screen', $current_screen ); } /** * Constructor * * @since 3.3.0 * @access private */ private function __construct() {} /** * Indicates whether the screen is in a particular admin * * @since 3.5.0 * * @param string $admin The admin to check against (network | user | site). * If empty any of the three admins will result in true. * @return boolean True if the screen is in the indicated admin, false otherwise. * */ public function in_admin( $admin = null ) { if ( empty( $admin ) ) return (bool) $this->in_admin; return ( $admin == $this->in_admin ); } /** * Sets the old string-based contextual help for the screen. * * For backwards compatibility. * * @since 3.3.0 * * @param WP_Screen $screen A screen object. * @param string $help Help text. */ static function add_old_compat_help( $screen, $help ) { self::$_old_compat_help[ $screen->id ] = $help; } /** * Set the parent information for the screen. * This is called in admin-header.php after the menu parent for the screen has been determined. * * @since 3.3.0 * * @param string $parent_file The parent file of the screen. Typically the $parent_file global. */ function set_parentage( $parent_file ) { $this->parent_file = $parent_file; list( $this->parent_base ) = explode( '?', $parent_file ); $this->parent_base = str_replace( '.php', '', $this->parent_base ); } /** * Adds an option for the screen. * Call this in template files after admin.php is loaded and before admin-header.php is loaded to add screen options. * * @since 3.3.0 * * @param string $option Option ID * @param mixed $args Option-dependent arguments. */ public function add_option( $option, $args = array() ) { $this->_options[ $option ] = $args; } /** * Gets the arguments for an option for the screen. * * @since 3.3.0 * * @param string $option Option ID. * @param mixed $key Optional. Specific array key for when the option is an array. */ public function get_option( $option, $key = false ) { if ( ! isset( $this->_options[ $option ] ) ) return null; if ( $key ) { if ( isset( $this->_options[ $option ][ $key ] ) ) return $this->_options[ $option ][ $key ]; return null; } return $this->_options[ $option ]; } /** * Gets the help tabs registered for the screen. * * @since 3.4.0 * * @return array Help tabs with arguments. */ public function get_help_tabs() { return $this->_help_tabs; } /** * Gets the arguments for a help tab. * * @since 3.4.0 * * @param string $id Help Tab ID. * @return array Help tab arguments. */ public function get_help_tab( $id ) { if ( ! isset( $this->_help_tabs[ $id ] ) ) return null; return $this->_help_tabs[ $id ]; } /** * Add a help tab to the contextual help for the screen. * Call this on the load-$pagenow hook for the relevant screen. * * @since 3.3.0 * * @param array $args * - string - title - Title for the tab. * - string - id - Tab ID. Must be HTML-safe. * - string - content - Help tab content in plain text or HTML. Optional. * - callback - callback - A callback to generate the tab content. Optional. * */ public function add_help_tab( $args ) { $defaults = array( 'title' => false, 'id' => false, 'content' => '', 'callback' => false, ); $args = wp_parse_args( $args, $defaults ); $args['id'] = sanitize_html_class( $args['id'] ); // Ensure we have an ID and title. if ( ! $args['id'] || ! $args['title'] ) return; // Allows for overriding an existing tab with that ID. $this->_help_tabs[ $args['id'] ] = $args; } /** * Removes a help tab from the contextual help for the screen. * * @since 3.3.0 * * @param string $id The help tab ID. */ public function remove_help_tab( $id ) { unset( $this->_help_tabs[ $id ] ); } /** * Removes all help tabs from the contextual help for the screen. * * @since 3.3.0 */ public function remove_help_tabs() { $this->_help_tabs = array(); } /** * Gets the content from a contextual help sidebar. * * @since 3.4.0 * * @return string Contents of the help sidebar. */ public function get_help_sidebar() { return $this->_help_sidebar; } /** * Add a sidebar to the contextual help for the screen. * Call this in template files after admin.php is loaded and before admin-header.php is loaded to add a sidebar to the contextual help. * * @since 3.3.0 * * @param string $content Sidebar content in plain text or HTML. */ public function set_help_sidebar( $content ) { $this->_help_sidebar = $content; } /** * Gets the number of layout columns the user has selected. * * The layout_columns option controls the max number and default number of * columns. This method returns the number of columns within that range selected * by the user via Screen Options. If no selection has been made, the default * provisioned in layout_columns is returned. If the screen does not support * selecting the number of layout columns, 0 is returned. * * @since 3.4.0 * * @return int Number of columns to display. */ public function get_columns() { return $this->columns; } /** * Render the screen's help section. * * This will trigger the deprecated filters for backwards compatibility. * * @since 3.3.0 */ public function render_screen_meta() { // Call old contextual_help_list filter. self::$_old_compat_help = apply_filters( 'contextual_help_list', self::$_old_compat_help, $this ); $old_help = isset( self::$_old_compat_help[ $this->id ] ) ? self::$_old_compat_help[ $this->id ] : ''; $old_help = apply_filters( 'contextual_help', $old_help, $this->id, $this ); // Default help only if there is no old-style block of text and no new-style help tabs. if ( empty( $old_help ) && ! $this->get_help_tabs() ) { $default_help = apply_filters( 'default_contextual_help', '' ); if ( $default_help ) $old_help = '<p>' . $default_help . '</p>'; } if ( $old_help ) { $this->add_help_tab( array( 'id' => 'old-contextual-help', 'title' => __('Overview'), 'content' => $old_help, ) ); } $help_sidebar = $this->get_help_sidebar(); $help_class = 'hidden'; if ( ! $help_sidebar ) $help_class .= ' no-sidebar'; // Time to render! ?> <div id="screen-meta" class="metabox-prefs"> <div id="contextual-help-wrap" class="<?php echo esc_attr( $help_class ); ?>" tabindex="-1" aria-label="<?php esc_attr_e('Contextual Help Tab'); ?>"> <div id="contextual-help-back"></div> <div id="contextual-help-columns"> <div class="contextual-help-tabs"> <ul> <?php $class = ' class="active"'; foreach ( $this->get_help_tabs() as $tab ) : $link_id = "tab-link-{$tab['id']}"; $panel_id = "tab-panel-{$tab['id']}"; ?> <li id="<?php echo esc_attr( $link_id ); ?>"<?php echo $class; ?>> <a href="<?php echo esc_url( "#$panel_id" ); ?>" aria-controls="<?php echo esc_attr( $panel_id ); ?>"> <?php echo esc_html( $tab['title'] ); ?> </a> </li> <?php $class = ''; endforeach; ?> </ul> </div> <?php if ( $help_sidebar ) : ?> <div class="contextual-help-sidebar"> <?php echo $help_sidebar; ?> </div> <?php endif; ?> <div class="contextual-help-tabs-wrap"> <?php $classes = 'help-tab-content active'; foreach ( $this->get_help_tabs() as $tab ): $panel_id = "tab-panel-{$tab['id']}"; ?> <div id="<?php echo esc_attr( $panel_id ); ?>" class="<?php echo $classes; ?>"> <?php // Print tab content. echo $tab['content']; // If it exists, fire tab callback. if ( ! empty( $tab['callback'] ) ) call_user_func_array( $tab['callback'], array( $this, $tab ) ); ?> </div> <?php $classes = 'help-tab-content'; endforeach; ?> </div> </div> </div> <?php // Setup layout columns // Back compat for plugins using the filter instead of add_screen_option() $columns = apply_filters( 'screen_layout_columns', array(), $this->id, $this ); if ( ! empty( $columns ) && isset( $columns[ $this->id ] ) ) $this->add_option( 'layout_columns', array('max' => $columns[ $this->id ] ) ); if ( $this->get_option( 'layout_columns' ) ) { $this->columns = (int) get_user_option("screen_layout_$this->id"); if ( ! $this->columns && $this->get_option( 'layout_columns', 'default' ) ) $this->columns = $this->get_option( 'layout_columns', 'default' ); } $GLOBALS[ 'screen_layout_columns' ] = $this->columns; // Set the global for back-compat. // Add screen options if ( $this->show_screen_options() ) $this->render_screen_options(); ?> </div> <?php if ( ! $this->get_help_tabs() && ! $this->show_screen_options() ) return; ?> <div id="screen-meta-links"> <?php if ( $this->get_help_tabs() ) : ?> <div id="contextual-help-link-wrap" class="hide-if-no-js screen-meta-toggle"> <a href="#contextual-help-wrap" id="contextual-help-link" class="show-settings" aria-controls="contextual-help-wrap" aria-expanded="false"><?php _e( 'Help' ); ?></a> </div> <?php endif; if ( $this->show_screen_options() ) : ?> <div id="screen-options-link-wrap" class="hide-if-no-js screen-meta-toggle"> <a href="#screen-options-wrap" id="show-settings-link" class="show-settings" aria-controls="screen-options-wrap" aria-expanded="false"><?php _e( 'Screen Options' ); ?></a> </div> <?php endif; ?> </div> <?php } public function show_screen_options() { global $wp_meta_boxes; if ( is_bool( $this->_show_screen_options ) ) return $this->_show_screen_options; $columns = get_column_headers( $this ); $show_screen = ! empty( $wp_meta_boxes[ $this->id ] ) || $columns || $this->get_option( 'per_page' ); $this->_screen_settings = apply_filters( 'screen_settings', '', $this ); switch ( $this->id ) { case 'widgets': $this->_screen_settings = '<p><a id="access-on" href="widgets.php?widgets-access=on">' . __('Enable accessibility mode') . '</a><a id="access-off" href="widgets.php?widgets-access=off">' . __('Disable accessibility mode') . "</a></p>\n"; break; } if ( $this->_screen_settings || $this->_options ) $show_screen = true; $this->_show_screen_options = apply_filters( 'screen_options_show_screen', $show_screen, $this ); return $this->_show_screen_options; } /** * Render the screen options tab. * * @since 3.3.0 */ public function render_screen_options() { global $wp_meta_boxes, $wp_list_table; $columns = get_column_headers( $this ); $hidden = get_hidden_columns( $this ); ?> <div id="screen-options-wrap" class="hidden" tabindex="-1" aria-label="<?php esc_attr_e('Screen Options Tab'); ?>"> <form id="adv-settings" action="" method="post"> <?php if ( isset( $wp_meta_boxes[ $this->id ] ) || $this->get_option( 'per_page' ) || ( $columns && empty( $columns['_title'] ) ) ) : ?> <h5><?php _e( 'Show on screen' ); ?></h5> <?php endif; if ( isset( $wp_meta_boxes[ $this->id ] ) ) : ?> <div class="metabox-prefs"> <?php meta_box_prefs( $this ); if ( 'dashboard' === $this->id && has_action( 'welcome_panel' ) && current_user_can( 'edit_theme_options' ) ) { if ( isset( $_GET['welcome'] ) ) { $welcome_checked = empty( $_GET['welcome'] ) ? 0 : 1; update_user_meta( get_current_user_id(), 'show_welcome_panel', $welcome_checked ); } else { $welcome_checked = get_user_meta( get_current_user_id(), 'show_welcome_panel', true ); if ( 2 == $welcome_checked && wp_get_current_user()->user_email != get_option( 'admin_email' ) ) $welcome_checked = false; } echo '<label for="wp_welcome_panel-hide">'; echo '<input type="checkbox" id="wp_welcome_panel-hide"' . checked( (bool) $welcome_checked, true, false ) . ' />'; echo _x( 'Welcome', 'Welcome panel' ) . "</label>\n"; } ?> <br class="clear" /> </div> <?php endif; if ( $columns ) : if ( ! empty( $columns['_title'] ) ) : ?> <h5><?php echo $columns['_title']; ?></h5> <?php endif; ?> <div class="metabox-prefs"> <?php $special = array('_title', 'cb', 'comment', 'media', 'name', 'title', 'username', 'blogname'); foreach ( $columns as $column => $title ) { // Can't hide these for they are special if ( in_array( $column, $special ) ) continue; if ( empty( $title ) ) continue; if ( 'comments' == $column ) $title = __( 'Comments' ); $id = "$column-hide"; echo '<label for="' . $id . '">'; echo '<input class="hide-column-tog" name="' . $id . '" type="checkbox" id="' . $id . '" value="' . $column . '"' . checked( !in_array($column, $hidden), true, false ) . ' />'; echo "$title</label>\n"; } ?> <br class="clear" /> </div> <?php endif; $this->render_screen_layout(); $this->render_per_page_options(); echo $this->_screen_settings; ?> <div><?php wp_nonce_field( 'screen-options-nonce', 'screenoptionnonce', false ); ?></div> </form> </div> <?php } /** * Render the option for number of columns on the page * * @since 3.3.0 */ function render_screen_layout() { if ( ! $this->get_option('layout_columns') ) return; $screen_layout_columns = $this->get_columns(); $num = $this->get_option( 'layout_columns', 'max' ); ?> <h5 class="screen-layout"><?php _e('Screen Layout'); ?></h5> <div class='columns-prefs'><?php _e('Number of Columns:'); for ( $i = 1; $i <= $num; ++$i ): ?> <label class="columns-prefs-<?php echo $i; ?>"> <input type='radio' name='screen_columns' value='<?php echo esc_attr( $i ); ?>' <?php checked( $screen_layout_columns, $i ); ?> /> <?php echo esc_html( $i ); ?> </label> <?php endfor; ?> </div> <?php } /** * Render the items per page option * * @since 3.3.0 */ function render_per_page_options() { if ( ! $this->get_option( 'per_page' ) ) return; $per_page_label = $this->get_option( 'per_page', 'label' ); $option = $this->get_option( 'per_page', 'option' ); if ( ! $option ) $option = str_replace( '-', '_', "{$this->id}_per_page" ); $per_page = (int) get_user_option( $option ); if ( empty( $per_page ) || $per_page < 1 ) { $per_page = $this->get_option( 'per_page', 'default' ); if ( ! $per_page ) $per_page = 20; } if ( 'edit_comments_per_page' == $option ) { $comment_status = isset( $_REQUEST['comment_status'] ) ? $_REQUEST['comment_status'] : 'all'; $per_page = apply_filters( 'comments_per_page', $per_page, $comment_status ); } elseif ( 'categories_per_page' == $option ) { $per_page = apply_filters( 'edit_categories_per_page', $per_page ); } else { $per_page = apply_filters( $option, $per_page ); } // Back compat if ( isset( $this->post_type ) ) $per_page = apply_filters( 'edit_posts_per_page', $per_page, $this->post_type ); ?> <div class="screen-options"> <?php if ( $per_page_label ) : ?> <input type="number" step="1" min="1" max="999" class="screen-per-page" name="wp_screen_options[value]" id="<?php echo esc_attr( $option ); ?>" maxlength="3" value="<?php echo esc_attr( $per_page ); ?>" /> <label for="<?php echo esc_attr( $option ); ?>"> <?php echo esc_html( $per_page_label ); ?> </label> <?php endif; echo get_submit_button( __( 'Apply' ), 'button', 'screen-options-apply', false ); ?> <input type='hidden' name='wp_screen_options[option]' value='<?php echo esc_attr($option); ?>' /> </div> <?php } }
zyblog
trunk/zyblog/wp-admin/includes/screen.php
PHP
asf20
29,069
<?php /** * WordPress Dashboard Widget Administration Screen API * * @package WordPress * @subpackage Administration */ /** * Registers dashboard widgets. * * Handles POST data, sets up filters. * * @since 2.5.0 */ function wp_dashboard_setup() { global $wp_registered_widgets, $wp_registered_widget_controls, $wp_dashboard_control_callbacks; $wp_dashboard_control_callbacks = array(); $screen = get_current_screen(); $update = false; $widget_options = get_option( 'dashboard_widget_options' ); if ( !$widget_options || !is_array($widget_options) ) $widget_options = array(); /* Register Widgets and Controls */ $response = wp_check_browser_version(); if ( $response && $response['upgrade'] ) { add_filter( 'postbox_classes_dashboard_dashboard_browser_nag', 'dashboard_browser_nag_class' ); if ( $response['insecure'] ) wp_add_dashboard_widget( 'dashboard_browser_nag', __( 'You are using an insecure browser!' ), 'wp_dashboard_browser_nag' ); else wp_add_dashboard_widget( 'dashboard_browser_nag', __( 'Your browser is out of date!' ), 'wp_dashboard_browser_nag' ); } // Right Now if ( is_blog_admin() && current_user_can('edit_posts') ) wp_add_dashboard_widget( 'dashboard_right_now', __( 'Right Now' ), 'wp_dashboard_right_now' ); if ( is_network_admin() ) wp_add_dashboard_widget( 'network_dashboard_right_now', __( 'Right Now' ), 'wp_network_dashboard_right_now' ); // Recent Comments Widget if ( is_blog_admin() && current_user_can('moderate_comments') ) { if ( !isset( $widget_options['dashboard_recent_comments'] ) || !isset( $widget_options['dashboard_recent_comments']['items'] ) ) { $update = true; $widget_options['dashboard_recent_comments'] = array( 'items' => 5, ); } $recent_comments_title = __( 'Recent Comments' ); wp_add_dashboard_widget( 'dashboard_recent_comments', $recent_comments_title, 'wp_dashboard_recent_comments', 'wp_dashboard_recent_comments_control' ); } // Incoming Links Widget if ( is_blog_admin() && current_user_can('publish_posts') ) { if ( !isset( $widget_options['dashboard_incoming_links'] ) || !isset( $widget_options['dashboard_incoming_links']['home'] ) || $widget_options['dashboard_incoming_links']['home'] != get_option('home') ) { $update = true; $num_items = isset($widget_options['dashboard_incoming_links']['items']) ? $widget_options['dashboard_incoming_links']['items'] : 10; $widget_options['dashboard_incoming_links'] = array( 'home' => get_option('home'), 'link' => apply_filters( 'dashboard_incoming_links_link', 'http://blogsearch.google.com/blogsearch?scoring=d&partner=wordpress&q=link:' . trailingslashit( get_option('home') ) ), 'url' => isset($widget_options['dashboard_incoming_links']['url']) ? apply_filters( 'dashboard_incoming_links_feed', $widget_options['dashboard_incoming_links']['url'] ) : apply_filters( 'dashboard_incoming_links_feed', 'http://blogsearch.google.com/blogsearch_feeds?scoring=d&ie=utf-8&num=' . $num_items . '&output=rss&partner=wordpress&q=link:' . trailingslashit( get_option('home') ) ), 'items' => $num_items, 'show_date' => isset($widget_options['dashboard_incoming_links']['show_date']) ? $widget_options['dashboard_incoming_links']['show_date'] : false ); } wp_add_dashboard_widget( 'dashboard_incoming_links', __( 'Incoming Links' ), 'wp_dashboard_incoming_links', 'wp_dashboard_incoming_links_control' ); } // WP Plugins Widget if ( ( ! is_multisite() && is_blog_admin() && current_user_can( 'install_plugins' ) ) || ( is_network_admin() && current_user_can( 'manage_network_plugins' ) && current_user_can( 'install_plugins' ) ) ) wp_add_dashboard_widget( 'dashboard_plugins', __( 'Plugins' ), 'wp_dashboard_plugins' ); // QuickPress Widget if ( is_blog_admin() && current_user_can('edit_posts') ) wp_add_dashboard_widget( 'dashboard_quick_press', __( 'QuickPress' ), 'wp_dashboard_quick_press' ); // Recent Drafts if ( is_blog_admin() && current_user_can('edit_posts') ) wp_add_dashboard_widget( 'dashboard_recent_drafts', __('Recent Drafts'), 'wp_dashboard_recent_drafts' ); // Primary feed (Dev Blog) Widget if ( !isset( $widget_options['dashboard_primary'] ) ) { $update = true; $widget_options['dashboard_primary'] = array( 'link' => apply_filters( 'dashboard_primary_link', __( 'http://wordpress.org/news/' ) ), 'url' => apply_filters( 'dashboard_primary_feed', __( 'http://wordpress.org/news/feed/' ) ), 'title' => apply_filters( 'dashboard_primary_title', __( 'WordPress Blog' ) ), 'items' => 2, 'show_summary' => 1, 'show_author' => 0, 'show_date' => 1, ); } wp_add_dashboard_widget( 'dashboard_primary', $widget_options['dashboard_primary']['title'], 'wp_dashboard_primary', 'wp_dashboard_primary_control' ); // Secondary Feed (Planet) Widget if ( !isset( $widget_options['dashboard_secondary'] ) ) { $update = true; $widget_options['dashboard_secondary'] = array( 'link' => apply_filters( 'dashboard_secondary_link', __( 'http://planet.wordpress.org/' ) ), 'url' => apply_filters( 'dashboard_secondary_feed', __( 'http://planet.wordpress.org/feed/' ) ), 'title' => apply_filters( 'dashboard_secondary_title', __( 'Other WordPress News' ) ), 'items' => 5, 'show_summary' => 0, 'show_author' => 0, 'show_date' => 0, ); } wp_add_dashboard_widget( 'dashboard_secondary', $widget_options['dashboard_secondary']['title'], 'wp_dashboard_secondary', 'wp_dashboard_secondary_control' ); // Hook to register new widgets // Filter widget order if ( is_network_admin() ) { do_action( 'wp_network_dashboard_setup' ); $dashboard_widgets = apply_filters( 'wp_network_dashboard_widgets', array() ); } elseif ( is_user_admin() ) { do_action( 'wp_user_dashboard_setup' ); $dashboard_widgets = apply_filters( 'wp_user_dashboard_widgets', array() ); } else { do_action( 'wp_dashboard_setup' ); $dashboard_widgets = apply_filters( 'wp_dashboard_widgets', array() ); } foreach ( $dashboard_widgets as $widget_id ) { $name = empty( $wp_registered_widgets[$widget_id]['all_link'] ) ? $wp_registered_widgets[$widget_id]['name'] : $wp_registered_widgets[$widget_id]['name'] . " <a href='{$wp_registered_widgets[$widget_id]['all_link']}' class='edit-box open-box'>" . __('View all') . '</a>'; wp_add_dashboard_widget( $widget_id, $name, $wp_registered_widgets[$widget_id]['callback'], $wp_registered_widget_controls[$widget_id]['callback'] ); } if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset($_POST['widget_id']) ) { check_admin_referer( 'edit-dashboard-widget_' . $_POST['widget_id'], 'dashboard-widget-nonce' ); ob_start(); // hack - but the same hack wp-admin/widgets.php uses wp_dashboard_trigger_widget_control( $_POST['widget_id'] ); ob_end_clean(); wp_redirect( remove_query_arg( 'edit' ) ); exit; } if ( $update ) update_option( 'dashboard_widget_options', $widget_options ); do_action('do_meta_boxes', $screen->id, 'normal', ''); do_action('do_meta_boxes', $screen->id, 'side', ''); } function wp_add_dashboard_widget( $widget_id, $widget_name, $callback, $control_callback = null ) { $screen = get_current_screen(); global $wp_dashboard_control_callbacks; if ( $control_callback && current_user_can( 'edit_dashboard' ) && is_callable( $control_callback ) ) { $wp_dashboard_control_callbacks[$widget_id] = $control_callback; if ( isset( $_GET['edit'] ) && $widget_id == $_GET['edit'] ) { list($url) = explode( '#', add_query_arg( 'edit', false ), 2 ); $widget_name .= ' <span class="postbox-title-action"><a href="' . esc_url( $url ) . '">' . __( 'Cancel' ) . '</a></span>'; $callback = '_wp_dashboard_control_callback'; } else { list($url) = explode( '#', add_query_arg( 'edit', $widget_id ), 2 ); $widget_name .= ' <span class="postbox-title-action"><a href="' . esc_url( "$url#$widget_id" ) . '" class="edit-box open-box">' . __( 'Configure' ) . '</a></span>'; } } if ( is_blog_admin () ) $side_widgets = array('dashboard_quick_press', 'dashboard_recent_drafts', 'dashboard_primary', 'dashboard_secondary'); else if (is_network_admin() ) $side_widgets = array('dashboard_primary', 'dashboard_secondary'); else $side_widgets = array(); $location = 'normal'; if ( in_array($widget_id, $side_widgets) ) $location = 'side'; $priority = 'core'; if ( 'dashboard_browser_nag' === $widget_id ) $priority = 'high'; add_meta_box( $widget_id, $widget_name, $callback, $screen, $location, $priority ); } function _wp_dashboard_control_callback( $dashboard, $meta_box ) { echo '<form action="" method="post" class="dashboard-widget-control-form">'; wp_dashboard_trigger_widget_control( $meta_box['id'] ); wp_nonce_field( 'edit-dashboard-widget_' . $meta_box['id'], 'dashboard-widget-nonce' ); echo '<input type="hidden" name="widget_id" value="' . esc_attr($meta_box['id']) . '" />'; submit_button( __('Submit') ); echo '</form>'; } /** * Displays the dashboard. * * @since 2.5.0 */ function wp_dashboard() { $screen = get_current_screen(); $class = 'columns-' . get_current_screen()->get_columns(); ?> <div id="dashboard-widgets" class="metabox-holder <?php echo $class; ?>"> <div id='postbox-container-1' class='postbox-container'> <?php do_meta_boxes( $screen->id, 'normal', '' ); ?> </div> <div id='postbox-container-2' class='postbox-container'> <?php do_meta_boxes( $screen->id, 'side', '' ); ?> </div> <div id='postbox-container-3' class='postbox-container'> <?php do_meta_boxes( $screen->id, 'column3', '' ); ?> </div> <div id='postbox-container-4' class='postbox-container'> <?php do_meta_boxes( $screen->id, 'column4', '' ); ?> </div> </div> <?php wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false ); wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false ); } /* Dashboard Widgets */ function wp_dashboard_right_now() { global $wp_registered_sidebars; $num_posts = wp_count_posts( 'post' ); $num_pages = wp_count_posts( 'page' ); $num_cats = wp_count_terms('category'); $num_tags = wp_count_terms('post_tag'); $num_comm = wp_count_comments( ); echo "\n\t".'<div class="table table_content">'; echo "\n\t".'<p class="sub">' . __('Content') . '</p>'."\n\t".'<table>'; echo "\n\t".'<tr class="first">'; // Posts $num = number_format_i18n( $num_posts->publish ); $text = _n( 'Post', 'Posts', intval($num_posts->publish) ); if ( current_user_can( 'edit_posts' ) ) { $num = "<a href='edit.php'>$num</a>"; $text = "<a href='edit.php'>$text</a>"; } echo '<td class="first b b-posts">' . $num . '</td>'; echo '<td class="t posts">' . $text . '</td>'; echo '</tr><tr>'; /* TODO: Show status breakdown on hover if ( $can_edit_pages && !empty($num_pages->publish) ) { // how many pages is not exposed in feeds. Don't show if !current_user_can $post_type_texts[] = '<a href="edit-pages.php">'.sprintf( _n( '%s page', '%s pages', $num_pages->publish ), number_format_i18n( $num_pages->publish ) ).'</a>'; } if ( $can_edit_posts && !empty($num_posts->draft) ) { $post_type_texts[] = '<a href="edit.php?post_status=draft">'.sprintf( _n( '%s draft', '%s drafts', $num_posts->draft ), number_format_i18n( $num_posts->draft ) ).'</a>'; } if ( $can_edit_posts && !empty($num_posts->future) ) { $post_type_texts[] = '<a href="edit.php?post_status=future">'.sprintf( _n( '%s scheduled post', '%s scheduled posts', $num_posts->future ), number_format_i18n( $num_posts->future ) ).'</a>'; } if ( current_user_can('publish_posts') && !empty($num_posts->pending) ) { $pending_text = sprintf( _n( 'There is <a href="%1$s">%2$s post</a> pending your review.', 'There are <a href="%1$s">%2$s posts</a> pending your review.', $num_posts->pending ), 'edit.php?post_status=pending', number_format_i18n( $num_posts->pending ) ); } else { $pending_text = ''; } */ // Pages $num = number_format_i18n( $num_pages->publish ); $text = _n( 'Page', 'Pages', $num_pages->publish ); if ( current_user_can( 'edit_pages' ) ) { $num = "<a href='edit.php?post_type=page'>$num</a>"; $text = "<a href='edit.php?post_type=page'>$text</a>"; } echo '<td class="first b b_pages">' . $num . '</td>'; echo '<td class="t pages">' . $text . '</td>'; echo '</tr><tr>'; // Categories $num = number_format_i18n( $num_cats ); $text = _n( 'Category', 'Categories', $num_cats ); if ( current_user_can( 'manage_categories' ) ) { $num = "<a href='edit-tags.php?taxonomy=category'>$num</a>"; $text = "<a href='edit-tags.php?taxonomy=category'>$text</a>"; } echo '<td class="first b b-cats">' . $num . '</td>'; echo '<td class="t cats">' . $text . '</td>'; echo '</tr><tr>'; // Tags $num = number_format_i18n( $num_tags ); $text = _n( 'Tag', 'Tags', $num_tags ); if ( current_user_can( 'manage_categories' ) ) { $num = "<a href='edit-tags.php'>$num</a>"; $text = "<a href='edit-tags.php'>$text</a>"; } echo '<td class="first b b-tags">' . $num . '</td>'; echo '<td class="t tags">' . $text . '</td>'; echo "</tr>"; do_action('right_now_content_table_end'); echo "\n\t</table>\n\t</div>"; echo "\n\t".'<div class="table table_discussion">'; echo "\n\t".'<p class="sub">' . __('Discussion') . '</p>'."\n\t".'<table>'; echo "\n\t".'<tr class="first">'; // Total Comments $num = '<span class="total-count">' . number_format_i18n($num_comm->total_comments) . '</span>'; $text = _n( 'Comment', 'Comments', $num_comm->total_comments ); if ( current_user_can( 'moderate_comments' ) ) { $num = '<a href="edit-comments.php">' . $num . '</a>'; $text = '<a href="edit-comments.php">' . $text . '</a>'; } echo '<td class="b b-comments">' . $num . '</td>'; echo '<td class="last t comments">' . $text . '</td>'; echo '</tr><tr>'; // Approved Comments $num = '<span class="approved-count">' . number_format_i18n($num_comm->approved) . '</span>'; $text = _nx( 'Approved', 'Approved', $num_comm->approved, 'Right Now' ); if ( current_user_can( 'moderate_comments' ) ) { $num = "<a href='edit-comments.php?comment_status=approved'>$num</a>"; $text = "<a class='approved' href='edit-comments.php?comment_status=approved'>$text</a>"; } echo '<td class="b b_approved">' . $num . '</td>'; echo '<td class="last t">' . $text . '</td>'; echo "</tr>\n\t<tr>"; // Pending Comments $num = '<span class="pending-count">' . number_format_i18n($num_comm->moderated) . '</span>'; $text = _n( 'Pending', 'Pending', $num_comm->moderated ); if ( current_user_can( 'moderate_comments' ) ) { $num = "<a href='edit-comments.php?comment_status=moderated'>$num</a>"; $text = "<a class='waiting' href='edit-comments.php?comment_status=moderated'>$text</a>"; } echo '<td class="b b-waiting">' . $num . '</td>'; echo '<td class="last t">' . $text . '</td>'; echo "</tr>\n\t<tr>"; // Spam Comments $num = number_format_i18n($num_comm->spam); $text = _nx( 'Spam', 'Spam', $num_comm->spam, 'comment' ); if ( current_user_can( 'moderate_comments' ) ) { $num = "<a href='edit-comments.php?comment_status=spam'><span class='spam-count'>$num</span></a>"; $text = "<a class='spam' href='edit-comments.php?comment_status=spam'>$text</a>"; } echo '<td class="b b-spam">' . $num . '</td>'; echo '<td class="last t">' . $text . '</td>'; echo "</tr>"; do_action('right_now_table_end'); do_action('right_now_discussion_table_end'); echo "\n\t</table>\n\t</div>"; echo "\n\t".'<div class="versions">'; $theme = wp_get_theme(); echo "\n\t<p>"; if ( $theme->errors() ) { if ( ! is_multisite() || is_super_admin() ) echo '<span class="error-message">' . __('ERROR: The themes directory is either empty or doesn&#8217;t exist. Please check your installation.') . '</span>'; } elseif ( ! empty($wp_registered_sidebars) ) { $sidebars_widgets = wp_get_sidebars_widgets(); $num_widgets = 0; foreach ( (array) $sidebars_widgets as $k => $v ) { if ( 'wp_inactive_widgets' == $k || 'orphaned_widgets' == substr( $k, 0, 16 ) ) continue; if ( is_array($v) ) $num_widgets = $num_widgets + count($v); } $num = number_format_i18n( $num_widgets ); $switch_themes = $theme->display('Name'); if ( current_user_can( 'switch_themes') ) $switch_themes = '<a href="themes.php">' . $switch_themes . '</a>'; if ( current_user_can( 'edit_theme_options' ) ) { printf(_n('Theme <span class="b">%1$s</span> with <span class="b"><a href="widgets.php">%2$s Widget</a></span>', 'Theme <span class="b">%1$s</span> with <span class="b"><a href="widgets.php">%2$s Widgets</a></span>', $num_widgets), $switch_themes, $num); } else { printf(_n('Theme <span class="b">%1$s</span> with <span class="b">%2$s Widget</span>', 'Theme <span class="b">%1$s</span> with <span class="b">%2$s Widgets</span>', $num_widgets), $switch_themes, $num); } } else { if ( current_user_can( 'switch_themes' ) ) printf( __('Theme <span class="b"><a href="themes.php">%1$s</a></span>'), $theme->display('Name') ); else printf( __('Theme <span class="b">%1$s</span>'), $theme->display('Name') ); } echo '</p>'; // Check if search engines are asked not to index this site. if ( !is_network_admin() && !is_user_admin() && current_user_can('manage_options') && '1' != get_option('blog_public') ) { $title = apply_filters('privacy_on_link_title', __('Your site is asking search engines not to index its content') ); $content = apply_filters('privacy_on_link_text', __('Search Engines Discouraged') ); echo "<p><a href='options-reading.php' title='$title'>$content</a></p>"; } update_right_now_message(); echo "\n\t".'<br class="clear" /></div>'; do_action( 'rightnow_end' ); do_action( 'activity_box_end' ); } function wp_network_dashboard_right_now() { $actions = array(); if ( current_user_can('create_sites') ) $actions['create-site'] = '<a href="' . network_admin_url('site-new.php') . '">' . __( 'Create a New Site' ) . '</a>'; if ( current_user_can('create_users') ) $actions['create-user'] = '<a href="' . network_admin_url('user-new.php') . '">' . __( 'Create a New User' ) . '</a>'; $c_users = get_user_count(); $c_blogs = get_blog_count(); $user_text = sprintf( _n( '%s user', '%s users', $c_users ), number_format_i18n( $c_users ) ); $blog_text = sprintf( _n( '%s site', '%s sites', $c_blogs ), number_format_i18n( $c_blogs ) ); $sentence = sprintf( __( 'You have %1$s and %2$s.' ), $blog_text, $user_text ); if ( $actions ) { echo '<ul class="subsubsub">'; foreach ( $actions as $class => $action ) { $actions[ $class ] = "\t<li class='$class'>$action"; } echo implode( " |</li>\n", $actions ) . "</li>\n"; echo '</ul>'; } ?> <br class="clear" /> <p class="youhave"><?php echo $sentence; ?></p> <?php do_action( 'wpmuadminresult', '' ); ?> <form action="<?php echo network_admin_url('users.php'); ?>" method="get"> <p> <input type="search" name="s" value="" size="30" autocomplete="off" /> <?php submit_button( __( 'Search Users' ), 'button', 'submit', false, array( 'id' => 'submit_users' ) ); ?> </p> </form> <form action="<?php echo network_admin_url('sites.php'); ?>" method="get"> <p> <input type="search" name="s" value="" size="30" autocomplete="off" /> <?php submit_button( __( 'Search Sites' ), 'button', 'submit', false, array( 'id' => 'submit_sites' ) ); ?> </p> </form> <?php do_action( 'mu_rightnow_end' ); do_action( 'mu_activity_box_end' ); } function wp_dashboard_quick_press() { global $post_ID; $drafts = false; if ( 'post' === strtolower( $_SERVER['REQUEST_METHOD'] ) && isset( $_POST['action'] ) && 0 === strpos( $_POST['action'], 'post-quickpress' ) && (int) $_POST['post_ID'] ) { $view = get_permalink( $_POST['post_ID'] ); $edit = esc_url( get_edit_post_link( $_POST['post_ID'] ) ); if ( 'post-quickpress-publish' == $_POST['action'] ) { if ( current_user_can('publish_posts') ) printf( '<div class="updated"><p>' . __( 'Post published. <a href="%s">View post</a> | <a href="%s">Edit post</a>' ) . '</p></div>', esc_url( $view ), $edit ); else printf( '<div class="updated"><p>' . __( 'Post submitted. <a href="%s">Preview post</a> | <a href="%s">Edit post</a>' ) . '</p></div>', esc_url( add_query_arg( 'preview', 1, $view ) ), $edit ); } else { printf( '<div class="updated"><p>' . __( 'Draft saved. <a href="%s">Preview post</a> | <a href="%s">Edit post</a>' ) . '</p></div>', esc_url( add_query_arg( 'preview', 1, $view ) ), $edit ); $drafts_query = new WP_Query( array( 'post_type' => 'post', 'post_status' => 'draft', 'author' => $GLOBALS['current_user']->ID, 'posts_per_page' => 1, 'orderby' => 'modified', 'order' => 'DESC' ) ); if ( $drafts_query->posts ) $drafts =& $drafts_query->posts; } printf('<p class="easy-blogging">' . __('You can also try %s, easy blogging from anywhere on the Web.') . '</p>', '<a href="' . esc_url( admin_url( 'tools.php' ) ) . '">' . __('Press This') . '</a>' ); $_REQUEST = array(); // hack for get_default_post_to_edit() } /* Check if a new auto-draft (= no new post_ID) is needed or if the old can be used */ $last_post_id = (int) get_user_option( 'dashboard_quick_press_last_post_id' ); // Get the last post_ID if ( $last_post_id ) { $post = get_post( $last_post_id ); if ( empty( $post ) || $post->post_status != 'auto-draft' ) { // auto-draft doesn't exists anymore $post = get_default_post_to_edit('post', true); update_user_option( get_current_user_id(), 'dashboard_quick_press_last_post_id', (int) $post->ID ); // Save post_ID } else { $post->post_title = ''; // Remove the auto draft title } } else { $post = get_default_post_to_edit( 'post' , true); $user_id = get_current_user_id(); // Don't create an option if this is a super admin who does not belong to this site. if ( ! ( is_super_admin( $user_id ) && ! in_array( get_current_blog_id(), array_keys( get_blogs_of_user( $user_id ) ) ) ) ) update_user_option( $user_id, 'dashboard_quick_press_last_post_id', (int) $post->ID ); // Save post_ID } $post_ID = (int) $post->ID; $media_settings = array( 'id' => $post->ID, 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ), ); if ( current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' ) ) { $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true ); $media_settings['featuredImageId'] = $featured_image_id ? $featured_image_id : -1; } ?> <form name="post" action="<?php echo esc_url( admin_url( 'post.php' ) ); ?>" method="post" id="quick-press"> <div class="input-text-wrap" id="title-wrap"> <label class="screen-reader-text prompt" for="title" id="title-prompt-text"><?php _e( 'Enter title here' ); ?></label> <input type="text" name="post_title" id="title" autocomplete="off" value="<?php echo esc_attr( $post->post_title ); ?>" /> </div> <?php if ( current_user_can( 'upload_files' ) ) : ?> <div id="wp-content-wrap" class="wp-editor-wrap hide-if-no-js wp-media-buttons"> <?php do_action( 'media_buttons', 'content' ); ?> </div> <?php endif; ?> <div class="textarea-wrap"> <label class="screen-reader-text" for="content"><?php _e( 'Content' ); ?></label> <textarea name="content" id="content" class="mceEditor" rows="3" cols="15"><?php echo esc_textarea( $post->post_content ); ?></textarea> </div> <script type="text/javascript"> edCanvas = document.getElementById('content'); edInsertContent = null; <?php if ( $_POST ) : ?> wp.media.editor.remove('content'); wp.media.view.settings.post = <?php echo json_encode( $media_settings ); // big juicy hack. ?>; wp.media.editor.add('content'); <?php endif; ?> </script> <div class="input-text-wrap" id="tags-input-wrap"> <label class="screen-reader-text prompt" for="tags-input" id="tags-input-prompt-text"><?php _e( 'Tags (separate with commas)' ); ?></label> <input type="text" name="tags_input" id="tags-input" value="<?php echo get_tags_to_edit( $post->ID ); ?>" /> </div> <p class="submit"> <span id="publishing-action"> <input type="submit" name="publish" id="publish" accesskey="p" class="button-primary" value="<?php current_user_can('publish_posts') ? esc_attr_e('Publish') : esc_attr_e('Submit for Review'); ?>" /> <span class="spinner"></span> </span> <input type="hidden" name="action" id="quickpost-action" value="post-quickpress-save" /> <input type="hidden" name="post_ID" value="<?php echo $post_ID; ?>" /> <input type="hidden" name="post_type" value="post" /> <?php wp_nonce_field('add-post'); ?> <?php submit_button( __( 'Save Draft' ), 'button', 'save', false, array( 'id' => 'save-post' ) ); ?> <input type="reset" value="<?php esc_attr_e( 'Reset' ); ?>" class="button" /> <br class="clear" /> </p> </form> <?php if ( $drafts ) wp_dashboard_recent_drafts( $drafts ); } function wp_dashboard_recent_drafts( $drafts = false ) { if ( !$drafts ) { $drafts_query = new WP_Query( array( 'post_type' => 'post', 'post_status' => 'draft', 'author' => $GLOBALS['current_user']->ID, 'posts_per_page' => 5, 'orderby' => 'modified', 'order' => 'DESC' ) ); $drafts =& $drafts_query->posts; } if ( $drafts && is_array( $drafts ) ) { $list = array(); foreach ( $drafts as $draft ) { $url = get_edit_post_link( $draft->ID ); $title = _draft_or_post_title( $draft->ID ); $item = "<h4><a href='$url' title='" . sprintf( __( 'Edit &#8220;%s&#8221;' ), esc_attr( $title ) ) . "'>" . esc_html($title) . "</a> <abbr title='" . get_the_time(__('Y/m/d g:i:s A'), $draft) . "'>" . get_the_time( get_option( 'date_format' ), $draft ) . '</abbr></h4>'; if ( $the_content = preg_split( '#[\r\n\t ]#', strip_tags( $draft->post_content ), 11, PREG_SPLIT_NO_EMPTY ) ) $item .= '<p>' . join( ' ', array_slice( $the_content, 0, 10 ) ) . ( 10 < count( $the_content ) ? '&hellip;' : '' ) . '</p>'; $list[] = $item; } ?> <ul> <li><?php echo join( "</li>\n<li>", $list ); ?></li> </ul> <p class="textright"><a href="edit.php?post_status=draft" ><?php _e('View all'); ?></a></p> <?php } else { _e('There are no drafts at the moment'); } } /** * Display recent comments dashboard widget content. * * @since 2.5.0 */ function wp_dashboard_recent_comments() { global $wpdb; // Select all comment types and filter out spam later for better query performance. $comments = array(); $start = 0; $widgets = get_option( 'dashboard_widget_options' ); $total_items = isset( $widgets['dashboard_recent_comments'] ) && isset( $widgets['dashboard_recent_comments']['items'] ) ? absint( $widgets['dashboard_recent_comments']['items'] ) : 5; $comments_query = array( 'number' => $total_items * 5, 'offset' => 0 ); if ( ! current_user_can( 'edit_posts' ) ) $comments_query['status'] = 'approve'; while ( count( $comments ) < $total_items && $possible = get_comments( $comments_query ) ) { foreach ( $possible as $comment ) { if ( ! current_user_can( 'read_post', $comment->comment_post_ID ) ) continue; $comments[] = $comment; if ( count( $comments ) == $total_items ) break 2; } $comments_query['offset'] += $comments_query['number']; $comments_query['number'] = $total_items * 10; } if ( $comments ) { echo '<div id="the-comment-list" data-wp-lists="list:comment">'; foreach ( $comments as $comment ) _wp_dashboard_recent_comments_row( $comment ); echo '</div>'; if ( current_user_can('edit_posts') ) _get_list_table('WP_Comments_List_Table')->views(); wp_comment_reply( -1, false, 'dashboard', false ); wp_comment_trashnotice(); } else { echo '<p>' . __( 'No comments yet.' ) . '</p>'; } } function _wp_dashboard_recent_comments_row( &$comment, $show_date = true ) { $GLOBALS['comment'] =& $comment; $comment_post_url = get_edit_post_link( $comment->comment_post_ID ); $comment_post_title = strip_tags(get_the_title( $comment->comment_post_ID )); $comment_post_link = "<a href='$comment_post_url'>$comment_post_title</a>"; $comment_link = '<a class="comment-link" href="' . esc_url(get_comment_link()) . '">#</a>'; $actions_string = ''; if ( current_user_can( 'edit_comment', $comment->comment_ID ) ) { // preorder it: Approve | Reply | Edit | Spam | Trash $actions = array( 'approve' => '', 'unapprove' => '', 'reply' => '', 'edit' => '', 'spam' => '', 'trash' => '', 'delete' => '' ); $del_nonce = esc_html( '_wpnonce=' . wp_create_nonce( "delete-comment_$comment->comment_ID" ) ); $approve_nonce = esc_html( '_wpnonce=' . wp_create_nonce( "approve-comment_$comment->comment_ID" ) ); $approve_url = esc_url( "comment.php?action=approvecomment&p=$comment->comment_post_ID&c=$comment->comment_ID&$approve_nonce" ); $unapprove_url = esc_url( "comment.php?action=unapprovecomment&p=$comment->comment_post_ID&c=$comment->comment_ID&$approve_nonce" ); $spam_url = esc_url( "comment.php?action=spamcomment&p=$comment->comment_post_ID&c=$comment->comment_ID&$del_nonce" ); $trash_url = esc_url( "comment.php?action=trashcomment&p=$comment->comment_post_ID&c=$comment->comment_ID&$del_nonce" ); $delete_url = esc_url( "comment.php?action=deletecomment&p=$comment->comment_post_ID&c=$comment->comment_ID&$del_nonce" ); $actions['approve'] = "<a href='$approve_url' data-wp-lists='dim:the-comment-list:comment-$comment->comment_ID:unapproved:e7e7d3:e7e7d3:new=approved' class='vim-a' title='" . esc_attr__( 'Approve this comment' ) . "'>" . __( 'Approve' ) . '</a>'; $actions['unapprove'] = "<a href='$unapprove_url' data-wp-lists='dim:the-comment-list:comment-$comment->comment_ID:unapproved:e7e7d3:e7e7d3:new=unapproved' class='vim-u' title='" . esc_attr__( 'Unapprove this comment' ) . "'>" . __( 'Unapprove' ) . '</a>'; $actions['edit'] = "<a href='comment.php?action=editcomment&amp;c={$comment->comment_ID}' title='" . esc_attr__('Edit comment') . "'>". __('Edit') . '</a>'; $actions['reply'] = '<a onclick="commentReply.open(\''.$comment->comment_ID.'\',\''.$comment->comment_post_ID.'\');return false;" class="vim-r hide-if-no-js" title="'.esc_attr__('Reply to this comment').'" href="#">' . __('Reply') . '</a>'; $actions['spam'] = "<a href='$spam_url' data-wp-lists='delete:the-comment-list:comment-$comment->comment_ID::spam=1' class='vim-s vim-destructive' title='" . esc_attr__( 'Mark this comment as spam' ) . "'>" . /* translators: mark as spam link */ _x( 'Spam', 'verb' ) . '</a>'; if ( !EMPTY_TRASH_DAYS ) $actions['delete'] = "<a href='$delete_url' data-wp-lists='delete:the-comment-list:comment-$comment->comment_ID::trash=1' class='delete vim-d vim-destructive'>" . __('Delete Permanently') . '</a>'; else $actions['trash'] = "<a href='$trash_url' data-wp-lists='delete:the-comment-list:comment-$comment->comment_ID::trash=1' class='delete vim-d vim-destructive' title='" . esc_attr__( 'Move this comment to the trash' ) . "'>" . _x('Trash', 'verb') . '</a>'; $actions = apply_filters( 'comment_row_actions', array_filter($actions), $comment ); $i = 0; foreach ( $actions as $action => $link ) { ++$i; ( ( ('approve' == $action || 'unapprove' == $action) && 2 === $i ) || 1 === $i ) ? $sep = '' : $sep = ' | '; // Reply and quickedit need a hide-if-no-js span if ( 'reply' == $action || 'quickedit' == $action ) $action .= ' hide-if-no-js'; $actions_string .= "<span class='$action'>$sep$link</span>"; } } ?> <div id="comment-<?php echo $comment->comment_ID; ?>" <?php comment_class( array( 'comment-item', wp_get_comment_status($comment->comment_ID) ) ); ?>> <?php if ( !$comment->comment_type || 'comment' == $comment->comment_type ) : ?> <?php echo get_avatar( $comment, 50 ); ?> <div class="dashboard-comment-wrap"> <h4 class="comment-meta"> <?php printf( /* translators: 1: comment author, 2: post link, 3: notification if the comment is pending */__( 'From %1$s on %2$s%3$s' ), '<cite class="comment-author">' . get_comment_author_link() . '</cite>', $comment_post_link.' '.$comment_link, ' <span class="approve">' . __( '[Pending]' ) . '</span>' ); ?> </h4> <?php else : switch ( $comment->comment_type ) : case 'pingback' : $type = __( 'Pingback' ); break; case 'trackback' : $type = __( 'Trackback' ); break; default : $type = ucwords( $comment->comment_type ); endswitch; $type = esc_html( $type ); ?> <div class="dashboard-comment-wrap"> <?php /* translators: %1$s is type of comment, %2$s is link to the post */ ?> <h4 class="comment-meta"><?php printf( _x( '%1$s on %2$s', 'dashboard' ), "<strong>$type</strong>", $comment_post_link." ".$comment_link ); ?></h4> <p class="comment-author"><?php comment_author_link(); ?></p> <?php endif; // comment_type ?> <blockquote><p><?php comment_excerpt(); ?></p></blockquote> <p class="row-actions"><?php echo $actions_string; ?></p> </div> </div> <?php } /** * The recent comments dashboard widget control. * * @since 3.0.0 */ function wp_dashboard_recent_comments_control() { if ( !$widget_options = get_option( 'dashboard_widget_options' ) ) $widget_options = array(); if ( !isset($widget_options['dashboard_recent_comments']) ) $widget_options['dashboard_recent_comments'] = array(); if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset($_POST['widget-recent-comments']) ) { $number = absint( $_POST['widget-recent-comments']['items'] ); $widget_options['dashboard_recent_comments']['items'] = $number; update_option( 'dashboard_widget_options', $widget_options ); } $number = isset( $widget_options['dashboard_recent_comments']['items'] ) ? (int) $widget_options['dashboard_recent_comments']['items'] : ''; echo '<p><label for="comments-number">' . __('Number of comments to show:') . '</label>'; echo '<input id="comments-number" name="widget-recent-comments[items]" type="text" value="' . $number . '" size="3" /></p>'; } function wp_dashboard_incoming_links() { wp_dashboard_cached_rss_widget( 'dashboard_incoming_links', 'wp_dashboard_incoming_links_output' ); } /** * Display incoming links dashboard widget content. * * @since 2.5.0 */ function wp_dashboard_incoming_links_output() { $widgets = get_option( 'dashboard_widget_options' ); @extract( @$widgets['dashboard_incoming_links'], EXTR_SKIP ); $rss = fetch_feed( $url ); if ( is_wp_error($rss) ) { if ( is_admin() || current_user_can('manage_options') ) { echo '<p>'; printf(__('<strong>RSS Error</strong>: %s'), $rss->get_error_message()); echo '</p>'; } return; } if ( !$rss->get_item_quantity() ) { echo '<p>' . __('This dashboard widget queries <a href="http://blogsearch.google.com/">Google Blog Search</a> so that when another blog links to your site it will show up here. It has found no incoming links&hellip; yet. It&#8217;s okay &#8212; there is no rush.') . "</p>\n"; $rss->__destruct(); unset($rss); return; } echo "<ul>\n"; if ( !isset($items) ) $items = 10; foreach ( $rss->get_items(0, $items) as $item ) { $publisher = ''; $site_link = ''; $link = ''; $content = ''; $date = ''; $link = esc_url( strip_tags( $item->get_link() ) ); $author = $item->get_author(); if ( $author ) { $site_link = esc_url( strip_tags( $author->get_link() ) ); if ( !$publisher = esc_html( strip_tags( $author->get_name() ) ) ) $publisher = __( 'Somebody' ); } else { $publisher = __( 'Somebody' ); } if ( $site_link ) $publisher = "<a href='$site_link'>$publisher</a>"; else $publisher = "<strong>$publisher</strong>"; $content = $item->get_content(); $content = wp_html_excerpt($content, 50) . ' ...'; if ( $link ) /* translators: incoming links feed, %1$s is other person, %3$s is content */ $text = __( '%1$s linked here <a href="%2$s">saying</a>, "%3$s"' ); else /* translators: incoming links feed, %1$s is other person, %3$s is content */ $text = __( '%1$s linked here saying, "%3$s"' ); if ( !empty( $show_date ) ) { if ( $link ) /* translators: incoming links feed, %1$s is other person, %3$s is content, %4$s is the date */ $text = __( '%1$s linked here <a href="%2$s">saying</a>, "%3$s" on %4$s' ); else /* translators: incoming links feed, %1$s is other person, %3$s is content, %4$s is the date */ $text = __( '%1$s linked here saying, "%3$s" on %4$s' ); $date = esc_html( strip_tags( $item->get_date() ) ); $date = strtotime( $date ); $date = gmdate( get_option( 'date_format' ), $date ); } echo "\t<li>" . sprintf( $text, $publisher, $link, $content, $date ) . "</li>\n"; } echo "</ul>\n"; $rss->__destruct(); unset($rss); } function wp_dashboard_incoming_links_control() { wp_dashboard_rss_control( 'dashboard_incoming_links', array( 'title' => false, 'show_summary' => false, 'show_author' => false ) ); } function wp_dashboard_primary() { wp_dashboard_cached_rss_widget( 'dashboard_primary', 'wp_dashboard_rss_output' ); } function wp_dashboard_primary_control() { wp_dashboard_rss_control( 'dashboard_primary' ); } /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @param string $widget_id */ function wp_dashboard_rss_output( $widget_id ) { $widgets = get_option( 'dashboard_widget_options' ); echo '<div class="rss-widget">'; wp_widget_rss_output( $widgets[$widget_id] ); echo "</div>"; } function wp_dashboard_secondary() { wp_dashboard_cached_rss_widget( 'dashboard_secondary', 'wp_dashboard_secondary_output' ); } function wp_dashboard_secondary_control() { wp_dashboard_rss_control( 'dashboard_secondary' ); } /** * Display secondary dashboard RSS widget feed. * * @since 2.5.0 * * @return unknown */ function wp_dashboard_secondary_output() { $widgets = get_option( 'dashboard_widget_options' ); @extract( @$widgets['dashboard_secondary'], EXTR_SKIP ); $rss = @fetch_feed( $url ); if ( is_wp_error($rss) ) { if ( is_admin() || current_user_can('manage_options') ) { echo '<div class="rss-widget"><p>'; printf(__('<strong>RSS Error</strong>: %s'), $rss->get_error_message()); echo '</p></div>'; } } elseif ( !$rss->get_item_quantity() ) { $rss->__destruct(); unset($rss); return false; } else { echo '<div class="rss-widget">'; wp_widget_rss_output( $rss, $widgets['dashboard_secondary'] ); echo '</div>'; $rss->__destruct(); unset($rss); } } function wp_dashboard_plugins() { wp_dashboard_cached_rss_widget( 'dashboard_plugins', 'wp_dashboard_plugins_output', array( 'http://wordpress.org/extend/plugins/rss/browse/popular/', 'http://wordpress.org/extend/plugins/rss/browse/new/' ) ); } /** * Display plugins most popular, newest plugins, and recently updated widget text. * * @since 2.5.0 */ function wp_dashboard_plugins_output() { $popular = fetch_feed( 'http://wordpress.org/extend/plugins/rss/browse/popular/' ); $new = fetch_feed( 'http://wordpress.org/extend/plugins/rss/browse/new/' ); if ( false === $plugin_slugs = get_transient( 'plugin_slugs' ) ) { $plugin_slugs = array_keys( get_plugins() ); set_transient( 'plugin_slugs', $plugin_slugs, DAY_IN_SECONDS ); } foreach ( array( 'popular' => __('Most Popular'), 'new' => __('Newest Plugins') ) as $feed => $label ) { if ( is_wp_error($$feed) || !$$feed->get_item_quantity() ) continue; $items = $$feed->get_items(0, 5); // Pick a random, non-installed plugin while ( true ) { // Abort this foreach loop iteration if there's no plugins left of this type if ( 0 == count($items) ) continue 2; $item_key = array_rand($items); $item = $items[$item_key]; list($link, $frag) = explode( '#', $item->get_link() ); $link = esc_url($link); if ( preg_match( '|/([^/]+?)/?$|', $link, $matches ) ) $slug = $matches[1]; else { unset( $items[$item_key] ); continue; } // Is this random plugin's slug already installed? If so, try again. reset( $plugin_slugs ); foreach ( $plugin_slugs as $plugin_slug ) { if ( $slug == substr( $plugin_slug, 0, strlen( $slug ) ) ) { unset( $items[$item_key] ); continue 2; } } // If we get to this point, then the random plugin isn't installed and we can stop the while(). break; } // Eliminate some common badly formed plugin descriptions while ( ( null !== $item_key = array_rand($items) ) && false !== strpos( $items[$item_key]->get_description(), 'Plugin Name:' ) ) unset($items[$item_key]); if ( !isset($items[$item_key]) ) continue; $title = esc_html( $item->get_title() ); $description = esc_html( strip_tags(@html_entity_decode($item->get_description(), ENT_QUOTES, get_option('blog_charset'))) ); $ilink = wp_nonce_url('plugin-install.php?tab=plugin-information&plugin=' . $slug, 'install-plugin_' . $slug) . '&amp;TB_iframe=true&amp;width=600&amp;height=800'; echo "<h4>$label</h4>\n"; echo "<h5><a href='$link'>$title</a></h5>&nbsp;<span>(<a href='$ilink' class='thickbox' title='$title'>" . __( 'Install' ) . "</a>)</span>\n"; echo "<p>$description</p>\n"; $$feed->__destruct(); unset($$feed); } } /** * Checks to see if all of the feed url in $check_urls are cached. * * If $check_urls is empty, look for the rss feed url found in the dashboard * widget options of $widget_id. If cached, call $callback, a function that * echoes out output for this widget. If not cache, echo a "Loading..." stub * which is later replaced by AJAX call (see top of /wp-admin/index.php) * * @since 2.5.0 * * @param string $widget_id * @param callback $callback * @param array $check_urls RSS feeds * @return bool False on failure. True on success. */ function wp_dashboard_cached_rss_widget( $widget_id, $callback, $check_urls = array() ) { $loading = '<p class="widget-loading hide-if-no-js">' . __( 'Loading&#8230;' ) . '</p><p class="hide-if-js">' . __( 'This widget requires JavaScript.' ) . '</p>'; $doing_ajax = ( defined('DOING_AJAX') && DOING_AJAX ); if ( empty($check_urls) ) { $widgets = get_option( 'dashboard_widget_options' ); if ( empty($widgets[$widget_id]['url']) && ! $doing_ajax ) { echo $loading; return false; } $check_urls = array( $widgets[$widget_id]['url'] ); } $cache_key = 'dash_' . md5( $widget_id ); if ( false !== ( $output = get_transient( $cache_key ) ) ) { echo $output; return true; } if ( ! $doing_ajax ) { echo $loading; return false; } if ( $callback && is_callable( $callback ) ) { $args = array_slice( func_get_args(), 2 ); array_unshift( $args, $widget_id ); ob_start(); call_user_func_array( $callback, $args ); set_transient( $cache_key, ob_get_flush(), 12 * HOUR_IN_SECONDS ); // Default lifetime in cache of 12 hours (same as the feeds) } return true; } /* Dashboard Widgets Controls */ // Calls widget_control callback /** * Calls widget control callback. * * @since 2.5.0 * * @param int $widget_control_id Registered Widget ID. */ function wp_dashboard_trigger_widget_control( $widget_control_id = false ) { global $wp_dashboard_control_callbacks; if ( is_scalar($widget_control_id) && $widget_control_id && isset($wp_dashboard_control_callbacks[$widget_control_id]) && is_callable($wp_dashboard_control_callbacks[$widget_control_id]) ) { call_user_func( $wp_dashboard_control_callbacks[$widget_control_id], '', array( 'id' => $widget_control_id, 'callback' => $wp_dashboard_control_callbacks[$widget_control_id] ) ); } } /** * The RSS dashboard widget control. * * Sets up $args to be used as input to wp_widget_rss_form(). Handles POST data * from RSS-type widgets. * * @since 2.5.0 * * @param string $widget_id * @param array $form_inputs */ function wp_dashboard_rss_control( $widget_id, $form_inputs = array() ) { if ( !$widget_options = get_option( 'dashboard_widget_options' ) ) $widget_options = array(); if ( !isset($widget_options[$widget_id]) ) $widget_options[$widget_id] = array(); $number = 1; // Hack to use wp_widget_rss_form() $widget_options[$widget_id]['number'] = $number; if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset($_POST['widget-rss'][$number]) ) { $_POST['widget-rss'][$number] = stripslashes_deep( $_POST['widget-rss'][$number] ); $widget_options[$widget_id] = wp_widget_rss_process( $_POST['widget-rss'][$number] ); // title is optional. If black, fill it if possible if ( !$widget_options[$widget_id]['title'] && isset($_POST['widget-rss'][$number]['title']) ) { $rss = fetch_feed($widget_options[$widget_id]['url']); if ( is_wp_error($rss) ) { $widget_options[$widget_id]['title'] = htmlentities(__('Unknown Feed')); } else { $widget_options[$widget_id]['title'] = htmlentities(strip_tags($rss->get_title())); $rss->__destruct(); unset($rss); } } update_option( 'dashboard_widget_options', $widget_options ); $cache_key = 'dash_' . md5( $widget_id ); delete_transient( $cache_key ); } wp_widget_rss_form( $widget_options[$widget_id], $form_inputs ); } // Display File upload quota on dashboard function wp_dashboard_quota() { if ( !is_multisite() || !current_user_can('upload_files') || get_site_option( 'upload_space_check_disabled' ) ) return true; $quota = get_space_allowed(); $used = get_space_used(); if ( $used > $quota ) $percentused = '100'; else $percentused = ( $used / $quota ) * 100; $used_color = ( $percentused >= 70 ) ? ' spam' : ''; $used = round( $used, 2 ); $percentused = number_format( $percentused ); ?> <p class="sub musub"><?php _e( 'Storage Space' ); ?></p> <div class="table table_content musubtable"> <table> <tr class="first"> <td class="first b b-posts"><?php printf( __( '<a href="%1$s" title="Manage Uploads" class="musublink">%2$sMB</a>' ), esc_url( admin_url( 'upload.php' ) ), number_format_i18n( $quota ) ); ?></td> <td class="t posts"><?php _e( 'Space Allowed' ); ?></td> </tr> </table> </div> <div class="table table_discussion musubtable"> <table> <tr class="first"> <td class="b b-comments"><?php printf( __( '<a href="%1$s" title="Manage Uploads" class="musublink">%2$sMB (%3$s%%)</a>' ), esc_url( admin_url( 'upload.php' ) ), number_format_i18n( $used, 2 ), $percentused ); ?></td> <td class="last t comments<?php echo $used_color;?>"><?php _e( 'Space Used' );?></td> </tr> </table> </div> <br class="clear" /> <?php } add_action( 'activity_box_end', 'wp_dashboard_quota' ); // Display Browser Nag Meta Box function wp_dashboard_browser_nag() { $notice = ''; $response = wp_check_browser_version(); if ( $response ) { if ( $response['insecure'] ) { $msg = sprintf( __( "It looks like you're using an insecure version of <a href='%s'>%s</a>. Using an outdated browser makes your computer unsafe. For the best WordPress experience, please update your browser." ), esc_attr( $response['update_url'] ), esc_html( $response['name'] ) ); } else { $msg = sprintf( __( "It looks like you're using an old version of <a href='%s'>%s</a>. For the best WordPress experience, please update your browser." ), esc_attr( $response['update_url'] ), esc_html( $response['name'] ) ); } $browser_nag_class = ''; if ( !empty( $response['img_src'] ) ) { $img_src = ( is_ssl() && ! empty( $response['img_src_ssl'] ) )? $response['img_src_ssl'] : $response['img_src']; $notice .= '<div class="alignright browser-icon"><a href="' . esc_attr($response['update_url']) . '"><img src="' . esc_attr( $img_src ) . '" alt="" /></a></div>'; $browser_nag_class = ' has-browser-icon'; } $notice .= "<p class='browser-update-nag{$browser_nag_class}'>{$msg}</p>"; $browsehappy = 'http://browsehappy.com/'; $locale = get_locale(); if ( 'en_US' !== $locale ) $browsehappy = add_query_arg( 'locale', $locale, $browsehappy ); $notice .= '<p>' . sprintf( __( '<a href="%1$s" class="update-browser-link">Update %2$s</a> or learn how to <a href="%3$s" class="browse-happy-link">browse happy</a>' ), esc_attr( $response['update_url'] ), esc_html( $response['name'] ), esc_url( $browsehappy ) ) . '</p>'; $notice .= '<p class="hide-if-no-js"><a href="" class="dismiss">' . __( 'Dismiss' ) . '</a></p>'; $notice .= '<div class="clear"></div>'; } echo apply_filters( 'browse-happy-notice', $notice, $response ); } function dashboard_browser_nag_class( $classes ) { $response = wp_check_browser_version(); if ( $response && $response['insecure'] ) $classes[] = 'browser-insecure'; return $classes; } /** * Check if the user needs a browser update * * @since 3.2.0 * * @return array|bool False on failure, array of browser data on success. */ function wp_check_browser_version() { if ( empty( $_SERVER['HTTP_USER_AGENT'] ) ) return false; $key = md5( $_SERVER['HTTP_USER_AGENT'] ); if ( false === ($response = get_site_transient('browser_' . $key) ) ) { global $wp_version; $options = array( 'body' => array( 'useragent' => $_SERVER['HTTP_USER_AGENT'] ), 'user-agent' => 'WordPress/' . $wp_version . '; ' . home_url() ); $response = wp_remote_post( 'http://api.wordpress.org/core/browse-happy/1.0/', $options ); if ( is_wp_error( $response ) || 200 != wp_remote_retrieve_response_code( $response ) ) return false; /** * Response should be an array with: * 'name' - string - A user friendly browser name * 'version' - string - The most recent version of the browser * 'current_version' - string - The version of the browser the user is using * 'upgrade' - boolean - Whether the browser needs an upgrade * 'insecure' - boolean - Whether the browser is deemed insecure * 'upgrade_url' - string - The url to visit to upgrade * 'img_src' - string - An image representing the browser * 'img_src_ssl' - string - An image (over SSL) representing the browser */ $response = maybe_unserialize( wp_remote_retrieve_body( $response ) ); if ( ! is_array( $response ) ) return false; set_site_transient( 'browser_' . $key, $response, WEEK_IN_SECONDS ); } return $response; } /** * Empty function usable by plugins to output empty dashboard widget (to be populated later by JS). */ function wp_dashboard_empty() {} /** * Displays a welcome panel to introduce users to WordPress. * * @since 3.3.0 */ function wp_welcome_panel() { ?> <div class="welcome-panel-content"> <h3><?php _e( 'Welcome to WordPress!' ); ?></h3> <p class="about-description"><?php _e( 'We&#8217;ve assembled some links to get you started:' ); ?></p> <div class="welcome-panel-column-container"> <div class="welcome-panel-column"> <h4><?php _e( 'Get Started' ); ?></h4> <a class="button button-primary button-hero load-customize hide-if-no-customize" href="<?php echo wp_customize_url(); ?>"><?php _e( 'Customize Your Site' ); ?></a> <a class="button button-primary button-hero hide-if-customize" href="<?php echo admin_url( 'themes.php' ); ?>"><?php _e( 'Customize Your Site' ); ?></a> <?php if ( current_user_can( 'install_themes' ) || ( current_user_can( 'switch_themes' ) && count( wp_get_themes( array( 'allowed' => true ) ) ) > 1 ) ) : ?> <p class="hide-if-no-customize"><?php printf( __( 'or, <a href="%s">change your theme completely</a>' ), admin_url( 'themes.php' ) ); ?></p> <?php endif; ?> </div> <div class="welcome-panel-column"> <h4><?php _e( 'Next Steps' ); ?></h4> <ul> <?php if ( 'page' == get_option( 'show_on_front' ) && ! get_option( 'page_for_posts' ) ) : ?> <li><?php printf( '<a href="%s" class="welcome-icon welcome-edit-page">' . __( 'Edit your front page' ) . '</a>', get_edit_post_link( get_option( 'page_on_front' ) ) ); ?></li> <li><?php printf( '<a href="%s" class="welcome-icon welcome-add-page">' . __( 'Add additional pages' ) . '</a>', admin_url( 'post-new.php?post_type=page' ) ); ?></li> <?php elseif ( 'page' == get_option( 'show_on_front' ) ) : ?> <li><?php printf( '<a href="%s" class="welcome-icon welcome-edit-page">' . __( 'Edit your front page' ) . '</a>', get_edit_post_link( get_option( 'page_on_front' ) ) ); ?></li> <li><?php printf( '<a href="%s" class="welcome-icon welcome-add-page">' . __( 'Add additional pages' ) . '</a>', admin_url( 'post-new.php?post_type=page' ) ); ?></li> <li><?php printf( '<a href="%s" class="welcome-icon welcome-write-blog">' . __( 'Add a blog post' ) . '</a>', admin_url( 'post-new.php' ) ); ?></li> <?php else : ?> <li><?php printf( '<a href="%s" class="welcome-icon welcome-write-blog">' . __( 'Write your first blog post' ) . '</a>', admin_url( 'post-new.php' ) ); ?></li> <li><?php printf( '<a href="%s" class="welcome-icon welcome-add-page">' . __( 'Add an About page' ) . '</a>', admin_url( 'post-new.php?post_type=page' ) ); ?></li> <?php endif; ?> <li><?php printf( '<a href="%s" class="welcome-icon welcome-view-site">' . __( 'View your site' ) . '</a>', home_url( '/' ) ); ?></li> </ul> </div> <div class="welcome-panel-column welcome-panel-last"> <h4><?php _e( 'More Actions' ); ?></h4> <ul> <li><?php printf( '<div class="welcome-icon welcome-widgets-menus">' . __( 'Manage <a href="%1$s">widgets</a> or <a href="%2$s">menus</a>' ) . '</div>', admin_url( 'widgets.php' ), admin_url( 'nav-menus.php' ) ); ?></li> <li><?php printf( '<a href="%s" class="welcome-icon welcome-comments">' . __( 'Turn comments on or off' ) . '</a>', admin_url( 'options-discussion.php' ) ); ?></li> <li><?php printf( '<a href="%s" class="welcome-icon welcome-learn-more">' . __( 'Learn more about getting started' ) . '</a>', __( 'http://codex.wordpress.org/First_Steps_With_WordPress' ) ); ?></li> </ul> </div> </div> </div> <?php }
zyblog
trunk/zyblog/wp-admin/includes/dashboard.php
PHP
asf20
53,467
<?php /** * Base WordPress Filesystem. * * @package WordPress * @subpackage Filesystem */ /** * Base WordPress Filesystem class for which Filesystem implementations extend * * @since 2.5 */ class WP_Filesystem_Base { /** * Whether to display debug data for the connection. * * @since 2.5 * @access public * @var bool */ var $verbose = false; /** * Cached list of local filepaths to mapped remote filepaths. * * @since 2.7 * @access private * @var array */ var $cache = array(); /** * The Access method of the current connection, Set automatically. * * @since 2.5 * @access public * @var string */ var $method = ''; /** * Returns the path on the remote filesystem of ABSPATH * * @since 2.7 * @access public * @return string The location of the remote path. */ function abspath() { $folder = $this->find_folder(ABSPATH); //Perhaps the FTP folder is rooted at the WordPress install, Check for wp-includes folder in root, Could have some false positives, but rare. if ( ! $folder && $this->is_dir('/wp-includes') ) $folder = '/'; return $folder; } /** * Returns the path on the remote filesystem of WP_CONTENT_DIR * * @since 2.7 * @access public * @return string The location of the remote path. */ function wp_content_dir() { return $this->find_folder(WP_CONTENT_DIR); } /** * Returns the path on the remote filesystem of WP_PLUGIN_DIR * * @since 2.7 * @access public * * @return string The location of the remote path. */ function wp_plugins_dir() { return $this->find_folder(WP_PLUGIN_DIR); } /** * Returns the path on the remote filesystem of the Themes Directory * * @since 2.7 * @access public * * @return string The location of the remote path. */ function wp_themes_dir() { return $this->wp_content_dir() . 'themes/'; } /** * Returns the path on the remote filesystem of WP_LANG_DIR * * @since 3.2.0 * @access public * * @return string The location of the remote path. */ function wp_lang_dir() { return $this->find_folder(WP_LANG_DIR); } /** * Locates a folder on the remote filesystem. * * Deprecated; use WP_Filesystem::abspath() or WP_Filesystem::wp_*_dir() methods instead. * * @since 2.5 * @deprecated 2.7 * @access public * * @param string $base The folder to start searching from * @param bool $echo True to display debug information * @return string The location of the remote path. */ function find_base_dir($base = '.', $echo = false) { _deprecated_function(__FUNCTION__, '2.7', 'WP_Filesystem::abspath() or WP_Filesystem::wp_*_dir()' ); $this->verbose = $echo; return $this->abspath(); } /** * Locates a folder on the remote filesystem. * * Deprecated; use WP_Filesystem::abspath() or WP_Filesystem::wp_*_dir() methods instead. * * @since 2.5 * @deprecated 2.7 * @access public * * @param string $base The folder to start searching from * @param bool $echo True to display debug information * @return string The location of the remote path. */ function get_base_dir($base = '.', $echo = false) { _deprecated_function(__FUNCTION__, '2.7', 'WP_Filesystem::abspath() or WP_Filesystem::wp_*_dir()' ); $this->verbose = $echo; return $this->abspath(); } /** * Locates a folder on the remote filesystem. * * Assumes that on Windows systems, Stripping off the Drive letter is OK * Sanitizes \\ to / in windows filepaths. * * @since 2.7 * @access public * * @param string $folder the folder to locate * @return string The location of the remote path. */ function find_folder($folder) { if ( strpos($this->method, 'ftp') !== false ) { $constant_overrides = array( 'FTP_BASE' => ABSPATH, 'FTP_CONTENT_DIR' => WP_CONTENT_DIR, 'FTP_PLUGIN_DIR' => WP_PLUGIN_DIR, 'FTP_LANG_DIR' => WP_LANG_DIR ); foreach ( $constant_overrides as $constant => $dir ) if ( defined($constant) && $folder === $dir ) return trailingslashit(constant($constant)); } elseif ( 'direct' == $this->method ) { $folder = str_replace('\\', '/', $folder); //Windows path sanitisation return trailingslashit($folder); } $folder = preg_replace('|^([a-z]{1}):|i', '', $folder); //Strip out windows drive letter if it's there. $folder = str_replace('\\', '/', $folder); //Windows path sanitisation if ( isset($this->cache[ $folder ] ) ) return $this->cache[ $folder ]; if ( $this->exists($folder) ) { //Folder exists at that absolute path. $folder = trailingslashit($folder); $this->cache[ $folder ] = $folder; return $folder; } if ( $return = $this->search_for_folder($folder) ) $this->cache[ $folder ] = $return; return $return; } /** * Locates a folder on the remote filesystem. * * Expects Windows sanitized path * * @since 2.7 * @access private * * @param string $folder the folder to locate * @param string $base the folder to start searching from * @param bool $loop if the function has recursed, Internal use only * @return string The location of the remote path. */ function search_for_folder($folder, $base = '.', $loop = false ) { if ( empty( $base ) || '.' == $base ) $base = trailingslashit($this->cwd()); $folder = untrailingslashit($folder); $folder_parts = explode('/', $folder); $last_index = array_pop( array_keys( $folder_parts ) ); $last_path = $folder_parts[ $last_index ]; $files = $this->dirlist( $base ); foreach ( $folder_parts as $index => $key ) { if ( $index == $last_index ) continue; //We want this to be caught by the next code block. //Working from /home/ to /user/ to /wordpress/ see if that file exists within the current folder, // If its found, change into it and follow through looking for it. // If it cant find WordPress down that route, it'll continue onto the next folder level, and see if that matches, and so on. // If it reaches the end, and still cant find it, it'll return false for the entire function. if ( isset($files[ $key ]) ){ //Lets try that folder: $newdir = trailingslashit(path_join($base, $key)); if ( $this->verbose ) printf( __('Changing to %s') . '<br/>', $newdir ); // only search for the remaining path tokens in the directory, not the full path again $newfolder = implode( '/', array_slice( $folder_parts, $index + 1 ) ); if ( $ret = $this->search_for_folder( $newfolder, $newdir, $loop) ) return $ret; } } //Only check this as a last resort, to prevent locating the incorrect install. All above procedures will fail quickly if this is the right branch to take. if (isset( $files[ $last_path ] ) ) { if ( $this->verbose ) printf( __('Found %s') . '<br/>', $base . $last_path ); return trailingslashit($base . $last_path); } if ( $loop ) return false; //Prevent this function from looping again. //As an extra last resort, Change back to / if the folder wasn't found. This comes into effect when the CWD is /home/user/ but WP is at /var/www/.... mainly dedicated setups. return $this->search_for_folder($folder, '/', true); } /** * Returns the *nix style file permissions for a file * * From the PHP documentation page for fileperms() * * @link http://docs.php.net/fileperms * @since 2.5 * @access public * * @param string $file string filename * @return int octal representation of permissions */ function gethchmod($file){ $perms = $this->getchmod($file); if (($perms & 0xC000) == 0xC000) // Socket $info = 's'; elseif (($perms & 0xA000) == 0xA000) // Symbolic Link $info = 'l'; elseif (($perms & 0x8000) == 0x8000) // Regular $info = '-'; elseif (($perms & 0x6000) == 0x6000) // Block special $info = 'b'; elseif (($perms & 0x4000) == 0x4000) // Directory $info = 'd'; elseif (($perms & 0x2000) == 0x2000) // Character special $info = 'c'; elseif (($perms & 0x1000) == 0x1000) // FIFO pipe $info = 'p'; else // Unknown $info = 'u'; // Owner $info .= (($perms & 0x0100) ? 'r' : '-'); $info .= (($perms & 0x0080) ? 'w' : '-'); $info .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-')); // Group $info .= (($perms & 0x0020) ? 'r' : '-'); $info .= (($perms & 0x0010) ? 'w' : '-'); $info .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-')); // World $info .= (($perms & 0x0004) ? 'r' : '-'); $info .= (($perms & 0x0002) ? 'w' : '-'); $info .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-')); return $info; } /** * Converts *nix style file permissions to a octal number. * * Converts '-rw-r--r--' to 0644 * From "info at rvgate dot nl"'s comment on the PHP documentation for chmod() * * @link http://docs.php.net/manual/en/function.chmod.php#49614 * @since 2.5 * @access public * * @param string $mode string *nix style file permission * @return int octal representation */ function getnumchmodfromh($mode) { $realmode = ''; $legal = array('', 'w', 'r', 'x', '-'); $attarray = preg_split('//', $mode); for ($i=0; $i < count($attarray); $i++) if ($key = array_search($attarray[$i], $legal)) $realmode .= $legal[$key]; $mode = str_pad($realmode, 10, '-', STR_PAD_LEFT); $trans = array('-'=>'0', 'r'=>'4', 'w'=>'2', 'x'=>'1'); $mode = strtr($mode,$trans); $newmode = $mode[0]; $newmode .= $mode[1] + $mode[2] + $mode[3]; $newmode .= $mode[4] + $mode[5] + $mode[6]; $newmode .= $mode[7] + $mode[8] + $mode[9]; return $newmode; } /** * Determines if the string provided contains binary characters. * * @since 2.7 * @access private * * @param string $text String to test against * @return bool true if string is binary, false otherwise */ function is_binary( $text ) { return (bool) preg_match('|[^\x20-\x7E]|', $text); //chr(32)..chr(127) } }
zyblog
trunk/zyblog/wp-admin/includes/class-wp-filesystem-base.php
PHP
asf20
9,948
<?php /** * Build Administration Menu. * * @package WordPress * @subpackage Administration */ if ( is_network_admin() ) do_action('_network_admin_menu'); elseif ( is_user_admin() ) do_action('_user_admin_menu'); else do_action('_admin_menu'); // Create list of page plugin hook names. foreach ($menu as $menu_page) { if ( false !== $pos = strpos($menu_page[2], '?') ) { // Handle post_type=post|page|foo pages. $hook_name = substr($menu_page[2], 0, $pos); $hook_args = substr($menu_page[2], $pos + 1); wp_parse_str($hook_args, $hook_args); // Set the hook name to be the post type. if ( isset($hook_args['post_type']) ) $hook_name = $hook_args['post_type']; else $hook_name = basename($hook_name, '.php'); unset($hook_args); } else { $hook_name = basename($menu_page[2], '.php'); } $hook_name = sanitize_title($hook_name); if ( isset($compat[$hook_name]) ) $hook_name = $compat[$hook_name]; elseif ( !$hook_name ) continue; $admin_page_hooks[$menu_page[2]] = $hook_name; } unset($menu_page, $compat); $_wp_submenu_nopriv = array(); $_wp_menu_nopriv = array(); // Loop over submenus and remove pages for which the user does not have privs. foreach ( array( 'submenu' ) as $sub_loop ) { foreach ($$sub_loop as $parent => $sub) { foreach ($sub as $index => $data) { if ( ! current_user_can($data[1]) ) { unset(${$sub_loop}[$parent][$index]); $_wp_submenu_nopriv[$parent][$data[2]] = true; } } unset($index, $data); if ( empty(${$sub_loop}[$parent]) ) unset(${$sub_loop}[$parent]); } unset($sub, $parent); } unset($sub_loop); // Loop over the top-level menu. // Menus for which the original parent is not accessible due to lack of privs will have the next // submenu in line be assigned as the new menu parent. foreach ( $menu as $id => $data ) { if ( empty($submenu[$data[2]]) ) continue; $subs = $submenu[$data[2]]; $first_sub = array_shift($subs); $old_parent = $data[2]; $new_parent = $first_sub[2]; // If the first submenu is not the same as the assigned parent, // make the first submenu the new parent. if ( $new_parent != $old_parent ) { $_wp_real_parent_file[$old_parent] = $new_parent; $menu[$id][2] = $new_parent; foreach ($submenu[$old_parent] as $index => $data) { $submenu[$new_parent][$index] = $submenu[$old_parent][$index]; unset($submenu[$old_parent][$index]); } unset($submenu[$old_parent], $index); if ( isset($_wp_submenu_nopriv[$old_parent]) ) $_wp_submenu_nopriv[$new_parent] = $_wp_submenu_nopriv[$old_parent]; } } unset($id, $data, $subs, $first_sub, $old_parent, $new_parent); if ( is_network_admin() ) do_action('network_admin_menu', ''); elseif ( is_user_admin() ) do_action('user_admin_menu', ''); else do_action('admin_menu', ''); // Remove menus that have no accessible submenus and require privs that the user does not have. // Run re-parent loop again. foreach ( $menu as $id => $data ) { if ( ! current_user_can($data[1]) ) $_wp_menu_nopriv[$data[2]] = true; // If there is only one submenu and it is has same destination as the parent, // remove the submenu. if ( ! empty( $submenu[$data[2]] ) && 1 == count ( $submenu[$data[2]] ) ) { $subs = $submenu[$data[2]]; $first_sub = array_shift($subs); if ( $data[2] == $first_sub[2] ) unset( $submenu[$data[2]] ); } // If submenu is empty... if ( empty($submenu[$data[2]]) ) { // And user doesn't have privs, remove menu. if ( isset( $_wp_menu_nopriv[$data[2]] ) ) { unset($menu[$id]); } } } unset($id, $data, $subs, $first_sub); // Remove any duplicated separators $separator_found = false; foreach ( $menu as $id => $data ) { if ( 0 == strcmp('wp-menu-separator', $data[4] ) ) { if (false == $separator_found) { $separator_found = true; } else { unset($menu[$id]); $separator_found = false; } } else { $separator_found = false; } } unset($id, $data); function add_cssclass($add, $class) { $class = empty($class) ? $add : $class .= ' ' . $add; return $class; } function add_menu_classes($menu) { $first = $lastorder = false; $i = 0; $mc = count($menu); foreach ( $menu as $order => $top ) { $i++; if ( 0 == $order ) { // dashboard is always shown/single $menu[0][4] = add_cssclass('menu-top-first', $top[4]); $lastorder = 0; continue; } if ( 0 === strpos($top[2], 'separator') ) { // if separator $first = true; $c = $menu[$lastorder][4]; $menu[$lastorder][4] = add_cssclass('menu-top-last', $c); continue; } if ( $first ) { $c = $menu[$order][4]; $menu[$order][4] = add_cssclass('menu-top-first', $c); $first = false; } if ( $mc == $i ) { // last item $c = $menu[$order][4]; $menu[$order][4] = add_cssclass('menu-top-last', $c); } $lastorder = $order; } return apply_filters( 'add_menu_classes', $menu ); } uksort($menu, "strnatcasecmp"); // make it all pretty if ( apply_filters('custom_menu_order', false) ) { $menu_order = array(); foreach ( $menu as $menu_item ) { $menu_order[] = $menu_item[2]; } unset($menu_item); $default_menu_order = $menu_order; $menu_order = apply_filters('menu_order', $menu_order); $menu_order = array_flip($menu_order); $default_menu_order = array_flip($default_menu_order); function sort_menu($a, $b) { global $menu_order, $default_menu_order; $a = $a[2]; $b = $b[2]; if ( isset($menu_order[$a]) && !isset($menu_order[$b]) ) { return -1; } elseif ( !isset($menu_order[$a]) && isset($menu_order[$b]) ) { return 1; } elseif ( isset($menu_order[$a]) && isset($menu_order[$b]) ) { if ( $menu_order[$a] == $menu_order[$b] ) return 0; return ($menu_order[$a] < $menu_order[$b]) ? -1 : 1; } else { return ($default_menu_order[$a] <= $default_menu_order[$b]) ? -1 : 1; } } usort($menu, 'sort_menu'); unset($menu_order, $default_menu_order); } // Remove the last menu item if it is a separator. $last_menu_key = array_keys( $menu ); $last_menu_key = array_pop( $last_menu_key ); if ( !empty( $menu ) && 'wp-menu-separator' == $menu[ $last_menu_key ][ 4 ] ) unset( $menu[ $last_menu_key ] ); unset( $last_menu_key ); if ( !user_can_access_admin_page() ) { do_action('admin_page_access_denied'); wp_die( __('You do not have sufficient permissions to access this page.') ); } $menu = add_menu_classes($menu);
zyblog
trunk/zyblog/wp-admin/includes/menu.php
PHP
asf20
6,307
<?php /** * File contains all the administration image manipulation functions. * * @package WordPress * @subpackage Administration */ /** * Crop an Image to a given size. * * @since 2.1.0 * * @param string|int $src The source file or Attachment ID. * @param int $src_x The start x position to crop from. * @param int $src_y The start y position to crop from. * @param int $src_w The width to crop. * @param int $src_h The height to crop. * @param int $dst_w The destination width. * @param int $dst_h The destination height. * @param int $src_abs Optional. If the source crop points are absolute. * @param string $dst_file Optional. The destination file to write to. * @return string|WP_Error|false New filepath on success, WP_Error or false on failure. */ function wp_crop_image( $src, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false ) { $src_file = $src; if ( is_numeric( $src ) ) { // Handle int as attachment ID $src_file = get_attached_file( $src ); if ( ! file_exists( $src_file ) ) { // If the file doesn't exist, attempt a url fopen on the src link. // This can occur with certain file replication plugins. $src = _load_image_to_edit_path( $src, 'full' ); } else { $src = $src_file; } } $editor = wp_get_image_editor( $src ); if ( is_wp_error( $editor ) ) return $editor; $src = $editor->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs ); if ( is_wp_error( $src ) ) return $src; if ( ! $dst_file ) $dst_file = str_replace( basename( $src_file ), 'cropped-' . basename( $src_file ), $src_file ); // The directory containing the original file may no longer exist when // using a replication plugin. wp_mkdir_p( dirname( $dst_file ) ); $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) ); $result = $editor->save( $dst_file ); return $dst_file; } /** * Generate post thumbnail attachment meta data. * * @since 2.1.0 * * @param int $attachment_id Attachment Id to process. * @param string $file Filepath of the Attached image. * @return mixed Metadata for attachment. */ function wp_generate_attachment_metadata( $attachment_id, $file ) { $attachment = get_post( $attachment_id ); $metadata = array(); if ( preg_match('!^image/!', get_post_mime_type( $attachment )) && file_is_displayable_image($file) ) { $imagesize = getimagesize( $file ); $metadata['width'] = $imagesize[0]; $metadata['height'] = $imagesize[1]; // Make the file path relative to the upload dir $metadata['file'] = _wp_relative_upload_path($file); // make thumbnails and other intermediate sizes global $_wp_additional_image_sizes; foreach ( get_intermediate_image_sizes() as $s ) { $sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => false ); if ( isset( $_wp_additional_image_sizes[$s]['width'] ) ) $sizes[$s]['width'] = intval( $_wp_additional_image_sizes[$s]['width'] ); // For theme-added sizes else $sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options if ( isset( $_wp_additional_image_sizes[$s]['height'] ) ) $sizes[$s]['height'] = intval( $_wp_additional_image_sizes[$s]['height'] ); // For theme-added sizes else $sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options if ( isset( $_wp_additional_image_sizes[$s]['crop'] ) ) $sizes[$s]['crop'] = intval( $_wp_additional_image_sizes[$s]['crop'] ); // For theme-added sizes else $sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options } $sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes ); if ( $sizes ) { $editor = wp_get_image_editor( $file ); if ( ! is_wp_error( $editor ) ) $metadata['sizes'] = $editor->multi_resize( $sizes ); } else { $metadata['sizes'] = array(); } // fetch additional metadata from exif/iptc $image_meta = wp_read_image_metadata( $file ); if ( $image_meta ) $metadata['image_meta'] = $image_meta; } return apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id ); } /** * Convert a fraction string to a decimal. * * @since 2.5.0 * * @param string $str * @return int|float */ function wp_exif_frac2dec($str) { @list( $n, $d ) = explode( '/', $str ); if ( !empty($d) ) return $n / $d; return $str; } /** * Convert the exif date format to a unix timestamp. * * @since 2.5.0 * * @param string $str * @return int */ function wp_exif_date2ts($str) { @list( $date, $time ) = explode( ' ', trim($str) ); @list( $y, $m, $d ) = explode( ':', $date ); return strtotime( "{$y}-{$m}-{$d} {$time}" ); } /** * Get extended image metadata, exif or iptc as available. * * Retrieves the EXIF metadata aperture, credit, camera, caption, copyright, iso * created_timestamp, focal_length, shutter_speed, and title. * * The IPTC metadata that is retrieved is APP13, credit, byline, created date * and time, caption, copyright, and title. Also includes FNumber, Model, * DateTimeDigitized, FocalLength, ISOSpeedRatings, and ExposureTime. * * @todo Try other exif libraries if available. * @since 2.5.0 * * @param string $file * @return bool|array False on failure. Image metadata array on success. */ function wp_read_image_metadata( $file ) { if ( ! file_exists( $file ) ) return false; list( , , $sourceImageType ) = getimagesize( $file ); // exif contains a bunch of data we'll probably never need formatted in ways // that are difficult to use. We'll normalize it and just extract the fields // that are likely to be useful. Fractions and numbers are converted to // floats, dates to unix timestamps, and everything else to strings. $meta = array( 'aperture' => 0, 'credit' => '', 'camera' => '', 'caption' => '', 'created_timestamp' => 0, 'copyright' => '', 'focal_length' => 0, 'iso' => 0, 'shutter_speed' => 0, 'title' => '', ); // read iptc first, since it might contain data not available in exif such // as caption, description etc if ( is_callable( 'iptcparse' ) ) { getimagesize( $file, $info ); if ( ! empty( $info['APP13'] ) ) { $iptc = iptcparse( $info['APP13'] ); // headline, "A brief synopsis of the caption." if ( ! empty( $iptc['2#105'][0] ) ) $meta['title'] = trim( $iptc['2#105'][0] ); // title, "Many use the Title field to store the filename of the image, though the field may be used in many ways." elseif ( ! empty( $iptc['2#005'][0] ) ) $meta['title'] = trim( $iptc['2#005'][0] ); if ( ! empty( $iptc['2#120'][0] ) ) { // description / legacy caption $caption = trim( $iptc['2#120'][0] ); if ( empty( $meta['title'] ) ) { // Assume the title is stored in 2:120 if it's short. if ( strlen( $caption ) < 80 ) $meta['title'] = $caption; else $meta['caption'] = $caption; } elseif ( $caption != $meta['title'] ) { $meta['caption'] = $caption; } } if ( ! empty( $iptc['2#110'][0] ) ) // credit $meta['credit'] = trim( $iptc['2#110'][0] ); elseif ( ! empty( $iptc['2#080'][0] ) ) // creator / legacy byline $meta['credit'] = trim( $iptc['2#080'][0] ); if ( ! empty( $iptc['2#055'][0] ) and ! empty( $iptc['2#060'][0] ) ) // created date and time $meta['created_timestamp'] = strtotime( $iptc['2#055'][0] . ' ' . $iptc['2#060'][0] ); if ( ! empty( $iptc['2#116'][0] ) ) // copyright $meta['copyright'] = trim( $iptc['2#116'][0] ); } } // fetch additional info from exif if available if ( is_callable( 'exif_read_data' ) && in_array( $sourceImageType, apply_filters( 'wp_read_image_metadata_types', array( IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM ) ) ) ) { $exif = @exif_read_data( $file ); if ( !empty( $exif['Title'] ) ) $meta['title'] = trim( $exif['Title'] ); if ( ! empty( $exif['ImageDescription'] ) ) { if ( empty( $meta['title'] ) && strlen( $exif['ImageDescription'] ) < 80 ) { // Assume the title is stored in ImageDescription $meta['title'] = trim( $exif['ImageDescription'] ); if ( ! empty( $exif['COMPUTED']['UserComment'] ) && trim( $exif['COMPUTED']['UserComment'] ) != $meta['title'] ) $meta['caption'] = trim( $exif['COMPUTED']['UserComment'] ); } elseif ( trim( $exif['ImageDescription'] ) != $meta['title'] ) { $meta['caption'] = trim( $exif['ImageDescription'] ); } } elseif ( ! empty( $exif['Comments'] ) && trim( $exif['Comments'] ) != $meta['title'] ) { $meta['caption'] = trim( $exif['Comments'] ); } if ( ! empty( $exif['Artist'] ) ) $meta['credit'] = trim( $exif['Artist'] ); elseif ( ! empty($exif['Author'] ) ) $meta['credit'] = trim( $exif['Author'] ); if ( ! empty( $exif['Copyright'] ) ) $meta['copyright'] = trim( $exif['Copyright'] ); if ( ! empty($exif['FNumber'] ) ) $meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 ); if ( ! empty($exif['Model'] ) ) $meta['camera'] = trim( $exif['Model'] ); if ( ! empty($exif['DateTimeDigitized'] ) ) $meta['created_timestamp'] = wp_exif_date2ts($exif['DateTimeDigitized'] ); if ( ! empty($exif['FocalLength'] ) ) $meta['focal_length'] = (string) wp_exif_frac2dec( $exif['FocalLength'] ); if ( ! empty($exif['ISOSpeedRatings'] ) ) { $meta['iso'] = is_array( $exif['ISOSpeedRatings'] ) ? reset( $exif['ISOSpeedRatings'] ) : $exif['ISOSpeedRatings']; $meta['iso'] = trim( $meta['iso'] ); } if ( ! empty($exif['ExposureTime'] ) ) $meta['shutter_speed'] = (string) wp_exif_frac2dec( $exif['ExposureTime'] ); } foreach ( array( 'title', 'caption', 'credit', 'copyright', 'camera', 'iso' ) as $key ) { if ( $meta[ $key ] && ! seems_utf8( $meta[ $key ] ) ) $meta[ $key ] = utf8_encode( $meta[ $key ] ); } return apply_filters( 'wp_read_image_metadata', $meta, $file, $sourceImageType ); } /** * Validate that file is an image. * * @since 2.5.0 * * @param string $path File path to test if valid image. * @return bool True if valid image, false if not valid image. */ function file_is_valid_image($path) { $size = @getimagesize($path); return !empty($size); } /** * Validate that file is suitable for displaying within a web page. * * @since 2.5.0 * @uses apply_filters() Calls 'file_is_displayable_image' on $result and $path. * * @param string $path File path to test. * @return bool True if suitable, false if not suitable. */ function file_is_displayable_image($path) { $info = @getimagesize($path); if ( empty($info) ) $result = false; elseif ( !in_array($info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG)) ) // only gif, jpeg and png images can reliably be displayed $result = false; else $result = true; return apply_filters('file_is_displayable_image', $result, $path); } /** * Load an image resource for editing. * * @since 2.9.0 * * @param string $attachment_id Attachment ID. * @param string $mime_type Image mime type. * @param string $size Optional. Image size, defaults to 'full'. * @return resource|false The resulting image resource on success, false on failure. */ function load_image_to_edit( $attachment_id, $mime_type, $size = 'full' ) { $filepath = _load_image_to_edit_path( $attachment_id, $size ); if ( empty( $filepath ) ) return false; switch ( $mime_type ) { case 'image/jpeg': $image = imagecreatefromjpeg($filepath); break; case 'image/png': $image = imagecreatefrompng($filepath); break; case 'image/gif': $image = imagecreatefromgif($filepath); break; default: $image = false; break; } if ( is_resource($image) ) { $image = apply_filters('load_image_to_edit', $image, $attachment_id, $size); if ( function_exists('imagealphablending') && function_exists('imagesavealpha') ) { imagealphablending($image, false); imagesavealpha($image, true); } } return $image; } /** * Retrieve the path or url of an attachment's attached file. * * If the attached file is not present on the local filesystem (usually due to replication plugins), * then the url of the file is returned if url fopen is supported. * * @since 3.4.0 * @access private * * @param string $attachment_id Attachment ID. * @param string $size Optional. Image size, defaults to 'full'. * @return string|false File path or url on success, false on failure. */ function _load_image_to_edit_path( $attachment_id, $size = 'full' ) { $filepath = get_attached_file( $attachment_id ); if ( $filepath && file_exists( $filepath ) ) { if ( 'full' != $size && ( $data = image_get_intermediate_size( $attachment_id, $size ) ) ) { $filepath = apply_filters( 'load_image_to_edit_filesystempath', path_join( dirname( $filepath ), $data['file'] ), $attachment_id, $size ); } } elseif ( function_exists( 'fopen' ) && function_exists( 'ini_get' ) && true == ini_get( 'allow_url_fopen' ) ) { $filepath = apply_filters( 'load_image_to_edit_attachmenturl', wp_get_attachment_url( $attachment_id ), $attachment_id, $size ); } return apply_filters( 'load_image_to_edit_path', $filepath, $attachment_id, $size ); } /** * Copy an existing image file. * * @since 3.4.0 * @access private * * @param string $attachment_id Attachment ID. * @return string|false New file path on success, false on failure. */ function _copy_image_file( $attachment_id ) { $dst_file = $src_file = get_attached_file( $attachment_id ); if ( ! file_exists( $src_file ) ) $src_file = _load_image_to_edit_path( $attachment_id ); if ( $src_file ) { $dst_file = str_replace( basename( $dst_file ), 'copy-' . basename( $dst_file ), $dst_file ); $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) ); // The directory containing the original file may no longer exist when // using a replication plugin. wp_mkdir_p( dirname( $dst_file ) ); if ( ! @copy( $src_file, $dst_file ) ) $dst_file = false; } else { $dst_file = false; } return $dst_file; }
zyblog
trunk/zyblog/wp-admin/includes/image.php
PHP
asf20
13,990
<?php /** * WordPress Comment Administration API. * * @package WordPress * @subpackage Administration */ /** * {@internal Missing Short Description}} * * @since 2.0.0 * @uses $wpdb * * @param string $comment_author Author of the comment * @param string $comment_date Date of the comment * @return mixed Comment ID on success. */ function comment_exists($comment_author, $comment_date) { global $wpdb; $comment_author = stripslashes($comment_author); $comment_date = stripslashes($comment_date); return $wpdb->get_var( $wpdb->prepare("SELECT comment_post_ID FROM $wpdb->comments WHERE comment_author = %s AND comment_date = %s", $comment_author, $comment_date) ); } /** * Update a comment with values provided in $_POST. * * @since 2.0.0 */ function edit_comment() { if ( ! current_user_can( 'edit_comment', (int) $_POST['comment_ID'] ) ) wp_die ( __( 'You are not allowed to edit comments on this post.' ) ); $_POST['comment_author'] = $_POST['newcomment_author']; $_POST['comment_author_email'] = $_POST['newcomment_author_email']; $_POST['comment_author_url'] = $_POST['newcomment_author_url']; $_POST['comment_approved'] = $_POST['comment_status']; $_POST['comment_content'] = $_POST['content']; $_POST['comment_ID'] = (int) $_POST['comment_ID']; foreach ( array ('aa', 'mm', 'jj', 'hh', 'mn') as $timeunit ) { if ( !empty( $_POST['hidden_' . $timeunit] ) && $_POST['hidden_' . $timeunit] != $_POST[$timeunit] ) { $_POST['edit_date'] = '1'; break; } } if ( !empty ( $_POST['edit_date'] ) ) { $aa = $_POST['aa']; $mm = $_POST['mm']; $jj = $_POST['jj']; $hh = $_POST['hh']; $mn = $_POST['mn']; $ss = $_POST['ss']; $jj = ($jj > 31 ) ? 31 : $jj; $hh = ($hh > 23 ) ? $hh -24 : $hh; $mn = ($mn > 59 ) ? $mn -60 : $mn; $ss = ($ss > 59 ) ? $ss -60 : $ss; $_POST['comment_date'] = "$aa-$mm-$jj $hh:$mn:$ss"; } wp_update_comment( $_POST ); } /** * {@internal Missing Short Description}} * * @since 2.0.0 * * @param int $id ID of comment to retrieve * @return bool|object Comment if found. False on failure. */ function get_comment_to_edit( $id ) { if ( !$comment = get_comment($id) ) return false; $comment->comment_ID = (int) $comment->comment_ID; $comment->comment_post_ID = (int) $comment->comment_post_ID; $comment->comment_content = format_to_edit( $comment->comment_content ); $comment->comment_content = apply_filters( 'comment_edit_pre', $comment->comment_content); $comment->comment_author = format_to_edit( $comment->comment_author ); $comment->comment_author_email = format_to_edit( $comment->comment_author_email ); $comment->comment_author_url = format_to_edit( $comment->comment_author_url ); $comment->comment_author_url = esc_url($comment->comment_author_url); return $comment; } /** * Get the number of pending comments on a post or posts * * @since 2.3.0 * @uses $wpdb * * @param int|array $post_id Either a single Post ID or an array of Post IDs * @return int|array Either a single Posts pending comments as an int or an array of ints keyed on the Post IDs */ function get_pending_comments_num( $post_id ) { global $wpdb; $single = false; if ( !is_array($post_id) ) { $post_id_array = (array) $post_id; $single = true; } else { $post_id_array = $post_id; } $post_id_array = array_map('intval', $post_id_array); $post_id_in = "'" . implode("', '", $post_id_array) . "'"; $pending = $wpdb->get_results( "SELECT comment_post_ID, COUNT(comment_ID) as num_comments FROM $wpdb->comments WHERE comment_post_ID IN ( $post_id_in ) AND comment_approved = '0' GROUP BY comment_post_ID", ARRAY_A ); if ( $single ) { if ( empty($pending) ) return 0; else return absint($pending[0]['num_comments']); } $pending_keyed = array(); // Default to zero pending for all posts in request foreach ( $post_id_array as $id ) $pending_keyed[$id] = 0; if ( !empty($pending) ) foreach ( $pending as $pend ) $pending_keyed[$pend['comment_post_ID']] = absint($pend['num_comments']); return $pending_keyed; } /** * Add avatars to relevant places in admin, or try to. * * @since 2.5.0 * @uses $comment * * @param string $name User name. * @return string Avatar with Admin name. */ function floated_admin_avatar( $name ) { global $comment; $avatar = get_avatar( $comment, 32 ); return "$avatar $name"; } function enqueue_comment_hotkeys_js() { if ( 'true' == get_user_option( 'comment_shortcuts' ) ) wp_enqueue_script( 'jquery-table-hotkeys' ); }
zyblog
trunk/zyblog/wp-admin/includes/comment.php
PHP
asf20
4,500
<?php /** * WordPress user administration API. * * @package WordPress * @subpackage Administration */ /** * Creates a new user from the "Users" form using $_POST information. * * @since 2.0 * * @return null|WP_Error|int Null when adding user, WP_Error or User ID integer when no parameters. */ function add_user() { return edit_user(); } /** * Edit user settings based on contents of $_POST * * Used on user-edit.php and profile.php to manage and process user options, passwords etc. * * @since 2.0 * * @param int $user_id Optional. User ID. * @return int user id of the updated user */ function edit_user( $user_id = 0 ) { global $wp_roles, $wpdb; $user = new stdClass; if ( $user_id ) { $update = true; $user->ID = (int) $user_id; $userdata = get_userdata( $user_id ); $user->user_login = $wpdb->escape( $userdata->user_login ); } else { $update = false; } if ( !$update && isset( $_POST['user_login'] ) ) $user->user_login = sanitize_user($_POST['user_login'], true); $pass1 = $pass2 = ''; if ( isset( $_POST['pass1'] )) $pass1 = $_POST['pass1']; if ( isset( $_POST['pass2'] )) $pass2 = $_POST['pass2']; if ( isset( $_POST['role'] ) && current_user_can( 'edit_users' ) ) { $new_role = sanitize_text_field( $_POST['role'] ); $potential_role = isset($wp_roles->role_objects[$new_role]) ? $wp_roles->role_objects[$new_role] : false; // Don't let anyone with 'edit_users' (admins) edit their own role to something without it. // Multisite super admins can freely edit their blog roles -- they possess all caps. if ( ( is_multisite() && current_user_can( 'manage_sites' ) ) || $user_id != get_current_user_id() || ($potential_role && $potential_role->has_cap( 'edit_users' ) ) ) $user->role = $new_role; // If the new role isn't editable by the logged-in user die with error $editable_roles = get_editable_roles(); if ( ! empty( $new_role ) && empty( $editable_roles[$new_role] ) ) wp_die(__('You can&#8217;t give users that role.')); } if ( isset( $_POST['email'] )) $user->user_email = sanitize_text_field( $_POST['email'] ); if ( isset( $_POST['url'] ) ) { if ( empty ( $_POST['url'] ) || $_POST['url'] == 'http://' ) { $user->user_url = ''; } else { $user->user_url = esc_url_raw( $_POST['url'] ); $protocols = implode( '|', array_map( 'preg_quote', wp_allowed_protocols() ) ); $user->user_url = preg_match('/^(' . $protocols . '):/is', $user->user_url) ? $user->user_url : 'http://'.$user->user_url; } } if ( isset( $_POST['first_name'] ) ) $user->first_name = sanitize_text_field( $_POST['first_name'] ); if ( isset( $_POST['last_name'] ) ) $user->last_name = sanitize_text_field( $_POST['last_name'] ); if ( isset( $_POST['nickname'] ) ) $user->nickname = sanitize_text_field( $_POST['nickname'] ); if ( isset( $_POST['display_name'] ) ) $user->display_name = sanitize_text_field( $_POST['display_name'] ); if ( isset( $_POST['description'] ) ) $user->description = trim( $_POST['description'] ); foreach ( _wp_get_user_contactmethods( $user ) as $method => $name ) { if ( isset( $_POST[$method] )) $user->$method = sanitize_text_field( $_POST[$method] ); } if ( $update ) { $user->rich_editing = isset( $_POST['rich_editing'] ) && 'false' == $_POST['rich_editing'] ? 'false' : 'true'; $user->admin_color = isset( $_POST['admin_color'] ) ? sanitize_text_field( $_POST['admin_color'] ) : 'fresh'; $user->show_admin_bar_front = isset( $_POST['admin_bar_front'] ) ? 'true' : 'false'; } $user->comment_shortcuts = isset( $_POST['comment_shortcuts'] ) && 'true' == $_POST['comment_shortcuts'] ? 'true' : ''; $user->use_ssl = 0; if ( !empty($_POST['use_ssl']) ) $user->use_ssl = 1; $errors = new WP_Error(); /* checking that username has been typed */ if ( $user->user_login == '' ) $errors->add( 'user_login', __( '<strong>ERROR</strong>: Please enter a username.' )); /* checking the password has been typed twice */ do_action_ref_array( 'check_passwords', array ( $user->user_login, & $pass1, & $pass2 )); if ( $update ) { if ( empty($pass1) && !empty($pass2) ) $errors->add( 'pass', __( '<strong>ERROR</strong>: You entered your new password only once.' ), array( 'form-field' => 'pass1' ) ); elseif ( !empty($pass1) && empty($pass2) ) $errors->add( 'pass', __( '<strong>ERROR</strong>: You entered your new password only once.' ), array( 'form-field' => 'pass2' ) ); } else { if ( empty($pass1) ) $errors->add( 'pass', __( '<strong>ERROR</strong>: Please enter your password.' ), array( 'form-field' => 'pass1' ) ); elseif ( empty($pass2) ) $errors->add( 'pass', __( '<strong>ERROR</strong>: Please enter your password twice.' ), array( 'form-field' => 'pass2' ) ); } /* Check for "\" in password */ if ( false !== strpos( stripslashes($pass1), "\\" ) ) $errors->add( 'pass', __( '<strong>ERROR</strong>: Passwords may not contain the character "\\".' ), array( 'form-field' => 'pass1' ) ); /* checking the password has been typed twice the same */ if ( $pass1 != $pass2 ) $errors->add( 'pass', __( '<strong>ERROR</strong>: Please enter the same password in the two password fields.' ), array( 'form-field' => 'pass1' ) ); if ( !empty( $pass1 ) ) $user->user_pass = $pass1; if ( !$update && isset( $_POST['user_login'] ) && !validate_username( $_POST['user_login'] ) ) $errors->add( 'user_login', __( '<strong>ERROR</strong>: This username is invalid because it uses illegal characters. Please enter a valid username.' )); if ( !$update && username_exists( $user->user_login ) ) $errors->add( 'user_login', __( '<strong>ERROR</strong>: This username is already registered. Please choose another one.' )); /* checking e-mail address */ if ( empty( $user->user_email ) ) { $errors->add( 'empty_email', __( '<strong>ERROR</strong>: Please enter an e-mail address.' ), array( 'form-field' => 'email' ) ); } elseif ( !is_email( $user->user_email ) ) { $errors->add( 'invalid_email', __( '<strong>ERROR</strong>: The email address isn&#8217;t correct.' ), array( 'form-field' => 'email' ) ); } elseif ( ( $owner_id = email_exists($user->user_email) ) && ( !$update || ( $owner_id != $user->ID ) ) ) { $errors->add( 'email_exists', __('<strong>ERROR</strong>: This email is already registered, please choose another one.'), array( 'form-field' => 'email' ) ); } // Allow plugins to return their own errors. do_action_ref_array('user_profile_update_errors', array ( &$errors, $update, &$user ) ); if ( $errors->get_error_codes() ) return $errors; if ( $update ) { $user_id = wp_update_user( $user ); } else { $user_id = wp_insert_user( $user ); wp_new_user_notification( $user_id, isset($_POST['send_password']) ? $pass1 : '' ); } return $user_id; } /** * Fetch a filtered list of user roles that the current user is * allowed to edit. * * Simple function who's main purpose is to allow filtering of the * list of roles in the $wp_roles object so that plugins can remove * inappropriate ones depending on the situation or user making edits. * Specifically because without filtering anyone with the edit_users * capability can edit others to be administrators, even if they are * only editors or authors. This filter allows admins to delegate * user management. * * @since 2.8 * * @return unknown */ function get_editable_roles() { global $wp_roles; $all_roles = $wp_roles->roles; $editable_roles = apply_filters('editable_roles', $all_roles); return $editable_roles; } /** * Retrieve user data and filter it. * * @since 2.0.5 * * @param int $user_id User ID. * @return object WP_User object with user data. */ function get_user_to_edit( $user_id ) { $user = get_userdata( $user_id ); $user->filter = 'edit'; return $user; } /** * Retrieve the user's drafts. * * @since 2.0.0 * * @param int $user_id User ID. * @return array */ function get_users_drafts( $user_id ) { global $wpdb; $query = $wpdb->prepare("SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'draft' AND post_author = %d ORDER BY post_modified DESC", $user_id); $query = apply_filters('get_users_drafts', $query); return $wpdb->get_results( $query ); } /** * Remove user and optionally reassign posts and links to another user. * * If the $reassign parameter is not assigned to an User ID, then all posts will * be deleted of that user. The action 'delete_user' that is passed the User ID * being deleted will be run after the posts are either reassigned or deleted. * The user meta will also be deleted that are for that User ID. * * @since 2.0.0 * * @param int $id User ID. * @param int $reassign Optional. Reassign posts and links to new User ID. * @return bool True when finished. */ function wp_delete_user( $id, $reassign = 'novalue' ) { global $wpdb; $id = (int) $id; $user = new WP_User( $id ); // allow for transaction statement do_action('delete_user', $id); if ( 'novalue' === $reassign || null === $reassign ) { $post_types_to_delete = array(); foreach ( get_post_types( array(), 'objects' ) as $post_type ) { if ( $post_type->delete_with_user ) { $post_types_to_delete[] = $post_type->name; } elseif ( null === $post_type->delete_with_user && post_type_supports( $post_type->name, 'author' ) ) { $post_types_to_delete[] = $post_type->name; } } $post_types_to_delete = apply_filters( 'post_types_to_delete_with_user', $post_types_to_delete, $id ); $post_types_to_delete = implode( "', '", $post_types_to_delete ); $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_author = %d AND post_type IN ('$post_types_to_delete')", $id ) ); if ( $post_ids ) { foreach ( $post_ids as $post_id ) wp_delete_post( $post_id ); } // Clean links $link_ids = $wpdb->get_col( $wpdb->prepare("SELECT link_id FROM $wpdb->links WHERE link_owner = %d", $id) ); if ( $link_ids ) { foreach ( $link_ids as $link_id ) wp_delete_link($link_id); } } else { $reassign = (int) $reassign; $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_author = %d", $id ) ); $wpdb->update( $wpdb->posts, array('post_author' => $reassign), array('post_author' => $id) ); if ( ! empty( $post_ids ) ) { foreach ( $post_ids as $post_id ) clean_post_cache( $post_id ); } $link_ids = $wpdb->get_col( $wpdb->prepare("SELECT link_id FROM $wpdb->links WHERE link_owner = %d", $id) ); $wpdb->update( $wpdb->links, array('link_owner' => $reassign), array('link_owner' => $id) ); if ( ! empty( $link_ids ) ) { foreach ( $link_ids as $link_id ) clean_bookmark_cache( $link_id ); } } // FINALLY, delete user if ( is_multisite() ) { remove_user_from_blog( $id, get_current_blog_id() ); } else { $meta = $wpdb->get_col( $wpdb->prepare( "SELECT umeta_id FROM $wpdb->usermeta WHERE user_id = %d", $id ) ); foreach ( $meta as $mid ) delete_metadata_by_mid( 'user', $mid ); $wpdb->delete( $wpdb->users, array( 'ID' => $id ) ); } clean_user_cache( $user ); // allow for commit transaction do_action('deleted_user', $id); return true; } /** * Remove all capabilities from user. * * @since 2.1.0 * * @param int $id User ID. */ function wp_revoke_user($id) { $id = (int) $id; $user = new WP_User($id); $user->remove_all_caps(); } add_action('admin_init', 'default_password_nag_handler'); /** * @since 2.8.0 */ function default_password_nag_handler($errors = false) { global $user_ID; if ( ! get_user_option('default_password_nag') ) //Short circuit it. return; //get_user_setting = JS saved UI setting. else no-js-fallback code. if ( 'hide' == get_user_setting('default_password_nag') || isset($_GET['default_password_nag']) && '0' == $_GET['default_password_nag'] ) { delete_user_setting('default_password_nag'); update_user_option($user_ID, 'default_password_nag', false, true); } } add_action('profile_update', 'default_password_nag_edit_user', 10, 2); /** * @since 2.8.0 */ function default_password_nag_edit_user($user_ID, $old_data) { if ( ! get_user_option('default_password_nag', $user_ID) ) //Short circuit it. return; $new_data = get_userdata($user_ID); if ( $new_data->user_pass != $old_data->user_pass ) { //Remove the nag if the password has been changed. delete_user_setting('default_password_nag', $user_ID); update_user_option($user_ID, 'default_password_nag', false, true); } } add_action('admin_notices', 'default_password_nag'); /** * @since 2.8.0 */ function default_password_nag() { global $pagenow; if ( 'profile.php' == $pagenow || ! get_user_option('default_password_nag') ) //Short circuit it. return; echo '<div class="error default-password-nag">'; echo '<p>'; echo '<strong>' . __('Notice:') . '</strong> '; _e('You&rsquo;re using the auto-generated password for your account. Would you like to change it to something easier to remember?'); echo '</p><p>'; printf( '<a href="%s">' . __('Yes, take me to my profile page') . '</a> | ', get_edit_profile_url( get_current_user_id() ) . '#password' ); printf( '<a href="%s" id="default-password-nag-no">' . __('No thanks, do not remind me again') . '</a>', '?default_password_nag=0' ); echo '</p></div>'; }
zyblog
trunk/zyblog/wp-admin/includes/user.php
PHP
asf20
13,252
<?php /** * WordPress Administration Scheme API * * Here we keep the DB structure and option values. * * @package WordPress * @subpackage Administration */ // Declare these as global in case schema.php is included from a function. global $wpdb, $wp_queries, $charset_collate; /** * The database character collate. * @var string * @global string * @name $charset_collate */ $charset_collate = $wpdb->get_charset_collate(); /** * Retrieve the SQL for creating database tables. * * @since 3.3.0 * * @param string $scope Optional. The tables for which to retrieve SQL. Can be all, global, ms_global, or blog tables. Defaults to all. * @param int $blog_id Optional. The blog ID for which to retrieve SQL. Default is the current blog ID. * @return string The SQL needed to create the requested tables. */ function wp_get_db_schema( $scope = 'all', $blog_id = null ) { global $wpdb; $charset_collate = ''; if ( ! empty($wpdb->charset) ) $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset"; if ( ! empty($wpdb->collate) ) $charset_collate .= " COLLATE $wpdb->collate"; if ( $blog_id && $blog_id != $wpdb->blogid ) $old_blog_id = $wpdb->set_blog_id( $blog_id ); // Engage multisite if in the middle of turning it on from network.php. $is_multisite = is_multisite() || ( defined( 'WP_INSTALLING_NETWORK' ) && WP_INSTALLING_NETWORK ); // Blog specific tables. $blog_tables = "CREATE TABLE $wpdb->terms ( term_id bigint(20) unsigned NOT NULL auto_increment, name varchar(200) NOT NULL default '', slug varchar(200) NOT NULL default '', term_group bigint(10) NOT NULL default 0, PRIMARY KEY (term_id), UNIQUE KEY slug (slug), KEY name (name) ) $charset_collate; CREATE TABLE $wpdb->term_taxonomy ( term_taxonomy_id bigint(20) unsigned NOT NULL auto_increment, term_id bigint(20) unsigned NOT NULL default 0, taxonomy varchar(32) NOT NULL default '', description longtext NOT NULL, parent bigint(20) unsigned NOT NULL default 0, count bigint(20) NOT NULL default 0, PRIMARY KEY (term_taxonomy_id), UNIQUE KEY term_id_taxonomy (term_id,taxonomy), KEY taxonomy (taxonomy) ) $charset_collate; CREATE TABLE $wpdb->term_relationships ( object_id bigint(20) unsigned NOT NULL default 0, term_taxonomy_id bigint(20) unsigned NOT NULL default 0, term_order int(11) NOT NULL default 0, PRIMARY KEY (object_id,term_taxonomy_id), KEY term_taxonomy_id (term_taxonomy_id) ) $charset_collate; CREATE TABLE $wpdb->commentmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, comment_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY comment_id (comment_id), KEY meta_key (meta_key) ) $charset_collate; CREATE TABLE $wpdb->comments ( comment_ID bigint(20) unsigned NOT NULL auto_increment, comment_post_ID bigint(20) unsigned NOT NULL default '0', comment_author tinytext NOT NULL, comment_author_email varchar(100) NOT NULL default '', comment_author_url varchar(200) NOT NULL default '', comment_author_IP varchar(100) NOT NULL default '', comment_date datetime NOT NULL default '0000-00-00 00:00:00', comment_date_gmt datetime NOT NULL default '0000-00-00 00:00:00', comment_content text NOT NULL, comment_karma int(11) NOT NULL default '0', comment_approved varchar(20) NOT NULL default '1', comment_agent varchar(255) NOT NULL default '', comment_type varchar(20) NOT NULL default '', comment_parent bigint(20) unsigned NOT NULL default '0', user_id bigint(20) unsigned NOT NULL default '0', PRIMARY KEY (comment_ID), KEY comment_post_ID (comment_post_ID), KEY comment_approved_date_gmt (comment_approved,comment_date_gmt), KEY comment_date_gmt (comment_date_gmt), KEY comment_parent (comment_parent) ) $charset_collate; CREATE TABLE $wpdb->links ( link_id bigint(20) unsigned NOT NULL auto_increment, link_url varchar(255) NOT NULL default '', link_name varchar(255) NOT NULL default '', link_image varchar(255) NOT NULL default '', link_target varchar(25) NOT NULL default '', link_description varchar(255) NOT NULL default '', link_visible varchar(20) NOT NULL default 'Y', link_owner bigint(20) unsigned NOT NULL default '1', link_rating int(11) NOT NULL default '0', link_updated datetime NOT NULL default '0000-00-00 00:00:00', link_rel varchar(255) NOT NULL default '', link_notes mediumtext NOT NULL, link_rss varchar(255) NOT NULL default '', PRIMARY KEY (link_id), KEY link_visible (link_visible) ) $charset_collate; CREATE TABLE $wpdb->options ( option_id bigint(20) unsigned NOT NULL auto_increment, option_name varchar(64) NOT NULL default '', option_value longtext NOT NULL, autoload varchar(20) NOT NULL default 'yes', PRIMARY KEY (option_id), UNIQUE KEY option_name (option_name) ) $charset_collate; CREATE TABLE $wpdb->postmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, post_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY post_id (post_id), KEY meta_key (meta_key) ) $charset_collate; CREATE TABLE $wpdb->posts ( ID bigint(20) unsigned NOT NULL auto_increment, post_author bigint(20) unsigned NOT NULL default '0', post_date datetime NOT NULL default '0000-00-00 00:00:00', post_date_gmt datetime NOT NULL default '0000-00-00 00:00:00', post_content longtext NOT NULL, post_title text NOT NULL, post_excerpt text NOT NULL, post_status varchar(20) NOT NULL default 'publish', comment_status varchar(20) NOT NULL default 'open', ping_status varchar(20) NOT NULL default 'open', post_password varchar(20) NOT NULL default '', post_name varchar(200) NOT NULL default '', to_ping text NOT NULL, pinged text NOT NULL, post_modified datetime NOT NULL default '0000-00-00 00:00:00', post_modified_gmt datetime NOT NULL default '0000-00-00 00:00:00', post_content_filtered longtext NOT NULL, post_parent bigint(20) unsigned NOT NULL default '0', guid varchar(255) NOT NULL default '', menu_order int(11) NOT NULL default '0', post_type varchar(20) NOT NULL default 'post', post_mime_type varchar(100) NOT NULL default '', comment_count bigint(20) NOT NULL default '0', PRIMARY KEY (ID), KEY post_name (post_name), KEY type_status_date (post_type,post_status,post_date,ID), KEY post_parent (post_parent), KEY post_author (post_author) ) $charset_collate;\n"; // Single site users table. The multisite flavor of the users table is handled below. $users_single_table = "CREATE TABLE $wpdb->users ( ID bigint(20) unsigned NOT NULL auto_increment, user_login varchar(60) NOT NULL default '', user_pass varchar(64) NOT NULL default '', user_nicename varchar(50) NOT NULL default '', user_email varchar(100) NOT NULL default '', user_url varchar(100) NOT NULL default '', user_registered datetime NOT NULL default '0000-00-00 00:00:00', user_activation_key varchar(60) NOT NULL default '', user_status int(11) NOT NULL default '0', display_name varchar(250) NOT NULL default '', PRIMARY KEY (ID), KEY user_login_key (user_login), KEY user_nicename (user_nicename) ) $charset_collate;\n"; // Multisite users table $users_multi_table = "CREATE TABLE $wpdb->users ( ID bigint(20) unsigned NOT NULL auto_increment, user_login varchar(60) NOT NULL default '', user_pass varchar(64) NOT NULL default '', user_nicename varchar(50) NOT NULL default '', user_email varchar(100) NOT NULL default '', user_url varchar(100) NOT NULL default '', user_registered datetime NOT NULL default '0000-00-00 00:00:00', user_activation_key varchar(60) NOT NULL default '', user_status int(11) NOT NULL default '0', display_name varchar(250) NOT NULL default '', spam tinyint(2) NOT NULL default '0', deleted tinyint(2) NOT NULL default '0', PRIMARY KEY (ID), KEY user_login_key (user_login), KEY user_nicename (user_nicename) ) $charset_collate;\n"; // usermeta $usermeta_table = "CREATE TABLE $wpdb->usermeta ( umeta_id bigint(20) unsigned NOT NULL auto_increment, user_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (umeta_id), KEY user_id (user_id), KEY meta_key (meta_key) ) $charset_collate;\n"; // Global tables if ( $is_multisite ) $global_tables = $users_multi_table . $usermeta_table; else $global_tables = $users_single_table . $usermeta_table; // Multisite global tables. $ms_global_tables = "CREATE TABLE $wpdb->blogs ( blog_id bigint(20) NOT NULL auto_increment, site_id bigint(20) NOT NULL default '0', domain varchar(200) NOT NULL default '', path varchar(100) NOT NULL default '', registered datetime NOT NULL default '0000-00-00 00:00:00', last_updated datetime NOT NULL default '0000-00-00 00:00:00', public tinyint(2) NOT NULL default '1', archived enum('0','1') NOT NULL default '0', mature tinyint(2) NOT NULL default '0', spam tinyint(2) NOT NULL default '0', deleted tinyint(2) NOT NULL default '0', lang_id int(11) NOT NULL default '0', PRIMARY KEY (blog_id), KEY domain (domain(50),path(5)), KEY lang_id (lang_id) ) $charset_collate; CREATE TABLE $wpdb->blog_versions ( blog_id bigint(20) NOT NULL default '0', db_version varchar(20) NOT NULL default '', last_updated datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (blog_id), KEY db_version (db_version) ) $charset_collate; CREATE TABLE $wpdb->registration_log ( ID bigint(20) NOT NULL auto_increment, email varchar(255) NOT NULL default '', IP varchar(30) NOT NULL default '', blog_id bigint(20) NOT NULL default '0', date_registered datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (ID), KEY IP (IP) ) $charset_collate; CREATE TABLE $wpdb->site ( id bigint(20) NOT NULL auto_increment, domain varchar(200) NOT NULL default '', path varchar(100) NOT NULL default '', PRIMARY KEY (id), KEY domain (domain,path) ) $charset_collate; CREATE TABLE $wpdb->sitemeta ( meta_id bigint(20) NOT NULL auto_increment, site_id bigint(20) NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY meta_key (meta_key), KEY site_id (site_id) ) $charset_collate; CREATE TABLE $wpdb->signups ( domain varchar(200) NOT NULL default '', path varchar(100) NOT NULL default '', title longtext NOT NULL, user_login varchar(60) NOT NULL default '', user_email varchar(100) NOT NULL default '', registered datetime NOT NULL default '0000-00-00 00:00:00', activated datetime NOT NULL default '0000-00-00 00:00:00', active tinyint(1) NOT NULL default '0', activation_key varchar(50) NOT NULL default '', meta longtext, KEY activation_key (activation_key), KEY domain (domain) ) $charset_collate;"; switch ( $scope ) { case 'blog' : $queries = $blog_tables; break; case 'global' : $queries = $global_tables; if ( $is_multisite ) $queries .= $ms_global_tables; break; case 'ms_global' : $queries = $ms_global_tables; break; default: case 'all' : $queries = $global_tables . $blog_tables; if ( $is_multisite ) $queries .= $ms_global_tables; break; } if ( isset( $old_blog_id ) ) $wpdb->set_blog_id( $old_blog_id ); return $queries; } // Populate for back compat. $wp_queries = wp_get_db_schema( 'all' ); /** * Create WordPress options and set the default values. * * @since 1.5.0 * @uses $wpdb * @uses $wp_db_version */ function populate_options() { global $wpdb, $wp_db_version, $current_site, $wp_current_db_version; $guessurl = wp_guess_url(); do_action('populate_options'); if ( ini_get('safe_mode') ) { // Safe mode can break mkdir() so use a flat structure by default. $uploads_use_yearmonth_folders = 0; } else { $uploads_use_yearmonth_folders = 1; } $template = WP_DEFAULT_THEME; // If default theme is a child theme, we need to get its template $theme = wp_get_theme( $template ); if ( ! $theme->errors() ) $template = $theme->get_template(); $timezone_string = ''; $gmt_offset = 0; /* translators: default GMT offset or timezone string. Must be either a valid offset (-12 to 14) or a valid timezone string (America/New_York). See http://us3.php.net/manual/en/timezones.php for all timezone strings supported by PHP. */ $offset_or_tz = _x( '0', 'default GMT offset or timezone string' ); if ( is_numeric( $offset_or_tz ) ) $gmt_offset = $offset_or_tz; elseif ( $offset_or_tz && in_array( $offset_or_tz, timezone_identifiers_list() ) ) $timezone_string = $offset_or_tz; $options = array( 'siteurl' => $guessurl, 'blogname' => __('My Site'), /* translators: blog tagline */ 'blogdescription' => __('Just another WordPress site'), 'users_can_register' => 0, 'admin_email' => 'you@example.com', /* translators: default start of the week. 0 = Sunday, 1 = Monday */ 'start_of_week' => _x( '1', 'start of week' ), 'use_balanceTags' => 0, 'use_smilies' => 1, 'require_name_email' => 1, 'comments_notify' => 1, 'posts_per_rss' => 10, 'rss_use_excerpt' => 0, 'mailserver_url' => 'mail.example.com', 'mailserver_login' => 'login@example.com', 'mailserver_pass' => 'password', 'mailserver_port' => 110, 'default_category' => 1, 'default_comment_status' => 'open', 'default_ping_status' => 'open', 'default_pingback_flag' => 1, 'posts_per_page' => 10, /* translators: default date format, see http://php.net/date */ 'date_format' => __('F j, Y'), /* translators: default time format, see http://php.net/date */ 'time_format' => __('g:i a'), /* translators: links last updated date format, see http://php.net/date */ 'links_updated_date_format' => __('F j, Y g:i a'), 'links_recently_updated_prepend' => '<em>', 'links_recently_updated_append' => '</em>', 'links_recently_updated_time' => 120, 'comment_moderation' => 0, 'moderation_notify' => 1, 'permalink_structure' => '', 'gzipcompression' => 0, 'hack_file' => 0, 'blog_charset' => 'UTF-8', 'moderation_keys' => '', 'active_plugins' => array(), 'home' => $guessurl, 'category_base' => '', 'ping_sites' => 'http://rpc.pingomatic.com/', 'advanced_edit' => 0, 'comment_max_links' => 2, 'gmt_offset' => $gmt_offset, // 1.5 'default_email_category' => 1, 'recently_edited' => '', 'template' => $template, 'stylesheet' => WP_DEFAULT_THEME, 'comment_whitelist' => 1, 'blacklist_keys' => '', 'comment_registration' => 0, 'html_type' => 'text/html', // 1.5.1 'use_trackback' => 0, // 2.0 'default_role' => 'subscriber', 'db_version' => $wp_db_version, // 2.0.1 'uploads_use_yearmonth_folders' => $uploads_use_yearmonth_folders, 'upload_path' => '', // 2.1 'blog_public' => '1', 'default_link_category' => 2, 'show_on_front' => 'posts', // 2.2 'tag_base' => '', // 2.5 'show_avatars' => '1', 'avatar_rating' => 'G', 'upload_url_path' => '', 'thumbnail_size_w' => 150, 'thumbnail_size_h' => 150, 'thumbnail_crop' => 1, 'medium_size_w' => 300, 'medium_size_h' => 300, // 2.6 'avatar_default' => 'mystery', // 2.7 'large_size_w' => 1024, 'large_size_h' => 1024, 'image_default_link_type' => 'file', 'image_default_size' => '', 'image_default_align' => '', 'close_comments_for_old_posts' => 0, 'close_comments_days_old' => 14, 'thread_comments' => 1, 'thread_comments_depth' => 5, 'page_comments' => 0, 'comments_per_page' => 50, 'default_comments_page' => 'newest', 'comment_order' => 'asc', 'sticky_posts' => array(), 'widget_categories' => array(), 'widget_text' => array(), 'widget_rss' => array(), 'uninstall_plugins' => array(), // 2.8 'timezone_string' => $timezone_string, // 3.0 'page_for_posts' => 0, 'page_on_front' => 0, // 3.1 'default_post_format' => 0, // 3.5 'link_manager_enabled' => 0, ); // 3.3 if ( ! is_multisite() ) { $options['initial_db_version'] = ! empty( $wp_current_db_version ) && $wp_current_db_version < $wp_db_version ? $wp_current_db_version : $wp_db_version; } // 3.0 multisite if ( is_multisite() ) { /* translators: blog tagline */ $options[ 'blogdescription' ] = sprintf(__('Just another %s site'), $current_site->site_name ); $options[ 'permalink_structure' ] = '/%year%/%monthnum%/%day%/%postname%/'; } // Set autoload to no for these options $fat_options = array( 'moderation_keys', 'recently_edited', 'blacklist_keys', 'uninstall_plugins' ); $existing_options = $wpdb->get_col("SELECT option_name FROM $wpdb->options"); $insert = ''; foreach ( $options as $option => $value ) { if ( in_array($option, $existing_options) ) continue; if ( in_array($option, $fat_options) ) $autoload = 'no'; else $autoload = 'yes'; $option = $wpdb->escape($option); if ( is_array($value) ) $value = serialize($value); $value = $wpdb->escape($value); if ( !empty($insert) ) $insert .= ', '; $insert .= "('$option', '$value', '$autoload')"; } if ( !empty($insert) ) $wpdb->query("INSERT INTO $wpdb->options (option_name, option_value, autoload) VALUES " . $insert); // in case it is set, but blank, update "home" if ( !__get_option('home') ) update_option('home', $guessurl); // Delete unused options $unusedoptions = array( 'blodotgsping_url', 'bodyterminator', 'emailtestonly', 'phoneemail_separator', 'smilies_directory', 'subjectprefix', 'use_bbcode', 'use_blodotgsping', 'use_phoneemail', 'use_quicktags', 'use_weblogsping', 'weblogs_cache_file', 'use_preview', 'use_htmltrans', 'smilies_directory', 'fileupload_allowedusers', 'use_phoneemail', 'default_post_status', 'default_post_category', 'archive_mode', 'time_difference', 'links_minadminlevel', 'links_use_adminlevels', 'links_rating_type', 'links_rating_char', 'links_rating_ignore_zero', 'links_rating_single_image', 'links_rating_image0', 'links_rating_image1', 'links_rating_image2', 'links_rating_image3', 'links_rating_image4', 'links_rating_image5', 'links_rating_image6', 'links_rating_image7', 'links_rating_image8', 'links_rating_image9', 'weblogs_cacheminutes', 'comment_allowed_tags', 'search_engine_friendly_urls', 'default_geourl_lat', 'default_geourl_lon', 'use_default_geourl', 'weblogs_xml_url', 'new_users_can_blog', '_wpnonce', '_wp_http_referer', 'Update', 'action', 'rich_editing', 'autosave_interval', 'deactivated_plugins', 'can_compress_scripts', 'page_uris', 'update_core', 'update_plugins', 'update_themes', 'doing_cron', 'random_seed', 'rss_excerpt_length', 'secret', 'use_linksupdate', 'default_comment_status_page', 'wporg_popular_tags', 'what_to_show', 'rss_language', 'language', 'enable_xmlrpc', 'enable_app', 'autoembed_urls', 'default_post_edit_rows', ); foreach ( $unusedoptions as $option ) delete_option($option); // delete obsolete magpie stuff $wpdb->query("DELETE FROM $wpdb->options WHERE option_name REGEXP '^rss_[0-9a-f]{32}(_ts)?$'"); } /** * Execute WordPress role creation for the various WordPress versions. * * @since 2.0.0 */ function populate_roles() { populate_roles_160(); populate_roles_210(); populate_roles_230(); populate_roles_250(); populate_roles_260(); populate_roles_270(); populate_roles_280(); populate_roles_300(); } /** * Create the roles for WordPress 2.0 * * @since 2.0.0 */ function populate_roles_160() { // Add roles // Dummy gettext calls to get strings in the catalog. /* translators: user role */ _x('Administrator', 'User role'); /* translators: user role */ _x('Editor', 'User role'); /* translators: user role */ _x('Author', 'User role'); /* translators: user role */ _x('Contributor', 'User role'); /* translators: user role */ _x('Subscriber', 'User role'); add_role('administrator', 'Administrator'); add_role('editor', 'Editor'); add_role('author', 'Author'); add_role('contributor', 'Contributor'); add_role('subscriber', 'Subscriber'); // Add caps for Administrator role $role =& get_role('administrator'); $role->add_cap('switch_themes'); $role->add_cap('edit_themes'); $role->add_cap('activate_plugins'); $role->add_cap('edit_plugins'); $role->add_cap('edit_users'); $role->add_cap('edit_files'); $role->add_cap('manage_options'); $role->add_cap('moderate_comments'); $role->add_cap('manage_categories'); $role->add_cap('manage_links'); $role->add_cap('upload_files'); $role->add_cap('import'); $role->add_cap('unfiltered_html'); $role->add_cap('edit_posts'); $role->add_cap('edit_others_posts'); $role->add_cap('edit_published_posts'); $role->add_cap('publish_posts'); $role->add_cap('edit_pages'); $role->add_cap('read'); $role->add_cap('level_10'); $role->add_cap('level_9'); $role->add_cap('level_8'); $role->add_cap('level_7'); $role->add_cap('level_6'); $role->add_cap('level_5'); $role->add_cap('level_4'); $role->add_cap('level_3'); $role->add_cap('level_2'); $role->add_cap('level_1'); $role->add_cap('level_0'); // Add caps for Editor role $role =& get_role('editor'); $role->add_cap('moderate_comments'); $role->add_cap('manage_categories'); $role->add_cap('manage_links'); $role->add_cap('upload_files'); $role->add_cap('unfiltered_html'); $role->add_cap('edit_posts'); $role->add_cap('edit_others_posts'); $role->add_cap('edit_published_posts'); $role->add_cap('publish_posts'); $role->add_cap('edit_pages'); $role->add_cap('read'); $role->add_cap('level_7'); $role->add_cap('level_6'); $role->add_cap('level_5'); $role->add_cap('level_4'); $role->add_cap('level_3'); $role->add_cap('level_2'); $role->add_cap('level_1'); $role->add_cap('level_0'); // Add caps for Author role $role =& get_role('author'); $role->add_cap('upload_files'); $role->add_cap('edit_posts'); $role->add_cap('edit_published_posts'); $role->add_cap('publish_posts'); $role->add_cap('read'); $role->add_cap('level_2'); $role->add_cap('level_1'); $role->add_cap('level_0'); // Add caps for Contributor role $role =& get_role('contributor'); $role->add_cap('edit_posts'); $role->add_cap('read'); $role->add_cap('level_1'); $role->add_cap('level_0'); // Add caps for Subscriber role $role =& get_role('subscriber'); $role->add_cap('read'); $role->add_cap('level_0'); } /** * Create and modify WordPress roles for WordPress 2.1. * * @since 2.1.0 */ function populate_roles_210() { $roles = array('administrator', 'editor'); foreach ($roles as $role) { $role =& get_role($role); if ( empty($role) ) continue; $role->add_cap('edit_others_pages'); $role->add_cap('edit_published_pages'); $role->add_cap('publish_pages'); $role->add_cap('delete_pages'); $role->add_cap('delete_others_pages'); $role->add_cap('delete_published_pages'); $role->add_cap('delete_posts'); $role->add_cap('delete_others_posts'); $role->add_cap('delete_published_posts'); $role->add_cap('delete_private_posts'); $role->add_cap('edit_private_posts'); $role->add_cap('read_private_posts'); $role->add_cap('delete_private_pages'); $role->add_cap('edit_private_pages'); $role->add_cap('read_private_pages'); } $role =& get_role('administrator'); if ( ! empty($role) ) { $role->add_cap('delete_users'); $role->add_cap('create_users'); } $role =& get_role('author'); if ( ! empty($role) ) { $role->add_cap('delete_posts'); $role->add_cap('delete_published_posts'); } $role =& get_role('contributor'); if ( ! empty($role) ) { $role->add_cap('delete_posts'); } } /** * Create and modify WordPress roles for WordPress 2.3. * * @since 2.3.0 */ function populate_roles_230() { $role =& get_role( 'administrator' ); if ( !empty( $role ) ) { $role->add_cap( 'unfiltered_upload' ); } } /** * Create and modify WordPress roles for WordPress 2.5. * * @since 2.5.0 */ function populate_roles_250() { $role =& get_role( 'administrator' ); if ( !empty( $role ) ) { $role->add_cap( 'edit_dashboard' ); } } /** * Create and modify WordPress roles for WordPress 2.6. * * @since 2.6.0 */ function populate_roles_260() { $role =& get_role( 'administrator' ); if ( !empty( $role ) ) { $role->add_cap( 'update_plugins' ); $role->add_cap( 'delete_plugins' ); } } /** * Create and modify WordPress roles for WordPress 2.7. * * @since 2.7.0 */ function populate_roles_270() { $role =& get_role( 'administrator' ); if ( !empty( $role ) ) { $role->add_cap( 'install_plugins' ); $role->add_cap( 'update_themes' ); } } /** * Create and modify WordPress roles for WordPress 2.8. * * @since 2.8.0 */ function populate_roles_280() { $role =& get_role( 'administrator' ); if ( !empty( $role ) ) { $role->add_cap( 'install_themes' ); } } /** * Create and modify WordPress roles for WordPress 3.0. * * @since 3.0.0 */ function populate_roles_300() { $role =& get_role( 'administrator' ); if ( !empty( $role ) ) { $role->add_cap( 'update_core' ); $role->add_cap( 'list_users' ); $role->add_cap( 'remove_users' ); // Never used, will be removed. create_users or // promote_users is the capability you're looking for. $role->add_cap( 'add_users' ); $role->add_cap( 'promote_users' ); $role->add_cap( 'edit_theme_options' ); $role->add_cap( 'delete_themes' ); $role->add_cap( 'export' ); } } /** * Install Network. * * @since 3.0.0 * */ if ( !function_exists( 'install_network' ) ) : function install_network() { if ( ! defined( 'WP_INSTALLING_NETWORK' ) ) define( 'WP_INSTALLING_NETWORK', true ); dbDelta( wp_get_db_schema( 'global' ) ); } endif; /** * populate network settings * * @since 3.0.0 * * @param int $network_id id of network to populate * @return bool|WP_Error True on success, or WP_Error on warning (with the install otherwise successful, * so the error code must be checked) or failure. */ function populate_network( $network_id = 1, $domain = '', $email = '', $site_name = '', $path = '/', $subdomain_install = false ) { global $wpdb, $current_site, $wp_db_version, $wp_rewrite; $errors = new WP_Error(); if ( '' == $domain ) $errors->add( 'empty_domain', __( 'You must provide a domain name.' ) ); if ( '' == $site_name ) $errors->add( 'empty_sitename', __( 'You must provide a name for your network of sites.' ) ); // check for network collision if ( $network_id == $wpdb->get_var( $wpdb->prepare( "SELECT id FROM $wpdb->site WHERE id = %d", $network_id ) ) ) $errors->add( 'siteid_exists', __( 'The network already exists.' ) ); $site_user = get_user_by( 'email', $email ); if ( ! is_email( $email ) ) $errors->add( 'invalid_email', __( 'You must provide a valid e-mail address.' ) ); if ( $errors->get_error_code() ) return $errors; // set up site tables $template = get_option( 'template' ); $stylesheet = get_option( 'stylesheet' ); $allowed_themes = array( $stylesheet => true ); if ( $template != $stylesheet ) $allowed_themes[ $template ] = true; if ( WP_DEFAULT_THEME != $stylesheet && WP_DEFAULT_THEME != $template ) $allowed_themes[ WP_DEFAULT_THEME ] = true; if ( 1 == $network_id ) { $wpdb->insert( $wpdb->site, array( 'domain' => $domain, 'path' => $path ) ); $network_id = $wpdb->insert_id; } else { $wpdb->insert( $wpdb->site, array( 'domain' => $domain, 'path' => $path, 'id' => $network_id ) ); } if ( !is_multisite() ) { $site_admins = array( $site_user->user_login ); $users = get_users( array( 'fields' => array( 'ID', 'user_login' ) ) ); if ( $users ) { foreach ( $users as $user ) { if ( is_super_admin( $user->ID ) && !in_array( $user->user_login, $site_admins ) ) $site_admins[] = $user->user_login; } } } else { $site_admins = get_site_option( 'site_admins' ); } $welcome_email = __( 'Dear User, Your new SITE_NAME site has been successfully set up at: BLOG_URL You can log in to the administrator account with the following information: Username: USERNAME Password: PASSWORD Log in here: BLOG_URLwp-login.php We hope you enjoy your new site. Thanks! --The Team @ SITE_NAME' ); $sitemeta = array( 'site_name' => $site_name, 'admin_email' => $site_user->user_email, 'admin_user_id' => $site_user->ID, 'registration' => 'none', 'upload_filetypes' => 'jpg jpeg png gif mp3 mov avi wmv midi mid pdf', 'blog_upload_space' => 100, 'fileupload_maxk' => 1500, 'site_admins' => $site_admins, 'allowedthemes' => $allowed_themes, 'illegal_names' => array( 'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator', 'files' ), 'wpmu_upgrade_site' => $wp_db_version, 'welcome_email' => $welcome_email, 'first_post' => __( 'Welcome to <a href="SITE_URL">SITE_NAME</a>. This is your first post. Edit or delete it, then start blogging!' ), // @todo - network admins should have a method of editing the network siteurl (used for cookie hash) 'siteurl' => get_option( 'siteurl' ) . '/', 'add_new_users' => '0', 'upload_space_check_disabled' => is_multisite() ? get_site_option( 'upload_space_check_disabled' ) : '1', 'subdomain_install' => intval( $subdomain_install ), 'global_terms_enabled' => global_terms_enabled() ? '1' : '0', 'ms_files_rewriting' => is_multisite() ? get_site_option( 'ms_files_rewriting' ) : '0', 'initial_db_version' => get_option( 'initial_db_version' ), 'active_sitewide_plugins' => array(), 'WPLANG' => get_locale(), ); if ( ! $subdomain_install ) $sitemeta['illegal_names'][] = 'blog'; $insert = ''; foreach ( $sitemeta as $meta_key => $meta_value ) { $meta_key = $wpdb->escape( $meta_key ); if ( is_array( $meta_value ) ) $meta_value = serialize( $meta_value ); $meta_value = $wpdb->escape( $meta_value ); if ( !empty( $insert ) ) $insert .= ', '; $insert .= "( $network_id, '$meta_key', '$meta_value')"; } $wpdb->query( "INSERT INTO $wpdb->sitemeta ( site_id, meta_key, meta_value ) VALUES " . $insert ); // When upgrading from single to multisite, assume the current site will become the main site of the network. // When using populate_network() to create another network in an existing multisite environment, // skip these steps since the main site of the new network has not yet been created. if ( ! is_multisite() ) { $current_site = new stdClass; $current_site->domain = $domain; $current_site->path = $path; $current_site->site_name = ucfirst( $domain ); $wpdb->insert( $wpdb->blogs, array( 'site_id' => $network_id, 'domain' => $domain, 'path' => $path, 'registered' => current_time( 'mysql' ) ) ); $current_site->blog_id = $blog_id = $wpdb->insert_id; update_user_meta( $site_user->ID, 'source_domain', $domain ); update_user_meta( $site_user->ID, 'primary_blog', $blog_id ); if ( $subdomain_install ) $wp_rewrite->set_permalink_structure( '/%year%/%monthnum%/%day%/%postname%/' ); else $wp_rewrite->set_permalink_structure( '/blog/%year%/%monthnum%/%day%/%postname%/' ); flush_rewrite_rules(); } if ( $subdomain_install ) { $vhost_ok = false; $errstr = ''; $hostname = substr( md5( time() ), 0, 6 ) . '.' . $domain; // Very random hostname! $page = wp_remote_get( 'http://' . $hostname, array( 'timeout' => 5, 'httpversion' => '1.1' ) ); if ( is_wp_error( $page ) ) $errstr = $page->get_error_message(); elseif ( 200 == wp_remote_retrieve_response_code( $page ) ) $vhost_ok = true; if ( ! $vhost_ok ) { $msg = '<p><strong>' . __( 'Warning! Wildcard DNS may not be configured correctly!' ) . '</strong></p>'; $msg .= '<p>' . sprintf( __( 'The installer attempted to contact a random hostname (<code>%1$s</code>) on your domain.' ), $hostname ); if ( ! empty ( $errstr ) ) $msg .= ' ' . sprintf( __( 'This resulted in an error message: %s' ), '<code>' . $errstr . '</code>' ); $msg .= '</p>'; $msg .= '<p>' . __( 'To use a subdomain configuration, you must have a wildcard entry in your DNS. This usually means adding a <code>*</code> hostname record pointing at your web server in your DNS configuration tool.' ) . '</p>'; $msg .= '<p>' . __( 'You can still use your site but any subdomain you create may not be accessible. If you know your DNS is correct, ignore this message.' ) . '</p>'; return new WP_Error( 'no_wildcard_dns', $msg ); } } return true; }
zyblog
trunk/zyblog/wp-admin/includes/schema.php
PHP
asf20
32,082
<?php /** * Comment Management Screen * * @package WordPress * @subpackage Administration */ /** Load WordPress Bootstrap */ require_once('./admin.php'); $parent_file = 'edit-comments.php'; $submenu_file = 'edit-comments.php'; wp_reset_vars( array('action') ); if ( isset( $_POST['deletecomment'] ) ) $action = 'deletecomment'; if ( 'cdc' == $action ) $action = 'delete'; elseif ( 'mac' == $action ) $action = 'approve'; if ( isset( $_GET['dt'] ) ) { if ( 'spam' == $_GET['dt'] ) $action = 'spam'; elseif ( 'trash' == $_GET['dt'] ) $action = 'trash'; } /** * Display error message at bottom of comments. * * @param string $msg Error Message. Assumed to contain HTML and be sanitized. */ function comment_footer_die( $msg ) { echo "<div class='wrap'><p>$msg</p></div>"; include('./admin-footer.php'); die; } switch( $action ) { case 'editcomment' : $title = __('Edit Comment'); get_current_screen()->add_help_tab( array( 'id' => 'overview', 'title' => __('Overview'), 'content' => '<p>' . __( 'You can edit the information left in a comment if needed. This is often useful when you notice that a commenter has made a typographical error.' ) . '</p>' . '<p>' . __( 'You can also moderate the comment from this screen using the Status box, where you can also change the timestamp of the comment.' ) . '</p>' ) ); get_current_screen()->set_help_sidebar( '<p><strong>' . __( 'For more information:' ) . '</strong></p>' . '<p>' . __( '<a href="http://codex.wordpress.org/Administration_Screens#Comments" target="_blank">Documentation on Comments</a>' ) . '</p>' . '<p>' . __( '<a href="http://wordpress.org/support/" target="_blank">Support Forums</a>' ) . '</p>' ); wp_enqueue_script('comment'); require_once('./admin-header.php'); $comment_id = absint( $_GET['c'] ); if ( !$comment = get_comment( $comment_id ) ) comment_footer_die( __('Oops, no comment with this ID.') . sprintf(' <a href="%s">' . __('Go back') . '</a>.', 'javascript:history.go(-1)') ); if ( !current_user_can( 'edit_comment', $comment_id ) ) comment_footer_die( __('You are not allowed to edit this comment.') ); if ( 'trash' == $comment->comment_approved ) comment_footer_die( __('This comment is in the Trash. Please move it out of the Trash if you want to edit it.') ); $comment = get_comment_to_edit( $comment_id ); include('./edit-form-comment.php'); break; case 'delete' : case 'approve' : case 'trash' : case 'spam' : $title = __('Moderate Comment'); $comment_id = absint( $_GET['c'] ); if ( !$comment = get_comment_to_edit( $comment_id ) ) { wp_redirect( admin_url('edit-comments.php?error=1') ); die(); } if ( !current_user_can( 'edit_comment', $comment->comment_ID ) ) { wp_redirect( admin_url('edit-comments.php?error=2') ); die(); } // No need to re-approve/re-trash/re-spam a comment. if ( $action == str_replace( '1', 'approve', $comment->comment_approved ) ) { wp_redirect( admin_url( 'edit-comments.php?same=' . $comment_id ) ); die(); } require_once('./admin-header.php'); $formaction = $action . 'comment'; $nonce_action = 'approve' == $action ? 'approve-comment_' : 'delete-comment_'; $nonce_action .= $comment_id; ?> <div class='wrap'> <div class="narrow"> <?php screen_icon(); ?> <h2><?php echo esc_html( $title ); ?></h2> <?php switch ( $action ) { case 'spam' : $caution_msg = __('You are about to mark the following comment as spam:'); $button = __('Spam Comment'); break; case 'trash' : $caution_msg = __('You are about to move the following comment to the Trash:'); $button = __('Trash Comment'); break; case 'delete' : $caution_msg = __('You are about to delete the following comment:'); $button = __('Permanently Delete Comment'); break; default : $caution_msg = __('You are about to approve the following comment:'); $button = __('Approve Comment'); break; } if ( $comment->comment_approved != '0' ) { // if not unapproved $message = ''; switch ( $comment->comment_approved ) { case '1' : $message = __('This comment is currently approved.'); break; case 'spam' : $message = __('This comment is currently marked as spam.'); break; case 'trash' : $message = __('This comment is currently in the Trash.'); break; } if ( $message ) echo '<div class="updated"><p>' . $message . '</p></div>'; } ?> <p><strong><?php _e('Caution:'); ?></strong> <?php echo $caution_msg; ?></p> <table class="form-table comment-ays"> <tr class="alt"> <th scope="row"><?php _e('Author'); ?></th> <td><?php echo $comment->comment_author; ?></td> </tr> <?php if ( $comment->comment_author_email ) { ?> <tr> <th scope="row"><?php _e('E-mail'); ?></th> <td><?php echo $comment->comment_author_email; ?></td> </tr> <?php } ?> <?php if ( $comment->comment_author_url ) { ?> <tr> <th scope="row"><?php _e('URL'); ?></th> <td><a href="<?php echo $comment->comment_author_url; ?>"><?php echo $comment->comment_author_url; ?></a></td> </tr> <?php } ?> <tr> <th scope="row" valign="top"><?php /* translators: field name in comment form */ _ex('Comment', 'noun'); ?></th> <td><?php echo $comment->comment_content; ?></td> </tr> </table> <p><?php _e('Are you sure you want to do this?'); ?></p> <form action='comment.php' method='get'> <table width="100%"> <tr> <td><a class="button" href="<?php echo admin_url('edit-comments.php'); ?>"><?php esc_attr_e('No'); ?></a></td> <td class="textright"><?php submit_button( $button, 'button' ); ?></td> </tr> </table> <?php wp_nonce_field( $nonce_action ); ?> <input type='hidden' name='action' value='<?php echo esc_attr($formaction); ?>' /> <input type='hidden' name='c' value='<?php echo esc_attr($comment->comment_ID); ?>' /> <input type='hidden' name='noredir' value='1' /> </form> </div> </div> <?php break; case 'deletecomment' : case 'trashcomment' : case 'untrashcomment' : case 'spamcomment' : case 'unspamcomment' : case 'approvecomment' : case 'unapprovecomment' : $comment_id = absint( $_REQUEST['c'] ); if ( in_array( $action, array( 'approvecomment', 'unapprovecomment' ) ) ) check_admin_referer( 'approve-comment_' . $comment_id ); else check_admin_referer( 'delete-comment_' . $comment_id ); $noredir = isset($_REQUEST['noredir']); if ( !$comment = get_comment($comment_id) ) comment_footer_die( __('Oops, no comment with this ID.') . sprintf(' <a href="%s">' . __('Go back') . '</a>.', 'edit-comments.php') ); if ( !current_user_can( 'edit_comment', $comment->comment_ID ) ) comment_footer_die( __('You are not allowed to edit comments on this post.') ); if ( '' != wp_get_referer() && ! $noredir && false === strpos(wp_get_referer(), 'comment.php') ) $redir = wp_get_referer(); elseif ( '' != wp_get_original_referer() && ! $noredir ) $redir = wp_get_original_referer(); elseif ( in_array( $action, array( 'approvecomment', 'unapprovecomment' ) ) ) $redir = admin_url('edit-comments.php?p=' . absint( $comment->comment_post_ID ) ); else $redir = admin_url('edit-comments.php'); $redir = remove_query_arg( array('spammed', 'unspammed', 'trashed', 'untrashed', 'deleted', 'ids', 'approved', 'unapproved'), $redir ); switch ( $action ) { case 'deletecomment' : wp_delete_comment( $comment_id ); $redir = add_query_arg( array('deleted' => '1'), $redir ); break; case 'trashcomment' : wp_trash_comment($comment_id); $redir = add_query_arg( array('trashed' => '1', 'ids' => $comment_id), $redir ); break; case 'untrashcomment' : wp_untrash_comment($comment_id); $redir = add_query_arg( array('untrashed' => '1'), $redir ); break; case 'spamcomment' : wp_spam_comment($comment_id); $redir = add_query_arg( array('spammed' => '1', 'ids' => $comment_id), $redir ); break; case 'unspamcomment' : wp_unspam_comment($comment_id); $redir = add_query_arg( array('unspammed' => '1'), $redir ); break; case 'approvecomment' : wp_set_comment_status( $comment_id, 'approve' ); $redir = add_query_arg( array( 'approved' => 1 ), $redir ); break; case 'unapprovecomment' : wp_set_comment_status( $comment_id, 'hold' ); $redir = add_query_arg( array( 'unapproved' => 1 ), $redir ); break; } wp_redirect( $redir ); die; break; case 'editedcomment' : $comment_id = absint( $_POST['comment_ID'] ); $comment_post_id = absint( $_POST['comment_post_ID'] ); check_admin_referer( 'update-comment_' . $comment_id ); edit_comment(); $location = ( empty( $_POST['referredby'] ) ? "edit-comments.php?p=$comment_post_id" : $_POST['referredby'] ) . '#comment-' . $comment_id; $location = apply_filters( 'comment_edit_redirect', $location, $comment_id ); wp_redirect( $location ); exit(); break; default: wp_die( __('Unknown action.') ); break; } // end switch include('./admin-footer.php');
zyblog
trunk/zyblog/wp-admin/comment.php
PHP
asf20
8,846
<?php /** * Plugins administration panel. * * @package WordPress * @subpackage Administration */ /** WordPress Administration Bootstrap */ require_once('./admin.php'); if ( ! current_user_can('activate_plugins') ) wp_die( __( 'You do not have sufficient permissions to manage plugins for this site.' ) ); $wp_list_table = _get_list_table('WP_Plugins_List_Table'); $pagenum = $wp_list_table->get_pagenum(); $action = $wp_list_table->current_action(); $plugin = isset($_REQUEST['plugin']) ? $_REQUEST['plugin'] : ''; $s = isset($_REQUEST['s']) ? urlencode($_REQUEST['s']) : ''; // Clean up request URI from temporary args for screen options/paging uri's to work as expected. $_SERVER['REQUEST_URI'] = remove_query_arg(array('error', 'deleted', 'activate', 'activate-multi', 'deactivate', 'deactivate-multi', '_error_nonce'), $_SERVER['REQUEST_URI']); if ( $action ) { switch ( $action ) { case 'activate': if ( ! current_user_can('activate_plugins') ) wp_die(__('You do not have sufficient permissions to activate plugins for this site.')); if ( is_multisite() && ! is_network_admin() && is_network_only_plugin( $plugin ) ) { wp_redirect( self_admin_url("plugins.php?plugin_status=$status&paged=$page&s=$s") ); exit; } check_admin_referer('activate-plugin_' . $plugin); $result = activate_plugin($plugin, self_admin_url('plugins.php?error=true&plugin=' . $plugin), is_network_admin() ); if ( is_wp_error( $result ) ) { if ( 'unexpected_output' == $result->get_error_code() ) { $redirect = self_admin_url('plugins.php?error=true&charsout=' . strlen($result->get_error_data()) . '&plugin=' . $plugin . "&plugin_status=$status&paged=$page&s=$s"); wp_redirect(add_query_arg('_error_nonce', wp_create_nonce('plugin-activation-error_' . $plugin), $redirect)); exit; } else { wp_die($result); } } if ( ! is_network_admin() ) { $recent = (array) get_option( 'recently_activated' ); unset( $recent[ $plugin ] ); update_option( 'recently_activated', $recent ); } if ( isset($_GET['from']) && 'import' == $_GET['from'] ) { wp_redirect( self_admin_url("import.php?import=" . str_replace('-importer', '', dirname($plugin))) ); // overrides the ?error=true one above and redirects to the Imports page, stripping the -importer suffix } else { wp_redirect( self_admin_url("plugins.php?activate=true&plugin_status=$status&paged=$page&s=$s") ); // overrides the ?error=true one above } exit; break; case 'activate-selected': if ( ! current_user_can('activate_plugins') ) wp_die(__('You do not have sufficient permissions to activate plugins for this site.')); check_admin_referer('bulk-plugins'); $plugins = isset( $_POST['checked'] ) ? (array) $_POST['checked'] : array(); // Only activate plugins which are not already active. if ( is_network_admin() ) { foreach ( $plugins as $i => $plugin ) { if ( is_plugin_active_for_network( $plugin ) ) unset( $plugins[ $i ] ); } } else { foreach ( $plugins as $i => $plugin ) { if ( is_plugin_active( $plugin ) || is_network_only_plugin( $plugin ) ) unset( $plugins[ $i ] ); } } if ( empty($plugins) ) { wp_redirect( self_admin_url("plugins.php?plugin_status=$status&paged=$page&s=$s") ); exit; } activate_plugins($plugins, self_admin_url('plugins.php?error=true'), is_network_admin() ); if ( ! is_network_admin() ) { $recent = (array) get_option('recently_activated' ); foreach ( $plugins as $plugin ) unset( $recent[ $plugin ] ); update_option( 'recently_activated', $recent ); } wp_redirect( self_admin_url("plugins.php?activate-multi=true&plugin_status=$status&paged=$page&s=$s") ); exit; break; case 'update-selected' : check_admin_referer( 'bulk-plugins' ); if ( isset( $_GET['plugins'] ) ) $plugins = explode( ',', $_GET['plugins'] ); elseif ( isset( $_POST['checked'] ) ) $plugins = (array) $_POST['checked']; else $plugins = array(); $title = __( 'Update Plugins' ); $parent_file = 'plugins.php'; require_once(ABSPATH . 'wp-admin/admin-header.php'); echo '<div class="wrap">'; screen_icon(); echo '<h2>' . esc_html( $title ) . '</h2>'; $url = self_admin_url('update.php?action=update-selected&amp;plugins=' . urlencode( join(',', $plugins) )); $url = wp_nonce_url($url, 'bulk-update-plugins'); echo "<iframe src='$url' style='width: 100%; height:100%; min-height:850px;'></iframe>"; echo '</div>'; require_once(ABSPATH . 'wp-admin/admin-footer.php'); exit; break; case 'error_scrape': if ( ! current_user_can('activate_plugins') ) wp_die(__('You do not have sufficient permissions to activate plugins for this site.')); check_admin_referer('plugin-activation-error_' . $plugin); $valid = validate_plugin($plugin); if ( is_wp_error($valid) ) wp_die($valid); if ( ! WP_DEBUG ) { error_reporting( E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR ); } @ini_set('display_errors', true); //Ensure that Fatal errors are displayed. // Go back to "sandbox" scope so we get the same errors as before function plugin_sandbox_scrape( $plugin ) { include( WP_PLUGIN_DIR . '/' . $plugin ); } plugin_sandbox_scrape( $plugin ); do_action('activate_' . $plugin); exit; break; case 'deactivate': if ( ! current_user_can('activate_plugins') ) wp_die(__('You do not have sufficient permissions to deactivate plugins for this site.')); check_admin_referer('deactivate-plugin_' . $plugin); if ( ! is_network_admin() && is_plugin_active_for_network( $plugin ) ) { wp_redirect( self_admin_url("plugins.php?plugin_status=$status&paged=$page&s=$s") ); exit; } deactivate_plugins( $plugin, false, is_network_admin() ); if ( ! is_network_admin() ) update_option( 'recently_activated', array( $plugin => time() ) + (array) get_option( 'recently_activated' ) ); if ( headers_sent() ) echo "<meta http-equiv='refresh' content='" . esc_attr( "0;url=plugins.php?deactivate=true&plugin_status=$status&paged=$page&s=$s" ) . "' />"; else wp_redirect( self_admin_url("plugins.php?deactivate=true&plugin_status=$status&paged=$page&s=$s") ); exit; break; case 'deactivate-selected': if ( ! current_user_can('activate_plugins') ) wp_die(__('You do not have sufficient permissions to deactivate plugins for this site.')); check_admin_referer('bulk-plugins'); $plugins = isset( $_POST['checked'] ) ? (array) $_POST['checked'] : array(); // Do not deactivate plugins which are already deactivated. if ( is_network_admin() ) { $plugins = array_filter( $plugins, 'is_plugin_active_for_network' ); } else { $plugins = array_filter( $plugins, 'is_plugin_active' ); $plugins = array_diff( $plugins, array_filter( $plugins, 'is_plugin_active_for_network' ) ); } if ( empty($plugins) ) { wp_redirect( self_admin_url("plugins.php?plugin_status=$status&paged=$page&s=$s") ); exit; } deactivate_plugins( $plugins, false, is_network_admin() ); if ( ! is_network_admin() ) { $deactivated = array(); foreach ( $plugins as $plugin ) $deactivated[ $plugin ] = time(); update_option( 'recently_activated', $deactivated + (array) get_option( 'recently_activated' ) ); } wp_redirect( self_admin_url("plugins.php?deactivate-multi=true&plugin_status=$status&paged=$page&s=$s") ); exit; break; case 'delete-selected': if ( ! current_user_can('delete_plugins') ) wp_die(__('You do not have sufficient permissions to delete plugins for this site.')); check_admin_referer('bulk-plugins'); //$_POST = from the plugin form; $_GET = from the FTP details screen. $plugins = isset( $_REQUEST['checked'] ) ? (array) $_REQUEST['checked'] : array(); if ( empty( $plugins ) ) { wp_redirect( self_admin_url("plugins.php?plugin_status=$status&paged=$page&s=$s") ); exit; } $plugins = array_filter($plugins, 'is_plugin_inactive'); // Do not allow to delete Activated plugins. if ( empty( $plugins ) ) { wp_redirect( self_admin_url( "plugins.php?error=true&main=true&plugin_status=$status&paged=$page&s=$s" ) ); exit; } include(ABSPATH . 'wp-admin/update.php'); $parent_file = 'plugins.php'; if ( ! isset($_REQUEST['verify-delete']) ) { wp_enqueue_script('jquery'); require_once(ABSPATH . 'wp-admin/admin-header.php'); ?> <div class="wrap"> <?php $files_to_delete = $plugin_info = array(); $have_non_network_plugins = false; foreach ( (array) $plugins as $plugin ) { if ( '.' == dirname($plugin) ) { $files_to_delete[] = WP_PLUGIN_DIR . '/' . $plugin; if( $data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin) ) { $plugin_info[ $plugin ] = $data; $plugin_info[ $plugin ]['is_uninstallable'] = is_uninstallable_plugin( $plugin ); if ( ! $plugin_info[ $plugin ]['Network'] ) $have_non_network_plugins = true; } } else { // Locate all the files in that folder $files = list_files( WP_PLUGIN_DIR . '/' . dirname($plugin) ); if ( $files ) { $files_to_delete = array_merge($files_to_delete, $files); } // Get plugins list from that folder if ( $folder_plugins = get_plugins( '/' . dirname($plugin)) ) { foreach( $folder_plugins as $plugin_file => $data ) { $plugin_info[ $plugin_file ] = _get_plugin_data_markup_translate( $plugin_file, $data ); $plugin_info[ $plugin_file ]['is_uninstallable'] = is_uninstallable_plugin( $plugin ); if ( ! $plugin_info[ $plugin_file ]['Network'] ) $have_non_network_plugins = true; } } } } screen_icon(); $plugins_to_delete = count( $plugin_info ); echo '<h2>' . _n( 'Delete Plugin', 'Delete Plugins', $plugins_to_delete ) . '</h2>'; ?> <?php if ( $have_non_network_plugins && is_network_admin() ) : ?> <div class="error"><p><strong><?php _e( 'Caution:' ); ?></strong> <?php echo _n( 'This plugin may be active on other sites in the network.', 'These plugins may be active on other sites in the network.', $plugins_to_delete ); ?></p></div> <?php endif; ?> <p><?php echo _n( 'You are about to remove the following plugin:', 'You are about to remove the following plugins:', $plugins_to_delete ); ?></p> <ul class="ul-disc"> <?php $data_to_delete = false; foreach ( $plugin_info as $plugin ) { if ( $plugin['is_uninstallable'] ) { /* translators: 1: plugin name, 2: plugin author */ echo '<li>', sprintf( __( '<strong>%1$s</strong> by <em>%2$s</em> (will also <strong>delete its data</strong>)' ), esc_html($plugin['Name']), esc_html($plugin['AuthorName']) ), '</li>'; $data_to_delete = true; } else { /* translators: 1: plugin name, 2: plugin author */ echo '<li>', sprintf( __('<strong>%1$s</strong> by <em>%2$s</em>' ), esc_html($plugin['Name']), esc_html($plugin['AuthorName']) ), '</li>'; } } ?> </ul> <p><?php if ( $data_to_delete ) _e('Are you sure you wish to delete these files and data?'); else _e('Are you sure you wish to delete these files?'); ?></p> <form method="post" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" style="display:inline;"> <input type="hidden" name="verify-delete" value="1" /> <input type="hidden" name="action" value="delete-selected" /> <?php foreach ( (array) $plugins as $plugin ) echo '<input type="hidden" name="checked[]" value="' . esc_attr($plugin) . '" />'; ?> <?php wp_nonce_field('bulk-plugins') ?> <?php submit_button( $data_to_delete ? __( 'Yes, Delete these files and data' ) : __( 'Yes, Delete these files' ), 'button', 'submit', false ); ?> </form> <form method="post" action="<?php echo esc_url(wp_get_referer()); ?>" style="display:inline;"> <?php submit_button( __( 'No, Return me to the plugin list' ), 'button', 'submit', false ); ?> </form> <p><a href="#" onclick="jQuery('#files-list').toggle(); return false;"><?php _e('Click to view entire list of files which will be deleted'); ?></a></p> <div id="files-list" style="display:none;"> <ul class="code"> <?php foreach ( (array)$files_to_delete as $file ) echo '<li>' . esc_html(str_replace(WP_PLUGIN_DIR, '', $file)) . '</li>'; ?> </ul> </div> </div> <?php require_once(ABSPATH . 'wp-admin/admin-footer.php'); exit; } //Endif verify-delete $delete_result = delete_plugins($plugins); set_transient('plugins_delete_result_' . $user_ID, $delete_result); //Store the result in a cache rather than a URL param due to object type & length wp_redirect( self_admin_url("plugins.php?deleted=true&plugin_status=$status&paged=$page&s=$s") ); exit; break; case 'clear-recent-list': if ( ! is_network_admin() ) update_option( 'recently_activated', array() ); break; } } $wp_list_table->prepare_items(); wp_enqueue_script('plugin-install'); add_thickbox(); add_screen_option( 'per_page', array('label' => _x( 'Plugins', 'plugins per page (screen options)' ), 'default' => 999 ) ); get_current_screen()->add_help_tab( array( 'id' => 'overview', 'title' => __('Overview'), 'content' => '<p>' . __('Plugins extend and expand the functionality of WordPress. Once a plugin is installed, you may activate it or deactivate it here.') . '</p>' . '<p>' . sprintf(__('You can find additional plugins for your site by using the <a href="%1$s">Plugin Browser/Installer</a> functionality or by browsing the <a href="%2$s" target="_blank">WordPress Plugin Directory</a> directly and installing new plugins manually. To manually install a plugin you generally just need to upload the plugin file into your <code>/wp-content/plugins</code> directory. Once a plugin has been installed, you can activate it here.'), 'plugin-install.php', 'http://wordpress.org/extend/plugins/') . '</p>' ) ); get_current_screen()->add_help_tab( array( 'id' => 'compatibility-problems', 'title' => __('Troubleshooting'), 'content' => '<p>' . __('Most of the time, plugins play nicely with the core of WordPress and with other plugins. Sometimes, though, a plugin&#8217;s code will get in the way of another plugin, causing compatibility issues. If your site starts doing strange things, this may be the problem. Try deactivating all your plugins and re-activating them in various combinations until you isolate which one(s) caused the issue.') . '</p>' . '<p>' . sprintf( __('If something goes wrong with a plugin and you can&#8217;t use WordPress, delete or rename that file in the <code>%s</code> directory and it will be automatically deactivated.'), WP_PLUGIN_DIR) . '</p>' ) ); get_current_screen()->set_help_sidebar( '<p><strong>' . __('For more information:') . '</strong></p>' . '<p>' . __('<a href="http://codex.wordpress.org/Managing_Plugins#Plugin_Management" target="_blank">Documentation on Managing Plugins</a>') . '</p>' . '<p>' . __('<a href="http://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>' ); $title = __('Plugins'); $parent_file = 'plugins.php'; require_once(ABSPATH . 'wp-admin/admin-header.php'); $invalid = validate_active_plugins(); if ( !empty($invalid) ) foreach ( $invalid as $plugin_file => $error ) echo '<div id="message" class="error"><p>' . sprintf(__('The plugin <code>%s</code> has been <strong>deactivated</strong> due to an error: %s'), esc_html($plugin_file), $error->get_error_message()) . '</p></div>'; ?> <?php if ( isset($_GET['error']) ) : if ( isset( $_GET['main'] ) ) $errmsg = __( 'You cannot delete a plugin while it is active on the main site.' ); elseif ( isset($_GET['charsout']) ) $errmsg = sprintf(__('The plugin generated %d characters of <strong>unexpected output</strong> during activation. If you notice &#8220;headers already sent&#8221; messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.'), $_GET['charsout']); else $errmsg = __('Plugin could not be activated because it triggered a <strong>fatal error</strong>.'); ?> <div id="message" class="updated"><p><?php echo $errmsg; ?></p> <?php if ( !isset( $_GET['main'] ) && !isset($_GET['charsout']) && wp_verify_nonce($_GET['_error_nonce'], 'plugin-activation-error_' . $plugin) ) { ?> <iframe style="border:0" width="100%" height="70px" src="<?php echo 'plugins.php?action=error_scrape&amp;plugin=' . esc_attr($plugin) . '&amp;_wpnonce=' . esc_attr($_GET['_error_nonce']); ?>"></iframe> <?php } ?> </div> <?php elseif ( isset($_GET['deleted']) ) : $delete_result = get_transient('plugins_delete_result_'.$user_ID); delete_transient('plugins_delete_result'); //Delete it once we're done. if ( is_wp_error($delete_result) ) : ?> <div id="message" class="updated"><p><?php printf( __('Plugin could not be deleted due to an error: %s'), $delete_result->get_error_message() ); ?></p></div> <?php else : ?> <div id="message" class="updated"><p><?php _e('The selected plugins have been <strong>deleted</strong>.'); ?></p></div> <?php endif; ?> <?php elseif ( isset($_GET['activate']) ) : ?> <div id="message" class="updated"><p><?php _e('Plugin <strong>activated</strong>.') ?></p></div> <?php elseif (isset($_GET['activate-multi'])) : ?> <div id="message" class="updated"><p><?php _e('Selected plugins <strong>activated</strong>.'); ?></p></div> <?php elseif ( isset($_GET['deactivate']) ) : ?> <div id="message" class="updated"><p><?php _e('Plugin <strong>deactivated</strong>.') ?></p></div> <?php elseif (isset($_GET['deactivate-multi'])) : ?> <div id="message" class="updated"><p><?php _e('Selected plugins <strong>deactivated</strong>.'); ?></p></div> <?php elseif ( 'update-selected' == $action ) : ?> <div id="message" class="updated"><p><?php _e('No out of date plugins were selected.'); ?></p></div> <?php endif; ?> <div class="wrap"> <?php screen_icon(); ?> <h2><?php echo esc_html( $title ); if ( ( ! is_multisite() || is_network_admin() ) && current_user_can('install_plugins') ) { ?> <a href="<?php echo self_admin_url( 'plugin-install.php' ); ?>" class="add-new-h2"><?php echo esc_html_x('Add New', 'plugin'); ?></a> <?php } if ( $s ) printf( '<span class="subtitle">' . __('Search results for &#8220;%s&#8221;') . '</span>', esc_html( $s ) ); ?> </h2> <?php do_action( 'pre_current_active_plugins', $plugins['all'] ) ?> <?php $wp_list_table->views(); ?> <form method="get" action=""> <?php $wp_list_table->search_box( __( 'Search Installed Plugins' ), 'plugin' ); ?> </form> <form method="post" action=""> <input type="hidden" name="plugin_status" value="<?php echo esc_attr($status) ?>" /> <input type="hidden" name="paged" value="<?php echo esc_attr($page) ?>" /> <?php $wp_list_table->display(); ?> </form> </div> <?php include(ABSPATH . 'wp-admin/admin-footer.php');
zyblog
trunk/zyblog/wp-admin/plugins.php
PHP
asf20
19,111
<?php /** * Dashboard Administration Screen * * @internal This file should be parseable by PHP4. * * @package WordPress * @subpackage Administration */ /** Load WordPress Bootstrap */ require_once('./admin.php'); /** Load WordPress dashboard API */ require_once(ABSPATH . 'wp-admin/includes/dashboard.php'); wp_dashboard_setup(); wp_enqueue_script( 'dashboard' ); if ( current_user_can( 'edit_theme_options' ) ) wp_enqueue_script( 'customize-loader' ); if ( current_user_can( 'install_plugins' ) ) wp_enqueue_script( 'plugin-install' ); if ( current_user_can( 'upload_files' ) ) wp_enqueue_script( 'media-upload' ); add_thickbox(); if ( wp_is_mobile() ) wp_enqueue_script( 'jquery-touch-punch' ); $title = __('Dashboard'); $parent_file = 'index.php'; if ( is_user_admin() ) add_screen_option('layout_columns', array('max' => 4, 'default' => 1) ); else add_screen_option('layout_columns', array('max' => 4, 'default' => 2) ); $help = '<p>' . __( 'Welcome to your WordPress Dashboard! This is the screen you will see when you log in to your site, and gives you access to all the site management features of WordPress. You can get help for any screen by clicking the Help tab in the upper corner.' ) . '</p>'; // Not using chaining here, so as to be parseable by PHP4. $screen = get_current_screen(); $screen->add_help_tab( array( 'id' => 'overview', 'title' => __( 'Overview' ), 'content' => $help, ) ); // Help tabs $help = '<p>' . __('The left-hand navigation menu provides links to all of the WordPress administration screens, with submenu items displayed on hover. You can minimize this menu to a narrow icon strip by clicking on the Collapse Menu arrow at the bottom.') . '</p>'; $help .= '<p>' . __('Links in the Toolbar at the top of the screen connect your dashboard and the front end of your site, and provide access to your profile and helpful WordPress information.') . '</p>'; $screen->add_help_tab( array( 'id' => 'help-navigation', 'title' => __('Navigation'), 'content' => $help, ) ); $help = '<p>' . __('You can use the following controls to arrange your Dashboard screen to suit your workflow. This is true on most other administration screens as well.') . '</p>'; $help .= '<p>' . __('<strong>Screen Options</strong> - Use the Screen Options tab to choose which Dashboard boxes to show, and how many columns to display.') . '</p>'; $help .= '<p>' . __('<strong>Drag and Drop</strong> - To rearrange the boxes, drag and drop by clicking on the title bar of the selected box and releasing when you see a gray dotted-line rectangle appear in the location you want to place the box.') . '</p>'; $help .= '<p>' . __('<strong>Box Controls</strong> - Click the title bar of the box to expand or collapse it. In addition, some boxes have configurable content, and will show a &#8220;Configure&#8221; link in the title bar if you hover over it.') . '</p>'; $screen->add_help_tab( array( 'id' => 'help-layout', 'title' => __('Layout'), 'content' => $help, ) ); $help = '<p>' . __('The boxes on your Dashboard screen are:') . '</p>'; if ( current_user_can( 'edit_posts' ) ) $help .= '<p>' . __('<strong>Right Now</strong> - Displays a summary of the content on your site and identifies which theme and version of WordPress you are using.') . '</p>'; if ( current_user_can( 'moderate_comments' ) ) $help .= '<p>' . __('<strong>Recent Comments</strong> - Shows the most recent comments on your posts (configurable, up to 30) and allows you to moderate them.') . '</p>'; if ( current_user_can( 'publish_posts' ) ) $help .= '<p>' . __('<strong>Incoming Links</strong> - Shows links to your site found by Google Blog Search.') . '</p>'; if ( current_user_can( get_post_type_object( 'post' )->cap->create_posts ) ) { $help .= '<p>' . __('<strong>QuickPress</strong> - Allows you to create a new post and either publish it or save it as a draft.') . '</p>'; $help .= '<p>' . __('<strong>Recent Drafts</strong> - Displays links to the 5 most recent draft posts you&#8217;ve started.') . '</p>'; } $help .= '<p>' . __('<strong>WordPress Blog</strong> - Latest news from the official WordPress project.') . '</p>'; $help .= '<p>' . __('<strong>Other WordPress News</strong> - Shows the <a href="http://planet.wordpress.org" target="_blank">WordPress Planet</a> feed. You can configure it to show a different feed of your choosing.') . '</p>'; if ( ! is_multisite() && current_user_can( 'install_plugins' ) ) $help .= '<p>' . __('<strong>Plugins</strong> - Features the most popular, newest, and recently updated plugins from the WordPress.org Plugin Directory.') . '</p>'; if ( current_user_can( 'edit_theme_options' ) ) $help .= '<p>' . __('<strong>Welcome</strong> - Shows links for some of the most common tasks when setting up a new site.') . '</p>'; $screen->add_help_tab( array( 'id' => 'help-content', 'title' => __('Content'), 'content' => $help, ) ); unset( $help ); $screen->set_help_sidebar( '<p><strong>' . __( 'For more information:' ) . '</strong></p>' . '<p>' . __( '<a href="http://codex.wordpress.org/Dashboard_Screen" target="_blank">Documentation on Dashboard</a>' ) . '</p>' . '<p>' . __( '<a href="http://wordpress.org/support/" target="_blank">Support Forums</a>' ) . '</p>' ); include (ABSPATH . 'wp-admin/admin-header.php'); $today = current_time('mysql', 1); ?> <div class="wrap"> <?php screen_icon(); ?> <h2><?php echo esc_html( $title ); ?></h2> <?php if ( has_action( 'welcome_panel' ) && current_user_can( 'edit_theme_options' ) ) : $classes = 'welcome-panel'; $option = get_user_meta( get_current_user_id(), 'show_welcome_panel', true ); // 0 = hide, 1 = toggled to show or single site creator, 2 = multisite site owner $hide = 0 == $option || ( 2 == $option && wp_get_current_user()->user_email != get_option( 'admin_email' ) ); if ( $hide ) $classes .= ' hidden'; ?> <div id="welcome-panel" class="<?php echo esc_attr( $classes ); ?>"> <?php wp_nonce_field( 'welcome-panel-nonce', 'welcomepanelnonce', false ); ?> <a class="welcome-panel-close" href="<?php echo esc_url( admin_url( '?welcome=0' ) ); ?>"><?php _e( 'Dismiss' ); ?></a> <?php do_action( 'welcome_panel' ); ?> </div> <?php endif; ?> <div id="dashboard-widgets-wrap"> <?php wp_dashboard(); ?> <div class="clear"></div> </div><!-- dashboard-widgets-wrap --> </div><!-- wrap --> <?php require(ABSPATH . 'wp-admin/admin-footer.php'); ?>
zyblog
trunk/zyblog/wp-admin/index.php
PHP
asf20
6,436
<?php /** * Bootstrap file for setting the ABSPATH constant * and loading the wp-config.php file. The wp-config.php * file will then load the wp-settings.php file, which * will then set up the WordPress environment. * * If the wp-config.php file is not found then an error * will be displayed asking the visitor to set up the * wp-config.php file. * * Will also search for wp-config.php in WordPress' parent * directory to allow the WordPress directory to remain * untouched. * * @internal This file must be parsable by PHP4. * * @package WordPress */ /** Define ABSPATH as this file's directory */ define( 'ABSPATH', dirname(__FILE__) . '/' ); error_reporting( E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR ); if ( file_exists( ABSPATH . 'wp-config.php') ) { /** The config file resides in ABSPATH */ require_once( ABSPATH . 'wp-config.php' ); } elseif ( file_exists( dirname(ABSPATH) . '/wp-config.php' ) && ! file_exists( dirname(ABSPATH) . '/wp-settings.php' ) ) { /** The config file resides one level above ABSPATH but is not part of another install */ require_once( dirname(ABSPATH) . '/wp-config.php' ); } else { // A config file doesn't exist // Set a path for the link to the installer if ( strpos($_SERVER['PHP_SELF'], 'wp-admin') !== false ) $path = 'setup-config.php'; else $path = 'wp-admin/setup-config.php'; define( 'WPINC', 'wp-includes' ); define( 'WP_CONTENT_DIR', ABSPATH . 'wp-content' ); require_once( ABSPATH . WPINC . '/load.php' ); require_once( ABSPATH . WPINC . '/version.php' ); wp_check_php_mysql_versions(); wp_load_translations_early(); require_once( ABSPATH . WPINC . '/functions.php' ); // Die with an error message $die = __( "There doesn't seem to be a <code>wp-config.php</code> file. I need this before we can get started." ) . '</p>'; $die .= '<p>' . __( "Need more help? <a href='http://codex.wordpress.org/Editing_wp-config.php'>We got it</a>." ) . '</p>'; $die .= '<p>' . __( "You can create a <code>wp-config.php</code> file through a web interface, but this doesn't work for all server setups. The safest way is to manually create the file." ) . '</p>'; $die .= '<p><a href="' . $path . '" class="button button-large">' . __( "Create a Configuration File" ) . '</a>'; wp_die( $die, __( 'WordPress &rsaquo; Error' ) ); }
zyblog
trunk/zyblog/wp-load.php
PHP
asf20
2,408
<?php /** * Used to set up and fix common variables and include * the WordPress procedural and class library. * * Allows for some configuration in wp-config.php (see default-constants.php) * * @internal This file must be parsable by PHP4. * * @package WordPress */ /** * Stores the location of the WordPress directory of functions, classes, and core content. * * @since 1.0.0 */ define( 'WPINC', 'wp-includes' ); // Include files required for initialization. require( ABSPATH . WPINC . '/load.php' ); require( ABSPATH . WPINC . '/default-constants.php' ); require( ABSPATH . WPINC . '/version.php' ); // Set initial default constants including WP_MEMORY_LIMIT, WP_MAX_MEMORY_LIMIT, WP_DEBUG, WP_CONTENT_DIR and WP_CACHE. wp_initial_constants( ); // Check for the required PHP version and for the MySQL extension or a database drop-in. wp_check_php_mysql_versions(); // Disable magic quotes at runtime. Magic quotes are added using wpdb later in wp-settings.php. @ini_set( 'magic_quotes_runtime', 0 ); @ini_set( 'magic_quotes_sybase', 0 ); // WordPress calculates offsets from UTC. date_default_timezone_set( 'UTC' ); // Turn register_globals off. wp_unregister_GLOBALS(); // Standardize $_SERVER variables across setups. wp_fix_server_vars(); // Check if we have received a request due to missing favicon.ico wp_favicon_request(); // Check if we're in maintenance mode. wp_maintenance(); // Start loading timer. timer_start(); // Check if we're in WP_DEBUG mode. wp_debug_mode(); // For an advanced caching plugin to use. Uses a static drop-in because you would only want one. if ( WP_CACHE ) WP_DEBUG ? include( WP_CONTENT_DIR . '/advanced-cache.php' ) : @include( WP_CONTENT_DIR . '/advanced-cache.php' ); // Define WP_LANG_DIR if not set. wp_set_lang_dir(); // Load early WordPress files. require( ABSPATH . WPINC . '/compat.php' ); require( ABSPATH . WPINC . '/functions.php' ); require( ABSPATH . WPINC . '/class-wp.php' ); require( ABSPATH . WPINC . '/class-wp-error.php' ); require( ABSPATH . WPINC . '/plugin.php' ); require( ABSPATH . WPINC . '/pomo/mo.php' ); // Include the wpdb class and, if present, a db.php database drop-in. require_wp_db(); // Set the database table prefix and the format specifiers for database table columns. $GLOBALS['table_prefix'] = $table_prefix; wp_set_wpdb_vars(); // Start the WordPress object cache, or an external object cache if the drop-in is present. wp_start_object_cache(); // Attach the default filters. require( ABSPATH . WPINC . '/default-filters.php' ); // Initialize multisite if enabled. if ( is_multisite() ) { require( ABSPATH . WPINC . '/ms-blogs.php' ); require( ABSPATH . WPINC . '/ms-settings.php' ); } elseif ( ! defined( 'MULTISITE' ) ) { define( 'MULTISITE', false ); } register_shutdown_function( 'shutdown_action_hook' ); // Stop most of WordPress from being loaded if we just want the basics. if ( SHORTINIT ) return false; // Load the L10n library. require_once( ABSPATH . WPINC . '/l10n.php' ); // Run the installer if WordPress is not installed. wp_not_installed(); // Load most of WordPress. require( ABSPATH . WPINC . '/class-wp-walker.php' ); require( ABSPATH . WPINC . '/class-wp-ajax-response.php' ); require( ABSPATH . WPINC . '/formatting.php' ); require( ABSPATH . WPINC . '/capabilities.php' ); require( ABSPATH . WPINC . '/query.php' ); require( ABSPATH . WPINC . '/theme.php' ); require( ABSPATH . WPINC . '/class-wp-theme.php' ); require( ABSPATH . WPINC . '/template.php' ); require( ABSPATH . WPINC . '/user.php' ); require( ABSPATH . WPINC . '/meta.php' ); require( ABSPATH . WPINC . '/general-template.php' ); require( ABSPATH . WPINC . '/link-template.php' ); require( ABSPATH . WPINC . '/author-template.php' ); require( ABSPATH . WPINC . '/post.php' ); require( ABSPATH . WPINC . '/post-template.php' ); require( ABSPATH . WPINC . '/post-thumbnail-template.php' ); require( ABSPATH . WPINC . '/category.php' ); require( ABSPATH . WPINC . '/category-template.php' ); require( ABSPATH . WPINC . '/comment.php' ); require( ABSPATH . WPINC . '/comment-template.php' ); require( ABSPATH . WPINC . '/rewrite.php' ); require( ABSPATH . WPINC . '/feed.php' ); require( ABSPATH . WPINC . '/bookmark.php' ); require( ABSPATH . WPINC . '/bookmark-template.php' ); require( ABSPATH . WPINC . '/kses.php' ); require( ABSPATH . WPINC . '/cron.php' ); require( ABSPATH . WPINC . '/deprecated.php' ); require( ABSPATH . WPINC . '/script-loader.php' ); require( ABSPATH . WPINC . '/taxonomy.php' ); require( ABSPATH . WPINC . '/update.php' ); require( ABSPATH . WPINC . '/canonical.php' ); require( ABSPATH . WPINC . '/shortcodes.php' ); require( ABSPATH . WPINC . '/class-wp-embed.php' ); require( ABSPATH . WPINC . '/media.php' ); require( ABSPATH . WPINC . '/http.php' ); require( ABSPATH . WPINC . '/class-http.php' ); require( ABSPATH . WPINC . '/widgets.php' ); require( ABSPATH . WPINC . '/nav-menu.php' ); require( ABSPATH . WPINC . '/nav-menu-template.php' ); require( ABSPATH . WPINC . '/admin-bar.php' ); // Load multisite-specific files. if ( is_multisite() ) { require( ABSPATH . WPINC . '/ms-functions.php' ); require( ABSPATH . WPINC . '/ms-default-filters.php' ); require( ABSPATH . WPINC . '/ms-deprecated.php' ); } // Define constants that rely on the API to obtain the default value. // Define must-use plugin directory constants, which may be overridden in the sunrise.php drop-in. wp_plugin_directory_constants( ); // Load must-use plugins. foreach ( wp_get_mu_plugins() as $mu_plugin ) { include_once( $mu_plugin ); } unset( $mu_plugin ); // Load network activated plugins. if ( is_multisite() ) { foreach( wp_get_active_network_plugins() as $network_plugin ) { include_once( $network_plugin ); } unset( $network_plugin ); } do_action( 'muplugins_loaded' ); if ( is_multisite() ) ms_cookie_constants( ); // Define constants after multisite is loaded. Cookie-related constants may be overridden in ms_network_cookies(). wp_cookie_constants( ); // Define and enforce our SSL constants wp_ssl_constants( ); // Create common globals. require( ABSPATH . WPINC . '/vars.php' ); // Make taxonomies and posts available to plugins and themes. // @plugin authors: warning: these get registered again on the init hook. create_initial_taxonomies(); create_initial_post_types(); // Register the default theme directory root register_theme_directory( get_theme_root() ); // Load active plugins. foreach ( wp_get_active_and_valid_plugins() as $plugin ) include_once( $plugin ); unset( $plugin ); // Load pluggable functions. require( ABSPATH . WPINC . '/pluggable.php' ); require( ABSPATH . WPINC . '/pluggable-deprecated.php' ); // Set internal encoding. wp_set_internal_encoding(); // Run wp_cache_postload() if object cache is enabled and the function exists. if ( WP_CACHE && function_exists( 'wp_cache_postload' ) ) wp_cache_postload(); do_action( 'plugins_loaded' ); // Define constants which affect functionality if not already defined. wp_functionality_constants( ); // Add magic quotes and set up $_REQUEST ( $_GET + $_POST ) wp_magic_quotes(); do_action( 'sanitize_comment_cookies' ); /** * WordPress Query object * @global object $wp_the_query * @since 2.0.0 */ $wp_the_query = new WP_Query(); /** * Holds the reference to @see $wp_the_query * Use this global for WordPress queries * @global object $wp_query * @since 1.5.0 */ $wp_query = $wp_the_query; /** * Holds the WordPress Rewrite object for creating pretty URLs * @global object $wp_rewrite * @since 1.5.0 */ $GLOBALS['wp_rewrite'] = new WP_Rewrite(); /** * WordPress Object * @global object $wp * @since 2.0.0 */ $wp = new WP(); /** * WordPress Widget Factory Object * @global object $wp_widget_factory * @since 2.8.0 */ $GLOBALS['wp_widget_factory'] = new WP_Widget_Factory(); /** * WordPress User Roles * @global object $wp_roles * @since 2.0.0 */ $GLOBALS['wp_roles'] = new WP_Roles(); do_action( 'setup_theme' ); // Define the template related constants. wp_templating_constants( ); // Load the default text localization domain. load_default_textdomain(); $locale = get_locale(); $locale_file = WP_LANG_DIR . "/$locale.php"; if ( ( 0 === validate_file( $locale ) ) && is_readable( $locale_file ) ) require( $locale_file ); unset( $locale_file ); // Pull in locale data after loading text domain. require_once( ABSPATH . WPINC . '/locale.php' ); /** * WordPress Locale object for loading locale domain date and various strings. * @global object $wp_locale * @since 2.1.0 */ $GLOBALS['wp_locale'] = new WP_Locale(); // Load the functions for the active theme, for both parent and child theme if applicable. if ( ! defined( 'WP_INSTALLING' ) || 'wp-activate.php' === $pagenow ) { if ( TEMPLATEPATH !== STYLESHEETPATH && file_exists( STYLESHEETPATH . '/functions.php' ) ) include( STYLESHEETPATH . '/functions.php' ); if ( file_exists( TEMPLATEPATH . '/functions.php' ) ) include( TEMPLATEPATH . '/functions.php' ); } do_action( 'after_setup_theme' ); // Set up current user. $wp->init(); /** * Most of WP is loaded at this stage, and the user is authenticated. WP continues * to load on the init hook that follows (e.g. widgets), and many plugins instantiate * themselves on it for all sorts of reasons (e.g. they need a user, a taxonomy, etc.). * * If you wish to plug an action once WP is loaded, use the wp_loaded hook below. */ do_action( 'init' ); // Check site status if ( is_multisite() ) { if ( true !== ( $file = ms_site_check() ) ) { require( $file ); die(); } unset($file); } /** * This hook is fired once WP, all plugins, and the theme are fully loaded and instantiated. * * AJAX requests should use wp-admin/admin-ajax.php. admin-ajax.php can handle requests for * users not logged in. * * @link http://codex.wordpress.org/AJAX_in_Plugins * * @since 3.0.0 */ do_action('wp_loaded');
zyblog
trunk/zyblog/wp-settings.php
PHP
asf20
9,899
<?php /** * Outputs the OPML XML format for getting the links defined in the link * administration. This can be used to export links from one blog over to * another. Links aren't exported by the WordPress export, so this file handles * that. * * This file is not added by default to WordPress theme pages when outputting * feed links. It will have to be added manually for browsers and users to pick * up that this file exists. * * @package WordPress */ require_once('./wp-load.php'); header('Content-Type: text/xml; charset=' . get_option('blog_charset'), true); $link_cat = ''; if ( !empty($_GET['link_cat']) ) { $link_cat = $_GET['link_cat']; if ( !in_array($link_cat, array('all', '0')) ) $link_cat = absint( (string)urldecode($link_cat) ); } echo '<?xml version="1.0"?'.">\n"; ?> <opml version="1.0"> <head> <title><?php printf( __('Links for %s'), esc_attr(get_bloginfo('name', 'display')) ); ?></title> <dateCreated><?php echo gmdate("D, d M Y H:i:s"); ?> GMT</dateCreated> <?php do_action('opml_head'); ?> </head> <body> <?php if ( empty($link_cat) ) $cats = get_categories(array('taxonomy' => 'link_category', 'hierarchical' => 0)); else $cats = get_categories(array('taxonomy' => 'link_category', 'hierarchical' => 0, 'include' => $link_cat)); foreach ( (array)$cats as $cat ) : $catname = apply_filters('link_category', $cat->name); ?> <outline type="category" title="<?php echo esc_attr($catname); ?>"> <?php $bookmarks = get_bookmarks(array("category" => $cat->term_id)); foreach ( (array)$bookmarks as $bookmark ) : $title = apply_filters('link_title', $bookmark->link_name); ?> <outline text="<?php echo esc_attr($title); ?>" type="link" xmlUrl="<?php echo esc_attr($bookmark->link_rss); ?>" htmlUrl="<?php echo esc_attr($bookmark->link_url); ?>" updated="<?php if ('0000-00-00 00:00:00' != $bookmark->link_updated) echo $bookmark->link_updated; ?>" /> <?php endforeach; // $bookmarks ?> </outline> <?php endforeach; // $cats ?> </body> </opml>
zyblog
trunk/zyblog/wp-links-opml.php
PHP
asf20
1,997
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>WordPress &#8250; 说明</title> <link rel="stylesheet" href="wp-admin/css/install.css?ver=20100228" type="text/css" /> </head> <body> <h1 id="logo"> <a href="http://wordpress.org/"><img alt="WordPress" src="wp-admin/images/wordpress-logo.png" /></a> <br /> 3.5 版本 </h1> <p style="text-align: center">优美的个人信息发布平台</p> <h1>写在最前</h1> <p>欢迎。WordPress 对我来说是一个具有特殊意义的项目。大家都能为 WordPress 添砖加瓦,因此作为其中一员我十分自豪。开发者和贡献者为 WordPress 奉献了难以估量的时间,我们都在致力于让 WordPress 更加优秀。现在,感谢您也参与其中。</p> <p style="text-align: right">&#8212; Matt Mullenweg</p> <h1>安装:著名的五分钟安装</h1> <ol> <li>将 WordPress 压缩包解压至一个空文件夹,并上传它。</li> <li>在浏览器中访问 <span class="file"><a href="wp-admin/install.php">wp-admin/install.php</a></span>。它将帮助您把数据库链接信息写入到 <code>wp-config.php</code> 文件中。 <ol> <li>如果上述方法无效,也没关系,这很正常。请用文本编辑器(如写字板)手动打开 <code>wp-config-sample.php</code> 文件,填入数据库信息。</li> <li>将文件另存为 <code>wp-config.php</code> 并上传。</li> <li>在浏览器中访问 <span class="file"><a href="wp-admin/install.php">wp-admin/install.php</a></span>。</li> </ol> </li> <li>在配置文件就绪之后,WordPress 会自动尝试建立数据库表。若发生错误,请检查 <code>wp-config.php</code> 文件中填写的信息是否准确,然后再试。若问题依然存在,请访问<a href="http://zh-cn.forums.wordpress.org/" title="WordPress 支持论坛">中文支持论坛</a>寻求帮助。</li> <li><strong>若您不设置密码,请牢记生成的随机密码。</strong>若您不输入用户名,用户名将是 <code>admin</code>。</li> <li>完成后,安装向导会带您到<a href="wp-login.php">登录页面</a>。用刚刚设置的用户名和密码登录。若您使用随机密码,在登录后可以按照页面提示修改密码。</li> </ol> <h1>升级</h1> <h2>自动升级</h2> <p>若您正在使用 WordPress 2.7 或以上版本,您可使用内置的自动升级工具进行升级:</p> <ol> <li>在浏览器中打开 <span class="file"><a href="wp-admin/update-core.php">wp-admin/update-core.php</a></span>,按照提示操作。</li> <li>还有别的步骤么 —— 没了!</li> </ol> <h2>手动升级</h2> <ol> <li>在升级之前,请确保备份旧有数据以及被您修改过的文件,例如 <code>index.php</code>。</li> <li>删除旧版程序文件,记得备份修改过的内容。</li> <li>上传新版程序文件。</li> <li>在浏览器中访问 <span class="file"><a href="wp-admin/upgrade.php">/wp-admin/upgrade.php</a>。</span></li> </ol> <h2>模板结构变化</h2> <p>如果您曾自己制作或者修改主题,可能您需要做一些修改以使模板在跨版本更新后正常工作。</p> <h1>从其他内容管理系统“搬家”</h1> <p>WordPress 支持<a href="http://codex.wordpress.org/Importing_Content">导入多种系统的数据</a>。请先按照上述步骤安装 WordPress。安装后,您可在后台使用<a href="wp-admin/import.php" title="Import to WordPress">我们提供的导入工具</a>。</p> <h1>最低系统需求</h1> <ul> <li><a href="http://php.net/">PHP</a> <strong>5.2.4</strong> 或更高版本。</li> <li><a href="http://www.mysql.com/">MySQL</a> <strong>5.0</strong> 或更高版本。</li> </ul> <h2>系统推荐</h2> <ul> <li>启用 <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html">mod_rewrite</a> 这一 Apache 模块。</li> <li>在您的站点设置至 <a href="http://cn.wordpress.org/">http://cn.wordpress.org</a> 的链接。</li> </ul> <h1>在线资源</h1> <p>若您遇上文档中未有提及的情况,请首先参考我们为您准备的丰富 WordPress 在线资源:</p> <dl> <dt><a href="http://codex.wordpress.org/">WordPress Codex 文档</a></dt> <dd>Codex 是 WordPress 的百科全书。它包含现有版本 WordPress 的海量信息资源。主要文章均包含中文译文。</dd> <dt><a href="http://wordpress.org/news/">WordPress 官方博客</a></dt> <dd>在这里,您将接触到 WordPress 的最新升级信息和相关新闻,建议加入收藏夹。</dd> <dt><a href="http://planet.wordpress.org/">WordPress Planet </a></dt> <dd>WordPress Planet 汇集了全球所有 WordPress 相关的内容。</dd> <dt><a href="http://zh-cn.forums.wordpress.org/forum/issues">WordPress 中文支持论坛</a></dt> <dd>如果感到束手无策,请将问题提交至中文支持论坛,它有大量的热心的用户和良好的社区氛围。无论求助还是助人,在这里您应该确保自己的问题和答案均准确细致。</dd> <dt><a href="http://codex.wordpress.org/IRC">WordPress IRC 频道</a></dt> <dd>同样,WordPress 也有即时的聊天室用于 WordPress 用户交流以及部分技术支持。IRC 的详细使用方法可以访问前面几个关于技术支持的站点。(<a href="irc://irc.freenode.net/wordpress">irc.freenode.net #wordpress</a>)</dd> </dl> <h1><abbr title="eXtensible Markup Language">XML</abbr>-<abbr title="Remote Procedure Call">RPC</abbr> 和 Atom 接口</h1> <p>您可以使用诸如 <a href="http://windowslivewriter.spaces.live.com/">Windows Live Writer</a>、<a href="http://ecto.kung-foo.tv/">Ecto</a>、<a href="http://bloggar.com/">Bloggar</a>、<a href="http://radio.userland.com">Radio Userland</a>(基于 Radio 的 email-to-blog 功能)、<a href="http://www.newzcrawler.com/">NewzCrawler</a> 等支持 blogging API 的工具更新博客。详情请参阅 Codex 上关于 <a href="http://codex.wordpress.org/XML-RPC_Support">XML-RPC 支持</a>(英文)的内容。</p> <h1>用电子邮件发布文章</h1> <p>您可以通过电子邮件发表站点更新!请前往后台的“写作”设置页面,输入相关信息和 <abbr title="Post Office Protocol 第三版本">POP3</abbr> 帐号信息。然后您需设法让 <code>wp-mail.php</code> 定期运行。您可以使用<a href="http://en.wikipedia.org/wiki/Cron">计划任务(Cron job)</a>来实现,或是让某个站点检测服务定期访问您的 <code>wp-mail.php</code> 的 <abbr title="Uniform Resource Locator">URL</abbr>。</p> <p>更新很简单:使用任何邮箱发送内容到指定地址均会被 WordPress 自动发表,并以邮件主题作为文章标题,所以该"指定地址"也最好保密并专用。发表后程序将自动<em>删除</em>邮件。</p> <h1>用户角色</h1> <p>WordPress 2.0 之后的版本加入了更为灵活的用户身份系统,同时移除了之前的用户等级制度。 <a href="http://codex.wordpress.org/Roles_and_Capabilities">到 Codex 阅读关于身份和权限的更多内容</a>(英文)。</p> <h1>最后</h1> <ul> <li>对 WordPress 有任何建议、想法、评论或发现了 bug,请加入<a href="http://zh-cn.forums.wordpress.org/">中文支持论坛</a>。</li> <li>WordPress 准备了完善的插件 API 接口方便您进行扩展开发。作为开发人员,如果你有兴趣了解并加以利用,请参阅 <a href="http://codex.wordpress.org/Plugin_API">Codex 上的插件文档</a>。请尽量不要更改核心代码。</li> </ul> <h1>分享精神</h1> <p>WordPress 没有数百万的市场运作资金,也没有名人赞助。不过我们有更棒的支持,那就是您!如果您喜欢 WordPress,请将它介绍给自己的朋友,或者帮助他人安装一个 WordPress,又或者写一篇赞扬我们的文章。</p> <p>WordPress 是对 Michel V. 创建的 <a href="http://cafelog.com/">b2/caf&#233;log</a> 的官方后续版本。<a href="http://wordpress.org/about/">WordPress 开发团队</a>将 b2/caf&#233;log 发展成如今的 WordPress。如果您愿意支持我们的工作,欢迎您对 WordPress 进行<a href="http://wordpress.org/donate/">捐赠</a>。</p> <h1>许可证</h1> <p>WordPress 基于 <abbr title="GNU Public License">GPL</abbr> 通用许可协议发布。详见 <a href="license.txt">license.txt</a>(英文)。</p> </body> </html>
zyblog
trunk/zyblog/readme.html
HTML
asf20
8,535
<?php /** * WordPress Cron Implementation for hosts, which do not offer CRON or for which * the user has not set up a CRON job pointing to this file. * * The HTTP request to this file will not slow down the visitor who happens to * visit when the cron job is needed to run. * * @package WordPress */ ignore_user_abort(true); if ( !empty($_POST) || defined('DOING_AJAX') || defined('DOING_CRON') ) die(); /** * Tell WordPress we are doing the CRON task. * * @var bool */ define('DOING_CRON', true); if ( !defined('ABSPATH') ) { /** Set up WordPress environment */ require_once('./wp-load.php'); } // Uncached doing_cron transient fetch function _get_cron_lock() { global $_wp_using_ext_object_cache, $wpdb; $value = 0; if ( $_wp_using_ext_object_cache ) { // Skip local cache and force refetch of doing_cron transient in case // another processs updated the cache $value = wp_cache_get( 'doing_cron', 'transient', true ); } else { $row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", '_transient_doing_cron' ) ); if ( is_object( $row ) ) $value = $row->option_value; } return $value; } if ( false === $crons = _get_cron_array() ) die(); $keys = array_keys( $crons ); $gmt_time = microtime( true ); if ( isset($keys[0]) && $keys[0] > $gmt_time ) die(); $doing_cron_transient = get_transient( 'doing_cron'); // Use global $doing_wp_cron lock otherwise use the GET lock. If no lock, trying grabbing a new lock. if ( empty( $doing_wp_cron ) ) { if ( empty( $_GET[ 'doing_wp_cron' ] ) ) { // Called from external script/job. Try setting a lock. if ( $doing_cron_transient && ( $doing_cron_transient + WP_CRON_LOCK_TIMEOUT > $gmt_time ) ) return; $doing_cron_transient = $doing_wp_cron = sprintf( '%.22F', microtime( true ) ); set_transient( 'doing_cron', $doing_wp_cron ); } else { $doing_wp_cron = $_GET[ 'doing_wp_cron' ]; } } // Check lock if ( $doing_cron_transient != $doing_wp_cron ) return; foreach ( $crons as $timestamp => $cronhooks ) { if ( $timestamp > $gmt_time ) break; foreach ( $cronhooks as $hook => $keys ) { foreach ( $keys as $k => $v ) { $schedule = $v['schedule']; if ( $schedule != false ) { $new_args = array($timestamp, $schedule, $hook, $v['args']); call_user_func_array('wp_reschedule_event', $new_args); } wp_unschedule_event( $timestamp, $hook, $v['args'] ); do_action_ref_array( $hook, $v['args'] ); // If the hook ran too long and another cron process stole the lock, quit. if ( _get_cron_lock() != $doing_wp_cron ) return; } } } if ( _get_cron_lock() == $doing_wp_cron ) delete_transient( 'doing_cron' ); die();
zyblog
trunk/zyblog/wp-cron.php
PHP
asf20
2,718
<?php /** * Gets the email message from the user's mailbox to add as * a WordPress post. Mailbox connection information must be * configured under Settings > Writing * * @package WordPress */ /** Make sure that the WordPress bootstrap has run before continuing. */ require(dirname(__FILE__) . '/wp-load.php'); if ( ! apply_filters( 'enable_post_by_email_configuration', true ) ) wp_die( __( 'This action has been disabled by the administrator.' ) ); /** Allow a plugin to do a complete takeover of Post by Email **/ do_action('wp-mail.php'); /** Get the POP3 class with which to access the mailbox. */ require_once( ABSPATH . WPINC . '/class-pop3.php' ); /** Only check at this interval for new messages. */ if ( !defined('WP_MAIL_INTERVAL') ) define('WP_MAIL_INTERVAL', 300); // 5 minutes $last_checked = get_transient('mailserver_last_checked'); if ( $last_checked ) wp_die(__('Slow down cowboy, no need to check for new mails so often!')); set_transient('mailserver_last_checked', true, WP_MAIL_INTERVAL); $time_difference = get_option('gmt_offset') * HOUR_IN_SECONDS; $phone_delim = '::'; $pop3 = new POP3(); if ( !$pop3->connect( get_option('mailserver_url'), get_option('mailserver_port') ) || !$pop3->user( get_option('mailserver_login') ) ) wp_die( esc_html( $pop3->ERROR ) ); $count = $pop3->pass( get_option('mailserver_pass') ); if( false === $count ) wp_die( esc_html( $pop3->ERROR ) ); if( 0 === $count ) { $pop3->quit(); wp_die( __('There doesn&#8217;t seem to be any new mail.') ); } for ( $i = 1; $i <= $count; $i++ ) { $message = $pop3->get($i); $bodysignal = false; $boundary = ''; $charset = ''; $content = ''; $content_type = ''; $content_transfer_encoding = ''; $post_author = 1; $author_found = false; $dmonths = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); foreach ($message as $line) { // body signal if ( strlen($line) < 3 ) $bodysignal = true; if ( $bodysignal ) { $content .= $line; } else { if ( preg_match('/Content-Type: /i', $line) ) { $content_type = trim($line); $content_type = substr($content_type, 14, strlen($content_type) - 14); $content_type = explode(';', $content_type); if ( ! empty( $content_type[1] ) ) { $charset = explode('=', $content_type[1]); $charset = ( ! empty( $charset[1] ) ) ? trim($charset[1]) : ''; } $content_type = $content_type[0]; } if ( preg_match('/Content-Transfer-Encoding: /i', $line) ) { $content_transfer_encoding = trim($line); $content_transfer_encoding = substr($content_transfer_encoding, 27, strlen($content_transfer_encoding) - 27); $content_transfer_encoding = explode(';', $content_transfer_encoding); $content_transfer_encoding = $content_transfer_encoding[0]; } if ( ( $content_type == 'multipart/alternative' ) && ( false !== strpos($line, 'boundary="') ) && ( '' == $boundary ) ) { $boundary = trim($line); $boundary = explode('"', $boundary); $boundary = $boundary[1]; } if (preg_match('/Subject: /i', $line)) { $subject = trim($line); $subject = substr($subject, 9, strlen($subject) - 9); // Captures any text in the subject before $phone_delim as the subject if ( function_exists('iconv_mime_decode') ) { $subject = iconv_mime_decode($subject, 2, get_option('blog_charset')); } else { $subject = wp_iso_descrambler($subject); } $subject = explode($phone_delim, $subject); $subject = $subject[0]; } // Set the author using the email address (From or Reply-To, the last used) // otherwise use the site admin if ( ! $author_found && preg_match( '/^(From|Reply-To): /', $line ) ) { if ( preg_match('|[a-z0-9_.-]+@[a-z0-9_.-]+(?!.*<)|i', $line, $matches) ) $author = $matches[0]; else $author = trim($line); $author = sanitize_email($author); if ( is_email($author) ) { echo '<p>' . sprintf(__('Author is %s'), $author) . '</p>'; $userdata = get_user_by('email', $author); if ( ! empty( $userdata ) ) { $post_author = $userdata->ID; $author_found = true; } } } if (preg_match('/Date: /i', $line)) { // of the form '20 Mar 2002 20:32:37' $ddate = trim($line); $ddate = str_replace('Date: ', '', $ddate); if (strpos($ddate, ',')) { $ddate = trim(substr($ddate, strpos($ddate, ',') + 1, strlen($ddate))); } $date_arr = explode(' ', $ddate); $date_time = explode(':', $date_arr[3]); $ddate_H = $date_time[0]; $ddate_i = $date_time[1]; $ddate_s = $date_time[2]; $ddate_m = $date_arr[1]; $ddate_d = $date_arr[0]; $ddate_Y = $date_arr[2]; for ( $j = 0; $j < 12; $j++ ) { if ( $ddate_m == $dmonths[$j] ) { $ddate_m = $j+1; } } $time_zn = intval($date_arr[4]) * 36; $ddate_U = gmmktime($ddate_H, $ddate_i, $ddate_s, $ddate_m, $ddate_d, $ddate_Y); $ddate_U = $ddate_U - $time_zn; $post_date = gmdate('Y-m-d H:i:s', $ddate_U + $time_difference); $post_date_gmt = gmdate('Y-m-d H:i:s', $ddate_U); } } } // Set $post_status based on $author_found and on author's publish_posts capability if ( $author_found ) { $user = new WP_User($post_author); $post_status = ( $user->has_cap('publish_posts') ) ? 'publish' : 'pending'; } else { // Author not found in DB, set status to pending. Author already set to admin. $post_status = 'pending'; } $subject = trim($subject); if ( $content_type == 'multipart/alternative' ) { $content = explode('--'.$boundary, $content); $content = $content[2]; // match case-insensitive content-transfer-encoding if ( preg_match( '/Content-Transfer-Encoding: quoted-printable/i', $content, $delim) ) { $content = explode($delim[0], $content); $content = $content[1]; } $content = strip_tags($content, '<img><p><br><i><b><u><em><strong><strike><font><span><div>'); } $content = trim($content); //Give Post-By-Email extending plugins full access to the content //Either the raw content or the content of the last quoted-printable section $content = apply_filters('wp_mail_original_content', $content); if ( false !== stripos($content_transfer_encoding, "quoted-printable") ) { $content = quoted_printable_decode($content); } if ( function_exists('iconv') && ! empty( $charset ) ) { $content = iconv($charset, get_option('blog_charset'), $content); } // Captures any text in the body after $phone_delim as the body $content = explode($phone_delim, $content); $content = empty( $content[1] ) ? $content[0] : $content[1]; $content = trim($content); $post_content = apply_filters('phone_content', $content); $post_title = xmlrpc_getposttitle($content); if ($post_title == '') $post_title = $subject; $post_category = array(get_option('default_email_category')); $post_data = compact('post_content','post_title','post_date','post_date_gmt','post_author','post_category', 'post_status'); $post_data = add_magic_quotes($post_data); $post_ID = wp_insert_post($post_data); if ( is_wp_error( $post_ID ) ) echo "\n" . $post_ID->get_error_message(); // We couldn't post, for whatever reason. Better move forward to the next email. if ( empty( $post_ID ) ) continue; do_action('publish_phone', $post_ID); echo "\n<p>" . sprintf(__('<strong>Author:</strong> %s'), esc_html($post_author)) . '</p>'; echo "\n<p>" . sprintf(__('<strong>Posted title:</strong> %s'), esc_html($post_title)) . '</p>'; if(!$pop3->delete($i)) { echo '<p>' . sprintf(__('Oops: %s'), esc_html($pop3->ERROR)) . '</p>'; $pop3->reset(); exit; } else { echo '<p>' . sprintf(__('Mission complete. Message <strong>%s</strong> deleted.'), $i) . '</p>'; } } $pop3->quit();
zyblog
trunk/zyblog/wp-mail.php
PHP
asf20
7,723
<?php /** * WordPress 基础配置文件。 * * 本文件包含以下配置选项:MySQL 设置、数据库表名前缀、密钥、 * WordPress 语言设定以及 ABSPATH。如需更多信息,请访问 * {@link http://codex.wordpress.org/zh-cn:%E7%BC%96%E8%BE%91_wp-config.php * 编辑 wp-config.php} Codex 页面。MySQL 设置具体信息请咨询您的空间提供商。 * * 这个文件用在于安装程序自动生成 wp-config.php 配置文件, * 您可以手动复制这个文件,并重命名为“wp-config.php”,然后输入相关信息。 * * @package WordPress */ // ** MySQL 设置 - 具体信息来自您正在使用的主机 ** // /** WordPress 数据库的名称 */ define('DB_NAME', 'zy_blog'); /** MySQL 数据库用户名 */ define('DB_USER', 'root'); /** MySQL 数据库密码 */ define('DB_PASSWORD', '2816843'); /** MySQL 主机 */ define('DB_HOST', 'localhost'); /** 创建数据表时默认的文字编码 */ define('DB_CHARSET', 'utf8'); /** 数据库整理类型。如不确定请勿更改 */ define('DB_COLLATE', ''); /**#@+ * 身份认证密匙设定。 * * 您可以随意写一些字符 * 或者直接访问 {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org 私钥生成服务}, * 任何修改都会导致 cookie 失效,所有用户必须重新登录。 * * @since 2.6.0 */ define('AUTH_KEY', '%g>Wc}~{rg@BqI;HL,jJkGwc3uZ=7H!2PyZ=jmz$,U@*_J18>ZS@[/Ky=oa!IYdV'); define('SECURE_AUTH_KEY', '7h@~.X;UuoIgYed7w^v+=}]-%CQdqK).xlpn>eklAI|qv TP |tL&Dyv4inLk?`~'); define('LOGGED_IN_KEY', 'Fr?nl>$k)H$9cK=9m[9VE2T &chy5U8) ]qFnIj1Sc_4`]L7WmX//=]JoMT}yh.5'); define('NONCE_KEY', '9%p4d!cdp8esk64XXs0}B}}hiX.O%a_VbTu=9s_Cs]+$y_ccoiUS0R22#1^#C$Yd'); define('AUTH_SALT', '/$ZSPQvk(_B<Y G-6JA>Y8:,)x%WP4!Az5*Or FZa[kMWOhF%Vb^DTW~A$(Ao-{_'); define('SECURE_AUTH_SALT', '-(VM}yRvam!r]z{4gYm:M~}@!1CIpGn0/m5JuRh1H/WQl-MGW`w2<7L@[-HCXHu)'); define('LOGGED_IN_SALT', '&V T01eV@ffA6etL[Pq#?-wn~}@xG)LXc~DZ0Qic0p32j0Y$j~klw6UtufFvt5J'); define('NONCE_SALT', 'f]>J?NgEq/g/O$A>T&@%x|E18&xCA*4IJ:j<ra<PBp>2O>LNHkC15+0A[d^f0Ct6'); /**#@-*/ /** * WordPress 数据表前缀。 * * 如果您有在同一数据库内安装多个 WordPress 的需求,请为每个 WordPress 设置不同的数据表前缀。 * 前缀名只能为数字、字母加下划线。 */ $table_prefix = 'zyblog_'; /** * WordPress 语言设置,中文版本默认为中文。 * * 本项设定能够让 WordPress 显示您需要的语言。 * wp-content/languages 内应放置同名的 .mo 语言文件。 * 要使用 WordPress 简体中文界面,只需填入 zh_CN。 */ define('WPLANG', 'zh_CN'); /** * 开发者专用:WordPress 调试模式。 * * 将这个值改为“true”,WordPress 将显示所有用于开发的提示。 * 强烈建议插件开发者在开发环境中启用本功能。 */ define('WP_DEBUG', false); /* 好了!请不要再继续编辑。请保存本文件。使用愉快! */ /** WordPress 目录的绝对路径。 */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /** 设置 WordPress 变量和包含文件。 */ require_once(ABSPATH . 'wp-settings.php');
zyblog
trunk/zyblog/wp-config.php
PHP
asf20
3,299
<?php /** * Front to the WordPress application. This file doesn't do anything, but loads * wp-blog-header.php which does and tells WordPress to load the theme. * * @package WordPress */ /** * Tells WordPress to load the WordPress theme and output it. * * @var bool */ define('WP_USE_THEMES', true); /** Loads the WordPress Environment and Template */ require('./wp-blog-header.php');
zyblog
trunk/zyblog/index.php
PHP
asf20
395
package cn.nju.zyy.model.hello; import org.springframework.stereotype.Component; @Component public class MessageStore { private String message; public MessageStore() { setMessage("Hello Struts2"); } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return message + " (from toString method)"; } }
zyy-struts-demo
trunk/src/cn/nju/zyy/model/hello/MessageStore.java
Java
asf20
454
package cn.nju.zyy.model.person; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.beans.factory.annotation.Autowired; public class PersonDAOImpl implements PersonDAO { private SessionFactory sessionFactory; @Autowired public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public long savePerson(Person person) { Session session = sessionFactory.openSession(); Transaction transaction = null; long personId = -1; try { transaction = session.beginTransaction(); personId = (Long) session.save(person); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } return personId; } @Override public List<Person> listPerson() { Session session = sessionFactory.openSession(); Transaction transaction = null; List<Person> persons = null; try { transaction = session.beginTransaction(); persons = session.createQuery("from Person").list(); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } return persons; } @Override public Person getPerson(long id) { Session session = sessionFactory.openSession(); Transaction transaction = null; Person person = null; try { transaction = session.beginTransaction(); person = (Person) session.get(Person.class, id); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } return person; } @Override public void update(Person person) { } @Override public void delete(long id) { Session session = sessionFactory.openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Person person = (Person) session.get(Person.class, id); session.delete(person); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } }
zyy-struts-demo
trunk/src/cn/nju/zyy/model/person/PersonDAOImpl.java
Java
asf20
2,362
package cn.nju.zyy.model.person; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.Table; @Entity @Table(name="PERSONS") public class Person { private int id; private String firstName; private String lastName; private String email; private String phoneNumber; private String sport; private String gender; private String residency; private boolean over21; private Set<String> carModels; private int age; public Person() { id = -1; carModels = new HashSet<String>(); }; public Person(int id, String firstName, String lastName, String email, String phoneNumber, String sport, String gender, String residency, boolean over21, String[] carModels) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; this.email = email; this.phoneNumber = phoneNumber; this.sport = sport; this.gender = gender; this.residency = residency; this.over21 = over21; this.carModels = new HashSet<String>(); for(String str : carModels) { this.carModels.add(str); } } @Id @GeneratedValue @Column(name="PERSON_ID") public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(name="FIRST_NAME", nullable=false) public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Column(name="LAST_NAME", nullable=false) public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Column(name="EMAIL", nullable=false) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Column(name="PHONE_NUMBER", nullable=false) public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } @Column(name="SPORT", nullable=false) public String getSport() { return sport; } public void setSport(String sport) { this.sport = sport; } @Column(name="GENDER", nullable=false) public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @Column(name="RESIDENCY", nullable=false) public String getResidency() { return residency; } public void setResidency(String residency) { this.residency = residency; } @Column(name="IS_OVER_21", nullable=false) public boolean isOver21() { return over21; } public void setOver21(boolean over21) { this.over21 = over21; } @ElementCollection @CollectionTable(name="CAR_MODELS", joinColumns=@JoinColumn(name="PERSON_ID")) @Column(name="CAR_MODEL") public String[] getCarModels() { return (String[]) carModels.toArray(); } public void setCarModels(String[] carModels) { this.carModels.clear(); for(String str : carModels) { this.carModels.add(str); } } @Column(name="AGE", nullable=false) public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "First name: " + getFirstName() + " | Last name: " + getLastName() + " | Favorite Sport: " + getSport() + " | Gender: " + getGender() + " | Residency: " + getResidency() + " | Over 21: " + isOver21() + " | Car models: " + Arrays.asList(getCarModels()) + " | Email: " + getEmail() + " | Age: " + getAge(); } }
zyy-struts-demo
trunk/src/cn/nju/zyy/model/person/Person.java
Java
asf20
3,848
package cn.nju.zyy.model.person; import java.util.List; public interface PersonDAO { public long savePerson(Person person); public List<Person> listPerson(); public Person getPerson(long id); public void update(Person person); public void delete(long id); }
zyy-struts-demo
trunk/src/cn/nju/zyy/model/person/PersonDAO.java
Java
asf20
281
package cn.nju.zyy.model.person; public class State { private String stateAbbr; private String stateName; public State(String stateAbbr, String stateName) { this.stateAbbr = stateAbbr; this.stateName = stateName; } public String getStateAbbr() { return stateAbbr; } public void setStateAbbr(String stateAbbr) { this.stateAbbr = stateAbbr; } public String getStateName() { return stateName; } public void setStateName(String stateName) { this.stateName = stateName; } public String toString() { return getStateAbbr(); } }
zyy-struts-demo
trunk/src/cn/nju/zyy/model/person/State.java
Java
asf20
591
package cn.nju.zyy.service.person; import cn.nju.zyy.model.person.Person; public interface EditService { Person getPerson(); void savePerson(Person person); }
zyy-struts-demo
trunk/src/cn/nju/zyy/service/person/EditService.java
Java
asf20
176
package cn.nju.zyy.service.person; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.SortedMap; import java.util.TreeMap; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import cn.nju.zyy.model.person.Person; @Component public class PersonService { private static final Logger logger = Logger.getLogger(PersonService.class .getName()); private static SortedMap<Integer, Person> personMap = new TreeMap<Integer, Person>(); static { personMap.put(1, new Person(1, "Zhang", "San", "zs@gmail.com", "123-456-7890", "football", "male", "KS", true, new String[] { "Ford" })); personMap.put(2, new Person(2, "Li", "Si", "ls@gmail.com", "111-111-1111", "baseball", "female", "AZ", true, new String[] { "Nissan" })); } private static List<Person> personList = new ArrayList<Person>(); static { for (Integer id : personMap.keySet()) { personList.add(personMap.get(id)); } } public static List<Person> getPersonList() { return personList; } public void save(Person person) { int newId = getNewId(); person.setId(newId); personMap.put(newId, person); rebuildPersonList(); } public Person getPerson(int id) { return personMap.get(id); } public void update(Person person) { Person tempPerson = personMap.get(person.getId()); tempPerson.setFirstName(person.getFirstName()); tempPerson.setLastName(person.getLastName()); tempPerson.setEmail(person.getEmail()); tempPerson.setPhoneNumber(person.getPhoneNumber()); tempPerson.setSport(person.getSport()); tempPerson.setGender(person.getGender()); tempPerson.setResidency(person.getResidency()); tempPerson.setOver21(person.isOver21()); tempPerson.setCarModels(person.getCarModels()); rebuildPersonList(); } public void delete(int id) { personMap.remove(id); rebuildPersonList(); } private int getNewId() { int newId = 0; try { newId = personMap.lastKey() + 1; } catch (NoSuchElementException ex) { logger.info("Id value set to 0"); } return newId; } private static void rebuildPersonList() { personList.clear(); for (Integer id : personMap.keySet()) { personList.add(personMap.get(id)); } } }
zyy-struts-demo
trunk/src/cn/nju/zyy/service/person/PersonService.java
Java
asf20
2,341
package cn.nju.zyy.service.person; import org.springframework.stereotype.Component; import cn.nju.zyy.model.person.Person; @Component public class EditServiceInMemory implements EditService { private static Person person; private static String[] carModels = { "Ford", "Nissan" }; static { person = new Person(); person.setFirstName("Bruce"); person.setLastName("Phillips"); person.setEmail("bp@gmail.com"); person.setPhoneNumber("123-456-7890"); person.setSport("basketball"); person.setGender("not sure"); person.setResidency("KS"); person.setOver21(true); person.setCarModels(carModels); } @Override public Person getPerson() { return person; } @Override public void savePerson(Person personBean) { person.setFirstName(personBean.getFirstName()); person.setLastName(personBean.getLastName()); person.setEmail(personBean.getEmail()); person.setPhoneNumber(personBean.getPhoneNumber()); person.setSport(personBean.getSport()); person.setGender(personBean.getGender()); person.setResidency(personBean.getResidency()); person.setOver21(personBean.isOver21()); person.setCarModels(personBean.getCarModels()); } }
zyy-struts-demo
trunk/src/cn/nju/zyy/service/person/EditServiceInMemory.java
Java
asf20
1,212
package cn.nju.zyy.action.hello; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import cn.nju.zyy.model.hello.MessageStore; import com.opensymphony.xwork2.ActionSupport; @Component public class HelloAction extends ActionSupport { private static final long serialVersionUID = 1L; private static int helloCount = 0; private MessageStore messageStore; private String userName; @Override public String execute() throws Exception { helloCount++; if (userName != null) { messageStore.setMessage(messageStore.getMessage() + " : " + userName); } return SUCCESS; } public int getHelloCount() { return helloCount; } public void setHelloCount(int helloCount) { HelloAction.helloCount = helloCount; } public MessageStore getMessageStore() { return messageStore; } @Autowired public void setMessageStore(MessageStore messageStore) { this.messageStore = messageStore; } public String getUserName() { return userName; } /* * The Action class may automatically receive the parameter values * provided it has a public set method that matches the parameter name. * (for both form inputs or query string) */ public void setUserName(String userName) { this.userName = userName; } }
zyy-struts-demo
trunk/src/cn/nju/zyy/action/hello/HelloAction.java
Java
asf20
1,353
package cn.nju.zyy.action.person; import java.util.ArrayList; import java.util.List; import org.apache.struts2.convention.annotation.Action; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import cn.nju.zyy.model.person.Person; import cn.nju.zyy.model.person.State; import cn.nju.zyy.service.person.EditService; import com.opensymphony.xwork2.ActionSupport; @Component public class EditAction extends ActionSupport { private static final long serialVersionUID = 1L; private EditService editService; private Person person; private String[] sports = { "football", "baseball", "basketball" }; private String[] genders = { "male", "female", "not sure" }; private List<State> states; private String[] carModelsAvailable = { "Ford", "Chrysler", "Toyota", "Nissan" }; @Override @Action("edit-input") public String input() throws Exception { setPerson(editService.getPerson()); return INPUT; } @Override public String execute() throws Exception { editService.savePerson(person); return SUCCESS; } @Autowired public void setEditService(EditService editService) { this.editService = editService; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public String[] getSports() { return sports; } public String[] getGenders() { return genders; } public List<State> getStates() { if (states == null) { states = new ArrayList<State>(); states.add(new State("AZ", "Arizona")); states.add(new State("CA", "California")); states.add(new State("FL", "Florida")); states.add(new State("KS", "Kansas")); states.add(new State("NY", "New York")); } return states; } public String[] getCarModelsAvailable() { return carModelsAvailable; } }
zyy-struts-demo
trunk/src/cn/nju/zyy/action/person/EditAction.java
Java
asf20
1,914
package cn.nju.zyy.action.person; import java.util.ArrayList; import java.util.List; import org.apache.struts2.convention.annotation.Action; import org.springframework.stereotype.Component; import cn.nju.zyy.model.person.Person; import cn.nju.zyy.model.person.State; import com.opensymphony.xwork2.ActionSupport; @Component public class RegisterAction extends ActionSupport { private static final long serialVersionUID = 1L; /* * The framework will create an instance of Person and call its public set * methods before calling the execute method. */ private Person person; private String[] sports = { "football", "baseball", "basketball" }; private String[] genders = { "male", "female", "not sure" }; private List<State> states; private String[] carModelsAvailable = { "Ford", "Chrysler", "Toyota", "Nissan" }; @Override @Action("register-input") public String input() throws Exception { return INPUT; } @Override public String execute() throws Exception { // call Service class to store person's state in database return SUCCESS; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public String[] getSports() { return sports; } public String[] getGenders() { return genders; } public List<State> getStates() { states = new ArrayList<State>(); states.add(new State("AZ", "Arizona")); states.add(new State("CA", "California")); states.add(new State("FL", "Florida")); states.add(new State("KS", "Kansas")); states.add(new State("NY", "New York")); return states; } public String[] getCarModelsAvailable() { return carModelsAvailable; } /* * If any errors have been added then Struts 2 will not proceed to call the * execute method. Rather the Struts 2 framework will return "input" as the * result of calling the action. */ @Override public void validate() { if (person.getFirstName().length() == 0) { addFieldError("person.firstName", "First name is required."); } if (person.getEmail().length() == 0) { addFieldError("person.email", "Email is required."); } } }
zyy-struts-demo
trunk/src/cn/nju/zyy/action/person/RegisterAction.java
Java
asf20
2,219
package cn.nju.zyy.action.person; import java.util.ArrayList; import java.util.List; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import cn.nju.zyy.model.person.Person; import cn.nju.zyy.model.person.State; import cn.nju.zyy.service.person.PersonService; import com.opensymphony.xwork2.ActionSupport; @Component @Results({ @Result(name="success", location="person-list.jsp"), @Result(name="input", location="person-input.jsp") }) public class PersonAction extends ActionSupport { private static final long serialVersionUID = 1L; private Person person; private int id; private String[] sports = { "football", "baseball", "basketball" }; private String[] genders = { "male", "female", "not sure" }; private List<State> states; private String[] carModelsAvailable = { "Ford", "Chrysler", "Toyota", "Nissan" }; private PersonService personService; private List<Person> personList = PersonService.getPersonList(); @Action("person-list") public String execute() throws Exception { return SUCCESS; } @Action("create") public String create() { return INPUT; } @Action("edit-person") public String edit() { person = personService.getPerson(id); return INPUT; } @Action("save-or-update") public String saveOrUpdate() { if (person.getId() > -1) { personService.update(person); } else { personService.save(person); } personList = PersonService.getPersonList(); return SUCCESS; } @Action("delete") public String delete() { personService.delete(id); personList = PersonService.getPersonList(); return SUCCESS; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String[] getSports() { return sports; } public String[] getGenders() { return genders; } public List<State> getStates() { states = new ArrayList<State>(); states.add(new State("AZ", "Arizona")); states.add(new State("CA", "California")); states.add(new State("FL", "Florida")); states.add(new State("KS", "Kansas")); states.add(new State("NY", "New York")); return states; } public String[] getCarModelsAvailable() { return carModelsAvailable; } public List<Person> getPersonList() { return personList; } public void setPersonList(List<Person> personList) { this.personList = personList; } @Autowired public void setPersonService(PersonService personService) { this.personService = personService; } }
zyy-struts-demo
trunk/src/cn/nju/zyy/action/person/PersonAction.java
Java
asf20
2,894
<#include "/${parameters.templateDir}/xhtml/controlheader.ftl" /> <#include "/${parameters.templateDir}/MyTheme_simple/checkboxlist.ftl" /> <#include "/${parameters.templateDir}/xhtml/controlfooter.ftl" /><#nt/>
zyy-struts-demo
trunk/WebContent/template/MyTheme/checkboxlist.ftl
FreeMarker
asf20
213
<#assign itemCount = 0/> <#if parameters.list??> <@s.iterator value="parameters.list"> <#assign itemCount = itemCount + 1/> <#if parameters.listKey??> <#assign itemKey = stack.findValue(parameters.listKey)/> <#else> <#assign itemKey = stack.findValue('top')/> </#if> <#if parameters.listValue??> <#assign itemValue = stack.findString(parameters.listValue)?default("")/> <#else> <#assign itemValue = stack.findString('top')/> </#if> <#assign itemKeyStr=itemKey.toString() /> <input type="checkbox" name="${parameters.name?html}" value="${itemKeyStr?html}" id="${parameters.name?html}-${itemCount}"<#rt/> <#if tag.contains(parameters.nameValue, itemKey)> checked="checked"<#rt/> </#if> <#if parameters.disabled?default(false)> disabled="disabled"<#rt/> </#if> <#if parameters.title??> title="${parameters.title?html}"<#rt/> </#if> <#include "/${parameters.templateDir}/simple/css.ftl" /> <#include "/${parameters.templateDir}/simple/scripting-events.ftl" /> <#include "/${parameters.templateDir}/simple/common-attributes.ftl" /> /> <label for="${parameters.name?html}-${itemCount}" class="checkboxLabel">${itemValue?html}</label> <br /> </@s.iterator> <#else> &nbsp; </#if> <input type="hidden" id="__multiselect_${parameters.id?html}" name="__multiselect_${parameters.name?html}" value=""<#rt/> <#if parameters.disabled?default(false)> disabled="disabled"<#rt/> </#if> />
zyy-struts-demo
trunk/WebContent/template/MyTheme_simple/checkboxlist.ftl
FreeMarker
asf20
1,670
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Basic Struts 2 Application - Welcome</title> <s:head/> </head> <body> <h1>Welcome to Struts 2!</h1> <hr> <p><a href="<s:url action='hello/hello'/>">Hello World</a></p> <s:url action="hello/hello" var="helloLink"> <s:param name="userName">Bruce Phillips</s:param> </s:url> <p><a href="${helloLink}">Hello Bruce</a></p> <p>Get your own personal hello by filling out and submitting this form.</p> <s:form action="hello/hello"> <s:textfield name="userName" label="Your name" /> <s:submit value="Submit" /> </s:form> <hr> <p><a href="<s:url action='person/register-input' />">Please register</a> for our prize drawing.</p> <h3>Registro español</h3> <s:url action="register-input" var="registerInputLinkES"> <s:param name="request_locale">es</s:param> </s:url> <p><a href="${registerInputLinkES}">Por favor, regístrese</a> para nuestro sorteo</p> <hr> <p><a href="<s:url action='index' namespace='config-browser' />">Launch the configuration browser</a></p> <p> <s:url action='index' var="indexDebugLink"> <s:param name="debug">browser</s:param> </s:url> <a href="${indexDebugLink}">Launch the Debugging Interceptor</a> </p> <hr> <p><a href="<s:url action='person/edit-input' />">Edit your information</a></p> <p><a href="<s:url action='person/person-list' />">See Person List</a></p> <s:text name="contact" /> </body> </html>
zyy-struts-demo
trunk/WebContent/WEB-INF/content/index.jsp
Java Server Pages
asf20
1,753
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Hello World!</title> </head> <body> <h1><s:text name="greeting" /></h1> <hr> <h3><s:property value="messageStore.message" /></h3> <h3><s:property value="messageStore" /></h3> <p>(I've said hello <s:property value="helloCount" /> times!)</p> <p> <a href="<s:url action='../index' />">Return to home page</a> </p> </body> </html>
zyy-struts-demo
trunk/WebContent/WEB-INF/content/hello/hello-success.jsp
Java Server Pages
asf20
685
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <base href="<%=basePath%>"> <title>People List</title> </head> <body> <h3>People List</h3> <s:if test="personList.size > 0"> <ol> <s:iterator value="personList"> <li> <s:property value="firstName" /> <s:property value="lastName" /> <s:url action="edit-person" var="editUrl"> <s:param name="id" value="id" /> </s:url> <s:url action="delete" var="deleteUrl"> <s:param name="id" value="id" /> </s:url> <a href="${editUrl}">Edit</a> <a href="<s:property value='#deleteUrl' />">Delete</a> </li> </s:iterator> </ol> </s:if> <s:url action="create" var="createUrl"> <s:param name="id" value="-1" /> </s:url> <p><a href="${createUrl}">Create</a> new person.</p> <p> <a href="<s:url action='../index' />">Return to home page</a> </p> </body> </html>
zyy-struts-demo
trunk/WebContent/WEB-INF/content/person/person-list.jsp
Java Server Pages
asf20
1,518
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <base href="<%=basePath%>"> <title>Person</title> <s:head /> </head> <body> <s:if test="id > -1"> <h3>Edit Person</h3> </s:if> <s:else> <h3>Create Person</h3> </s:else> <s:form action="save-or-update"> <s:textfield key="person.firstName" /> <s:textfield key="person.lastName" /> <s:textfield key="person.email" /> <s:textfield key="person.phoneNumber" /> <s:select key="person.sport" list="sports" /> <s:radio key="person.gender" list="genders" /> <s:select key="person.residency" list="states" listKey="stateAbbr" listValue="stateName" /> <s:checkbox key="person.over21" /> <s:checkboxlist key="person.carModels" list="carModelsAvailable" theme="MyTheme"></s:checkboxlist> <s:submit value="Save" /> </s:form> <p> <a href="<s:url action='../index' />">Return to home page</a> </p> </body> </html>
zyy-struts-demo
trunk/WebContent/WEB-INF/content/person/person-input.jsp
Java Server Pages
asf20
1,508
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Registration Successful</title> </head> <body> <h3><s:text name="thankyou" /></h3> <p>Your registration information, <s:property value="person" /></p> <p><a href="<s:url action='../index' />">Return to home page</a></p> </body> </html>
zyy-struts-demo
trunk/WebContent/WEB-INF/content/person/register-success.jsp
Java Server Pages
asf20
585
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <base href="<%=basePath%>"> <title>Edit Person</title> <s:head /> </head> <body> <h3>Edit Information</h3> <s:form action="edit"> <s:textfield key="person.firstName" /> <s:textfield key="person.lastName" /> <s:textfield key="person.email" /> <s:textfield key="person.phoneNumber" /> <s:select key="person.sport" list="sports" /> <s:radio key="person.gender" list="genders" /> <s:select key="person.residency" list="states" listKey="stateAbbr" listValue="stateName" /> <s:checkbox key="person.over21" /> <s:checkboxlist key="person.carModels" list="carModelsAvailable"></s:checkboxlist> <s:submit value="Save" /> </s:form> <p> <a href="<s:url action='../index' />">Return to home page</a> </p> </body> </html>
zyy-struts-demo
trunk/WebContent/WEB-INF/content/person/edit-input.jsp
Java Server Pages
asf20
1,408
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <base href="<%=basePath%>"> <title>Edit Person</title> <s:head /> </head> <body> <h3>Register Yourself</h3> <s:form action="register"> <s:textfield key="person.firstName" /> <s:textfield key="person.lastName" /> <s:textfield key="person.email" /> <s:textfield key="person.phoneNumber" /> <s:select key="person.sport" list="sports" /> <s:radio key="person.gender" list="genders" /> <s:select key="person.residency" list="states" listKey="stateAbbr" listValue="stateName" /> <s:checkbox key="person.over21" /> <s:checkboxlist key="person.carModels" list="carModelsAvailable"></s:checkboxlist> <s:submit value="Save" /> </s:form> <p> <a href="<s:url action='../index' />">Return to home page</a> </p> </body> </html>
zyy-struts-demo
trunk/WebContent/WEB-INF/content/person/register-input.jsp
Java Server Pages
asf20
1,413
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Update Successful</title> </head> <body> <h3>Updated Information</h3> <p>Your information, <s:property value="person" /></p> <p><a href="<s:url action='../index' />">Return to home page</a></p> </body> </html>
zyy-struts-demo
trunk/WebContent/WEB-INF/content/person/edit-success.jsp
Java Server Pages
asf20
559
<?php // On démarre la session session_start(); if (isset($_POST['remember']) && empty($_COOKIE['pseudo'])) { //si cookie vide setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } else if(isset($_POST['remember']) && !empty($_COOKIE['pseudo'])) { // si cookie non vide setcookie('pseudo', '', 0, null, null, false, true); setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } ?> <html> <head> <link rel="stylesheet" type="text/css" href="styleFr.css" /> </head> <body> <?php function Online($fic_onl, $login) { $handle = fopen($fic_onl,"a"); fwrite ($handle,$login); fwrite ($handle,"\r\n"); fclose($handle); } function readfiles() { //on verifie d'avoir si le login rentré n'est pas déja existant $fichier="registerFr.txt"; $fp = fopen($fichier,"r"); if(filesize ($fichier)!=0) //On teste si le fichier est vide ou non { $contenu = fread ($fp, filesize ($fichier)); } fclose ($fp); return $contenu; } function checkParam($param) { return isset($param) && !empty($param); } function check() { if(checkParam($_POST['login1']) && checkParam($_POST['password1']) ) { $car="%"; $contenu=readfiles(); if(!empty($contenu)) { $tableau = explode("\r\n", $contenu); foreach($tableau as $ligne) { $tab = explode($car, $ligne); $login = $tab[0]; $pass = $tab[1]; if($_POST['login1']==$login && md5($_POST['password1'])== $pass) { $loginOK = true; $_SESSION['login1'] = $login; $_SESSION['password1'] = $pass; Online("onlineFr.txt", $login); ?><meta http-equiv="refresh" content="3 ; url=chatFr.php"> <a><img src="./image/bienvenue.gif" border="0" /></a><br /></meta> <?php exit; } } if( $_POST['login1']!=$login || md5($_POST['password1'])!= $pass) echo "Veuillez vous inscrire d'abord!"; } } } check(); ?> </body> </html>
zzchatmb
trunk/testphpunit/checkFr.php
PHP
mit
1,991
<?php require ('checkFr.php'); if (isset($_POST['remember']) && empty($_COOKIE['pseudo'])) { //si cookie vide setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } else if(isset($_POST['remember']) && !empty($_COOKIE['pseudo'])) { // si cookie non vide setcookie('pseudo', '', 0, null, null, false, true); setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } if ($_SESSION['login1'] == NULL) { header('Location: authentifFr.php'); } else { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" > <head> <meta charset="utf-8" /> <link style rel="stylesheet" type="text/css" href="style.css"> <h2><?php echo $_SESSION['login1']; ?></br> </br> <span> <a href="logoutFr.php" >Deconnexion</a></h2></span> <form action="profileFr.php" method="post"> <center><input type="submit" value="Editer mon profil" /></center><br><br> </form> </head> <body> <form action="#" method="post"> <center> <table id = "border" border="1" width=30% height=300 border align ="center" > <td id ="border1" valign="bottom" width=20% height=300 border align ="left"> <div id="convers"> <script> String.prototype.nl2br = function() { return this.replace(/\n/g, "<br />"); } function discuss() { $.ajax({ url: "mess_sessionFr.txt", success: function(msg) { $("#convers").html(msg.nl2br()); } }); } </script> <?php function writefile($fic_mess) { $handle = fopen($fic_mess,"a"); if (!empty($_POST['message']) && isset($_POST['message'])) { $date = date("d-m-Y"); $heure = date("H:i"); $message=$_POST['message']; fwrite ($handle,$date); fwrite ($handle," "); fwrite ($handle,$heure); fwrite ($handle," "); fwrite ($handle,$_SESSION['login1']); fwrite ($handle," a dit: "); fwrite ($handle,$_POST['message']); fwrite ($handle,"\r\n"); ?></div> <script src="jquery.js"></script> <script charset="utf-8"> setInterval("discuss()",1); </script> <?php fclose($handle); } } writefile( "mess_sessionFr.txt"); ?> </br></br> <label for="message"></label><textarea rows="3" name="message" id="message" placeholder="Message ..."></textarea><br /> <script > function SmileySmile(){document.getElementById('message').innerHTML += ':)';}function SmileyClin(){document.getElementById('message').innerHTML += ';)';}function SmileyLangue(){document.getElementById('message').innerHTML += ':p';} function SmileyRigole(){document.getElementById('message').innerHTML += ':d';}function SmileyHi(){document.getElementById('message').innerHTML += '^^';}function SmileyCoeur(){document.getElementById('message').innerHTML += '<3';} function bold(){ document.getElementById('message').style.fontWeight='bold';} function italics(){ document.getElementById('message').style.fontStyle='italic';} function strike(){ document.getElementById('message').style.textDecoration="line-through";} function underlined(){ document.getElementById('message').style.textDecoration = 'underline';} function normal(){ document.getElementById('message').style.fontWeight = 'normal';} function red(){document.getElementById('message').style.color = 'red'};function green(){document.getElementById('message').style.color = 'green'}; function blue(){document.getElementById('message').style.color = 'blue'}; function black(){document.getElementById('message').style.color = 'black'};function jaune(){document.getElementById('message').style.color = 'yellow'};function pink(){document.getElementById('message').style.color = 'pink'}; </script> <div id="SmMsg" style="visibility:hidden;" ></div> <div id="smiley"> <a onClick="javascript:SmileySmile()"><img src="./image/sourire.png" /></a> <a onClick="javascript:SmileyClin()"><img src="./image/clin.png" /></a> <a onClick="javascript:SmileyLangue()"><img src="./image/langue.png" /></a> <a onclick="javascript:SmileyRigole()"><img src="./image/rigole.png" /></a> <a onClick="javascript:SmileyHi()"><img src="./image/hihi.png" /></a> <a onclick="javascript:SmileyCoeur()"><img src="./image/coeur.png" /></a>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <a onclick="javascript:normal()">N</a>&nbsp&nbsp <a onclick="javascript:bold()"><b>G</b></a>&nbsp&nbsp <a onclick="javascript:italics()"><I>I</I></a>&nbsp&nbsp <a onclick="javascript:strike()"><strike>B</strike></a>&nbsp&nbsp <a onclick="javascript:underlined()"><u>S</u></a>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <a onclick="javascript:red()"><img src="./image/rouge.gif" /></a>&nbsp&nbsp <a onclick="javascript:green()"><img src="./image/carrevert.jpg" /></a>&nbsp&nbsp <a onclick="javascript:blue()"><img src="./image/carre_bleu.gif" /></a>&nbsp&nbsp <a onclick="javascript:black()"><img src="./image/noir.jpg" /></a>&nbsp&nbsp <a onclick="javascript:jaune()"><img src="./image/jaune.jpg" /></a>&nbsp&nbsp <a onclick="javascript:pink()"><img src="./image/pink.png" /></a>&nbsp&nbsp </br></br> <input type="submit" onClick="post(), clear()" value="Send" /> <td id ="border2" width=10% height=300 border align ="left"> <span id="ad">Membres en ligne:<br/> <?php function Members($fic_onl) { $fp = fopen($fic_onl,"r"); if(filesize ($fic_onl)!=0) //On teste si le fichier est vide ou non { $contenu = fread ($fp, filesize ($fic_onl)); $tableau = explode("\r\n", $contenu); foreach($tableau as $ligne) { if(!empty($ligne)) { $login = $ligne; echo '<img src="./image/vert.png" />'; echo $login.'<br/>'; } } } fclose($fp); } Members("onlineFr.txt"); ?> </span> <div id="change_status"> <form action="#" method="post"> <select id="status" > <option value="#" selected>------</option> <option value="0" >Disponible </option> <option value="1" >Occupe</option> <option value="2" >Indisponible</option> </select> </form> </div> </center> </form> </table> </body> <?php } ?> </html>
zzchatmb
trunk/testphpunit/chatFr.php
PHP
mit
6,720
<?php if (isset($_POST['remember']) && empty($_COOKIE['pseudo'])) { //si cookie vide setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } else if(isset($_POST['remember']) && !empty($_COOKIE['pseudo'])) { // si cookie non vide setcookie('pseudo', '', 0, null, null, false, true); setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } ?> <html> <head> <link rel="stylesheet" type="text/css" href="styleFr.css" /> </head> <body> <?php function manage($login,$pwd) { $car="%"; $boole= false; $fichier="registerFr.txt"; $fp = fopen($fichier,"a"); fwrite ($fp,$login); fwrite ($fp,'%'); fwrite ($fp,md5($pwd)); fwrite ($fp,"\r\n"); fclose($fp); $boole=true; return $boole; } function readfiles() { //on verifie d'avoir si le login rentré n'est pas déja existant $fichier="registerFr.txt"; $fp = fopen($fichier,"r"); if(filesize ($fichier)!=0) //On teste si le fichier est vide ou non { $contenu = fread ($fp, filesize ($fichier)); } fclose ($fp); return $contenu; } function checkParam($param) { return isset($param) && !empty($param); } function sign() { if(checkParam($_POST['login']) && checkParam($_POST['password']) && checkParam($_POST['name']) && checkParam($_POST['surname']) && checkParam($_POST['sex']) && checkParam($_POST['date']) && checkParam($_POST['confirm_email']) && checkParam($_POST['confirm_password']) && checkParam($_POST['email']) && checkParam($_POST['password']) && $_POST['email'] == $_POST['confirm_email'] && $_POST['password'] == $_POST['confirm_password']) { $car="%"; $contenu=readfiles(); if(!empty($contenu)) { $tableau = explode("\r\n", $contenu); foreach($tableau as $ligne) { $tab = explode($car, $ligne); $login = $tab[0]; if( $_POST['login']== $login ) { echo ("Pseudo indisponible, Veuillez en choisir un autre svp"); exit; } } if( $_POST['login']!= $login ) { $boole=manage($_POST['login'], $_POST['password']); if(boole){ echo '<h1>Inscription Reussie !</h1>'; ?> <meta http-equiv="refresh" content="2 ; url=authentifFr.php"> <center> <p><h2><center>Connectez-vous maintenant ! </br></br><img src="./image/loading.gif" /></center></h2></p> <br /> </center> <?php } } } else { $boole=manage($_POST['login'], $_POST['password']); if(boole){ echo '<h1>Inscription Reussie !</h1>'; ?> <meta http-equiv="refresh" content="2 ; url=authentifFr.php"> <center> <p><h2><center>Connectez-vous maintenant ! </br></br><img src="./image/loading.gif" /></center></h2></p> <br /> </center> <?php } } } else { echo "Vous avez fait des erreurs !\n Veuillez verifier que vous avez bien saisi les memes mots de passe et adresses email"; } } sign(); ?> </body> </html>
zzchatmb
trunk/testphpunit/signupFr.php
PHP
mit
3,169
<?php require_once("chatFr.php"); class test extends PHPUnit_Framework_TestCase { public function setUp() { echo "I run before each test\n"; } public function testRegister() { $this->assertFileExists('/home/mbaye/Documents/dev web/mess_sessionFr.txt'); } public function testfilewrite() { $fic_mess='mess_sessionFr.txt'; $handle = fopen($fic_mess,"w"); $date = date("d-m-Y"); $heure = date("H:i"); $message='salut'; $login='mbaye'; fwrite ($handle,$date); fwrite ($handle," "); fwrite ($handle,$heure); fwrite ($handle," "); fwrite ($handle,$login); fwrite ($handle," a dit: "); fwrite ($handle,$message); fwrite ($handle,"\r\n"); fclose($handle); //on reouvre pour voir s'il a bien ecrit ce qu'on veut $handle = fopen($fic_mess,"r"); $contenu = fread ($handle, filesize ($fic_mess)); fclose ($handle); $tableau = explode("\r\n", $contenu); foreach($tableau as $ligne) { $this->assertEquals($ligne, 'ssdsds'); } } public function TearDown() { echo "I run after each test\n"; } }
zzchatmb
trunk/testphpunit/TestchatFr.php
PHP
mit
1,080
<?php require_once("checkFr.php"); class test extends PHPUnit_Framework_TestCase { public function setUp() { echo "I run before each test\n"; } public function testRegister() { $this->assertFileExists('/home/mbaye/Documents/devweb/registerFr.txt'); } public function testOnline() { $this->assertFileExists('/home/mbaye/Documents/devweb/onlineFr.txt'); } public function testcheckParam() { $param='foo'; $this->assertFalse(checkParam($param)); } public function testfileread() { $contenu=readfiles(); $this->assertNotEquals($contenu, 'mbaye%c5ae282905386426559806a'); } public function testfilewrite() { Online("onlineFr.txt", 'lolaa'); //on re ouvre le fichier pour tester s'il a bien ecrit ce qu'on voulit qu'il ecrive $fp = fopen("onlineFr.txt","r"); $contenu = fread ($fp, filesize ("onlineFr.txt")); fclose ($fp); $tableau = explode("\r\n", $contenu); foreach($tableau as $ligne) { $this->assertNotEquals($ligne, 'lolaa'); } } public function TearDown() { echo "I run after each test\n"; } } ?>
zzchatmb
trunk/testphpunit/TestcheckFr.php
PHP
mit
1,158
<?php require_once("signupFr.php"); class test extends PHPUnit_Framework_TestCase { public function setUp() { echo "I run before each test\n"; } public function testmanage() { $login="mama"; $pwd="passe"; $this->assertFalse(manage($login, $pwd)); } public function TearDown() { echo "I run after each test\n"; } } ?>
zzchatmb
trunk/testphpunit/TestsignFr.php
PHP
mit
350
#titre { color: #FF1493; } #words{ color: white; } #transparent{ opacity:0; filter:alpha(opacity=0); /* For IE8 and earlier */ } body{ background-image: url("image.gif"); } /* margin-top: 15px; height: 200px; border-radius: 5px; background: url('images/sanfrancisco.jpg') no-repeat; position: relative; box-shadow: 0px 4px 4px #1c1a19; margin-bottom: 25px; } #image1 { position:absolute; left:0; bottom:0; }*/ #cadre { /*border: 1px solid #696;*/ -webkit-border-radius: 10px 10px 10px 10px; -moz-border-radius:10px 10px 10px 10px; border-radius:10px 10px 10px 10px; } /*http://html5.outils-webmaster.com/arrondi.php*/ label { display: block; width: 600px; float: left; } #coul { color: pink; } #border{ background-color: white; border-spacing: 10px 5px; border-radius: 10px; } #border1{ background-color: white; }
zzchatmb
trunk/anglais/styleEng.css
CSS
mit
851
<?php require ('checkEng.php'); if (isset($_POST['remember']) && empty($_COOKIE['pseudo'])) { //si cookie vide setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } else if(isset($_POST['remember']) && !empty($_COOKIE['pseudo'])) { // si cookie non vide setcookie('pseudo', '', 0, null, null, false, true); setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } if ($_SESSION['login1'] == NULL) { header('Location: authentifEng.php'); } else { ?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" > <head> <link style rel="stylesheet" type="text/css" href="style.css"> <h2><?php echo $_SESSION['login1']; ?></br> </br> <span> <a href="logoutEng.php" >Logout</a></h2></span> <form action="profileEng.php" method="post"> <center><input type="submit" value="Edit my profile" /></center><br><br> </form> </head> <body> <form action="#" method="post"> <center> <table id = "border" border="1" width=30% height=300 border align ="center" > <td id ="border1" valign="bottom" width=20% height=300 border align ="left"> <div id="convers"> <script> String.prototype.nl2br = function() { return this.replace(/\n/g, "<br />"); } function discuss() { $.ajax({ url: "mess_sessionEng.txt", success: function(msg) { $("#convers").html(msg.nl2br()); } }); } </script> <?php function writefile($fic_mess) { $handle = fopen($fic_mess,"a"); if (!empty($_POST['message']) && isset($_POST['message'])) { $date = date("d-m-Y"); $heure = date("H:i"); $message=$_POST['message']; fwrite ($handle,$date); fwrite ($handle," "); fwrite ($handle,$heure); fwrite ($handle," "); fwrite ($handle,$_SESSION['login1']); fwrite ($handle," said: "); fwrite ($handle,$_POST['message']); fwrite ($handle,"\r\n"); ?></div> <script src="jquery.js"></script> <script> setInterval("discuss()",1); </script> <?php fclose($handle); } } writefile( "mess_sessionEng.txt"); ?> </br></br> <label for="message"></label><textarea rows="3" name="message" id="message" placeholder="Message ..."></textarea><br /> <script > function SmileySmile(){document.getElementById('message').innerHTML += ':)';}function SmileyClin(){document.getElementById('message').innerHTML += ';)';}function SmileyLangue(){document.getElementById('message').innerHTML += ':p';} function SmileyRigole(){document.getElementById('message').innerHTML += ':d';}function SmileyHi(){document.getElementById('message').innerHTML += '^^';}function SmileyCoeur(){document.getElementById('message').innerHTML += '<3';} function bold(){ document.getElementById('message').style.fontWeight='bold';} function italics(){ document.getElementById('message').style.fontStyle='italic';} function strike(){ document.getElementById('message').style.textDecoration="line-through";} function underlined(){ document.getElementById('message').style.textDecoration = 'underline';} function normal(){ document.getElementById('message').style.fontWeight = 'normal';} function red(){document.getElementById('message').style.color = 'red'};function green(){document.getElementById('message').style.color = 'green'}; function blue(){document.getElementById('message').style.color = 'blue'}; function black(){document.getElementById('message').style.color = 'black'};function jaune(){document.getElementById('message').style.color = 'yellow'};function pink(){document.getElementById('message').style.color = 'pink'}; </script> <div id="SmMsg" style="visibility:hidden;" ></div> <div id="smiley"> <a onClick="javascript:SmileySmile()"><img src="./image/sourire.png" /></a> <a onClick="javascript:SmileyClin()"><img src="./image/clin.png" /></a> <a onClick="javascript:SmileyLangue()"><img src="./image/langue.png" /></a> <a onclick="javascript:SmileyRigole()"><img src="./image/rigole.png" /></a> <a onClick="javascript:SmileyHi()"><img src="./image/hihi.png" /></a> <a onclick="javascript:SmileyCoeur()"><img src="./image/coeur.png" /></a>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <a onclick="javascript:normal()">N</a>&nbsp&nbsp <a onclick="javascript:bold()"><b>G</b></a>&nbsp&nbsp <a onclick="javascript:italics()"><I>I</I></a>&nbsp&nbsp <a onclick="javascript:strike()"><strike>B</strike></a>&nbsp&nbsp <a onclick="javascript:underlined()"><u>S</u></a>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <a onclick="javascript:red()"><img src="./image/rouge.gif" /></a>&nbsp&nbsp <a onclick="javascript:green()"><img src="./image/carrevert.jpg" /></a>&nbsp&nbsp <a onclick="javascript:blue()"><img src="./image/carre_bleu.gif" /></a>&nbsp&nbsp <a onclick="javascript:black()"><img src="./image/noir.jpg" /></a>&nbsp&nbsp <a onclick="javascript:jaune()"><img src="./image/jaune.jpg" /></a>&nbsp&nbsp <a onclick="javascript:pink()"><img src="./image/pink.png" /></a>&nbsp&nbsp </br></br> <input type="submit" onClick="post(), clear()" value="Send" /> <td id ="border2" width=10% height=300 border align ="left"> <span id="ad">Members Online:<br/> <?php function Members($fic_onl) { $fp = fopen($fic_onl,"r"); if(filesize ($fic_onl)!=0) //On teste si le fichier est vide ou non { $contenu = fread ($fp, filesize ($fic_onl)); $tableau = explode("\r\n", $contenu); foreach($tableau as $ligne) { if(!empty($ligne)) { $login = $ligne; echo '<img src="./image/vert.png" />'; echo $login.'<br/>'; } } } fclose($fp); } Members("onlineEng.txt"); ?> </span> <div id="change_status"> <form action="#" method="post"> <select id="status" > <option value="#" selected>------</option> <option value="0" >Available </option> <option value="1" >Busy</option> <option value="2" >Unavailable</option> </select> </form> </div> </center> </form> </body> <?php } ?> </html>
zzchatmb
trunk/anglais/chatEng.php
PHP
mit
6,555
<?php //démarrage de la session session_start(); if (isset($_POST['remember']) && empty($_COOKIE['pseudo'])) { //si cookie vide setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } else if(isset($_POST['remember']) && !empty($_COOKIE['pseudo'])) { // si cookie non vide setcookie('pseudo', '', 0, null, null, false, true); setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } ?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <html> <head> <title>chat-mb</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <link rel="stylesheet" type="text/css" href="styleEng.css" /> </head> <body> <FONT face= "arial"> <form action="checkEng.php" method="post"> <p id= "words"> Login: <input type="text" name="login1" maxlength=15 value=<?php echo $_COOKIE['pseudo']; ?> />&nbsp &nbsp Password: <input type="password" name="password1" /><br/> <br/> Remember me<input type="checkbox" name="remember" /><br /><br /> <input type="reset" value="Cancel" > <input type="submit" value="Sign in" > <br/> <br/> </p> </form> <form action="signupEng.php" onsubmit="return checkregister(this)" method="post"> <p> <div> <center> <h2><FONT SIZE="6" id="words">Sign Up</FONT></h2> <center><table border="1" width=60% id="border1"> <td> <FONT SIZE="4" > <label for="name">Name :</label><input type="text" name="name" onblur="checkname_surname(this)" maxlength= "30" /><br /> <label for="surname">Surname :</label><input type="text" name="surname" onblur="checkname_surname(this)" maxlength= "30" /><br /> <label for="login">Nickname :</label><input type="text" name="login" onblur="checklogin(this)" maxlength= "15" placeholder="Minimum: 5 caracters" /><br /> <label for="date">Date of birth :</label><input type="date" name="date" onblur="checkdate(this)" /><br /> <label for="email">Email Address : </label><input type="email" name="email" onblur="checkemail(this)" /><br/> <label for="confirm_email" id="transparent">Confirm_email</label><input type="email" name="confirm_email" placeholder=" Confirm your email" onblur="checkemail(this)" /><br /> <label for="password">Password :<FONT SIZE="2"><br>(contains at least 8 characters with a capital letter, a lowercase letter and one number) </FONT > </label><input type="password" name="password" onblur="checkpwd(this)" /><br /> <label for="confirm_password"id="transparent">Confirm_password</label><input type="password" name="confirm_password" placeholder="Confirm you password" onblur="checkpwd(this)" /><br /> <label for="sex">Sex :</label><input type="radio" name="sex" />Male <input type="radio" name="sex" />Female<br /> <input type="reset" value="Cancel" /> <input type="submit" value="Sign up"/> <br><a href="http://www.site.com">Forgotten Password ?</a> </FONT> </td> </table></center> </div> </p> </form> </FONT> <script type="text/javascript" language= Javascript src="signupEng.js"> </script> </body> </html>
zzchatmb
trunk/anglais/authentifEng.php
PHP
mit
3,241
<?php // On démarre la session session_start(); if (isset($_POST['remember']) && empty($_COOKIE['pseudo'])) { //si cookie vide setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } else if(isset($_POST['remember']) && !empty($_COOKIE['pseudo'])) { // si cookie non vide setcookie('pseudo', '', 0, null, null, false, true); setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } ?> <html> <head> <link rel="stylesheet" type="text/css" href="styleEng.css" /> </head> <body> <?php function Online($fic_onl, $login) { $handle = fopen($fic_onl,"a"); fwrite ($handle,$login); fwrite ($handle,"\r\n"); fclose($handle); } function readfiles() { //on verifie d'avoir si le login rentré n'est pas déja existant $fichier="registerEng.txt"; $fp = fopen($fichier,"r"); if(filesize ($fichier)!=0) //On teste si le fichier est vide ou non { $contenu = fread ($fp, filesize ($fichier)); } fclose ($fp); return $contenu; } function checkParam($param) { return isset($param) && !empty($param); } function check() { if(checkParam($_POST['login1']) && checkParam($_POST['password1']) ) { $car="%"; $contenu=readfiles(); if(!empty($contenu)) { $tableau = explode("\r\n", $contenu); foreach($tableau as $ligne) { $tab = explode($car, $ligne); $login = $tab[0]; $pass = $tab[1]; if($_POST['login1']==$login && md5($_POST['password1'])== $pass) { $loginOK = true; $_SESSION['login1'] = $login; $_SESSION['password1'] = $pass; Online("onlineEng.txt", $login); ?><meta http-equiv="refresh" content="3 ; url=chatEng.php"> <a><img src="./image/bienvenue.gif" border="0" /></a><br /></meta> <?php exit; } } if( $_POST['login1']!=$login || md5($_POST['password1'])!= $pass) echo "Please Sign up!"; } } } check(); ?> </body> </html>
zzchatmb
trunk/anglais/checkEng.php
PHP
mit
1,977
<?php if (isset($_POST['remember']) && empty($_COOKIE['pseudo'])) { //si cookie vide setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } else if(isset($_POST['remember']) && !empty($_COOKIE['pseudo'])) { // si cookie non vide setcookie('pseudo', '', 0, null, null, false, true); setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } ?> <html> <head> <link rel="stylesheet" type="text/css" href="styleEng.css" /> </head> <body> <?php function manage($login, $pwd) { $car="%"; $boole= false; $fichier="registerEng.txt"; $fp = fopen($fichier,"a"); fwrite ($fp,$login); fwrite ($fp,'%'); fwrite ($fp,md5($pwd)); fwrite ($fp,"\r\n"); fclose($fp); $boole=true; return $boole; } function readfiles() { //on verifie d'avoir si le login rentré n'est pas déja existant $fichier="registerEng.txt"; $fp = fopen($fichier,"r"); if(filesize ($fichier)!=0) //On teste si le fichier est vide ou non { $contenu = fread ($fp, filesize ($fichier)); } return $contenu; } function checkParam($param) { return isset($param) && !empty($param); } function sign() { if(checkParam($_POST['login']) && checkParam($_POST['password']) && checkParam($_POST['name']) && checkParam($_POST['surname']) && checkParam($_POST['sex']) && checkParam($_POST['date']) && checkParam($_POST['confirm_email']) && checkParam($_POST['confirm_password']) && checkParam($_POST['email']) && checkParam($_POST['password']) && $_POST['email'] == $_POST['confirm_email'] && $_POST['password'] == $_POST['confirm_password']) { $car="%"; $contenu=readfiles(); if(!empty($contenu)) { $tableau = explode("\r\n", $contenu); foreach($tableau as $ligne) { $tab = explode($car, $ligne); $login = $tab[0]; if( $_POST['login']== $login ) { echo ("Nickname unavailable, Please choose another one please"); exit; } } if( $_POST['login']!= $login ) { $boole=manage( $_POST['login'], $_POST['password']); if(boole){ echo '<h1>Successfull Registration !</h1>'; ?> <meta http-equiv="refresh" content="2 ; url=authentifEng.php"> <center> <p><h2><center>Sign in now ! </br></br><img src="./image/loading.gif" /></center></h2></p> <br /> </center> <?php } } } else { $boole=manage( $_POST['login'], $_POST['password']); if(boole){ echo '<h1>Successfull Registration !</h1>'; ?> <meta http-equiv="refresh" content="2 ; url=authentifEng.php"> <center> <p><h2><center>Sign in now ! </br></br><img src="./image/loading.gif" /></center></h2></p> <br /> </center> <?php } } } else { echo "You have made mistakes! \n Please check that you have entered the same passwords and email addresses"; } } sign(); ?> </body> </html>
zzchatmb
trunk/anglais/signupEng.php
PHP
mit
3,129
<?php session_start(); if (isset($_POST['remember']) && empty($_COOKIE['pseudo'])) { //si cookie vide setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } else if(isset($_POST['remember']) && !empty($_COOKIE['pseudo'])) { // si cookie non vide setcookie('pseudo', '', 0, null, null, false, true); setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } ?> <html> <head> <meta http-equiv="refresh" content="3;url=authentifEng.php"/> <meta charset="utf-8" /> </head> <body> <?php require ('checkEng.php'); // quand l'utilisateur se deconnecte on le supprime du fichier online.txt function delete($fic_onl) { $handle = fopen($fic_onl, 'r'); if(filesize ($fic_onl)!=0) //On teste si le fichier est vide ou non { $contenu = fread ($handle, filesize ($fic_onl)); $tableau = explode("\r\n", $contenu); fclose($handle); $handle = fopen($fic_onl, 'w'); fputs($handle, ''); fclose($handle); foreach($tableau as $ligne) { if( $ligne != $_SESSION['login1']) { $fp = fopen($fic_onl, 'a'); fwrite($fp, $ligne); fwrite ($fp,"\r\n"); } } fclose($fp); } } delete("onlineEng.txt"); // On écrase le tableau de session $_SESSION = array(); // On détruit la session session_destroy(); ?> </br></br> <p><h2><center>Logout ...</br><img src="./image/logout.gif" /></center></h2></p> </body> </html>
zzchatmb
trunk/anglais/logoutEng.php
PHP
mit
1,487
//Fonction qui colorie les cases function underline(block, erreur) { if(erreur) block.style.backgroundColor = "red"; else block.style.backgroundColor = "green"; } // Fonction vérifiant le login function checklogin(block) { var space = /\s/g; // Le login doit avoir une taille >5 et ne doit pas contenir d'espaces if(block.value.length <=4 || space.test(block.value)) { underline(block, true); return false;//on le colorie en rouge } else { underline(block, false); return true;//on le colorie en vert } } // Fonction vérifiant le nom et le prénom function checkname_surname(block) { if(block.value.length >=30 || block.value.length ==0 ) { underline(block, true); return false; } else { underline(block, false); return true; } } // Fonction vérifiant l'email function checkemail(block) { var regex = /^[a-zA-Z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}$/; if(block.value.length !=0 && regex.test(block.value)) { underline(block, false); return true; } else { underline(block, true); return false; } } // Fonction vérifiant le mot de passe function checkpwd(block) { var tLongCarac = /.{8,}/; var test1minus = /[a-z]{1,}/; var test1Majus = /[A-Z]{1,}/; var test1chiff = /[0-9]{1,}/; if (tLongCarac.test(block.value) & test1minus.test(block.value) & test1Majus.test(block.value) & test1chiff.test(block.value) ) { underline(block, false); return true; } else { underline(block, true); return false; } } //Fonction qui vérifie la date function checkdate(block) { if(block.value.length !=0 ) { underline(block, false); return true; } else { underline(block, true); return false; } } //Fonction qui vérifie tout le formulaire d'inscription function checkregister( r) { var name_surnameOk = checkname_surname(r.name); var name_surnameOk = checkname_surname(r.surname); var loginOk = checklogin(r.login); var emailOk = checkemail(r.email); var email_bisOk = checkemail(r.confirm_email); var pwdOk = checkpwd(r.password); var pwd_bisOk = checkpwd(r.confirm_password); var datedOk = checkdate(r.date); if(loginOk && name_surnameOk && emailOk && pwdOk && email_bisOk && datedOk &&pwd_bisOk ) return true ; else { alert("Please fill the boxes correctly"); return false; } }
zzchatmb
trunk/anglais/signupEng.js
JavaScript
mit
2,579
<?php require ('checkEng.php'); if ($_SESSION['login1'] == NULL) { header('Location: authentifEng.php'); } else { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <link rel="stylesheet" type="text/css" href="styleEng.css" /> <html> <head> <br/><br/><br/><br/><br/> </head> <body><center> <table id = "border" border="1" width=30% height=300 border align ="center" > <td> Address<br/><input type="text" name="address" maxlength=15/><br/> Post Code<br/><input type="text" name="address" maxlength=15/><br/> Region<br/><input type="text" name="address" maxlength=15/><br/> Country<br/><select id="country" > <option value="#" selected>------</option> <option>France </option> <option>Argentine</option> <option>Etats Unis</option> </select><br/> Nationality<br/><select > <option value="#" selected>------</option> <option>France </option> <option>Argentine</option> <option>United States</option> </select><br/> Status<br/><select id="status" > <option value="#" selected>------</option> <option>Single </option> <option>Couple</option> <option>Married</option> <option>Widower</option> </select><br/><br/> <form action="chatEng.php" method="post"> <input type="reset" value="Cancel" >&nbsp&nbsp&nbsp <input type="submit" value="Check in" ><br/> </form> </center></table> </body> <?php } ?> </html>
zzchatmb
trunk/anglais/profileEng.php
PHP
mit
1,601
<html> <head> <title>chat-mb</title> <link rel="stylesheet" type="text/css" href="./francais/styleFr.css" /> <center></br> <h1 id="words"><FONT SIZE="9" > <a><img src="./francais/image/chatzz2.png" border="0" /></a> </FONT></h1> </center> </head> <body> </br></br></br></br></br></br> <FONT face= "arial"> <center> <a href="./francais/authentifFr.php"><img src="./francais/image/Entrer.png" border="0" /></a><br/><br/><br/> <a href="./anglais/authentifEng.php"><img src="./anglais/image/Enter.png" border="0" /></a> </center> </FONT> </body> </html>
zzchatmb
trunk/index.html
HTML
mit
637
<?php // On démarre la session session_start(); if (isset($_POST['remember']) && empty($_COOKIE['pseudo'])) { //si cookie vide setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } else if(isset($_POST['remember']) && !empty($_COOKIE['pseudo'])) { // si cookie non vide setcookie('pseudo', '', 0, null, null, false, true); setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } ?> <html> <head> <link rel="stylesheet" type="text/css" href="styleFr.css" /> </head> <body> <?php function Online($fic_onl, $login) { $handle = fopen($fic_onl,"a"); fwrite ($handle,$login); fwrite ($handle,"\r\n"); fclose($handle); } function readfiles() { //on verifie d'avoir si le login rentré n'est pas déja existant $fichier="registerFr.txt"; $fp = fopen($fichier,"r"); if(filesize ($fichier)!=0) //On teste si le fichier est vide ou non { $contenu = fread ($fp, filesize ($fichier)); } fclose ($fp); return $contenu; } function checkParam($param) { return isset($param) && !empty($param); } function check() { if(checkParam($_POST['login1']) && checkParam($_POST['password1']) ) { $car="%"; $contenu=readfiles(); if(!empty($contenu)) { $tableau = explode("\r\n", $contenu); foreach($tableau as $ligne) { $tab = explode($car, $ligne); $login = $tab[0]; $pass = $tab[1]; if($_POST['login1']==$login && md5($_POST['password1'])== $pass) { $loginOK = true; $_SESSION['login1'] = $login; $_SESSION['password1'] = $pass; Online("onlineFr.txt", $login); ?><meta http-equiv="refresh" content="3 ; url=chatFr.php"> <a><img src="./image/bienvenue.gif" border="0" /></a><br /></meta> <?php exit; } } if( $_POST['login1']!=$login || md5($_POST['password1'])!= $pass) echo "Veuillez vous inscrire d'abord!"; } } } check(); ?> </body> </html>
zzchatmb
trunk/francais/checkFr.php
PHP
mit
1,989
<?php session_start(); if (isset($_POST['remember']) && empty($_COOKIE['pseudo'])) { //si cookie vide setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } else if(isset($_POST['remember']) && !empty($_COOKIE['pseudo'])) { // si cookie non vide setcookie('pseudo', '', 0, null, null, false, true); setcookie('pseudo', $_POST['login1'], time() + 3600*24*3, null, null, false, true); } ?> <html> <head> <meta http-equiv="refresh" content="3;url=authentifFr.php"/> <meta charset="utf-8" /> </head> <body> <?php require ('checkFr.php'); // quand l'utilisateur se deconnecte on le supprime du fichier online.txt function delete($fic_onl) { $handle = fopen($fic_onl, 'r'); if(filesize ($fic_onl)!=0) //On teste si le fichier est vide ou non { $contenu = fread ($handle, filesize ($fic_onl)); $tableau = explode("\r\n", $contenu); fclose($handle); $handle = fopen($fic_onl, 'w'); fputs($handle, ''); fclose($handle); foreach($tableau as $ligne) { if( $ligne != $_SESSION['login1']) { $fp = fopen($fic_onl, 'a'); fwrite($fp, $ligne); fwrite ($fp,"\r\n"); } } fclose($fp); } } delete("onlineFr.txt"); // On écrase le tableau de session $_SESSION = array(); // On détruit la session session_destroy(); ?> </br></br> <p><h2><center>Deconnexion ...</br><img src="./image/logout.gif" /></center></h2></p> </body> </html>
zzchatmb
trunk/francais/logoutFr.php
PHP
mit
1,477
<?php require ('checkFr.php'); if ($_SESSION['login1'] == NULL) { header('Location: authentifFr.php'); } else { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <link rel="stylesheet" type="text/css" href="styleEng.css" /> <html> <head> <br/><br/><br/><br/><br/> </head> <body><center> <table id = "border" border="1" width=30% height=300 border align ="center" > <td> Adresse<br/><input type="text" name="address" maxlength=15/><br/> Code Postal<br/><input type="text" name="address" maxlength=15/><br/> Region<br/><input type="text" name="address" maxlength=15/><br/> Pays<br/><select id="country" > <option value="#" selected>------</option> <option>France </option> <option>Argentine</option> <option>Etats Unis</option> </select><br/> Nationalite<br/><select > <option value="#" selected>------</option> <option>France </option> <option>Argentine</option> <option>Etats Unis</option> </select><br/> Statut<br/><select id="status" > <option value="#" selected>------</option> <option>Celibataire </option> <option>En couple</option> <option>Marie</option> <option>Veuf</option> </select><br/><br/> <form action="chatFr.php" method="post"> <input type="reset" value="Annuler" >&nbsp&nbsp&nbsp <input type="submit" value="Enregistrer" ><br/> </form> </center></table> </body> <?php } ?> </html>
zzchatmb
trunk/francais/profileFr.php
PHP
mit
1,601