Facebook php-sdk error [closed] - facebook

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Facebook was change before some day the php-sdk and now I have a problem with that.
When I try to login I got this errors:
An error occurred. Please try again later.
API Error Code: 100
API Error Description: Invalid parameter
Error Message: Please migrate to OAuth2 and use new /dialog/oauth endpoint. return_session is no longer available.
My php connect file is:
<?php
class JO_Api_Facebook_Connect {
/**
* Version.
*/
const VERSION = '2.1.2';
/**
* Default options for curl.
*/
public static $CURL_OPTS = array(
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_USERAGENT => 'facebook-php-2.0',
);
/**
* List of query parameters that get automatically dropped when rebuilding
* the current URL.
*/
protected static $DROP_QUERY_PARAMS = array(
'session',
'signed_request',
);
/**
* Maps aliases to Facebook domains.
*/
public static $DOMAIN_MAP = array(
'api' => 'https://api.facebook.com/',
'api_read' => 'https://api-read.facebook.com/',
'graph' => 'https://graph.facebook.com/',
'www' => 'https://www.facebook.com/',
);
/**
* The Application ID.
*/
protected $appId;
/**
* The Application API Secret.
*/
protected $apiSecret;
/**
* The active user session, if one is available.
*/
protected $session;
/**
* The data from the signed_request token.
*/
protected $signedRequest;
/**
* Indicates that we already loaded the session as best as we could.
*/
protected $sessionLoaded = false;
/**
* Indicates if Cookie support should be enabled.
*/
protected $cookieSupport = false;
/**
* Base domain for the Cookie.
*/
protected $baseDomain = '';
/**
* Indicates if the CURL based # syntax for file uploads is enabled.
*/
protected $fileUploadSupport = false;
/**
* Initialize a Facebook Application.
*
* The configuration:
* - appId: the application ID
* - secret: the application secret
* - cookie: (optional) boolean true to enable cookie support
* - domain: (optional) domain for the cookie
* - fileUpload: (optional) boolean indicating if file uploads are enabled
*
* #param Array $config the application configuration
*/
public function __construct($config) {
$this->setAppId($config['appId']);
$this->setApiSecret($config['secret']);
if (isset($config['cookie'])) {
$this->setCookieSupport($config['cookie']);
}
if (isset($config['domain'])) {
$this->setBaseDomain($config['domain']);
}
if (isset($config['fileUpload'])) {
$this->setFileUploadSupport($config['fileUpload']);
}
}
/**
* Set the Application ID.
*
* #param String $appId the Application ID
*/
public function setAppId($appId) {
$this->appId = $appId;
return $this;
}
/**
* Get the Application ID.
*
* #return String the Application ID
*/
public function getAppId() {
return $this->appId;
}
/**
* Set the API Secret.
*
* #param String $appId the API Secret
*/
public function setApiSecret($apiSecret) {
$this->apiSecret = $apiSecret;
return $this;
}
/**
* Get the API Secret.
*
* #return String the API Secret
*/
public function getApiSecret() {
return $this->apiSecret;
}
/**
* Set the Cookie Support status.
*
* #param Boolean $cookieSupport the Cookie Support status
*/
public function setCookieSupport($cookieSupport) {
$this->cookieSupport = $cookieSupport;
return $this;
}
/**
* Get the Cookie Support status.
*
* #return Boolean the Cookie Support status
*/
public function useCookieSupport() {
return $this->cookieSupport;
}
/**
* Set the base domain for the Cookie.
*
* #param String $domain the base domain
*/
public function setBaseDomain($domain) {
$this->baseDomain = $domain;
return $this;
}
/**
* Get the base domain for the Cookie.
*
* #return String the base domain
*/
public function getBaseDomain() {
return $this->baseDomain;
}
/**
* Set the file upload support status.
*
* #param String $domain the base domain
*/
public function setFileUploadSupport($fileUploadSupport) {
$this->fileUploadSupport = $fileUploadSupport;
return $this;
}
/**
* Get the file upload support status.
*
* #return String the base domain
*/
public function useFileUploadSupport() {
return $this->fileUploadSupport;
}
/**
* Get the data from a signed_request token
*
* #return String the base domain
*/
public function getSignedRequest() {
if (!$this->signedRequest) {
if (isset($_REQUEST['signed_request'])) {
$this->signedRequest = $this->parseSignedRequest(
$_REQUEST['signed_request']);
}
}
return $this->signedRequest;
}
/**
* Set the Session.
*
* #param Array $session the session
* #param Boolean $write_cookie indicate if a cookie should be written. this
* value is ignored if cookie support has been disabled.
*/
public function setSession($session=null, $write_cookie=true) {
$session = $this->validateSessionObject($session);
$this->sessionLoaded = true;
$this->session = $session;
if ($write_cookie) {
$this->setCookieFromSession($session);
}
return $this;
}
/**
* Get the session object. This will automatically look for a signed session
* sent via the signed_request, Cookie or Query Parameters if needed.
*
* #return Array the session
*/
public function getSession() {
if (!$this->sessionLoaded) {
$session = null;
$write_cookie = true;
// try loading session from signed_request in $_REQUEST
$signedRequest = $this->getSignedRequest();
if ($signedRequest) {
// sig is good, use the signedRequest
$session = $this->createSessionFromSignedRequest($signedRequest);
}
// try loading session from $_REQUEST
if (!$session && isset($_REQUEST['session'])) {
$_REQUEST['session'] = html_entity_decode($_REQUEST['session']);
$session = json_decode(
get_magic_quotes_gpc()
? stripslashes($_REQUEST['session'])
: $_REQUEST['session'],
true
);
$session = $this->validateSessionObject($session);
}
// try loading session from cookie if necessary
if (!$session && $this->useCookieSupport()) {
$cookieName = $this->getSessionCookieName();
if (isset($_COOKIE[$cookieName])) {
$_COOKIE[$cookieName] = html_entity_decode($_COOKIE[$cookieName]);
$session = array();
parse_str(trim(
get_magic_quotes_gpc()
? stripslashes($_COOKIE[$cookieName])
: $_COOKIE[$cookieName],
'"'
), $session);
$session = $this->validateSessionObject($session);
// write only if we need to delete a invalid session cookie
$write_cookie = empty($session);
}
}
$this->setSession($session, $write_cookie);
}
return $this->session;
}
/**
* Get the UID from the session.
*
* #return String the UID if available
*/
public function getUser() {
$session = $this->getSession();
return $session ? $session['uid'] : null;
}
/**
* Gets a OAuth access token.
*
* #return String the access token
*/
public function getAccessToken() {
$session = $this->getSession();
// either user session signed, or app signed
if ($session) {
return $session['access_token'];
} else {
return $this->getAppId() .'|'. $this->getApiSecret();
}
}
/**
* Get a Login URL for use with redirects. By default, full page redirect is
* assumed. If you are using the generated URL with a window.open() call in
* JavaScript, you can pass in display=popup as part of the $params.
*
* The parameters:
* - next: the url to go to after a successful login
* - cancel_url: the url to go to after the user cancels
* - req_perms: comma separated list of requested extended perms
* - display: can be "page" (default, full page) or "popup"
*
* #param Array $params provide custom parameters
* #return String the URL for the login flow
*/
public function getLoginUrl($params=array()) {
$currentUrl = $this->getCurrentUrl();
return $this->getUrl(
'www',
'login.php',
array_merge(array(
'api_key' => $this->getAppId(),
'cancel_url' => $currentUrl,
'display' => 'page',
'fbconnect' => 1,
'next' => $currentUrl,
'return_session' => 1,
'session_version' => 3,
'v' => '1.0',
), $params)
);
}
/**
* Get a Logout URL suitable for use with redirects.
*
* The parameters:
* - next: the url to go to after a successful logout
*
* #param Array $params provide custom parameters
* #return String the URL for the logout flow
*/
public function getLogoutUrl($params=array()) {
return $this->getUrl(
'www',
'logout.php',
array_merge(array(
'next' => $this->getCurrentUrl(),
'access_token' => $this->getAccessToken(),
), $params)
);
}
/**
* Get a login status URL to fetch the status from facebook.
*
* The parameters:
* - ok_session: the URL to go to if a session is found
* - no_session: the URL to go to if the user is not connected
* - no_user: the URL to go to if the user is not signed into facebook
*
* #param Array $params provide custom parameters
* #return String the URL for the logout flow
*/
public function getLoginStatusUrl($params=array()) {
return $this->getUrl(
'www',
'extern/login_status.php',
array_merge(array(
'api_key' => $this->getAppId(),
'no_session' => $this->getCurrentUrl(),
'no_user' => $this->getCurrentUrl(),
'ok_session' => $this->getCurrentUrl(),
'session_version' => 3,
), $params)
);
}
/**
* Make an API call.
*
* #param Array $params the API call parameters
* #return the decoded response
*/
public function api(/* polymorphic */) {
$args = func_get_args();
if (is_array($args[0])) {
return $this->_restserver($args[0]);
} else {
return call_user_func_array(array($this, '_graph'), $args);
}
}
/**
* Invoke the old restserver.php endpoint.
*
* #param Array $params method call object
* #return the decoded response object
* #throws JO_Api_Facebook_Exception
*/
protected function _restserver($params) {
// generic application level parameters
$params['api_key'] = $this->getAppId();
$params['format'] = 'json-strings';
$result = json_decode($this->_oauthRequest(
$this->getApiUrl($params['method']),
$params
), true);
// results are returned, errors are thrown
if (is_array($result) && isset($result['error_code'])) {
throw new JO_Api_Facebook_Exception($result);
}
return $result;
}
/**
* Invoke the Graph API.
*
* #param String $path the path (required)
* #param String $method the http method (default 'GET')
* #param Array $params the query/post data
* #return the decoded response object
* #throws JO_Api_Facebook_Exception
*/
protected function _graph($path, $method='GET', $params=array()) {
if (is_array($method) && empty($params)) {
$params = $method;
$method = 'GET';
}
$params['method'] = $method; // method override as we always do a POST
$result = json_decode($this->_oauthRequest(
$this->getUrl('graph', $path),
$params
), true);
// results are returned, errors are thrown
if (is_array($result) && isset($result['error'])) {
$e = new JO_Api_Facebook_Exception($result);
switch ($e->getType()) {
// OAuth 2.0 Draft 00 style
case 'OAuthException':
// OAuth 2.0 Draft 10 style
case 'invalid_token':
$this->setSession(null);
}
throw $e;
}
return $result;
}
/**
* Make a OAuth Request
*
* #param String $path the path (required)
* #param Array $params the query/post data
* #return the decoded response object
* #throws JO_Api_Facebook_Exception
*/
protected function _oauthRequest($url, $params) {
if (!isset($params['access_token'])) {
$params['access_token'] = $this->getAccessToken();
}
// json_encode all params values that are not strings
foreach ($params as $key => $value) {
if (!is_string($value)) {
$params[$key] = json_encode($value);
}
}
return $this->makeRequest($url, $params);
}
/**
* Makes an HTTP request. This method can be overriden by subclasses if
* developers want to do fancier things or use something other than curl to
* make the request.
*
* #param String $url the URL to make the request to
* #param Array $params the parameters to use for the POST body
* #param CurlHandler $ch optional initialized curl handle
* #return String the response text
*/
protected function makeRequest($url, $params, $ch=null) {
if (!$ch) {
$ch = curl_init();
}
$opts = self::$CURL_OPTS;
if ($this->useFileUploadSupport()) {
$opts[CURLOPT_POSTFIELDS] = $params;
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
$opts[CURLOPT_URL] = $url;
// disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
// for 2 seconds if the server does not support this header.
if (isset($opts[CURLOPT_HTTPHEADER])) {
$existing_headers = $opts[CURLOPT_HTTPHEADER];
$existing_headers[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $existing_headers;
} else {
$opts[CURLOPT_HTTPHEADER] = array('Expect:');
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT
self::errorLog('Invalid or no certificate authority found, using bundled information');
curl_setopt($ch, CURLOPT_CAINFO,
dirname(__FILE__) . '/fb_ca_chain_bundle.crt');
$result = curl_exec($ch);
}
if ($result === false) {
$e = new JO_Api_Facebook_Exception(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
}
/**
* The name of the Cookie that contains the session.
*
* #return String the cookie name
*/
protected function getSessionCookieName() {
return 'fbs_' . $this->getAppId();
}
/**
* Set a JS Cookie based on the _passed in_ session. It does not use the
* currently stored session -- you need to explicitly pass it in.
*
* #param Array $session the session to use for setting the cookie
*/
protected function setCookieFromSession($session=null) {
if (!$this->useCookieSupport()) {
return;
}
$cookieName = $this->getSessionCookieName();
$value = 'deleted';
$expires = time() - 3600;
$domain = $this->getBaseDomain();
if ($session) {
$value = '"' . http_build_query($session, null, '&') . '"';
if (isset($session['base_domain'])) {
$domain = $session['base_domain'];
}
$expires = $session['expires'];
}
// prepend dot if a domain is found
if ($domain) {
$domain = '.' . $domain;
}
// if an existing cookie is not set, we dont need to delete it
if ($value == 'deleted' && empty($_COOKIE[$cookieName])) {
return;
}
if (headers_sent()) {
self::errorLog('Could not set cookie. Headers already sent.');
// ignore for code coverage as we will never be able to setcookie in a CLI
// environment
// #codeCoverageIgnoreStart
} else {
setcookie($cookieName, $value, $expires, '/', $domain);
}
// #codeCoverageIgnoreEnd
}
/**
* Validates a session_version=3 style session object.
*
* #param Array $session the session object
* #return Array the session object if it validates, null otherwise
*/
protected function validateSessionObject($session) {
// make sure some essential fields exist
if (is_array($session) &&
isset($session['uid']) &&
isset($session['access_token']) &&
isset($session['sig'])) {
// validate the signature
$session_without_sig = $session;
unset($session_without_sig['sig']);
$expected_sig = self::generateSignature(
$session_without_sig,
$this->getApiSecret()
);
if ($session['sig'] != $expected_sig) {
self::errorLog('Got invalid session signature in cookie.');
$session = null;
}
// check expiry time
} else {
$session = null;
}
return $session;
}
/**
* Returns something that looks like our JS session object from the
* signed token's data
*
* TODO: Nuke this once the login flow uses OAuth2
*
* #param Array the output of getSignedRequest
* #return Array Something that will work as a session
*/
protected function createSessionFromSignedRequest($data) {
if (!isset($data['oauth_token'])) {
return null;
}
$session = array(
'uid' => $data['user_id'],
'access_token' => $data['oauth_token'],
'expires' => $data['expires'],
);
// put a real sig, so that validateSignature works
$session['sig'] = self::generateSignature(
$session,
$this->getApiSecret()
);
return $session;
}
/**
* Parses a signed_request and validates the signature.
* Then saves it in $this->signed_data
*
* #param String A signed token
* #param Boolean Should we remove the parts of the payload that
* are used by the algorithm?
* #return Array the payload inside it or null if the sig is wrong
*/
protected function parseSignedRequest($signed_request) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = self::base64UrlDecode($encoded_sig);
$data = json_decode(self::base64UrlDecode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
self::errorLog('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload,
$this->getApiSecret(), $raw = true);
if ($sig !== $expected_sig) {
self::errorLog('Bad Signed JSON signature!');
return null;
}
return $data;
}
/**
* Build the URL for api given parameters.
*
* #param $method String the method name.
* #return String the URL for the given parameters
*/
protected function getApiUrl($method) {
static $READ_ONLY_CALLS =
array('admin.getallocation' => 1,
'admin.getappproperties' => 1,
'admin.getbannedusers' => 1,
'admin.getlivestreamvialink' => 1,
'admin.getmetrics' => 1,
'admin.getrestrictioninfo' => 1,
'application.getpublicinfo' => 1,
'auth.getapppublickey' => 1,
'auth.getsession' => 1,
'auth.getsignedpublicsessiondata' => 1,
'comments.get' => 1,
'connect.getunconnectedfriendscount' => 1,
'dashboard.getactivity' => 1,
'dashboard.getcount' => 1,
'dashboard.getglobalnews' => 1,
'dashboard.getnews' => 1,
'dashboard.multigetcount' => 1,
'dashboard.multigetnews' => 1,
'data.getcookies' => 1,
'events.get' => 1,
'events.getmembers' => 1,
'fbml.getcustomtags' => 1,
'feed.getappfriendstories' => 1,
'feed.getregisteredtemplatebundlebyid' => 1,
'feed.getregisteredtemplatebundles' => 1,
'fql.multiquery' => 1,
'fql.query' => 1,
'friends.arefriends' => 1,
'friends.get' => 1,
'friends.getappusers' => 1,
'friends.getlists' => 1,
'friends.getmutualfriends' => 1,
'gifts.get' => 1,
'groups.get' => 1,
'groups.getmembers' => 1,
'intl.gettranslations' => 1,
'links.get' => 1,
'notes.get' => 1,
'notifications.get' => 1,
'pages.getinfo' => 1,
'pages.isadmin' => 1,
'pages.isappadded' => 1,
'pages.isfan' => 1,
'permissions.checkavailableapiaccess' => 1,
'permissions.checkgrantedapiaccess' => 1,
'photos.get' => 1,
'photos.getalbums' => 1,
'photos.gettags' => 1,
'profile.getinfo' => 1,
'profile.getinfooptions' => 1,
'stream.get' => 1,
'stream.getcomments' => 1,
'stream.getfilters' => 1,
'users.getinfo' => 1,
'users.getloggedinuser' => 1,
'users.getstandardinfo' => 1,
'users.hasapppermission' => 1,
'users.isappuser' => 1,
'users.isverified' => 1,
'video.getuploadlimits' => 1);
$name = 'api';
if (isset($READ_ONLY_CALLS[strtolower($method)])) {
$name = 'api_read';
}
return self::getUrl($name, 'restserver.php');
}
/**
* Build the URL for given domain alias, path and parameters.
*
* #param $name String the name of the domain
* #param $path String optional path (without a leading slash)
* #param $params Array optional query parameters
* #return String the URL for the given parameters
*/
protected function getUrl($name, $path='', $params=array()) {
$url = self::$DOMAIN_MAP[$name];
if ($path) {
if ($path[0] === '/') {
$path = substr($path, 1);
}
$url .= $path;
}
if ($params) {
$url .= '?' . http_build_query($params, null, '&');
}
return $url;
}
/**
* Returns the Current URL, stripping it of known FB parameters that should
* not persist.
*
* #return String the current URL
*/
protected function getCurrentUrl() {
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'
? 'https://'
: 'http://';
$currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$parts = parse_url($currentUrl);
// drop known fb params
$query = '';
if (!empty($parts['query'])) {
$params = array();
parse_str($parts['query'], $params);
foreach(self::$DROP_QUERY_PARAMS as $key) {
unset($params[$key]);
}
if (!empty($params)) {
$query = '?' . http_build_query($params, null, '&');
}
}
// use port if non default
$port =
isset($parts['port']) &&
(($protocol === 'http://' && $parts['port'] !== 80) ||
($protocol === 'https://' && $parts['port'] !== 443))
? ':' . $parts['port'] : '';
// rebuild
return $protocol . $parts['host'] . $port . $parts['path'] . $query;
}
/**
* Generate a signature for the given params and secret.
*
* #param Array $params the parameters to sign
* #param String $secret the secret to sign with
* #return String the generated signature
*/
protected static function generateSignature($params, $secret) {
// work with sorted data
ksort($params);
// generate the base string
$base_string = '';
foreach($params as $key => $value) {
$base_string .= $key . '=' . $value;
}
$base_string .= $secret;
return md5($base_string);
}
/**
* Prints to the error log if you aren't in command line mode.
*
* #param String log message
*/
protected static function errorLog($msg) {
// disable error log if we are running in a CLI environment
// #codeCoverageIgnoreStart
if (php_sapi_name() != 'cli') {
error_log($msg);
}
// uncomment this if you want to see the errors on the page
// print 'error_log: '.$msg."\n";
// #codeCoverageIgnoreEnd
}
/**
* Base64 encoding that doesn't need to be urlencode()ed.
* Exactly the same as base64_encode except it uses
* - instead of +
* _ instead of /
*
* #param String base64UrlEncodeded string
*/
protected static function base64UrlDecode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
}
?>
How to migrate to OAuth 2.0 and how to solve this problems.

Update your SDK https://github.com/facebook/facebook-php-sdk/ and it will use the new endpoint.

Related

Cross-Origin Request (CORS) in ( Yii2 Framework + Ionic )

I'm trying to make some HTTP requests from my Ionic project to my Yii2 backend. But when I try to get data I'm getting the cross-origin issue, I don't know what to change in my Yii2 settings.
I've already tried to make a proxy for my request, and also make Cordova request but none of them worked, I think it's all about Yii2 settings.
Here is my filters/cors.php file in Yii2
class Cors extends ActionFilter
{
/**
* #var Request the current request. If not set, the `request` application component will be used.
*/
public $request;
/**
* #var Response the response to be sent. If not set, the `response` application component will be used.
*/
public $response;
/**
* #var array define specific CORS rules for specific actions
*/
public $actions = [];
/**
* #var array Basic headers handled for the CORS requests.
*/
public $cors = [
'Origin' => ['*'],
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
'Access-Control-Request-Headers' => ['*'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 86400
];
/**
* {#inheritdoc}
*/
public function beforeAction($action)
{
$this->request = $this->request ?: Yii::$app->getRequest();
$this->response = $this->response ?: Yii::$app->getResponse();
$this->overrideDefaultSettings($action);
$requestCorsHeaders = $this->extractHeaders();
$responseCorsHeaders = $this->prepareHeaders($requestCorsHeaders);
$this->addCorsHeaders($this->response, $responseCorsHeaders);
if ($this->request->isOptions && $this->request->headers->has('Access-Control-Request-Method')) {
// it is CORS preflight request, respond with 200 OK without further processing
$this->response->setStatusCode(200);
return false;
}
return true;
}
/**
* Override settings for specific action.
* #param \yii\base\Action $action the action settings to override
*/
public function overrideDefaultSettings($action)
{
if (isset($this->actions[$action->id])) {
$actionParams = $this->actions[$action->id];
$actionParamsKeys = array_keys($actionParams);
foreach ($this->cors as $headerField => $headerValue) {
if (in_array($headerField, $actionParamsKeys)) {
$this->cors[$headerField] = $actionParams[$headerField];
}
}
}
}
/**
* Extract CORS headers from the request.
* #return array CORS headers to handle
*/
public function extractHeaders()
{
$headers = [];
foreach (array_keys($this->cors) as $headerField) {
$serverField = $this->headerizeToPhp($headerField);
$headerData = isset($_SERVER[$serverField]) ? $_SERVER[$serverField] : null;
if ($headerData !== null) {
$headers[$headerField] = $headerData;
}
}
return $headers;
}
/**
* For each CORS headers create the specific response.
* #param array $requestHeaders CORS headers we have detected
* #return array CORS headers ready to be sent
*/
public function prepareHeaders($requestHeaders)
{
$responseHeaders = [];
// handle Origin
if (isset($requestHeaders['Origin'], $this->cors['Origin'])) {
if (in_array($requestHeaders['Origin'], $this->cors['Origin'], true)) {
$responseHeaders['Access-Control-Allow-Origin'] = $requestHeaders['Origin'];
}
if (in_array('*', $this->cors['Origin'], true)) {
// Per CORS standard (https://fetch.spec.whatwg.org), wildcard origins shouldn't be used together with credentials
if (isset($this->cors['Access-Control-Allow-Credentials']) && $this->cors['Access-Control-Allow-Credentials']) {
if (YII_DEBUG) {
throw new InvalidConfigException("Allowing credentials for wildcard origins is insecure. Please specify more restrictive origins or set 'credentials' to false in your CORS configuration.");
} else {
Yii::error("Allowing credentials for wildcard origins is insecure. Please specify more restrictive origins or set 'credentials' to false in your CORS configuration.", __METHOD__);
}
} else {
$responseHeaders['Access-Control-Allow-Origin'] = '*';
}
}
}
$this->prepareAllowHeaders('Headers', $requestHeaders, $responseHeaders);
if (isset($requestHeaders['Access-Control-Request-Method'])) {
$responseHeaders['Access-Control-Allow-Methods'] = implode(', ', $this->cors['Access-Control-Request-Method']);
}
if (isset($this->cors['Access-Control-Allow-Credentials'])) {
$responseHeaders['Access-Control-Allow-Credentials'] = $this->cors['Access-Control-Allow-Credentials'] ? 'true' : 'false';
}
if (isset($this->cors['Access-Control-Max-Age']) && $this->request->getIsOptions()) {
$responseHeaders['Access-Control-Max-Age'] = $this->cors['Access-Control-Max-Age'];
}
if (isset($this->cors['Access-Control-Expose-Headers'])) {
$responseHeaders['Access-Control-Expose-Headers'] = implode(', ', $this->cors['Access-Control-Expose-Headers']);
}
if (isset($this->cors['Access-Control-Allow-Headers'])) {
$responseHeaders['Access-Control-Allow-Headers'] = implode(', ', $this->cors['Access-Control-Allow-Headers']);
}
return $responseHeaders;
}
/**
* Handle classic CORS request to avoid duplicate code.
* #param string $type the kind of headers we would handle
* #param array $requestHeaders CORS headers request by client
* #param array $responseHeaders CORS response headers sent to the client
*/
protected function prepareAllowHeaders($type, $requestHeaders, &$responseHeaders)
{
$requestHeaderField = 'Access-Control-Request-' . $type;
$responseHeaderField = 'Access-Control-Allow-' . $type;
if (!isset($requestHeaders[$requestHeaderField], $this->cors[$requestHeaderField])) {
return;
}
if (in_array('*', $this->cors[$requestHeaderField])) {
$responseHeaders[$responseHeaderField] = $this->headerize($requestHeaders[$requestHeaderField]);
} else {
$requestedData = preg_split('/[\\s,]+/', $requestHeaders[$requestHeaderField], -1, PREG_SPLIT_NO_EMPTY);
$acceptedData = array_uintersect($requestedData, $this->cors[$requestHeaderField], 'strcasecmp');
if (!empty($acceptedData)) {
$responseHeaders[$responseHeaderField] = implode(', ', $acceptedData);
}
}
}
/**
* Adds the CORS headers to the response.
* #param Response $response
* #param array $headers CORS headers which have been computed
*/
public function addCorsHeaders($response, $headers)
{
if (empty($headers) === false) {
$responseHeaders = $response->getHeaders();
foreach ($headers as $field => $value) {
$responseHeaders->set($field, $value);
}
}
}
/**
* Convert any string (including php headers with HTTP prefix) to header format.
*
* Example:
* - X-PINGOTHER -> X-Pingother
* - X_PINGOTHER -> X-Pingother
* #param string $string string to convert
* #return string the result in "header" format
*/
protected function headerize($string)
{
$headers = preg_split('/[\\s,]+/', $string, -1, PREG_SPLIT_NO_EMPTY);
$headers = array_map(function ($element) {
return str_replace(' ', '-', ucwords(strtolower(str_replace(['_', '-'], [' ', ' '], $element))));
}, $headers);
return implode(', ', $headers);
}
/**
* Convert any string (including php headers with HTTP prefix) to header format.
*
* Example:
* - X-Pingother -> HTTP_X_PINGOTHER
* - X PINGOTHER -> HTTP_X_PINGOTHER
* #param string $string string to convert
* #return string the result in "php $_SERVER header" format
*/
protected function headerizeToPhp($string)
{
return 'HTTP_' . strtoupper(str_replace([' ', '-'], ['_', '_'], $string));
}
}
I expect to get the same JSON data in my Ionic app that I get when I enter the URL in the browser.
Use yii\filters\Cors
Yii offers a class that you can use directly. You can add it as a behavior directly in your controllers customizing the behaviors() method.
use yii\filters\Cors;
use yii\rest\Controller;
class MyController extends Controller // or ActiveController
{
// Customize the verbs as needed
private $_verbs = ['GET','POST','PATCH','PUT','DELETE'];
public function behaviors()
{
$behaviors = parent::behaviors();
// remove auth filter
unset($behaviors['authenticator']);
// add CORS filter
$behaviors['corsFilter'] = [
'class' => Cors::class,
'cors' => [
'Origin' => ['*'],
'Access-Control-Request-Method' => $this->_verbs,
'Access-Control-Allow-Headers' => ['content-type'],
'Access-Control-Request-Headers' => ['*'],
],
];
// re-add authentication filter
$behaviors['authenticator'] = [
'class' => HttpBearerAuth::class,
];
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
$behaviors['authenticator']['except'] = ['options'];
return $behaviors;
}
// Some other methods here if needed
/**
* Send the HTTP options available to this route
*/
public function actionOptions()
{
if (Yii::$app->getRequest()->getMethod() !== 'OPTIONS') {
Yii::$app->getResponse()->setStatusCode(405);
}
Yii::$app->getResponse()->getHeaders()->set('Allow', implode(', ', $this->_verbs));
}
}
Notice that, if you are using the authentication filter, it needs to be disabled before adding the cors filter, then reset. From the documentation:
Adding the Cross-Origin Resource Sharing filter to a controller is a bit more complicated than adding other filters described above, because the CORS filter has to be applied before authentication methods and thus needs a slightly different approach compared to other filters. Also authentication has to be disabled for the CORS Preflight requests so that a browser can safely determine whether a request can be made beforehand without the need for sending authentication credentials.
There is more info on the docs.
For other users. You may have an error in your code. Double-click on the OPTIONS request will open a new tab, and Yii will send you an error message.

Too many Redirects with Controller

When I try to define my routes with an ImagesController, I get a "site redirected you too many times" error when going to what should be the index. I'm stumped. Am I over-tired and not seeing something obvious?
web.php
Route::prefix('images')->group(function(){
Route::post('add-tag', 'ImagesController#addTag');
Route::get('test', 'ImagesController#index');
});
When I access /images/test, the controller responds correctly. When I have it defined as '' or / it redirects too much. I'm not setting them simultaneously.
Route::prefix('images')->group(function(){
Route::post('add-tag', 'ImagesController#addTag');
// like this:
Route::get('', 'ImagesController#index');
// or like the following:
Route::get('/', 'ImagesController#index');
});
I've even tried to define /images before the prefix group to no avail. images/test is fine in this case.
Route::get('images', 'ImagesController#index');
Route::prefix('images')->group(function(){
Route::post('add-tag', 'ImagesController#addTag');
Route::get('test', 'ImagesController#index');
});
ImagesController.php
namespace App\Http\Controllers;
use \Auth;
use App\Helpers;
use App\Image;
use App\Tag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Console\Helper\Helper;
class ImagesController extends Controller
{
private $sortBy = [
'created_at',
'updated_at',
'orig_name',
'orig_size'
];
private $defaultSortBy = 'created_at';
private $defaultOrder = 'desc';
/**
* #param Request $request
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index(Request $request)
{
$sort = $request->get('sort', $this->defaultSortBy);
$sort = in_array($sort, $this->sortBy) ? $sort : 'created_at';
$order = $request->get('order', $this->defaultOrder);
$order = $order == 'desc' ? 'desc' : 'asc';
$images = Image::orderBy($sort, $order)
->whereQuestionable(0)
->wherePrivate(0)
->paginate(config('image.images_per_page'));
if ($images !== null && $sort !== $this->defaultSortBy) {
$images->appends(['sort' => $sort]);
}
if ($images !== null && $order !== $this->defaultOrder) {
$images->appends(['order' => $order]);
}
return view(
'images.index',
[
'images' => $images,
'sort' => $sort,
'order' => $order
]
);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
//this function works correctly, but I suppose it may be interfering?
public function addTag(Request $request)
{
Log::debug(print_r($request->all(), true));
$error = '';
$uid = trim($request->input('uid', ''));
$newTag = Helpers::prepTag($request->input('tag', ''));
if (!Auth::check()){
$error .= 'You can only add tags to images if you are logged in.';
} else if ($uid === '' || $newTag === '') {
$error .= 'UID and tag cannot be empty';
} else {
$image = Image::whereUid($uid)->unQuestionable()->first();
$currentTags = [];
if (count($image->tags)){
foreach ($image->tags as $currentTag) {
$currentTags[$currentTag->id] = $currentTag->tag;
}
}
if ($image === null) {
$error .= "Image $uid was not found.";
} else {
$tag = Tag::firstOrNew(['tag'=>$newTag]);
if ($tag->ip == '') {
$tag->ip = $request->getClientIp();
$tag->user_id = Auth::check() ? Auth::user()->id : 5;
$tag->save();
}
//\Log::info(print_r($currentTags, true));
//\Log::info(print_r($tag, true));
$addTag = !(bool)isset($currentTags[$tag->id]);
$image->tags()->sync([$tag->id], false);
}
}
if ($request->ajax()) {
if ($error !== '') {
return response()->json(['message' => $error],400);
}
return response()->json(['tagId' => $tag->id, 'imageUid' => $image->uid, 'tag' => $tag->tag, 'isAdmin' => true, 'addTag' => $addTag]);
} else {
if ($error !== '') {
Helpers::alert(3, $error, 'Tag Not Added');
}
return redirect('/');
}
}
}
As I have a model named Images implicit binding was interfering with my defined routes for a controller with the name ImagesController, and applying the prefix /images. After changing the name in the routing to image this issue went away.

How can I get the TYPO3 "appearance" media images by using "ViewHelper"?

thanks for reading and answering...
I have some TYPO3 gridelements in my TYPO3 pagecontent.
Each gridelement has a tab "appearance", where I define an image file.
The database relation from tt_content to the media image are in sys_file_reference.
My question is how can I get this image file in my fluid template by using the ViewHelper and the uid of my gridelement?
I wrote an little ViewHelper (tested on 7.6, but should not need so much changes for 8.7) to get referenced images for an newsletter layout:
<?php
namespace Vendor\Extension\ViewHelpers;
use TYPO3\CMS\Core\Log\LogManager;
use TYPO3\CMS\Core\Resource\FileRepository;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Resource\FileReference;
use TYPO3\CMS\Core\Resource\Exception;
use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3\CMS\Fluid\Core\ViewHelper\Facets\CompilableInterface;
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
class ImagesReferencesViewHelper extends AbstractViewHelper implements CompilableInterface
{
/**
* Iterates through elements of $each and renders child nodes
*
* #param int $uid The ID of the element
* #param string $table The Referenced table name
* #param string $fieldName The Referenced field name
* #param string $as The name of the iteration variable
* #param string $key The name of the variable to store the current array key
* #param boolean $reverse If enabled, the iterator will start with the last element and proceed reversely
* #param string $iteration The name of the variable to store iteration information (index, cycle, isFirst, isLast, isEven, isOdd)
* #param string $link The name of the variable to store link
*
* #return string Rendered string
* #api
*/
public function render($uid, $table = 'tt_content', $fieldName = 'assets', $as, $key = '', $reverse = false, $iteration = null, $link = null)
{
return self::renderStatic($this->arguments, $this->buildRenderChildrenClosure(), $this->renderingContext);
}
/**
* #param array $arguments
* #param \Closure $renderChildrenClosure
* #param \TYPO3\CMS\Fluid\Core\Rendering\RenderingContextInterface $renderingContext
*
* #return string
* #throws \TYPO3\CMS\Fluid\Core\ViewHelper\Exception
*/
static public function renderStatic(array $arguments, \Closure $renderChildrenClosure, \TYPO3\CMS\Fluid\Core\Rendering\RenderingContextInterface $renderingContext)
{
$templateVariableContainer = $renderingContext->getTemplateVariableContainer();
if ($arguments['uid'] === null || $arguments['table'] === null || $arguments['fieldName'] === null) {
return '';
}
/** #var FileRepository $fileRepository */
$fileRepository = GeneralUtility::makeInstance(FileRepository::class);
$images = array();
try {
$images = $fileRepository->findByRelation($arguments['table'], $arguments['fieldName'], $arguments['uid']);
} catch (Exception $e) {
/** #var \TYPO3\CMS\Core\Log\Logger $logger */
$logger = GeneralUtility::makeInstance(LogManager::class)->getLogger();
$logger->warning('The file-reference with uid "' . $arguments['uid'] . '" could not be found and won\'t be included in frontend output');
}
if (is_object($images) && !$images instanceof \Traversable) {
throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception('ImagesReferencesViewHelper only supports arrays and objects implementing \Traversable interface', 1248728393);
}
if ($arguments['reverse'] === true) {
// array_reverse only supports arrays
if (is_object($images)) {
$images = iterator_to_array($images);
}
$images = array_reverse($images);
}
$iterationData = array(
'index' => 0,
'cycle' => 1,
'total' => count($images)
);
$output = '';
foreach ($images as $keyValue => $singleElement) {
$templateVariableContainer->add($arguments['as'], $singleElement);
/** #var FileReference $singleElement */
if ($arguments['link'] !== null && $singleElement->getLink()) {
$link = $singleElement->getLink();
/** #var ContentObjectRenderer $contentObject */
$contentObject = GeneralUtility::makeInstance(ContentObjectRenderer::class);
$newLink = $contentObject->typoLink_URL(array('parameter' => $link));
$templateVariableContainer->add($arguments['link'], $newLink);
}
if ($arguments['key'] !== '') {
$templateVariableContainer->add($arguments['key'], $keyValue);
}
if ($arguments['iteration'] !== null) {
$iterationData['isFirst'] = $iterationData['cycle'] === 1;
$iterationData['isLast'] = $iterationData['cycle'] === $iterationData['total'];
$iterationData['isEven'] = $iterationData['cycle'] % 2 === 0;
$iterationData['isOdd'] = !$iterationData['isEven'];
$templateVariableContainer->add($arguments['iteration'], $iterationData);
$iterationData['index']++;
$iterationData['cycle']++;
}
$output .= $renderChildrenClosure();
$templateVariableContainer->remove($arguments['as']);
if ($arguments['link'] !== null && $singleElement->getLink()) {
$templateVariableContainer->remove($arguments['link']);
}
if ($arguments['key'] !== '') {
$templateVariableContainer->remove($arguments['key']);
}
if ($arguments['iteration'] !== null) {
$templateVariableContainer->remove($arguments['iteration']);
}
}
return $output;
}
}

TYPO3 fe_user how login user via php code?

I have TYPO3 7.6.18 and extension femanager.
$GLOBALS['TSFE']->fe_user->checkPid = '';
$info = $GLOBALS['TSFE']->fe_user->getAuthInfoArray();
$user = $GLOBALS['TSFE']->fe_user->fetchUserRecord($info['db_user'], $username);
$loginData = array('uname' => $username, 'uident' => $password, 'status' => 'login');
$GLOBALS['TSFE']->fe_user->forceSetCookie = TRUE;
$GLOBALS['TSFE']->fe_user->createUserSession($user);
$GLOBALS['TSFE']->fe_user->user = $GLOBALS['TSFE']->fe_user->fetchUserSession();
$loginSuccess = $GLOBALS['TSFE']->fe_user->compareUident($user, $loginData);
this code does't work. error:
PHP Catchable Fatal Error: Argument 2 passed to In2code\Femanager\Utility\LogUtility::log() must be an instance of In2code\Femanager\Domain\Model\User, boolean given, called in /home/abenteuer/public_html/typo3conf/ext/feusersplus/Classes/Controller/NewController.php on line 91 and defined in /home/abenteuer/public_html/typo3conf/ext/femanager/Classes/Utility/LogUtility.php line 48
Is it hard code? May be exists better way ?
Do you know how login user via php code ?
For the $loginData['uname'] i use the email as username, you can simply change it with the username it self ($user->getUsername());
Class StandardLogin:
<?php
namespace Ads\Adsmanager\Authentication\Login;
/**
* Standard Login of users
*
* #author Andrei Todorut <todorutac#gmail.com>
*/
class StandardLogin extends \TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication implements LoginInterface
{
/**
*
* #param \Ads\Adsmanager\Domain\Model\User $user
* #return boolean
*/
public function login(\Ads\Adsmanager\Domain\Model\User $user)
{
$passwordProcessor = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Saltedpasswords\\Salt\\PhpassSalt');
$loginData = array(
'uname' => $user->getEmail(), //usernmae
'uident' => $user->getPassword(), //password
'status' => 'login'
);
$this->checkPid = false;
$info = $this->getAuthInfoArray();
$info['db_user']['username_column'] = 'email';
$user_db = $this->fetchUserRecord($info['db_user'], $loginData['uname']);
if ($user_db && $passwordProcessor->checkPassword($user->getPassword(), $user_db['password'])) {
$this->setSession($user_db);
return true;
}
return false;
}
private function setSession($user_db)
{
$GLOBALS['TSFE']->fe_user->createUserSession($user_db);
$GLOBALS['TSFE']->fe_user->user = $user_db;
$GLOBALS['TSFE']->fe_user->setKey('ses', 'fe_typo_user', $user_db);
}
}
Your action controller:
<?php
//...
//stuff
public function loginAction(\TYPO3\CMS\Extbase\Domain\Model\User $user)
{
$login = new StandardLogin();
$login->login($user);
}
//...
Call it with username as a parameter
function loginUser($username)
{
$GLOBALS['TSFE']->fe_user->checkPid = '';
$info = $GLOBALS['TSFE']->fe_user->getAuthInfoArray();
$user = $GLOBALS['TSFE']->fe_user->fetchUserRecord($info['db_user'], $username);
$loginData = array('uname' => $username, 'uident' => $user['password'], 'status' => 'login');
$GLOBALS['TSFE']->fe_user->forceSetCookie = TRUE;
$GLOBALS['TSFE']->fe_user->createUserSession($user);
$reflection = new \ReflectionClass($GLOBALS['TSFE']->fe_user);
$setSessionCookieMethod = $reflection->getMethod('setSessionCookie');
$setSessionCookieMethod->setAccessible(TRUE);
$setSessionCookieMethod->invoke($GLOBALS['TSFE']->fe_user);
$GLOBALS['TSFE']->fe_user->user = $GLOBALS['TSFE']->fe_user->fetchUserSession();
$session_data = $GLOBALS['TSFE']->fe_user->fetchUserSession();
$loginSuccess = $GLOBALS['TSFE']->fe_user->compareUident($user, $loginData);
setcookie('fe_typo_user', $session_data['ses_id'], time() + (86400 * 30), "/");
setcookie('nc_staticfilecache', 'fe_typo_user_logged_in', time() + (86400 * 30), "/");
}
Typo3 recently changed it's Cookie policy to not create a fe_typo_user by default (due to GDPR/DSGVO). The other solutions no longer work since they missed "start()".
The below function works as expected:
public function loginUser($username, $password)
{
$loginData = array(
'uname' => $username,
'uident_text' => $password,
'status' => 'login'
);
$GLOBALS['TSFE']->fe_user->checkPid = 0;
$info = $GLOBALS['TSFE']->fe_user->getAuthInfoArray();
$userAuth = $this->objectManager->get(FrontendUserAuthentication::class);
$user = $userAuth->fetchUserRecord($info['db_user'], $loginData['uname']);
if ($user) {
$userAuth->checkPid = false;
$isValidLoginData = $this->saltedPasswordService->compareUident($user, $loginData);
if (!$isValidLoginData) {
return false;
} else {
$GLOBALS['TSFE']->fe_user->forceSetCookie = TRUE;
$GLOBALS['TSFE']->fe_user->dontSetCookie = false;
$GLOBALS['TSFE']->fe_user->start();
$GLOBALS['TSFE']->fe_user->createUserSession($user);
$GLOBALS['TSFE']->fe_user->setAndSaveSessionData('dummy', TRUE);
$GLOBALS['TSFE']->fe_user->loginUser = 1;
return true;
}
} else {
return false;
}
}
It lacks serious status handling. If I improve it further it can be found here: https://gist.github.com/tserowski/8572c2314f7f909f31248a9ad0023509
Maybe you miss an $GLOBALS['TSFE']->fe_user->fetchGroupData(); and a $GLOBALS["TSFE"]->fe_user->storeSessionData(); to save the changes.
I have only an old (TYPO3 4.5) example, where it works:
$user = $GLOBALS['TSFE']->fe_user->getRawUserByName($username);
$GLOBALS['TSFE']->fe_user->createUserSession($user);
$GLOBALS["TSFE"]->fe_user->user = $GLOBALS["TSFE"]->fe_user->fetchUserSession();
$GLOBALS['TSFE']->fe_user->fetchGroupData();
$GLOBALS["TSFE"]->fe_user->setKey("ses", "do_redirect", 0);
$GLOBALS["TSFE"]->fe_user->storeSessionData();
Try this for size.
Works for TYPO3 V10.
/**
* User sign in.
*
* #param string $suppliedPassword - The just-supplied password
* #param string $storedPassword - The stored user password
* #param int $permanentLogin - Whether to log the user permanently.
* - Requires setting $GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] to 1
* in your ext_localconf file.
* - Optionally, set $GLOBALS['TYPO3_CONF_VARS']['FE']['lifetime'] to how long
* you want the permanent session to last.
* #param int $uid - The UID of the user you want to login.
* #param null|mixed $userSessionData - User's data you want to persist.
*/
public function logon(string $suppliedPassword, string $storedPassword, int $permanentLogin, int $uid, $userSessionData = NULL): void {
/**
* Password.
*/
if ($this->passwordIsAuthentic($suppliedPassword, $storedPassword)) {
#Log in user
$GLOBALS['TSFE']->fe_user->is_permanent = $permanentLogin;
$GLOBALS['TSFE']->fe_user->createUserSession(['uid' => $uid]);
if($userSessionData){
/**
* #tip You can change the key name '__USER__' to whatever you like.
*/
$GLOBALS['TSFE']->fe_user->setAndSaveSessionData('__USER__', $userSessionData);
}
$GLOBALS['TSFE']->fe_user->loginSessionStarted = 1;
$GLOBALS['TSFE']->fe_user->setSessionCookie();
/**
* #Note $GLOBALS['TSFE']->loginUser is deprecated in favor of
* $context->getPropertyFromAspect('frontend.user', 'isLoggedIn');
*/
}
}
/**
* Check password here
*
* #param string $suppliedPassword
* #param string $storedPassword
*
* #return bool
*/
private function passwordIsAuthentic(string $suppliedPassword, string $storedPassword): bool {
$saltFactory = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Crypto\PasswordHashing\PasswordHashFactory::class);
$invalidPasswordHashException = NULL;
try {
$hashInstance = $saltFactory->get($storedPassword, TYPO3_MODE);
if (($hashInstance instanceof \TYPO3\CMS\Core\Crypto\PasswordHashing\PasswordHashInterface) && $hashInstance->checkPassword($suppliedPassword, $storedPassword)) {
return TRUE;
}
} catch (\TYPO3\CMS\Core\Crypto\PasswordHashing\InvalidPasswordHashException $invalidPasswordHashException) {
// Get a hashed password instance for the hash stored in db of this user
return FALSE;
}
return FALSE;
}

MimeMailParser put message part together

i'm building a small interface that pipe messages from postfix via stdin, and want to remove attachments from email/ anyway, i don't want to remove all the attachments, just those who are too big to be emailed.
i found MimeMailParser as a good point of start and made a few modifications to it's code (made some private methods public, in order to call them seperatley). here is the class in my version:
<?php
require_once('attachment.class.php');
/**
* Fast Mime Mail parser Class using PHP's MailParse Extension
* #author gabe#fijiwebdesign.com
* #url http://www.fijiwebdesign.com/
* #license http://creativecommons.org/licenses/by-sa/3.0/us/
* #version $Id$
*/
class MimeMailParser {
/**
* PHP MimeParser Resource ID
*/
public $resource;
/**
* A file pointer to email
*/
public $stream;
/**
* A text of an email
*/
public $data;
/**
* Stream Resources for Attachments
*/
public $attachment_streams;
public $parts;
/**
* Inialize some stuff
* #return
*/
public function __construct() {
$this->attachment_streams = array();
}
/**
* Free the held resouces
* #return void
*/
public function __destruct() {
// clear the email file resource
if (is_resource($this->stream)) {
fclose($this->stream);
}
// clear the MailParse resource
if (is_resource($this->resource)) {
mailparse_msg_free($this->resource);
}
// remove attachment resources
foreach($this->attachment_streams as $stream) {
fclose($stream);
}
}
/**
* Set the file path we use to get the email text
* #return Object MimeMailParser Instance
* #param $mail_path Object
*/
public function setPath($path) {
// should parse message incrementally from file
$this->resource = mailparse_msg_parse_file($path);
$this->stream = fopen($path, 'r');
$this->parse();
return $this;
}
/**
* Set the Stream resource we use to get the email text
* #return Object MimeMailParser Instance
* #param $stream Resource
*/
public function setStream($stream) {
// streams have to be cached to file first
if (get_resource_type($stream) == 'stream') {
$tmp_fp = tmpfile();
if ($tmp_fp) {
while(!feof($stream)) {
fwrite($tmp_fp, fread($stream, 2028));
}
fseek($tmp_fp, 0);
$this->stream =& $tmp_fp;
} else {
throw new Exception('Could not create temporary files for attachments. Your tmp directory may be unwritable by PHP.');
return false;
}
fclose($stream);
} else {
$this->stream = $stream;
}
$this->resource = mailparse_msg_create();
// parses the message incrementally low memory usage but slower
while(!feof($this->stream)) {
mailparse_msg_parse($this->resource, fread($this->stream, 2082));
}
$this->parse();
return $this;
}
/**
* Set the email text
* #return Object MimeMailParser Instance
* #param $data String
*/
public function setText($data) {
$this->resource = mailparse_msg_create();
// does not parse incrementally, fast memory hog might explode
mailparse_msg_parse($this->resource, $data);
$this->data = $data;
$this->parse();
return $this;
}
/**
* Parse the Message into parts
* #return void
* #private
*/
private function parse() {
$structure = mailparse_msg_get_structure($this->resource);
$this->parts = array();
foreach($structure as $part_id) {
$part = mailparse_msg_get_part($this->resource, $part_id);
$this->parts[$part_id] = mailparse_msg_get_part_data($part);
}
}
/**
* Retrieve the Email Headers
* #return Array
*/
public function getHeaders() {
if (isset($this->parts[1])) {
return $this->getPartHeaders($this->parts[1]);
} else {
throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email headers.');
}
return false;
}
/**
* Retrieve the raw Email Headers
* #return string
*/
public function getHeadersRaw() {
if (isset($this->parts[1])) {
return $this->getPartHeaderRaw($this->parts[1]);
} else {
throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email headers.');
}
return false;
}
/**
* Retrieve a specific Email Header
* #return String
* #param $name String Header name
*/
public function getHeader($name) {
if (isset($this->parts[1])) {
$headers = $this->getPartHeaders($this->parts[1]);
if (isset($headers[$name])) {
return $headers[$name];
}
} else {
throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email headers.');
}
return false;
}
/**
* Returns the email message body in the specified format
* #return Mixed String Body or False if not found
* #param $type Object[optional]
*/
public function getMessageBody($type = 'text') {
$body = false;
$mime_types = array(
'text'=> 'text/plain',
'html'=> 'text/html'
);
if (in_array($type, array_keys($mime_types))) {
foreach($this->parts as $part) {
if ($this->getPartContentType($part) == $mime_types[$type]) {
$headers = $this->getPartHeaders($part);
$body = $this->getPartBody($part);
break;
}
}
} else {
throw new Exception('Invalid type specified for MimeMailParser::getMessageBody. "type" can either be text or html.');
}
return $body;
}
/**
* get the headers for the message body part.
* #return Array
* #param $type Object[optional]
*/
public function getMessageBodyHeaders($type = 'text') {
$headers = false;
$mime_types = array(
'text'=> 'text/plain',
'html'=> 'text/html'
);
if (in_array($type, array_keys($mime_types))) {
foreach($this->parts as $part) {
if ($this->getPartContentType($part) == $mime_types[$type]) {
$headers = $this->getPartHeaders($part);
break;
}
}
} else {
throw new Exception('Invalid type specified for MimeMailParser::getMessageBody. "type" can either be text or html.');
}
return $headers;
}
/**
* Returns inline content files.
* #return Array
*/
public function getInlineContent() {
$content = array();
foreach($this->parts as $part) {
$content_id = $this->getPartContentId($part);
if ($content_id !== FALSE) {
$content[] = new MimeMailParser_attachment(
$this->getPartContentName($part),
$this->getPartContentType($part),
$this->getAttachmentStream($part),
$this->getPartContentDisposition($part),
$this->getPartHeaders($part)
);
}
}
return $content;
}
/**
* Returns the attachments contents in order of appearance
* #return Array
* #param $type Object[optional]
*/
public function getAttachments() {
$attachments = array();
$dispositions = array("attachment","inline");
foreach($this->parts as $part) {
$disposition = $this->getPartContentDisposition($part);
if (in_array($disposition, $dispositions) === TRUE) {
if (isset($part['disposition-filename']) === FALSE) {
$part['disposition-filename'] = md5(uniqid());
}
$attachments[] = new MimeMailParser_attachment(
$part['disposition-filename'],
$this->getPartContentType($part),
$this->getAttachmentStream($part),
$disposition,
$this->getPartHeaders($part)
);
}
}
return $attachments;
}
/**
* Return the Headers for a MIME part
* #return Array
* #param $part Array
*/
private function getPartHeaders($part) {
if (isset($part['headers'])) {
return $part['headers'];
}
return false;
}
/**
* Return a Specific Header for a MIME part
* #return Array
* #param $part Array
* #param $header String Header Name
*/
private function getPartHeader($part, $header) {
if (isset($part['headers'][$header])) {
return $part['headers'][$header];
}
return false;
}
/**
* Return the ContentType of the MIME part
* #return String
* #param $part Array
*/
private function getPartContentType($part) {
if (isset($part['content-type'])) {
return $part['content-type'];
}
return false;
}
/**
* Return the ContentName of the MIME part
* #return String
* #param $part Array
*/
private function getPartContentName($part) {
if (isset($part['content-name'])) {
return $part['content-name'];
}
return false;
}
/**
* Return the Content Disposition
* #return String
* #param $part Array
*/
private function getPartContentDisposition($part) {
if (isset($part['content-disposition'])) {
return $part['content-disposition'];
}
return false;
}
/**
* Return the Content id
* #return String
* #param $part Array
*/
private function getPartContentId($part) {
if (isset($part['content-id'])) {
return $part['content-id'];
}
return false;
}
/**
* Retrieve the raw Header of a MIME part
* #return String
* #param $part Object
*/
private function getPartHeaderRaw(&$part) {
$header = '';
if ($this->stream) {
$header = $this->getPartHeaderFromFile($part);
} else if ($this->data) {
$header = $this->getPartHeaderFromText($part);
} else {
throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email parts.');
}
return $header;
}
/**
* Retrieve the Body of a MIME part
* #return String
* #param $part Object
*/
private function getPartBody(&$part) {
$body = '';
if ($this->stream) {
$body = $this->getPartBodyFromFile($part);
} else if ($this->data) {
$body = $this->getPartBodyFromText($part);
} else {
throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email parts.');
}
return $body;
}
/**
* Retrieve the Header from a MIME part from file
* #return String Mime Header Part
* #param $part Array
*/
private function getPartHeaderFromFile(&$part) {
$start = $part['starting-pos'];
$end = $part['starting-pos-body'];
fseek($this->stream, $start, SEEK_SET);
$header = fread($this->stream, $end-$start);
return $header;
}
/**
* Retrieve the Body from a MIME part from file
* #return String Mime Body Part
* #param $part Array
*/
private function getPartBodyFromFile(&$part) {
$start = $part['starting-pos-body'];
$end = $part['ending-pos-body'];
fseek($this->stream, $start, SEEK_SET);
$body = fread($this->stream, $end-$start);
return $body;
}
/**
* Retrieve the Header from a MIME part from text
* #return String Mime Header Part
* #param $part Array
*/
public function getPartHeaderFromText(&$part) {
$start = $part['starting-pos'];
$end = $part['starting-pos-body'];
$header = substr($this->data, $start, $end-$start);
return $header;
}
/**
* Retrieve the Body from a MIME part from text
* #return String Mime Body Part
* #param $part Array
*/
public function getPartBodyFromText(&$part) {
$start = $part['starting-pos-body'];
$end = $part['ending-pos-body'];
$body = substr($this->data, $start, $end-$start);
return $body;
}
/**
* Read the attachment Body and save temporary file resource
* #return String Mime Body Part
* #param $part Array
*/
private function getAttachmentStream(&$part) {
$temp_fp = tmpfile();
array_key_exists('content-transfer-encoding', $part['headers']) ? $encoding = $part['headers']['content-transfer-encoding'] : $encoding = '';
if ($temp_fp) {
if ($this->stream) {
$start = $part['starting-pos-body'];
$end = $part['ending-pos-body'];
fseek($this->stream, $start, SEEK_SET);
$len = $end-$start;
$written = 0;
$write = 2028;
$body = '';
while($written < $len) {
if (($written+$write < $len )) {
$write = $len - $written;
}
$part = fread($this->stream, $write);
fwrite($temp_fp, $this->decode($part, $encoding));
$written += $write;
}
} else if ($this->data) {
$attachment = $this->decode($this->getPartBodyFromText($part), $encoding);
fwrite($temp_fp, $attachment, strlen($attachment));
}
fseek($temp_fp, 0, SEEK_SET);
} else {
throw new Exception('Could not create temporary files for attachments. Your tmp directory may be unwritable by PHP.');
return false;
}
return $temp_fp;
}
/**
* Decode the string depending on encoding type.
* #return String the decoded string.
* #param $encodedString The string in its original encoded state.
* #param $encodingType The encoding type from the Content-Transfer-Encoding header of the part.
*/
public function decode($encodedString, $encodingType) {
if (strtolower($encodingType) == 'base64') {
return base64_decode($encodedString);
} else if (strtolower($encodingType) == 'quoted-printable') {
return quoted_printable_decode($encodedString);
} else {
return $encodedString;
}
}
}
?>
i call the code and use it as follows:
<?php
ini_set("display_errors","on");
error_reporting(E_ALL);
require_once('MimeMailParser.class.php');
$Parser = new MimeMailParser();
$Parser->setText(file_get_contents('php://stdin'));
$attachments = $Parser->getAttachments();
/*foreach($attachments as $attachment) {
echo $attachment->filename;
}*/
echo $Parser->getHeadersRaw(); # print email header
foreach ($Parser->parts as $xPart=>$yPart) {
if ($xPart=='1') {
continue;
}
echo $Parser->getPartHeaderFromText($yPart);
echo $Parser->getPartBodyFromText($yPart);
}
?>
that sends the message and all of the conetnts appears ok - beside one issue - attachments are not displayed. although, when i click "show original" the attachments as base64 encoded does appear on the message source.
any idea?