PHP code function not working properly - php

I have a PHP file where I use the following PHP code to access my DB to retrieve some data to create a geojson. It does return a geojson but all html etc is exluded when i call this function.
<?php
require_once("db.php");
$geo = connectToDB::getGeoJSON();
?>
This is the function im calling from another a db.php file.
public static function getGeoJSON() {
$db_connection = new mysqli(mysqlServer, mysqlUser, mysqlPass, mysqlDB);
$statement = $db_connection->prepare("Select poiId, lat,lng,description from poi");
$statement->bind_result( $id, $lat, $lng, $description);
$statement->execute();
$feature = array();
$geojson = array(
'type' => 'FeatureCollection',
'features' => $feature
);
while ($statement->fetch()) {
$feature = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => array($lng, $lat)
),
'properties' => array(
'description' => $description
//Other fields here, end without a comma
)
);
array_push($geojson, $feature);
}
$statement->close();
$db_connection->close();
//Return routing result
header("Content-Type:application/json",true);
return $geojson;
}
Can anyone see whats wrong with the code? It does return the correct output but then the rest of the page wont show. Other functions I call is working normally so its the geojson function something is wrong with.

Related

Upload CSV File in Admin Controller - Custom module

I'm trying to create an Admin Controller with a csv file uploader to process it like an array.
I can't find an efficient way to do it, I tried to use $this-> fields_form, but nothing is showing up.
Then I did a tpl file with an input file, called in initContent, but I don't know how to retrieve my file in the controller.
I need to create multiple object of different classes that I made, thanks to the csv file.
Does somebody have some documentation that could help me, I've already search through prestashop dev doc, stack overflow, ect but I've didn't see anything that could help me (maybe I didn't search the good way ?)
Waiting for your help guys !
Update :
Update :
Just found a way to upload my file, but it's upload as .tmp and can't be processed as a csv file, how can I convert a tmp file to a csv ?
Here is my code :
public function __construct()
{
parent::__construct();
// Base
$this->bootstrap = true; // use Bootstrap CSS
$this->fields_options = array(
'general' => array(
'title' => $this->l('Upload DB'),
'fields' => array(
'DB_BULB_DATA' => array(
'title' => $this->l('Upload DB'),
'type' => 'file',
'name' => 'DB_BULB_DATA'
),
),
'submit' => array('title' => $this->trans('Save', array(), 'Admin.Actions')),
),
);
if(isset($_FILES['DB_BULB_DATA'])){
$headers = fgetcsv(fopen($_FILES['DB_BULB_DATA']['tmp_name'], "r+"));
print_r($headers);
}
}
There is no file type name csvfile , you need to use filed type file and then hadel the csv file after upload, check file extension then process the data.
Just find out how to do it, I feel dummy 😅
I just needed to save my tmp file as a csv to be able to use it then.
Here is the full code :
<?php
class Admin<YourModuleName>Upload<YourThings>DatabaseController extends ModuleAdminController
{
public function __construct()
{
parent::__construct();
// Base
$this->bootstrap = true; // use Bootstrap CSS
$this->name = "Admin<YourModuleName>Upload<YourThings>Database";
$this->fields_options = array(
'general' => array(
'title' => $this->l('Upload DB'),
'fields' => array(
'DB_<YourThings>_DATA' => array(
'title' => $this->l('Upload DB'),
'type' => 'file',
'name' => 'DB_<YourThings>_DATA'
),
),
'submit' => array('title' => $this->l('Save')),
),
);
}
public function initContent()
{
parent::initContent();
unset($_FILES);
}
public function postProcess()
{
$fileName = '<YourThings>Db.csv';
if (!file_exists(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName)) {
if (isset($_FILES['DB_<YourThings>_DATA'])) {
$tmpPath = $_FILES['DB_<YourThings>_DATA']["tmp_name"];
move_uploaded_file($tmpPath, _PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName);
$uploadCsv = file(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName, FILE_SKIP_EMPTY_LINES);
$Db = array_map("str_getcsv", $uploadCsv, array_fill(0, count($uploadCsv), ';'));
$keys = array_shift($Db);
foreach ($Db as $i => $row) {
$Db[$i] = array_combine($keys, $row);
}
print_r($Db);
}
} else {
$uploadCsv = file(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName, FILE_SKIP_EMPTY_LINES);
$Db = array_map("str_getcsv", $uploadCsv, array_fill(0, count($uploadCsv), ';'));
$keys = array_shift($Db);
foreach ($Db as $i => $row) {
$Db[$i] = array_combine($keys, $row);
}
print_r($Db);
}
unset($_FILES['DB_<YourThings>_DATA']);
}
}

Prestashop WebService API - save in database HTML rich text

I am developing a php manager for prestashop via webservice. I have a module created to keep notes about orders.
From the management program I have a form with TinyMCE. But I can't save the text when it has HTML tags
webService class in prestashop module
class sellerNotas extends ObjectModel {
public $id;
public $id_seller;
public $nota;
public static $definition = array(
'table' => 'seller_notas',
'primary' => 'id',
'fields' => array(
'id' => array('type' => self::TYPE_INT),
'id_seller' => array('type' => self::TYPE_INT),
'nota' =>array('type' => self::TYPE_HTML, 'lang' => false, 'validate' => 'isCleanHtml'),
)
);
protected $webserviceParameters = array();
}
MySQL TABLE
I have no problem saving plain text without labels, the problem is when the text has labels.
I have tried htmlentities with no correct results.
create note php function
Please make sure you have used CDATA for that HTML node so it not get break due to any any component
$node = dom_import_simplexml($resources ->nota);
$no = $node -> ownerDocument;
$node -> appendChild($no -> createCDATASection($nota));
$resources ->nota= $nota;
SOLVED WITH htmlentities PHP CODE:
static function nuevaNota($idVendedor, $nota, $tienda) {
try{
$webService = webService::webServiceTienda($tienda);
$opt = [
'resource' => 'seller_notas?schema=blank'
];
$xml = $webService->get($opt);
$resources = $xml->seller_notas->children();
$resources->id_seller = intval($idVendedor);
$resources->nota = htmlentities($nota);
var_dump( $resources->nota);
$opt = [
'resource' => 'seller_notas',
'postXml' => $xml->asXML(),
];
$createdXml = $webService->add($opt);
}
catch (PrestaShopWebserviceException $e){
webService::controlErroresTienda($e, $tienda);
}
}

POST request in PHP is returning PHP code when file extension is used

I am sending post requests in PHP to get a boolean value from my API (so it should return wither true or false)
This is the code I am using in the file for my API. The file is called users.php
if ($_POST['type'] == "authenticateMinecraft"){
$p = new dibdibs\post(
array(
'url' => 'https://authserver.mojang.com/authenticate',
'data' => array(
'agent' => array(
'name' => 'Minecraft',
'version' => 1
),
'username' => $_POST['username'],
'password' => $_POST['password'],
'clientToken' => "33225A179D9A4E1BDA73C012C1C3CBAB8BD00326883BDBEB6FA682482E40F68D"
)
)
);
$res = $p->json();
if (isset($res["selectedProfile"])){
echo("true");
}
else{
echo("false");
}
}
This is the code I am using to reference it (I am using a class which I have put on Pastebin to actually send the request).
$params = array(
'data' => array(
'type' => 'authenticateMinecraft',
'username' => $mcuname,
'password' => $mcpasswd
),
'url' => "api/users.php"
);
$c = new dibdibs\post($params);
$r = $c->http();
var_dump($r);
Whenever I use the .php fule extension when defining url, the whole PHP code of the API page is returned, but when I remove the extension, only true or false is returned. Why is this and is it a problem that I should be aware of and I should fox?

Prestashop error "invalid security token"

im creating a new module for prestashop 1.5.6 and im having some problems with it.
The module has to send sms to the costumers and it has to be an option of the back-Office menu.
I have created the module with the install and uninstall functions and added the tabs to the back-office menu, but im a newbie in prestashop so i don´t know how to make the AdminMyModuleController.php and when i try to click the tab of the module it says "INVALID SECURITY TOKEN", i don´t know how resolve this issue because i don´t know much of security.
If someone can add me on facebook or whatever to help me would be amazing.
Here is the code of the mymodule.php:
private function _createTab()
{
// Tab Raiz
$data = array(
'id_tab' => '',
'id_parent' => 0,
'class_name' => 'Empty',
'module' => 'mymodule',
'position' => 14, 'active' => 1
);
/* Insert the data to the tab table*/
$res = Db::getInstance()->insert('tab', $data);
//Get last insert id from db which will be the new tab id
$id_tabP = Db::getInstance()->Insert_ID();
//Define tab multi language data
$data_lang = array(
'id_tab' => $id_tabP,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'SMS a clientes'
);
// Now insert the tab lang data
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
// Tab Configuracion
$data = array(
'id_tab' => '',
'id_parent' => $id_tabP,
'class_name' => 'AdminMymodule',
'module' => 'mymodule',
'position' => 1, 'active' => 1
);
$res = Db::getInstance()->insert('tab', $data);
$id_tab = Db::getInstance()->Insert_ID();
$data_lang = array(
'id_tab' => $id_tab,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'Configuracion'
);
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
// Tab Enviar Sms
$data = array(
'id_tab' => '',
'id_parent' => $id_tabP,
'class_name' => 'AdminEnviar',
'module' => 'mymodule',
'position' => 1, 'active' => 1
);
$res = Db::getInstance()->insert('tab', $data);
$id_tab = Db::getInstance()->Insert_ID();
$data_lang = array(
'id_tab' => $id_tab,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'Enviar SMS'
);
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
return true;
}
Thanks
As Lliw said, you must use InstallModuleTab function.
private function installModuleTab($tabClass, $tabName, $idTabParent)
{
$pass = true;
$tab = new Tab();
$tab->name = $tabName;
$tab->class_name = $tabClass;
$tab->module = $this->name; // defined in __construct() function
$tab->id_parent = $idTabParent;
$pass = $tab->save();
return($pass);
}
You can put all in your Install function. For example for your first tab:
public function install()
{
if(!parent::install()
|| !$this->installModuleTab('Empty', array(1 => 'SMS a clientes'), $idTabParent = 0))
return false;
return true;
}
You can set languages with the following array:
array(1 => 'SMS a clientes', 2 => 'Language 2', 3 => 'Language 3')
Then you must create the AdminMyModuleController.php file
It's the wrong way to create a module tab. You should use this function in your install() :
$this->installModuleTab('AdminMyModule', array(1 => 'Attribute description'), $idTabParent = 9);
Then create an AdminMyModuleController.php in your module folder/controllers/admin/AdminMyModuleController.php
But you will need to set some function to see something displayed, i'll make a tutorial for that but until i do it, you can look in another admincontroller from the prestashop core and do the same.

Building a valid dynamic RSS feed using PHP that passes variables via GET

Is it possible to create a valid dynamic RSS feed that passes a variable containing values that would be used to build a MySQL query and return the result as a feed?
This code will generate a feed:
<?php
$dbh = new PDO('mysql:host=127.0.0.1;dbname=local', 'local', 'local');
$sql = 'SELECT * FROM table_name';
$open = <<<XMLHEAD
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="../_src/css/rss.css" ?>
<rss version="2.0">
<channel>
<title>Test</title>
<description>Test</description>
<lastBuildDate>2011-05-20</lastBuildDate>
<pubDate>2011-05-20</pubDate>
XMLHEAD;
echo $open;
// item
foreach ($dbh->query($sql) as $row)
{
echo $row['col1'] . ' ' . $row['col2'];
}
$dbh->exec();
$dbh = null;
$close = <<<XMLFOOT
</channel>
</rss>
XMLFOOT;
echo $close;
header("Content-Type: application/rss+xml; charset=UTF-8");
?>
I just need to be able to pass something like http://localhost/feed.php?date=20110520
So that I can build this:
$d = $_POST['date'];
// Validate/clean here then set value
$date = $d;
$sql = 'SELECT * FROM table_name' where date=' . ''' . $date . ''';
Thanks!
Yes. RSS is just a data format like any other.
Your pseudo-code is vulnerable to SQL injection though, and you should build XML files using an XML library not by mashing strings together.
You can use Zend_Filter_Input to prevent sql injections
enter code here
$filters = array(
'page' => array('HtmlEntities', 'StripTags', 'StringTrim'),
'name' => array('HtmlEntities', 'StripTags', 'StringTrim'),
'val' => array('HtmlEntities', 'StripTags', 'StringTrim'),
'do' => array('HtmlEntities', 'StripTags', 'StringTrim'),
'obj' => array('HtmlEntities', 'StripTags', 'StringTrim')
);
$validators = array(
'page' => array('Int'),
'name' => array(),
'val' => array(),
'do' => array(),
'obj' => array()
);
/* array('InArray', array('add', 'clear')), */
$input = new Zend_Filter_Input($filters, $validators);
$input->setData($this->getRequest()->getParams());`
You can also use Zend_Feed to generate feed from array
foreach ($result as $r) {
$output['entries'][] = array(
'title' => $r['name'],
'link' => $this->apiBaseUrl.$r['name'].".mp3",
'description' => $answers,
'lastUpdated' => ''
);
} $feed = Zend_Feed::importArray($output, 'atom'); $feed->send();

Categories