/** * Replaces core function to start preview theme output buffer. */ static function preview_theme() { // are we previewing? if (!isset($_GET['template']) || !wp_verify_nonce($_GET['preview_ctc'])) { return; } // can user preview? if (!current_user_can('switch_themes')) { return; } // hide admin bar in preview if (isset($_GET['preview_iframe'])) { show_admin_bar(false); } // sanitize template param $_GET['template'] = preg_replace('|[^a-z0-9_./-]|i', '', $_GET['template']); // check for manipulations if (validate_file($_GET['template'])) { return; } // replace future get_template calls with preview template add_filter('template', 'ChildThemeConfiguratorPreview::preview_theme_template_filter'); if (isset($_GET['stylesheet'])) { // sanitize stylesheet param $_GET['stylesheet'] = preg_replace('|[^a-z0-9_./-]|i', '', $_GET['stylesheet']); // check for manipulations if (validate_file($_GET['stylesheet'])) { return; } // replace future get_stylesheet calls with preview stylesheet add_filter('stylesheet', 'ChildThemeConfiguratorPreview::preview_theme_stylesheet_filter'); } // swap out theme mods with preview theme mods add_filter('pre_option_theme_mods_' . get_option('stylesheet'), 'ChildThemeConfiguratorPreview::preview_mods'); }
/** * Get the ignored words * * @param string $lang * * @return array */ private function get_ignored_words($lang) { if (null == $this->ignored_words) { // Require the lang file $relative_path = '/ignored-words/' . $lang . '.php'; // Validate the file path to prevent traversal attacks if (0 !== validate_file($relative_path)) { return array(); } $filename = dirname(__FILE__) . $relative_path; // Check if file exists if (!file_exists($filename)) { return array(); } // Require the file $ignored_words = (require $filename); // Check if the the $ignored_words are set if (is_null($ignored_words) || !is_array($ignored_words)) { return array(); } // add extra ignored words (setting) $ignored_words = array_merge($ignored_words, $this->get_extra_ignored_words()); // Words to ignore $this->ignored_words = apply_filters('rp4wp_ignored_words', $ignored_words); } return $this->ignored_words; }
/** * Force download of certain file types via ?download=path/filename.type * * This prompts "Save As" -- handy for MP3, PDF, etc. Only works on local files. * * This information was useful: http://wordpress.stackexchange.com/questions/3480/how-can-i-force-a-file-download-in-the-wordpress-backend * * Use add_theme_support( 'ctfw_force_downloads' ); * * @since 0.9 * @global object $wp_query * @global object $wp_filesystem; */ function ctfw_force_download() { global $wp_query, $wp_filesystem; // Theme supports this? if (!current_theme_supports('ctfw-force-downloads')) { return; } // Check if this URL is a request for file download if (is_front_page() && !empty($_GET['download'])) { // relative file path $relative_file_path = ltrim($_GET['download'], '/'); // remove preceding slash, if any // check for directory traversal attack if (!validate_file($relative_file_path)) { // false means it passed validation // path to file in uploads folder (only those can be downloaded) $upload_dir = wp_upload_dir(); $upload_file_path = $upload_dir['basedir'] . '/' . $relative_file_path; // file exists in uploads folder? if (file_exists($upload_file_path)) { // make sure file valid as upload (valid type, extension, etc.) $validate = wp_check_filetype_and_ext($upload_file_path, basename($upload_file_path)); if ($validate['type'] && $validate['ext']) { // empty if type not in upload_mimes, doesn't exist, etc. // headers to prompt "save as" $filename = basename($upload_file_path); $filesize = filesize($upload_file_path); header('Content-Type: application/octet-stream', true, 200); // replace WordPress 404 Not Found with 200 Okay header('Content-Disposition: attachment; filename=' . $filename); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . $filesize); // clear buffering just in case @ob_end_clean(); flush(); // Prepare to use WP_Filesystem /* See comments below if ( ! class_exists( 'WP_Filesystem_Base') ) { require_once ABSPATH . 'wp-admin/includes/file.php'; } WP_Filesystem(); */ // Output file contents using Direct method // readfile more efficient; WP_Filesystem security used, causes Theme Check warning //echo $wp_filesystem->get_contents( $upload_file_path ); @readfile($upload_file_path); // we're done, stop further execution exit; } } } // failure of any type results in 404 file not found $wp_query->set_404(); status_header(404); } }
function voce_theme_customizer_init() { if (class_exists('WP_Customize_Control')) { $files = glob(__DIR__ . '/controls/*.php'); foreach ($files as $file) { $class = basename($file); if (!class_exists($class) && 0 === validate_file($file)) { require_once $file; } } Voce_Customize_Image_Control::init(); Voce_Customize_PSU_Control::init(); } }
function amp_render() { $__DIR__ = dirname(__FILE__); require $__DIR__ . '/includes/amp-template-actions.php'; $post_id = get_queried_object_id(); do_action('pre_amp_render', $post_id); $amp_post = new AMP_Post($post_id); $default_template = $__DIR__ . '/templates/amp-index.php'; $template = apply_filters('amp_template_file', $default_template); if (0 !== validate_file($template)) { _doing_it_wrong(__FUNCTION__, __('Path validation for `amp_template_file` failed.'), '0.1'); $template = $default_template; } include $template; exit; }
function validate_file_to_edit($file, $allowed_files = '') { $file = stripslashes($file); $code = validate_file($file, $allowed_files); if (!$code) { return $file; } switch ($code) { case 1: wp_die(__('Sorry, can’t edit files with ".." 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’t call files with their real path.')); case 3: wp_die(__('Sorry, that file cannot be edited.')); } }
/** * Returns array of network plugin files to be included in global scope. * * The default directory is wp-content/plugins. To change the default directory * manually, define <code>WP_PLUGIN_DIR</code> and <code>WP_PLUGIN_URL</code> * in wp-config.php. * * @access private * @since 3.1.0 * @return array Files to include */ function wp_get_active_network_plugins() { $active_plugins = (array) get_site_option('active_sitewide_plugins', array()); if (empty($active_plugins)) { return array(); } $plugins = array(); $active_plugins = array_keys($active_plugins); sort($active_plugins); foreach ($active_plugins as $plugin) { if (!validate_file($plugin) && '.php' == substr($plugin, -4) && file_exists(WP_PLUGIN_DIR . '/' . $plugin)) { $plugins[] = WP_PLUGIN_DIR . '/' . $plugin; } } return $plugins; }
protected function GetPostTemplate($post) { $id = $post->ID; $template = get_page_template_slug($id); $pagename = $post->post_name; $templates = array(); if ($template && 0 === validate_file($template)) { $templates[] = $template; } if ($pagename) { $templates[] = "page-{$pagename}.php"; } if ($id) { $templates[] = "page-{$id}.php"; } $templates[] = 'page.php'; return get_query_template('page', $templates); }
function get_file($path, $args = []) { // Initial tests and path assignment; note that `validate_file()` is a core WP function if (empty($path) || !is_string($path) || validate_file($path) > 0 || !file_exists($path)) { return; } // Attempt to fetch file contents if (!($contents = @file_get_contents($path))) { return; } // Process arguments $args = wp_parse_args($args, ['replace' => []]); // Optionally strip contents of specified strings if (is_array($args['replace']) && !empty($args['replace'])) { $contents = str_replace(array_keys($args['replace']), array_values($args['replace']), $contents); } // Return whatever we have return $contents; }
function wp_get_active_and_valid_plugins() { $plugins = array(); $active_plugins = (array) get_option('active_plugins', array()); // Check for hacks file if the option is enabled if (get_option('hack_file') && file_exists(ABSPATH . 'my-hacks.php')) { _deprecated_file('my-hacks.php', '1.5'); array_unshift($plugins, ABSPATH . 'my-hacks.php'); } if (empty($active_plugins) || wp_installing()) { return $plugins; } $network_plugins = is_multisite() ? wp_get_active_network_plugins() : false; foreach ($active_plugins as $plugin) { if (!validate_file($plugin) && '.php' == substr($plugin, -4) && file_exists(WP_PLUGIN_DIR . '/' . $plugin) && (!$network_plugins || !in_array(WP_PLUGIN_DIR . '/' . $plugin, $network_plugins))) { $plugins[] = WP_PLUGIN_DIR . '/' . $plugin; } } return $plugins; }
/** * Replaces core function to start preview theme output buffer. */ static function preview_theme() { // are we previewing? if (!isset($_GET['template']) || !wp_verify_nonce($_GET['preview_ctc'])) { return; } // can user preview? if (!current_user_can('switch_themes')) { return; } // hide admin bar in preview if (isset($_GET['preview_iframe'])) { show_admin_bar(false); } // sanitize template param $_GET['template'] = preg_replace('|[^a-z0-9_./-]|i', '', $_GET['template']); // check for manipulations if (validate_file($_GET['template'])) { return; } // replace future get_template calls with preview template add_filter('template', 'ChildThemeConfiguratorPreview::preview_theme_template_filter'); if (isset($_GET['stylesheet'])) { // sanitize stylesheet param $_GET['stylesheet'] = preg_replace('|[^a-z0-9_./-]|i', '', $_GET['stylesheet']); // check for manipulations if (validate_file($_GET['stylesheet'])) { return; } // replace future get_stylesheet calls with preview stylesheet add_filter('stylesheet', 'ChildThemeConfiguratorPreview::preview_theme_stylesheet_filter'); } // swap out theme mods with preview theme mods add_filter('pre_option_theme_mods_' . get_option('stylesheet'), 'ChildThemeConfiguratorPreview::preview_mods'); // impossibly high priority to test for stylesheets loaded after wp_head() add_action('wp_print_styles', 'ChildThemeConfiguratorPreview::test_css', 999999); // pass the wp_styles queue back to use for stylesheet handle verification add_action('wp_footer', 'ChildThemeConfiguratorPreview::parse_stylesheet'); }
public static function intercept_page_template_request($current) { // only perform this logic if the current requested assset is a page if (!is_page()) { return $current; } // get a list of our plugin page templates $intercept = apply_filters('qsot-templates-page-templates', array()); // find the name of the template requested by this page $template = get_page_template_slug(); // if the template is on the list of templates inside our plugin, then if (isset($intercept[$template])) { $templates = array(); // add our file to a list of files to search for in the plugin template dir if ($template && 0 === validate_file($template)) { $templates[] = $template; } // find any files that match the filename in the stylesheet dir, then the theme dir, then our plugin dir. if none are found, then use whatever the $current was when the function was called $current = apply_filters('qsot-locate-template', $current, $templates); } return $current; }
/** * Retrieve an array of active and valid plugin files. * * While upgrading or installing WordPress, no plugins are returned. * * The default directory is wp-content/plugins. To change the default * directory manually, define `WP_PLUGIN_DIR` and `WP_PLUGIN_URL` * in wp-config.php. * * @since 3.0.0 * @access private * * @return array Files. */ function wp_get_active_and_valid_plugins() { $plugins = array(); $active_plugins = (array) get_option('active_plugins', array()); if (empty($active_plugins) || wp_installing()) { return $plugins; } $network_plugins = is_multisite() ? wp_get_active_network_plugins() : false; foreach ($active_plugins as $plugin) { if (!validate_file($plugin) && '.php' == substr($plugin, -4) && file_exists(WP_PLUGIN_DIR . '/' . $plugin) && (!$network_plugins || !in_array(WP_PLUGIN_DIR . '/' . $plugin, $network_plugins))) { $plugins[] = WP_PLUGIN_DIR . '/' . $plugin; } } return $plugins; }
/** * Validate a plugin filename * * Checks that the file exists and {@link validate_file() is valid file}. If * it either condition is not met, returns false and adds an error to the * {@see MessageHandler} stack. * * @since 1.0 * * @param $filename Path to plugin * @return bool True if file exists and is valid, otherwise an exception will be thrown */ function validate_plugin($filename) { switch (validate_file($filename)) { case 1: case 2: throw new Exception(_r('Invalid plugin path.'), Errors::get_code('admin.plugins.invalid_path')); break; default: if (file_exists(get_plugin_dir() . $filename)) { return true; } else { throw new Exception(_r('Plugin file was not found.'), Errors::get_code('admin.plugins.not_found')); } } return false; }
/** * Start preview theme output buffer. * * Will only preform task if the user has permissions and template and preview * query variables exist. * * @since 2.6.0 */ function preview_theme() { if (!(isset($_GET['template']) && isset($_GET['preview']))) { return; } if (!current_user_can('switch_themes')) { return; } // Admin Thickbox requests if (isset($_GET['preview_iframe'])) { show_admin_bar(false); } $_GET['template'] = preg_replace('|[^a-z0-9_./-]|i', '', $_GET['template']); if (validate_file($_GET['template'])) { return; } add_filter('template', '_preview_theme_template_filter'); if (isset($_GET['stylesheet'])) { $_GET['stylesheet'] = preg_replace('|[^a-z0-9_./-]|i', '', $_GET['stylesheet']); if (validate_file($_GET['stylesheet'])) { return; } add_filter('stylesheet', '_preview_theme_stylesheet_filter'); } // Prevent theme mods to current theme being used on theme being previewed add_filter('pre_option_theme_mods_' . get_option('stylesheet'), '__return_empty_array'); ob_start('preview_theme_ob_filter'); }
/** * 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 * * @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 string|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, that file cannot be edited.' ) ); // case 2 : // wp_die( __('Sorry, can’t call files with their real path.' )); case 3 : wp_die( __( 'Sorry, that file cannot be edited.' ) ); } }
require_once ABSPATH . 'wp-admin/admin-header.php'; } if (file_exists(WPMU_PLUGIN_DIR . "/{$plugin_page}")) { include WPMU_PLUGIN_DIR . "/{$plugin_page}"; } else { include WP_PLUGIN_DIR . "/{$plugin_page}"; } } include ABSPATH . 'wp-admin/admin-footer.php'; exit; } elseif (isset($_GET['import'])) { $importer = $_GET['import']; if (!current_user_can('import')) { wp_die(__('You are not allowed to import.')); } if (validate_file($importer)) { wp_redirect(admin_url('import.php?invalid=' . $importer)); exit; } if (!isset($wp_importers[$importer]) || !is_callable($wp_importers[$importer][2])) { wp_redirect(admin_url('import.php?invalid=' . $importer)); exit; } /** * Fires before an importer screen is loaded. * * The dynamic portion of the hook name, `$importer`, refers to the importer slug. * * @since 3.5.0 */ do_action('load-importer-' . $importer);
require_once '../define.php'; if (!current_user_can('level_8')) { die("You must be a WordPress Administrator to view the Duplicator logs."); } $logs = glob(DUPLICATOR_SSDIR_PATH . '/*.log'); if (count($logs)) { @chmod(duplicator_safe_path($logs[0]), 0644); } if (count($logs)) { @usort($logs, create_function('$a,$b', 'return filemtime($b) - filemtime($a);')); } if (isset($_GET['logname'])) { $logname = trim($_GET['logname']); //prevent escaping the folder $validFiles = array_map('basename', $logs); if (validate_file($logname, $validFiles) > 0) { //Invalid filename provided, don't use it unset($logname); } //done with validFiles unset($validFiles); } if (!isset($logname) || !$logname) { $logname = basename($logs[0]); } $logpath = DUPLICATOR_SSDIR_PATH . '/' . $logname; $logfound = strlen($logname) > 0 ? true : false; $handle = @fopen($logpath, "c+"); $file = $handle ? fread($handle, filesize($logpath)) : ""; @fclose($handle); $plugins_url = plugins_url();
*/ $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';
/** * Render various admin template files * * @param string $view file slug * @since 0.4 */ function render($view = '') { if (empty($view)) { return; } $this->_set_global_query_for_tables($view); require_once ABSPATH . '/wp-admin/includes/class-wp-list-table.php'; require_once ABSPATH . '/wp-admin/includes/class-wp-posts-list-table.php'; require_once ABSPATH . '/wp-admin/includes/class-wp-media-list-table.php'; require_once FU_ROOT . '/lib/php/class-frontend-uploader-wp-media-list-table.php'; require_once FU_ROOT . '/lib/php/class-frontend-uploader-wp-posts-list-table.php'; $file = FU_ROOT . "/lib/views/manage-ugc-{$view}.tpl.php"; if (0 === validate_file($file)) { include_once $file; } }
/** * Matching of MD5 hashes * * @since 0.0.1 * @change 0.0.1 * * @hook array checksum_verifier_ignore_files * * @param array $checksums File checksums * @return array $matches File paths */ private static function _match_checksums($checksums) { /* Reset time limit */ if (!ini_get('safe_mode')) { set_time_limit(0); } /* Ignore files filter */ $ignore_files = (array) apply_filters('checksum_verifier_ignore_files', array('wp-config-sample.php', 'wp-includes/version.php')); /* Init matches */ $matches = array(); /* Loop files */ foreach ($checksums as $file => $checksum) { /* File path */ $file_path = ABSPATH . $file; /* Skip version.php */ if (in_array($file, $ignore_files)) { continue; } /* File check */ if (validate_file($file_path) !== 0 or !file_exists($file_path)) { continue; } /* Compare MD5 hashes */ if (md5_file($file_path) !== $checksum) { $matches[] = $file; } } return $matches; }
function sp_validate_plugin($plugin) { if (validate_file($plugin)) { return new WP_Error('plugin_invalid', sp_text('Invalid plugin path')); } if (!file_exists(SFPLUGINDIR . $plugin)) { return new WP_Error('plugin_not_found', sp_text('Plugin file does not exist')); } $installed_plugins = sp_get_plugins(); if (!isset($installed_plugins[$plugin])) { return new WP_Error('no_plugin_header', sp_text('The plugin does not have a valid header')); } return 0; }
* * @author Conor Mac Aoidh <*****@*****.**> * @license http://furasta.org/licence.txt The BSD License * @version 1.0 * @package plugin_architecture */ require 'header.php'; /** * check if user has permission to view page */ if (!$User->hasPerm('p')) { error('You have insufficient privelages to view this page. Please contact one of the administrators.', 'Permissions Error'); } $p_name = str_replace('-', ' ', @$_GET['p_name']); if ($p_name == '') { error('Undefined plugin error, please de-activate recently activated plugins to resolve the problem.', 'Plugin Error'); } $Plugins->adminPage($p_name); /** * allows plugins to have their own templates for plugin * pages */ $plugin = $Plugins->plugins($p_name); if (isset($plugin['admin']['template_override'])) { $template = $plugin['admin']['template_override']; if (validate_file($template)) { require HOME . $template; exit; } } require HOME . 'admin/layout/admin.php';
require (ABSPATH . WPINC . '/vars.php'); // Check for hacks file if the option is enabled if ( get_option('hack_file') ) { if ( file_exists(ABSPATH . 'my-hacks.php') ) require(ABSPATH . 'my-hacks.php'); } $current_plugins = get_option('active_plugins'); if ( is_array($current_plugins) && !defined('WP_INSTALLING') ) { foreach ( $current_plugins as $plugin ) { // check the $plugin filename // Validate plugin filename if ( validate_file($plugin) // $plugin must validate as file || '.php' != substr($plugin, -4) // $plugin must end with '.php' || !file_exists(WP_PLUGIN_DIR . '/' . $plugin) // $plugin must exist ) continue; include_once(WP_PLUGIN_DIR . '/' . $plugin); } unset($plugin); } unset($current_plugins); require (ABSPATH . WPINC . '/pluggable.php'); /* * In most cases the default internal encoding is latin1, which is of no use,
require ABSPATH . WPINC . '/vars.php'; // make taxonomies available to plugins and themes // @plugin authors: warning: this gets registered again on the init hook create_initial_taxonomies(); // Check for hacks file if the option is enabled if (get_option('hack_file')) { if (file_exists(ABSPATH . 'my-hacks.php')) { require ABSPATH . 'my-hacks.php'; } } $current_plugins = get_option('active_plugins'); if (is_array($current_plugins) && !defined('WP_INSTALLING')) { foreach ($current_plugins as $plugin) { // check the $plugin filename // Validate plugin filename if (validate_file($plugin) || '.php' != substr($plugin, -4) || !file_exists(WP_PLUGIN_DIR . '/' . $plugin)) { continue; } include_once WP_PLUGIN_DIR . '/' . $plugin; } unset($plugin); } unset($current_plugins); require ABSPATH . WPINC . '/pluggable.php'; /* * In most cases the default internal encoding is latin1, which is of no use, * since we want to use the mb_ functions for utf-8 strings */ if (function_exists('mb_internal_encoding')) { if (!@mb_internal_encoding(get_option('blog_charset'))) { mb_internal_encoding('UTF-8');
/** * Validate the plugin path. * * Checks that the file exists and is valid file. * * @since 1.0 * @uses validate_file() to check the passed plugin identifier isn't malformed * @uses bb_get_plugin_path() to get the full path of the plugin * @uses bb_get_plugins() to get the plugins that actually exist * * @param string $plugin Plugin Path * @param string $location The location of plugin, one of 'user', 'core' or 'all' * @param string $type The type of plugin, one of 'all', 'autoload' or 'normal' * @return nxt_Error|int 0 on success, nxt_Error on failure. */ function bb_validate_plugin($plugin, $location = 'all', $type = 'all') { if (validate_file(trim($plugin))) { return new nxt_Error('plugin_invalid', __('Invalid plugin path.')); } $path = bb_get_plugin_path(trim($plugin)); if (!file_exists($path)) { return new nxt_Error('plugin_not_found', __('Plugin file does not exist.')); } if (!in_array(trim($plugin), array_keys(bb_get_plugins($location, $type)))) { return new nxt_Error('plugin_not_available', __('That type of plugin is not available in the specified location.')); } return $path; }
public static function is_module($module) { return !empty($module) && !validate_file($module, Jetpack::get_available_modules()); }
/** * Retrieve path of page template in current or parent template. * * Will first look for the specifically assigned page template * The will search for 'page-{slug}.php' followed by 'page-id.php' * and finally 'page.php' * * @since 1.5.0 * * @return string */ function get_page_template() { $id = get_queried_object_id(); $template = get_page_template_slug(); $pagename = get_query_var('pagename'); if (!$pagename && $id) { // If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object $post = get_queried_object(); $pagename = $post->post_name; } $templates = array(); if ($template && 0 === validate_file($template)) { $templates[] = $template; } if ($pagename) { $templates[] = "page-{$pagename}.php"; } if ($id) { $templates[] = "page-{$id}.php"; } $templates[] = 'page.php'; return get_query_template('page', $templates); }
/** * Validate the plugin path. * * Checks that the file exists and {@link validate_file() is valid file}. * * @since 2.5.0 * * @param string $plugin Plugin Path * @return WP_Error|int 0 on success, WP_Error on failure. */ function validate_plugin($plugin) { if (validate_file($plugin)) { return new WP_Error('plugin_invalid', __('Invalid plugin path.')); } if (!file_exists(WP_PLUGIN_DIR . '/' . $plugin)) { return new WP_Error('plugin_not_found', __('Plugin file does not exist.')); } $installed_plugins = get_plugins(); if (!isset($installed_plugins[$plugin])) { return new WP_Error('no_plugin_header', __('The plugin does not have a valid header.')); } return 0; }
/** * Use the absolute path to an image to set an attachment type for a given item. * * @since 2.4.0 * * @param string $type The attachment type to create (avatar or cover_image). Default: avatar. * @param array $args { * @type int $item_id The ID of the object (Required). Default: 0. * @type string $object The object type (eg: group, user, blog) (Required). Default: 'user'. * @type string $component The component for the object (eg: groups, xprofile, blogs). Default: ''. * @type string $image The absolute path to the image (Required). Default: ''. * @type int $crop_w Crop width. Default: 0. * @type int $crop_h Crop height. Default: 0. * @type int $crop_x The horizontal starting point of the crop. Default: 0. * @type int $crop_y The vertical starting point of the crop. Default: 0. * } * @return bool True on success, false otherwise. */ function bp_attachments_create_item_type($type = 'avatar', $args = array()) { if (empty($type) || $type !== 'avatar' && $type !== 'cover_image') { return false; } $r = bp_parse_args($args, array('item_id' => 0, 'object' => 'user', 'component' => '', 'image' => '', 'crop_w' => 0, 'crop_h' => 0, 'crop_x' => 0, 'crop_y' => 0), 'create_item_' . $type); if (empty($r['item_id']) || empty($r['object']) || !file_exists($r['image']) || !@getimagesize($r['image'])) { return false; } // Make sure the file path is safe if (0 !== validate_file($r['image'])) { return false; } // Set the component if not already done if (empty($r['component'])) { if ('user' === $r['object']) { $r['component'] = 'xprofile'; } else { $r['component'] = $r['object'] . 's'; } } // Get allowed mimes for the Attachment type and check the image one is. $allowed_mimes = bp_attachments_get_allowed_mimes($type); $is_allowed = wp_check_filetype($r['image'], $allowed_mimes); // It's not an image. if (!$is_allowed['ext']) { return false; } // Init the Attachment data $attachment_data = array(); if ('avatar' === $type) { // Set crop width for the avatar if not given if (empty($r['crop_w'])) { $r['crop_w'] = bp_core_avatar_full_width(); } // Set crop height for the avatar if not given if (empty($r['crop_h'])) { $r['crop_h'] = bp_core_avatar_full_height(); } if (is_callable($r['component'] . '_avatar_upload_dir')) { $dir_args = array($r['item_id']); // In case of xprofile, we need an extra argument if ('xprofile' === $r['component']) { $dir_args = array(false, $r['item_id']); } $attachment_data = call_user_func_array($r['component'] . '_avatar_upload_dir', $dir_args); } } elseif ('cover_image' === $type) { $attachment_data = bp_attachments_uploads_dir_get(); // The BP Attachments Uploads Dir is not set, stop. if (!$attachment_data) { return false; } // Default to members for xProfile $object_subdir = 'members'; if ('xprofile' !== $r['component']) { $object_subdir = sanitize_key($r['component']); } // Set Subdir $attachment_data['subdir'] = $object_subdir . '/' . $r['item_id'] . '/cover-image'; // Set Path $attachment_data['path'] = trailingslashit($attachment_data['basedir']) . $attachment_data['subdir']; } if (!isset($attachment_data['path']) || !isset($attachment_data['subdir'])) { return false; } // It's not a regular upload, we may need to create some folders if (!is_dir($attachment_data['path'])) { if (!wp_mkdir_p($attachment_data['path'])) { return false; } } // Set the image name and path $image_file_name = wp_unique_filename($attachment_data['path'], basename($r['image'])); $image_file_path = $attachment_data['path'] . '/' . $image_file_name; // Copy the image file into the avatar dir if (!copy($r['image'], $image_file_path)) { return false; } // Init the response $created = false; // It's an avatar, we need to crop it. if ('avatar' === $type) { $created = bp_core_avatar_handle_crop(array('object' => $r['object'], 'avatar_dir' => trim(dirname($attachment_data['subdir']), '/'), 'item_id' => (int) $r['item_id'], 'original_file' => trailingslashit($attachment_data['subdir']) . $image_file_name, 'crop_w' => $r['crop_w'], 'crop_h' => $r['crop_h'], 'crop_x' => $r['crop_x'], 'crop_y' => $r['crop_y'])); // It's a cover image we need to fit it to feature's dimensions } elseif ('cover_image' === $type) { $cover_image = bp_attachments_cover_image_generate_file(array('file' => $image_file_path, 'component' => $r['component'], 'cover_image_dir' => $attachment_data['path'])); $created = !empty($cover_image['cover_file']); } // Remove copied file if it fails if (!$created) { @unlink($image_file_path); } // Return the response return $created; }