I have component called mycomponent
models
paypal.php
controllers
paypal.php
views
paypal
view.html.php
index.html
tmpl(folder)
default.php
index.html
In controller i have this code
<?php
// No direct access.
defined('_JEXEC') or die;
jimport('joomla.application.component.controlleradmin');
/**
* Objectdefects list controller class.
*/
class MycomponentControllerPaypal extends JControllerAdmin
{
public function paypaldetails()
{
$model = $this->getModel('paypal');
// Get token
$token = urlencode(htmlspecialchars(JRequest::getVar('token')));
if (!$token)
{
// Missing $token parameter
$app = JFactory::getApplication();
$app->enqueueMessage(JText::_('COM_INSTALLER_MSG_MISSING_TOKEN'));
}
else
{
// Install plugin
$model->paypaldetails($token);
}
}
}
In model i have this fragment of code
public function paypaldetails($token){
$environment= $this->environment;
// Add request-specific fields to the request string.
$nvpStr = "&TOKEN=$token";
// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = $this->PPHttpPost('GetExpressCheckoutDetails', $nvpStr);
//var_dump($httpParsedResponseAr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
$paypaldetails=array();
$paypaldetails["firstname"]= $httpParsedResponseAr['FIRSTNAME'];
$paypaldetails["lastname"] = $httpParsedResponseAr["LASTNAME"];
$paypaldetails["countrycode"] = $httpParsedResponseAr["COUNTRYCODE"];
$this->paypaldetails=$paypaldetails;
$a=$this->paypaldetails;
var_dump($a);
} else {
exit('GetExpressCheckoutDetails failed: ' . print_r($httpParsedResponseAr, true));
}
}
In view/template/default.php i have this
<?php
// no direct access
defined('_JEXEC') or die;
// Import CSS
$document = JFactory::getDocument();
$document->addStyleSheet('components/com_mycomponent/assets/css/defects.css');
$results = $this->items;
var_dump($results);
echo 'Firstname: '.$results[firstname];
echo '<br>Lastname: '.$results[lastname];
echo '<br>Countrycode: '.$results[countrycode];
When i run this url index.php?option=com_fewostar&view=paypal&task=paypal.paypaldetails&token=EC-92L7275685367793U&PayerID=TGWAUKNJLH2WL
I view first var_dump($a); located on model, but second var_dump($results); located in views/paypal/tmpl/default.php not display, and field in view not display. for any reason this url not call view. When i run this url index.php?option=com_fewostar&view=paypal code without task, view is display. but for this url
index.php?option=com_fewostar&view=paypal&task=paypal.paypaldetails&token=EC-92L7275685367793U&PayerID=TGWAUKNJLH2WL no display view. How i call view for this task, may be i need other view file, different of default.php?
I see a couple of problems here.
First, the code is not exactly using Joomla MVC style (even if it works for you, might be harder for people familiar with Joomla to debug).
Model method should be called getPaypaldetails and return something
public function getPaypaldetails()
{
// For Joomla 1.7+ use JInput instead of JRequest (deprecated)
$token = JFactory::getApplication()->input->getVar('token');
// some code
return $paypaldetails;
}
view.html.php should and get and data from model and assign to itself
public function display($tpl = null)
{
// Get some data from the models
$items = $this->model->get('paypaldetails');
// If data are incorrect, show nice error message
// ...
$this->items = $items;
}
View Layout file should be placed in /com_fewostar/views/paypal/tmpl/default.php
By default, the view is only called by the "display" task (which is the default task). Since you use your own task, you need to either redirect to the view after your task is finished or try to load the display function at the end.
Related
I'm using Cakephp with json parse extension and the RequestHandler component in order to create Web services using json.
I created a controller named Ws
In this controller I have a named userSubscribe
In order to avoid a lot of If else statements in the next methods, I thought about using a private function inside this controller that will check somes conditions and stop the script normaly BUT ALSO render the json normaly. I just want to do a DRY way !
My question is :
How could I render the json view in a sub function (called by the userSubscribe) ?
To make it clear, here is the style code that would like
public function userSubscribe() {
$this->check();
// Following code only executed if check didn't render the json view
// $data = ...
$code = 1;
$i = 2;
}
private function check() {
$input = &$this->request->data;
if ($_SERVER["CONTENT_TYPE"] != "application/json") { // For example
$result = "KO";
$this->set(compact("result"));
$this->set('_serialize', 'result');
$this->render(); // HERE, it will stop the 'normal behaviour' and render the json with _serialize
}
if (!isset($input["input"])) {
$result = "KO";
$this->set(compact("result"));
$this->set('_serialize', 'result');
$this->render(); // HERE, it will stop the 'normal behaviour' and render the json with _serialize
}
}
It's seems to be quite simple to do, but why can't I find the answer ?!
Thanks in advance for clue/advise/anything !
I'm looking proper way to revert any given redirect command in ZF2 controller
For example in one of my function i use - $this->redirect()->toRoute('my/desire/path/to/redirect');
But after getting result I want to cancel that command and show something else to my user.
Here is my code to illustrate more precisely -
considering following method inside controller that will retrieve data for one id
public function getMyData(){
$idX = $this->params()->fromRoute('id');
$rtrn=$this->myTableGateway->getData($idX);
if($rtrn!==false){
$mnfctr['myData']=$rtrn;
$mnfctr['readMode']='yes';
return $mnfctr;
}else return $this->redirect()->toRoute('product-loader/sub-categories', array('cid'=>$this->mcep->id));
}
now in a real action inside controller
public function readAction(){
$data=$this->getMyData();
if($data instanceof \Zend\Http\PhpEnvironment\Response) return $data;
# do rest of the staff of read action
}
public function deleteAction(){
$data=$this->getMyData();
if($data instanceof \Zend\Http\PhpEnvironment\Response) return $data;
# do rest of the staff of delete action
}
now i want to show a logo of my company through the same controller
problem is if i simply redirect the logo should not draw properly
so i design my image action method as follows
public function logoAction(){
$logoFlName='Unknown Company';
$data=$this->getMyData();
#echo '$mnfctr: '.get_class($mnfctr); exit();
$response = $this->getResponse();
if($mnfctr instanceof \Zend\Http\PhpEnvironment\Response){
# in this situation i need to cancel my previous response command
$logoFlName='Invalid Company';
if($response->isRedirect()){
$this->flashMessenger()->clearCurrentMessages();
$response->getHeaders()->clearHeaders();
$response->setStatusCode(Response::STATUS_CODE_200);
}
}elseif(is_array($data) && array_key_exists('myData', $data) && $data['myData'] instanceof MyData){
# code to draw the real logo
$logoFlName='Logo of XYZ Company';
}else{ /* something wrong and can't be happen. but we really can't find logo */ }
$newImage=PLImageHelper::getLogoFromString($string2draw__not_found_image__or__logo);
$response->setContent($newImage->get('png'));
$response->getHeaders()
->addHeaderLine('Content-Transfer-Encoding', 'binary')
->addHeaderLine('Content-Type', 'image/png')
->addHeaderLine('Content-Disposition', 'filename="'.$logoFlName.'.png"')
#->addHeaderLine('Content-Length', mb_strlen($imageContent))
;
return $response;
}
I know there has a lot of way, suppose its possible to redirect to a real no-image-found.png file to show. but i want it programmatically
If you want to redirect the user to where the request is coming from you can use the following:
/** #var \Zend\Http\Request $request */
$request = $this->getRequest()
return $this->redirect()->toUrl($request->getHeaders()->get('referer')->getUri());
getUri() will return an url, for example: http://http://stackoverflow.com/posts/27318052/edit. Hope this helps.
Best possible way I get -
$response = $this->getResponse();
if($response->isRedirect()){
$response->getHeaders()->clearHeaders();
$response->setStatusCode(Response::STATUS_CODE_200);
}
Is there any other way to do it. I mean more efficient way that I can use.
I have a strange bug at the moment in my web service I am coding.
When I am loading an specific url I get a success and error at the same time?
This is what I have in my index.php:
<?php
require_once 'functions/lib.php';
require_once 'core/init.php';
// Ask for request URL that was submitted and define scriptPath. Explode content of REQUEST URL to evaluate validity.
$requestURL = (($_SERVER['REQUEST_URI'] != "") ? $_SERVER['REQUEST_URI'] : $_SERVER['REDIRECT_URL']);
$scriptPath = dirname($_SERVER['PHP_SELF']);
$requestURL = str_replace($scriptPath, "", $requestURL);
$requestParts = explode("/", $requestURL);
// Check for valid api version
$validAPIVersions = array("v1");
$apiVersion = $requestParts[1];
// If API Version not in valid API array return 404, else OK.
if (!in_array($apiVersion, $validAPIVersions)) {
httpResponseCode(404);
echo $GLOBALS['http_response_code'];
echo "<br>" . "API Version not valid";
exit();
}
// Check for valid API endpoint
$validEndPoints = array("tickets");
$endPoint = $requestParts[2];
if (!in_array($endPoint, $validEndPoints)) {
httpResponseCode(404);
echo $GLOBALS['http_response_code'];
echo "<br>" . "Endpoint not valid";
exit();
}
// get the endpoint class name
$endPoint = ucfirst(strtolower($endPoint));
$classFilePath = "$apiVersion/$endPoint.php";
if (!file_exists($classFilePath)) {
httpResponseCode(404);
echo $GLOBALS['http_response_code'];
exit();
}
// load endpoint class and make an instance
try {
require_once($classFilePath);
$instance = new $endPoint($requestParts);
} catch (Exception $e) {
httpResponseCode(500);
echo $GLOBALS['http_response_code'];
exit();
}
and this is the corresponding "Tickets.php"
<?php
echo "OK";
?>
In the last two rows of my index.php, I am loading the specific class (named in the URL). For testing purposes, I have an "echo "OK" in this file. And this is the result when I am loading the URL I need:
http://api.medifaktor.de/v1/tickets
OK
Fatal error: Class 'Tickets' not found in /usr/www/users/kontug/api.medifaktor.de/webservice/index.php on line 45
I get the OK I was expecting AND the error for the Class Tickets, that is not found. Line 45 is
$instance = new $endPoint($requestParts);
Can someone give me a helping hand?
Best
Sebastian
The problem is that you don't have a class "Tickets" defined. After you load the tickets.php file, you are attempting to instantiate a class. Loading a file is not the same thing as defining a class. Within tickets.php (or some other included file), you need to define the class, like so:
class Tickets
{
// some properties here
private $endpoint;
// some methods here
public function __construct($endpoint)
{
$this->endpoint = $endpoint;
}
}
If you're not sure how to construct classes in PHP, read the section in the manual on classes.
Update: I added some example code within the class for version PHP5+.
Try the following for your test, in the 'ticket.php' file add:
class Ticket {
public function __construct()
{
echo 'testing';
}
}
Then make sure you either namespace or require the file.
For which cases are these classes suitable? I've been trying to use both, but none of them works.
The component skeleton was generated, and there are CRUD operations in the administrator's side. I tried using JToolbarHelper from this generated code, like this in mycomponent/view.html.php:
// Overwriting JView display method
function display($tpl = null)
{
// Include helper submenu
InvoiceHelper::addSubmenu('invoice');
// Assign data to the view
$this->items = $this->get('Items');
$this->pagination = $this->get('Pagination');
// Check for errors.
if (count($errors = $this->get('Errors'))){
JError::raiseError(500, implode('<br />', $errors));
return false;
};
// Set the toolbar
$this->addToolBar();
// Show sidebar
$this->sidebar = JHtmlSidebar::render();
// Display the view
parent::display($tpl);
}
protected function addToolBar()
{
JLoader::register('JToolbarHelper', JPATH_ADMINISTRATOR.'/includes/toolbar.php');
$canDo = InvoiceHelper::getActions();
JToolBarHelper::title(JText::_('Invoice Manager'), 'invoice');
if($canDo->get('core.create')){
JToolBarHelper::addNew('invoic.add', 'JTOOLBAR_NEW');
};
if($canDo->get('core.edit')){
JToolBarHelper::editList('invoic.edit', 'JTOOLBAR_EDIT');
};
if($canDo->get('core.delete')){
JToolBarHelper::deleteList('', 'invoice.delete', 'JTOOLBAR_DELETE');
};
}
But it doesn't even appear on the page.
Then I came across this tutorial http://docs.joomla.org/J3.x:Using_the_JToolBar_class_in_the_frontend and it kindof works, except I can't imagine implementing something like a list of entities with checkboxes and operations for each. And it's unclear for me how to handle form submissions using this approach, seems like it happens through JS, do I get it right?
So, please tell, what's the difference and why doesn't the first approach even make the toolbar appear?
I know this is a long time ago, but I was looking to achieve the same result and found the following to loads the toolbar on the page. Using the above code:
protected function addToolBar()
{
JLoader::register('JToolbarHelper', JPATH_ADMINISTRATOR.'/includes/toolbar.php');
$canDo = InvoiceHelper::getActions();
JToolBarHelper::title(JText::_('Invoice Manager'), 'invoice');
if($canDo->get('core.create')){
JToolBarHelper::addNew('invoic.add', 'JTOOLBAR_NEW');
}
if($canDo->get('core.edit')){
JToolBarHelper::editList('invoic.edit', 'JTOOLBAR_EDIT');
}
if($canDo->get('core.delete')){
JToolBarHelper::deleteList('', 'invoice.delete', 'JTOOLBAR_DELETE');
}
$this->toolbar = JToolbar::getInstance(); // <<<---------- ADD THIS TO METHOD!
}
Then in your view do this:
<?php echo $this->toolbar->render(); ?>
Hope this helps!!! enjoy.
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.