public static function check($force = false) { if ($force || XenForo_Application::getoptions()->dpAnalyticsInternal['d'] + 3600 < Xenforo_Application::$time) { $addOn = XenForo_Model::create('XenForo_Model_AddOn')->getAddOnVersion(self::$_addOnId); $client = XenForo_Helper_Http::getClient('https://api.digitalpoint.com/v1/marketplace/licensed.json'); $client->setParameterGet(array('item_id' => self::$_itemId, 'url' => XenForo_Application::get('options')->boardUrl, 'item_version' => $addOn['version_string'])); try { $response = $client->request('GET'); $response = @json_decode($response->getBody()); } catch (Exception $e) { } XenForo_Model::create('XenForo_Model_Option')->updateOption('dpAnalyticsInternal', array('d' => XenForo_Application::$time, 'v' => @$response->results->good)); return @$response->results->good; } else { return @XenForo_Application::getoptions()->dpAnalyticsInternal['v']; } }
/** * Determines if CAPTCHA is valid (passed). * * @see XenForo_Captcha_Abstract::isValid() */ public function isValid(array $input) { if (!$this->_cKey) { return true; // if not configured, always pass } if (empty($input['adcopy_challenge']) || empty($input['adcopy_response'])) { return false; } try { $client = XenForo_Helper_Http::getClient('http://verify.solvemedia.com/papi/verify'); $client->setParameterPost(array('privatekey' => $this->_vKey, 'challenge' => $input['adcopy_challenge'], 'response' => $input['adcopy_response'], 'remoteip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '')); $contents = trim($client->request('POST')->getBody()); $parts = explode("\n", $contents, 3); $result = trim($parts[0]); $error = isset($parts[1]) ? trim($parts[1]) : null; if ($result == 'true') { return true; } switch ($error) { case 'wrong answer': case 'invalid remoteip': // generally end user mistakes return false; default: // this is likely a configuration error, log and let it through XenForo_Error::logError("Solve Media CAPTCHA error: {$error}"); return true; } } catch (Zend_Http_Client_Adapter_Exception $e) { // this is an exception with the underlying request, so let it go through XenForo_Error::logException($e, false, "Solve Media connection error: "); return true; } }
/** * Validates the callback request is valid. If failure happens, the response should * tell the processor to retry. * * @param string $errorString Output error string * * @return boolean */ public function validateRequest(&$errorString) { try { if ($this->_filtered['test_ipn'] && XenForo_Application::debugMode()) { $validator = XenForo_Helper_Http::getClient('http://www.sandbox.paypal.com/cgi-bin/webscr'); } else { $validator = XenForo_Helper_Http::getClient('http://www.paypal.com/cgi-bin/webscr'); } $validator->setParameterPost('cmd', '_notify-validate'); $validator->setParameterPost($_POST); $validatorResponse = $validator->request('POST'); if (!$validatorResponse || $validatorResponse->getBody() != 'VERIFIED' || $validatorResponse->getStatus() != 200) { $errorString = 'Request not validated'; return false; } } catch (Zend_Http_Client_Exception $e) { $errorString = 'Connection to PayPal failed'; return false; } if (strtolower($this->_filtered['business']) != strtolower(XenForo_Application::get('options')->payPalPrimaryAccount)) { $errorString = 'Invalid business'; return false; } return true; }
/** * @param int $position * @param array $options * @param string $detailedMessage * @return bool|int|string|true */ public function rebuild($position = 0, array &$options = array(), &$detailedMessage = '') { $options['batch'] = max(1, isset($options['batch']) ? $options['batch'] : 10); /* @var sonnb_XenGallery_Model_Location $locationModel */ $locationModel = XenForo_Model::create('sonnb_XenGallery_Model_Location'); $locations = $locationModel->getLocationsWithoutCoordinate($position, $options['batch']); if (count($locations) < 1) { return true; } XenForo_Db::beginTransaction(); $db = XenForo_Application::getDb(); /** @var sonnb_XenGallery_Model_Location $locationModel */ $locationModel = XenForo_Model::create('sonnb_XenGallery_Model_Location'); foreach ($locations as $locationId => $location) { $position = $location['location_id']; try { $client = XenForo_Helper_Http::getClient($locationModel->getGeocodeUrlForAddress($location['location_name'])); $response = $client->request('GET'); $response = @json_decode($response->getBody(), true); if (empty($response['results'][0])) { continue; } $address = $response['results'][0]['formatted_address']; $lat = $response['results'][0]['geometry']['location']['lat']; $lng = $response['results'][0]['geometry']['location']['lng']; $db->update('sonnb_xengallery_location', array('location_name' => $address, 'location_lat' => $lat, 'location_lng' => $lng), array('location_id = ?' => $location['location_id'])); } catch (Exception $e) { continue; } } XenForo_Db::commit(); $detailedMessage = XenForo_Locale::numberFormat($position); return $position; }
/** * Determines if CAPTCHA is valid (passed). * * @see XenForo_Captcha_Abstract::isValid() */ public function isValid(array $input) { if (!$this->_keyUserId) { return true; // if not configured, always pass } if (empty($input['keycaptcha_code']) || !is_string($input['keycaptcha_code'])) { return false; } $parts = explode('|', $input['keycaptcha_code']); if (count($parts) < 4) { return false; } if ($parts[0] !== md5('accept' . $parts[1] . $this->_privateKey . $parts[2])) { return false; } if (substr($parts[2], 0, 7) !== 'http://') { return false; } try { $client = XenForo_Helper_Http::getClient($parts[2]); $contents = trim($client->request('GET')->getBody()); return $contents == '1'; } catch (Zend_Http_Client_Adapter_Exception $e) { // this is an exception with the underlying request, so let it go through XenForo_Error::logException($e, false, 'KeyCAPTCHA connection error:'); return true; } }
public function execute(array $deferred, array $data, $targetRunTime, &$status) { $data = array_merge(array('batch' => 10, 'position' => 0, 'positionRebuild' => false), $data); /* @var sonnb_XenGallery_Model_Location $locationModel */ $locationModel = XenForo_Model::create('sonnb_XenGallery_Model_Location'); $locations = $locationModel->getLocationsWithoutCoordinate($data['position'], $data['batch']); if (count($locations) < 1) { return false; } $db = XenForo_Application::getDb(); /** @var sonnb_XenGallery_Model_Location $locationModel */ $locationModel = XenForo_Model::create('sonnb_XenGallery_Model_Location'); foreach ($locations as $locationId => $location) { $data['position'] = $location['location_id']; try { $client = XenForo_Helper_Http::getClient($locationModel->getGeocodeUrlForAddress($location['location_name'])); $response = $client->request('GET'); $response = @json_decode($response->getBody(), true); if (empty($response['results'][0])) { continue; } $address = $response['results'][0]['formatted_address']; $lat = $response['results'][0]['geometry']['location']['lat']; $lng = $response['results'][0]['geometry']['location']['lng']; $db->update('sonnb_xengallery_location', array('location_name' => $address, 'location_lat' => $lat, 'location_lng' => $lng), array('location_id = ?' => $location['location_id'])); } catch (Exception $e) { continue; } } $actionPhrase = new XenForo_Phrase('rebuilding'); $typePhrase = new XenForo_Phrase('sonnb_xengallery_location'); $status = sprintf('%s... %s (%s)', $actionPhrase, $typePhrase, XenForo_Locale::numberFormat($data['position'])); return $data; }
/** * Gets the user picture for the current user. * * @param string $accessToken FB access token (from code swap, or given by user) * @param string $size Size/type of picture. Defaults to large * * @return string Binary data */ public static function getUserPicture($accessToken, $size = 'large') { try { $client = XenForo_Helper_Http::getClient('https://graph.facebook.com/v2.4/me/picture?type=' . $size); $client->setParameterGet('access_token', $accessToken); $response = $client->request('GET'); return $response->getBody(); } catch (Zend_Http_Client_Exception $e) { return false; } }
protected static function _checkBranding($matches) { $return = @$matches[1]; $client = XenForo_Helper_Http::getClient('https://api.digitalpoint.com/v1/marketplace/branding'); $client->setParameterGet(array('item_id' => self::$_itemId, 'url' => XenForo_Application::get('options')->boardUrl)); $response = $client->request('GET'); $response = @json_decode($response->getBody()); if (!@$response->results->has_brand_removal) { $return .= self::$_attributionHtml; } return $return; }
protected function _fetchAvatarsFromExternalSites() { /* @var $externalAuthModel XenForo_Model_UserExternal */ $externalAuthModel = $this->getModelFromCache('XenForo_Model_UserExternal'); $external = $externalAuthModel->getExternalAuthAssociationsForUser($this->get('user_id')); $fbUser = false; if (!empty($external['facebook'])) { $extra = @unserialize($external['twitter']['extra_data']); if (!empty($extra['token'])) { $avatarData = XenForo_Helper_Facebook::getUserPicture($extra['token']); if ($avatarData && $this->_applyAvatar($avatarData)) { return true; } } } $twitterUser = false; if (!empty($external['twitter'])) { $extra = @unserialize($external['twitter']['extra_data']); if (!empty($extra['token'])) { $credentials = XenForo_Helper_Twitter::getUserFromToken($extra['token'], $extra['secret']); if (!empty($credentials['profile_image_url'])) { try { // get the original size $url = str_replace('_normal', '', $credentials['profile_image_url']); $request = XenForo_Helper_Http::getClient($url)->request(); $avatarData = $request->getBody(); } catch (Exception $e) { $avatarData = ''; } if ($avatarData && $this->_applyAvatar($avatarData)) { return true; } } } } $externalExtendedHelpers = array('battlenet' => 'BattleNet', 'github' => 'GitHub', 'linkedin' => 'LinkedIn', 'live' => 'Live', 'odnoklassniki' => 'Odnoklassniki', 'soundcloud' => 'SoundCloud', 'tumblr' => 'Tumblr', 'twitch' => 'Twitch', 'vk' => 'VK'); foreach ($externalExtendedHelpers as $provider => $class) { if (!empty($external[$provider])) { $extra = $external[$provider]['extra_data']; if (!empty($extra['token'])) { $helper = $this->_getExternalExtendedHelper($class); if ($helper->avatarExists) { $eeUser = $helper->getUserInfo($extra['token']); $avatarData = $helper->getAvatar($eeUser); if ($avatarData && $this->_applyAvatar($avatarData)) { return true; } } } } } return false; }
/** * Gets the Twitter service object for a token * * @param string|Zend_Oauth_Token_Access $token Access token object or access token string * @param null|string $secret Access token secret if token is provided as string * * @return Zend_Service_Twitter */ public static function getService($token, $secret = null) { $options = XenForo_Application::getOptions(); Zend_Oauth::setHttpClient(XenForo_Helper_Http::getClient('https://api.twitter.com/oauth')); if ($token instanceof Zend_Oauth_Token_Access) { $accessToken = $token; } else { $accessToken = new Zend_Oauth_Token_Access(); $accessToken->setToken($token); $accessToken->setTokenSecret($secret); } return new Zend_Service_Twitter(array('accessToken' => $accessToken, 'oauthOptions' => array('consumerKey' => trim($options->twitterAppKey), 'consumerSecret' => trim($options->twitterAppSecret)), 'httpClientOptions' => XenForo_Helper_Http::getExtraHttpClientOptions('https://api.twitter.com/oauth'))); }
public function getUserInfo($userId, $accessToken) { try { $client = XenForo_Helper_Http::getClient(sprintf('%s://%s/user', $this->schema, $this->api)); $client->setHeaders('Authorization', 'Bearer ' . $accessToken); $response = $client->request('GET'); $body = $response->getBody(); $body = json_decode($body, true); return $body; } catch (Zend_Http_Client_Exception $e) { return false; } }
public function querySfs($user) { $apiUrl = $this->_getSfsApiUrl(array('username' => $user['username'], 'email' => $user['email'], 'ip' => $user['ip'])); $apiResponse = false; $client = XenForo_Helper_Http::getClient($apiUrl); try { $response = $client->request('GET'); $body = $response->getBody(); $apiResponse = $this->_decodeSfsApiData($body); } catch (Zend_Http_Exception $e) { } return $apiResponse; }
public static function getTitle($url, $text) { if (preg_match('#^https?://#i', $url)) { try { $client = XenForo_Helper_Http::getClient($url, array('timeout' => 10)); $request = $client->request(); if ($request->isSuccessful()) { $html = $request->getBody(); if (preg_match('#<title[^>]*>(.*)</title>#siU', $html, $match)) { return $match[1]; } } } catch (Zend_Http_Client_Exception $e) { return $text; } } return $text; }
/** * Validates the callback request is valid. If failure happens, the response should * tell the processor to retry. * * @param string $errorString Output error string * * @return boolean */ public function validateRequest(&$errorString) { try { if ($this->_filtered['test_ipn'] && XenForo_Application::debugMode()) { $validator = XenForo_Helper_Http::getClient('https://www.sandbox.paypal.com/cgi-bin/webscr'); } else { $validator = XenForo_Helper_Http::getClient('https://www.paypal.com/cgi-bin/webscr'); } $validator->setParameterPost('cmd', '_notify-validate'); $validator->setParameterPost($_POST); $validatorResponse = $validator->request('POST'); if (!$validatorResponse || $validatorResponse->getBody() != 'VERIFIED' || $validatorResponse->getStatus() != 200) { $host = XenForo_Model_Ip::getHost($this->_request->getClientIp(false)); if (preg_match('#(^|\\.)paypal.com$#i', $host)) { $errorString = 'Request not validated'; } else { $errorString = array(false, 'Request not validated (from unknown source)'); } return false; } } catch (Zend_Http_Client_Exception $e) { $errorString = 'Connection to PayPal failed'; return false; } $business = strtolower($this->_filtered['business']); $receiverEmail = strtolower($this->_filtered['receiver_email']); $options = XenForo_Application::get('options'); $accounts = preg_split('#\\r?\\n#', $options->payPalAlternateAccounts, -1, PREG_SPLIT_NO_EMPTY); $accounts[] = $options->payPalPrimaryAccount; $matched = false; foreach ($accounts as $account) { $account = trim(strtolower($account)); if ($account && ($business == $account || $receiverEmail == $account)) { $matched = true; break; } } if (!$matched) { $errorString = 'Invalid business or receiver_email'; return false; } return true; }
public function getThumbnailUrl($videoId) { $this->_videoId = $videoId; $this->_mediaSiteId = 'youtube'; $urlVideoId = rawurlencode($videoId); $preferredThumbnail = "https://i.ytimg.com/vi/{$urlVideoId}/maxresdefault.jpg"; $fallbackThumbnail = "https://i.ytimg.com/vi/{$urlVideoId}/hqdefault.jpg"; try { $client = XenForo_Helper_Http::getClient($preferredThumbnail); $response = $client->request('GET'); if ($response->isSuccessful()) { $this->_thumbnailUrl = $preferredThumbnail; } else { $this->_thumbnailUrl = $fallbackThumbnail; } } catch (Zend_Http_Client_Exception $e) { } return $this->verifyThumbnailUrl($this->_thumbnailUrl); }
public function getThumbnailUrl($videoId) { $this->_videoId = $videoId; $this->_mediaSiteId = 'dailymotion'; $urlVideoId = rawurlencode($videoId); $thumbnailUrl = "https://api.dailymotion.com/video/{$urlVideoId}?fields=thumbnail_url"; try { $client = XenForo_Helper_Http::getClient($thumbnailUrl); $response = $client->request('GET'); $body = $response->getBody(); if (preg_match('#^[{\\[]#', $body)) { $videoData = json_decode($body, true); if (!empty($videoData['thumbnail_url'])) { $this->_thumbnailUrl = $videoData['thumbnail_url']; } } } catch (Zend_Http_Client_Exception $e) { } return $this->verifyThumbnailUrl($this->_thumbnailUrl); }
public function getThumbnailUrl($videoId) { $this->_videoId = $videoId; $this->_mediaSiteId = 'liveleak'; $urlVideoId = rawurlencode($videoId); $videoUrl = "http://www.liveleak.com/view?i={$urlVideoId}"; try { $client = XenForo_Helper_Http::getClient($videoUrl); $response = $client->request('GET'); $body = $response->getBody(); if ($body) { $dom = new Zend_Dom_Query($body); $thumbnailUrl = $dom->query('meta[property="og:image"]'); if ($thumbnailUrl->count()) { $this->_thumbnailUrl = $thumbnailUrl->current()->getAttribute('content'); } } } catch (Zend_Http_Client_Exception $e) { } return $this->verifyThumbnailUrl($this->_thumbnailUrl); }
public static function getGroups($accessToken) { try { $client = XenForo_Helper_Http::getClient('https://graph.facebook.com/v2.0/me/groups'); $client->setParameterGet('access_token', $accessToken); $response = $client->request('GET'); $jsonDecoded = json_decode($response->getBody(), true); if (!empty($jsonDecoded['data'])) { $groups = array(); foreach ($jsonDecoded['data'] as $entry) { $groups[$entry['id']] = array('name' => $entry['name'], 'target_id' => bdSocialShare_Helper_Common::encryptTargetId($entry['name'], array('targetId' => $entry['id'], 'accessToken' => $accessToken, 'type' => 'group'))); } return $groups; } } catch (Zend_Http_Client_Exception $e) { if (XenForo_Application::debugMode()) { XenForo_Error::logException($e, false); } } return false; }
/** * Internal function to get title and page description etc. * Slightly amended from XenForo_Helper_Url::getTitle. * * @return string */ protected function _getTitleAndDescription($url) { if (preg_match('#^https?://#i', $url)) { try { $client = XenForo_Helper_Http::getClient($url, array('timeout' => 10)); $request = $client->request(); if ($request->isSuccessful()) { $html = $request->getBody(); preg_match('#<title[^>]*>(.*?)</title>#simU', $html, $urlTitleMatches); preg_match('#<[\\s]*meta[\\s]*(name|property)="(og:|twitter:|)description"?[\\s]*content="?([^>"]*)"?[\\s]*[\\/]?[\\s]*>#simU', $html, $urlDescriptionMatches); $urlTitle = isset($urlTitleMatches[1]) ? $urlTitleMatches[1] : ''; $urlTitle = $this->_prepareString($urlTitle); $urlDescription = isset($urlDescriptionMatches[3]) ? $urlDescriptionMatches[3] : ''; $urlDescription = $this->_prepareString($urlDescription); return array($urlTitle, $urlDescription); } } catch (Zend_Http_Client_Exception $e) { return false; } } return false; }
/** * Determines if CAPTCHA is valid (passed). * * @see XenForo_Captcha_Abstract::isValid() */ public function isValid(array $input) { if (!$this->_siteKey || !$this->_secretKey) { return true; // if not configured, always pass } if (empty($input['g-recaptcha-response'])) { return false; } $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ''; try { $client = XenForo_Helper_Http::getClient('https://www.google.com/recaptcha/api/siteverify'); $client->setParameterGet(array('secret' => $this->_secretKey, 'response' => $input['g-recaptcha-response'], 'remoteip' => $ip)); $response = json_decode($client->request()->getBody(), true); if (isset($response['success'])) { return $response['success']; } return false; } catch (Zend_Http_Client_Adapter_Exception $e) { // this is an exception with the underlying request, so let it go through XenForo_Error::logException($e, false, "ReCAPTCHA (No CAPTCHA) connection error: "); return true; } }
public function getEmbedVideoData($type, $key) { if (!isset(self::$_siteApi[$type])) { return array(); } $url = str_replace("{video_key}", $key, self::$_siteApi[$type]); if ($type === 'facebook') { return array('title' => '', 'thumbnailUrl' => $url, 'description' => '', 'duration' => 0); } elseif ($type === 'metacafe') { $key = explode('/', $key); $key = $key[0]; $url = str_replace("{video_key}", $key, self::$_siteApi[$type]); } try { $client = XenForo_Helper_Http::getClient($url); $response = $client->request('GET'); $function = "_" . $type; $return = $this->{$function}($response->getBody()); if (isset($return['title'])) { $return['title'] = strip_tags($return['title']); } if (isset($return['description'])) { $return['description'] = strip_tags($return['description']); } return $return; } catch (Exception $e) { return array(); } }
/** * Registers a new account (or associates with an existing one) using Google. * * @return XenForo_ControllerResponse_Abstract */ public function actionGoogleRegister() { $this->_assertPostOnly(); $session = XenForo_Application::getSession(); $credentials = $session->get('googleCredentials'); if (!$credentials) { return $this->responseError(new XenForo_Phrase('you_did_not_grant_permission_to_access_external_account')); } $userExternalModel = $this->_getUserExternalModel(); $doAssoc = $this->_input->filterSingle('associate', XenForo_Input::STRING) || $this->_input->filterSingle('force_assoc', XenForo_Input::UINT); $redirect = XenForo_Application::getSession()->get('loginRedirect'); if (!$redirect) { $redirect = $this->getDynamicRedirect(false, false); } if ($doAssoc) { $userId = $this->_associateExternalAccount(); $userExternalModel->updateExternalAuthAssociation('google', $credentials['basic']['sub'], $userId, $credentials['extra']); return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $redirect); } $googleUser = $credentials['user']; $data = $this->_input->filter(array('username' => XenForo_Input::STRING, 'timezone' => XenForo_Input::STRING, 'location' => XenForo_Input::STRING, 'dob_day' => XenForo_Input::UINT, 'dob_month' => XenForo_Input::UINT, 'dob_year' => XenForo_Input::UINT)); $data['email'] = $credentials['basic']['email']; if (!empty($googleUser['currentLocation'])) { $data['location'] = $googleUser['currentLocation']; } else { if (!empty($googleUser['placesLived']) && is_array($googleUser['placesLived'])) { foreach ($googleUser['placesLived'] as $place) { if (!empty($place['primary'])) { $data['location'] = $place['value']; break; } } } } if (isset($googleUser['gender'])) { switch ($googleUser['gender']) { case 'male': case 'female': $data['gender'] = $googleUser['gender']; break; } } if (!empty($googleUser['birthday'])) { $birthday = $this->_validateBirthdayString($googleUser['birthday'], 'y-m-d'); if ($birthday) { $data['dob_year'] = $birthday[0]; $data['dob_month'] = $birthday[1]; $data['dob_day'] = $birthday[2]; } } $writer = $this->_setupExternalUser($data); if (!$this->_validateBirthdayInput($writer, $birthdayError)) { $writer->error($birthdayError); } $spamModel = $this->_runSpamCheck($writer); $writer->advanceRegistrationUserState(false); $writer->save(); $user = $writer->getMergedData(); $spamModel->logSpamTrigger('user', $user['user_id']); if (!empty($googleUser['image']['url']) && $this->_canApplyAvatar()) { try { // get the original size $url = preg_replace('/(\\?|&)sz=\\d+/', '', $googleUser['image']['url']); $request = XenForo_Helper_Http::getClient($url)->request(); $avatarData = $request->getBody(); } catch (Exception $e) { $avatarData = ''; } $this->_applyAvatar($user, $avatarData); } $userExternalModel->updateExternalAuthAssociation('google', $credentials['basic']['sub'], $user['user_id'], $credentials['extra']); return $this->_completeRegistration($user); }
public function publish($targetId, bdSocialShare_Shareable_Abstract $shareable, $accessToken) { try { $link = $shareable->getLink($this); $imageDataPath = $shareable->getImageDataPath($this); $userText = $shareable->getUserText($this); $title = $shareable->getTitle($this); $description = $shareable->getDescription($this); $image = $shareable->getImage($this); $userText = strval($userText); $title = strval($title); $description = strval($description); $sendLinkData = (bdSocialShare_Option::get('facebookSendLinkData') or $shareable instanceof bdSocialShare_Shareable_StaffShare); if ($sendLinkData and !empty($imageDataPath)) { // upload as a new photo in the app album $client = XenForo_Helper_Http::getClient(sprintf('https://graph.facebook.com/v2.0/%s/photos', $targetId)); $client->setFileUpload($imageDataPath, 'source'); $parts = array(); if (!empty($title)) { $parts[] = $title; } if (empty($parts)) { if (!empty($description)) { $parts[] = $description; } } if (!empty($link)) { $parts[] = $link; } if (!empty($parts)) { $client->setParameterPost('message', implode("\n", $parts)); } } if (empty($client) and !empty($link)) { // publish as a link $client = XenForo_Helper_Http::getClient(sprintf('https://graph.facebook.com/v2.0/%s/feed', $targetId)); $client->setParameterPost('link', $link); if ($sendLinkData and !empty($title)) { // send link data $client->setParameterPost('name', $title); if (!empty($image)) { $client->setParameterPost('picture', $image); } if (!empty($description)) { $client->setParameterPost('description', $description); } } if (!empty($userText)) { $client->setParameterPost('message', $userText); } } if (empty($client) and !empty($userText)) { // publish as a status $client = XenForo_Helper_Http::getClient(sprintf('https://graph.facebook.com/v2.0/%s/feed', $targetId)); if (!empty($link)) { // merge user text and link $client->setParameterPost('message', sprintf('%s %s', $userText, $link)); } else { $client->setParameterPost('message', $userText); } } if (empty($client)) { return false; } $client->setParameterPost('access_token', $accessToken); $response = $client->request('POST'); $responseBody = $response->getBody(); $responseArray = json_decode($responseBody, true); if (isset($responseArray['id'])) { return $responseArray; } else { throw new bdSocialShare_Exception_Interrupted($responseBody); } } catch (Zend_Http_Client_Exception $e) { throw new bdSocialShare_Exception_HttpClient($e->getMessage()); } // MUST NOT REACH HERE!!!! }
/** * Queries the SFS spam check API with the spam check data and returns an array of response data * * @param array $user * @param string $apiUrl * @param boolean $fromCache * * @return array */ protected function _getSfsApiResponse(array $user, &$apiUrl = '', &$fromCache = false) { $apiUrl = $this->_getSfsApiUrl($user); $cacheKey = $this->_getSfsCacheKey($apiUrl); $fromCache = false; if ($result = $this->_getRegistrationResultFromCache($cacheKey)) { $fromCache = true; return unserialize($result); } $client = XenForo_Helper_Http::getClient($apiUrl); try { $response = $client->request('GET'); $body = $response->getBody(); $contents = $this->_decodeSfsApiData($body); return is_array($contents) ? $contents : false; } catch (Zend_Http_Exception $e) { //XenForo_Error::logException($e, false); return false; } }
public function stepAvatars($start, array $options) { $options = array_merge(array('avatarPath' => isset($this->_config['avatarPath']) ? $this->_config['avatarPath'] : '', 'attachmentPaths' => isset($this->_config['attachmentPaths']) ? $this->_config['attachmentPaths'] : '', 'limit' => 50, 'max' => false), $options); $sDb = $this->_sourceDb; $prefix = $this->_prefix; /* @var $model XenForo_Model_Import */ $model = $this->_importModel; if ($options['max'] === false) { $options['max'] = $sDb->fetchOne(' SELECT MAX(members.id_member) FROM ' . $prefix . 'members AS members LEFT JOIN ' . $prefix . 'attachments AS avatar ON (members.id_member = avatar.id_member AND avatar.attachment_type IN (0, 1)) WHERE (members.avatar <> \'\' OR avatar.id_attach IS NOT NULL) AND (avatar.id_msg IS NULL OR avatar.id_msg = 0) AND (avatar.id_member IS NULL OR avatar.id_member <> 0) '); } $avatars = $sDb->fetchAll($sDb->limit(' SELECT members.*, avatar.*, IF (avatar.id_member IS NULL, members.id_member, avatar.id_member) AS id_member FROM ' . $prefix . 'members AS members LEFT JOIN ' . $prefix . 'attachments AS avatar ON (members.id_member = avatar.id_member AND avatar.attachment_type IN (0, 1)) WHERE members.id_member > ' . $sDb->quote($start) . ' AND (members.avatar <> \'\' OR avatar.id_attach IS NOT NULL) AND (avatar.id_msg IS NULL OR avatar.id_msg = 0) AND (avatar.id_member IS NULL OR avatar.id_member <> 0) ORDER BY members.id_member ', $options['limit'])); if (!$avatars) { return true; } $userIdMap = $model->getUserIdsMapFromArray($avatars, 'id_member'); $next = 0; $total = 0; foreach ($avatars as $avatar) { $next = $avatar['id_member']; $newUserId = $this->_mapLookUp($userIdMap, $avatar['id_member']); if (!$newUserId) { continue; } $avatarFile = null; // We have a path to an avatar in the members table, otherwise it's an attachment. if ($avatar['avatar']) { // Only import an avatar if it is a URL, otherwise it's a gallery avatar (skip it). if (Zend_Uri::check($avatar['avatar'])) { try { $httpClient = XenForo_Helper_Http::getClient($avatar['avatar']); $response = $httpClient->request('GET'); if ($response->isSuccessful()) { $avatarFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf'); file_put_contents($avatarFile, $response->getBody()); } } catch (Zend_Http_Client_Exception $e) { } } } else { $filePath = ''; switch ($avatar['attachment_type']) { // Attachment directory case 0: if (!isset($options['attachmentPaths'][$avatar['id_folder']])) { // Going to have to assume that it was a single attachment directory environment. $attachmentPath = $options['attachmentPaths'][0]; } else { $attachmentPath = $options['attachmentPaths'][$avatar['id_folder']]; } if ($avatar['file_hash'] === '') { $filePath = "{$attachmentPath}/{$avatar['filename']}"; } else { $filePath = "{$attachmentPath}/{$avatar['id_attach']}_{$avatar['file_hash']}"; } break; // Custom avatar directory // Custom avatar directory case 1: $filePath = "{$options['avatarPath']}/{$avatar['filename']}"; break; default: continue; } if (!file_exists($filePath)) { continue; } $avatarFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf'); copy($filePath, $avatarFile); } if ($this->_importModel->importAvatar($avatar['id_member'], $newUserId, $avatarFile)) { $total++; } @unlink($avatarFile); } $this->_session->incrementStepImportTotal($total); return array($next, $options, $this->_getProgressOutput($next, $options['max'])); }
protected function _getHandler($url) { if (self::canUseCurlMulti()) { // need to reset the URL if sending parameters $this->_url = $url; $this->_currentHandle = curl_init($url); } else { $this->_currentHandle = XenForo_Helper_Http::getClient($url); } }
protected function _getHandler() { if (self::_canUseCurlMulti()) { $this->_currentHandle = curl_init(self::$_analyticsEndPoint); } else { $this->_currentHandle = XenForo_Helper_Http::getClient(self::$_analyticsEndPoint); } }
public function stepAvatars($start, array $options) { $options = array_merge(array('path' => $this->_config['ipboard_path'] . '/uploads', 'limit' => 50, 'max' => false, 'fetchRemote' => false, 'importPhotos' => false), $options); $where = array("pp.avatar_type = 'upload'"); if ($options['fetchRemote']) { $where[] = "pp.avatar_type = 'url'"; } if ($options['importPhotos']) { $where[] = "pp.pp_main_photo <> ''"; } $where = '(' . implode(' OR ', $where) . ')'; $sDb = $this->_sourceDb; $prefix = $this->_prefix; /* @var $model XenForo_Model_Import */ $model = $this->_importModel; if ($options['max'] === false) { $options['max'] = $sDb->fetchOne(' SELECT MAX(pp_member_id) FROM ' . $prefix . 'profile_portal AS pp WHERE ' . $where . ' '); } $avatars = $sDb->fetchAll($sDb->limit(' SELECT members.member_id, pp.pp_main_photo, pp.pp_main_width, pp.pp_main_height, pp.avatar_location, pp.avatar_size, pp.avatar_type FROM ' . $prefix . 'profile_portal AS pp INNER JOIN ' . $prefix . 'members AS members ON (members.member_id = pp.pp_member_id) WHERE ' . $where . ' AND pp.pp_member_id > ' . $sDb->quote($start) . ' ORDER BY pp.pp_member_id ', $options['limit'])); if (!$avatars) { return true; } $userIdMap = $model->getUserIdsMapFromArray($avatars, 'member_id'); $next = 0; $total = 0; foreach ($avatars as $avatar) { $next = $avatar['member_id']; $newUserId = $this->_mapLookUp($userIdMap, $avatar['member_id']); if (!$newUserId) { continue; } $avatarFile = null; // use profile photo instead of avatar if (!empty($options['importPhotos']) && $avatar['pp_main_photo'] && file_exists("{$options['path']}/{$avatar['pp_main_photo']}")) { $avatarFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf'); copy("{$options['path']}/{$avatar['pp_main_photo']}", $avatarFile); } else { if (!empty($options['fetchRemote']) && $avatar['avatar_type'] == 'url' && $avatar['avatar_location'] && $avatar['avatar_location'] != 'noavatar' && Zend_Uri::check($avatar['avatar_location'])) { try { $httpClient = XenForo_Helper_Http::getClient(preg_replace('/\\s+/', '%20', $avatar['avatar_location'])); $response = $httpClient->request('GET'); if ($response->isSuccessful()) { $avatarFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf'); file_put_contents($avatarFile, $response->getBody()); } } catch (Zend_Http_Client_Exception $e) { } } } // regular avatar import if (empty($avatarFile) && $avatar['avatar_type'] == 'upload' && $avatar['avatar_location'] && file_exists("{$options['path']}/{$avatar['avatar_location']}")) { $avatarFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf'); copy("{$options['path']}/{$avatar['avatar_location']}", $avatarFile); } $isTemp = true; if ($this->_importModel->importAvatar($avatar['member_id'], $newUserId, $avatarFile)) { $total++; } if ($isTemp) { @unlink($avatarFile); } } $this->_session->incrementStepImportTotal($total); return array($next, $options, $this->_getProgressOutput($next, $options['max'])); }
protected static function _request($method, array $provider, $path, $accessToken = false, $expectedKey = false, array $params = array()) { try { if (Zend_Uri::check($path)) { $uri = $path; } else { $uri = call_user_func_array('sprintf', array('%s/index.php?%s', rtrim($provider['root'], '/'), $path)); } $client = XenForo_Helper_Http::getClient($uri); if ($accessToken !== false and !isset($params['oauth_token'])) { $params['oauth_token'] = $accessToken; } if ($method === 'GET') { $client->setParameterGet($params); } else { $client->setParameterPost($params); } $response = $client->request($method); $body = $response->getBody(); $json = @json_decode($body, true); if (!is_array($json)) { $json = array('_body' => $body); } if ($expectedKey !== false) { if (!isset($json[$expectedKey])) { XenForo_Error::logException(new XenForo_Exception(sprintf('Key "%s" not found in %s `%s`: %s', $method, $expectedKey, $path, $body)), false); return false; } } $json['_headers'] = $response->getHeaders(); $json['_responseStatus'] = $response->getStatus(); return $json; } catch (Zend_Http_Client_Exception $e) { XenForo_Error::logException($e, false); return false; } }
/** * Fetches the image at the specified URL using the standard proxy config. * * @param string $url * * @return array */ protected function _fetchImageForProxy($url) { $urlHash = md5($url); $urlParts = parse_url($url); XenForo_ImageProxyStream::register(); // convert kilobytes to bytes XenForo_ImageProxyStream::setMaxSize(XenForo_Application::getOptions()->imageProxyMaxSize * 1024); $streamUri = 'xf-image-proxy://' . $urlHash . '-' . uniqid(); $streamFile = XenForo_ImageProxyStream::getTempFile($streamUri); $requestFailed = true; $error = false; $imageMeta = null; $fileName = !empty($urlParts['path']) ? basename($urlParts['path']) : ''; $mimeType = ''; $fileSize = 0; $image = false; $requestUrl = strtr($url, array(' ' => '+')); if (preg_match_all('/[^A-Za-z0-9._~:\\/?#\\[\\]@!$&\'()*+,;=%-]/', $requestUrl, $matches)) { foreach ($matches[0] as $match) { $requestUrl = str_replace($match[0], '%' . strtoupper(dechex(ord($match[0]))), $requestUrl); } } try { $response = XenForo_Helper_Http::getClient($requestUrl, array('output_stream' => $streamUri, 'timeout' => 10))->setHeaders('Accept-encoding', 'identity')->request('GET'); if ($response->isSuccessful()) { $disposition = $response->getHeader('Content-Disposition'); if (is_array($disposition)) { $disposition = end($disposition); } if ($disposition && preg_match('/filename=(\'|"|)(.+)\\1/siU', $disposition, $match)) { $fileName = $match[2]; } if (!$fileName) { $fileName = 'image'; } $mimeHeader = $response->getHeader('Content-Type'); if (is_array($mimeHeader)) { $mimeHeader = end($mimeHeader); } $mimeType = $mimeHeader ? $mimeHeader : 'unknown/unknown'; $imageMeta = XenForo_ImageProxyStream::getMetaData($streamUri); if (!empty($imageMeta['error'])) { switch ($imageMeta['error']) { case 'not_image': $error = new XenForo_Phrase('file_not_an_image'); break; case 'too_large': $error = new XenForo_Phrase('file_is_too_large'); break; case 'invalid_type': $error = new XenForo_Phrase('image_is_invalid_type'); break; default: $error = $imageMeta['error']; } } else { $requestFailed = false; $image = $imageMeta['image']; $mimeType = $image['mime']; $fileSize = $imageMeta['length']; $extension = XenForo_Helper_File::getFileExtension($fileName); $extensionMap = array(IMAGETYPE_GIF => array('gif'), IMAGETYPE_JPEG => array('jpg', 'jpeg', 'jpe'), IMAGETYPE_PNG => array('png')); $validExtensions = $extensionMap[$image[2]]; if (!in_array($extension, $validExtensions)) { $extensionStart = strrpos($fileName, '.'); $fileName = ($extensionStart ? substr($fileName, 0, $extensionStart) : $fileName) . '.' . $validExtensions[0]; } } } else { $error = new XenForo_Phrase('received_unexpected_response_code_x_message_y', array('code' => $response->getStatus(), 'message' => $response->getMessage())); } } catch (Exception $e) { $error = $e->getMessage(); $response = null; } $response = null; return array('url' => $url, 'failed' => $requestFailed, 'error' => $error, 'image' => $image, 'fileName' => $fileName, 'mimeType' => $mimeType, 'fileSize' => $fileSize, 'tempFile' => $streamFile); }