import External API into function.php for wordpress - arrays

I have an API that I want to use as a reusable block in my theme.
the actual problem is that array is not a simple array like other models that I saw in here.
bellow is my code which only fetches the Whole array but does not create the HTML as i mention in Foreach () function in my code when i use [external_data] as shortcode in my theme.
defined( 'ABSPATH' ) or die( 'Unauthorized Access' );
add_shortcode('external_data', 'callback_function_name');
function callback_function_name(){
$url = 'https://api-football-standings.azharimm.site/leagues';
$object = array(
'method' => 'GET',
);
$response = wp_remote_get( $url, $object );
if ( is_wp_error( $response ) ){
$error_message = $response -> get_error_message();
return "Something went wrong: $error_message";
}
$results = json_decode( wp_remote_retrieve_body( $response ) );
var_dump($results);
$html = '';
$html .= '<table>';
$html .= '<tr>';
$html .= '<td>ID</td>';
$html .='<td>League</td>';
$html .='<td>Slug</td>';
$html .='<td>Abbr</td>';
$html .='<td>ax</td>';
$html .= '</tr/>';
foreach( $results as $result ) {
$html .= '<tr>';
$html .= '<td>' . $results->id . '</td>';
$html .= '<td>' . $results->name . '</td>';
$html .= '<td>' . $results->slug . '</td>';
$html .= '<td>' . $results->abbr . '</td>';
$html .= '<td><img src='. $results->logos->light .'/></td>';
$html .= '</tr/>';
}
$html .= '</table>';
return $html;
}

Related

Gmail API - send email to external recipients

I've developed an app (PHP) to send email from my own web service using the Gmail API. We have Gmail / Google Workspace for the company. It is possible to send emails to internal recipients.
However, I can not send emails to external recipients.
I use a service user for the authentication.
I have the user in TEST MODE.
What could I have missed?
require_once __DIR__.'/vendor/autoload.php';
function sendmail($mailto, $from, $cc, $subject, $message, $file) {
$cc = null;
$uid = md5(uniqid(time()));
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . "/credentials.json");
$client->setScopes(['https://mail.google.com']);
$client->setSubject($from);
$service = new Google_Service_Gmail($client);
$header = "From: ".$from." <".$from.">\r\n";
$header .= "Reply-To: ".$from."\r\n";
$header .= "To: ".$mailto." <".$mailto."> \r\n";
if(!is_null($cc)){ $header .= "Cc: ".$cc." <".$cc."> \r\n";}
$header .= 'Subject: =?utf-8?B?' . base64_encode($subject) . "?=\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/html; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
if(is_file($file)){
$filename = basename($file);
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/pdf; name=\"".$filename."\"\r\n"; // use different content types here
$header .= "Content-Description:\"".$filename."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
}
$header .= "--".$uid."--";
$mime = rtrim(strtr(base64_encode($header), '+/', '-_'), '=');
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
$service->users_messages->send("me", $msg);
}
credentials.json refers to a service user

One character only is being returned when using foreach phpfox

I am trying to get some data from a table but when i use foreach it returns only 1 character or the 1st letter/number and one row is returned.
Here is my code.
home.class.php
public function getData()
{
$aRow = $this->database()->select('*')
->from('tablename')
->execute('getSlaveRow');
return $aRow;
}
ajax.class.php
public function getArr()
{
$data = 'No data found';
$results = Phpfox::getService('files.home')->getData();
if($results) {
$data = '<div id="fileparse" style="height:295px;overflow:auto;display:none;"</div>';
$data .= '<div id="filelist" style="height:295px;overflow:auto;">';
$data .= '<table style="width:100%;"><tr><td><b>File Name</b></td><td> <b>Account Type</b></td><td><b>Account Number</b></td><td><b>Company</b></td><td><b>Results</b></td></tr>';
foreach($results as $result) {
$data .= '<tr>';
$data .= '<td>'.$result['file'].'</td>';
$data .= '<td>'.$result['result'].'</td>';
$data .= '</tr>';
}
$data .= '</table>';
$data .= '</div>';
} else
$data = 'No results found';
$this->html('#eqblock', $data);
}
use getSlaveRows insted of getSlaveRow
getSlaveRow return single array while getSlaveRows return all rows

CakePHP paggination, Not Working (not showing the data correctly)

I'm having a hard time figure out how to paginate in cakePHP when i have activate admin routing.
I have localhost/myapp that is the main page
and localhost/myapp/admin that is tthe admin area. So I want to paginate on the fron end, so in the localhost/myapp index page.
So as the main index page is index of Typology Model.
in my app/Config/routes.php i have this routing for homepage:
Router::connect(
'/',
array(
'admin'=>false,
'controller' => 'typologies',
'action' => 'index', 'index'
)
);
PS: i Also Use slug for finding posts.
In my app/Controller/TypologyController I have this:
$this->Paginator->settings = array(
'joins' => array(
array(
'table' => 'items',
'alias' => 'Item',
'type' => 'LEFT',
'conditions' => array('Item.id = Typology.item_id')
)
),
'conditions' => array(
'Item.published' => 1,
'Typology.published' => 1
),
'limit' => 1,
'order' => array('Typology.sort' => 'ASC'),
'fields' => array('Item.*', 'Typology.*'),
'recursive' => 2
);
$typologies = $this->paginate('Typology');
$this->set(compact('typologies'));
I have set limit=>1 just for testing purposes.
In my View/Typologies/index.ctp i have this:
<?php
$result = '';
foreach ($typologies as $typology):
$id = h($typology['Typology']['id']);
$item_id = h($typology['Typology']['item_id']);
$title = h($typology['Typology']['title']);
$description = h($typology['Typology']['description']);
$thumbnail = h($typology['Typology']['thumbnail']);
$price = h($typology['Typology']['price']);
$typology_category_id = h($typology['Typology']['typology_category_id']);
$typology_condition_id = h($typology['Typology']['typology_condition_id']);
if (strlen($description)>330) {
$short_description = substr($description, 0, 327);
$description = $short_description."...";
}
$dir = "img/uploads/typology/thumbnails/";
if (file_exists( $dir . $thumbnail)) {
$typologyThumbnails = $dir . $thumbnail;
}
else {
$typologyThumbnails = "img/uploads/noimg.jpg";
}
if($thumbnail=='NULL' || $thumbnail=='') {
$typologyThumbnails = "img/uploads/noimg.jpg";
}
$result .= "<div class=\"item_shadow\">";
if ($logged_in) {
if ($typology['Typology']['published']==0 || $typology['Typology']['published']==false || $typology['TypologyItem']['published']==0 || $typology['TypologyItem']['published']==false) {
$result .= "<div class=\"badge red\"> non publicato </div>";
}
}
$result .= "<div class=\"item\" style=\"background-image:url({$typologyThumbnails});\">";
$result .= "<div class=\"item-content\">";
$result .= "<div class=\"item-top-content\">";
$result .= "<div class=\"item-top-content-inner\">";
$result .= "<div class=\"item-top-title\">";
$result .= "<h4>{$title}</h4>";
$result .= "</div>";
$result .= "</div>" ;
$result .= "</div>";
$result .= "<div class=\"item-add-content\">";
$result .= "<div class=\"item-add-content-inner\">";
$result .= "<div class=\"description-inner\">";
$result .= "<p>{$description}</p>";
$result .= "</div>";
$result .= "<div class=\"read-more-inner\">";
$result .= $this->Html->link("maggiori informazioni". $this->Html->image('elenco.png'), array('admin'=>false,'controller' => 'items', 'action' => 'view', 'slug' => Inflector::slug($typology['TypologyItem']['seo_url'],'-'),'id'=>$typology['Typology']['item_id'],'?'=> array('active_tab' => $typology['Typology']['id'])), array('escape' => false));
$result .= "</div>";
$result .= "</div>";
$result .= "</div>";
$result .= "</div>";
$result .= "</div>";
$result .= "</div>";
endforeach;
$result .= "";
?>
So as you see first i store all the data into a variable then i echo it like this with the paginator helper:
<?php
if (isset($result)) {
echo $result;
}
?>
<p>
<?php
echo $this->Paginator->counter(array(
'format' => __('Page{:page} di {:pages}, Showing {:current} records of {:count} in total, starting at {:start}, and finishing at {:end}')
));
?>
</p>
<div class="paging">
<?php
echo $this->Paginator->prev('< ' . __('Preview'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('Next') . ' >', array(), null, array('class' => 'next disabled'));
?>
</div>
So the first time i load the page, URL is like this http://localhost/mycakephpApp/ it displays one date like it suppose to:
When i click next, or number 2, URL is like this: http://localhost/mycakephpApp/typologies/index/index/page:2, it should display the next one. It does but now it is blank like this.
I don't know what am i missing or what am i doing wrong. Does anyone has any idea how to fix this?
I would really appriciate your your help.
Relative urls are problematic
The view contains the following:
$result .= "<div class=\"item\" style=\"background-image:url({$typologyThumbnails});\">";
Where $typologyThumbnails is a relative url of the form:
img/uploads/typology/thumbnails/whatever.jpg
That means that for the url http://localhost/mycakephpApp/ the following image url is requested:
http://localhost/mycakephpApp/img/uploads/typology/thumbnails/whatever.jpg
However, for the url http://localhost/mycakephpApp/typologies/index/index/page:2 the following image url is requested:
http://localhost/mycakephpApp/typologies/index/index/img/uploads/typology/thumbnails/whatever.jpg
Which doesn't exist.
There's a very simple solution:
Always use absolute urls i.e. /img/uploads/typology/thumbnails/whatever.jpg
Use helper functions and the router class, or at least recognise what they do.
You can fix the problem as asked by doing the following before using the variable:
$typologyThumbnails = Router::url('/' . $typologyThumbnails);
This will output:
/mycakephpApp/img/uploads/typology/thumbnails/whatever.jpg
Use helpers and elements
View files of the form:
echo "large chunk of html"
are rather hard to read/maintain. Instead the view code should be for example:
<?php
foreach ($typologies as $typology) {
echo $this->element('typology', array('row' => $typology));
}
// pagination links
And the body of the foreach loop in an element. But don't write large swathes of html as strings - it's a lot easier to read/maintain if it's written as:
<?php
// /App/View/elements/typology.ctp
// variable setup
?>
<div class="item_shadow">
<div class="item" style="background-image:url(<?= Router::url($typologyThumbnails) ?>);">
...
<h4><?= h($row['Typology']['title']) ?></h4>
It also has the added benefit that your editor will highlight the html.

Send file using multipart/form-data request in php

I have image resource stored in variable which I need to send to server using its http API and PHP. I have to send request with content type multipart/form-data. So, I need to make similiar request as when form with file input and enctype=multipart/form-data attribute is sent.
I tried this:
<?php
$url = 'here_is_url_for_web_API';
$input = fopen('delfin.jpg','r');
$header = array('Content-Type: multipart/form-data');
$resource = curl_init();
curl_setopt($resource, CURLOPT_URL, $url);
curl_setopt($resource, CURLOPT_USERPWD, "user:password");
curl_setopt($resource, CURLOPT_HTTPAUTH, CURLAUTH_ANYSAFE);
curl_setopt($resource, CURLOPT_HTTPHEADER, $header);
curl_setopt($resource, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($resource, CURLOPT_BINARYTRANSFER, true );
curl_setopt($resource, CURLOPT_INFILESIZE, 61631);
curl_setopt($resource, CURLOPT_INFILE, $input);
$result = curl_exec($resource);
curl_close($resource);
var_dump($result);
?>
I don't know how exactly response should look like but this returns:
http status 405
and error report is: The specified HTTP method is not allowed for the requested resource ().
use multipart/form-data and boundaries in POST content with curl.
$filenames = array("/tmp/1.jpg", "/tmp/2.png");
$files = array();
foreach ($filenames as $f){
$files[$f] = file_get_contents($f);
}
// more fields for POST request
$fields = array("f1"=>"value1", "another_field2"=>"anothervalue");
$url = "http://example.com/upload";
$curl = curl_init();
$url_data = http_build_query($data);
$boundary = uniqid();
$delimiter = '-------------' . $boundary;
$post_data = build_data_files($boundary, $fields, $files);
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
//CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $post_data,
CURLOPT_HTTPHEADER => array(
//"Authorization: Bearer $TOKEN",
"Content-Type: multipart/form-data; boundary=" . $delimiter,
"Content-Length: " . strlen($post_data)
)
));
//
$response = curl_exec($curl);
$info = curl_getinfo($curl);
//echo "code: ${info['http_code']}";
//print_r($info['request_header']);
var_dump($response);
$err = curl_error($curl);
echo "error";
var_dump($err);
curl_close($curl);
function build_data_files($boundary, $fields, $files){
$data = '';
$eol = "\r\n";
$delimiter = '-------------' . $boundary;
foreach ($fields as $name => $content) {
$data .= "--" . $delimiter . $eol
. 'Content-Disposition: form-data; name="' . $name . "\"".$eol.$eol
. $content . $eol;
}
foreach ($files as $name => $content) {
$data .= "--" . $delimiter . $eol
. 'Content-Disposition: form-data; name="' . $name . '"; filename="' . $name . '"' . $eol
//. 'Content-Type: image/png'.$eol
. 'Content-Transfer-Encoding: binary'.$eol;
$data .= $eol;
$data .= $content . $eol;
}
$data .= "--" . $delimiter . "--".$eol;
return $data;
}
See the full example here: https://gist.github.com/maxivak/18fcac476a2f4ea02e5f80b303811d5f
If you work with CURL, you have to just:
1, set header 'Content-Type' as 'multipart/form-data;'
2, set option 'RETURNTRANSFER' of curl to true (use option method of curl)
3, set option 'POST' of curl to true (use option method of curl)
4, get source of your file (what you get from fopen in PHP):
$tempFile = tempnam(sys_get_temp_dir(), 'File_');
file_put_contents($tempFile, $source);
$post = array(
"uploadedFile" => "#" . $tempFile, //"#".$tempFile.";type=image/jpeg",
);
5, use post method of CURL with parameter in $post variable

Array placeholders

I’ve got an array where PLACEHOLDER is a placeholder for the variable $value that I get later in the code:
$names = array(
"<a href='http://skyler.com' title='PLACEHOLDER'>Skyler</a>",
"<a href='http://jesse.com' title='PLACEHOLDER'>Jesse</a>",
"<a href='http://walter.com' title='PLACEHOLDER'>Walter</a>",
"<a href='http://skyler.com' title='PLACEHOLDER'>Skyler</a>",
"<a href='http://hank.com' title='PLACEHOLDER'>Hank</a>",
"<a href='http://marie.com' title='PLACEHOLDER'>Marie</a>",
"<a href='http://walter.com' title='PLACEHOLDER'>Walter</a>",
"<a href='http://walter.com' title='PLACEHOLDER'>Walter</a>",
"<a href='http://jesse.com' title='PLACEHOLDER'>Jesse</a>",
);
To check how often an equal value is in my array,
I count them with array_count_values.
$count = array_count_values($names);
foreach ($count as $key => $value) {
echo $value . ' – ' . $key . '<br />';
}
So I get something like this:
3 – <a href='http:/walter.com' title='PLACEHOLDER'>Walter</a>
2 – <a href='http://jesse.com' title='PLACEHOLDER'>Jesse</a>
2 – <a href='http://skyler.com' title='PLACEHOLDER'>Skyler</a>
1 – <a href='http://hank.com' title='PLACEHOLDER'>Hank</a>
1 – <a href='http://marie.com' title='PLACEHOLDER'>Marie</a>
Now I’d PLACEHOLDER be replaced by $value, so I get the number as title tag of the link.
foreach ($count as $key => $value) {
echo $value . ' – ' . str_replace('PLACEHOLDER', $value, $key) . '<br />';
}
What are you asking, I don't understand, you want to replace PLACEHOLD with $value then do this
$names = array(
"<a href='http://skyler.com' title='".$PLACEHOLDER."'>Skyler</a>",
"<a href='http://jesse.com' title='".$PLACEHOLDER."'>Jesse</a>"
);
Use str_replace to replace PLACEHOLDER with $value
foreach ($count as $key => $value) {
$key = str_replace('PLACEHOLDER', $value, $key); //<--replace PLACEHOLDER here
echo $value . ' – ' . $key . '<br />';
}
Correct code is :
foreach ($count as $key => $value) {
echo str_replace('PLACEHOLDER', $value, $key); //this will replace placeholder with number of tags
echo '<br />';
}

Resources