Slim Framework $_GET 404 error - php

Hello so I have a simple code here which will do an update in a column and redirect to a page based on the GET parameter. My code is here:
In my html:
Move
and in the index.php
$app->get('/user/admin/table/:table_id/move', 'RecycleTable');
function RecycleTable($table_id)
{
$session = new \RKA\Session();
$app = \Slim\Slim::getInstance();
if (!$session->type) {
$app->redirect('/user/login');
}
else {
$sponsorID = $app->request()->get('sponsor');
$db = new db();
$bind = array(
':table_id' => $table_id
);
$update = array(
'status' => '2'
);
$db->update("tables", $update, "tableID = :table_id", $bind);
$db = null;
$app->redirect('/user/admin/table/'.$sponsorID);
}
}
When I try to click Move I get a 404 error. Do I get the parameter sponsor correctly? Or is there something wrong here?

It appears as if your link in the HTML is incorrect. Your route states that the path should be:
Move
not
Move
You are missing the /user/admin/table part which is why you would be receiving a 404. It cannot resolve to the correct route.

Related

PhalconPHP - How to return return single typed Raw SQL Statement Result

I have a relatively average (however basic) knowledge with PHP but I'm fairly new to PhalconPHP. I've learned of PhalconPHP while browsing a specific online course website and that this framework is rather fast and unique than other PHP Frameworks, plus it has a Micro package for easy development of REST API.
So as it is, I'm trying to learn how to develop an API with the help of PhalconPHP Framework. And as it is, for beginners like me, I'd like to start with using raw SQL statements rather than the provided phql syntax because I'm not entirely developing an MVC Application (and I'm really having a hard time learning the entire concept of PHQL itself, I need a separate time to learn this).
I have managed to make things work when working with multi-column query results that map to the class much like how it is supposed to be with PhalconPHP, with below sample code:
<?php
namespace MyApplication\Db\ShortLinks\Services;
use MyApplication\Db\ShortLinks\DatabaseTables;
use Phalcon\Mvc\Model\Resultset\Simple as ResultSet;
class VisitorService
{
function getVisitorLogByLinkId($id)
{
$sqlQry = "SELECT * FROM visitors v WHERE v.link_id = $id ORDER BY v.visitor_id DESC;";
$visitor = new DatabaseTables\Visitor();
$resultSet = new ResultSet(null, $visitor, $visitor->getReadConnection()->query($sqlQry));
$data = [];
foreach ($resultSet as $result) {
$data[] = [
"visitor_name" => $result->visitor_name,
"access_timestamp" => $result->access_timestamp
];
}
return $data;
}
}
?>
However, I cannot seem to get the concept on how to work this out with single-columned query results such as getting the SUM, COUNT, or even ids and specific data type. I've tried below code as I've tried to recreate provided answer here:
function isLinkIdValid($id)
{
$sqlQry = "SELECT IF(COUNT(l.link_id) = 0, 0, 1) 'is_exist' FROM links l WHERE l.link_id = $id;";
$result = $app->di->db->query($sqlQry);
$result->setFetchMode(Phalcon\Db::FETCH_ASSOC);
$result = $result->fetchAll($result);
return $result;
}
But, as i have expected, it would not work since $app (which is an instance of Phalcon\Mvc\Micro which is in index.php) is not accessible from the function.
Also, its best to explain to everyone that while I do have models for the database tables, I've separated all database logic from the model object to keep it clean and serve its only purpose - being a model. How I've done this is I've created a new folder named /service and creating service for each model that there is (for example: VisitorService).
To show everyone my code, I basically patterned it after PhalconPHP's REST Tutorial, below is a snippet of my code:
index.php:
<?php
use Phalcon\Loader;
use Phalcon\Mvc\Micro;
use Phalcon\Di\FactoryDefault;
use Phalcon\Db\Adapter\Pdo\Mysql as PdoMySql;
use Phalcon\Http\Response;
# Loader initialization and namespace registration
$loader = new Loader();
$loader->registerNamespaces([
"MyApplication\Db\ShortLinks\DatabaseTables" => __DIR__ . "/models/",
"MyApplication\Db\ShortLinks\Services" => __DIR__ . "/services/"
]);
$loader->register();
# DependencyInjector initialization and instantiation of database connection
$di = new FactoryDefault();
$di->set("db", function() {
return new PdoMySql([
"host" => "127.0.0.1",
"username" => "username",
"password" => "password",
"dbname" => "short_links"
]);
});
# Micro initialization, route definition
$app = new Micro($di);
$app->notFound(function() use ($app) {
$response = new Response();
$response->setStatusCode(404, "Not Found");
$response->setJsonContent([
"status" => 404,
"message" => "The specified route was not found, or does not exist",
"data" => ""
]);
return $response;
});
require "routes/visitor_route.php";
$app->handle();
?>
routes/visitor_route.php
<?php
use Phalcon\Http\Response;
use MyApplication\Db\ShortLinks\Services;
require "services/visitor_service.php";
$app->get('/v1/visitors/log/{id:[0-9]+}', function($id) use ($app) {
$response = new Response();
# validate id parameter
if($id <= 0) {
$response->setStatusCode(422, "Unprocessable Entity");
$response->setJsonContent([
"status" => 422,
"message" => "Invalid link id specified.",
"data" => ""
]);
return $response;
}
$service = new Services\VisitorService();
$response->setStatusCode(200, "OK");
$response->setJsonContent([
"status" => 200,
"message" => "",
"data" => $service->getVisitorLogByLinkId($id)
]);
# This partially works, except that it does not return whether a link id is valid, so I'm trying to create a logic for one.
// return $response;
$tempService = new Services\LinkService();
$tempResult = $tempService->isLinkIdValid($id);
return print_r($tempResult);
});
?>
service/visitor_service.php
<?php
namespace MyApplication\Db\ShortLinks\Services;
use MyApplication\Db\ShortLinks\DatabaseTables;
use Phalcon\Mvc\Model\Resultset\Simple as ResultSet;
class VisitorService
{
# technically belongs to 'services/link_service.php' but placed here to shorten attached codes.
function getAllLinks()
{
$sqlQry = "SELECT * FROM links;";
$link = new DatabaseTables\Link();
$resultSet = new ResultSet(null, $link, $link->getReadConnection()->query($sqlQry));
$data = [];
foreach ($resultSet as $result) {
$data[] = [
"link_id" => $result->link_id,
"description" => $result->description,
"original_url" => $result->original_url,
"short_url" => $result->short_url
];
}
return $data;
}
# technically belongs to 'services/link_service.php' but placed here to shorten attached codes.
function createNewShortLink($link)
{
$sqlQry = "INSERT INTO links VALUES (DEFAULT, '$link->description', '$link->original_url', $link->base_url, '$link->unique_key', DEFAULT, DEFAULT);";
$link = new DatabaseTables\Link();
$link->getReadConnection()->query($sqlQry);
}
# technically belongs to 'services/link_service.php' but placed here to shorten attached codes.
# This is the experimental code i am working with
function isLinkIdValid($id)
{
/*
As it is, everything here doesn't work.
*/
$sqlQry = "SELECT IF(COUNT(l.link_id) = 0, 0, 1) 'is_exist' FROM links l WHERE l.link_id = $id;";
$result = $app->di->db->query($sqlQry);
$result->setFetchMode(Phalcon\Db::FETCH_ASSOC);
$result = $result->fetchAll($result);
return $result;
}
function getVisitorLogByLinkId($id)
{
$sqlQry = "SELECT * FROM visitors v WHERE v.link_id = $id ORDER BY v.visitor_id DESC;";
$visitor = new DatabaseTables\Visitor();
$resultSet = new ResultSet(null, $visitor, $visitor->getReadConnection()->query($sqlQry));
$data = [];
foreach ($resultSet as $result) {
$data[] = [
"visitor_name" => $result->visitor_name,
"access_timestamp" => $result->access_timestamp
];
}
return $data;
}
}
?>
To summarize, I'm looking for a way to fetch single-columned data from my database using RAW SQL Statements inside PhalconPHP. I've dug up several resources but there's just too few of them, if not lacking.
EDIT 1: i know that how i implemented the service is not perfect, and that is prone to security attacks. but please focus on the issue main issue. i'll resolve other issues afterwards. also, what i'm looking for is to be able to use the PdoMysql stored in $app->di["db"] from the index.php much like how i managed to in getAllLinks() and createNewShortLink($link) functions. however, i made a "temporary" solution by passing in the PdoMysql object from the $app->di["db"] to the function like below:
function isLinkIdValid($dbConn, $id)
{
$sqlQry = "SELECT IF(COUNT(l.link_id) = 0, 0, 1) 'is_exist' FROM links l WHERE l.link_id = $id;";
$isExist = $dbConn->fetchAll($sqlQry, \Phalcon\Db::FETCH_ASSOC);
return $isExist;
}

magento : how to add parameter with soap request

I am new to Magento I tried calling a category level using the Magento SOAP API with parent category id. I used the following code:
<?php
$proxy = new SoapClient('http://domain/index.php/api/soap/?wsdl');
$session = $proxy->login('user', 'password');
$result = $proxy->call($session,'catalog_category.level');
echo json_encode($result);
?>
For the above code "Default Category" details are coming, I tried to call some other category by using the following code:
$result = $proxy->call($session,'catalog_category.level',12);
This is not working:
$arguments = array( 'parentCategory' => 12);
$result = $proxy->call($session,'catalog_category.level',$arguments);
This is also not working:
Then I tried calling category tree using following code:
<?php
$proxy = new SoapClient('http://domain/index.php/api/soap/?wsdl');
$session = $proxy->login('user', 'password');
$result = $proxy->call($session,'catalog_category.tree');
echo json_encode($result);
?>
It shows the entire category tree so it means API is working but whenever I try to pass an argument it shows server not found error.
Can anyone please tell me how to pass arguments with the request.
You will need to call it like
$proxy->call($sessionId, 'category.level', array(null, null, 12));
For more information about the function check class
Mage_Catalog_Model_Category_Api
function level($website = null, $store = null, $categoryId = null)
If you want to pass particular website and store you can pass it instead of null parameter.
i manage to get output using soapv2. but it is slow compare to soapv1 but it is giving the required out put. the code i use to pass parameter is given as below.
<?php
$proxy = new SoapClient('http://domain/index.php/api/v2_soap/?wsdl=1');
$session = $proxy->login((object)array('username' => 'user', 'apiKey' => 'password'));
$result = $proxy->catalogCategoryTree((object)array('sessionId' => $session->result, 'parentId' => '12'));
echo json_encode($result);
?>

PHP and Wordpress - Submit URL using wp_http

I have a URL that is generated by php and ends up as a string called $myurl and looks like this...
http://www.mydomain.com/submit.php?favcol=blue&favfood=crisps&favday=Tuesday
I am trying to use the following snippet to submit this url
$request = new WP_Http();
$response = $request->post($myurl, array());
It is not working, although if I submit the URL manually then it does work.
What am I doing wrong?
I might be wrong, but it seems to me that you are not posting anything actually, but use the url so the page can handle the GET paramaters from the url? Try this:
$url = 'http://www.mydomain.com/submit.php?favcol=blue&favfood=crisps&favday=Tuesday';
$request = new WP_Http;
$result = $request->request( $url );
Edit I've just checked the class-http.php file and I'm wrong, there is a post method defined.
function post($url, $args = array()) {
$defaults = array('method' => 'POST');
$r = wp_parse_args( $args, $defaults );
return $this->request($url, $r);
}
Which is still just a function created specifically to do:
$request->request($myurl, array('method'=>'post', 'data' => 'whatever'));
Alternatively, you can just use the wrapper that was created explicitly for this.
wp_remote_post($url, array());

Mediawiki stopping a page from saving and redirecting back to edit page with an error message

My wiki articles contain a link to a specific dataset. I want to enforce that these links are unique (as in no one can create a new page with a link that is present in another page.) I have already written most of the code for this extension. I created a table 'unique_external_links' that stores the url as an index and the page id that the URL lives in.
Here is a part of the code I wrote:
$wgHooks['ParserFirstCallInit'][] = 'UniqueURLSetupParserFunction';
$wgHooks['LoadExtensionSchemaUpdates'][] = 'fnExternalLinksDBHook';
// Allow translation of the parser function name
$wgExtensionMessagesFiles['UniqueUrl'] = dirname( __FILE__ ) . '/UniqueUrl.i18n.php';
// Tell MediaWiki that the parser function exists.
function UniqueURLSetupParserFunction( &$parser ) {
$parser->setFunctionHook( 'example', 'UniqueURLParserFunction' );
return true;
}
function UniqueURLParserFunction( $parser, $param1 = '', $param2 = '' ) {
// The input parameters are wikitext with templates expanded.
// The output should be wikitext too.
global $wgRequest, $wgOut;
$return_url = $wgRequest->getRequestURL();
$pid = $param2;
$param1 = trim($param1);
$url_pattern = '/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/';
$match = preg_match($url_pattern, $param1);
if (!$match) {
// return ERROR not a valid URL!
}
$patterns = array('/^(https?:\/\/)/', '/\/$/');
$replace = array('','');
$url = preg_replace($patterns, $replace, $param1);
if (empty($param2)) { // creating a new page
try {
$dbw = wfGetDB( DB_MASTER );
$res = $dbw->insert('unique_external_links',
array('link_url' => $url , 'page_id' => $pid));
} catch(Exception $e) {
// return ERROR page with this link already exists!
}
} else { //Trying to edit existing page
$dbr = wfGetDB( DB_SLAVE );
$res = $dbr->select(
'unique_external_links',
array( 'link_url' ),
'link_url = "' .$url.'" AND page_id = "' .$pid.'"'
);
if ($dbr->numRows($res) == 0) {
try {
$dbw = wfGetDB( DB_MASTER );
$res = $dbw->insert('unique_external_links',
array('link_url' => $url , 'page_id' => $pid));
} catch(Exception $e) {
//return ERROR Dataset Already Exists
$response = $wgRequest -> response();
$response -> header('Location: '.$return_url);
return $return_url;
}
}else {
//just editing page, not changing link, all is good
return $param1;
}
}
return $param1;
}
First off, I apologize for the sloppy code, really just slapped this together very quickly with no prior extension experience...
As you can see there are places where I have the comment //return ERROR I would like to stop media wiki from saving the page if one of those conditions are true. Instead of saving, I would like to return the user to the edit page with a message telling them there is a problem with the link they are providing.
Any ideas? I looked around a lot but couldn't find anything similar, I assume it is because I don't know really what question to ask. I am aware that there are hooks like 'ArticleSave', but i didn't know how I would use that in conjunction with a parser.
Any help would be great! Even if its telling me to completely re-do what I did because its all wrong haha.
EDIT: I fixed this problem by throwing MWExceptions at those places where I wanted to return an error. I then went to Exceptions.php and updated the MWExceptionhandler to take a different action when it sees that the exception message matches the ones I am throwing from this extension. This is hacky I admit.. But what can you do sometimes..
Writing this extension as a parser function is probably the wrong direction. If you want to reject edits, use the EditFilter hook. You may want to take a look at the SpamBlacklist extension as a model, as it also looks at links to decide whether to reject an edit.
Also, the one issue I see with your extension is that, once a page has been saved with one of these unique links, there's nothing in place to remove rows from unique_external_links even if the link (or the entire page!) is removed, making it sometimes impossible to reinsert a link that's been removed. You'll probably want to fix that.

Redirection Loop in CakePHP Application

I am using CakePHP v1.2 for my web application hosted here: http://lol-land.in
The application was working fine till Yesterday, but it suddenly started to get stuck in some redirection loops. What makes it weirder is the fact that the problem is with just one controller: posts. And even in that most of the functions are working. But http://lol-land.in/posts is redirecting to lol-land.in/posts/view/133 which is in turn redirecting to itself.
Actually 110 of the 117 posts of the form /posts/view/ are stuck in this 302 redirection.
Can anyone please tell me what could have caused this?
[CakePHP 1.3 and PHP5]
Edit: Adding View Logic
function view($id = null) {
$this->log("View Logic Entry", LOG_DEBUG);
// These Log entires are missing
$this->layout = 'postview';
if (!$id) {
$this->Session->setFlash(__('Invalid Post.', true));
$this->log("Redirect due to missing id", LOG_DEBUG);
$this->redirect(array('action'=>'index'));
}
$log = $this->Session->read('Auth.User');
$logid = $log['id'];
$temp = $this->Post->read(null, $id);
$ratings = $temp['Rating'];
$this->set(compact('up', 'down', 'userrated', 'userrateid'));
$coms = $temp['Comment'];
$comuser = array();
for ($i=0; $i<count($coms); $i++) {
$comuser[$i] = $coms[$i]['user_id'];
}
$comuser = $this->Post->User->find('list', array( 'fields'=>array('User.id', 'User.username'),
'conditions'=>array("User.id" => $comuser)
));
$this->set(compact('comuser'));
$this->pageTitle = $temp['Post']['title'];
$this->set('post', $temp);
$alltypes = $this->Post->Type->find('list', array('fields'=> array('Type.id', 'Type.typename')));
$selectedtab = -1;
$this->set(compact('alltypes', 'selectedtab' ));
//Calling updateFBStats
// Removed because unnecessary.
}
Chances are you are either 1) using circular references with the Auth component OR 2) the function in your controller is redirecting do to something within the method. Can you show the code of posts_controller.php function view() ?

Categories