Send JSON from HTTPS to HTTP - json

I use Request solution for ajax-request, but I get an error:
reqwest.min.js:6 Mixed Content: The page at 'https://...' was loaded
over HTTPS, but requested an insecure XMLHttpRequest endpoint
'http://...'. This request has been blocked; the content must be
served over HTTPS.
Server-side code (i'm using wordpress plugin for this):
add_action('wp_ajax_nopriv_wpse144893_search', 'wpse144893_search_data'); // allow logged out users
add_action('wp_ajax_wpse144893_search', 'wpse144893_search_data'); // allow logged in users
function wpse144893_search_data(){
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
$errors = array();
$data = array(
'status' => 'error',
'message' => '',
'result' => array()
);
if(!isset($_REQUEST['term']) || empty($_REQUEST['term']))
$errors[] = 'No search term given!';
if(!isset($_REQUEST['limit']) || empty($_REQUEST['limit']))
$limit = 10;
else
$limit = (int) $_REQUEST['limit'];
if(empty($errors)){
$term = sanitize_text_field($_REQUEST['term']);
// setup query data
$args = array(
'posts_per_page' => $limit,
's' => $term
);
$query = new WP_Query($args); // run query
$results = array();
if($query->have_posts()): while($query->have_posts()): $query->the_post();
$post_item = array(
'title' => get_the_title(),
'excerpt' => get_the_excerpt(),
'permalink' => get_permalink()
);
$results[] = $post_item;
endwhile;
$data['status'] = 'success';
$data['message'] = 'Results found!';
$data['result'] = $results;
else:
$errors[] = 'No post found!';
$data['message'] = $errors;
endif;
}
echo json_encode($data); // print json
die(); // kill the script
}
Client-side code (request plugin):
reqwest({
url: 'http://...'
, type: 'json'
, method: 'get'
, crossOrigin: true
, withCredentials: true
, error: function (err) { alert('1'); }
, success: function (resp) {
alert('2');
}
})
I tried use this header('Content-type: application/json');header('Access-Control-Allow-Origin: *'); (see in server code above) but it does not solve the problem.

Problem is solved by moving second server to HTTPS...

Related

WordPress API JSON output not valid with quotes

I have a custom function that outputs a Json
However the Json Output has always quotes added and is thus unvalid.
function my_callback( $data ) {
$zz999_ids = do_shortcode('[wpv-view name="json-zz999-ids"]');
//$result = do_shortcode('[wpv-view name="json-traject-bus" ids="'.$zz999_ids.'"]');
$result = '[{"bus_id":"BC025","traject_id":"D","traject_show":[["06:00-08:16"]]}]';
return print_r($result, true);
}
add_action( 'rest_api_init', function () {
register_rest_route( 'wp/v2', '/traject2/', array(
'methods' => 'GET',
'callback' => 'my_callback',
) );
} );
The result I get is: "[{\"bus_id\":\"BC025\",\"traject_id\":\"D\",\"traject_show\":[[\"06:00-08:16\"]]}]"
I just replaced the $result with a teststring. It is exactly same format that comes through the function.
How to get rid of those outer quotes?
function my_callback( $data ) {
$zz999_ids = do_shortcode('[wpv-view name="json-zz999-ids"]');
//$result = do_shortcode('[wpv-view name="json-traject-bus" ids="'.$zz999_ids.'"]');
$result = '[{"bus_id":"BC025","traject_id":"D","traject_show":[["06:00-08:16"]]}]';
$result = json_decode($result);
return $result;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'wp/v2', '/traject2/', array(
'methods' => 'GET',
'callback' => 'my_callback',
) );
} );
For you better understanding about json_decode please visit here

JSON WP REST API getting featured image by Taxonomy Terms

I'm trying to get a featured-image from my custom taxonomy-*projects* term-*elfla*.
I managed to get a image from the posts with this code what i found here but I don't understand how to do it with taxonomy terms.
At this point I do not understand how to get the featured image source and whether the 'GET' request url is correct.
JS:
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET','http://localhost/test/wordpress/wp-json/wp/v2/posts/?filter=projects&filter=elfla&_embed');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
createHTML(data);
portfolioPostsBtn.remove();
console.log(data);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
});
}
function createHTML(postsData) {
var ourHTMLString = '';
for (i = 0; i < postsData.length; i++) {
ourHTMLString += '<img src="'+postsData[i].featured_image_thumbnail_url+ '" alt="img">';
}
portfolioPostsContainer.innerHTML = ourHTMLString;
}
Functions.php
function my_rest_prepare_post( $data, $post, $request ) {
$_data = $data->data;
$thumbnail_id = get_term_meta( $post->ID , 'thumbnlai' false );
$thumbnail = wp_get_attachment_image_src( $thumbnail_id );
$_data['featured_image_thumbnail_url'] = $thumbnail[0];
$data->data = $_data;
return $data;
}
add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );
Use this function.
**function custom_api_get_all_posts() {
register_rest_route( 'custom/v1', '/all-posts', array(
'methods' => 'GET',
'callback' => 'custom_api_get_all_posts_callback'
)); }
function custom_api_get_all_posts_callback( $request ) {
// Initialize the array that will receive the posts' data.
$posts_data = array();
// Receive and set the page parameter from the $request for pagination purposes
$paged = $request->get_param( 'page' );
$paged = ( isset( $paged ) || ! ( empty( $paged ) ) ) ? $paged : 1;
// Get the posts using the 'post' and 'news' post types
$posts = get_posts( array(
'paged' => $paged,
'post__not_in' => get_option( 'sticky_posts' ),
'posts_per_page' => 1000,
'post_type' => array('post') // This is the line that allows to fetch multiple post types.
)
);
// Loop through the posts and push the desired data to the array we've initialized earlier in the form of an object
foreach( $posts as $post ) {
$id = $post->ID;
$post_thumbnail = ( has_post_thumbnail( $id ) ) ? get_the_post_thumbnail_url( $id ) : null;
$posts_data[] = (object) array(
'id' => $id,
'slug' => $post->post_name,
'type' => $post->post_type,
'title' => $post->post_title,
"content" => apply_filters('the_content', $post->post_content),
'featured_img_src' => $post_thumbnail
);
}
return $posts_data; }
use this link http://yourdomin.com/wp-json/custom/v1/all-posts.
I think it will work for you

add folder to folder using google drive API

The script below is creating folders within a parent folder using
"google drive API". It works perfectly however, after a while (20 folders or so) it is not working anymore.
No error message just no more folder creation within the parent folder.
It goes somewhere else!
To enable that creation a "service account" was created and parent folder is share between "personal google account" and "service account"
Can someone provide help please?
php function send_google_drive($id,$fileno,$filename1,$filename2){
global $wpdb;
require(ABSPATH.'/wp-content/themes/enemat/googledrives/vendor/autoload.php');
$client = getClient();
$service = new Google_Service_Drive($client);
if(!empty($filename1)){
$results = $service->files->listFiles();
foreach ($results->getFiles() as $item) {
if ($item['name'] == 'ENEMAT CRM FILES') {
$folderId = $item['id'];
break;
}
}
$parentid = $folderId;
$childid = "";
foreach ($results->getFiles() as $item) {
if ($item['name'] == $fileno) {
$childid = $item['id'];
break;
}
}
if(empty($childid)){
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => $fileno,
'parents'=>array($parentid),
'mimeType' => 'application/vnd.google-apps.folder'));
$file = $service->files->create($fileMetadata, array(
'fields' => 'id'));
$folderId = $file->id;
}else{
$folderId = $childid;
}
$newPermission = new Google_Service_Drive_Permission();
$newPermission->setType('anyone');
$newPermission->setRole('reader');
$service->permissions->create($folderId, $newPermission);
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => array(basename($filename1)),
'parents' => array($folderId)
));
$content = file_get_contents($filename1);
$files = $service->files->create($fileMetadata, array(
'data' => $content,
'uploadType' => 'resumable',
'fields' => 'id'));
$fileids = $files->id;
$docusignorgs = "https://drive.google.com/open?id=".$fileids."";
$folderslink = "https://drive.google.com/drive/folders/".$folderId."";
#unlink(ABSPATH."wp-content/themes/enemat/pdfs/".basename($filename1));
$newPermission = new Google_Service_Drive_Permission();
$newPermission->setType('anyone');
$newPermission->setRole('reader');
$service->permissions->create($fileids, $newPermission);
}
if(!empty($filename2)){
$results = $service->files->listFiles();
foreach ($results->getFiles() as $item) {
if ($item['name'] == '46 - CONTRAT PARTENARIAT') {
$folderId = $item['id'];
break;
}
}
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => array(basename($filename2)),
'parents' => array($folderId)
));
$content = file_get_contents($filename2);
$files = $service->files->create($fileMetadata, array(
'data' => $content,
'uploadType' => 'resumable',
'fields' => 'id'));
$fileids1 = $files->id;
$contractdrivelink = "https://drive.google.com/open?id=".$fileids1."";
$newPermission = new Google_Service_Drive_Permission();
$newPermission->setType('anyone');
$newPermission->setRole('reader');
$service->permissions->create($fileids1, $newPermission);
}
}
?
The reason there is no error message is because your code has no error handling! If GDrive fails to do something, it returns an error code and message to explain why. Your code should be catching that error and displaying it.
My guess is that you are hitting a rate limit. To see if this is the cause or not, add a 2 second delay between each folder creation. If it no runs correctly, you know that rate limiting is your problem.

Json returned from recaptcha is ... bad

When doing
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
$result = json_decode($response);
The response is
)]}'
["uvresp","03AJpayVHarkP_b40i5...stuff...VOrIy6m3ws",1,120]
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
The )]}' breaks things. I have no idea where that is coming from.
$g_recaptcha_response looks fine to me (what I am sending to google to verify).
The function to verify recaptcha
function verify_recaptcha ($g_recaptcha_response, $remote_address) {
# Verify captcha
$post_data = http_build_query(
array(
'secret' => 'secret',
'response' => $g_recaptcha_response,
'remoteip' => $remote_address
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
$context = stream_context_create($opts);
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
$result = json_decode($response);
return $result->success;
}
Thanks.
Ok my bad. The above code works, I had a problem further downstream (query was trying to use a column that did not exist).

Yii2: Run a web action in a console controller

Is it possible to run a web action in a console controller?
In a web controller (yii\web\Controller) I have an action which I would like to run as a cron job. But if I try to run it in a console controller (yii\console\Controller):
Yii::$app->runAction('controller/action');
then I receive the following error message:
Error: Unknown command "controller/action".
Run a web action in a console controller:
Yii::$app->controllerNamespace = "app\controllers";
Yii::$app->runAction('controller/action');
Assign controllerNamespace before running the web action from console.
In addition, disable enableCsrfValidation for the web action:
public function beforeAction($action)
{
if ($action->id == 'action') {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
The 'action' ID could be replaced with your current web action ID.
Sorry, I did not understand the context of the question.
As #soju says, you should find a way to do it using CURL, but there is a way.
$config = \yii\helpers\ArrayHelper::merge(
require(Yii::getAlias('#common').'/config/main.php'),
require(Yii::getAlias('#common').'/config/main-local.php'),
require(Yii::getAlias('#frontend').'/config/main.php'),
require(Yii::getAlias('#frontend').'/config/main-local.php')
);
$web_application = new \yii\web\Application($config);
$web_application->runAction('/site/index',['param1' => 1,'param2' => 2]);
You should be aware that the controller works with their behaviors, then the AccessControl could prevent the execution
The solution with cURL.
In the web controller have to be disabled the CSRF validation:
public function beforeAction() {
if ($this->action->id == 'export') {
Yii::$app->controller->enableCsrfValidation = false;
}
return true;
}
The cURL commands in the console Controller can look e.g. like this:
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_REFERER => $url,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_COOKIESESSION => true,
CURLOPT_COOKIEJAR => 'curl-cookie.txt',
CURLOPT_COOKIEFILE => '/var/www/yii/frontend/web/tmp',
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
CURLOPT_USERAGENT => "Dark Secret Ninja/1.0",
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => "LoginForm[username]=".$username.
"&LoginForm[password]=".$password.
"&LoginForm[rememberMe]=1",
CURLOPT_SSL_VERIFYPEER => false,
);
curl_setopt_array( $ch, $options );
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
if ( $httpCode != 200 ){
echo "Return code is {$httpCode} \n"
.curl_error($ch);
} else {
echo htmlspecialchars($response);
}
curl_close($ch);