Disable image loading with PHP Selenium - selenium-chromedriver

How do you disable image loading in ChromeOptions? (PHP library)
I tried the following but not sure if syntax is correct
$options = new ChromeOptions();
// disable images
$options->addArguments(array(
"service_args=['--load-images=no']"
));
$caps = DesiredCapabilities::chrome();
$caps->setCapability(ChromeOptions::CAPABILITY, $options);
$driver = RemoteWebDriver::create($host, $caps);

To disable, use the argument: --blink-settings=imagesEnabled=false
$options->addArguments(array(
'--blink-settings=imagesEnabled=false'
));
https://github.com/facebook/php-webdriver/issues/641#issuecomment-512255496

Leaving following fuller examples for future reference:
This is what works:
$capabilities = DesiredCapabilities::chrome();
$capabilities->setCapability('acceptInsecureCerts', true);
$capabilities->setCapability(ChromeOptions::CAPABILITY_W3C, [
'args' => [
'--blink-settings=imagesEnabled=false',
]
]);
This is what also works:
$options = new ChromeOptions();
$options->addArguments(
[
'--blink-settings=imagesEnabled=false',
]
);
$result = DesiredCapabilities::chrome();
$result->setCapability(
ChromeOptions::CAPABILITY_W3C,
$options->toArray() // Notice that ->toArray() is used
);
The following does NOT work:
$options = new ChromeOptions();
$options->addArguments(
[
'--blink-settings=imagesEnabled=false',
]
);
$result = DesiredCapabilities::chrome();
$result->setCapability(
ChromeOptions::CAPABILITY_W3C,
$options // Notice that ->toArray() is NOT used
);

Related

Generate PDF from HTML using MPdf with Japanese characters and NotoSansJP font [duplicate]

I'm using version 7.x of mPDF and tried to follow this documentation:
https://mpdf.github.io/fonts-languages/fonts-in-mpdf-7-x.html
I just can't get it to work. No errors, but the font is still the default mPDF font.
I also tried to do it another way with the answers from these:
How to generate PDF using mPDF and add custom Google font to it?
php mPDF, impossible to set font-family and font-size
adding font to mPDF
But I guess they donĀ“t work, as they might only be for older version than 7.X ...So here's is my latest attempt trying to use the information for the 7.x documentation.
Heres my php file:
require_once __DIR__ . '/vendor/autoload.php';
$defaultConfig = (new Mpdf\Config\ConfigVariables())->getDefaults();
$fontDirs = $defaultConfig['fontDir'];
$defaultFontConfig = (new Mpdf\Config\FontVariables())->getDefaults();
$fontData = $defaultFontConfig['fontdata'];
$mpdf = new \Mpdf\Mpdf(['tempDir' => __DIR__ . '/upload'],
['fontdata' => $fontData + [
'BentonSans' => [
'R' => 'BentonSans.ttf',
'I' => 'BentonSans-Bold.ttf',
]
],
'default_font' => 'BentonSans'
]);
$url = rawurldecode($_REQUEST['url']);
$html = file_get_contents($url);
$stylesheet = file_get_contents('style.css');
$mpdf->setBasePath($url);
$mpdf->AddFontDirectory('fonts');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($html);
$mpdf->Output('filename.pdf','I');
And my css:
body {
font-family: 'BentonSans';
font-size: 14px;
font-style: normal;
font-variant: normal;
font-weight: normal;
line-height: 20px;
}
My custom fonts are stored in "fonts" which is in the same folder as the php file.
Here's the real working solution as instructed in the docs:
"Define the font details in fontdata configuration variable - font name must be lowercase".
So BentonSans must be changed to bentonsans.
Code would be:
$defaultConfig = (new \Mpdf\Config\ConfigVariables())->getDefaults();
$fontDirs = $defaultConfig['fontDir'];
$defaultFontConfig = (new \Mpdf\Config\FontVariables())->getDefaults();
$fontData = $defaultFontConfig['fontdata'];
$mpdf = new \Mpdf\Mpdf(
[
'tempDir' => __DIR__ . '/upload',
'fontDir' => array_merge($fontDirs, [
__DIR__ . '/fonts'
]),
'fontdata' => $fontData + [
'bentonsans' => [
'R' => 'BentonSans.ttf',
'I' => 'BentonSans-Bold.ttf',
],
],
'default_font' => 'bentonsans'
]
);
The issue is in Mpdf version 7 the configuration is passed as a single parameter (an array), while you were passing in multiple parameters to the constructor.
This is a valid configuration:
$mpdf = new \Mpdf\Mpdf(
[
'tempDir' => __DIR__ . '/upload',
'fontdata' => $fontData + [
'bentonsans' => [
'R' => 'BentonSans.ttf',
'I' => 'BentonSans-Bold.ttf',
],
],
'default_font' => 'BentonSans',
]
);
Got it to work. Not sure what did the trick, but here's the working code:
<?php
require_once __DIR__ . '/vendor/autoload.php';
if (!defined('_MPDF_TTFONTPATH')) {
// an absolute path is preferred, trailing slash required:
define('_MPDF_TTFONTPATH', realpath('fonts/'));
// example using Laravel's resource_path function:
// define('_MPDF_TTFONTPATH', resource_path('fonts/'));
}
function add_custom_fonts_to_mpdf($mpdf, $fonts_list) {
$fontdata = [
'bentonsans' => [
'R' => 'BentonSans.ttf',
'B' => 'BentonSans-Bold.ttf',
],
];
foreach ($fontdata as $f => $fs) {
// add to fontdata array
$mpdf->fontdata[$f] = $fs;
// add to available fonts array
foreach (['R', 'B', 'I', 'BI'] as $style) {
if (isset($fs[$style]) && $fs[$style]) {
// warning: no suffix for regular style! hours wasted: 2
$mpdf->available_unifonts[] = $f . trim($style, 'R');
}
}
}
$mpdf->default_available_fonts = $mpdf->available_unifonts;
}
$mpdf = new \Mpdf\Mpdf(['tempDir' => __DIR__ . '/upload']);
add_custom_fonts_to_mpdf($mpdf);
$url = rawurldecode($_REQUEST['url']);
$html = file_get_contents($url);
$stylesheet = file_get_contents('style.css');
$mpdf->setBasePath($url);
$mpdf->AddFontDirectory('fonts');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($html);
$mpdf->Output('filename.pdf','I');
?>

Qr code is image not showing even libraries are included

My Qr code is not working. I have already included my libraries consisting of CIqrcode and the qrcode. Is there anything that i missed? Any guides will be appreciated. Thank you
Controller:
class Testingpage extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('Testingpagemodels');
$this->load->library('Ciqrcode');
}
function QRcode($try){
QRcode::png(
$try,
$outfile = false,
$level = QR_ECLEVEL_H,
$size= 5,
$margin =2,
);
}
public function fetchqr()
{
$list = $this->Testingpagemodels->get_datatables_testing();
$json = array();
$no = $_POST['start'];
foreach ($list as $rows) {
$no++;
$first=$rows->ID_NUMBER;
$json[]=array(
'<tr><th><center><img src="testingpage/QRcode/'.$first.'" width="110px"><br>'.$rows->NAME.'<br>'.$rows->DEPARTMENT.'</center></th>', //I'm calling the function of my QR here.
);
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->Testingpagemodels->count_all_testing(),
"recordsFiltered" => $this->Testingpagemodels->count_filtered_testing(),
"data" => $json,
);
//output to json format
echo json_encode($output);
}
My Dear friend you did not mention your environment is local or live in case of the production server that might be the extension issue.to avoid that use the below mention code to display your image.
<?php
// $path is path where your image is stored.
$path = "assets/custom/img/img.jpg";
$type = pathinfo($path, PATHINFO_EXTENSION);
$file_data = file_get_contents($path);
$base64_img = 'data:image/' . $type . ';base64,' .
base64_encode($file_data);
?>
Solved.
From my "Config" i have deleted this:
From
$autoload['helper'] = array('url','html','email');
To
$autoload['helper'] = array('url','html');
Now it is working. Anyone who can help me why it is an error when I include it in autoload? Is there a conflict between qrcode and email? Thank you.

How do I write a single function in laravel that will be usable for different controllers or schedule commands and access different facades of models

I have this public function below but I will have to write a similar code in about 60 other places, I don't want to repeat myself rather, I want to be able to write a single function such that all I need change is 'Dailysaving::', and '00:00:00' each time I use the function. And please note that I will be creating several other schedule commands which this function should work for. How do I go about this please and where am I supposed to place the function I write And how do I access different models from the function. Thanks in advance for anyone that will help me out.
public function handle()
{
$users= Dailysaving::where('debit_time', '00:00:00')->where('status', 'Active')->get();
//die($users);
foreach ($users as $user) {
$email = $user->email;
$amount = $user->amount_daily * 100;
//Let's know where the payment is on the db
$user_id = $user->user_id;
$savings_id = $user->id;
$auth_code= $user->authorization_code;
//
$metastring = '{"custom_fields":[{"user_id":'. $user_id. '}, {"action": "activatedaily"},{"savings_id": '.$savings_id.'},{"savingstype": "dailysavings"}]}';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.paystack.co/transaction/charge_authorization",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'amount'=>$amount,
'email'=>$email,
'authorization_code' =>$auth_code,
'metadata' => $metastring,
]),
CURLOPT_HTTPHEADER => [
"authorization:Bearer sk_test_656456h454545",
"content-type: application/json",
"cache-control: no-cache"
],
));
$response = curl_exec($curl);
$err = curl_error($curl);
if($err){
$failedtranx = new Failedtransaction;
$failedtranx->error = $err;
$failedtranx->save();
}
if($response) {
$tranx = json_decode($response);
if (!$tranx->status) {
// there was an error contacting the Paystack API
//register in failed transaction table
$failedtranx = new Failedtransaction;
$failedtranx->error = $err;
$failedtranx->save();
}
if ('success' == $tranx->data->status) {
$auth_code = $tranx->data->authorization->authorization_code;
$amount = ($tranx->data->amount) / 100;
$last_transaction = $tranx->data->transaction_date;
$payment_ref = $tranx->data->reference;
$record = new Transactionrecord;
$record->payment_ref = $payment_ref;
$record->save();
//saving complete
//die('saved');
$item = Dailysaving::find($savings_id);
$total_deposit = $item->total_deposit + $amount;
$item->total_deposit = $total_deposit;
$item->last_transaction_date = date('Y-m-d H:i:s');
$target = $item->day_target;
if ($target == $total_deposit) {
$item->status = 'Completed';
}
$item->save();
}
echo 'done';
}
else{
echo 'failed';
}
}
}
As I understand you are trying to make custom helper functions.
So you need create helpers.php with your functions and follow instructions in the below answer: https://stackoverflow.com/a/28290359/5407558

wordpress json rest API to get custom field data

I am currently using the JSON REST API (WP API) plug-in to get my post and page data.
I have noticed that none of my custom field data is returned in the json, and looking at the routes, i don't think i can obtain these.
Any ideas via the current plug-in, or how I can accomplish this otherwise?
If you are using 'advanced custom fields' - until something more official is decided, you can use this plugin: https://github.com/times/acf-to-wp-api (and now on the shelf in standard wp plugin area too.)
It will include the custom fields under acf: [], in your json structure.
To grab a custom field value using native WP functions only, add the following to your functions.php
function my_rest_prepare_post( $data, $post, $request ) {
$_data = $data->data;
$_data[$field] = get_post_meta( $post->ID, 'my_custom_field_key', true );
$data->data = $_data;
return $data;
}
add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );
Replace 'my_custom_field_key' with your custom field key name.
For multiple fields:
function my_rest_prepare_post( $data, $post, $request ) {
$_data = $data->data;
// My custom fields that I want to include in the WP API v2 responce
$fields = ['writer', 'publisher', 'year', 'youtube_link'];
foreach ( $fields as $field ) {
$_data[$field] = get_post_meta( $post->ID, $field, true );
}
$data->data = $_data;
return $data;
}
add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );
You need to create this file contain following code in
wp-content\themes\name\inc\functions
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
/*
* init function
*/
if ( ! function_exists( 'mnu_rest_init' ) ) {
function mnu_rest_init() {
register_rest_route( 'guider/v1', '/booking', array(
'methods' => 'GET',
'callback' => 'handle_get_all',
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
}
) );
register_rest_route( 'guider/v1', '/booking', array(
'methods' => 'POST',
'callback' => 'handle_post_booking',
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
}
) );
}
}
//GET QUERY PARMS
function handle_get_all( $request_data) {
$parameters = $request_data->get_params();
$userId = $parameters["Id"];
global $wpdb;
$query = "SELECT * FROM `wp_trav_tour_bookings` WHERE `user_id` = $userId";
$list = $wpdb->get_results($query);
return $list;
}
// GET BODY PARMS
function handle_post_booking( $request_data) {
$parameters = $request_data->get_body();
$params = json_decode( $parameters , true );
// $userId = $parameters["Id"];
// global $wpdb;
// $query = "SELECT * FROM `wp_trav_tour_bookings` WHERE `user_id` = $userId";
// $list = $wpdb->get_results($query);
return $params ;
}
then you need to add
//actions
add_action( 'rest_api_init', 'mnu_rest_init');
to your main.php in
wp-content\themes\name\inc\functions
to do that you need to require this file to main.php
require_once dirname( __FILE__ ) . '/filename.php';
You can manipulate the response and add custom fields to the JSON. I'm using Advanced Custom Fields in my example but you can just add any key/value-pairs to the data object before returning it.
// In functions.php
function modify_rest_post( $data, $post, $request ) {
if (is_admin()) {
return $data;
}
$data->my_favorite_data = get_field('my_custom_field', $post->ID);
return $data;
}
add_filter( 'rest_prepare_post', 'modify_rest_post', 10, 3 );

Creating and filling database from a Controller (Symfony 2, Doctrine)

I am trying to create an installation Bundle for my Symfony 2.2.3 application.
Therefore I want to drop/create a database (mysql) and then create the schema via Controller Actions.
My Code:
$kernel = $this->get('kernel');
$application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
$application->setAutoExit(false);
// drop old database
$options = array('command' => 'doctrine:database:drop', '--force' => true);
$application->run(new \Symfony\Component\Console\Input\ArrayInput($options));
// create new database
$options = array('command' => 'doctrine:database:create');
$result = $application->run(new \Symfony\Component\Console\Input\ArrayInput($options));
// check if database:create was successful, then create schema
if($result == 0) {
$options = array('command' => 'doctrine:schema:create');
$result = $application->run(new \Symfony\Component\Console\Input\ArrayInput($options));
}
database:drop and database:create work fine (both commands return 0), but creating the schema then fails.
However, when I comment the first 2 commands out so that only doctrine:schema:create will be executed (if clause removed, of course) and reload the page without changing anything else the database schema will be created properly.
Can anyone tell me what the problem is?
This code works (Symfony 2.7)
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
/**
* #Route("/resetDB", name="adminResetDB")
*/
public function resetDBAction()
{
$application = new Application($this->get('kernel'));
$application->setAutoExit(false);
// Drop old database
$options = array('command' => 'doctrine:database:drop', '--force' => true);
$application->run(new ArrayInput($options));
// Make sure we close the original connection because it lost the reference to the database
$this->getDoctrine()->getManager()->getConnection()->close();
// Create new database
$options = array('command' => 'doctrine:database:create');
$application->run(new ArrayInput($options));
// Update schema
$options = array('command' => 'doctrine:schema:update','--force' => true);
$application->run(new ArrayInput($options));
// Loading Fixtures, --append option prevent confirmation message
$options = array('command' => 'doctrine:fixtures:load','--append' => true);
$application->run(new ArrayInput($options));
return $this->redirect($this->generateUrl('index'));
}