• 0

PHP Function, Pass Empty $username Value


Question

On Symfony's Friends of Symfony User Bundle, I managed to modify a profile action that allows me to view specific user profiles instead of only seeing my own. I basically took the Group Controller's function, and made some code useable for the User Controller, as the Group Controller allows you to view the group, using the name in the URL; now in the User Controller, where profile/ becomes profile/mrxxiv. I'm trying to keep profile/ as well, but the way I have the function set up, it's almost impossible due to Symfony giving me an error, telling me about the empty value in the function, where I'd need to enter a username in order to find & view the user's data.

This is the error when not entering a username in the URL:

Controller "FOS\UserBundle\Controller\ProfileController::showAction()" requires that you provide a value for the "$username" argument (because there is no default value or because there is a non optional argument after this one).

I don't want to enter a default value, I just want to find a way to pass the parameter when it's empty as when I use only the url profile/, I can view my own profile data on the spot. Plus I can't be specific against all users. Disregard the IF statement by the way.

public function showAction($username) {
	$user = $this->container->get('security.context')->getToken()->getUser();

	if (!is_object($user) || !$user instanceof UserInterface) {
			throw new AccessDeniedException('This user does not have access to this section.');
	}

	$user = $this->findUserBy('username', $username);
	return $this->container->get('templating')->renderResponse('FOSUserBundle:Profile:show.html.'.$this->container->getParameter('fos_user.template.engine'), array('user' => $user));
}

14 answers to this question

Recommended Posts

  • 0

On Symfony's Friends of Symfony User Bundle, I managed to modify a profile action that allows me to view specific user profiles instead of only seeing my own. I basically took the Group Controller's function, and made some code useable for the User Controller, as the Group Controller allows you to view the group, using the name in the URL; now in the User Controller, where profile/ becomes profile/mrxxiv. I'm trying to keep profile/ as well, but the way I have the function set up, it's almost impossible due to Symfony giving me an error, telling me about the empty value in the function, where I'd need to enter a username in order to find & view the user's data.

This is the error when not entering a username in the URL:

Controller "FOS\UserBundle\Controller\ProfileController::showAction()" requires that you provide a value for the "$username" argument (because there is no default value or because there is a non optional argument after this one).

I don't want to enter a default value, I just want to find a way to pass the parameter when it's empty as when I use only the url profile/, I can view my own profile data on the spot. Plus I can't be specific against all users. Disregard the IF statement by the way.

public function showAction($username) {
	$user = $this->container->get('security.context')->getToken()->getUser();

	if (!is_object($user) || !$user instanceof UserInterface) {
			throw new AccessDeniedException('This user does not have access to this section.');
	}

	$user = $this->findUserBy('username', $username);
	return $this->container->get('templating')->renderResponse('FOSUserBundle:Profile:show.html.'.$this->container->getParameter('fos_user.template.engine'), array('user' => $user));
}

I'm not familiar with Symfony, but you should be able to assign a 'default' value (I know you said you didn't want to assign a default but this is sort of different?) when the function is defined:

public function showAction($username='') {

That way, if nothing is passed to the function, it assigns an empty value.

  • 0

Your question makes no sense, if there's no username provided, don't run the function.

Obviously you can't get a profile for a user that doesn't exist.

EDIT: If what I think you mean is you want to access profiles via /<username> instead of /index.php?user=<username> then you've got 3 methods of doing it.

1) Use apache rewrites to rewrite the URL.

2) Modify the symfony function above which means you've forked symphony - congratulations if you upgrade you'll break it and if you don't upgrade you'll be stuck with all future security flaws

3) Make your own functions to do all the calling... Which as said in the other thread is why it's MUCH easier and better to create your own code from scratch rather than using a framework that you've no clue about, you could be going back and forth between many many functions looking for how things happen like why the function is being called twice.

Edited by n_K
  • 0

Your question makes no sense, if there's no username provided, don't run the function.

Obviously you can't get a profile for a user that doesn't exist.

There are 2 users in the database. Where I go to both /profile/mrxxiv and /profile/mrsxxiv. Originally, it only set up /profile to where I can just see my profile, but I wanted to extend that user feature to allow users to see each other's profiles.

I'm not sure how to prevent that function, because that is a controller that renders the page. Remember, this is an MVC Framework, I practically have no choice at the moment because this is how all the other controllers run.

I'm basically asking for help on how to keep a variable ignored, if the value is empty. This has nothing to do with existence.

  • 0

In that case it's passing the argument via another function, as I said you'll need to go through and find how and where the function is being called and rewrite it which means you've forked it *wrong buzzer noise*

Keep a value ignored?

if (!is_null($Username))

{

//Insert all the above function here

}

Edited by n_K
  • 0

In that case it's passing the argument via another function, as I said you'll need to go through and find how and where the function is being called and rewrite it which means you've forked it *wrong buzzer noise*

I've already done a rewrite to use app.php (the index) as the base of the URL, as the site already uses the Address as subdirectories, not query's and variables.

I'm not sure passing another will work because the function right there that renders the page basically works with the router for the GET function.

You've used Symfony before right? :/

  • 0

No, I don't bother with frameworks, and I don't need to in order to see that the error is coming from a file that is part of the framework. Modify any of the framework files = fork, the idea of the framework is you use the functions of the framework without modifying the framework itself.

Yes it uses other functions to get and process the username, get out grep and look for what other files call that function, then comment them out one by one until you find the function you need to change.

  • 0

I'm basically asking for help on how to keep a variable ignored, if the value is empty. This has nothing to do with existence.

Doesn't my way essentially do that? And then do this if need be:

if($username != '')

$user = $this-&gt;findUserBy('username', $username);

  • 0

I don't think he's asking about that, he's saying that it always gets the profile of the logged in user and he wants it to get the profile of the user in the URL.

I already get the other users profiles using the username in the URL, but using this function will pass an error for an empty value when only using /profile. Like so.

post-388684-0-03413100-1357266911.png

post-388684-0-45501000-1357266917.png

  • 0

WAIT!

This is what's throwing the exception.

protected function findUserBy($key, $value)
    {
        if (!empty($value)) {
            $user = $this-&gt;container-&gt;get('fos_user.user_manager')-&gt;{'findUserBy'.ucfirst($key)}($value);
        }

        if (empty($user)) {
            throw new NotFoundHttpException(sprintf('The user with "%s" does not exist for value "%s"', $key, $value));
        }

        return $user;
    }

  • 0

Are you using this function to get the profile then?? If so, return out of the function if you aren't using it:


public function showAction($username='') {
if($username == '')
return;
		$user = $this-&gt;container-&gt;get('security.context')-&gt;getToken()-&gt;getUser();

		if (!is_object($user) || !$user instanceof UserInterface) {
						throw new AccessDeniedException('This user does not have access to this section.');
		}

		$user = $this-&gt;findUserBy('username', $username);
		return $this-&gt;container-&gt;get('templating')-&gt;renderResponse('FOSUserBundle:Profile:show.html.'.$this-&gt;container-&gt;getParameter('fos_user.template.engine'), array('user' =&gt; $user));
}

Edit:

If thats throwing the exception, skip it like posted a couple posts above?

  • 0

So you want it to get the profile of the logged in user when no profile is given?

if (is_null($Username))

{

GLOBAL $x;

$Username = $x;

}

$x being the variable that holds the logged in username, if it's a session variable you can remove the GLOBAL line.

  • 0

Are you using this function to get the profile then?? If so, return out of the function if you aren't using it:

Edit:

If thats throwing the exception, skip it like posted a couple posts above?

So you want it to get the profile of the logged in user when no profile is given?

if (is_null($Username))

{

GLOBAL $x;

$Username = $x;

}

$x being the variable that holds the logged in username, if it's a session variable you can remove the GLOBAL line.

The function "findUserBy" is the function that searches for the user, it's right under the showAction function. There's already if(empty) exception there, but even if I modify it. I can't get the logged in user info as another exception from the showAction will appear, thus into a paradox (ahh hell).

EDIT:

Let me try, using 2 different functions, since this is a controller working with a router. I'll try to render profile/ and profile/{user} from 2 different public functions.

EDIT #2:

Really appreciate your help guys. I used 2 different functions as said by also using the router to modify what function I want to use.

XML Router:

    &lt;route id="fos_user_profile_show" pattern="/"&gt;
        &lt;default key="_controller"&gt;FOSUserBundle:Profile:main&lt;/default&gt;
        &lt;requirement key="_method"&gt;GET&lt;/requirement&gt;
    &lt;/route&gt;

&lt;route id="fos_other_user_profile_show" pattern="/{username}"&gt;
        &lt;default key="_controller"&gt;FOSUserBundle:Profile:show&lt;/default&gt;
        &lt;requirement key="_method"&gt;GET&lt;/requirement&gt;
    &lt;/route&gt;

Controller:


    /**
     * Show the main user
     */
    public function mainAction()
    {
        $user = $this-&gt;container-&gt;get('security.context')-&gt;getToken()-&gt;getUser();

if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        return $this-&gt;container-&gt;get('templating')-&gt;renderResponse('FOSUserBundle:Profile:show.html.'.$this-&gt;container-&gt;getParameter('fos_user.template.engine'), array('user' =&gt; $user));
    }


    /**
     * Show the user
     */
    public function showAction($username)
    {
        $user = $this-&gt;container-&gt;get('security.context')-&gt;getToken()-&gt;getUser();

$user = $this-&gt;findUserBy('username', $username);

if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        return $this-&gt;container-&gt;get('templating')-&gt;renderResponse('FOSUserBundle:Profile:show.html.'.$this-&gt;container-&gt;getParameter('fos_user.template.engine'), array('user' =&gt; $user));
    }

Edited by Mr.XXIV
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • UK nudity blockers are a looming privacy disaster, we must be able to see the source code by Paul Hill Image via Pexels The UK government, just like many state governments in the US and national governments around the world, has begun going on a bit of a power trip when it comes to digital safety. The major step taken so far is the introduction of the Online Safety Act, which requires users to prove their age to access adult websites (it includes more than this, too). Now, UK PM Keir Starmer is calling on Apple and Google, and presumably other mobile OS makers, to scan phones for explicit images to protect children. This potentially mandatory on-device scanning by vendor-controlled software will create unacceptable harms to individual freedoms and transparency, and introduce massive surveillance risks. In a statement on June 8, the Prime Minister stated that big tech companies, such as Apple and Google, must add features to their platforms, such as iOS and Android, that will detect and block sexually explicit or nude images involving under-18s on phones or tablets. Adults who want to take or send nudes would be required to hand over some form of identification to stop their phone from blocking these pictures, creating unnecessary privacy risks. According to the government, it wants to see these measures implemented within three months; otherwise, the government will introduce legislation to force them to introduce such technology. The legislation will include fines for companies and maybe even criminal liability for tech bosses who do not comply with the measures. In its announcement, the government said that stopping users from taking, sending, or receiving nudes without verifying their age is technically feasible, and pointed to a British firm called SafeToNet, which has made proprietary, closed-source, uninstallable software called HarmBlock and is actively selling a device with it enabled and is working with other OEMs. The fact that this software is closed source is a huge problem because it’s a black box; you do not know what it is doing on your device. The fact that it is unremovable is also a problem because you lose control of a phone that you own. Laughably, the government, just before highlighting SafeToNet, says that companies must introduce such measures “without threatening privacy or collecting any data.” It then says over-18s will still be able to view adult content by providing proof of age… Which sounds to me like data collection. SafeToNet makes some debatable claims about HarmBlock The government’s example software, HarmBlock, is a hugely alarming choice to espouse the virtues of this type of software. SafeToNet claims that HarmBlock is “ethically developed,” but this is the opposite of the truth. This black box software puts digital handcuffs on you if it’s installed in your device, taking away your freedom to control what software runs on your device, as it cannot be removed. It is not even free software, so we cannot inspect the source code to see what it is doing. For all we know, it could be acting maliciously. While that’s unlikely, we can’t verify that it’s not doing that. When Google and Apple do inevitably integrate these features on devices in the UK, they are very likely to be closed-source binaries, which will also be non-auditable. They will also have identity services built into them, which will require at least temporary collection of sensitive identity documents to verify your age. One saving grace for Android users is that this nudity blocker will very likely be implemented within the Google Play infrastructure that’s deeply tied into commercial Android devices. However, anyone with enough determination to throw out Google apps from their phone by flashing a custom ROM could find they regain control over their phone again without these digital handcuffs. Obviously, this is only how I expect Google to implement the feature; if it bakes it into the open-source Android somehow, that would be bad news for anyone looking to escape it. Outside of stripping mobile phone users of their freedom and sovereignty over their devices, these proprietary on-device machine learning or hash-matching solutions cannot be independently audited. This means that hackers could potentially exploit them because security researchers can’t investigate the code, and they could overstep their intended use case and collect even more user data without anybody knowing. We also wouldn’t know if the code is prone to detecting false positives or biased classification, because we can’t see the code. In the government’s announcement, contributing comments from the Internet Watch Foundation keep talking about “on-device protections” as if to say that users don’t need to worry about server-side processing; however, this is misleading, as data could flow from devices for the purpose of updates, remote model changes, telemetry, or server-side matching. We’ve also seen with the Online Safety Act that the government is never content with the laws it introduces; it always wants to expand the controls. If this scanning functionality arrives on devices, it might only block nudes initially, but later governments could pressure vendors for expanded access or use mandated features for other surveillance aims. The introduction of on-device scanners opens the door to massive risks in the future. Once nude blocking becomes normalized, regulators like Ofcom or politicians themselves could push for more controls over people’s devices. Very possible candidates for blocking include hate speech, misinformation, or undesirable political content. Also, there is a chance that once Apple and Google have developed this software, they might attempt to reuse the infrastructure for commercial or foreign requests, putting customers in greater danger. Just the UK's demand for this sets a precedent. What if a dictatorship decides to spy on activists by demanding that Google or Apple implement similar controls? Another concern with this scanning is that it adds compliance costs for businesses looking to get into the mobile operating system space. While Google and Apple dominate the space right now, there are lots of smaller companies creating mobile operating systems too, including community projects with very shallow pockets. How are these smaller competitors supposed to implement sophisticated nudity detectors? Simply put, they can’t. Then the government goes after them, causes them to shut down, and Google and Apple have less competition. Image via Aurora Store For us users who value sovereignty over our technology, this development will force us to seek freedom-respecting alternatives. The simplest path forward will likely be to install a custom ROM on an Android device; however, kicking Google off the phone with its black box nudity blocker could also make it harder to access apps such as banking apps, which tend to need you to pass Google's integrity checks. Thankfully, Google Play Store apps can still be obtained by storefronts such as the Aurora Store, but it just adds to the friction. To be fair to those pushing this measure to protect children, I think it will be reasonably effective, but people will still try to find ways around it, just as they’ve done with age gates on adult websites introduced under the Online Safety Act. In the effort to find circumvention methods, it could lead users to join riskier platforms that introduce new dangers. This effort also diverts resources from proven interventions such as law enforcement cooperation, targeted investigations, education, and support services to broad technical controls that have uncertain effectiveness (due to their newness). If the government is set on introducing such tools, then there ought to be safeguards in place. Any mandated code should be released as free software so that it can be audited, and the binaries should be reproducible builds so that the public knows nothing has been tampered with in the code used to create the binaries shipped out. Ideally, these tools should also be voluntary, opt-in, and even community-run. This would also allow people to have full control over their hardware while allowing parents to flip a switch to turn on these protections for children, with the knowledge that the code being run is doing exactly what it says on the tin, and nothing nefarious, like a black box solution could be doing. The government should also have a narrow legal scope where this technology stays with blocking nudes and not spreading to blocking political opinions, hate speech, and so on. Ideally, any implementation should avoid identity-linked age verification to keep user data safe, and matching should be done locally with no server telemetry to ensure it is truly on-device. While I do understand that stakeholders such as parents want to keep children safe, the potential for abuse with this type of software is colossal. It would entrench black-box surveillance and take away our freedom to use our devices as we want. There is also the acute risk that the government will demand this surveillance be expanded to block other activities, which could be particularly dangerous. If you are in the UK and don’t wish to see these measures implemented, it is still possible to write to your MP, which could lead to some better safeguards being introduced before it’s too late. Once we get more technical information about how this will be implemented, then we will be able to see if de-Googling Android devices will bypass this measure. For anyone with an iPhone, there is zero chance that you’ll be able to take off these handcuffs because Apple doesn’t let you mess with your software.
    • I'm reading the reports as EU rejecting Apple's proposal because Trusted System Agent would be an intermediary offered to third party AI's (this article is also worded as such) but Siri AI itself would not pass this intermediary. This would cause a situation where Siri AI would have more direct system access and offer it an unfair advantage. (speaking from EU regulator perspective here) Apple is citing security issues with doing what EU asked for, and I think this also supports this theory, because truly direct system access like Siri AI would make it impossible to control third party AI's running on the devices and e.g. reign them in via adjustments to Trusted System Agent. So, I _think_ this is the sticking point right now: EU saying they need to be on equal footing as Siri AI, Apple saying they can't be because Apple only trusts their own AI. Apple could of course be leaning a bit extra hard towards this because they're biased in terms of excluding competitors. One method to find an agreement would be to have Siri AI also run through Trusted System Agent and treat it as untrusted. This kind of defensive architecture design (especially when involving an AI) would honestly not be a very bad idea from a sheer engineering standpoint. But then Apple would need to swallow their pride and adapt worldwide due to EU, and make perhaps major updates delaying Siri AI once more.
    • I have not even heard of that game. will take a look
    • Chasys Photo 5.41.01 by Razvan Serea Chasys Photo is a suite of image editing applications including a layer-based image editor with adjustment layers, linked layers, timeline and frame-based animation, icon editing, image stacking and comprehensive plug-in support (Chasys Photo Editor), a fast image viewer (Chasys Photo Viewer) and a fast multi-threaded image file converter (Chasys Photo Converter) , with RAW image support in all components. It supports the native file formats of several competitors including Adobe Photoshop, Affinity Photo, ArtWeaver, Corel PhotoPaint, FireAlpaca, GIMP, Krita, Paint.NET, PaintShop Pro and Pixlr, and the whole suite is designed to make effective use of multi-core processors, touch-screens and pen-input devices. Designed under the mantra of “unique, flexible and powerful”, Chasys Photo takes a radically different approach to image editing with the aim of opening up new possibilities for those who dare to be different. Chasys Photo key features: Free-style layering with blending modes Adjustment layers with multiple adjustments per layer Linked layers (a.k.a Linked Smart Objects) Composite, Image List, Frame Animation and Object Animation image modes Animation, both frame-based and object-based (timeline animation) Animation Composer engine Image Stacking for noise reduction, super-resolution, etc. Tablet/Pen-input/Stylus support with pressure control Touch-screen support with gestures including pitch-to-zoom and multi-finger panning Support for the native formats of Adobe Photoshop, Affinity Photo, ArtWeaver, Corel PhotoPaint, FireAlpaca, GIMP, Krita, Paint.NET, PaintShop Pro and Pixlr Support for common formats such as JPEG, animated PNG, animated GIF, TIFF, PICT, WebP, HEIF, DDS, JPEG-2000, JPEG-XR, JPEG-XL, AVI video, etc. Support for the OpenRaster interchange file format and rare formats such as QOI, MNG/JNG and DPX Support for older formats such as PPM/PGM/PBM, PCX/DCX, PCD, TGA, COKE, etc. Comprehensive Camera RAW file support with live adjustment Extensive plug-in support with streamlined SDKs Support for Photoshop Filter Plug-ins (.8BF) Advanced printing and scanning engines PDF document generation Icon and cursor editing, import and export, including Vista-style and Mac-OS icons Screen Capture, including Video Screen Capture with multiple triggering modes Video capture from devices (e.g. TV/Video) Supports multi-core processors, High-DPI displays and Multiple Display setups Integrated File Browser, Bluetooth OBEX and in-built utilities (Calculator, Notepad) Shell integration with thumbnails and conflict detection Unlimited Undo/Redo and Asynchronous Auto-Save, with Just-in-time memory compression to save space Fully re-editable text with advanced styling and effects (TextArt) Full alpha channel through out the workflow with Alpha protection (a.k.a. transparency protection) Multiple language support with user-editable language files and translation assistant (Chasys Photo Language Studio) Anti-aliasing and super-sampling support in tools and paths* Smart-resizing (similar to seam-carving) Best-in-class post-edit heuristics anti-aliasing engine Physical measurement specification with display size detection via EDID Uses the latest CD5 specification with animation and multi-resolution Super-fast internal graphics engine (JpDRAW2) Full UNICODE support in all components Metadata save, restore and scale to imitate vector art Configurable Guides and Grids with Snap-to-Grid Smart-dither to custom palette Asynchronous preview rendering engine Pantone equivalent palettes for PMS 100 to 814-2x Automatic color naming ... and many more! Chasys Photo 5.41.01 changelog: New Features Layered images with multiple pages (Composite/Multi-page) Additional templates to support template-centric workflow New Layer Blend Mode: Inverse Luma Mask Horizon detection in Rotate Transform Cropping option when importing video Orientation options in QR Code Generator plug-in Solved angle ambiguities (CCW versus CW) Internal Improvements Improved graphics engine (JpDRAW2™ v26.05) Improved CD5 codec (v4.10, improved ACSC compression) Improved interpolation when downsizing images Improved motion detection in Video Capture Slightly lower memory usage (RAM is getting expensive!) File Support and Bug Fixes Improved PXZ file support (placeholders, blanks) [bug-fix] Memory leak in flt_JPEG.dll Download: Chasys Photo 5.41.01 | 46.1 MB (Freeware) View: Chasys Photo Home Page | Wikipedia Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Very Popular
      Captain_Eric earned a badge
      Very Popular
    • One Month Later
      amusc earned a badge
      One Month Later
    • One Month Later
      DJC50PLUS earned a badge
      One Month Later
    • Week One Done
      DJC50PLUS earned a badge
      Week One Done
    • Proficient
      Eric Biran went up a rank
      Proficient
  • Popular Contributors

    1. 1
      +primortal
      508
    2. 2
      PsYcHoKiLLa
      220
    3. 3
      ATLien_0
      92
    4. 4
      +Edouard
      90
    5. 5
      Steven P.
      83
  • Tell a friend

    Love Neowin? Tell a friend!