Bing API related searches - bing-api

How does one get related searches to be included in response from Bing search API?
I am trying to apply responseFilter with value RelatedSearches as per the documentation here: https://learn.microsoft.com/en-us/rest/api/cognitiveservices/bing-web-api-v7-reference#relatedsearchanswer
Below is my code based on sample from Bing. I have added "&responseFilter=RelatedSearches" to the URL that is fetched by file_get_contents().
The error I get back is:
PHP Warning: file_get_contents(https://api.cognitive.microsoft.com/bing/v7.0/search?responseFilter=RelatedSearches&q=iphone+case): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden
Clearly I am applying it wrong. What can I change to be making it working?
<?php
$accessKey = 'abc123';
$endpoint = 'https://api.cognitive.microsoft.com/bing/v7.0/search';
$term = 'burrito recipe';
function BingWebSearch ($url, $key, $query) {
$headers = "Ocp-Apim-Subscription-Key: $key\r\n";
$options = array ('http' => array (
'header' => $headers,
'method' => 'GET'));
$context = stream_context_create($options);
$result = file_get_contents($url . "?q=" . urlencode($query) . "&responseFilter=RelatedSearches", false, $context);
$headers = array();
foreach ($http_response_header as $k => $v) {
$h = explode(":", $v, 2);
if (isset($h[1]))
if (preg_match("/^BingAPIs-/", $h[0]) || preg_match("/^X-MSEdge-/", $h[0]))
$headers[trim($h[0])] = trim($h[1]);
}
return array($headers, $result);
}
if (strlen($accessKey) == 32) {
print "Searching the Web for: " . $term . "\n";
list($headers, $json) = BingWebSearch($endpoint, $accessKey, $term);
print "\nRelevant Headers:\n\n";
foreach ($headers as $k => $v) {
print $k . ": " . $v . "\n";
}
print "\nJSON Response:\n\n";
echo json_encode(json_decode($json), JSON_PRETTY_PRINT);
} else {
print("Invalid Bing Search API subscription key!\n");
print("Please paste yours into the source code.\n");
}
?>

The "403 Forbidden" is the hint. You don't have permission to request RelatedSearches unless you are on the S1 instance as per here: https://azure.microsoft.com/en-us/pricing/details/cognitive-services/search-api/

Related

upload image to ckeditor in laravel Incorrect server response

i am trying to upload image through ckeditor 4
when i press send it the server
getting this Error Incorrect Server Response
here is my controller
public function mediauploadpost(Request $request){
$CKEditor = $request->input('CKEditor');
$funcNum = $request->input('CKEditorFuncNum');
$message = $url = '';
if (Input::hasFile('upload')) {
$file = Input::file('upload');
if ($file->isValid()) {
$filename =rand(1000,9999).$file->getClientOriginalName();
$file->move(public_path().'/wysiwyg/', $filename);
$url = url('wysiwyg/' . $filename);
} else {
$message = 'An error occurred while uploading the file.';
}
} else {
$message = 'No file uploaded.';
}
return '<script>window.parent.CKEDITOR.tools.callFunction('.$funcNum.', "'.$url.'", "'.$message.'")</script>';
}
I had this same issue recently, and the solution was to add this line to my ckeditor-config.js file:
config.filebrowserUploadMethod = 'form';
If you are using java as your backend server: return string response:
"{\n " +
" \"uploaded\": 1,\n" +
" \"fileName\": \"foo.jpg\",\n" +
" \"url\": \"/files/foo.jpg\"\n" +
"}"
See this link fro more information.
Also remember to to have annotation: produces = MediaType.TEXT_HTML_VALUE over your rest API.
Remove this one
$res = "<script>window.parent.CKEDITOR.tools.callFunction(" .$funcNum. "," . $url . "," .$message. ")</script>"
Use this code in your return .
return response()->json([ 'fileName' => 'your file name put here', 'uploaded' => false, 'url' => $url, ]);
$res = "<script>window.parent.CKEDITOR.tools.callFunction(" .$funcNum. "," . $url . "," .$message. ")</script>"
return response()->json(['data' => $res]);
set the these propertis in your file
<script>
CKEDITOR.replace('textarea_id',{
filebrowserUploadUrl:"upload.php",
filebrowserUploadMethod: "form"
});
</script>
in laravel 7
CKEDITOR.replace('body', {
filebrowserUploadUrl:'/admin/general-topic/images', // Route
filebrowserImageUploadUrl:'/admin/general-topic/images', // File location
filebrowserUploadMethod: "form"
})

Magento 2 oauth 1 get request token

Am not able to get request token in magento app. Signature is always invalid.
This is the code i use to generate the signature. The consumer key is the one is i get from localhost:8000 (magento shop) request to localhost:3000.
I tried changing the url both to localhost 8000 and 3000.
Followed these instructions: Magento instructions
function getSignature($consumerKey)
{
$params = array(
'oauth_nonce' => uniqid(mt_rand(1, 1000)),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_version' => '1.0',
'oauth_consumer_key' => $consumerKey,
);
ksort($params);
$baseString = strtoupper('POST') . '&';
$baseString .= rawurlencode('http://localhost:8000') . '&';
$baseString .= rawurlencode(buildSignatureDataString($params));
$signature = hash_hmac('SHA1', $baseString, getSigningKey(), true);
return base64_encode($signature);
}
function getSigningKey()
{
return rawurlencode('magento_private_key') . '&';
}
function buildSignatureDataString(array $signatureData)
{
$signatureString = '';
$delimiter = '';
foreach ($signatureData as $key => $value) {
$signatureString .= $delimiter . $key . '=' . $value;
$delimiter = '&';
}
return $signatureString;
}

How to use Ajax pager in Drupal7

I want to use ajax_pager in my block.
I've installed Libraries API and Ajax Pager API (as it described on the AP API page). But it's still not working.
When I use 'pager' instead of 'ajax_pager' it works.
What I'm doing wrong?
<?php
function latest_news_block_info() {
$blocks['latest_news_block'] = array(
// info: The name of the block.
'info' => t('Latest News'),
);
return $blocks;
}
function latest_news_block_view($delta = '') {
// The $delta parameter tells us which block is being requested.
switch ($delta) {
case 'latest_news_block':
// Create your block content here
$block['subject'] = t('Last news');
$query = new EntityFieldQuery();
//change news by the name of your content type
$entities = $query->entityCondition('entity_type', 'node')
->pager(5, 0)
->entityCondition('bundle', 'news')
->propertyOrderBy("created", "DESC")
->execute();
$content = "";
foreach($entities['node'] as $obj) {
$node = node_load($obj->nid);
$content .= "<img src='" .file_create_url($node->field_image['und'][0]['uri']) . "' width='200px' height='200px'>" . l($node->title, "node/" . $node->nid) . truncate_utf8($node->body['und'][0]['value'], 200, true, true) . '<br><hr>';
$block['content'] = $content;
}
break;
}
$pager = theme('ajax_pager', array('parameters' => array('selector' => 'block-system-main')));
$block['content'] .= $pager;
return $block;
}

set a chosen image-file-input as a featured image from wp frontend

SCENARIO : I allow to create posts from front-end. The form also has four image upload fields. I use the code pasted below for image attachments and setting the post thumbnail.
//insert attachments
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
}
}
//attachment helper function
function insert_attachment($file_handler,$post_id,$setthumb='false') {
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK){ return __return_false();
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
//set post thumbnail
if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id); //you will need to comment out this line if you use my solution
return $attach_id;//you will need to comment out this line if you use my solution
}
The post-thumbnail/featured image that is set through this code is the LAST image that is uploaded. I tried a google search for "set post thumbnail from frontend wordpress" and grazed through a lot of articles but none came close to what I am asking here. Majority of threads I came across at SE in regards to front-end posting, either talks about setting the featured image or about multiple uploads. I have also checked all the suggested questions which were prompted, while I was writing this question just to make sure if it has been asked before.
If it matters, here is the html that is used in the form, pretty standard.
<input type="file" name="image-one" id="image-one"/>
<input type="file" name="image-two" id="image-two"/>
<input type="file" name="image-three" id="image-three"/>
REQUEST : It would be great if I could get a solution that helps to assign any chosen image-input-field as a featured-image but at this moment, at least what I need to set the FIRST image input to be set as a featured-image/post-thumbnail. Kindly suggest a solution.
Bottomline is that I do not have an issue with setting post-thumbnail
but question is about having a choice to choose any of the uploaded
images as post-thumbnail or at least the first image, instead of the
last image as set by the current code.
PROGRESS REPORT :
Never know if it would help in cracking this issue. But when I print_($newupload), I get the id eg. 54287 ,of the last-image-input attachment that is saved as post-thumbnail.
This thread suggests a way to set a featured-image with the first image found in the post so I thought of working on that idea. But the code does not seem to work either.
$attachments = get_children(array(
'post_parent' => $pid,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'ID'
));
if ($attachments) {
foreach ($attachments as $attachment) {
set_post_thumbnail($pid, $attachment->ID);
break;
}
FINAL WORD : The code in the progress report momentarily gets the job done for me, that is.. setting the first image-file-input as a featured-image/post-thumbnail and I am not even sure if this is the best way to do this. I am still looking for a solution which could give a flexibility to choose any image-input-field as a featured-image. If you decide to use this feature remember to comment out the second last and third last lines from the original code.
Saving a post_meta with _thumbnail_id as meta_key and the attach_id as meta_value won't make that image a featured image, you can use wp_insert_attachment that will help you a lot in this. Make sure you read the codex and the examples there. The function should be used in conjunction with wp_update_attachment_metadata() and wp_generate_attachment_metadata() this way your feature image will be created properly by wordpress.
EDIT:
I've looked over your code and I'm gussing it's easier to use it then my schetch in this case. I've added a file count and a parameter to insert_attachment. Check this code let me know what happens.
Example:
<?php
//insert attachments
if ($_FILES) {
array_reverse($_FILES);
$i = 0;//this will count the posts
foreach ($_FILES as $file => $array) {
if ($i == 0) $set_feature = 1; //if $i ==0 then we are dealing with the first post
else $set_feature = 0; //if $i!=0 we are not dealing with the first post
$newupload = insert_attachment($file,$pid, $set_feature);
$i++; //count posts
}
}
//attachment helper function
function insert_attachment($file_handler,$post_id,$setthumb='false') {
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK){ return __return_false();
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
//set post thumbnail if setthumb is 1
if ($setthumb == 1) update_post_meta($post_id,'_thumbnail_id',$attach_id);
return $attach_id;
}
?>
We can set post featured image from frontend using following function,
simple you need to call this function
post_imgs_update($new_post_id);
after creating new post. and add following function in functions.php
if ( ! function_exists( 'post_imgs_update' ) ) :
function post_imgs_update($new_post_id) {
$data = array();
$attachment_ids = array();
// code for save featured image
if( isset( $_POST['nonce'] ) && wp_verify_nonce( $_POST['nonce'], 'image_upload' ) ){ // here nonce text is "image_upload" you need to add in form
$files = reArrayFiles($_FILES['files']);
if(!empty($_FILES['files'])){
//$i = 0;
$set_featured_img = 0 ;
foreach( $files as $file ){
if( is_array($file) ){
$attachment_id = upload_user_file( $file, basename($file['name']) );
if ( is_numeric($attachment_id) ) {
if ($set_featured_img == '0') {
set_post_thumbnail($new_post_id, $attachment_id);
$set_featured_img++;
$attachment_ids[] = $attachment_id;
}
else{
$attachment_ids[] = $attachment_id;
}
}
}
}
//add to array
$mediaurl = array();
foreach ($attachment_ids as $img_id) {
$imgurl = wp_get_attachment_url( $img_id );
$image_gallery[$img_id] = $imgurl;
}
update_post_meta( $new_post_id, '_stw_property_multi_images', $image_gallery); // 2nd arg field key
}
}
else {
$data['status'] = false;
$data['message'] = __('Nonce verify failed','realestate');
}
return $new_post_id;
}
endif;
if ( ! function_exists( 'reArrayFiles' ) ) :
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
endif;
if ( ! function_exists( 'upload_user_file' ) ) :
function upload_user_file( $file = array(), $title = false ) {
require_once ABSPATH.'wp-admin/includes/admin.php';
$file_return = wp_handle_upload($file, array('test_form' => false));
if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){
return false;
}else{
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_content' => '',
'post_type' => 'attachment',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
if($title){
$attachment['post_title'] = $title;
}
$attachment_id = wp_insert_attachment( $attachment, $filename );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
endif;
function my_handle_attachment($file_handler,$post_id,$set_thu=false) {
$attachurlarray = array();
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
return $attach_id;
}

Incorrect Signature in facebook stream_publish call

I am having a facebook error on stream_publish call. I actually used an extension for Magento for Fconnect. Fconnect & Flogin is working fine. But it is requirement that when user place an order it should be posted on user's wall. For that I have implemented like this
document.observe('click', function(e){
if (e.element().match('a[rel^=facebook-connect]') || e.element().match('button[rel^=facebook-connect]')) {
e.stop();
FB.login(function(response){
if(response.status=='connected') setLocation('http://staging.mystore.com/facebook/customer_account/connect/');
}, {perms:"email,publish_stream"});
}
});
in Facebook Client file generateSignature method is like this
private function _generateSig($params_array)
{
Mage::log($params_array);
$str = '';
ksort($params_array);
foreach ($params_array as $k=>$v) {
$str .= "$k=$v";
}
$str .= $this->_secret;
Mage::log($str);
Mage::log('md5 sigs:: ' . md5($str));
return md5($str);
}
& My code that is calling the API is like this
$message = 'just placed an order on mystore.com';
$attachment = array(
'name' => "mystore",
'href' => 'http://www.mystore.com/',
'description' => 'New order on mystore.com',
'media' => array(array('type' => 'image',
'src' => 'http://www.mystore.com/skin/frontend/default/mystore/images/logo.png',
'href' => 'http://www.mystore.com/')));
$action_links = array( array('text' => 'Buy#mystore', 'href' => 'http://www.mystore.com/'));
$attachment = json_encode($attachment);
$action_links = json_encode($action_links);
try{
// if( $facebook->api_client->stream_publish($message, $attachment, $action_links, null, $target_id))
if($this->_getClient()->call( 'facebook.stream.publish',
array($message, $attachment, $action_links,
$this->_getClient()->users->getLoggedInUser(),
Mage::getSingleton('facebook/config')->getApiKey() )
) )
{
Mage::log( "Added on FB Wall" );
}
} catch(Exception $e)
{
Mage::log( "Exception in wall write" );
Mage::log($e);
}
After logging the Signature I found in log is
api_key=XXXXXXXXmethod=facebook.stream.publishsession_key=2.AQCm5fABfobInAS5.3600.1309352400.1-1000025660978090=just placed an order on mystore.comcall_id=1309345883.3068format=JSONv=1.01={"name":"mystore","href":"http:\/\/www.mystore.com\/","description":"New order on mystore.com","media":[{"type":"image","src":"http:\/\/www.mystore.com\/skin\/frontend\/default\/mystore\/images\/logo.png","href":"http:\/\/www.mystore.com\/"}]}2=[{"text":"Buy#mystore","href":"http:\/\/www.mystore.com\/"}]3=1000025660978094=5070afefb42b162aff748f55ecf44d110d9e2a90117ee1704e2adb41f1d190fa
I have never done any development on Facebook SO I have no Idea what to do? Please help me with solution. & let me know if u guys need any other info to understand this.
Oh yeah One more thing the Client File code that is calling Api (call method) its like this
private function _prepareParams($method, $params)
{
$defaultParams = array(
'api_key' => $this->_apiKey,
'call_id' => microtime(true),
'format' => 'JSON',
'v' => '1.0'
);
if($this->_sessionKey){
$defaultParams['session_key'] = $this->_sessionKey;
}
$params = array_merge($defaultParams, $params);
foreach ($params as $key => &$val) {
if (!is_array($val)) continue;
$val = Zend_Json::encode($val);
}
$params['method'] = $method;
if(isset($params['sig'])) {
unset($params['sig']);
}
$params['sig'] = $this->_generateSig($params);
return $params;
}
public function call($method, $args=array())
{
Mage::log($args);
$params = $this->_prepareParams($method, $args);
$client = self::_getHttpClient()
->setUri(self::FACEBOOK_REST_URI)
->setMethod(Zend_Http_Client::POST)
->resetParameters()
->setParameterPost($params);
try {
$response = $client->request();
} catch(Exception $e) {
throw new Mage_Core_Exception('Service unavaliable');
}
if(!$response->isSuccessful()) {
throw new Mage_Core_Exception('Service unavaliable');
}
$result = Zend_Json::decode($response->getBody());
//json decode returns float on long uid number? is_json check? old php?
if(is_float($result)){
$result = $response->getBody();
}
if(is_array($result) && isset($result['error_code'])) {
throw new Mage_Core_Exception($result['error_msg'], $result['error_code']);
}
return $result;
}
For calling API I used two ways $this->_getClient()->call( 'facebook.stream.publish',
& $this->_getClient()->call( 'stream_publish',
None of them are working
ok GUys I figure out the mistake
look at my code
format=JSONv=1.01={"name":"mystore","href":"http:\/\/www.mystore.com\/","description":"New order on mystore.com","media":[{"type":"image","src":"http:\/\/www.mystore.com\/skin\/frontend\/default\/mystore\/images\/logo.png","href":"http:\/\/www.mystore.com\/"}]}2=[{"text":"Buy#mystore","href":"http:\/\/www.mystore.com\/"}]3=1000025660978094=5070afefb42b162aff748f55ecf44d110d9e2a90117ee1704e2adb41f1d190fa
where u can see format=JSONv=1.01={....}2=[{.....}] the problem was I used numeric arrays for parameters. they should be associated arrays
like message={new order}attachment={....}
Once I fixed the associative array problem my code start working correctly
here is a link that'll give u detail about parameters to pass to stream.publish
http://schoolout.net/en/developers/view/39
Hope this will help somebody else too.

Resources