how to: use Tx_Extbase_Domain_Repository_FrontendUserRepository in typo3 v4.5 - typo3

I am trying to read the username of a front end user whose uid is known. I tried this in my controller's showAction method:
$objectManger = t3lib_div::makeInstance('Tx_Extbase_Object_ObjectManager');
// get repository
$repository = $objectManger->get('Tx_Extbase_Domain_Repository_FrontendUserRepository ');
$newObject = $repository->findByUid($coupon->getCreator()); //this is the uid of whoever was loggin in
print_r($newObject);
echo $newObject->getUsername(); die;
but when that code runs I get:
Oops, an error occured!
"Tx_Extbase_Domain_Repository_FrontendUserRepository " is not a valid cache entry identifier.
It turns out that $repository is empty, so how do I get fe_user data?
I am using typo3 v4.5 with extbase.
Thanks
Update to show complete answer.
This is the code (it goes in my CouponController) that worked (plus the typoscript mentioned):
/**
* #var Tx_Extbase_Domain_Repository_FrontendUserRepository
*/
protected $userRepository;
/**
* Inject the user repository
* #param Tx_Extbase_Domain_Repository_FrontendUserRepository $userRepository
* #return void */
public function injectFrontendUserRepository(Tx_Extbase_Domain_Repository_FrontendUserRepository $userRepository) {
$this->userRepository = $userRepository;
}
public function showAction(Tx_Coupons_Domain_Model_Coupon $coupon) {
$userRepository = $this->objectManager->get("Tx_Extbase_Domain_Repository_FrontendUserRepository");
$newObject = $userRepository->findByUid($coupon->getCreator());
$this->view->assign('coupon', $coupon);
$this->view->assign('creatorname', $newObject->getUsername() );
}

If you are using extbase yourself you dont have to call makeInstance for your objectManager, it's already there ($this->objectManager).
anyway, you should inject this repository (see my answer here: TYPO3 - Call another repository)
Clear the Cache after the Injection.
You maybe have to disable the recordtype extbase sets for its FrontendUser:
config.tx_extbase.persistence.classes.Tx_Extbase_Domain_Model_FrontendUser.mapping.recordType >

Set the source storage pid where the repository fetches the data from:
/** #var Tx_Extbase_Domain_Repository_FrontendUserRepository $repos */
$repos = $this->objectManager->get("Tx_Extbase_Domain_Repository_FrontendUserRepository");
$querySettings = $repos->createQuery()->getQuerySettings();
$querySettings->setStoragePageIds(array(123, 567));
$repos->setDefaultQuerySettings($querySettings);
$user = $repos->findByUid(56); // Queries for user 56 in storages 123 and 567

Related

Symfony 5: The server couldn't send a response: Ensure that the backend is working properly

I am trying to send a modification through Json to my project in Symfony 5, but I only get error responses, as if there is no Url, I have not inserted any API key or any header, I have searched for a guide but I cannot find it:
UserController.php
<?php
namespace App\Controller;
use App\Entity\User;
use App\Repository\UserRepository;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class UserController
{
private $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
/**
* #Route("/user/", name="add_user", methods={"POST"})
* #param Request $request
* #return JsonResponse
*/
public function add(Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
$firstName = $data['firstName'];
$lastName = $data['lastName'];
$email = $data['email'];
$phoneNumber = $data['phoneNumber'];
if (empty($firstName) || empty($lastName) || empty($email) || empty($phoneNumber)) {
throw new NotFoundHttpException('Expecting mandatory parameters!');
}
$this->userRepository->saveUser($firstName, $lastName, $email, $phoneNumber);
return new JsonResponse(['status' => 'User created!'], Response::HTTP_CREATED);
}
UserRepository.php:
public function saveUser($firstName, $lastName, $email, $phoneNumber)
{
$newUser = new User();
$newUser
->setFirstName($firstName)
->setLastName($lastName)
->setEmail($email)
->setPhoneNumber($phoneNumber);
$this->manager->persist($newUser);
$this->manager->flush();
}
As for the GET, I have done it correctly and I get an answer with the data.
Your path looks wrong. On the controller action you define the route as:
/**
* #Route("/user/", name="add_user", methods={"POST"})
* #param Request $request
* #return JsonResponse
*/
The add_user is just the internal route name. The url in postman should probably be:
https://127.0.0.1:8000/user/
Additionally, since you did not get any response, so not even a 404 not found, I assume you do not have a web server running right now. If you use the Symfony CLI-tool you can call the command: symfony serve in your project directory to get the web server running. Closing the terminal window or restarting your computer will stop the web server.

trying to do email confirmation after user registration and getting error "Class 'App\Http\Middleware\Auth' not found

Here is my VerifyUserbyEmail custom middle-ware
Can any one please help to sort it out ?
while I have used namespace properly but still getting error
<?php
namespace App\Http\Middleware;
use App\Http\Middleware\Auth;
use Closure;
class VerifyUserbyEmail
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = \App\User::findOrFail(Auth::id());
if ($user->status == 0){
Auth::logout();
return redirect('login')->with('messege', 'you need to verify your account, check your email');
}
return $next($request);
}
}
Try changing
use App\Http\Middleware\Auth;
with
use Illuminate\Support\Facades\Auth;

How to define redirect page for protected pages

In a TYPO3 6.1 site, I would like to make the creation of restricted (fe_groups) pages as easy as possible for editors. There's not one single protected area, but several protected pages all over the pagetree.
What I would like to achieve would be that whenever a page has some login behaviour/restriction and no valid fe_user is logged in, there is a redirection to a central login page.
I have found this post
TYPO3 - Redirecting to login page when user is not logged in that refers to the same issue - but the solution requires setting PIDs by hand.
I can hardly believe that such a feature ("set target page for redirections based on access restrictions") is not available. Or does it exist, or is it on a roadmap somewhere? And if not, is there a workaround?
This is indeed a big missing feature in TYPO3. The problem is that because of the way TYPO3 is built it's hard to determine whether a page doesn't exist (404) or access is forbidden (403). I did some further development of an unpublished extension that does the job, see https://github.com/phluzern/adfc_pagenotfound
In readme.txt you will find the configuration that is needed. It is in use with TYPO3 4.7, therefore some used classes may be deprecated or removed in 6.1. If so, fork the project, change them and make some pull requests so I can update it.
The extension makes use of a custom parameter $arPid (access restriction pid). The ID to the page that is access restricted is sent to the login page. Your login form must be able to handle this parameter in order to redirect, see an example here:
https://github.com/phluzern/phzldap/blob/master/pi1/class.tx_phzldap_pi1.php#L133
It might be better to use a redirect_url as it is supported in felogin.
Update
In the meantime, I'm using an improved class with the following features:
If access to page is forbidden, redirect to a login page with the standard redirect_url parameter. This allows a redirect after a successful fe login using EXT:felogin without modifications and also supports speaking URLs.
Redirect to 404 page if page is not found respecting the current language of the site.
The code is as follows:
<?php
use TYPO3\CMS\Core\Utility\GeneralUtility;
class user_pageNotFound {
/**
* Detect language and redirect to 404 error page
*
* #param array $params "currentUrl", "reasonText" and "pageAccessFailureReasons"
* #param \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController $tsfeObj
*/
public function pageNotFound($params, $tsfeObj) {
/*
* If a non-existing page with a RealURL path was requested (www.mydomain.tld/foobar), a fe_group value for an empty
* key is set:
* $params['pageAccessFailureReasons']['fe_group'][null] = 0;
* This is the reason why the second check was implemented.
*/
if (!empty($params['pageAccessFailureReasons']['fe_group']) && !array_key_exists(null, $params['pageAccessFailureReasons']['fe_group'])) {
// page access failed because of missing permissions
header('HTTP/1.0 403 Forbidden');
$this->initTSFE(1);
/** #var \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer $cObj */
$cObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\ContentObject\\ContentObjectRenderer');
$loginUrl = $cObj->typoLink_URL(array(
'parameter' => $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_loginPageID'],
'useCacheHash' => FALSE,
'forceAbsoluteUrl' => TRUE,
'additionalParams' => '&redirect_url=' . $params['currentUrl']
));
TYPO3\CMS\Core\Utility\HttpUtility::redirect($loginUrl);
} else {
// page not found
// get first realurl configuration array (important for multidomain)
$realurlConf = array_shift($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']);
// look for language configuration
foreach ($realurlConf['preVars'] as $conf) {
if ($conf['GETvar'] == 'L') {
foreach ($conf['valueMap'] as $k => $v) {
// if the key is empty (e.g. default language without prefix), break
if (empty($k)) {
continue;
}
// we expect a part like "/de/" in requested url
if (GeneralUtility::isFirstPartOfStr($params['currentUrl'], '/' . $k . '/')) {
$tsfeObj->pageErrorHandler('/index.php?id=' . $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_redirectPageID'] . '&L=' . $v);
}
}
}
}
// handle default language
$tsfeObj->pageErrorHandler('/index.php?id=' . $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_redirectPageID']);
}
}
/**
* Initializes a TypoScript Frontend necessary for using TypoScript and TypoLink functions
*
* #param int $id
* #param int $typeNum
*/
protected function initTSFE($id = 1, $typeNum = 0) {
\TYPO3\CMS\Frontend\Utility\EidUtility::initTCA();
if (!is_object($GLOBALS['TT'])) {
$GLOBALS['TT'] = new \TYPO3\CMS\Core\TimeTracker\NullTimeTracker;
$GLOBALS['TT']->start();
}
$GLOBALS['TSFE'] = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Controller\\TypoScriptFrontendController', $GLOBALS['TYPO3_CONF_VARS'], $id, $typeNum);
$GLOBALS['TSFE']->sys_page = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
$GLOBALS['TSFE']->sys_page->init(TRUE);
$GLOBALS['TSFE']->connectToDB();
$GLOBALS['TSFE']->initFEuser();
$GLOBALS['TSFE']->determineId();
$GLOBALS['TSFE']->initTemplate();
$GLOBALS['TSFE']->rootLine = $GLOBALS['TSFE']->sys_page->getRootLine($id, '');
$GLOBALS['TSFE']->getConfigArray();
if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('realurl')) {
$rootline = \TYPO3\CMS\Backend\Utility\BackendUtility::BEgetRootLine($id);
$host = \TYPO3\CMS\Backend\Utility\BackendUtility::firstDomainRecord($rootline);
$_SERVER['HTTP_HOST'] = $host;
}
}
}
The only thing you need to configure are the PIDs of the page not found and login pages:
// ID of the page to redirect to if page was not found
$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_redirectPageID'] = 4690;
// ID of the page to redirect to if current page is access protected
$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_loginPageID'] = 5404;

Zend Enable SQL Query logging

I am using this to retrieve the database connection atm.
$db = Zend_Db_Table::getDefaultAdapter();
I do set this up in my config like this:
resources.db.adapter = pdo_mysql
resources.db.isDefaultTableAdapter = true
resources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password = password
resources.db.params.dbname = db
resources.db.params.profiler.enabled = true
resources.db.params.profiler.class = Zend_Db_Profiler
I would like to output everything to a sql.log for example. Is this possible to apply on the default adapter? for example through the settings, so I can ignore it in production environment?
Much appriciated.
I did look at: How to enable SQL output to log file with Zend_Db? but it didn't seem to cover my issue.
/Marcus
There is an example of extending Zend_Db_Profiler so you can write the queries to /logs/db-queries.log file.
So you have to do the following:
Create My_Db_Profiler_Log class in the library folder
Add the following lines to the application.ini
resources.db.params.profiler.enabled = true
resources.db.params.profiler.class = My_Db_Profiler_Log
Note: be aware, that the log file will become very big, very soon! So it is a good idea to log only the queries you are interested in. And this example should be considered only as a starting point in implementation of such a logging system.
Here is the code for the custom profiler class:
<?php
class My_Db_Profiler_Log extends Zend_Db_Profiler {
/**
* Zend_Log instance
* #var Zend_Log
*/
protected $_log;
/**
* counter of the total elapsed time
* #var double
*/
protected $_totalElapsedTime;
public function __construct($enabled = false) {
parent::__construct($enabled);
$this->_log = new Zend_Log();
$writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/logs/db-queries.log');
$this->_log->addWriter($writer);
}
/**
* Intercept the query end and log the profiling data.
*
* #param integer $queryId
* #throws Zend_Db_Profiler_Exception
* #return void
*/
public function queryEnd($queryId) {
$state = parent::queryEnd($queryId);
if (!$this->getEnabled() || $state == self::IGNORED) {
return;
}
// get profile of the current query
$profile = $this->getQueryProfile($queryId);
// update totalElapsedTime counter
$this->_totalElapsedTime += $profile->getElapsedSecs();
// create the message to be logged
$message = "\r\nElapsed Secs: " . round($profile->getElapsedSecs(), 5) . "\r\n";
$message .= "Query: " . $profile->getQuery() . "\r\n";
// log the message as INFO message
$this->_log->info($message);
}
}
?>
Extend the Zend_Db_Profiler to write to an SQL.log and attach the profiler to your db adapter
<?php
class File_Profiler extends Zend_Db_Profiler {
/**
* The filename to save the queries
*
* #var string
*/
protected $_filename;
/**
* The file handle
*
* #var resource
*/
protected $_handle = null;
/**
* Class constructor
*
* #param string $filename
*/
public function __construct( $filename ) {
$this->_filename = $filename;
}
/**
* Change the profiler status. If the profiler is not enabled no
* query will be written to the destination file
*
* #param boolean $enabled
*/
public function setEnabled( $enabled ) {
parent::setEnabled($enabled);
if( $this->getEnabled() ) {
if( !$this->_handle ) {
if( !($this->_handle = #fopen($this->_filename, "a")) ) {
throw new Exception("Unable to open filename {$this->_filename} for query profiling");
}
}
}
else {
if( $this->_handle ) {
#fclose($this->_handle);
}
}
}
/**
* Intercept parent::queryEnd to catch the query and write it to a file
*
* #param int $queryId
*/
public function queryEnd($queryId) {
$state = parent::queryEnd($queryId);
if(!$this->getEnabled() || $state == self::IGNORED) {
return;
}
$profile = $this->getQueryProfile($queryId);
#fwrite($this->_handle, round($profile->getElapsedSecs(),5) . " " . $profile->getQuery() . " " . ($params=$profile->getQueryParams())?$params:null);
}
}
Haven't test it, but it should do the trick. Give it a try and let me know.
Btw you do know that you can log all queries on the mysql as well?
this will let you see sql queries to the web page , IT MIGHT BE OFF TOPIC but it helpful
I am highly recommend you to use ZF debug bar , it will give you very handy information
i am using it to see my doctrine queries , and it had support for zend db too
https://github.com/jokkedk/ZFDebug

how to build query string in zend framework?

I'm trying to build a query string as following:
Next Page
I want to add an array to query string. For example, array('find_loc'=>'New+York', 'find_name'=>'starbucks')
I expect to get url that looks like http://example.com/1/?find_loc=New+York&find_name=starbucks
What's the best way to do this? I found a similar question that suggested appending the string to the url. Is there a helper for query string?
Simple answer to your question is no.
Here is the class description:
/**
* Helper for making easy links and getting urls that depend on the routes and router
*
* #package Zend_View
* #subpackage Helper
* #copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* #license http://framework.zend.com/license/new-bsd New BSD License
*/
Helper for making easy links and getting urls that depend on the routes and router
I think the description is clear in it's purpose. Use it for making URLs that depend on the routes and router. So, just append your query strings as recommend in the link you posted in your question.
The following should work for you:
Next Page
The ZF-Router will map the values to the Request object.
In your controller you can access these params with the Response-Object:
$loc = $this->getRequest()->getParam('find_loc');
$name = $this->getRequest()->getParam('find_name);
You can make custom helper:
class My_View_Helper_UrlHttpQuery extends Zend_View_Helper_Abstract
{
public function urlHttpQuery($query)
{
$urlHelper = $this->view->getHelper('url');
$params = func_get_args();
array_shift($params);//removing first argument
$url = call_user_func_array(($urlHelper, 'url'), $params);
if(!is_string($query)) { //allow raw query string
$query = array($query);
$query = http_build_query($query);
}
if(!empty($query) {
$url .= '?' . ltrim('?', $query);
}
return $url;
}
}
After you register this helper with view, you can use it like this Next Page
Working code
/**
* Class Wp_View_Helper_UrlHttpQuery
*/
class Wp_View_Helper_UrlHttpQuery extends Zend_View_Helper_Abstract
{
public function urlHttpQuery($query = array())
{
$urlHelper = $this->view->getHelper('url');
$params = func_get_args();
//removing first argument
array_shift($params);
$url = call_user_func_array(array($urlHelper, 'url'), $params);
if (is_array($query) || is_object($query)) {
$query = http_build_query($query);
}
if (!empty($query)) {
$url .= '?' . ltrim($query, '?');
}
return $url;
}
}
since the upstream code doesn't work