public function fetchFeed($vURLs, $numItems = 0, $fCacheRenew = false) { $arrURLs = is_array($vURLs) ? $vURLs : (array) $vURLs; $strURLID = md5(serialize($arrURLs)); if (!isset($this->arrFeedItems[$strURLID]) && $fCacheRenew == false) { $this->arrFeedItems[$strURLID] = FetchTweets_WPUtilities::getTransient($this->strTransientPrefix . $strURLID, array()); unset($this->arrFeedItems[$strURLID][0]); // casting array causes the 0 key, } // If it's out of stock, fill the array by fetching the feed. if (empty($this->arrFeedItems[$strURLID])) { // When an array of urls is passed to the Simple Pie's set_feed_url() method, the memory usage increases largely. // So fetch the feeds one by one per url and store the output into an array. foreach ($arrURLs as $strURL) { $oFeed = $this->getFeedObj($strURL, null, $fCacheRenew ? 0 : 3600); foreach ($oFeed->get_items() as $oItem) { // foreach ( $oFeed->get_items( 0, $numItems * 3 ) as $item ) does not change the memory usage $this->arrFeedItems[$strURLID][$oItem->get_title()] = array('strContent' => $oItem->get_content(), 'description' => $oItem->get_description(), 'title' => $oItem->get_title(), 'strDate' => $oItem->get_title(), 'strAuthor' => $oItem->get_date('j F Y, g:i a'), 'strLink' => $oItem->get_permalink()); } // For PHP below 5.3 to release the memory. $oFeed->__destruct(); // Do what PHP should be doing on it's own. unset($oFeed); } // This life span should be little longer than the feed cache life span, which is 1700. FetchTweets_WPUtilities::setTransient($this->strTransientPrefix . $strURLID, $this->arrFeedItems[$strURLID], 1800); // 30 minutes } $arrOut = $this->arrFeedItems[$strURLID]; if ($numItems) { array_splice($arrOut, ${$numItems}); } return $arrOut; }
/** * * @see https://dev.twitter.com/docs/api/1.1/get/application/rate_limit_status */ public function getStatus() { // Return the cached response if available. $_sCacheID = FetchTweets_Commons::TransientPrefix . '_' . md5(serialize(array($this->sConsumerKey, $this->sConsumerSecret, $this->sAccessToken, $this->sAccessSecret))); $_vData = FetchTweets_WPUtilities::getTransient($_sCacheID); if (false !== $_vData) { return $_vData; } // Perform the requests. $_oConnect = new FetchTweets_TwitterOAuth($this->sConsumerKey, $this->sConsumerSecret, $this->sAccessToken, $this->sAccessSecret); $_aUser = $_oConnect->get('account/verify_credentials'); // If the user id could not be retrieved, it means it failed. if (!isset($_aUser['id']) || !$_aUser['id']) { return array(); } // Otherwise, it is okay. Retrieve the current status. $_aStatusKeys = apply_filters('fetch_tweets_filter_request_rate_limit_status_keys', array('statuses', 'search', 'lists')); // keys can be added such as 'help', 'users' etc $_aStatus = $_oConnect->get('https://api.twitter.com/1.1/application/rate_limit_status.json?resources=' . implode(',', $_aStatusKeys)); // Set the cache. $_aData = is_array($_aStatus) ? $_aUser + $_aStatus : $_aUser; FetchTweets_WPUtilities::setTransient($_sCacheID, $_aData, 60); // stores the cache only for 60 seconds. return $_aData; }
/** * Redirects to the twitter to get authenticated. * * @since 1.3.0 * @since 2.4.5 Moved from the admin page class. * @remark This is redirected from the "Connect to Twitter" button. */ private function _redirect() { /* Build TwitterOAuth object with client credentials. */ $_oConnect = new FetchTweets_TwitterOAuth(FetchTweets_Commons::ConsumerKey, FetchTweets_Commons::ConsumerSecret); /* Get temporary credentials - Requesting authentication tokens, the parameter is the URL we will be redirected to. */ $_aRequestToken = $_oConnect->getRequestToken(add_query_arg(array('post_type' => 'fetch_tweets', 'page' => 'fetch_tweets_settings', 'tab' => 'twitter_callback'), admin_url($GLOBALS['pagenow']))); /* Save temporary credentials to transient. */ $_aTemporaryTokens = array(); $_aTemporaryTokens['oauth_token'] = $_aRequestToken['oauth_token']; $_aTemporaryTokens['oauth_token_secret'] = $_aRequestToken['oauth_token_secret']; FetchTweets_WPUtilities::setTransient(FetchTweets_Commons::TransientPrefix . '_oauth', $_aTemporaryTokens, 60 * 10); // 10 minutes /* If last connection failed don't display authorization link. */ switch ($_oConnect->http_code) { case 200: /* Build authorize URL and redirect user to Twitter. */ wp_redirect($_oConnect->getAuthorizeURL($_aTemporaryTokens['oauth_token'])); // goes to twitter.com break; default: /* Show notification if something went wrong. */ die(__('Could not connect to Twitter. Refresh the page or try again later.', 'fetch-tweets')); } exit; }
/** * Re-saves the cache after adding oEmbed elements. * * @since 1.3.0 */ public function _replyToAddOEmbedElements($sRequestURI) { $strTransientKey = FetchTweets_Commons::TransientPrefix . "_" . md5($sRequestURI); // Check if the transient is locked $strLockTransient = FetchTweets_Commons::TransientPrefix . '_' . md5("LockOEm_" . trim($strTransientKey)); // up to 40 characters, the prefix can be up to 8 characters if (false !== FetchTweets_WPUtilities::getTransient($strLockTransient)) { return; // it means the cache is being modified. } // Set a lock flag transient that indicates the transient is being renewed. FetchTweets_WPUtilities::setTransient($strLockTransient, true, FetchTweets_Utilities::getAllowedMaxExecutionTime()); // Perform oEmbed caching - no API request will be performed $oFetch = new FetchTweets_Fetch(); // structure: array( 'mod' => time(), 'data' => $this->oBase64->encode( $vData ) ), $arrTransient = $oFetch->getTransient($strTransientKey); // If the mandatory keys are not set, it's broken. if (!isset($arrTransient['mod'], $arrTransient['data'])) { FetchTweets_WPUtilities::deleteTransient($strTransientKey); return; } $arrTweets = (array) $this->oBase64->decode($arrTransient['data']); $oFetch->addEmbeddableMediaElements($arrTweets); // the array is passed as reference. // Re-save the cache. // FetchTweets_Debug::logArray( 'saving oembed transient' ); $oFetch->setTransient($sRequestURI, $arrTweets, $arrTransient['mod'], true); // the method handles the encoding. // Delete the lock transient FetchTweets_WPUtilities::deleteTransient($strLockTransient); }
/** * A wrapper method for the set_transient() function. * * @since 1.2.0 * @since 1.3.0 Made it public as the event method uses it. */ public function setTransient($sRequestURI, $vData, $iTime = null, $bIgnoreLock = false) { $_sTransientKey = FetchTweets_Commons::TransientPrefix . "_" . md5(trim($sRequestURI)); $_sLockTransient = FetchTweets_Commons::TransientPrefix . '_' . md5("Lock_" . $_sTransientKey); // Give some time to the server to store transients in case of simultaneous accesses. if (FetchTweets_Cron::isBackground()) { sleep(1); } // Check if the transient is locked. if (!$bIgnoreLock && false !== FetchTweets_WPUtilities::getTransient($_sLockTransient)) { return; // it means the cache is being modified. } // Set a lock flag transient that indicates the transient is being renewed. if (!$bIgnoreLock) { FetchTweets_WPUtilities::setTransient($_sLockTransient, 'locked', 10); } // Store the cache $_bIsSet = FetchTweets_WPUtilities::setTransient($_sTransientKey, array('mod' => $iTime ? $iTime : time(), 'data' => $this->oBase64->encode($vData))); if (!$_bIsSet) { return; } // Schedule the action to run in the background with WP Cron. If already scheduled, skip. // This adds the embedding elements which takes some time to process. $_aArgs = array($sRequestURI); if ($iTime || wp_next_scheduled('fetch_tweets_action_transient_add_oembed_elements', $_aArgs)) { return; } wp_schedule_single_event(time(), 'fetch_tweets_action_transient_add_oembed_elements', $_aArgs); if ('intense' == $this->oOption->aOptions['cache_settings']['caching_mode']) { FetchTweets_Cron::see(array(), true); } else { // $this->arrExpiredTransientsRequestURIs wp_remote_get(site_url("/wp-cron.php"), array('timeout' => 0.01, 'sslverify' => false)); } // Delete the lock transient // FetchTweets_WPUtilities::deleteTransient( $_sLockTransient ); }
/** * Validates submitted form data of the page. * @remark validation_{page slug} * * @since unknown * @since 2.4.5 Changed the name from 'validation_fetch_tweets_add_rule_by_list'. */ public function validatePageFormData($aInput, $aOldInput, $oFactory, $aSubmitInformation) { // Check if the input has been properly sent. if (!isset($aInput['add_rule_by_list']['list_owner_screen_name'], $aInput['add_rule_by_list']['list_owner_accounts'])) { $oFactory->setSettingNotice(__('Something went wrong. Your input could not be received. Try again and if this happens again, contact the developer.', 'fetch-tweets')); return $aOldInput; } $_aCredentials = $this->_getCredentiaslByAccountID($aInput['add_rule_by_list']['list_owner_accounts']); // Variables $_aErrors = array(); // error array $_iAccountID = $aInput['add_rule_by_list']['list_owner_accounts'] == -1 ? 0 : $aInput['add_rule_by_list']['list_owner_accounts']; $_sOwnerScreenName = $aInput['add_rule_by_list']['list_owner_accounts'] == '-1' ? $aInput['add_rule_by_list']['list_owner_screen_name'] : $_aCredentials['screen_name']; // The list owner screen name must be provided. if (empty($_sOwnerScreenName)) { $_aErrors['add_rule_by_list']['list_owner_screen_name'] = __('The screen name of the list owner must be specified: ') . $_sOwnerScreenName; $oFactory->setFieldErrors($_aErrors); $oFactory->setSettingNotice(__('There was an error in your input.', 'fetch-tweets')); return $aOldInput; } // Fetch the lists by the screen name. $_oFetch = new FetchTweets_Fetch($_aCredentials['consumer_key'], $_aCredentials['consumer_secret'], $_aCredentials['access_token'], $_aCredentials['access_secret']); $_aLists = $_oFetch->getListNamesFromScreenName($_sOwnerScreenName, $_iAccountID); if (empty($_aLists)) { $oFactory->setSettingNotice(__('No list found.', 'fetch-tweets')); return $aOldInput; } // Set the transient of the fetched IDs. This will be used right next page load. $_sListCacheID = uniqid(); FetchTweets_WPUtilities::setTransient($_sListCacheID, $_aLists, 60); exit(wp_redirect(add_query_arg(array('post_type' => FetchTweets_Commons::PostTypeSlug, 'tweet_type' => 'list', 'list_cache' => $_sListCacheID, 'screen_name' => $_sOwnerScreenName, 'account_id' => $_iAccountID), admin_url('post-new.php')))); }
/** * A callback for the accessSiteAtShutDown() method. * * @since 1.0.0 */ public static function _replyToAccessSite() { // Retrieve the plugin scheduled tasks array. $_sTransientName = md5(get_class()); $_aTasks = FetchTweets_WPUtilities::getTransient($_sTransientName); $_aTasks = $_aTasks ? $_aTasks : array(); $_nNow = microtime(true); // Check the excessive background call protection interval if (!self::$_fIgnoreLock) { $_nCalled = isset($_aTasks['called']) ? $_aTasks['called'] : 0; if ($_nCalled + self::$_iLockBackgroundCallInterval > $_nNow) { return; // if it's called within 10 seconds from the last time of calling this method, do nothing to avoid excessive calls. } } // Renew the called time. $_aFlagKeys = array('called' => $_nNow); FetchTweets_WPUtilities::setTransient($_sTransientName, $_aFlagKeys + $_aTasks, self::getAllowedMaxExecutionTime()); // set a locked key so it prevents duplicated function calls due to too many calls caused by simultaneous accesses. // Compose a GET query array $_aGet = self::$_aGet; if (defined('WP_DEBUG')) { $_aGet['debug'] = WP_DEBUG; } unset($_aGet[0]); // Load the site in the background. wp_remote_get(site_url('?' . http_build_query($_aGet)), array('timeout' => 0.01, 'sslverify' => false, 'cookies' => $_aFlagKeys + array($_sTransientName => true))); }