How to use phpthumb in phx:tv? - code-snippets

Using MODX Evo 1.0.7
I am using phx:tv in a chunk like this:
[+phx:tv=`14?Photo`+]
Here is the phx:tv snippet (Source: http://wiki.modxcms.com/index.php/PHx/CustomModifiers#phx:tv)
<?php
if(strlen($options )>0) {
$data = explode("?",trim($options),2);
$id= (!empty($data[0]) && is_numeric($data[0])) ? $data[0]: '';
$tv= (!empty($data[1])) ? $data[1]: '';
$result = $modx->getTemplateVar($tv, 'name', $id, 1);
return $result['value'];
}
?>
How can I use the phpthumb to resize the image in the Photo TV in the code?

I haven't used phx or Evo for a long time, but you might try chaining it like this:
[+phx:tv=`14?Photo`:phpthumb=`w=450`+]

Related

TCPDF how do I create several pdf's without opening a browser

I need to create like 350 pdf's at once. Now the browser opens a window for each pdf. I takes longer to open all the 350 windows than to create the pdf's. How do I create and save the pdf's without opening a browser windows? (In my pdf I use Header, body and footer all with variables)
Now I do a loop on php_page_1 which opens the pdf create file.
$sql = "SELECT id FROM shipping_id WHERE datum BETWEEN $date_range AND acc_id=$acc_id;";
$STH = $dbo->prepare( $sql );
$STH->execute();
$contains_files = 0;
$client_id='';
while ( $row = $STH->fetch( PDO::FETCH_ASSOC ) ) {
$contains_files++;
$link = "vb_print_1_no_screen.php?id=" . $row[ 'id' ] . "&nr=".$contains_files;
echo '<script>window.open("https://' . $website_admin . $link . '");</script>';
}
You can use curl to make the request to the URL instead of opening it directly in the browser or you can just include the file that generates the PDF. Try this code
$sql = "SELECT id FROM shipping_id WHERE datum BETWEEN $date_range AND acc_id=$acc_id;";
$STH = $dbo->prepare( $sql );
$STH->execute();
$contains_files = 0;
$client_id='';
while ( $row = $STH->fetch( PDO::FETCH_ASSOC ) ) {
$contains_files++;
$link = "vb_print_1_no_screen.php?id=" . $row[ 'id' ] . "&nr=".$contains_files;
// echo '<script>window.open("https://' . $website_admin . $link . '");</script>';
// method 1 using curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $website_admin . $link);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);
curl_close($ch);
// method 2 include pdf generator script
$_GET['id'] = $row['id'];
$_GET['nr'] = $contains_files;
include "vb_print_1_no_screen.php";
}
Kindly make sure to use just one method.

Pagination is not working in twilio call logs laravel

<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ApiController;
use App\Model\User;
use Illuminate\Support\Facades\Validator;
use Auth;
use Twilio\Rest\Client;
use Twilio\TwiML\VoiceResponse;
class TwilioController extends ApiController
{
public function __construct(){
$sid = env('TWILIO_SID');
$token = env('TWILIO_TOKEN');
$this->twilio = new Client($sid, $token);
if (request('lang'))
\App::setLocale(request('lang'));
}
public function callLogs(Request $request){
try{
$twilioNumber = Auth::user()->twilio_number;
$calls = $this->twilio->calls
->read([], 20);
$data = [];
$i = 0;
foreach($calls as $call){
$data[$i]['from'] = $call->from;
$i++;
}
$responseData = array('status'=>true, 'message'=>'Data has been returned successfully!', 'data'=>$data);
} catch (\Exception $e) {
$responseData = array('status'=>false, 'message'=>$e->getMessage(), 'data'=>[]);
}
$res = json_encode($responseData);
print $res;
}
Pagination is not working when i get call history in twilio using laravel rest api. when i use page parameter with this then pagination is not working it give me save output as given me 1st page.
Postman parameters - Page:2
Thanks
I think Twilio's page() function will help you. Like read(), it accepts an array of options to narrow your search along with a pageSize parameter defaulting to 50 calls per page. (I believe the maximum value is 1000.)
Here is an example.
//Get all call logs. 20 per page
$calls = $twilio->calls->page( [], 20 );
$data = [];
foreach($calls as $call){
$data[] = $call->sid;
}
//You can access the previous and next page urls using the resource functions in the calls object return from twilio.
return response()->json(["prev" => $calls->getPreviousPageUrl(), "next" => $calls->getNextPageUrl(), "calls" => $data]);

Youtube Data API is returning invalid data

I'm not really sure how to ask this, but I have a php script that pulls data from the youtube-v3-api for my youtube channel, mainly a list of videos that I have published. It's been working great up until earlier today when I went to run it again because I added a new video. Here's the output for the first object in the items array
items:[
{
kind:"youtube#searchResult",
etag:"" XpPGQXPnxQJhLgs6enD_n8JR4Qk/tluoWYe5GE9lVFAkcMtcec2Ycug"",
id:{
kind:"youtube#channel",
channelId:"UCD8d3FGC907iS1qiMF0ccxA"
},
snippet:{
publishedAt:"2006-04-30T19:39:08.000Z",
channelId:"UCD8d3FGC907iS1qiMF0ccxA",
title:"Travis Ballard",
description:"",
thumbnails:{
default:{
url:"https://yt3.ggpht.com/-L5MV7tUNjlk/AAAAAAAAAAI/AAAAAAAAAAA/dXNuqxAYprw/s88-c-k-no-mo-rj-c0xffffff/photo.jpg"
},
medium:{
url:"https://yt3.ggpht.com/-L5MV7tUNjlk/AAAAAAAAAAI/AAAAAAAAAAA/dXNuqxAYprw/s240-c-k-no-mo-rj-c0xffffff/photo.jpg"
},
high:{
url:"https://yt3.ggpht.com/-L5MV7tUNjlk/AAAAAAAAAAI/AAAAAAAAAAA/dXNuqxAYprw/s800-c-k-no-mo-rj-c0xffffff/photo.jpg"
}
},
channelTitle:"Travis Ballard",
liveBroadcastContent:"none"
}
}
]
This does not represent a video on my channel? also, it's not in order at all. It should be ordered by date as i'm asking it to in my php script:
<?php
const APIKEY = 'MyAPIKeyHere';
const CHANNELID = 'UCD8d3FGC907iS1qiMF0ccxA';
const VIDEO_COUNT = 50;
class FetchYoutubeVideos {
private $api_key = null;
private $channel_id = null;
private $count = null;
public function __construct($api_key, $channel_id, $count = 10) {
$this->api_key = $api_key;
$this->channel_id = $channel_id;
$this->count = $count;
$this->writeToFile(
'videos.json',
$this->fetch($this->getApiUrl())
);
printf( 'fetched videos from: %s', $this->getApiUrl());
}
public function getApiUrl($options = array()) {
$endpoint = 'https://www.googleapis.com/youtube/v3/search';
$default_options = array(
'key' => $this->api_key,
'channelId' => $this->channel_id,
'part' => 'snippet,id',
'order' => 'date',
'maxResults' => $this->count
);
$options = array_merge($options, $default_options);
return sprintf('%s/?%s', $endpoint, http_build_query($options));
}
public function fetch($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
return $result;
}
public function writeToFile($filename, $data) {;
$fh = fopen($filename, 'w+');
fwrite($fh, $data, strlen($data));
fclose($fh);
}
}
$fetchVideos = new FetchYoutubeVideos(APIKEY, CHANNELID, VIDEO_COUNT);
The newest video should be 'Tragic - Rock-a-Hoola Revisited' and then 'Rocket Timelapse - Anycubic i3 Mega'. You can reference my yt channel to see what it should be returning: https://www.youtube.com/channel/UCD8d3FGC907iS1qiMF0ccxA?view_as=subscriber
Any insights into why it changed? Or why it's not returning the data that it should be?
You experienced an API issue which is known for a few days now. Follow-up https://issuetracker.google.com/issues/128673552, or the answers already given on this site (e.g. https://stackoverflow.com/a/55246970/8327971).
Either of the two links we'll lead you to find a workaround for the issue at hand.
Note that, until now, Google has refrained itself from providing an ETA for when it'll enable back the API's features it disabled. I suppose that it may well take a few more days (perhaps weeks?) until we'll see those disabled features working again.

Inaccurate results from ImageMagick function queryFontMetrics

Imagick::queryFontMetrics does not seem to be working. When I use the metrics provided by queryFontMetrics to size the image, some fonts are still being cut off. Any ideas?
Here's my code:
if (!file_exists($cache['dirname'].'/'.$cache['basename'])) {
try {
$draw = new ImagickDraw();
$draw->setFont($font_path['dirname'].'/'.$font_path['basename']);
$draw->setFontSize($size);
$draw->setGravity(Imagick::GRAVITY_CENTER);
$draw->setFillColor($color);
$canvas = new Imagick();
$metrics = $canvas->queryFontMetrics($draw, $text);
$canvas->newImage($metrics['textWidth'], $metrics['textHeight'], "transparent", "png");
$canvas->annotateImage($draw, 0, 0, 0, $text);
$canvas->setImageFormat('PNG');
mkdir($cache['dirname'], 0777, true);
$canvas->writeImage($cache['dirname'].'/'.$cache['basename']);
header("Content-Type: image/png");
echo $canvas;
$canvas->clear();
$canvas->destroy();
$draw->clear();
$draw->destroy();
} catch(Exception $e) {
// Output an error message
echo 'Error: ', $e->getMessage(), "";
}
} else {
// Output the image
$canvas = new Imagick($cache['dirname'].'/'.$cache['basename']);
header("Content-Type: image/png");
echo $canvas;
}
Okay, it looks like I'll be answering this one myself. After quite a bit of research, I've discovered that it's basically impossible to get correct metrics from the font itself. This is because each font designer could potentially define the metrics differently. The best way to proceed is to simply make the image much larger than necessary (to ensure that no clipping occurs) and then use the trim command: http://www.php.net/manual/en/imagick.trimimage.php.

How to correctly use oembed to pull thumbs from youtube

I show a lot of thumbs on my homepage from youtube videos. I was using this function below to grab the thumb from a youtube url which works fast but it doesn't work for url's in the shortned form like youtu.be/JSHDLSKL.
function get_youtube_screen_link( $url = '', $type = 'default', $echo = true ) {
if( empty( $url ) )
return false;
if( !isset( $type ) )
$type = '';
$url = esc_url( $url );
preg_match("|[\\?&]v=([^&#]*)|",$url,$vid_id);
if( !isset( $vid_id[1] ) )
return false;
$img_server_num = 'i'. rand(1,4);
switch( $type ) {
case 'large':
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/0.jpg";
break;
case 'first':
// Thumbnail of the first frame
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/1.jpg";
break;
case 'small':
// Thumbnail of a later frame(i'm not sure how they determine this)
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/2.jpg";
break;
case 'default':
case '':
default:
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/default.jpg";
break;
}
if( $echo )
echo $img_link;
else
return $img_link;
}
So I tried to use Oembed to get the thumbs instead which works for all variations of the youtube url but it retrieves the 480px/360px thumb which causes a lot of cropping to get it down to the 120px/90px size I use to display them. The other issue was it caused my page speed to increase by 4 seconds which Im guessing is a problem with the way I'm implementing it. Here's how I call the thumb inside a loop.
<?php
require_once(ABSPATH.'wp-includes/class-oembed.php');
$oembed= new WP_oEmbed;
$name = get_post_meta($post->ID,'video_code',true);
$url = $name;
//As noted in the comments below, you can auto-detect the video provider with the following
$provider = $oembed->discover($name);
//$provider = 'http://www.youtube.com/oembed';
$video = $oembed->fetch($provider, $url, array('width' => 300, 'height' => 175));
$thumb = $video->thumbnail_url; if ($thumb) { ?>
<img src="<?php echo $thumb; ?>" width="120px" height="90px" />
<?php } ?>
So how should I be doing this to maximize efficiency?
I came across this page from youtube explaining their oembed support, They mentioned that they output to json format so I made a function that gets the json data and then enables you to use it.
Feel free to ask if you need more help.
<?php
$youtube_url = 'http://youtu.be/oHg5SJYRHA0'; // url to youtube video
function getJson($youtube_url){
$baseurl = 'http://www.youtube.com/oembed?url='; // youtube oembed base url
$url = $baseurl . $youtube_url . '&format=json'; // combines the url with format json
$json = json_decode(file_get_contents($url)); // gets url and decodes the json
return $json;
}
$json = getJson($youtube_url);
// from this point on you have all your data placed in variables.
$provider_url = $json->{'provider_url'};
$thumbnail_url = $json->{'thumbnail_url'};
$title = $json->{'title'};
$html = $json->{'html'};
$author_name = $json->{'author_name'};
$height = $json->{'height'};
$thumbnail_width = $json->{'thumbnail_width'};
$thumbnail_height = $json->{'thumbnail_height'};
$width = $json->{'width'};
$version = $json->{'version'};
$author_url = $json->{'author_url'};
$provider_name = $json->{'provider_name'};
$type = $json->{'type'};
echo '<img src="'.$thumbnail_url.'" />'; // echo'ing out the thumbnail image
Ok I came up with a solution from pieces of other questions. First we need to get the id from any type of url youtube has using this function.
function getVideoId($url)
{
$parsedUrl = parse_url($url);
if ($parsedUrl === false)
return false;
if (!empty($parsedUrl['query']))
{
$query = array();
parse_str($parsedUrl['query'], $query);
if (!empty($query['v']))
return $query['v'];
}
if (strtolower($parsedUrl['host']) == 'youtu.be')
return trim($parsedUrl['path'], '/');
return false;
}
Now we can get use YouTube Data API to get the thumbnail from the video id. Looks like this.
<?php
$vid_id = getVideoId($video_code);
$json = json_decode(file_get_contents("http://gdata.youtube.com/feeds/api/videos/$vid_id?v=2&alt=jsonc"));
echo '<img src="' . $json->data->thumbnail->sqDefault . '" width="176" height="126">';
?>
The problem is that is causing an extra 2 seconds load time so I simply use the $vid_id and place it inside http://i3.ytimg.com/vi/<?php echo $vid_id; ?>/default.jpg which gets rid of the 2 seconds added by accessing the youtube api.

Resources