running different codes when entered from different urls in yii 1 - php

I have following code in my php class called Plaint:
class Plaint extends CAction
{
public function run()
{
$model = new PlaintForm();
$this->runTests($model);
...........
I need to run this class without($this->runTests($model)), if enter from this url /plaint. If I enter this page from other url, I need to run $this->runTests($model);.(e.g /filled). How can I do it?

You can look for specific phrase in current url:
if(strpos(Yii::app()->request->requestUri, '/filled') !== false) {
$this->runTests($model);
}
I advise against putting test code into production code.

Related

How to read config values in PHP controller?

I am using symfony 4.2 framework in which there is PHP controller with multiple actions. I have set below values in packages\config.yaml.
myDir: '/abc'
I have below controller with 2 actions as defined below.
//this works
public function uploadTestAction(Request $r_request)
{
$myDir = $r_request->request->get("myDir");
}
//this doesn't work
public function loadTestAction(Request $r_request)
{
$myDir = $r_request->request->get("myDir");
//$myDir = $r_request->query->get("myDir"); //this is also not working
}
Issue here is I am able to get the value in uploadTestAction but value is coming as null in uploadTestAction. I have tried using query as well but still not getting the correct value. Both request types are GET. What I am missing here or how can trace it ?
you should define it as parameter:
https://symfony.com/doc/current/service_container/parameters.html
final class XyController extends SymfonyController {
public function registerAction() {
$dir = $this->container->getParameter('dir');
}
}

SilverStripe 3.1+ Using PHP to dynamically change the URL slug of a Redirector

This is an extension of my original question SilverStripe 3.1+ Dynamically creating page redirects
I have a product page URL
a) www.mysite.com/category/subcat/productid
You can visit this page via a a separate redirector page
b) www.mysite.com/productid
Page 'a' has tabs which can be visited via
c) www.mysite.com/category/subcat/productid/tabid
I would like to use PHP to dynamically create links / redirectors for each product page create so it can be visited by:
1) A short URL using only its 'predicted' shown in 'b' (I can do this by creating a page redirector but this is long winded for a large number of products.
2) Create a short URL for each tab link as well, so 'c' would be redirected from: d) www.mysite.com/productid/tabid
The 'tabid' can be hard coded and in my case would be: audio, videos, pictures, firmware
Currently using the code in my ProductPage.php
class ProductPage_Controller extends Page_Controller {
private static $allowed_actions = array(
'audio',
'pictures',
'firmware',
'videos',
);
public function audio() {
$this->redirect($this->Link().'?tab=audio');
}
public function pictures() {
$this->redirect($this->Link().'?tab=pictures');
}
public function firmware() {
$this->redirect($this->Link().'?tab=firmware');
}
public function videos() {
$this->redirect($this->Link().'?tab=videos');
}
Allows me to go from /video to /?tab=video but this of course does not shorten the URL which is the final result I'm after.
Possibly this could be done in an extension of the RedirectorPage.php?
One way to do this is to use onBeforeHTTPError404 to hook into when a 404 error is called and to redirect any product found.
We create a ProductRedirectExtension with an onBeforeHTTPError404 function. This function will get called when a page cannot be found, but before the system returns a 404 error. The code in here will check if a ProductPage exists with a URLSegment with the first part of user's URL string. If a ProductPage is found we then check if the second part of the user's URL string is one of the tab keywords. After that the user is redirected to the page.
ProductRedirectExtension.php
class ProductRedirectExtension extends Extension {
public function onBeforeHTTPError404( $request ) {
$urlSegment = $request->param('URLSegment');
$action = strtolower($request->param('Action'));
$page = ProductPage::get()->filter('URLSegment', $urlSegment)->first();
if ($page) {
$link = $page->Link();
if ($action == 'audio' || $action == 'pictures' || $action == 'firmware' || $action == 'videos') {
$link .= '?tab=' . $action;
}
$response = new SS_HTTPResponse();
$response->redirect($link, 301);
throw new SS_HTTPResponse_Exception($response);
}
}
}
We enable this extension with the following config settings.
config.yml
RequestHandler:
extensions:
- ProductRedirectExtension
ContentController:
extensions:
- ProductRedirectExtension
ModelAsController:
extensions:
- ProductRedirectExtension
The shortest you could go is www.mysite.com/product/productid/tabid. It is possible to do this without the product part, but this would make your life a lot harder as you would have to go through a lot of trouble to still have access to Admin and Dev for example.
If you want the shortest URL you should make a new Page, as your current ProductPage is a child of another page, telling from your URL:
www.mysite.com/category/subcat/productid
You can achieve the best scenario with this code:
class ProductRedirectPage_Controller extends Page_Controller
{
private static $allowed_actions = [
'Product'
];
private static $url_handlers = [
'$ID/$TabID' => 'Product'
];
public function Product()
{
// Get your ProductPage, this should work if there is only one ProductPage
$page = ProductPage::get()->first();
if(! $productId = $this->request->param('ID'))
return $this->redirect($page->Link()); // or send them somewhere else
$tabId = $this->request->param('TabID');
$link = $page->Link('yourAction/' . $productId . '/' . $tabId);
return $this->redirect($link);
}
}
EDIT
With this code, when www.mysite.com/product/productid/tabid is visited, it will redirect you to where your ProductPage is. Maybe you wish to change the /$tabId to ?tabId=' . $tabId, but that is totally up to you.
So if I'm to summarise, you want newpage/video to open the correct on page tab, rather than being an action to render a different page?
You could do something funky with private static $url_handlers, to set a parameter you could query through $request->param('Thing').
Or you could set up handleAction to test whether or not $action either is one of the things in the list (and set flags for later use in eg. a template), or otherwise parent::handleAction.
This answer isn't extremely fleshed out, but should hopefully provide you some ideas on directions to investigate for your own use case.

How to access CodeIgniter functions without extending CI_Controller

I'm trying to write an external library which has functions commonly used among various classes.
Currently I'm trying to write a log message function. The problem is I need access to the session library and a model. How do I access them without extending from CI_Controller? Any workaround?
Here's my code:
Common_functions library:
public function _send_message($message, $log_to_db=TRUE)
{
$this->session->set_userdata("message", $message);
if($log_to_db) $this->User_log_model->log_mesage($message);
}
Usage in other classes example:
public function new_user()
{
$this->_set_validation_rules();
if($this->form_validation->run())
{
if($user_id = $this->User_model->insert($this->_prepare_new_user_array()))
{
$this->common_functions->_send_message("New User created successfully. | user_id: " . $user_id);
}
else {
$this->common_functions->_send_message("Unable to create new User record.");
}
}
}
Managed to solve it. Just moved my log message functions to the User_log_model instead.

Bolt CMS Events

I am working with the save event but having limited luck.
I have currently tried two ways but to limited success.
1) I can either never get the function to fire,
2) I am not too sure what to pass into the function for method two.
All I am trying to do is to dump the event information out on content save.Any help greatly appreciated, really loving this CMS
Attempt One -- never runs the function at all
class Extension extends BaseExtension
{
public function initialize() {
$this->addCss('assets/extension.css');
$this->addJavascript('assets/start.js', true);
$this->app['dispatcher']->addListener(\Bolt\Events\StorageEvents::POST_SAVE, 'postSave');
}
function postSave(\Bolt\StorageEvent $event)
{
dump($event);
}
Attempt two -- what do I input as a parameter?
class Extension extends BaseExtension
{
public function initialize() {
$this->addCss('assets/extension.css');
$this->addJavascript('assets/start.js', true);
$this->app['dispatcher']->addListener(\Bolt\Events\StorageEvents::POST_SAVE,$this->postsave($this->?????));
}
function postSave(\Bolt\StorageEvent $event)
{
dump($event);
}
Hopefully my answer doesn't come too late!
You simply can modify the content and save it back to the database:
public function postSave(\Bolt\Events\StorageEvent $event) {
// get the content
$content = $event->getContent();
// get a field out of the contenttype
$data = $content->get("myField");
// now modify $data here
$data = "new data - what ever you want";
// set data to the content
$content->setValue("data", $data);
// write the modified content to the database
$this->app['storage']->saveContent($content);
}
Note that the function gets fired every time you save contents. So just add an if-statement like this to just modify content you really want to:
if ($event->getContentType() == "my_type")
The parameter needed is a php callback the format for this is something like this:
$this->app['dispatcher']->addListener(\Bolt\Events\StorageEvents::POST_SAVE, array($this, 'postSave'));
That syntax is saying to run the postSave method within the current class. So this would work with your example number 1.
Now you can dump the event in your postSave method and see the results.

How To Use MVC PHP With Case Sensitive?

I am creating website in PHP. I am using MVC in PHP. My website works like this, if user go to example.com/about then it it will load About class and index() function. If user will go to localhost/about/founder then it will load founder() function from About class. but the thing is that if I go to localhost/About or localhost/AbOut or anything like that it is loading default index() function from About class file. So what to do with case sensitivity? I mean I want my script to load index() function from class file if it is localhost/about or localhost/terms. If anything is in uppercase, then it should load 404 error function. 404 error function is already set in my site.
Please help me friends.
here is my Bootstrap.php class file
<?php
/*
Bootstrap class to run functions by URL
*/
class Bootstrap {
public $_req;
public $_body;
public $_file;
public $_error;
function __construct(){
if(empty($_GET['req'])){
require 'classes/home.php';
$this->_body = new Home();
$this->hdr($this->_body->head());
$this->_body->index();
$this->ftr();
exit();
}
$this->_req = rtrim($_GET['req'], '/');
$this->_req = explode('/', $this->_req );
$_file = 'classes/'.$this->_req[0].'.php';
if(file_exists($_file)){
require $_file;
}
else {
$this->error(404);
}
$this->_body = new $this->_req[0];
$this->hdr($this->_body->head());
if(isset($this->_req[2])){
if(method_exists($this->_req[0], $this->_req[1])){
$this->_body->{$this->_req[1]}($this->_req[2]);
}else {
$this->error(404);
}
}else {
if(isset($this->_req[1])){
if(method_exists($this->_req[0], $this->_req[1])){
$this->_body->{$this->_req[1]}();
}else {
$this->error(404);
}
}else {
$this->_body->index();
}
$this->ftr();
}
}
//this function is to set header in html code
public function hdr($var = false){
echo '<!DOCTYPE HTML><html><head>'.$var.'</head><body>';
}
//this function is tp set footer in html code
public function ftr($var = false){
echo $var.'</body></html>';
}
//error handler
public function error($var){
require 'classes/er_pg.php';
$this->_error = new Error();
$this->_error->index($var);
}
}
You shouldn't use anything to load non-lowercase URLs because of the duplicate content, and that's a good thing you're doing. The wrong URLs should fail automatically in such cases.
However, since you didn't show how are you making those calls, then only thing I can suggest at this point is to check if the called method exists (case-sensitive), and if not, throw/redirect to a 404 page (header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");).
UPDATE
After all the chat in the comments, seems like file_exists is not case-sensitive in your case, which is really weird. Hopefully someone will be able to figure it out so I can delete this (keeping it because of the info in the comments).
I solved the problem. I used this
if(ctype_lower($this->_req[0])){
$_file = 'classes/'.$this->_req[0].'.php';
and now its working. Thanx anyways friends.

Categories