Slim 3 - replacement for isPost()? - slim

In Slim 2, I would do this,
$app->map('/login', function () use ($app) {
// Test for Post & make a cheap security check, to get avoid from bots
if ($app->request()->isPost() && sizeof($app->request()->post()) >= 2) {
//
}
// render login
$app->render('login.twig');
})->via('GET','POST')->setName('login');
But in Slim 3,
// Post the login form.
$app->post('/login', function (Request $request, Response $response, array $args) {
// Get all post parameters:
$allPostPutVars = $request->getParsedBody();
// Test for Post & make a cheap security check, to get avoid from bots
if ($request()->isPost() && sizeof($allPostPutVars) >= 2) {
///
}
});
I get this error,
Fatal error: Function name must be a string in C:...
Obviously that isPost() is deprecated, so what should I use instead in Slim 3 for isPost's replacement?

In Slim 4, there's no such helper and so the syntax gets longer (like a lot of Slim 4 stuff):
$request->getMethod() === 'POST'

According to documentation and comments, Slim supports these proprietary methods:
$request->isGet()
$request->isPost()
$request->isPut()
$request->isDelete()
$request->isHead()
$request->isPatch()
$request->isOptions()
Here it is an example of usage:
<?php
require 'vendor/autoload.php';
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
$app = new \Slim\App;
$app->map(['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'PATCH', 'OPTIONS'], '/', function (ServerRequestInterface $request, ResponseInterface $response) {
echo "isGet():" . $request->isGet() . "<br/>";
echo "isPost():" . $request->isPost() . "<br/>";
echo "isPut():" . $request->isPut() . "<br/>";
echo "isDelete():" . $request->isDelete() . "<br/>";
echo "isHead():" . $request->isHead() . "<br/>";
echo "isPatch():" . $request->isPatch() . "<br/>";
echo "isOptions():" . $request->isOptions() . "<br/>";
return $response;
});
$app->run();

Related

Returning Route Parameter in a page in SLIM 3

i a, having a link which sends public to view timeline of a specific user by passing variable in route.
<a href="<?php echo $baseLocation ?>/bnb-details/<?php echo $row['username']?>" >View</a>
and my route is defined as:
$app->get('/bnb-details/{name}', function (Request $request, Response $response, $args) {
include_once('bnb-details.php');
return $response; });
how can i pass the {name} args in the bnb-details.php ??
any kind of help would be appriciated.
you can use like this :
you should pass parametere from args to variable
$app->get('/bnb-details/{name}', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) {
$name = $args['name'];
include_once('bnb-details.php');
return $response;
});
then use
echo $name;
in bnb-details.php

Retrieve users/company information

On connecting to Quickbook within our app we are able to get access token and realmid but on trying to implement Get App Now we couldn't get any information after redirecting to our openid url. What I have tried so far is
define('OAUTH_CONSUMER_KEY', $consumerkey);
define('OAUTH_CONSUMER_SECRET', $consumersecret);
define('OAUTH_URL', 'https://oauth.intuit.com/');
define('APPCENTER_URL', 'https://appcenter.intuit.com/');
define('OAUTH_REQUEST_URL', OAUTH_URL . 'oauth/v1/get_request_token');
define('OAUTH_ACCESS_URL', OAUTH_URL . 'oauth/v1/get_access_token');
define('OAUTH_AUTHORISE_URL', APPCENTER_URL . 'Connect/Begin');
define('OAUTH_CURRENT_USER', APPCENTER_URL . 'api/v1/user/current');
try{
$oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
$oauth->enableDebug();
$request_token = $oauth->getRequestToken(OAUTH_CURRENT_USER,CALLBACK_URL);
echo '<pre>';
print_r($_POST);
print_r($_GET);
print_r($_REQUEST);
print_r($_SESSION);
echo $request_token;
print_r($request_token);
echo '</pre>';
} catch(OAuthException $e) {
pr($e);
}
I can't get any valuable information on the above code, I maybe doing it wrong and expecting that there would be realmid and access token once the authorization is done and quickbooks redirect to our openid url. Any information would be appreciated.
Please note I really don't have knowledge about this as this is my first time using quickbooks api and related technologies.
Updated
<?php
require 'openid.php';
try {
# Change 'localhost' to your domain name.
$openid = new LightOpenID($_SERVER["HTTP_HOST"]);
if(!$openid->mode) {
if(isset($_GET['login'])) {
$openid->identity = 'https://openid.intuit.com/OpenId/Provider';//'https://www.google.com/accounts/o8/id';
$openid->required = array(
'contact/email',
'namePerson/first',
'namePerson/last'
);
header('Location: ' . $openid->authUrl());
}
?>
<form action="?login" method="post">
<button>Login with Google</button>
</form>
<?php
} elseif($openid->mode == 'cancel') {
echo 'User has canceled authentication!';
} else {
echo 'User ' . ($openid->validate() ? $openid->identity . ' has ' : 'has not ') . 'logged in.';
}
} catch(ErrorException $e) {
echo $e->getMessage();
}
When the form above gets submitted it results into No OpenID Server found at https://openid.intuit.com/OpenId/Provider

Code to access Facebook Graph API with PHP SDK not working when reloading page

I'm writing some code to get the Facebook pages administered by a Facebook user, using Facebook Graph API. My code asks for authorization of the user and gets a token that enables it to get this information, which is then stored in a session. The problem is that if I reload the page, the stored token is unset and I will not be able to get the Facebook pages administered by the Facebook user.
The token is apparently revoked via the 'validateExpiration()' function when the page is reloaded.
What am I missing?
Here is my code:
session_start();
// Load the Facebook PHP SDK
require_once __DIR__ . '/facebook-sdk-v5/autoload.php';
define('APP_ID', 'xxxxxxxxxxxxxxxx');
define('APP_SECRET', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$fb = new Facebook\Facebook([
'app_id' => APP_ID,
'app_secret' => APP_SECRET,
'default_graph_version' => 'v2.7'
]);
if(isset($_SESSION['fb_access_token'])) {
echo '$_SESSION["fb_access_token"] = ' . $_SESSION['fb_access_token'] . '<br>';
// Create a new AccessToken object from its string code. Needed?
$accessToken = new Facebook\Authentication\AccessToken($_SESSION['fb_access_token']);
$expirationDate = $accessToken->getExpiresAt();
echo 'Token expires at: ' . var_dump($expirationDate) . '<br>'; // Returns null!
// verifies the validity and expiration of the token
$oAuth2Client = $fb->getOAuth2Client();
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
try {
echo 'Validating token<br>';
$tokenMetadata->validateAppId(APP_ID);
$tokenMetadata->validateExpiration(); // This apparently throws an exception
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'I will now unset the token<br>';
unset($accessToken);
unset($_SESSION['fb_access_token']);
}
if(!isset($accessToken)){
echo 'Token not set!';
exit;
}
// Check permissions
if (isset($accessToken)) {
$response = $fb->get('/me/permissions', $accessToken);
$permissions = $response->getDecodedBody();
echo 'Permissions: ';
print_r($permissions);
$permissions_list = [];
foreach($permissions['data'] as $perm) {
if($perm['status'] == 'granted') {
$permissions_list[] = $perm['permission'];
}
}
echo 'Permissions list: ';
print_r($permissions_list);
if(!in_array('pages_show_list', $permissions_list)) {
echo 'I will now unset the token<br>';
unset($accessToken);
unset($_SESSION['fb_access_token']);
}
}
} else {
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}
if(isset($accessToken)) {
// Logged in!
// Save the string code of the AccessToken to re-create it later
$_SESSION['fb_access_token'] = (string) $accessToken;
echo '$_SESSION["fb_access_token"] = ' . $_SESSION['fb_access_token'] . '<br>';
try {
$response = $fb->get('/me/accounts', $accessToken);
$data = $response->getDecodedBody();
echo '<pre>';
print_r($data);
echo '</pre>';
exit;
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
} else {
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'public_profile','pages_show_list']; // Optional permissions
$redirect_url = "https://www.example.com/this_file.php";
$loginUrl = $helper->getLoginUrl($redirect_url, $permissions);
echo 'Log in with Facebook!';
}
I finally got it!
The problem is that the Facebook AccessToken is an object with two properties: a string code, and a datetime PHP object with the expiration time - see the code in:
Github repository of Facebook's PHP SDK. The first time I get a fresh token, its expiration time is set and everything works fine. But when I store its code in a session and try to recreate it with
$accessToken = new Facebook\Authentication\AccessToken($_SESSION['fb_access_token']);
I'm not setting the expiration time, which the object defaults to the UNIX time 0 (i.e. January 1, 1970). Since after I invoke the function validateExpiration(), this will return that the access token has expired (it just looks at the expiration time in the AccessToken object) and will fire an exception.
Solution: Do not re-validate the stored token. The validateAppId(APP_ID) continues to be valid. For the expiration time, either store it (for example in a session) and use it when recreating the AccessToken object, or make a call to the Graph API. If this call returns an error (probably because of a token which was expired or a permission which was revoked by the user), ask the user for a new token via Facebook Login.

How to create RESTfull webservice in Zend framework?

I am new for zend.i need to create web-service in zend using Zend_Json_Server with JSON responce. I have define api controller here..
<?php
class ApiController extends Zend_Controller_Action
{
public function init()
{ }
public function indexAction()
{ }
public function restAction()
{
// disable layouts and renderers
$this->getHelper('viewRenderer')->setNoRender ( true );
// initialize REST server
$server = new Zend_Json_Server();
// set REST service class
$server->setClass('Test_Return');
// handle request
if ('GET' == $_SERVER['REQUEST_METHOD']) {
$server->setTarget('/json-rpc.php')
->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_2);
$smd = $server->getServiceMap();
// Set Dojo compatibility:
// $smd->setDojoCompatible(true);
header('Content-Type: application/json');
echo $smd;
}
$server->handle();
}
}
?>
And Test_Return define in Library/Test
Test_Return code is here..
<?php
class Test_Return {
public function add($x, $y)
{
return $x + $y;
}
public function subtract($x, $y)
{
return $x - $y;
}
public function multiply($x, $y)
{
return $x * $y;
}
public function divide($x, $y)
{
return $x / $y;
}
} ?>
How can call particular expression.
As describe in here on your index you create an instance of the zend_rest_server add your methods and run it. The methods should be specified in the url. I sugest you chose zend 2 for better implementation
The Zend_Json_Server initialization should be in your public/index.php
defined('APPLICATION_PATH') ||
define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
defined('APPLICATION_ENV') ||
define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));
set_include_path(implode(PATH_SEPARATOR, array(
dirname(dirname(__FILE__)) . '/libs',
get_include_path(),
)));
require_once 'Zend/Application.php';
$application = new Zend_Application(
APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
$application->getBootstrap()->bootstrap();
// Instantiate server ...
$server = new Zend_Json_Server();
include_once APPLICATION_PATH . '/Calculator.php';
$server->setClass(new Calculator());
if ('GET' == $_SERVER['REQUEST_METHOD'])
{
// Indicate the URL endpoint, and the JSON-RPC version used:
$server->setTarget('/api/1.0/jsonrpc.php')->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_2);
// Grab the SMD
$smd = $server->getServiceMap();
// Return the SMD to the client
header('Content-Type: application/json');
echo $smd;
return;
}
$server->handle();
$application->bootstrap()->run();
With curl on the command line you wont see anything ;-). This frustrated me a bit.
curl -H "Content-Type: application/json" -d '{"method":"add","x":5,"y":10}' http://zend.rest.server/api/1.0/jsonrpc.php
On the browser you can use this jQuery plugin
app = jQuery.Zend.jsonrpc({url: '/api/1.0/jsonrpc'});
app.add(5, 5);
{"result":10,"id":"1","jsonrpc":"2.0"}
You maybe want to follow the steps as describe here.
I suggest that you apgrade your version of zend if you can as zend2.X.X has better support for rest services.

Zend framework 2 - standalone forms

Is it possible to use the ZF2 forms a as standalone component? This was possible with ZF1, but I can't figure it out with ZF2.
I can create a form and a validator, but can't figure out how to render the form:
$form = new AddressBookForm('address_book'); \\ extends Zend\Form\Form
if ($this->input->isPost()) {
$validator = new AddressBookValidator(); \\ implements Zend\InputFilter\InputFilterAwareInterface
$form->setInputFilter($validator->getInputFilter());
$form->setData($this->input->getPost());
if ($form->isValid()) {
echo 'valid'; exit;
}
}
// Render form somehow here???
I tried creating a view, but couldn't figure out how to give it the view helpers. Thanks.
I have a basic solution, that seems to do the job
$zfView = new \Zend\View\Renderer\PhpRenderer();
$plugins = $zfView->getHelperPluginManager();
$config = new Zend\Form\View\HelperConfig;
$config->configureServiceManager($plugins);
and then render the form
echo $zfView->form()->openTag($form);
echo $zfView->formRow($form->get('name'));
echo $zfView->formSubmit( $form->get('submit'));
echo $zfView->form()->closeTag();
Checkout this blog.
Form Render in View file
you can do simply by zend framework form view helper.
$form = $this->form;
$form->prepare();
$this->form()->render($form);
#CodeMonkey's method is a good one but the code is incomplete. I cobbled together a working example from his and other answers I found with partial code.
<?php
/*
* #author Carl McDade
*
* #since 2012-06-11
* #version 0.2
*
*/
namespace zftest;
$path = DOCROOT .'/_frameworks/zf/ZendFramework-2.2.2/library';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once($path . '/Zend/Loader/StandardAutoloader.php');
use Zend\Loader;
use Zend\Http\Request;
use Zend\Http\Client;
use Zend\Captcha;
use Zend\Form\Element;
use Zend\Form\Fieldset;
use Zend\Form\Form;
use Zend\Form\FormInterface;
use Zend\InputFilter\Input;
use Zend\InputFilter\InputFilter;
use Zend\Form\View\Helper;
use \Common;
class zftest{
function __construct()
{
spl_autoload_register(array($this, '_zftest_autoload'));
}
function _zftest_autoload($class)
{
//
$loader = new \Zend\Loader\StandardAutoloader(array('autoregister_zf' => true));
$loader->registerNamespaces(array('Zend'));
// finally send namespaces and prefixes to the autoloader SPL
$loader->register();
return;
}
function zftest()
{
$uri = 'http://maps.google.com/maps/api/geocode/json';
$address = urlencode('berlin');
$sensor = 'false';
$request = new Request();
$request->setUri($uri);
$request->setMethod('GET');
$client = new Client($uri);
$client->setRequest($request);
$client->setParameterGet(array('sensor'=>$sensor,'address'=>$address));
$response = $client->dispatch($request);
if ($response->isSuccess()) {
print 'Your Request for:<pre>' . print_r($address, 1) . '</pre>';
print '<pre>' . print_r($response->getBody(), 1) . '</pre>';
}
}
function zfform()
{
// Zend Framework 2 form example
$name = new Element('name');
$name->setLabel('Your name');
$name->setAttributes(array(
'type' => 'text'
));
$email = new Element\Email('email');
$email->setLabel('Your email address');
$subject = new Element('subject');
$subject->setLabel('Subject');
$subject->setAttributes(array(
'type' => 'text'
));
$message = new Element\Textarea('message');
$message->setLabel('Message');
$captcha = new Element\Captcha('captcha');
$captcha->setCaptcha(new Captcha\Dumb());
$captcha->setLabel('Please verify you are human');
$csrf = new Element\Csrf('security');
$send = new Element('send');
$send->setValue('Submit');
$send->setAttributes(array(
'type' => 'submit'
));
$form = new Form('contact');
$form->add($name);
$form->add($email);
$form->add($subject);
$form->add($message);
$form->add($captcha);
$form->add($csrf);
$form->add($send);
$nameInput = new Input('name');
// configure input... and all others
$inputFilter = new InputFilter();
// attach all inputs
$form->setInputFilter($inputFilter);
$zfView = new \Zend\View\Renderer\PhpRenderer();
$plugins = $zfView->getHelperPluginManager();
$config = new \Zend\Form\View\HelperConfig;
$config->configureServiceManager($plugins);
$output = $zfView->form()->openTag($form) . "\n";
$output .= $zfView->formRow($form->get('name')) . "<br />\n";
$output .= $zfView->formRow($form->get('captcha')) . "<br />\n";
$output .= $zfView->formSubmit( $form->get('send')) . "<br />\n";
$output .= $zfView->form()->closeTag() . "\n";
echo $output;
}
}
?>
You can use the Zend\Form\View\Helper view helpers to render the form inside a view.
Example: (view context)
My Form:
<?php echo $this->form()->openTag($this->form); ?>
<?php echo $this->formCollection($this->form); ?>
<?php echo $this->form()->closeTag($this->form); ?>
Note that $this->form is the $form variable assigned to the view. Also, view helpers are always available in views as far as they are registered as invokables (this is always true for built-in helpers).
This would render all elements inside a <form ...> ... </form> tag.
Check the other view helpers for further information.
Also, see the example docs: http://zf2.readthedocs.org/en/latest/modules/zend.form.quick-start.html
There's a lot more you can do with this.
None of the simpler answers helped me since I did not have Service Manager set up nor the View Helper methods.
But in a hurry this worked for me:
$checkbox = new Element\Checkbox('checkbox');
$checkbox->setLabel('Label');
$checkbox->setCheckedValue("good");
$checkbox->setUncheckedValue("bad");
$form = new FormCheckbox();
echo $form->render($checkbox);