Geoserver Rest API update workspace name - php

I am trying to update workspace name through geoserver rest api using put method.
I am getting "Can't change the name of a workspace." error.
This is my code.
$service = geoserver_url;
$data = "<workspace><name>testnew</name></workspace>";
$url = $service . "rest/workspaces/workspacename";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$passwordStr = username:password
curl_setopt($ch, CURLOPT_USERPWD, $passwordStr);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/xml"););
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
Any kind of help appreciated.

That is not an allowable operation (as mentioned in the manual). Any PUT that changes the name of a workspace returns a 403 Error.
All you can do is create a new workspace, copy the contents of the old one and then delete it.

According to geoserver REST API documentations (link), you can simply edit workspace name (ws_name) by putting a request which has an xml string data in its body.
Here I've given you an example. Because of using Express as my application sever I've implemented a request using javascript but it can be changed to your favorite syntax.
const options = {
url: 'http://localhost:8080/geoserver/rest/workspaces/{current_ws_sname}',
method: 'PUT',
headers: { 'Content-type': 'text/xml' },
body: '<workspace><name>{new_ws_name}</name></workspace>',
auth: {
user: {geoserver_username},
pass: {geoserver_password}
}
and for executing the request based on above option variable I've used request function in Express:
request(options, (error, response, body) => {
console.log('response status code:' , response.statusCode)
console.log('response status message: ', response.statusMessage)
const result = {}
if (!error) {
const statusCode = response.statusCode;
const statusMessage = response.statusMessage;
if (statusCode == 200) {
result.err = false
result.msg = `Modified`
} else if (statusCode == 404) {
result.err = true
result.msg = 'Workspace not found!'
} else if (statusCode == 405) {
result.err = true
result.msg = 'Forbidden to change the name of the workspace!'
//because of your username and/or password
} else if (statusCode == 500) {
result.err = true
result.msg = 'Server internal error or duplicate names'
}
} else {
result.err = true,
result.msg = error;
}
res.send(result);
})
Don't forget to replace {current_ws_sname}, {new_ws_sname}, {geoserver_username}, {geoserver_password} by your own values.
All the possible situations have been mentioned as above (i.e. 200, 404, 405, 500) and there is no error message like "Can't change the name of a workspace." in geoserver documentations!
What statusCode and statusMessage do you get in response? Can you confirm that your {new_ws_sname} isn't duplicate?

Related

PHP Curl after execution does not return back to Ajax Request

I was integrating a PHP code to ping sitemap to google and Bing. The code executed perfectly but to be a fact if i'm initiating the request from a ajax call. It does not return back
Below is the Jquery code i'm using to make ajax call
$("body").on('click', 'button#sitemap_google_submit', function(event){
toastr.info("Would require few seconds, Please wait, do not refresh Page..",
"Submitting Sitemap to Google!",
{ progressBar:!0,
showMethod:"slideDown",
hideMethod:"slideUp",
timeOut:2e3,
preventDuplicates: true,
positionClass: "toast-bottom-right"
}
);
$("button#sitemap_google_submit").attr("disabled", true);
$("button#sitemap_google_submit").html("<i class='ft-loader spinner'></i> Submitting to Google..");
$.ajax({
url: '/bypasser/modules/seoController.php',
type: 'POST',
dataType: 'JSON',
data: {type: 'submit', console: 'google'},
})
.done(function(resp) {
$("button#sitemap_google_submit").attr("disabled", false);
$("button#sitemap_google_submit").html("<i class='fa fa-google fa-lg'></i> Submit to Google");
toastr[resp.type](resp.message,
resp.heading,
{ showMethod:"slideDown",
hideMethod:"slideUp",
preventDuplicates: true,
positionClass: "toast-bottom-right"
});
});
});
on PHP side i'm using below request
<?php
include("appController.php");
$reqType = preg_replace("/[^a-zA-Z]/", "", $_REQUEST['type']);
class seoController Extends appController
{
public function submitGoogle($url)
{
$url = "http://www.google.com/webmasters/sitemaps/ping?sitemap=".$this->websiteBaseURL().$url;
$returnCode = $this->myCurl($url);
if($returnCode == 200) {
echo json_encode(array("type" => "success",
"heading" => "Success!",
"message" => "Sitemap Submitted to Google!!")
);
}else{
echo json_encode(array("type" => "warning",
"heading" => "Warning!",
"message" => "Problem occured while submitted SiteMap, try again after Sometime!"
)
);
}
}
function myCurl($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER , true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpCode;
}
}
$seoController = new seoController();
if($reqType == "submit" &&
preg_replace("/[^a-z]/", "", $_POST['console']) == "google")
$seoController->submitGoogle("sitemap.xml");
?>
The JSON encodes displays perfectly in the preview panel of network tab of inspect element, but somehow it does not return the response to ajax, what is the issue?
Set
curl_setopt($ch, CURLOPT_HEADER , false); // we don't want headers
instead of
curl_setopt($ch, CURLOPT_HEADER , true); // we want headers
we don't want the headers as well, as far a i understand your question, you may be looking for ping status code only!

Search FB Messenger Message for Specific Word in PHP

So I'm trying to create a Facebook Messenger Chatbot, a very simple one. I have it working with a hardcoded response, but I want it to be able to read the senders message and respond in a specific way if it finds that word - like how chatbots should. I' trying to do so by using preg_match() but when I use my current code, the bot doesn't reply at all. Here's my code:
<?php
/**
* Webhook for Facebook Messenger Bot
*/
$access_token = "{mytoken}";
$verify_token = "{mytoken2}";
$hub_verify_token = null;
if (isset($_REQUEST['hub_challenge'])) {
$challenge = $_REQUEST['hub_challenge'];
$hub_verify_token = $_REQUEST['hub_verify_token'];
}
if ($hub_verify_token == $verify_token) {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
// perform a case-Insensitive search for the word "time"
if (preg_match('[hi|hello|sup]', $message)) {
$answer = "Hiya!";
}
else {
$answer = "IDK.";
}
// send the response back to sender
// 'text': 'Hiya!'
$jsonData = "{
'recipient': {
'id': $sender
},
'message': {
'text': $answer
}
}";
// initiate cURL.
$ch = curl_init("https://graph.facebook.com/v2.6/me/messages?access_token=$access_token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
if (!empty($input['entry'][0]['messaging'][0]['message'])) {
curl_exec($ch);
}
Do you know whether you actually receive messages from the Messenger Platform? Your webhook verification ends in an echo, where in fact you need to respond to the platform with a status code 200. You can also check your Facebook Apps dashboard to figure out whether your webhook is verified and being sent messages.
Documentation: https://developers.facebook.com/docs/messenger-platform/getting-started/webhook-setup
Once you know that your webhook is verified and you are receiving messages, start with a fixed reply and then work towards dynamic responses. As #Toto suggested, adding logging will be very helpful to debug your code.

Telegram webhook php bot doesn't answer

I'm trying to set up a telegram bot with a webhook. I can get it to work with getUpdates, but I want it to work with a webhook.
My site (that hosts the bot php script) has the SSL certificate working (I get the green lock in the address bar):
I set up the webhook with
https://api.telegram.org/bot<token>/setwebhook?url=https://www.example.com/bot/bot.php
And I got: {"ok":true,"result":true,"description":"Webhook was set"}
(I don't know if this matters, but I have given rwx rights to both the folder and the script)
The php bot: (https://www.example.com/bot/bot.php)
<?php
$botToken = <token>;
$website = "https://api.telegram.org/bot".$botToken;
#$update = url_get_contents('php://input');
$update = file_get_contents('php://input');
$update = json_decode($update, TRUE);
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
switch($message) {
case "/test":
sendMessage($chatId, "test");
break;
case "/hi":
sendMessage($chatId, "hi there!");
break;
default:
sendMessage($chatId, "default");
}
function sendMessage ($chatId, $message) {
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chatId."&text=".urlencode($message);
url_get_contents($url);
}
function url_get_contents($Url) {
if(!function_exists('curl_init')) {
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
?>
But when I write anything to the bot I receive no answers...
Any ideas why?
Thanks
In your question it's not clear the script location. Seeing your code, it seems that you try to load a request through url_get_contents to retrieve telegram server response. This is the correct method if your bot works without webhook. Otherwise, after setting webhook, you have to process incoming requests.
I.e., if you set webhook to https://example.com/mywebhook.php, in your https://example.com/mywebhook.php script you have to write something like this:
<?php
$request = file_get_contents( 'php://input' );
# ↑↑↑↑
$request = json_decode( $request, TRUE );
if( !$request )
{
// Some Error output (request is not valid JSON)
}
elseif( !isset($request['update_id']) || !isset($request['message']) )
{
// Some Error output (request has not message)
}
else
{
$chatId = $request['message']['chat']['id'];
$message = $request['message']['text'];
switch( $message )
{
// Process your message here
}
}

libcurl sending post to php on server (online services with POST), server sees nothing

Pretty basic problem, but im not sure what else to do.
From the code processing my curl request and executing it:
ResponseData Request::exec()
{
CURLcode res = CURL_LAST;
CURL *h = curl_easy_init();
ResponseData response;
if(h) {
curl_easy_setopt(h, CURLOPT_URL, getURL().c_str());
curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, handle_data);
switch(this->_type) {
default:
case TYPE_GET:
printf("sending get");
break;
case TYPE_POST:
printf("sending post");
curl_easy_setopt(h, CURLOPT_POST, 1);
break;
case TYPE_PUT:
printf("sending put");
curl_easy_setopt(h, CURLOPT_PUT, 1);
break;
case TYPE_DELETE:
curl_easy_setopt(h, CURLOPT_CUSTOMREQUEST, "DELETE");
break;
}
//printf("%d", postData.size());
if(postData.size() > 0) {
string post;
int it = 0;
for each (postDataItem var in postData)
{
it++;
//printf("\n[]Key: %s, Value: %s", var.key, var.value);
post.append(var.key);
post.append("=");
post.append(var.value);
if(it != postData.size()) {
// dont append & if last element
post.append("&");
}
}
const char * postString = post.c_str();
const char * postUrl = curl_easy_escape(h, postString, 0);
printf("\npayload: %s\n\n", postUrl);
curl_easy_setopt(h, CURLOPT_POSTFIELDS, postUrl);
}
res = curl_easy_perform(h);
switch(res)
{
case CURLE_WRITE_ERROR:
break;
case CURLE_OK:
response.setData(contents.c_str());
break;
}
curl_easy_cleanup(h);
return response;
} else {
printf("Could not initialize curl");
}
}
The data that im sending at the moment as that POSTFIELDS is:
username%3DDuke%26password%3DNukem
and when i use WireShark to see whats going on
Message: POST /api/account/login HTTP/1.1
Request Method: POST
Request URI: /api/account/login
Request Version: HTTP/1.1
Host: [url redacted, not important]
Line-based text data: application/x-www-form-urlencoded
username%3DDuke%26password%3DNukem
So as far as I can tell, i am sending what would be a normal POST from, for example, an HTML form, right?
On the server side on that url, is a basic no logic php script that looks like this:
<?
print("GET");
var_dump($_GET);
print("POST");
var_dump($_POST);
print("REQUEST");
var_dump($_REQUEST);
What i see in my console as output?
GETarray(0) {
}
POSTarray(0) {
}
REQUESTarray(0) {
}
Soo... im not sure what im doing wrong.... is my C++ curl request missing something to send to the server properly?
Was a simple scope issue!
Two ways to solve this issue:
Instead of:
if(postData.size() > 0) {
string post;
int it = 0;
I needed:
if(postData.size() > 0) {
static string post;
int it = 0;
or declare string post; below ResponseData response;

Openlayers- the server responded with a status of 401 (Unauthorized

I am doing the Map Project on Plain Openlayes on WMS. The local server is Debian_x64 on Oracle Virtual Box and the Map Server is National Land Survey Finland. The requests and polls examples are available here http://www.maanmittauslaitos.fi/aineistot-palvelut/rajapintapalvelut/rasteriaineistojen-palvelurajapinta-wms/kayttoonotto/kyselyt-es. I have successfully completed the GetCapabilities request and got the XML response. On the basis of that XML response I tried to get the Map Layers with GetMap. The Map parameters are assigned according to the XML response I got now the problems I have are
There are the parameters on BoundingBox “ resx and resy” , Do I need to utilize them for what I'm doing, and if so, how?
I monitored the console on Chrome developer tool and it responded with the following error:
Failed to load resource: the server responded with a status of 401 (Unauthorized) https://ws.nls.fi/rasteriaineistot/image?LAYERS=yleiskartta_12m&VERSION=1.1.1&FORMAT=image%2Fpng&REQUEST=GetMap&TRANSPARENT=FALSE&STYLES=light&SERVICE=WMS&SRS=EPSG%3A4326&BBOX=0,45,45,90&WIDTH=256&HEIGHT=256
...at the same time pink tiles are loading. I have used the Php cURL proxy “proxy.php” for HTTPS basic authentication with username and password,that is in the same folder where there are Openlayers.js , style.css and index.php . Now is it possible that the proxy I am assigning is not working as it should be? or there may be some same origin policy matter ? My username and password are valid. How can I fix this problem? It will be very helpful if someone provide the code examples.
My proxy.php file is as follows:
$string = $_GET['url'];
$urli = urldecode($string);
$url = $urli;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD,"user:pass");
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
$type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$im = imagecreatefromstring($data);
if ($type == "image/jpeg") {
header('Content-Type: image/jpeg');
imagejpeg($im);
} else if ($type == "image/png") {
header('Content-Type: image/png');
imagepng($im);
} else if ($type == "image/gif") {
header('Content-Type: image/gif');
imagegif($im);
} else if ($type == "text/xml") {
header('Content-Type: text/xml');
print_r($data);
}
imagedestroy($im);
curl_close($ch);
exit;
and the index.php is as following
function init() {
var map = new OpenLayers.Map('map',options)
var request = OpenLayers.Request.GET({
url:"https://ws.nls.fi/rasteriaineistot/image?",
params: {service:"WMS",
version:"1.1.1",
format:"text/xml",
request:"GetCapabilities"},
proxy: "queryboth.php?url=",
async: false,
callback: handler
} );
function handler(request) {
console.log(request);
// alert(request.responseText);
// alert(request.status);
// alert(request.getAllResponseHeaders());
}
// Here I set my ProxyHost could it be some mistake here
OpenLayers.ProxyHost = "proxy.php?url=";
var layer = new OpenLayers.Layer.WMS("yleiskartta",
"https://ws.nls.fi/rasteriaineistot/image?",
{
layers: "yleiskartta_12m",
version:"1.1.1",
format: "image/png",
request: "GetMap",
transparent: false,
styles:"light"
},
{
isBaseLayer: true,
opacity: 1
}
);
var options = {
sphericalMercator: true,
projection: new OpenLayers.Projection("EPSG:3067"),
maxExtent: new OpenLayers.Bounds(-380688,6247443,1347312,8227443),
minScale: 2121.32,
maxScale: 8485.28,
units: "m",
numZoomLevels: 6
};
map.addLayers([layer]);
map.zoomToMaxExtent();
map.addControl( new OpenLayers.Control.LayerSwitcher() );
}
and the response of one layers in xml is as follows ( sorry I removed the tags ):
Layer opaque="1"
Name:yleiskartta_12m
Title : Yleiskarttarasteri 1:12 milj
LatLonBoundingBox minx="1.21" miny="55.57" maxx="51.93" maxy="71.79"
BoundingBox SRS="EPSG:3067" minx="-380688" miny="6247443" maxx="1347312" maxy="8227443" resx="1500.0" resy="1500.0"
BoundingBox SRS="EPSG:2393" minx="2619125.63" miny="6250068.42" maxx="4347827.2" maxy="8147483.65" resx="1500.0" resy="1500.0"
ScaleHint min="2121.32" max="8485.28"
</Layer>
</pre>

Categories