CakePHP get current URL without language prefix - php

I used this solution for i18n of my CakePHP 2.3 website.
When user in this URL: example.com/myController/myAction/param1/param2
I want to give link to example.com/eng/myController/myAction/param1/param2
This works well with this code inside my view file:
English
But when user in this URL: example.com/fre/myController/myAction/param1/param2
I can't link him to this URL: example.com/eng/myController/myAction/param1/param2
I can get the full URL with this:
fullURL = Router::url( $this->here, true );
$strippedURL = str_replace("http://example.com/fre/myController/myAction/param1/param2","myController/myAction/param1/param2",$fullURL)
But I need to make this for every language. Or I can strip first 22 characters from $fullURL. But they don't seem good solutions.
Do you have any suggestions?
Edit: Inside my Helper/View file I used this:
function getRelURL() {
$controller = $this->request->params['controller'];
$action = $this->request->params['action'];
$URL = "/".$controller."/".$action."/";
foreach ($this->request->params['pass'] as $p) {
$URL .= urlencode($p)."/";
}
}
I would be happy if you can recommend better alternative.

I used a slightly different approach that seems to work well, even though I have not tested it with named parameters and all other routing features.
I created the following function in AppHelper:
public function urlLanguage($lang) {
static $hereUrl=null;
if (empty($hereUrl)) {
$hereUrl = $this->request->params;
unset ( $hereUrl ['models'] );
unset ( $hereUrl ['named'] );
unset ( $hereUrl ['paging'] );
if (isset ( $hereUrl ['pass'] )) {
foreach ( $hereUrl ['pass'] as $pass ) {
$hereUrl [] = $pass;
}
unset ( $hereUrl ['pass'] );
}
}
return array_merge( $hereUrl, array ('language' => $lang ) );
}
and use it in the View as follows:
foreach ($languages as $lang=>$langDesc) {
echo $this->Html->link($languageDesc, $this->Html->urlLanguage($lang));
}
where $languages is an array with all the available language. I skipped the HTML around it the link itself.
I followed the instructions here for setting up the routes and language switching.

Related

using $variable inside preg_match function

I'm trying to learn MVC with PHP with some online courses. So in this tutorial, the teacher trying to detect a path.
$pathCheck=preg_match("#^{$link}$#",'$this->nowPath',$params);
print_r($params);
When he opens the project with desired path, let's say project/index.php, Array returns with 1.
If he try to write wrong path like project/asdasdas.php , Array returns with 0.
But for me, it returns empty.
Array ( ) Array ( ) Array ( ) Array ( ) Array ( )
I think the problem is preg_match part "#^{$link}$#"
I'm stucked.
I'm working on a localhost. AppServ (PHP Ver 7.3)
EDİT:
I'm adding my full codes to explain my situation a little bit better.
app.php
<?php
class App
{
protected $nowPath;
protected $nowMethod;
protected static $routes = [];
public function __construct()
{
$this->nowPath = $_SERVER['REQUEST_URI'];
$this->nowMethod = $_SERVER['REQUEST_METHOD'];
$this->startRoute();
}
public static function getAction($link, $path, $auth = false, $area = null)
{
self::$routes = ['GET', $link, $path, $auth, $area];
}
public function startRoute()
{
foreach (self::$routes as $routes) {
list($method, $link, $path, $auth, $area) = $routes;
$methodCheck = $this->nowMethod == $method;
$pathCheck=preg_match("#^{$link}$#",'$this->nowPath',$params);
print_r($params);
}
}
}
?>
route.php;
<?php
App::getAction('/index','/default/index',false); ?>
Fixed finally. I'm not fully understand but the teacher working with project/index folder.Mine was www/project/index. Maybe i made mistake on routing.

Why getPostParameters doesn't work on symfony 1.4?

I have a form in symfony 1.4 which are created for each competence. My forms was created with success. But when I try to save my form I can't. I go to see my action code and the function getPostParameters seem dosn't work. I use getParameterHolder to see what's wrong in my parameters but after I put the good value the getPostParameters function doesn't work.
This is what I get from getParameterHolder:
sfParameterHolder Object
([parameters:protected] => Array
(
[professionnal_competence] => Array
(
[rayon_competence3] => 24
[rayon_competence9] => 22
[rayon_competence19] => 32
)
[module] => professionnal_subregion
[action] => saveCompetenceRadius
)
)
And my function:
public function executeSaveCompetenceRadius(sfWebRequest $request) {
$user = $this->getUser()->getGuardUser();
$q = ProfessionnalCompetenceQuery::create()
->addSelect('pc.*')
->where('pc.professionnal_id= ?', $user->getId());
$res = $q->execute();
$values = $request->getPostParameters(['professionnal_competence']);
$test = $request->getParameterHolder();
var_dump($values); print_r($values); print_r($request->getParameterHolder());
exit;
foreach ($res as $professionnalCompetence) {
foreach ($values['professionnal_competence'] as $k => $val) {
if ($k == 'rayon_competence' . $professionnalCompetence->getCompetenceId()) {
$professionnalCompetence->setRayonCompetence($val);
$professionnalCompetence->save();
}
}
}
return $this->renderComponent('professionnal_subregion', 'competenceRadius');
// return "test";
//return $this->renderPartial('professionnal_subregion/competenceradius');
}
This is my form:
class ProfessionnalCompetenceRadiusForm extends BaseProfessionnalCompetenceForm {
public function configure()
{
unset($this['rayon_competence']);
$this->widgetSchema['rayon_competence'.$this->object->getCompetenceId()] = new sfWidgetFormSelectUISlider(array('max'=>50,'step'=>1));
$this->widgetSchema->setHelp('rayon_competence'.$this->object->getCompetenceId(),'en kilomètres');
$this->widgetSchema->setLabel('rayon_competence'.$this->object->getCompetenceId(),'rayon');
$this->setValidator('rayon_competence'.$this->object->getCompetenceId(), new sfValidatorInteger(array('max'=>50)));
}
}
Someone has an idea or can help me ?? Because I try lot of thing but without success. Thank in advance :).
I think the error hides in this line:
$values = $request->getPostParameters(['professionnal_competence']);
You're passing an array to a function that takes a string. Try removing the brackets around 'professionnal_competence'.
EDIT: Scratch that. getPostParameters takes no parameters. getPostParameter, on the other hand, takes two - the first of which is the field name - a string. So, your code should be:
$values = $request->getPostParameter('professionnal_competence');
The error is here:
$values = $request->getPostParameters(['professionnal_competence']);
The function sfWebRequest::getPostParameters doesn't actually take parameters.
You can either access this array with [...], or use getPostParameter, which allows "safe" deep access:
$val = $request->getPostParameter('a[b]');
// basically the same as, but with error checks:
$val = $request->getPostParameters()['a']['b'];

Error trying to add parserHook to mediawiki

I'm running Mediawiki 1.23 and using the Syntaxhighlight plugin. 90% of the time, we use SQL as the specified language. E.g.,:
<syntaxhighlight lang="sql">
select 'foo';
</syntaxhighlight>
So I thought, "Why not just have a separate "sql" tag that invokes highlighter and sets the language to SQL? I.e.,:
<sql>
select 'foo';
</sql>
So I tried the following, but it doesn't work. I'm probably misusing PHP and I could use some help.
In LocalSettings.php:
require_once "$IP/extensions/SyntaxHighlight_GeSHi/SyntaxHighlight_GeSHi.php";
In SyntaxHighlight_SeSHi.php I added the third setHook:
function efSyntaxHighlight_GeSHiSetup( &$parser ) {
$parser->setHook( 'source', array( 'SyntaxHighlight_GeSHi', 'parserHook' ) );
$parser->setHook( 'syntaxhighlight', array( 'SyntaxHighlight_GeSHi', 'parserHook' ) );
$parser->setHook( 'sql', array( 'SyntaxHighlight_GeSHi', 'parserHookSql' ) );
return true;
}
And finally in SyntaxHighlight_SeSHi.class.php I try to keep all the values that were coming in from the parser, but adding (or replacing) the "lang" value, and then call the original parserHook:
class SyntaxHighlight_GeSHi {
private static $initialised = false;
private static $languages = null;
public static function parserHookSql( $text, $args = array(), $parser ) {
$args['lang']='sql';
self::parserHook($text,$args,$parser);
}
public static function parserHook( $text, $args = array(), $parser ) {
global $wgSyntaxHighlightDefaultLang, $wgUseSiteCss, $wgUseTidy;
wfProfileIn( __METHOD__ );
self::initialise();
...
...
When I do this, the page renders but the rendered text from the sql tag is "UNIQ088c1443c530026e-sql-00000007-QINU", so I'm obviously doing something wrong.
So any help with my PHP, or maybe I'm extending mediawiki the wrong way... In either case, thanks in advance!
return self::parserHook($text,$args,$parser);

How can i get $_POST full value without any sanitization operation on it in codeigniter?

I have a controller something like this in codeigniter:
class ABC extends MX_Controller {
...
...
...
.
.
.
...
...
public function getTestPostData(){
print_r($_POST);
}
}
In getTestPostData when i print $_POST i need full $_POST data without any sanitization of any kind. I can't set $config['global_xss_filtering'] = FALSE; in config.php
How can i achieve that?
Edit:
In post data i am sending some HTML content with some <script>(script) tags, but when i print the data in my controller using $this->input->post("content") the <script>(script)tags gets replace by [removed] tags. This happens when the global_xss_filtering is TRUE. I can't change this value to FALSE.
I hope now the question is clear.
Try this, in my tests it worked even after unsetting $_POST completely.
public function getTestPostData()
{
$post_data = explode( "&", file_get_contents('php://input') );
$result = array();
foreach( $post_data as $post_datum ) {
$pair = explode("=", $post_datum );
$result[urldecode($pair[0])] = urldecode($pair[1]);
}
print_r( $result );
}
you can't set $config['global_xss_filtering'] = FALSE; in config.php?
then if you can't access core/input.php class
and remove _POST from it
function _sanitize_globals()
{
// It would be "wrong" to unset any of these GLOBALS.
$protected = array('_SERVER', '_GET', '_POST', '_FILES', '_REQUEST',
'_SESSION', '_ENV', 'GLOBALS',
or change the var $xss_clean to false like this
function get_post($index = '', $xss_clean = FALSE)
{
if ( ! isset($_POST[$index]) )
{
return $this->get($index, false); //here
}
then you can't view the post data unfiltered from
print_r($_POST);
print_r( $this->input->post() )
that's all
If you have CI v. 2+ try the following:
Create a new Core file that extends CI_Security and overwrite the xss_clean function like so:
class MY_Security extends CI_Security {
public function xss_clean($str, $is_image = FALSE)
{
return $str;
}
}
EDIT: I just tested this and it works. FYI.

How to pass series of variables in function as array or regardless of their order?

I am sorry, that sounds like a noob question. I am trying to do this, maybe my question is not clear.
I want to be able to pass something like this:
make_thumbnail( array( 'width' => 60, 'height' => 40', 'title' => 'my image' ) );
Now the above line calls the function which already produces the thumbnails I have that no problem, but I want flexibility here. I mean my function has variables ordered like this:
function make_thumbnail($title,$width,$height) {
the code..
echo ...
}
Now you get what I want to do? I want to be able to pass the variables in any order.. they do not have to come in same order title, width, height.. i want to be able to specify the order when I call the function in template as I put in very first line.
I tried to make my question as clear as I can, but really could not find anything about it.
This sort of thing?
function make_thumbnail($myarray) {
$sometitle = $myarray["title"]
$somewidth = $myarray["width"]
$someheight = $myarray["height"]
}
Why not have the array as the function argument? e.g.
function make_thumbnail($argsArray) {
echo $argsArray['width'];
}
You can create variables within your function for each parameter
function make_thumbnail($argsArray) {
$width = $argsArray['width'];
$height = $argsArray['height'];
$title = $argsArray['title'];
// ...plug the rest of your original function here
}
Then your function will behave exactly the same, except you can pass in an array.
What you're asking for is a description of the Reflection syntax of PHP:
function callWithNamedParams( $funcName, array $args = null )
{
if( is_null( $args ) ) return $funcName();
$f = new ReflectionFunction($funcName);
$input = array();
foreach( $f->getParameters() as $param )
{
array_push( $input, #$args[ $param->getName() ] );
}
return call_user_func_array( $funcName, $input );
}
Use:
function myFunc( $foo, $bar )
{
echo "foo = $foo; Bar = $bar";
}
callWithNamedParams( "myFunc", array( "bar"=>1, "foo"=>2 ) );
You should get foo = 2; Bar = 1 as an output.
you need to define your logic to take any parameter as the one you want it to be. Array is the best thing you can use. But changing the parameters changes the signatures.
you are kinda implementing polymorphism but in a wrong way..

Categories