Вопросы

не работает авторизация через Одноклассники в hybridauth

Не могу получить email
Odnoklassniki.php
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/

/**
 * Hybrid_Providers_Odnoklassniki provider adapter based on OAuth2 protocol
 */
class Hybrid_Providers_Odnoklassniki extends Hybrid_Provider_Model_OAuth2
{
	/**
	* ID wrappers initializer
	*/
	function initialize()
	{
		parent::initialize();
		// Provider apis end-points
		$this->api->api_base_url    = "http://api.ok.ru/fb.do";
		$this->api->authorize_url   = "http://connect.ok.ru/oauth/authorize";
		$this->api->token_url       = "http://api.odnoklassniki.ru/oauth/token.do";
		$this->api->sign_token_name = "access_token";
	}

	private function request($url, $params=false, $type="GET")
	{
		Hybrid_Logger::info("Enter OAuth2Client::request($url)");
		Hybrid_Logger::debug("OAuth2Client::request(). dump request params: ", serialize($params));
		if ($type === "GET"){
			$url = $url . (strpos($url, '?') ? '&' : '?') . http_build_query($params, '', '&');
		}
		$this->http_info = array();
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL            , $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1);
		curl_setopt($ch, CURLOPT_TIMEOUT        , $this->api->curl_time_out);
		curl_setopt($ch, CURLOPT_USERAGENT      , $this->api->curl_useragent);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , $this->api->curl_connect_time_out);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , $this->api->curl_ssl_verifypeer);
		curl_setopt($ch, CURLOPT_HTTPHEADER     , $this->api->curl_header);
		if ($this->api->curl_proxy) {
			curl_setopt($ch, CURLOPT_PROXY  , $this->api->curl_proxy);
		}
		if ($type === "POST") {
			curl_setopt($ch, CURLOPT_POST, 1);
			if ($params) curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
		}
		$response = curl_exec($ch);
		Hybrid_Logger::debug("OAuth2Client::request(). dump request info: ", serialize(curl_getinfo($ch)));
		Hybrid_Logger::debug("OAuth2Client::request(). dump request result: ", serialize($response));
		$this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$this->http_info = array_merge($this->http_info, curl_getinfo($ch));
		curl_close ($ch);
		return $response;
	}

	private function parseRequestResult($result)
	{
		if (json_decode($result)) return json_decode($result);
		parse_str($result, $output);
		$result = new StdClass();
		foreach ($output as $k => $v) {
			$result->$k = $v;
		}
		return $result;
	}

	function authodnoklass($code)
	{
		$params = array(
			"client_id"     => $this->api->client_id,
			"client_secret" => $this->api->client_secret,
			"grant_type"    => "authorization_code",
			"redirect_uri"  => $this->api->redirect_uri,
			"code"          => $code
		);

		$response = $this->request($this->api->token_url, http_build_query($params, '', '&'), $this->api->curl_authenticate_method);
		$response = $this->parseRequestResult($response);

		if (!$response || !isset($response->access_token)) {
			throw new Exception("The Authorization Service has return: " . $response->error);
		}
		if (isset($response->access_token)) $this->api->access_token          = $response->access_token;
		if (isset($response->refresh_token)) $this->api->refresh_token        = $response->refresh_token;
		if (isset($response->expires_in)) $this->api->access_token_expires_in = $response->expires_in;

		// Calculate when the access token expire.
		// At this moment Odnoklassniki does not return expire time in response.
		// 30 minutes expire time staten in dev docs http://apiok.ru/wiki/pages/viewpage.action?pageId=42476652
		if (isset($response->expires_in)) {
			$this->api->access_token_expires_at = time() + $response->expires_in;
		}
		else {
			$this->api->access_token_expires_at = time() + 1800;
		}
		return $response;
	}

	function loginFinish()
	{
		$error = (array_key_exists('error',$_REQUEST))?$_REQUEST['error']:"";
		// Check for errors
		if ($error) {
			throw new Exception("Authentication failed! {$this->providerId} returned an error: $error", 5);
		}
		// Try to authenticate user
		$code = (array_key_exists('code',$_REQUEST))?$_REQUEST['code']:"";
		try {
			$this->authodnoklass($code);
		}
		catch (Exception $e) {
			throw new Exception("User profile request failed! {$this->providerId} returned an error: $e->getMessage() ", 6);
		}
		// Check if authenticated
		if (!$this->api->access_token) {
			throw new Exception("Authentication failed! {$this->providerId} returned an invalid access token.", 5);
		}
		// Store tokens
		$this->token("access_token" , $this->api->access_token);
		$this->token("refresh_token", $this->api->refresh_token);
		$this->token("expires_in"   , $this->api->access_token_expires_in);
		$this->token("expires_at"   , $this->api->access_token_expires_at);
		// Set user connected locally
		$this->setUserConnected();
	}

	/**
	* Load the user profile.
	*/
	function getUserProfile()
	{
		// Set fields you want to get from OK user profile.
		// @see https://apiok.ru/wiki/display/api/users.getCurrentUser+ru
		// @see https://apiok.ru/wiki/display/api/fields+ru
		$fields = "UID,LOCALE,FIRST_NAME,LAST_NAME,NAME,GENDER,AGE,BIRTHDAY,HAS_EMAIL,EMAIL,CURRENT_STATUS,CURRENT_STATUS_ID,CURRENT_STATUS_DATE,ONLINE,PHOTO_ID,PIC190X190,PIC640X480,LOCATION";

		// Signature
		$sig = md5('application_key=' . $this->config['keys']['key'] . 'fields=' . $fields .'method=users.getCurrentUser' . md5($this->api->access_token . $this->api->client_secret));
		// Signed request
		$response = $this->api->api('?application_key=' . $this->config['keys']['key'] . '&fields=' . $fields .'&method=users.getCurrentUser&sig=' . $sig);

		if (!isset($response->uid)) {
			throw new Exception("User profile request failed! {$this->providerId} returned an invalid response.", 6);
		}
                 $copy=false;
   		 if (property_exists($response,'pic_1')){
     		 $path="assets/od_ava/".$response->uid.".jpg";
     		 $copy=copy($response->pic_1,$path);
    			}
		$this->user->profile->photoURL      = ($copy)?$path:"";
		$this->user->profile->identifier    = (property_exists($response,'uid'))?$response->uid:"";
		$this->user->profile->firstName     = (property_exists($response,'first_name'))?$response->first_name:"";
		$this->user->profile->lastName      = (property_exists($response,'last_name'))?$response->last_name:"";
		$this->user->profile->displayName   = (property_exists($response,'name'))?$response->name:"";
		// Get better size of user avatar
		$this->user->profile->photoURL      = (property_exists($response,'pic190x190'))?$response->pic190x190:"";
		$this->user->profile->photoBIG      = (property_exists($response,'pic640x480'))?$response->pic640x480:"";
		$this->user->profile->profileURL    = (property_exists($response,'link'))?$response->link:"";
		$this->user->profile->gender        = (property_exists($response,'gender'))?$response->gender:"";
		$this->user->profile->email         = (property_exists($response,'email'))?$response->email:"";
		$this->user->profile->emailVerified = (property_exists($response,'email'))?$response->email:"";
		if (property_exists($response, 'birthday')) {
			list($birthday_year, $birthday_month, $birthday_day) = explode('-', $response->birthday);
			$this->user->profile->birthDay   = (int) $birthday_day;
			$this->user->profile->birthMonth = (int) $birthday_month;
			$this->user->profile->birthYear  = (int) $birthday_year;
		}
		return $this->user->profile;
	}
}
не знаю в чем дело…
Roman
10 апреля 2018, 18:53
modx.pro
1 738
0

Чем можно заменить элемент p, если он заключен в тег span

Element p not allowed as child of element span in this context.
Чем можно заменить?
Ольга
10 апреля 2018, 17:22
modx.pro
1 540
-1

Кнопка очистить список

Как добавить кнопку очистки всех сравнений?
Denis Chernavin
10 апреля 2018, 16:54
modx.pro
1
976
0

Помогите выстроить логику работы плагина/сниппета.

Приветствую

Не знаю с какой стороны правильно подступиться к решению задачи. В текстовой файле есть 100 строк («ID» * «текст» [* «ссылка»] (ссылка — факультативная запись строки)). Надо чтобы один раз были взяты десять случайных строк из файла, куда-то сохранены и отображались на сайте, но с некоторыми ограничениями (опишу далее).
weranda
10 апреля 2018, 14:16
modx.pro
811
0

Различное отображение страницы товара в админке MS2

Есть задача сделать различное отображение товара в админке для разных контент-менеджеров.
Сделал по инструкции автора https://docs.modx.pro/components/minishop2/development/plug-ins-products. Все работает.
Дальше попытался в файле index.php определить различные msproductdata.js для разных групп пользователей или конкретных пользователей… Но неудача. Видно, ms2 эти файлы подключает до инициализации пользователя…
Прошу подсказать как реализовать мою идею?
Василий К.
10 апреля 2018, 11:59
modx.pro
904
0

TicketForm сделать поле content необязательным

Как сделать поле
content
необязательным?
[[!TicketForm? 
    					    &tplFormCreate=`Zayavka.create` 
    					    &allowedFields=`parent,pagetitle,content,published,mail,baseu,kphone,country,fiop,fiok,age,nom,counts,countr,countn,nomer,subscribe`
    					    &requiredFields=`parent,pagetitle,mail,kphone,nom,counts,nomer,oferta`
    					    &redirectUnpublished=`50`
					    ]]
Максим
10 апреля 2018, 11:36
modx.pro
727
0

SocialTools socDailogForm в модальном окне Uncaught ReferenceError

вызов в модальном окне: [[!socDialogForm]]

в форме при нажатии на кнопку
input type=«button» name=«send» class=«socFormButton btn» onclick=«SocialTools.message.send(this.form, this);» value="[[%socialtools_form_submit_label]]"

ошибка:
Uncaught ReferenceError: SocialTools is not defined
at HTMLInputElement.onclick

Подскажите куда прописать про SocialTools, чтоб заработало
NZ
NZ
10 апреля 2018, 10:59
modx.pro
895
0

Как получить id комментария который удаляется ?

Здравствуйте, подскажите пожалуйста. Создаю свой плагин который будет выполняться на событие OnBeforeCommentRemove, то есть перед удалением комментария.
К комментарию просто можно прикрепить файл, а когда комментарий администратор удаляет через админу, файл который был прикреплен не удаляется и остаётся на сервере.
Собственно сам вопрос в том, каким образом можно получить id комментария который удаляется, либо текущий объект комментария как то. Просто зная ID комментария который удаляется, я тогда могу получить путь к картинке таким вот образом, $modx->getObject(«TicketComment», $id)->photo; и потом собственно удалить картинку.
В самом объекте находиться свойство photo, а в этом свойстве находиться путь до картинки.
Подскажите пожалуйста, что тут можно сделать. Заранее благодарю
Сергей Хлопов
10 апреля 2018, 10:18
modx.pro
729
0

Не корректно отрабатывает msOptionsPrice2

Доброго времени суток.
Неожиданно возникла проблемма с работой плагина цена товра берется из раздела «свойства товара», а не из модификаций плагина. Перед «поломкой» работы плагина был обновлен modx на одну версию, установлен плагин seoPro, удален кеш через ftp.
Изза отчаяния пытался подсунуть обратно старый кеш, заработало но не корректно, при загрузке сайта цена товара сначала берется из раздела «свойства товара» -это наблюдается около секунды, после уже начинают отображаться цены из модификаций плагина и то как то затороможенно, медленно.
При очистки кэша престает работать и это.

Уже всю голову сломал ((

Rustam
09 апреля 2018, 23:56
modx.pro
655
0

Замена самодельных font-тегов на реальные. Валидатор ругается

Простите за глупый вопрос.
Html валидатор ругается на самодельные теги.
Я часто использовала теги для выделения текста, типа
<p2>,  <d1>
и тд.
Обычно я прописывала в стилях свойство тега, и затем применяла его, например:
<style> p2 {
	font-family: 'Open Sans Condensed';
	font-size: 13px;
	font-style: normal;
	font-variant: small-caps;
	font-weight: 100;
	line-height: 9px;
}
</style>
<p2> текст текст текст <p2>
Чем их можно заменить, чтобы уменьшить количество errors, выделяемых html checker?
Ольга
09 апреля 2018, 23:12
modx.pro
915
0