/** * Used internally to log error messages to a log file. * * @since 1.0 */ public static function log( $message, $src = 'Feed to Post', $log_level = null ) { // check if the logging function exists in the core if ( function_exists( 'wprss_log' ) ) { // If log level is declared in core, or the log level is default if( is_null($log_level) || $log_level = self::get_log_level_value($log_level) ) { if( is_null($log_level) ) $log_level = self::LOG_LEVEL_ERROR; wprss_log( $message, $src, $log_level ); } } else { $date = date( 'd-m-Y H:i:s' ); $source = 'Feed to Post' . ( ( strlen( $src ) > 0 )? " ($src)" : '' ) ; $str = "[$date] $source: '$message'\n"; file_put_contents( WPRSS_FTP_LOG_FILE , $str, FILE_APPEND ); } }
/** * Calls the EDD Software Licensing API to perform licensing tasks on the addon's store server. * * @since 4.4.5 */ function wprss_edd_licensing_api($addon, $license_key = NULL, $action = 'check_license', $return = 'license') { // If no license argument was given if ($license_key === NULL) { // Get the license key $license_key = wprss_get_license_key($addon); } // Get the license status from the DB $license_status = wprss_get_license_status($addon); // Prepare constants $item_name = strtoupper($addon); $item_name_constant = constant("WPRSS_{$item_name}_SL_ITEM_NAME"); $store_url_constant = constant("WPRSS_{$item_name}_SL_STORE_URL"); // data to send in our API request $api_params = array('edd_action' => $action, 'license' => sanitize_text_field($license_key), 'item_name' => urlencode($item_name_constant), 'url' => urlencode(network_site_url()), 'time' => time()); // Send the request to the API $response = wp_remote_get(add_query_arg($api_params, $store_url_constant)); // If the response is an error, return the value in the DB if (is_wp_error($response)) { wprss_log(sprintf('Licensing API request failed: %1$s', $response->get_error_message()), __FUNCTION__, WPRSS_LOG_LEVEL_WARNING); return $license_status; } // decode the license data $license_data = json_decode(wp_remote_retrieve_body($response)); // Could not decode response JSON if (is_null($license_data)) { wprss_log(sprintf('Licensing API: Failed to decode response JSON'), __FUNCTION__, WPRSS_LOG_LEVEL_WARNING); return $license_status; } // Update the DB option $license_statuses = get_option('wprss_settings_license_statuses'); $license_statuses["{$addon}_license_status"] = $license_data->license; $license_statuses["{$addon}_license_expires"] = $license_data->expires; update_option('wprss_settings_license_statuses', $license_statuses); // Return the data if (strtoupper($return) === 'ALL') { return $license_data; } else { return isset($license_data->{$return}) ? $license_data->{$return} : null; } }
/** * Get the size of the image, which is locally cached. * * @since 4.6.10 * @return array A numeric array, where index 0 holds image width, and index 1 holds image height. * @throws Exception If image file is unreadable. */ public function get_size() { if (!isset($this->_size)) { $error_caption = 'Could not get image size'; $path = $this->get_local_path(); if (!$this->is_readable()) { throw new Exception(sprintf('%1$s: image file is not readable', $path)); } // Trying simplest way if ($size = getimagesize($path)) { $this->_size = array(0 => $size[0], 1 => $size[1]); } wprss_log(sprintf('Tried `getimagesize()`: %1$s', empty($this->_size) ? 'failure' : 'success'), __METHOD__, WPRSS_LOG_LEVEL_SYSTEM); if (!$this->_size && function_exists('gd_info')) { $image = file_get_contents($path); $image = imagecreatefromstring($image); $width = imagesx($image); $height = imagesy($image); $this->_size = array(0 => $width, 1 => $height); wprss_log(sprintf('Tried GD: %1$s', empty($this->_size) ? 'failure' : 'success'), __METHOD__, WPRSS_LOG_LEVEL_SYSTEM); } } return $this->_size; }
function wprss_convert_fb_a_tag($matches) { $url = preg_replace_callback('/\s*href\s*=\s*(\"([^"]*\")|\'[^\']*\'|([^\'">\s]+))/', 'wprss_convert_fb_url', $matches[1]); $tag = "<a href=$url>" . $matches[2] . '</a>'; wprss_log("Converted FB link " . $matches[0] . " to {$tag}", WPRSS_LOG_LEVEL_INFO ); return $tag; }
/** * Fetches the feed items from a feed at the given URL. * * Called from 'wprss_fetch_insert_single_feed_items' * * @since 3.0 */ function wprss_get_feed_items($feed_url, $source) { // Add filters and actions prior to fetching the feed items add_filter('wp_feed_cache_transient_lifetime', 'wprss_feed_cache_lifetime'); add_action('wp_feed_options', 'wprss_do_not_cache_feeds'); /* Fetch the feed from the soure URL specified */ $feed = wprss_fetch_feed($feed_url, $source); // Remove previously added filters and actions remove_action('wp_feed_options', 'wprss_do_not_cache_feeds'); remove_filter('wp_feed_cache_transient_lifetime', 'wprss_feed_cache_lifetime'); if (!is_wp_error($feed)) { // Return the items in the feed. return $feed->get_items(); } else { wprss_log('Failed to fetch feed "' . $feed_url . '". ' . $feed->get_error_message()); return NULL; } }
/** * Calls the EDD Software Licensing API to perform licensing tasks on the addon's store server. * * @param string $addonId The ID of the addon * @param string $action The action to perform on the license. * @param string $return What to return from the response. If 'ALL', the entire license status object is returned, * Otherwise, the property with name $return will be returned, or null if it doesn't exist. * @return mixed */ public function sendApiRequest($addonId, $action = 'check_license', $return = 'license') { // Get the license for the addon $license = $this->getLicense($addonId); // Use blank license if addon license does not exist if ($license === null) { $license = new License(); } // Addon Uppercase ID $addonUid = strtoupper($addonId); // Prepare constants $itemName = constant("WPRSS_{$addonUid}_SL_ITEM_NAME"); $storeUrl = constant("WPRSS_{$addonUid}_SL_STORE_URL"); try { $licenseData = $this->api($storeUrl, array('edd_action' => $action, 'license' => $license, 'item_name' => $itemName)); } catch (Exception $e) { wprss_log(sprintf('Could not retrieve licensing data from "%1$s": %2$s', $storeUrl, $e->getMessage()), __FUNCTION__, WPRSS_LOG_LEVEL_WARNING); return $license->getStatus(); } // Update the DB option $license->setStatus($licenseData->license); $license->setExpiry($licenseData->expires); $this->saveLicenseStatuses(); // Return the data if (strtoupper($return) === 'ALL') { return $licenseData; } else { return isset($licenseData->{$return}) ? $licenseData->{$return} : null; } }
/** * Shutdown function for detecting if the PHP script reaches the maximum execution time limit * while importing a feed. * * @since 4.6.6 */ function wprss_detect_exec_timeout() { // Get last error if ($error = error_get_last()) { // Check if it is an E_ERROR and if it is a max exec time limit error if ($error['type'] === E_ERROR && stripos($error['message'], 'maximum execution') === 0) { // If the importing process was running if (array_key_exists('wprss_importing_feed', $GLOBALS) && $GLOBALS['wprss_importing_feed'] !== NULL) { // Get the ID of the feed that was importing $feed_ID = $GLOBALS['wprss_importing_feed']; // Perform clean up wprss_flag_feed_as_idle($feed_ID); $msg = sprintf(__('The PHP script timed out while importing an item from this feed, after %d seconds.', WPRSS_TEXT_DOMAIN), wprss_get_item_import_time_limit()); update_post_meta($feed_ID, 'wprss_error_last_import', $msg); // Log the error wprss_log('The PHP script timed out while importing feed #' . $feed_ID, NULL, WPRSS_LOG_LEVEL_ERROR); } } } }
/** * Converts a single wprss_feed_item to a post. * * @param feed The wprss_feed_item object to convert * @param source The wprss_feed id of the feed item. Used to retrieve settings for conversion. * @since 1.0 */ public static function convert_to_post( $item, $source, $permalink ) { WPRSS_FTP_Utils::log( 'Starting conversion to post', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO ); $error_source = 'convert_to_post'; $source_obj = get_post( $source ); // If the feed source does not exist, exit if ( $source_obj === null || $source === '' ) { // unschedule any scheduled updates wprss_feed_source_update_stop_schedule( $source ); WPRSS_FTP_Utils::log_object( 'Source does not exist. Aborting.', $source, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_WARNING ); return NULL; } else { // If the feed source exists, but is trashed or paused, exit if ( $source_obj->post_status !== 'trash' && !wprss_is_feed_source_active( $source ) ) { WPRSS_FTP_Utils::log_object( 'Source is inactive or trashed. Aborting.', $source, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_NOTICE ); return NULL; } } # If we got NULL, pass it on if ( $item === NULL ) { WPRSS_FTP_Utils::log( 'Item is null. Aborting.', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_WARNING ); return NULL; } # If the item has an empty permalink, log an error message if ( empty( $permalink ) ){ WPRSS_FTP_Utils::log( 'Encounted feed item with no permalink for feed source "' . $source_obj->post_title . '". Possibly a corrupt RSS feed.', $error_source, WPRSS_FTP_Utils::LOG_LEVEL_WARNING ); } # check existence of permalink $existing_permalinks = self::get_existing_permalinks( $source ); # If permalink exists, do nothing if ( in_array( $permalink, $existing_permalinks ) ) { WPRSS_FTP_Utils::log_object( 'Item with this permalink already exists. Aborting.', $permalink, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_NOTICE ); return NULL; } # Get the computed options ( global settings merged against individual settings ) $options = WPRSS_FTP_Settings::get_instance()->get_computed_options( $source ); if ( $options['post_type'] === 'wprss_feed_item' ) { WPRSS_FTP_Utils::log_object( 'Legacy import method. Aborting.', $source, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO ); return $item; } self::_prepareItem( $item ); /*============================================== * 1) DETERMINE THE POST AUTHOR USER */ WPRSS_FTP_Utils::log( 'Determining post author...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO ); // Get author-related options from meta, or from global settings, if not found $def_author = $options['def_author']; $fallback_author = $options['fallback_author']; $author_fallback_method = $options['author_fallback_method']; $fallback_user = get_user_by( 'id', $fallback_author ); if ( ! is_object( $fallback_user ) ) { $fallback_user = get_user_by( 'login', $fallback_author ); } $fallback_user = $fallback_user->ID; $no_author_found = $options['no_author_found']; // Determined user. Start with NULL $user = NULL; // If using an existing user, we are done. if ( $def_author !== '.' ) { $user = $def_author; WPRSS_FTP_Utils::log( 'Author is preset.', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); } // If getting feed from author, determine the user to assign to the post else { /* Get the author from the feed * If author not found - use fallback user */ if ( $author = $item->get_author() ) { $has_author_name = $author->get_name() !== '' && is_string( $author->get_name() ); $has_author_email = $author->get_email() !== '' && is_string( $author->get_email() ); } else { $has_author_name = $has_author_email = false; } // Author NOT found if ( $author === NULL || !( $has_author_name || $has_author_email ) ) { // If option to use fallback when no author found, use fallback if ( $no_author_found === 'fallback' ) { $user = $fallback_user; WPRSS_FTP_Utils::log_object( 'Author is a fallback user.', $fallback_user, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); } // Otherwise, skip the post else { WPRSS_FTP_Utils::log( 'Author could not be determined. Aborting.', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_WARNING ); return NULL; } } // Author found else { WPRSS_FTP_Utils::log( 'Author found in feed.', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $author_name = $author->get_name(); $author_email = $author->get_email(); // No author name fix if ( !$has_author_name && $has_author_email ) { // "Email is actually the name"" fix if ( filter_var( $author_email, FILTER_VALIDATE_EMAIL ) === FALSE ) { // Set the name to the email, and reset the email $author_name = $author_email; $author_email = ''; // Set the flags appropriately $has_author_name = TRUE; $has_author_email = FALSE; } else { $parts = explode("@", $author_email); $author_name = $parts[0]; $has_author_name = TRUE; } WPRSS_FTP_Utils::log_object( sprintf( 'Author name determined from email "%1$s".', $author_email), $author_name, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); } // No author email fix if ( !$has_author_email && $has_author_name ) { // Get rid of wwww and everything before it $domain_name = preg_replace( '/^www\./', '', $_SERVER['SERVER_NAME'] ); // Lowercase the author name, remove the spaces $email_username = str_replace( ' ', '', strtolower($author_name) ); // Remove all disallowed chars $email_username = preg_replace('![^\w\d_.]!', '', $email_username); // For domains with no TLDN suffix (such as localhost) if ( stripos( $domain_name, '.' ) === FALSE ) $domain_name .= '.com'; // Generate the email $author_email = "$email_username@$domain_name"; $has_author_email = TRUE; WPRSS_FTP_Utils::log_object( sprintf( 'Author email determined from name "%1$s".', $author_name), $author_email, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); } $user_obj = FALSE; // If email is available, check if a user with this email exists $user_obj = get_user_by( 'email', $author_email ); // If search by email failed, search the email for the login if ( !$user_obj ) { $user_obj = get_user_by( 'login', $author_email ); } // If search by email failed, search by name if ( !$user_obj ) { $user_obj = get_user_by( 'login', $author_name ); } // Feed author has a user on site if ( $user_obj !== FALSE && isset( $user_obj->ID ) ) { $user = $user_obj->ID; WPRSS_FTP_Utils::log_object( 'User found in system', $user, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); } // Author has no user on site else { $new_user_id = NULL; // Fallback method: create user if ( $author_fallback_method === 'create' ) { $random_password = wp_generate_password( $length = 12, $include_standard_special_chars = false ); $new_user_id = wp_create_user( $author_name, $random_password, $author_email ); WPRSS_FTP_Utils::log_object( 'User not found in system. Attempted to create', $author_email, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); if ( !$new_user_id || ($is_error = is_wp_error( $new_user_id )) ) { WPRSS_FTP_Utils::log_object( 'User could not be created.', $is_error ? $new_user_id->get_error_message() : $author_email, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_NOTICE ); $new_user_id = null; } else { // Check if the author has a URI in the feed $author_uri = $author->get_link(); if ( $author_uri !== NULL ) { // Filter the meta field and value $uri_meta = apply_filters( 'wprss_author_uri_meta_field', 'wprss_author_uri' ); $author_uri = apply_filters( 'wprss_author_uri', $author_uri, $source ); // Add the URI as user meta add_user_meta( $user, $uri_meta, $author_uri ); // Add the URI to the author wp_update_user( array( 'ID' => $new_user_id, 'user_url' => $author_uri, ) ); } // Check if the author name has spaces if ( strpos( $author_name, ' ' ) !== FALSE ) { // Split name into parts $split = explode( ' ', $author_name ); $first_name = ''; $last_name = ''; // check if we have more than one parts if ( ( $c = count( $split ) ) > 1 ) { $m = $c / 2; $first_half = array_slice( $split, 0, $m); $second_half = array_slice( $split, $m ); $first_name = implode( ' ', $first_half ); $last_name = implode( ' ', $second_half ); } // Update the user wp_update_user( array( 'ID' => $new_user_id, 'first_name' => $first_name, 'last_name' => $last_name, ) ); } } } // Fallback method: existing user // OR creating a user failed if ( $new_user_id === NULL ) { $new_user_id = $fallback_user; WPRSS_FTP_Utils::log_object( 'Falling back to existing user', $new_user_id, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); } $user = $new_user_id; } } } WPRSS_FTP_Utils::log_object( 'Post author determined', $user, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO ); // Get WordPress' GMT offset in hours, and PHP's timezone $wp_tz = function_exists('wprss_get_timezone_string') ? wprss_get_timezone_string() : get_option( 'timezone_string ' ); $php_tz = date_default_timezone_get(); // Set Timezone to WordPress' date_default_timezone_set( $wp_tz ); WPRSS_FTP_Utils::log_object( 'Default timezone temporarily changed', $wp_tz, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); // Prepare the rest of the post data $date_timestamp = ( $options['post_date'] === 'original' && ( $date_timestamp = $item->get_date( 'U' ) ) ) ? $date_timestamp : date( 'U' ); // Fall back to current date if explicitly configured, or no date // Prepare post dates $post_date = date( 'Y-m-d H:i:s', $date_timestamp ); $post_date_gmt = gmdate( 'Y-m-d H:i:s', $date_timestamp ); WPRSS_FTP_Utils::log_object( 'Post timestamp determined', $date_timestamp, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); // Reset Timezone to PHP's date_default_timezone_set( $php_tz ); WPRSS_FTP_Utils::log_object( 'Default timezone restored', $php_tz, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); // Prepare the post tags $tags_str = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'post_tags' ); $tags = array_map( 'trim', explode( ',', $tags_str ) ); if( count( $tags ) ) WPRSS_FTP_Utils::log_object( 'Tags will be added', $tags_str, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); /*============================================== * 2) APPLY FILTERS TO POST FIELDS */ WPRSS_FTP_Utils::log( 'Applying filters to post fields...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); WPRSS_FTP_Utils::log( 'Applying post_title filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $post_title = apply_filters( 'wprss_ftp_converter_post_title', $item->get_title(), $source ); WPRSS_FTP_Utils::log( 'Applying post_content filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $post_content = apply_filters( 'wprss_ftp_converter_post_content', $item->get_content(), $source ); WPRSS_FTP_Utils::log( 'Applying post_status filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $post_status = apply_filters( 'wprss_ftp_converter_post_status', $options['post_status'], $source ); WPRSS_FTP_Utils::log( 'Applying post_comments filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $post_comments = apply_filters( 'wprss_ftp_converter_post_comments', $options['comment_status'], $source ); WPRSS_FTP_Utils::log( 'Applying post_type filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $post_type = apply_filters( 'wprss_ftp_converter_post_type', $options['post_type'], $source ); WPRSS_FTP_Utils::log( 'Applying post_format filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $post_format = apply_filters( 'wprss_ftp_converter_post_format', $options['post_format'], $source ); WPRSS_FTP_Utils::log( 'Applying post_terms filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $post_terms = apply_filters( 'wprss_ftp_converter_post_terms', $options['post_terms'], $source ); WPRSS_FTP_Utils::log( 'Applying post_taxonomy filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $post_taxonomy = apply_filters( 'wprss_ftp_converter_post_taxonomy', $options['post_taxonomy'], $source ); WPRSS_FTP_Utils::log( 'Applying permalink filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $permalink = apply_filters( 'wprss_ftp_converter_permalink', $permalink, $source ); WPRSS_FTP_Utils::log( 'Applying post_author filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $post_author = apply_filters( 'wprss_ftp_converter_post_author', $user, $source ); WPRSS_FTP_Utils::log( 'Applying post_date filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $post_date = apply_filters( 'wprss_ftp_converter_post_date', $post_date, $source ); WPRSS_FTP_Utils::log( 'Applying post_date_gmt filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $post_date_gmt = apply_filters( 'wprss_ftp_converter_post_date_gmt', $post_date_gmt, $source ); WPRSS_FTP_Utils::log( 'Applying post_tags filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $post_tags = apply_filters( 'wprss_ftp_converter_post_tags', $tags, $source ); WPRSS_FTP_Utils::log( 'Applying post_language filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $post_language = apply_filters( 'wprss_ftp_converter_post_language', $options['post_language'], $source ); WPRSS_FTP_Utils::log( 'Applying post_site filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $post_site = apply_filters( 'wprss_ftp_converter_post_site', $options['post_site'], $source ); WPRSS_FTP_Utils::log( 'Filters applied', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $post_comments = ( WPRSS_FTP_Utils::multiboolean( $post_comments ) === TRUE )? 'open' : 'close'; WPRSS_FTP_Utils::log_object( 'Comments status determined', $post_comments, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); /*============================================== * 3) CREATE THE POST */ // Initialize the excerpt to an empty string $post_excerpt = ''; // Prepare the post data WPRSS_FTP_Utils::log( 'Begin creating post...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); $post = array( 'post_title' => $post_title, 'post_content' => $post_content, 'post_excerpt' => $post_excerpt, 'post_date' => $post_date, 'post_date_gmt' => $post_date_gmt, 'post_status' => $post_status, 'post_type' => $post_type, 'post_author' => $post_author, 'tags_input' => implode( ', ' , $post_tags ), 'comment_status' => $post_comments ); /** * Filter the post args. * @var array $post Array containing the post fields * @var WP_Post $source An post that represents the feed source * @var SimplePie_Item $item The feed item currently being processed */ $post = apply_filters( 'wprss_ftp_post_args', $post, $source, $item ); WPRSS_FTP_Utils::log( 'Post args filters applied', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); /*============================================== * 4) INSERT THE POST */ if ( defined( 'ICL_SITEPRESS_VERSION' ) ) @include_once( WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php' ); if ( defined( 'ICL_LANGUAGE_CODE' ) ) { $_POST['icl_post_language'] = $language_code = ICL_LANGUAGE_CODE; WPRSS_FTP_Utils::log_object( 'WPMP Detected. Language determined.', $language_code, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO ); } // check for multisite option - and switch blogs if necessaray $switch_success = FALSE; if ( WPRSS_FTP_Utils::is_multisite() && $post_site !== '' ) { global $switched; if( $switch_success = switch_to_blog( $post_site ) ) WPRSS_FTP_Utils::log_object( 'Switched blog.', $post_site, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); else WPRSS_FTP_Utils::log_object( 'Could not switch to blog.', $post_site, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_NOTICE ); } // Check if embedded content is allowed $allow_embedded_content = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'allow_embedded_content' ); // If embedded content is allowed, remove KSES filtering if ( WPRSS_FTP_Utils::multiboolean( $allow_embedded_content ) === TRUE ) { kses_remove_filters(); WPRSS_FTP_Utils::log( 'Embedded content allowed', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO ); } // Insert the post $inserted_id = wp_insert_post( $post ); // If embedded content is allowed, re-add KSES filtering if ( WPRSS_FTP_Utils::multiboolean( $allow_embedded_content ) === TRUE ) { kses_init_filters(); } if ( !is_wp_error( $inserted_id ) ) { if ( is_object( $inserted_id ) ) { if ( isset( $inserted_id['ID'] ) ) { $inserted_id = $inserted_id['ID']; } elseif ( isset( $inserted_id->ID ) ) { $inserted_id = $inserted_id->ID; } } WPRSS_FTP_Utils::log_object( 'Post created', $inserted_id, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO ); if ( $user === NULL ) WPRSS_FTP_Utils::log( 'Failed to determine a user for post #$inserted_id', $error_source, WPRSS_FTP_Utils::LOG_LEVEL_WARNING ); // Update the post format set_post_format( $inserted_id, $post_format ); if ( function_exists( 'wpml_update_translatable_content' ) ) { if ( $post_language === '' || $post_language === NULL ) { $post_language = ICL_LANGUAGE_CODE; } // Might be needed by WPML? $_POST['icl_post_language '] = $post_language; // Update the translation for the created post wpml_add_translatable_content( 'post_' . $post_type, $inserted_id, $post_language ); wpml_update_translatable_content( 'post_' . $post_type, $inserted_id, $post_language ); icl_cache_clear($post_type.'s_per_language'); WPRSS_FTP_Utils::log_object( 'Post translated', $post_language, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO ); } /*============================================== * 5) ADD THE POST META DATA */ WPRSS_FTP_Utils::log( 'Adding post meta', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO ); $thumbnail = ''; $enclosure_image = ''; if ( $enclosure = $item->get_enclosure() ) { $thumbnail = $enclosure->get_thumbnail(); $enclosure_image = $enclosure->get_link(); $enclosure_player = $enclosure->get_player(); WPRSS_FTP_Utils::log( 'Item has enclosure', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO ); } // Prepare the post meta, and pass though the wprss_ftp_post_meta filter. // Note: Prepend '!' to ignore the 'wprss_ftp_' prefix $post_meta_data = apply_filters( 'wprss_ftp_post_meta', array( '!wprss_item_permalink' => $permalink, 'feed_source' => $source, 'media:thumbnail' => $thumbnail, 'enclosure:thumbnail' => $enclosure_image, 'enclosure_link' => $enclosure_image, // Included twice for code readablity 'enclosure_player' => $enclosure_player, 'import_date' => time(), '!wprss_item_date' => $date_timestamp, // Required by core '!wprss_feed_id' => $source, ), $inserted_id, $source, $item ); WPRSS_FTP_Utils::log_object( 'Post meta filters applied', $inserted_id, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); // Insert the post meta WPRSS_FTP_Meta::get_instance()->add_meta( $inserted_id, $post_meta_data ); WPRSS_FTP_Utils::log( 'Post meta added', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO ); /*============================================== * 6) ADD THE TAXONOMY TERMS * $all_post_terms = ( !is_array( $post_terms ) )? array() : $post_terms; // Check if the source auto creates taxonomy terms $auto_create_terms = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'post_auto_tax_terms' ); // If yes ... if ( WPRSS_FTP_Utils::multiboolean( $auto_create_terms ) === TRUE ) { // Get the feed categories $categories = $item->get_categories(); if ( is_array( $categories ) && count( $categories ) > 0 ) { // For each category in the feed item // Turn the categories into an array $new_categories = array(); foreach( $categories as $cat ) { $new_categories[] = array( 'name' => $cat->get_label(), 'args' => array(), ); } // Filter the categories $categories = apply_filters( 'wprss_auto_create_terms', $new_categories, $post_taxonomy, $source ); foreach ( $categories as $category_obj ) { $category = $category_obj['name']; // Find the term that matches that category $cat_term = term_exists( $category , $post_taxonomy ); // If the term does not exist create it if ( $cat_term === 0 || $cat_term === NULL ) { // check if parent field exists, and turn the slug into an id if ( isset( $category_obj['args']['parent'] ) ) { // Get the slug, and find the term by the slug $parent_slug = $category_obj['args']['parent']; $parent_term = get_term_by( 'slug', $parent_slug, $post_taxonomy, 'ARRAY_A' ); // If term not found, removed the parent arg if ( $parent_term === FALSE ) { unset( $category_obj['args']['parent'] ); } // Otherwise, change the slug to the id else $category_obj['args']['parent'] = intval( $parent_term['term_id'] ); } // Insert the term $cat_term = wp_insert_term( $category, $post_taxonomy, $category_obj['args'] ); delete_option($post_taxonomy."_children"); // clear the cache } $term_id = $cat_term['term_id']; $term_obj = get_term_by( 'id', $term_id, $post_taxonomy, 'ARRAY_A' ); if ( $term_obj !== FALSE && $term_obj !== NULL ) { if ( !is_array($all_post_terms) ) { WPRSS_FTP_Utils::log_object( 'The $all_post_terms variable is not an array:', $all_post_terms, $error_source ); } else { // Add it to the list of terms to add $all_post_terms[] = $term_obj['slug']; } } } } } $wp_categories_return = wp_set_object_terms( $inserted_id, $all_post_terms, $post_taxonomy, FALSE ); if ( !is_array( $wp_categories_return ) ) { WPRSS_FTP_Utils::log_object( "Possible error while inserting taxonomy terms for post #$inserted_id:", $all_post_terms ); } */ wprss_ftp_add_taxonomies_to_post( $inserted_id, $source, $item ); WPRSS_FTP_Utils::log( 'Added taxonomies', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO ); /*============================================== * 8) CUSTOM FIELD MAPPING */ WPRSS_FTP_Utils::log( 'Mapping custom fields', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO ); // Get the namespaces $cfm_namespaces = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'rss_namespaces' ); $cfm_namespaces = ( $cfm_namespaces === '' )? array() : $cfm_namespaces; // Get the tags $cfm_tags = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'rss_tags' ); $cfm_tags = ( $cfm_tags === '' )? array() : $cfm_tags; // Get the custom fields $cfm_fields = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'custom_fields' ); $cfm_fields = ( $cfm_fields === '' )? array() : $cfm_fields; // For each custom field mapping for ( $i = 0; $i < count( $cfm_namespaces ); $i++ ) { // Get the URL of the namespace $namespace_url = WPRSS_FTP_Settings::get_namespace_url( $cfm_namespaces[$i] ); // If the namespace url is NULL (namespace no longer exists in the settings), skip to next mapping if ( $namespace_url === NULL ) continue; // Match the syntax "tagname[attrib]" in the tag name preg_match('/([^\[]+) (\[ ([^\]]+) \])?/x', $cfm_tags[$i], $m); // If no matches, stop. Tag name is not correct. Possibly empty if ( !is_array($m) || count($m) < 2 ) continue; // Get the tag and attribute from the matches $tag_name = $m[1]; $attrib = ( isset( $m[3] ) )? $m[3] : NULL; // Get the tag from the feed item $item_tags = $item->get_item_tags( $namespace_url, $tag_name ); // Check if the tag exists. If not, skip to next mapping if ( !isset( $item_tags[0] ) ) continue; // Get the first tag found, and get its data contents $item_tag = $item_tags[0]; $attribs = $item_tag['attribs']['']; // If not using an attribute, simply get the text data if ( $attrib === NULL ) { $data = $item_tag['data']; } // Otherwise, check if the attribute exists elseif ( isset( $attribs[ $attrib ] ) ) { $data = $attribs[ $attrib ]; } // Otherwise do nothing else { continue; } // Put the data in the inserted post's meta, using the custom field as the meta key update_post_meta( $inserted_id, $cfm_fields[$i], $data ); WPRSS_FTP_Utils::log_object( 'Post meta updated', $i+1 . '/' . count($cfm_namespaces), __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); } WPRSS_FTP_Utils::log( 'Custom fields mapped', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO ); $post = get_post( $inserted_id ); if ( $post === NULL || $post === FALSE ) { $title = $item->get_title(); WPRSS_FTP_Utils::log( "An error occurred while converting a feed item into a post \"$title\". Kindly report this error to support@wprssaggregator.com" ); } else { WPRSS_FTP_Utils::log_object( 'Post created', $inserted_id, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO ); do_action( 'wprss_ftp_converter_inserted_post', $inserted_id, $source ); self::trim_words_for_post( $inserted_id, $source ); } } else { WPRSS_FTP_Utils::log( 'Failed to insert post. $inserted_id = ' . $inserted_id, $error_source ); } // If multisite and blog was switched, switch back to current blog if ( WPRSS_FTP_Utils::is_multisite() && $switch_success === TRUE ) { restore_current_blog(); WPRSS_FTP_Utils::log( 'Blog restored', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM ); } WPRSS_FTP_Utils::log( 'Conversion complete', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO ); // Filter the return value $return = apply_filters( 'wprss_ftp_converter_return_post_'.$inserted_id, TRUE ); // If the return is still TRUE, ensure that the post that was created was not deleted if ( $return === TRUE ) { $post = get_post( $inserted_id ); $return = ( $post !== NULL && $post !== FALSE ); } // Log return value if anything other than TRUE else { wprss_log( 'Recieved "'.$return.'" as a return value for post #'.$inserted_id, NULL, WPRSS_LOG_LEVEL_SYSTEM ); } return $return; }
function wprss_schedule_reimport_all($deleted_ids) { if (!get_transient(WPRSS_TRANSIENT_NAME_IS_REIMPORTING)) { return; } wprss_log('Re-import scheduled...', __FUNCTION__, WPRSS_LOG_LEVEL_SYSTEM); delete_transient(WPRSS_TRANSIENT_NAME_IS_REIMPORTING); wprss_fetch_insert_all_feed_items(TRUE); }
/** * Dumps an object to the log file. * * @since 3.9.6 */ function wprss_log_obj($message, $obj, $src = '') { wprss_log("{$message}: " . print_r($obj, TRUE), $src); }
/** * Insert wprss_feed_item posts into the DB * * @since 3.0 */ function wprss_items_insert_post($items, $feed_ID) { update_post_meta($feed_ID, 'wprss_feed_is_updating', $update_started_at = time()); wprss_log_obj('Starting import of items for feed ' . $feed_ID, $update_started_at, null, WPRSS_LOG_LEVEL_INFO); // Gather the permalinks of existing feed item's related to this feed source $existing_permalinks = get_existing_permalinks($feed_ID); // Count of items inserted $items_inserted = 0; foreach ($items as $item) { // Normalize the URL $permalink = wprss_normalize_permalink($item->get_permalink()); wprss_log_obj('Importing item', $permalink, null, WPRSS_LOG_LEVEL_INFO); wprss_log_obj('Original permalink', $item->get_permalink(), null, WPRSS_LOG_LEVEL_SYSTEM); // Save the enclosure URL $enclosure_url = ''; if ($enclosure = $item->get_enclosure(0)) { wprss_log('Item has an enclosure', null, WPRSS_LOG_LEVEL_SYSTEM); if ($enclosure->get_link()) { $enclosure_url = $enclosure->get_link(); wprss_log_obj('Enclosure has link', $enclosure_url, null, WPRSS_LOG_LEVEL_SYSTEM); } } /* OLD NORMALIZATION CODE - TO NORMALIZE URLS FROM PROXY URLS $response = wp_remote_head( $permalink ); if ( !is_wp_error( $response ) && isset( $response['headers']['location'] ) ) { $permalink = current( explode( '?', $response['headers']['location'] ) ); }*/ // Check if newly fetched item already present in existing feed items, // if not insert it into wp_posts and insert post meta. if (!in_array($permalink, $existing_permalinks)) { wprss_log('Importing unique item', null, WPRSS_LOG_LEVEL_INFO); // Apply filters that determine if the feed item should be inserted into the DB or not. $item = apply_filters('wprss_insert_post_item_conditionals', $item, $feed_ID, $permalink); // Check if the imported count should still be updated, even if the item is NULL $still_update_count = apply_filters('wprss_still_update_import_count', FALSE); // If the item is not NULL, continue to inserting the feed item post into the DB if ($item !== NULL && !is_bool($item)) { wprss_log('Using core logic', null, WPRSS_LOG_LEVEL_SYSTEM); // Get the date and GTM date and normalize if not valid dor not present $format = 'Y-m-d H:i:s'; $has_date = $item->get_date('U') ? TRUE : FALSE; $timestamp = $has_date ? $item->get_date('U') : date('U'); $date = date($format, $timestamp); $date_gmt = gmdate($format, $timestamp); // Prepare the item data $feed_item = apply_filters('wprss_populate_post_data', array('post_title' => html_entity_decode($item->get_title()), 'post_content' => '', 'post_status' => 'publish', 'post_type' => 'wprss_feed_item', 'post_date' => $date, 'post_date_gmt' => $date_gmt), $item); wprss_log('Post data filters applied', null, WPRSS_LOG_LEVEL_SYSTEM); if (defined('ICL_SITEPRESS_VERSION')) { @(include_once WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php'); } if (defined('ICL_LANGUAGE_CODE')) { $_POST['icl_post_language'] = $language_code = ICL_LANGUAGE_CODE; wprss_log_obj('WPML detected. Language code determined', $language_code, null, WPRSS_LOG_LEVEL_SYSTEM); } // Create and insert post object into the DB $inserted_ID = wp_insert_post($feed_item); if (!is_wp_error($inserted_ID)) { if (is_object($inserted_ID)) { if (isset($inserted_ID['ID'])) { $inserted_ID = $inserted_ID['ID']; } elseif (isset($inserted_ID->ID)) { $inserted_ID = $inserted_ID->ID; } } // Increment the inserted items counter $items_inserted++; // Create and insert post meta into the DB wprss_items_insert_post_meta($inserted_ID, $item, $feed_ID, $permalink, $enclosure_url); // Remember newly added permalink $existing_permalinks[] = $permalink; wprss_log_obj('Item imported', $inserted_ID, null, WPRSS_LOG_LEVEL_INFO); } else { update_post_meta($source, "wprss_error_last_import", "true"); wprss_log_obj('Failed to insert post', $feed_item, 'wprss_items_insert_post > wp_insert_post'); } } elseif (is_bool($item) && $item === TRUE || $still_update_count === TRUE) { $items_inserted++; } } else { wprss_log('Item already exists and will be skipped', null, WPRSS_LOG_LEVEL_NOTICE); } wprss_log_obj('Finished importing item', $permalink, null, WPRSS_LOG_LEVEL_INFO); } update_post_meta($feed_ID, 'wprss_last_update_items', $items_inserted); wprss_log_obj(sprintf('Finished importing %1$d items for feed source', $items_inserted), $feed_ID, null, WPRSS_LOG_LEVEL_INFO); }
/** * Dumps an object to the log file. * * @since 3.9.6 */ function wprss_log_obj($message, $obj, $src = '', $log_level = WPRSS_LOG_LEVEL_ERROR) { wprss_log("{$message}: " . print_r($obj, TRUE), $src, $log_level); }
/** * Creates an updater instance for an addon. * * @param string $id The ID of the addon. * @param string $itemName The name of the addon as registered in EDD on our servers. * @param string $version The current version of the addon. * @param string $path The path to the addon's main file. * @param string $storeUrl The URL of the server that handles the licensing and serves the updates. * @return boolean True if the updater was initialized, false on failure due to an invalid license. */ public function initUpdaterInstance($id, $itemName, $version, $path, $storeUrl = WPRSS_SL_STORE_URL) { // Prepare the data $license = $this->getLicense($id); // If the addon doesn't have a license or the license is not valid, do not set the updater. // Returns false to indicate this failure. if ($license === null || $license->getStatus() !== Status::VALID) { return false; } try { // Create an updater $updater = $this->newUpdater($storeUrl, $path, array('version' => $version, 'license' => $license, 'item_name' => $itemName)); // Register the updater $this->_setUpdaterInstance($id, $updater); // Return true to indicate success return true; } catch (UpdaterException $e) { wprss_log(sprintf('Could not create new updater:: %1$s', $e->getMessage()), __FUNCTION__, WPRSS_LOG_LEVEL_WARNING); return false; } }
/** * Checks if the given image obeys the given minimum size contraints. * * @since 1.8.2 */ public function image_obeys_minimum_size( $img_url, $min_width, $min_height ) { // Check for filter to skip the size checking $skip_size_check = apply_filters( 'wprss_ftp_skip_image_size_check', FALSE ); if ( $skip_size_check === TRUE ) { return TRUE; } $img_url = trim( $img_url ); $img_url = str_replace( ' ', '%20', $img_url ); // Get the image via the cache. $img = $this->get_cache()->get_images( $img_url ); // Check if the cache download or lookup succeeded. if ( $img instanceof WPRSS_Image_Cache_Image ) { // Try to get the dimensions of the image. $dimensions = $img->get_size(); if ( ! empty( $dimensions ) ) { // We found the dimensions of the image. list( $width, $height ) = $dimensions; wprss_log( sprintf( 'Dimensions: %1$dx%2$d', $dimensions[0], $dimensions[1] ), NULL, WPRSS_LOG_LEVEL_SYSTEM ); } else { // Couldn't get the dimensions, this isn't a valid image. $img->delete(); wprss_log( 'Dimensions could not be acquired', NULL, WPRSS_LOG_LEVEL_SYSTEM ); return FALSE; } } else { // Cache download/lookup failed. wprss_log( 'Image could not be downloaded', NULL, WPRSS_LOG_LEVEL_SYSTEM ); return FALSE; } // Check if the image obeys the size requirements. $obeysMinimum = TRUE; if ( $min_width !== '' ) $obeysMinimum = ( $obeysMinimum && ( $width >= $min_width ) ); if ( $min_height !== '' ) $obeysMinimum = ( $obeysMinimum && ( $height >= $min_height ) ); if ( $obeysMinimum === FALSE ) { $img->delete(); // We don't need to keep this image around. } return $obeysMinimum; }