14 array(
"twitter_key",
GetMessage(
"socserv_tw_key"),
"", Array(
"text", 40)),
15 array(
"twitter_secret",
GetMessage(
"socserv_tw_secret"),
"", Array(
"text", 40)),
26 $arParams[
'BACKURL'] =
$APPLICATION->GetCurPageParam(
'',
array(
"logout",
"auth_service_error",
"auth_service_id",
"current_fieldset"));
32 return '<a href="javascript:void(0)
" onclick="BX.util.popup(\
''.
htmlspecialcharsbx(CUtil::JSEscape(
$url)).
'\', 800, 450)
" class="bx-ss-button twitter-button
"></a><span class="bx-spacer
"></span><span>'.$phrase.'</span>';
35 public function GetOnClickJs($arParams)
37 $url = $this->getUrl($arParams);
38 return "BX.util.popup(
'".CUtil::JSEscape($url)."', 800, 450)
";
41 public function getUrl($arParams)
43 // due to something strange reason Twitter does incorrect encoding of oauth_redirect parameters
44 return '/bitrix/tools/oauth/twitter.php?check_key='.\CSocServAuthManager::getUniqueKey().(isset($arParams['BACKURL']) ? "&backurl=
".urlencode(urlencode($arParams['BACKURL'])) : '');
47 public function Authorize()
49 $GLOBALS["APPLICATION
"]->RestartBuffer();
53 if(!isset($_REQUEST["oauth_token
"]) || $_REQUEST["oauth_token
"] == '')
55 $tw = new CTwitterInterface();
56 $callback = CSocServUtil::GetCurUrl('auth_service_id='.self::ID, false, false);
58 if($tw->GetRequestToken($callback))
60 $tw->RedirectAuthUrl();
63 elseif(CSocServAuthManager::CheckUniqueKey())
65 $tw = new CTwitterInterface(false, false, $_REQUEST["oauth_token
"], $_REQUEST["oauth_verifier
"]);
66 if(($arResult = $tw->GetAccessToken()) !== false && $arResult["user_id
"] <> '')
68 $twUser = $tw->GetUserInfo($arResult["user_id
"]);
70 $first_name = $last_name = "";
71 if(is_array($twUser) && ($twUser["name
"] <> ''))
73 $aName = explode(" ", $twUser["name
"]);
74 $first_name = $aName[0];
76 $last_name = $aName[1];
80 'EXTERNAL_AUTH_ID' => self::ID,
81 'XML_ID' => $arResult["user_id
"],
82 'LOGIN' => $arResult["screen_name
"],
84 'LAST_NAME'=> $last_name,
86 if(isset($twUser["profile_image_url
"]) && self::CheckPhotoURI($twUser["profile_image_url
"]))
88 $twUser["profile_image_url
"] = preg_replace("/_normal\./i
", ".
", $twUser["profile_image_url
"]);
89 if ($arPic = CFile::MakeFileArray($twUser["profile_image_url
"]))
91 $arFields["PERSONAL_PHOTO
"] = $arPic;
95 $arFields["PERSONAL_WWW
"] = "https:
98 if(COption::GetOptionString(
'socialservices',
'last_twit_id',
'1') == 1)
100 if(isset($twUser[
"status"][
"id_str"]))
101 COption::SetOptionString(
'socialservices',
'last_twit_id', $twUser[
"status"][
"id_str"]);
105 $bSuccess = $authError ===
true;
111 $aRemove =
array(
"logout",
"auth_service_error",
"auth_service_id",
"oauth_token",
"oauth_verifier",
"check_key",
"current_fieldset",
"ncc");
113 $url = isset(
$_REQUEST[
'backurl']) ?
$_REQUEST[
'backurl'] :
$GLOBALS[
'APPLICATION']->GetCurPageParam(($bSuccess ===
true ?
'' :
'auth_service_id='.self::ID.
'&auth_service_error='.$bSuccess), $aRemove);
114 if(CModule::IncludeModule(
"socialnetwork") && mb_strpos(
$url,
"current_fieldset=") ===
false)
115 $url = (preg_match(
"/\?/",
$url)) ?
$url.
"¤t_fieldset=SOCSERV" :
$url.
"?current_fieldset=SOCSERV";
122 window.opener.location = \''.CUtil::JSEscape(
$url).
'\';
126 CMain::FinalActions();
130 // some error occured
135 public function GetUserMessage($socServUserArray, $sinceId = '1
')
140 if(!empty($socServUserArray))
142 $hash = COption::GetOptionString("socialservices", "twitter_search_hash", "#b24");
143 $appID = trim(self::GetOption("twitter_key"));
144 $appSecret = trim(self::GetOption("twitter_secret"));
145 if(is_array($socServUserArray[1]) && $arToken = $socServUserArray[1])
147 $key = array_rand($arToken, 1);
148 $token = $arToken[$key];
149 if(is_array($socServUserArray[2]))
150 $secret = $socServUserArray[2][$key];
153 $tw = new CTwitterInterface($appID, $appSecret, $token, false, $secret);
154 $result = $tw->SearchByHash($hash, $socServUserArray, $sinceId);
160 public function setUser($userId)
162 $this->userId = $userId;
165 public function getFriendsList($limit, &$next)
169 $currentUser = $this->userId;
172 $currentUser = $USER->GetID();
175 $tw = new CTwitterInterface();
176 $userId = self::TwitterUserId($currentUser);
180 $res = $tw->getUserFriends($userId, $limit, $next);
182 if(is_array($res) && is_array($res['users
']))
184 foreach($res['users
'] as $key => $contact)
186 $res['users
'][$key]['uid
'] = $contact['id_str
'];
187 $res['users
'][$key]['url
'] = "https://twitter.com/".$contact["screen_name"];
188 $res['users
'][$key]['first_name
'] = $contact['name
'];
190 if($contact['profile_image_url
'])
192 $res['users
'][$key]['picture
'] = CMain::IsHTTPS()
193 ? $contact['profile_image_url_https
']
194 : $contact['profile_image_url
'];
195 $res['users
'][$key]['picture
'] = preg_replace("/_normal\./i", ".",
196 $res['users
'][$key]['picture
']);
200 return $res['users
'];
207 public static function sendMessage($uid, $message)
211 $tw = new CTwitterInterface();
212 $userId = self::TwitterUserId($USER->GetID());
216 $res = $tw->sendMessage($userId, $uid, $message);
222 public static function TwitterUserId($userId)
224 $dbSocservUser = \Bitrix\Socialservices\UserTable::getList([
225 'filter
' => ['=USER_ID
' => intval($userId), "=EXTERNAL_AUTH_ID" => self::ID],
228 $arOauth = $dbSocservUser->fetch();
230 return $arOauth["ID"];
234 public static function SendUserFeed($userId, $message, $messageId)
237 $appID = trim(self::GetOption("twitter_key"));
238 $appSecret = trim(self::GetOption("twitter_secret"));
239 $tw = new CTwitterInterface($appID, $appSecret);
240 return $tw->SendTwit($userId, $message, $messageId);
245class CTwitterInterface
247 const REQUEST_URL = "https://api.twitter.com/oauth/request_token";
248 const AUTH_URL = "https://api.twitter.com/oauth/authenticate";
249 const TOKEN_URL = "https://api.twitter.com/oauth/access_token";
250 const API_URL = "https://api.twitter.com/1.1/users/show.json";
251 const POST_URL = "https://api.twitter.com/1.1/statuses/update.json";
252 const SEARCH_URL = "https://api.twitter.com/1.1/search/tweets.json";
253 const FRIENDS_URL = "https://api.twitter.com/1.1/friends/list.json";
254 const MESSAGE_URL = "https://api.twitter.com/1.1/direct_messages/new.json";
257 protected $appSecret;
258 protected $token = false;
259 protected $tokenVerifier = false;
260 protected $tokenSecret = false;
261 protected $oauthArray;
263 public function __construct($appID = false, $appSecret = false, $token = false, $tokenVerifier = false, $tokenSecret = false)
267 $appID = trim(CSocServTwitter::GetOption("twitter_key"));
270 if($appSecret === false)
272 $appSecret = trim(CSocServTwitter::GetOption("twitter_secret"));
275 $this->httpTimeout = SOCSERV_DEFAULT_HTTP_TIMEOUT;
276 $this->appID = $appID;
277 $this->appSecret = $appSecret;
279 $this->token = $token;
280 $this->tokenVerifier = $tokenVerifier;
281 if($this->token && isset($_SESSION["twitter_token_secret"]))
283 $this->tokenSecret = $_SESSION["twitter_token_secret"];
285 if($this->token && $tokenSecret)
287 $this->tokenSecret = $tokenSecret;
291 protected function GetDefParams()
293 $this->oauthArray = array(
294 "oauth_consumer_key" => $this->appID,
295 "oauth_nonce" => md5(microtime().mt_rand()),
296 "oauth_signature_method" => "HMAC-SHA1",
297 "oauth_timestamp" => time(),
298 "oauth_version" => "1.0",
301 return $this->oauthArray;
304 public function GetRequestToken($callback)
306 $arParams = array_merge($this->GetDefParams(), array(
307 "oauth_callback" => $callback,
310 $arParams["oauth_signature"] = $this->BuildSignature($this->GetSignatureString($arParams, self::REQUEST_URL));
312 $result = CHTTP::sPostHeader(self::REQUEST_URL, $arParams, array(), $this->httpTimeout);
313 parse_str($result, $arResult);
314 if(isset($arResult["oauth_token"]) && $arResult["oauth_token"] <> '')
316 $this->token = $arResult["oauth_token"];
317 $this->tokenSecret = $arResult["oauth_token_secret"];
318 $_SESSION["twitter_token_secret"] = $this->tokenSecret;
324 public function RedirectAuthUrl()
329 LocalRedirect(self::AUTH_URL."?oauth_token=".urlencode($this->token).'&check_key=
'.\CSocServAuthManager::getUniqueKey()/*."&state=".urlencode($state)*/, true);
332 public function GetAccessToken()
334 if(!$this->token || !$this->tokenVerifier || !$this->tokenSecret)
337 $arParams = array_merge($this->GetDefParams(), array(
338 "oauth_token" => $this->token,
339 "oauth_verifier" => $this->tokenVerifier,
342 $arParams["oauth_signature"] = $this->BuildSignature($this->GetSignatureString($arParams, self::TOKEN_URL));
343 $result = CHTTP::sPostHeader(self::TOKEN_URL, $arParams, array(), $this->httpTimeout);
344 parse_str($result, $arResult);
345 if(isset($arResult["oauth_token"]) && $arResult["oauth_token"] <> '')
347 $this->token = $arResult["oauth_token"];
348 $this->tokenSecret = $arResult["oauth_token_secret"];
349 $_SESSION["OAUTH_DATA"] = array("OATOKEN" => $this->token, "OASECRET" => $this->tokenSecret);
355 public function GetUserInfo($user_id)
357 $arParams = array_merge($this->GetDefParams(), array(
358 "oauth_token" => $this->token,
359 "user_id" => $user_id,
361 $arParams["oauth_signature"] = urlencode($this->BuildSignature($this->GetSignatureString($arParams, self::API_URL)));
364 "Authorization" => 'OAuth oauth_consumer_key=
"'.$arParams["oauth_consumer_key
"].'", oauth_nonce=
"'.$arParams["oauth_nonce
"].'", oauth_signature=
"'.$arParams["oauth_signature
"].'", oauth_signature_method=
"HMAC-SHA1", oauth_timestamp=
"'.$arParams["oauth_timestamp
"].'", oauth_token=
"'.$this->token.'", oauth_version=
"1.0"',
365 "Content-type" => "application/x-www-form-urlencoded",
368 $result = CHTTP::sGetHeader(self::API_URL.'?user_id=
'.$user_id, $arHeaders, $this->httpTimeout);
370 return CUtil::JsObjectToPhp($result);
373 public function getUserFriends($user_id, $limit, &$next)
385 $this->SetOauthKeys($user_id);
387 $arParams = array_merge($this->GetDefParams(), array(
388 "oauth_token" => $this->token,
390 "skip_status" => "true",
391 "include_user_entities" => "false",
394 $url = self::FRIENDS_URL.'?cursor=
'.urlencode($next).'&skip_status=
true&include_user_entities=
false';
398 $arParams["count"] = intval($limit);
399 $url .= '&
count=
'.$arParams["count"];
402 $arParams["oauth_signature"] = urlencode($this->BuildSignature($this->GetSignatureString($arParams, self::FRIENDS_URL)));
405 "Authorization" => 'OAuth oauth_consumer_key=
"'.$arParams["oauth_consumer_key
"].'", oauth_nonce=
"'.$arParams["oauth_nonce
"].'", oauth_signature=
"'.$arParams["oauth_signature
"].'", oauth_signature_method=
"HMAC-SHA1", oauth_timestamp=
"'.$arParams["oauth_timestamp
"].'", oauth_token=
"'.$this->token.'", oauth_version=
"1.0"',
406 "Content-type" => "application/x-www-form-urlencoded",
408 $result = CHTTP::sGetHeader($url, $arHeaders, $this->httpTimeout);
410 $res = CUtil::JsObjectToPhp($result);
412 $next = $res['next_cursor_str
'];
421 public function sendMessage($user_id, $uid, $message)
423 $this->SetOauthKeys($user_id);
425 if($this->access_token === false)
428 $arParams = array_merge($this->GetDefParams(), array(
429 "oauth_token" => $this->token,
434 $arParams["oauth_signature"] = urlencode($this->BuildSignature($this->GetSignatureString($arParams, self::MESSAGE_URL)));
437 "Authorization" => 'OAuth oauth_consumer_key=
"'.$arParams["oauth_consumer_key
"].'", oauth_nonce=
"'.$arParams["oauth_nonce
"].'", oauth_signature=
"'.$arParams["oauth_signature
"].'", oauth_signature_method=
"HMAC-SHA1", oauth_timestamp=
"'.$arParams["oauth_timestamp
"].'", oauth_token=
"'.$this->token.'", oauth_version=
"1.0"',
445 $ob = new \Bitrix\Main\Web\HttpClient();
446 foreach($arHeaders as $header => $value)
448 $ob->setHeader($header, $value);
451 return $ob->post(self::MESSAGE_URL, $arPost);
454 public function SetOauthKeys($socServUserId)
456 $dbSocservUser = \Bitrix\Socialservices\UserTable::getList([
457 'filter
' => ['=ID
' => $socServUserId],
458 'select' => ["OATOKEN", "OASECRET"]
460 while($arOauth = $dbSocservUser->fetch())
462 $this->token = $arOauth["OATOKEN"];
463 $this->tokenSecret = $arOauth["OASECRET"];
465 if(!$this->token || !$this->tokenSecret)
470 public function SearchByHash($hash, $socServUserArray, $sinceId)
472 $arParams = array_merge(array("count" => 100, "include_entities" => "false"), $this->GetDefParams());
473 $arParams = array_merge($arParams, array(
474 "oauth_token" => $this->token,
476 "since_id" => $sinceId,
478 $arParams["oauth_signature"] = urlencode($this->BuildSignature($this->GetSignatureString($arParams, self::SEARCH_URL)));
480 "Authorization" => 'OAuth oauth_consumer_key=
"'.$arParams["oauth_consumer_key
"].'", oauth_nonce=
"'.$arParams["oauth_nonce
"].'", oauth_signature=
"'.$arParams["oauth_signature
"].'", oauth_signature_method=
"HMAC-SHA1", oauth_timestamp=
"'.$arParams["oauth_timestamp
"].'", oauth_token=
"'.$this->token.'", oauth_version=
"1.0"',
481 "Content-type" => "application/x-www-form-urlencoded",
483 $result = @CHTTP::sGetHeader(self::SEARCH_URL."?count=100&include_entities=false&q=".urlencode($hash)."&since_id=".$sinceId, $arHeaders, $this->httpTimeout);
486 $arResult = Json::decode($result);
487 if (empty($arResult) || !is_array($arResult))
492 if(is_array($arResult["statuses"]))
493 foreach($arResult["statuses"] as $key => $value)
495 if(!$find = array_search($value["user"]["id_str"], $socServUserArray[0]))
496 unset($arResult["statuses"][$key]);
499 $arResult["statuses"][$key]["kp_user_id"] = $find;
500 $arResult["statuses"][$key]["user_perms"] = self::GetUserPerms($value["user"]["id_str"]);
508 private function GetAllPages($arResult)
510 static $arTwits = array();
511 if(!isset($arResult["search_metadata"]["next_results"]))
513 parse_str(preg_replace("|\?|", '', $arResult["search_metadata"]["next_results"]), $searchMetaData);
514 $arParams = array_merge(array("count" => $searchMetaData["count"], "include_entities" => $searchMetaData["include_entities"], "max_id" => $searchMetaData["max_id"]), $this->GetDefParams());
515 $arParams = array_merge($arParams, array(
516 "oauth_token" => $this->token,
517 "q" => $searchMetaData["q"],
519 $arParams["oauth_signature"] = urlencode($this->BuildSignature($this->GetSignatureString($arParams, self::SEARCH_URL)));
521 "Authorization" => 'OAuth oauth_consumer_key=
"'.$arParams["oauth_consumer_key
"].'", oauth_nonce=
"'.$arParams["oauth_nonce
"].'", oauth_signature=
"'.$arParams["oauth_signature
"].'", oauth_signature_method=
"HMAC-SHA1", oauth_timestamp=
"'.$arParams["oauth_timestamp
"].'", oauth_token=
"'.$this->token.'", oauth_version=
"1.0"',
522 "Content-type" => "application/x-www-form-urlencoded",
524 $result = CHTTP::sGetHeader(self::SEARCH_URL."?count=".$searchMetaData["count"]."&include_entities=".$searchMetaData["include_entities"]."&max_id=".$searchMetaData["max_id"]."&q=".urlencode($searchMetaData["q"]), $arHeaders, $this->httpTimeout);
526 $arResult = CUtil::JsObjectToPhp($result);
527 if(is_array($arResult["statuses"]))
528 $arTwits = array_merge($arTwits, $arResult["statuses"]);
529 return self::GetAllPages($arResult);
532 private function GetAllPagesNotAuth($arResult)
534 static $arTwits = array();
535 if(!isset($arResult["next_page"]) || $arResult["page"] == 15 || intval($arResult["page"]) < 1)
537 $result = CHTTP::sGet(self::SEARCH_URL.$arResult["next_page"]);
538 $arResult = CUtil::JsObjectToPhp($result);
539 $arTwits = array_merge($arTwits, $arResult["results"]);
540 return self::GetAllPages($arResult);
543 public function SendTwit($socServUserId, $message, $messageId)
545 $isSetOauthKeys = true;
546 if(!$this->token || !$this->tokenSecret)
547 $isSetOauthKeys = self::SetOauthKeys($socServUserId);
549 if($isSetOauthKeys === false)
551 CSocServMessage::Delete($messageId);
555 if(mb_strlen($message) > 139)
556 $message = mb_substr($message, 0, 137)."...";
558 $arParams = array_merge($this->GetDefParams(), array(
559 "oauth_token" => $this->token,
562 $arParams["oauth_signature"] = urlencode($this->BuildSignature($this->GetSignatureString($arParams, $this::POST_URL)));
565 "Authorization" => 'OAuth oauth_consumer_key=
"'.$arParams["oauth_consumer_key
"].'", oauth_nonce=
"'.$arParams["oauth_nonce
"].'", oauth_signature=
"'.$arParams["oauth_signature
"].'", oauth_signature_method=
"HMAC-SHA1", oauth_timestamp=
"'.$arParams["oauth_timestamp
"].'", oauth_token=
"'.$this->token.'", oauth_version=
"1.0"',
567 $arPost = array("status"=> $message);
568 $result = @CHTTP::sPostHeader($this::POST_URL, $arPost, $arHeaders, $this->httpTimeout);
569 if($result !== false)
571 return CUtil::JsObjectToPhp($result);
578 private function GetUserPerms($userXmlId)
580 $arUserPermis = array();
581 $dbSocUser = \Bitrix\Socialservices\UserTable::getList([
583 '=EXTERNAL_AUTH_ID
'=>'Twitter
',
584 '=XML_ID
'=>$userXmlId
586 'select' => ["PERMISSIONS"]
588 while($arSocUser = $dbSocUser->fetch())
590 $arUserPermis = unserialize($arSocUser["PERMISSIONS"], ['allowed_classes
' => false]);
591 if(is_array($arUserPermis))
592 foreach($arUserPermis as $key=>$value)
594 $arUserPermis[$key] = "G2";
596 if(!empty($arUserPermis))
597 return $arUserPermis;
599 return array("UA" => array("UA"));
602 protected function urlencode($mixParams)
604 if(is_array($mixParams))
605 return array_map(array($this, 'urlencode'), $mixParams);
606 elseif (is_scalar($mixParams))
607 return str_replace(array('+
','%7E
'), array(' ','~
'), rawurlencode($mixParams));
612 protected function GetSignatureString($arParams, $url)
614 $typeRequest = "POST";
615 if($url === self::API_URL || $url === self::SEARCH_URL || $url == self::FRIENDS_URL)
616 $typeRequest = "GET";
617 if(array_key_exists('oauth_signature
', $arParams))
618 unset($arParams['oauth_signature
']);
625 $this->BuildQuery($arParams),
631 protected function BuildQuery($params)
636 $keys = $this->urlencode(array_keys($params));
637 $values = $this->urlencode(array_values($params));
638 $params = array_combine($keys, $values);
640 uksort($params, 'strcmp
');
643 foreach ($params as $parameter => $value)
648 foreach ($value as $duplicate_value)
649 $pairs[] = $parameter . '=
' . $duplicate_value;
652 $pairs[] = $parameter . '=
' . $value;
654 return implode('&
', $pairs);
657 protected function BuildSignature($sigString)
659 if(!function_exists("hash_hmac"))
666 ($this->tokenSecret? $this->tokenSecret : ''),
670 return base64_encode(hash_hmac('sha1
', $sigString, $key, true));
change_password_forgot_link login popup forget pas AUTH_GOTO_FORGOT_FORM login btn wrap change_password_button login popup link login popup return auth javascript
static URN2URI($urn, $server_name='')
AuthorizeUser($socservUserFields, $bSave=false)
static getOAuthProxyString()
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
htmlspecialcharsbx($string, $flags=ENT_COMPAT, $doubleEncode=true)
IncludeModuleLangFile($filepath, $lang=false, $bReturnArray=false)
GetMessage($name, $aReplace=null)
</p ></td >< td valign=top style='border-top:none;border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;padding:0cm 2.0pt 0cm 2.0pt;height:9.0pt'>< p class=Normal align=center style='margin:0cm;margin-bottom:.0001pt;text-align:center;line-height:normal'>< a name=ТекстовоеПоле54 ></a ><?=($taxRate > count( $arTaxList) > 0) ? $taxRate."%"
$GLOBALS['_____370096793']