Retrieving data from the session - php

How to retrieve data in .htm page using twig.
public function onRun()
{
$captchaImagePath = '/Applications/MAMP/htdocs/install-master/storage/app/uploads/captcha/';
Log::info($captchaImagePath);
$captchaImageUrl = '/Applications/MAMP/htdocs/install-master/storage/app/uploads/captcha/';
$captchaFontPath = '/Applications/MAMP/htdocs/install-master/storage/app/uploads/fonts/verdana.ttf';
$val = array(
'word_length' => 5,
'word' => '',
'img_path' => $captchaImagePath,
'img_url' => $captchaImageUrl,
'font_path' => $captchaFontPath,
'img_width' => '150',
'img_height' => 30,
'expiration' => 7200
);
$img_path=$captchaImagePath;
$img_url=$captchaImageUrl;
$font_path=$captchaFontPath;
$captcha = $this->create_captcha($val,$img_path,$img_url,$font_path);
$url = Request::url();
if (ends_with($url, ['.html', '.htm']))
{
$url = str_replace(['.html', '.htm'], '', $url);
return Redirect::to($url, 301)->with($captcha);
}
Log::info($url);
Log::info($captcha);
}
the function in same file public function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '')
{
// Log::info($data);
// Log::info($img_path);
// Log::info($img_url);
// Log::info($font_path);
if(!isset($data['word_length']))
{
$length=5;
}
else
{
$length=$data['word_length'];
}
//Log::info($length);
$defaults = array('word' => '', 'word_length' => $length,'img_path' => '', 'img_url' => '', 'img_width' => '150', 'img_height' => '30', 'font_path' => '', 'expiration' => 7200);
// Log::info($defaults);
foreach ($defaults as $key => $val)
{
if ( ! is_array($data))
{
if ( ! isset($$key) OR $$key == '')
{
$$key = $val;
// Log::info( $$key);
}
}
else
{
$$key = ( ! isset($data[$key])) ? $val : $data[$key];
}
}
// Log::info($img_path); Log::info($img_url);
if ($img_path == '' OR $img_url == '')
{
return FALSE;
}
if ( ! is_dir($img_path))
{
return FALSE;
}
if ( ! is_writable($img_path))
{
return FALSE;
}
if ( ! extension_loaded('gd'))
{
return FALSE;
}
// -----------------------------------
// Remove old images
// -----------------------------------
list($usec, $sec) = explode(" ", microtime());
$now = ((float)$usec + (float)$sec);
$current_dir = #opendir($img_path);
while($filename = #readdir($current_dir))
{
if ($filename != "." and $filename != ".." and $filename != "index.html")
{
$name = str_replace(".jpg", "", $filename);
if (($name + $expiration) < $now)
{
#unlink($img_path.$filename);
}
}
}
#closedir($current_dir);
// -----------------------------------
// Do we have a "word" yet?
// -----------------------------------
if ($word == '')
{
//$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$str = '';
for ($i = 0; $i < $word_length; $i++)
{
$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
}
$word = $str;
}
// -----------------------------------
// Determine angle and position
// -----------------------------------
$length = strlen($word);
$angle = ($length >= 6) ? rand(-($length-6), ($length-6)) : 0;
$x_axis = rand(6, (360/$length)-16);
$y_axis = ($angle >= 0 ) ? rand($img_height, $img_width) : rand(6, $img_height);
// -----------------------------------
// Create image
// -----------------------------------
// PHP.net recommends imagecreatetruecolor(), but it isn't always available
if (function_exists('imagecreatetruecolor'))
{
$im = imagecreatetruecolor($img_width, $img_height);
}
else
{
$im = imagecreate($img_width, $img_height);
}
// -----------------------------------
// Assign colors
// -----------------------------------
$bg_color = imagecolorallocate ($im, 255, 255, 255);
$border_color = imagecolorallocate ($im, 232, 244, 252);
$text_color = imagecolorallocate ($im, 57, 136, 190);
$grid_color = imagecolorallocate($im, 220, 239, 253);
$shadow_color = imagecolorallocate($im, 255, 240, 240);
// -----------------------------------
// Create the rectangle
// -----------------------------------
ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $bg_color);
// -----------------------------------
// Create the spiral pattern
// -----------------------------------
$theta = 1;
$thetac = 7;
$radius = 16;
$circles = 20;
$points = 32;
for ($i = 0; $i < ($circles * $points) - 1; $i++)
{
$theta = $theta + $thetac;
$rad = $radius * ($i / $points );
$x = ($rad * cos($theta)) + $x_axis;
$y = ($rad * sin($theta)) + $y_axis;
$theta = $theta + $thetac;
$rad1 = $radius * (($i + 1) / $points);
$x1 = ($rad1 * cos($theta)) + $x_axis;
$y1 = ($rad1 * sin($theta )) + $y_axis;
imageline($im, $x, $y, $x1, $y1, $grid_color);
$theta = $theta - $thetac;
}
// -----------------------------------
// Write the text
// -----------------------------------
$use_font = ($font_path != '' AND file_exists($font_path) AND function_exists('imagettftext')) ? TRUE : FALSE;
if ($use_font == FALSE)
{
$font_size = 5;
$x = rand(0, $img_width/($length/3));
$y = 0;
}
else
{
$font_size = 16;
$x = rand(0, $img_width/($length/1.5));
$y = $font_size+2;
}
for ($i = 0; $i < strlen($word); $i++)
{
if ($use_font == FALSE)
{
$y = rand(0 , $img_height/2);
imagestring($im, $font_size, $x, $y, substr($word, $i, 1), $text_color);
$x += ($font_size*2);
}
else
{
$y = rand($img_height/2, $img_height-3);
imagettftext($im, $font_size, $angle, $x, $y, $text_color, $font_path, substr($word, $i, 1));
$x += $font_size;
}
}
// -----------------------------------
// Create the border
// -----------------------------------
imagerectangle($im, 0, 0, $img_width-1, $img_height-1, $border_color);
// -----------------------------------
// Generate the image
// -----------------------------------
$img_name = $now.'.jpg';
ImageJPEG($im, $img_path.$img_name);
$img = "<img src=\"$img_url$img_name\" width=\"$img_width\" height=\"$img_height\" style=\"border:0;\" alt=\" \" />";
ImageDestroy($im);
return array('word' => $word, 'time' => $now, 'image' => $img);
}
}
now how to use captcha which is image + word created through above function in
default.htm
<span id="captcha">
<img src="{{captcha.image}}" width="150" height="30" style="border:0;" alt=" " /> </span>
the file created by above function saves in given path bt how to show that image when form appears...................................................................................................................................................

First you need to correct your syntex, to flash session while redirecting you need to use
with('name', 'value')
so you need to use
if (ends_with($url, ['.html', '.htm']))
{
$url = str_replace(['.html', '.htm'], '', $url);
return Redirect::to($url, 301)->with('captcha', $captcha); // <- correct this
// $this->create_captcha() must return string value
// here $captch seems object/image so you should not pass objects in session
}
instead I guess you need to pass some random value
$someRandomValue = 'blabla';
$val = array(
'word_length' => 5,
'word' => '', // <----------------- something here [$someRandomValue]
'img_path' => $captchaImagePath,
'img_url' => $captchaImageUrl,
'font_path' => $captchaFontPath,
'img_width' => '150',
'img_height' => 30,
'expiration' => 7200
);
and then pass it like
with('captcha', $someRandomValue)
and now in other place you can get it by
$captchaValue = session::get('captcha')
so this $captchaValue will be same as $someRandomValue
in short in last you need user input as text/string and compare with $captchaValue (this will be from session) to validate it
if any doubt please comment.

Related

How to add a simple message by 'echo' in invoice pdf format in Magento2?

I have generated an invoice slip from magento2 sales order's invoice option and got the screenshot for the reference, see the screenshot: https://prnt.sc/tje4zn
This is the file path for invoice pdf: /vendor/magento/module-sales/Model/Order/Pdf/AbstractPdf.php and below is the file code,
<?php
namespace Magento\Sales\Model\Order\Pdf;
use Magento\Framework\App\Filesystem\DirectoryList;
/**
* Sales Order PDF abstract model
*/
abstract class AbstractPdf extends \Magento\Framework\DataObject
{
public $y;
protected $_renderers = [];
const XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID = 'sales_pdf/invoice/put_order_id';
const XML_PATH_SALES_PDF_SHIPMENT_PUT_ORDER_ID = 'sales_pdf/shipment/put_order_id';
const XML_PATH_SALES_PDF_CREDITMEMO_PUT_ORDER_ID = 'sales_pdf/creditmemo/put_order_id';
protected $_pdf;
abstract public function getPdf();
protected $_paymentData;
protected $string;
protected $_localeDate;
protected $_scopeConfig;
protected $_mediaDirectory;
protected $_rootDirectory;
protected $_pdfConfig;
protected $_pdfTotalFactory;
protected $_pdfItemsFactory;
protected $inlineTranslation;
protected $addressRenderer;
public function __construct(
\Magento\Payment\Helper\Data $paymentData,
\Magento\Framework\Stdlib\StringUtils $string,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\Filesystem $filesystem,
Config $pdfConfig,
\Magento\Sales\Model\Order\Pdf\Total\Factory $pdfTotalFactory,
\Magento\Sales\Model\Order\Pdf\ItemsFactory $pdfItemsFactory,
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
\Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
\Magento\Sales\Model\Order\Address\Renderer $addressRenderer,
array $data = []
) {
$this->addressRenderer = $addressRenderer;
$this->_paymentData = $paymentData;
$this->_localeDate = $localeDate;
$this->string = $string;
$this->_scopeConfig = $scopeConfig;
$this->_mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->_rootDirectory = $filesystem->getDirectoryRead(DirectoryList::ROOT);
$this->_pdfConfig = $pdfConfig;
$this->_pdfTotalFactory = $pdfTotalFactory;
$this->_pdfItemsFactory = $pdfItemsFactory;
$this->inlineTranslation = $inlineTranslation;
parent::__construct($data);
}
public function widthForStringUsingFontSize($string, $font, $fontSize)
{
$drawingString = '"libiconv"' == ICONV_IMPL ? iconv(
'UTF-8',
'UTF-16BE//IGNORE',
$string
) : #iconv(
'UTF-8',
'UTF-16BE',
$string
);
$characters = [];
for ($i = 0; $i < strlen($drawingString); $i++) {
$characters[] = ord($drawingString[$i++]) << 8 | ord($drawingString[$i]);
}
$glyphs = $font->glyphNumbersForCharacters($characters);
$widths = $font->widthsForGlyphs($glyphs);
$stringWidth = array_sum($widths) / $font->getUnitsPerEm() * $fontSize;
return $stringWidth;
}
public function getAlignRight($string, $x, $columnWidth, \Zend_Pdf_Resource_Font $font, $fontSize, $padding = 5)
{
$width = $this->widthForStringUsingFontSize($string, $font, $fontSize);
return $x + $columnWidth - $width - $padding;
}
public function getAlignCenter($string, $x, $columnWidth, \Zend_Pdf_Resource_Font $font, $fontSize)
{
$width = $this->widthForStringUsingFontSize($string, $font, $fontSize);
return $x + round(($columnWidth - $width) / 2);
}
protected function insertLogo(&$page, $store = null)
{
$this->y = $this->y ? $this->y : 815;
$image = $this->_scopeConfig->getValue(
'sales/identity/logo',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
$store
);
if ($image) {
$imagePath = '/sales/store/logo/' . $image;
if ($this->_mediaDirectory->isFile($imagePath)) {
$image = \Zend_Pdf_Image::imageWithPath($this->_mediaDirectory->getAbsolutePath($imagePath));
$top = 830;
//top border of the page
$widthLimit = 270;
//half of the page width
$heightLimit = 270;
//assuming the image is not a "skyscraper"
$width = $image->getPixelWidth();
$height = $image->getPixelHeight();
//preserving aspect ratio (proportions)
$ratio = $width / $height;
if ($ratio > 1 && $width > $widthLimit) {
$width = $widthLimit;
$height = $width / $ratio;
} elseif ($ratio < 1 && $height > $heightLimit) {
$height = $heightLimit;
$width = $height * $ratio;
} elseif ($ratio == 1 && $height > $heightLimit) {
$height = $heightLimit;
$width = $widthLimit;
}
$y1 = $top - $height;
$y2 = $top;
$x1 = 25;
$x2 = $x1 + $width;
//coordinates after transformation are rounded by Zend
$page->drawImage($image, $x1, $y1, $x2, $y2);
$this->y = $y1 - 10;
}
}
}
protected function _formatAddress($address)
{
$return = [];
foreach (explode('|', $address) as $str) {
foreach ($this->string->split($str, 45, true, true) as $part) {
if (empty($part)) {
continue;
}
$return[] = $part;
}
}
return $return;
}
protected function _calcAddressHeight($address)
{
$y = 0;
foreach ($address as $value) {
if ($value !== '') {
$text = [];
foreach ($this->string->split($value, 55, true, true) as $_value) {
$text[] = $_value;
}
foreach ($text as $part) {
$y += 15;
}
}
}
return $y;
}
protected function insertOrder(&$page, $obj, $putOrderId = true)
{
if ($obj instanceof \Magento\Sales\Model\Order) {
$shipment = null;
$order = $obj;
} elseif ($obj instanceof \Magento\Sales\Model\Order\Shipment) {
$shipment = $obj;
$order = $shipment->getOrder();
}
$this->y = $this->y ? $this->y : 815;
$top = $this->y;
$page->setFillColor(new \Zend_Pdf_Color_GrayScale(0.45));
$page->setLineColor(new \Zend_Pdf_Color_GrayScale(0.45));
$page->drawRectangle(25, $top, 570, $top - 55);
$page->setFillColor(new \Zend_Pdf_Color_GrayScale(1));
$this->setDocHeaderCoordinates([25, $top, 570, $top - 55]);
$this->_setFontRegular($page, 10);
if ($putOrderId) {
$page->drawText(__('Order No # ') . $order->getRealOrderId(), 35, $top -= 30, 'UTF-8');
$top +=15;
}
$top -=30;
$page->drawText(
__('Order Date: ') .
$this->_localeDate->formatDate(
$this->_localeDate->scopeDate(
$order->getStore(),
$order->getCreatedAt(),
true
),
\IntlDateFormatter::MEDIUM,
false
),
35,
$top,
'UTF-8'
);
$top -= 10;
$page->setFillColor(new \Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
$page->setLineColor(new \Zend_Pdf_Color_GrayScale(0.5));
$page->setLineWidth(0.5);
$page->drawRectangle(25, $top, 275, $top - 25);
$page->drawRectangle(275, $top, 570, $top - 25);
/* Calculate blocks info */
/* Billing Address */
$billingAddress = $this->_formatAddress($this->addressRenderer->format($order->getBillingAddress(), 'pdf'));
/* Payment */
$paymentInfo = $this->_paymentData->getInfoBlock($order->getPayment())->setIsSecureMode(true)->toPdf();
$paymentInfo = htmlspecialchars_decode($paymentInfo, ENT_QUOTES);
$payment = explode('{{pdf_row_separator}}', $paymentInfo);
foreach ($payment as $key => $value) {
if (strip_tags(trim($value)) == '') {
unset($payment[$key]);
}
}
reset($payment);
/* Shipping Address and Method */
if (!$order->getIsVirtual()) {
/* Shipping Address */
$shippingAddress = $this->_formatAddress($this->addressRenderer->format($order->getShippingAddress(), 'pdf'));
$shippingMethod = $order->getShippingDescription();
}
$page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
$this->_setFontBold($page, 12);
$page->drawText(__('Billed to:'), 35, $top - 15, 'UTF-8');
if (!$order->getIsVirtual()) {
$page->drawText(__('Shipped/Delivery to:'), 285, $top - 15, 'UTF-8');
} else {
$page->drawText(__('Payment Method:'), 285, $top - 15, 'UTF-8');
}
$addressesHeight = $this->_calcAddressHeight($billingAddress);
if (isset($shippingAddress)) {
$addressesHeight = max($addressesHeight, $this->_calcAddressHeight($shippingAddress));
}
$page->setFillColor(new \Zend_Pdf_Color_GrayScale(1));
$page->drawRectangle(25, $top - 25, 570, $top - 33 - $addressesHeight);
$page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
$this->_setFontRegular($page, 10);
$this->y = $top - 40;
$addressesStartY = $this->y;
foreach ($billingAddress as $value) {
if ($value !== '') {
$text = [];
foreach ($this->string->split($value, 45, true, true) as $_value) {
$text[] = $_value;
}
foreach ($text as $part) {
$page->drawText(strip_tags(ltrim($part)), 35, $this->y, 'UTF-8');
$this->y -= 15;
}
}
}
$addressesEndY = $this->y;
if (!$order->getIsVirtual()) {
$this->y = $addressesStartY;
foreach ($shippingAddress as $value) {
if ($value !== '') {
$text = [];
foreach ($this->string->split($value, 45, true, true) as $_value) {
$text[] = $_value;
}
foreach ($text as $part) {
$page->drawText(strip_tags(ltrim($part)), 285, $this->y, 'UTF-8');
$this->y -= 15;
}
}
}
$addressesEndY = min($addressesEndY, $this->y);
$this->y = $addressesEndY;
$page->setFillColor(new \Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
$page->setLineWidth(0.5);
$page->drawRectangle(25, $this->y, 275, $this->y - 25);
$page->drawRectangle(275, $this->y, 570, $this->y - 25);
$this->y -= 15;
$this->_setFontBold($page, 12);
$page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
$page->drawText(__('Payment Method'), 35, $this->y, 'UTF-8');
$page->drawText(__('Shipping Method:'), 285, $this->y, 'UTF-8');
$this->y -= 10;
$page->setFillColor(new \Zend_Pdf_Color_GrayScale(1));
$this->_setFontRegular($page, 10);
$page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
$paymentLeft = 35;
$yPayments = $this->y - 15;
} else {
$yPayments = $addressesStartY;
$paymentLeft = 285;
}
foreach ($payment as $value) {
if (trim($value) != '') {
//Printing "Payment Method" lines
$value = preg_replace('/<br[^>]*>/i', "\n", $value);
foreach ($this->string->split($value, 45, true, true) as $_value) {
$page->drawText(strip_tags(trim($_value)), $paymentLeft, $yPayments, 'UTF-8');
$yPayments -= 15;
}
}
}
if ($order->getIsVirtual()) {
// replacement of Shipments-Payments rectangle block
$yPayments = min($addressesEndY, $yPayments);
$page->drawLine(25, $top - 25, 25, $yPayments);
$page->drawLine(570, $top - 25, 570, $yPayments);
$page->drawLine(25, $yPayments, 570, $yPayments);
$this->y = $yPayments - 15;
} else {
$topMargin = 15;
$methodStartY = $this->y;
$this->y -= 15;
foreach ($this->string->split($shippingMethod, 45, true, true) as $_value) {
$page->drawText(strip_tags(trim($_value)), 285, $this->y, 'UTF-8');
$this->y -= 15;
}
$yShipments = $this->y;
$totalShippingChargesText = "(" . __(
'Total Shipping Charges'
) . " " . $order->formatPriceTxt(
$order->getShippingAmount()
) . ")";
$page->drawText($totalShippingChargesText, 285, $yShipments - $topMargin, 'UTF-8');
$yShipments -= $topMargin + 10;
$tracks = [];
if ($shipment) {
$tracks = $shipment->getAllTracks();
}
if (count($tracks)) {
$page->setFillColor(new \Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
$page->setLineWidth(0.5);
$page->drawRectangle(285, $yShipments, 510, $yShipments - 10);
$page->drawLine(400, $yShipments, 400, $yShipments - 10);
//$page->drawLine(510, $yShipments, 510, $yShipments - 10);
$this->_setFontRegular($page, 9);
$page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
//$page->drawText(__('Carrier'), 290, $yShipments - 7 , 'UTF-8');
$page->drawText(__('Title'), 290, $yShipments - 7, 'UTF-8');
$page->drawText(__('Number'), 410, $yShipments - 7, 'UTF-8');
$yShipments -= 20;
$this->_setFontRegular($page, 8);
foreach ($tracks as $track) {
$maxTitleLen = 45;
$endOfTitle = strlen($track->getTitle()) > $maxTitleLen ? '...' : '';
$truncatedTitle = substr($track->getTitle(), 0, $maxTitleLen) . $endOfTitle;
$page->drawText($truncatedTitle, 292, $yShipments, 'UTF-8');
$page->drawText($track->getNumber(), 410, $yShipments, 'UTF-8');
$yShipments -= $topMargin - 5;
}
} else {
$yShipments -= $topMargin - 5;
}
$currentY = min($yPayments, $yShipments);
$page->drawLine(25, $methodStartY, 25, $currentY);
$page->drawLine(25, $currentY, 570, $currentY);
$page->drawLine(570, $currentY, 570, $methodStartY);
$this->y = $currentY;
$this->y -= 15;
}
}
public function insertDocumentNumber(\Zend_Pdf_Page $page, $text)
{
$page->setFillColor(new \Zend_Pdf_Color_GrayScale(1));
$this->_setFontRegular($page, 10);
$docHeader = $this->getDocHeaderCoordinates();
$page->drawText($text, 35, $docHeader[1] - 15, 'UTF-8');
}
protected function _sortTotalsList($a, $b)
{
if (!isset($a['sort_order']) || !isset($b['sort_order'])) {
return 0;
}
if ($a['sort_order'] == $b['sort_order']) {
return 0;
}
return $a['sort_order'] > $b['sort_order'] ? 1 : -1;
}
protected function _getTotalsList()
{
$totals = $this->_pdfConfig->getTotals();
usort($totals, [$this, '_sortTotalsList']);
$totalModels = [];
foreach ($totals as $totalInfo) {
$class = empty($totalInfo['model']) ? null : $totalInfo['model'];
$totalModel = $this->_pdfTotalFactory->create($class);
$totalModel->setData($totalInfo);
$totalModels[] = $totalModel;
}
return $totalModels;
}
protected function insertTotals($page, $source)
{
$order = $source->getOrder();
$totals = $this->_getTotalsList();
$lineBlock = ['lines' => [], 'height' => 15];
foreach ($totals as $total) {
$total->setOrder($order)->setSource($source);
if ($total->canDisplay()) {
$total->setFontSize(10);
foreach ($total->getTotalsForDisplay() as $totalData) {
$lineBlock['lines'][] = [
[
'text' => $totalData['label'],
'feed' => 475,
'align' => 'right',
'font_size' => $totalData['font_size'],
'font' => 'bold',
],
[
'text' => $totalData['amount'],
'feed' => 565,
'align' => 'right',
'font_size' => $totalData['font_size'],
'font' => 'bold'
],
];
}
}
}
$this->y -= 20;
$page = $this->drawLineBlocks($page, [$lineBlock]);
return $page;
}
protected function _parseItemDescription($item)
{
$matches = [];
$description = $item->getDescription();
if (preg_match_all('/<li.*?>(.*?)<\/li>/i', $description, $matches)) {
return $matches[1];
}
return [$description];
}
protected function _beforeGetPdf()
{
$this->inlineTranslation->suspend();
}
protected function _afterGetPdf()
{
$this->inlineTranslation->resume();
}
protected function _formatOptionValue($value, $order)
{
$resultValue = '';
if (is_array($value)) {
if (isset($value['qty'])) {
$resultValue .= sprintf('%d', $value['qty']) . ' x ';
}
$resultValue .= $value['title'];
if (isset($value['price'])) {
$resultValue .= " " . $order->formatPrice($value['price']);
}
return $resultValue;
} else {
return $value;
}
}
protected function _initRenderer($type)
{
$rendererData = $this->_pdfConfig->getRenderersPerProduct($type);
foreach ($rendererData as $productType => $renderer) {
$this->_renderers[$productType] = ['model' => $renderer, 'renderer' => null];
}
}
protected function _getRenderer($type)
{
if (!isset($this->_renderers[$type])) {
$type = 'default';
}
if (!isset($this->_renderers[$type])) {
throw new \Magento\Framework\Exception\LocalizedException(__('We found an invalid renderer model.'));
}
if ($this->_renderers[$type]['renderer'] === null) {
$this->_renderers[$type]['renderer'] = $this->_pdfItemsFactory->get($this->_renderers[$type]['model']);
}
return $this->_renderers[$type]['renderer'];
}
public function getRenderer($type)
{
return $this->_getRenderer($type);
}
protected function _drawItem(\Magento\Framework\DataObject $item, \Zend_Pdf_Page $page, \Magento\Sales\Model\Order $order)
{
$type = $item->getOrderItem()->getProductType();
$renderer = $this->_getRenderer($type);
$renderer->setOrder($order);
$renderer->setItem($item);
$renderer->setPdf($this);
$renderer->setPage($page);
$renderer->setRenderedModel($this);
$renderer->draw();
return $renderer->getPage();
}
protected function _setFontRegular($object, $size = 7)
{
$font = \Zend_Pdf_Font::fontWithPath(
$this->_rootDirectory->getAbsolutePath('lib/internal/GnuFreeFont/FreeSerif.ttf')
);
$object->setFont($font, $size);
return $font;
}
protected function _setFontBold($object, $size = 7)
{
$font = \Zend_Pdf_Font::fontWithPath(
$this->_rootDirectory->getAbsolutePath('lib/internal/GnuFreeFont/FreeSerifBold.ttf')
);
$object->setFont($font, $size);
return $font;
}
protected function _setFontItalic($object, $size = 7)
{
$font = \Zend_Pdf_Font::fontWithPath(
$this->_rootDirectory->getAbsolutePath('lib/internal/GnuFreeFont/FreeSerifItalic.ttf')
);
$object->setFont($font, $size);
return $font;
}
protected function _setPdf(\Zend_Pdf $pdf)
{
$this->_pdf = $pdf;
return $this;
}
protected function _getPdf()
{
if (!$this->_pdf instanceof \Zend_Pdf) {
throw new \Magento\Framework\Exception\LocalizedException(__('Please define the PDF object before using.'));
}
return $this->_pdf;
}
public function newPage(array $settings = [])
{
$pageSize = !empty($settings['page_size']) ? $settings['page_size'] : \Zend_Pdf_Page::SIZE_A4;
$page = $this->_getPdf()->newPage($pageSize);
$this->_getPdf()->pages[] = $page;
$this->y = 800;
return $page;
}
public function drawLineBlocks(\Zend_Pdf_Page $page, array $draw, array $pageSettings = [])
{
foreach ($draw as $itemsProp) {
if (!isset($itemsProp['lines']) || !is_array($itemsProp['lines'])) {
throw new \Magento\Framework\Exception\LocalizedException(
__('We don\'t recognize the draw line data. Please define the "lines" array.')
);
}
$lines = $itemsProp['lines'];
$height = isset($itemsProp['height']) ? $itemsProp['height'] : 10;
if (empty($itemsProp['shift'])) {
$shift = 0;
foreach ($lines as $line) {
$maxHeight = 0;
foreach ($line as $column) {
$lineSpacing = !empty($column['height']) ? $column['height'] : $height;
if (!is_array($column['text'])) {
$column['text'] = [$column['text']];
}
$top = 0;
foreach ($column['text'] as $part) {
$top += $lineSpacing;
}
$maxHeight = $top > $maxHeight ? $top : $maxHeight;
}
$shift += $maxHeight;
}
$itemsProp['shift'] = $shift;
}
if ($this->y - $itemsProp['shift'] < 15) {
$page = $this->newPage($pageSettings);
}
foreach ($lines as $line) {
$maxHeight = 0;
foreach ($line as $column) {
$font = $this->setFont($page, $column);
$fontSize = $column['font_size'];
if (!is_array($column['text'])) {
$column['text'] = [$column['text']];
}
$lineSpacing = !empty($column['height']) ? $column['height'] : $height;
$top = 0;
foreach ($column['text'] as $part) {
if ($this->y - $lineSpacing < 15) {
$page = $this->newPage($pageSettings);
$font = $this->setFont($page, $column);
$fontSize = $column['font_size'];
}
$feed = $column['feed'];
$textAlign = empty($column['align']) ? 'left' : $column['align'];
$width = empty($column['width']) ? 0 : $column['width'];
switch ($textAlign) {
case 'right':
if ($width) {
$feed = $this->getAlignRight($part, $feed, $width, $font, $fontSize);
} else {
$feed = $feed - $this->widthForStringUsingFontSize($part, $font, $fontSize);
}
break;
case 'center':
if ($width) {
$feed = $this->getAlignCenter($part, $feed, $width, $font, $fontSize);
}
break;
default:
break;
}
$page->drawText($part, $feed, $this->y - $top, 'UTF-8');
$top += $lineSpacing;
}
$maxHeight = $top > $maxHeight ? $top : $maxHeight;
}
$this->y -= $maxHeight;
}
}
return $page;
}
}
I want to echo simple text message in the end of the file like <?php echo "NOTE: This is not a GST invoice. This is a packing slip only."; ?>
Please help how I can add this message to pdf invoice format as I have also mentioned in the screenshot above.
Many Thanks in Advance.
Assuming you have a custom MyCompany_Invoice module:
Put following content into the MyCompany/Invoice/etc/di.xml:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Sales\Model\Order\Pdf\Invoice" type="MyCompany\Invoice\Model\Order\Pdf\InvoicePdf"/>
</config>
Now create MyCompany\Invoice\Model\Order\Pdf\InvoicePdf.php:
<?php
namespace MyCompany\Invoice\Model\Order\Pdf;
use \Magento\Sales\Model\Order\Pdf\Invoice;
class InvoicePdf extends Invoice
{
/**
* We only need to override the getPdf of Invoice,
* most of this method is copied directly from parent class
*
* #param array $invoices
* #return \Zend_Pdf
*/
public function getPdf($invoices = []) {
$this->_beforeGetPdf();
$this->_initRenderer('invoice');
$pdf = new \Zend_Pdf();
$this->_setPdf($pdf);
$style = new \Zend_Pdf_Style();
$this->_setFontBold($style, 10);
foreach ($invoices as $invoice) {
if ($invoice->getStoreId()) {
$this->_localeResolver->emulate($invoice->getStoreId());
$this->_storeManager->setCurrentStore($invoice->getStoreId());
}
$page = $this->newPage();
$order = $invoice->getOrder();
/* Add image */
$this->insertLogo($page, $invoice->getStore());
/* Add address */
$this->insertAddress($page, $invoice->getStore());
/* Add head */
$this->insertOrder(
$page,
$order,
$this->_scopeConfig->isSetFlag(
self::XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
$order->getStoreId()
)
);
/* Add document text and number */
$this->insertDocumentNumber($page, __('Invoice # ') . $invoice->getIncrementId());
/* Add table */
$this->_drawHeader($page);
/* Add body */
foreach ($invoice->getAllItems() as $item) {
if ($item->getOrderItem()->getParentItem()) {
continue;
}
/* Draw item */
$this->_drawItem($item, $page, $order);
$page = end($pdf->pages);
}
/* Add totals */
$this->insertTotals($page, $invoice);
if ($invoice->getStoreId()) {
$this->_localeResolver->revert();
}
// draw custom notice
$this->drawNotice($page);
}
$this->_afterGetPdf();
return $pdf;
}
/**
* draw notice below content
*
* #param \Zend_Pdf_Page $page
*/
protected function drawNotice(\Zend_Pdf_Page $page) {
$iFontSize = 10; // font size
$iColumnWidth = 520; // whole page width
$iWidthBorder = 260; // half page width
$sNotice = "NOTE: This is not a GST invoice. This is a packing slip only."; // your message
$iXCoordinateText = 30;
$sEncoding = 'UTF-8';
$this->y -= 10; // move down on page
try {
$oFont = $this->_setFontRegular($page, $iFontSize);
$iXCoordinateText = $this->getAlignCenter($sNotice, $iXCoordinateText, $iColumnWidth, $oFont, $iFontSize); // center text coordinate
$page->setLineColor(new \Zend_Pdf_Color_Rgb(1, 0, 0)); // red lines
$iXCoordinateBorder = $iXCoordinateText - 10; // border is wider than text
// draw top border
$page->drawLine($iXCoordinateBorder, $this->y, $iXCoordinateBorder + $iWidthBorder, $this->y);
// draw text
$this->y -= 15; // further down
$page->drawText($sNotice, $iXCoordinateText, $this->y, $sEncoding);
$this->y -= 10; // further down
// draw bottom border
$page->drawLine($iXCoordinateBorder, $this->y, $iXCoordinateBorder + $iWidthBorder, $this->y);
// draw left border
$page->drawLine($iXCoordinateBorder, $this->y, $iXCoordinateBorder, $this->y + 25 /* back to first line */);
// draw right border
$page->drawLine($iXCoordinateBorder + $iWidthBorder, $this->y, $iXCoordinateBorder + $iWidthBorder, $this->y + 25 /* back to first line */);
$this->y -= 10;
} catch (\Exception $exception) {
// handle
}
}
/**
* Draw header for item table
*
* #param \Zend_Pdf_Page $page
* #return void
*/
protected function _drawHeader(\Zend_Pdf_Page $page)
{
/* Add table head */
$this->_setFontRegular($page, 10);
$page->setFillColor(new \Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
$page->setLineColor(new \Zend_Pdf_Color_GrayScale(0.5));
$page->setLineWidth(0.5);
$page->drawRectangle(25, $this->y, 570, $this->y - 15);
$this->y -= 10;
$page->setFillColor(new \Zend_Pdf_Color_Rgb(0, 0, 0));
//columns headers
$lines[0][] = ['text' => __('Products'), 'feed' => 35];
$lines[0][] = ['text' => __('SKU'), 'feed' => 290, 'align' => 'right'];
// custom column
$lines[0][] = ['text' => __('HSN'), 'feed' => 290, 'align' => 'right'];
$lines[0][] = ['text' => __('Qty'), 'feed' => 435, 'align' => 'right'];
$lines[0][] = ['text' => __('Price'), 'feed' => 360, 'align' => 'right'];
$lines[0][] = ['text' => __('Tax'), 'feed' => 495, 'align' => 'right'];
$lines[0][] = ['text' => __('Subtotal'), 'feed' => 565, 'align' => 'right'];
$lineBlock = ['lines' => $lines, 'height' => 5];
$this->drawLineBlocks($page, [$lineBlock], ['table_header' => true]);
$page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
$this->y -= 20;
}
}
Let me know if you need the content of other files required for a module to work or if anything is not working for you as expected.
I did not try to change the text color yet, so you might need to find a solution for that by yourself.
EDIT: custom header added

Displaying generated PNG in PHP?

So I'm trying to get a generated UPC bar code to display on an index page. but all it does is output the PNG contents instead of displaying the PNG itself.
I'm not quite sure why its doing this. I'm guessing its some silly little thing i need to add but I have no clue what it would be. So any help would be appreciated.
INDEX CODE
<form method="POST">
<head>UPC Barcode and QRcode Generator</head><br>
<label for="">Type 11 Didgits Here => </label>
<input type="text" class="form-control" name="text_code">
<button type="submit" class="btn btn-primary" name="generate">Generate</button>
<hr>
<?php
//QR CODE
if(isset($_POST['generate'])){
$code = $_POST['text_code'];
echo "<img src='https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=$code&choe=UTF-8'>";}
//Barcode
include "generate.php";
$upc = new BC(null,4);
$number = $_POST['text_code'];
$upc->build($number);
echo "*".substr($code, 0,6)."#".substr($code, 6,6)."*";
?>
GENERATE CODE
<?php
class BC{//
private $height;
private $width;
private $barheight;
private $barwidth;
private $lable;
private $border;
private $padding;
private $mapcode;
private $rightmap;
private $code;
function __construct($lable=null,$barwidth=2) {//
$this->set_width($barwidth);
$this->set_lable($lable);
$this->padding = $barwidth*5;
$this->border =2;
$this->mapcode = array
('0' => '0001101', '1' => '0011001', '2' => '0010011', '3' => '0111101', '4' => '0100011',
'5' => '0110001', '6' => '0101111', '7' => '0111011', '8' => '0110111', '9' => '0001011',
'#' => '01010', '*' => '101');
$this->rightmap = array
('0' => '1110010', '1' => '1100110', '2' => '1101100', '3' => '1000010', '4' => '1011100',
'5' => '1001110', '6' => '1010000', '7' => '1000100', '8' => '1001000', '9' => '1110100',
'#' => '01010', '*' => '101');
}
public function set_width($barwidth) {//
if(is_int($barwidth)) {//
$this->barwidth = $barwidth;
}
else{//
$this->barwidth = 2;
}
}
public function set_lable($lable) {//
if(is_null($lable)) {//
$this->lable = "none";
}
else{//
$this->lable = $lable;
}
}
public function build($code = null) {//
if(is_null($code)) {//
$this->code = "00000000000";
}
else{//
$this->code = $code;
}
$this-> code = substr($code, 0, 11);
if(is_numeric($code)){//
$checksum = 0;
for($digit = 0; $digit < strlen($code); $digit++) {
if($digit%2 == 0) {//
$checksum += (int)$code[$digit] * 3;
}
else{//
$checksum += (int) $code[$digit];
}
}
$checkdigit = 10 - $checksum % 10;
$code .= $checkdigit;
$code_disp = $code;
$code = "*".substr($code, 0,6)."#".substr($code, 6,6)."*";
$this->width = $this-> barwidth*95 + $this->padding*2;
$this->barheight = $this->barwidth*95*0.75;
$this->height = $this->barwidth*95*0.75 + $this->padding*2;
$barcode = imagecreatetruecolor($this->width, $this->barheight);
$black = imagecolorallocate($barcode, 0, 0, 0);
$white = imagecolorallocate($barcode, 255, 255, 255);
imagefill($barcode, 0, 0, $black);
imagefilledrectangle($barcode, $this->border, $this->width - $this->border, -1, $this->barheight - $this->border - 1, $white);
$bar_pos = $this->padding;
for($count = 0; $count < 15; $count++) {
$character = $code [$count];
for($subcount = 0; $subcount < strlen($this->mapcode[$character]); $subcount++) {//
if($count < 7) {
$color = ($this->mapcode[$character][$subcount] == 0) ? $white : $black;
}
else{
$color = ($this->rightmap[$character][$subcount] == 0) ? $white : $black;
}
if(strlen($this->mapcode[$character]) == 7) {
$height_offset = $this->height * 0.05;
}
else {
$height_offset = 0;
}
imagefilledrectangle($barcode, $bar_pos, $this->padding, $bar_pos+$this->barwidth - 1, $this->barheight - $height_offset - $this->padding, $color);
$bar_pos += $this->barwidth;
}
imagepng($barcode);
}
}
}
}
?>
So this is the output
after adding the new code
To display an image in an HTML page, you need to use an <img /> tag. To display image contents in an <img /> tag, you need to use a Data URI Scheme.
You'll end up with something like this:
echo '<img src="data:image/png;base64,', base64_encode($the_png_contents), '" />';
I checked out your Q and in the comments you said it still is not working so I decided to have a look with you. I used your code as you posted in and used it on my own little environment to make it work. What I did is the following:
Changed I made in your index.php:
// Check if request method is post
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Check if both Generate and Text_code have been set
if(isset($_POST['generate']) && isset($_POST['text_code'])) {
// Set code used through the if statement
$code = $_POST['text_code'];
echo '<img src="https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl='. $code . '&choe=UTF-8">';
// Include file; generate.php
include "generate.php";
// New instance of class; BC
$upc = new BC(null, 4);
// Set barcode base64 to variable and display
$barcodeBase64 = $upc->build($code);
echo '<img src="data:image/png;base64,' . base64_encode($barcodeBase64) . '" />';
}
}
Furthermore your generate.php needed a little change in the function build:
public function build($code = null) {
$this->code = is_null($code) ? "00000000000" : $code;
$code = substr($code, 0, 11);
$code = str_pad($code, 11, "00000000000");
if(is_numeric($code)){//
$checksum = 0;
for($digit = 0; $digit < strlen($code); $digit++) {
if($digit%2 == 0) {//
$checksum += (int)$code[$digit] * 3;
}
else{//
$checksum += (int) $code[$digit];
}
}
$checkdigit = 10 - $checksum % 10;
$code .= $checkdigit;
$code_disp = $code;
$code = "*".substr($code, 0,6)."#".substr($code, 6,6)."*";
$this->width = $this-> barwidth*95 + $this->padding*2;
$this->barheight = $this->barwidth*95*0.75;
$this->height = $this->barwidth*95*0.75 + $this->padding*2;
$barcode = imagecreatetruecolor($this->width, $this->barheight);
$black = imagecolorallocate($barcode, 0, 0, 0);
$white = imagecolorallocate($barcode, 255, 255, 255);
imagefill($barcode, 0, 0, $black);
imagefilledrectangle($barcode, $this->border, $this->width - $this->border, -1, $this->barheight - $this->border - 1, $white);
$bar_pos = $this->padding;
for($count = 0; $count < 15; $count++) {
$character = $code[$count];
for($subcount = 0; $subcount < strlen($this->mapcode[$character]); $subcount++) {//
if($count < 7) {
$color = ($this->mapcode[$character][$subcount] == 0) ? $white : $black;
}
else{
$color = ($this->rightmap[$character][$subcount] == 0) ? $white : $black;
}
if(strlen($this->mapcode[$character]) == 7) {
$height_offset = $this->height * 0.05;
}
else {
$height_offset = 0;
}
imagefilledrectangle($barcode, $bar_pos, $this->padding, $bar_pos+$this->barwidth - 1, $this->barheight - $height_offset - $this->padding, $color);
$bar_pos += $this->barwidth;
}
}
ob_start();
imagepng($barcode);
$barcodeImage = ob_get_contents();
ob_clean();
return $barcodeImage;
}
}
I also see that you filled the image with black which normally is filled with white as the code is a black on white image. To change this simply replace:
imagefill($barcode, 0, 0, $black); > imagefill($barcode, 0, 0, $white);

How to add watermark on image in CakePHP

I want to add watermark on image when i upload in CakePHP. I found many components on Google but I don't know how to use them like ImageTool, Qimage etc. I don't know what value should pass to component function to add watermark. Could anybody help me.
Here is the ImageToolComponent::watermark() function:-
public static function watermark($options = array()) {
$options = array_merge(array(
'afterCallbacks' => null,
'scale' => false,
'strech' => false,
'repeat' => false,
'watermark' => null,
'output' => null,
'input' => null,
'position' => 'center',
'compression' => 9,
'quality' => 100,
'chmod' => null,
'opacity' => 100
), $options);
// if output path (directories) doesn’t exist, try to make whole path
if (!self::createPath($options['output'])) {
return false;
}
$img = self::openImage($options['input']);
unset($options['input']);
if (empty($img)) {
return false;
}
$src_wm = self::openImage($options['watermark']);
unset($options['watermark']);
if (empty($src_wm)) {
return false;
}
// image size
$img_im_w = imagesx($img);
$img_im_h = imagesy($img);
// watermark size
$img_wm_w = imagesx($src_wm);
$img_wm_h = imagesy($src_wm);
if ($options['scale']) {
if ($options['strech']) {
$r = imagecopyresampled($img, $src_wm, 0, 0, 0, 0, $img_im_w, $img_im_h, $img_wm_w, $img_wm_h);
} else {
$x = 0;
$y = 0;
$w = $img_im_w;
$h = $img_im_h;
if (($img_im_w / $img_im_h) > ($img_wm_w / $img_wm_h)) {
$ratio = $img_im_h / $img_wm_h;
$w = $ratio * $img_wm_w;
$x = round(($img_im_w - $w) / 2);
} else {
$ratio = $img_im_w / $img_wm_w;
$h = $ratio * $img_wm_h;
$y = round(($img_im_h - $h) / 2);
}
$r = imagecopyresampled($img, $src_wm, $x, $y, 0, 0, $w, $h, $img_wm_w, $img_wm_h);
}
} else if ($options['repeat']) {
if (is_array($options['position'])) {
$options['position'] = 5;
}
switch ($options['position']) {
case 'top-left':
for ($y = 0; $y < $img_im_h; $y+=$img_wm_h) {
for ($x = 0; $x < $img_im_w; $x+=$img_wm_w) {
$r = self::imagecopymerge_alpha($img, $src_wm, $x, $y, 0, 0, $img_wm_w, $img_wm_h, $options['opacity']);
}
}
break;
case 'top-right':
for ($y = 0; $y < $img_im_h; $y+=$img_wm_h) {
for ($x = $img_im_w; $x > -$img_wm_w; $x-=$img_wm_w) {
$r = self::imagecopymerge_alpha($img, $src_wm, $x, $y, 0, 0, $img_wm_w, $img_wm_h, $options['opacity']);
}
}
break;
case 'bottom-right':
for ($y = $img_im_h; $y > -$img_wm_h; $y-=$img_wm_h) {
for ($x = $img_im_w; $x > -$img_wm_w; $x-=$img_wm_w) {
$r = self::imagecopymerge_alpha($img, $src_wm, $x, $y, 0, 0, $img_wm_w, $img_wm_h, $options['opacity']);
}
}
break;
case 'bottom-left':
for ($y = $img_im_h; $y > -$img_wm_h; $y-=$img_wm_h) {
for ($x = 0; $x < $img_im_w; $x+=$img_wm_w) {
$r = self::imagecopymerge_alpha($img, $src_wm, $x, $y, 0, 0, $img_wm_w, $img_wm_h, $options['opacity']);
}
}
break;
case 'center':
default:
$pos_x = -(($img_im_w % $img_wm_w) / 2);
$pos_y = -(($img_im_h % $img_wm_h) / 2);
for ($y = $pos_y; $y < $img_im_h; $y+=$img_wm_h) {
for ($x = $pos_x; $x < $img_im_w; $x+=$img_wm_w) {
$r = self::imagecopymerge_alpha($img, $src_wm, $x, $y, 0, 0, $img_wm_w, $img_wm_h, $options['opacity']);
}
}
break;
}
} else {
// custom location
if (is_array($options['position'])) {
list($pos_x, $pos_y) = $options['position'];
} else {
// predefined location
switch ($options['position']) {
case 'top-left':
$pos_x = 0;
$pos_y = 0;
break;
case 'top-right':
$pos_x = $img_im_w - $img_wm_w;
$pos_y = 0;
break;
case 'bottom-right':
$pos_x = $img_im_w - $img_wm_w;
$pos_y = $img_im_h - $img_wm_h;
break;
case 'bottom-left':
$pos_x = 0;
$pos_y = $img_im_h - $img_wm_h;
break;
case 'center':
default:
$pos_x = round(($img_im_w - $img_wm_w) / 2);
$pos_y = round(($img_im_h - $img_wm_h) / 2);
break;
}
}
$r = self::imagecopymerge_alpha($img, $src_wm, $pos_x, $pos_y, 0, 0, $img_wm_w, $img_wm_h, $options['opacity']);
}
if (!$r) {
return false;
}
if (!self::afterCallbacks($img, $options['afterCallbacks'])) {
return false;
}
return self::saveImage($img, $options);
}
I don't know what parameter should i pass to watermark function.`

CF Image IP changing opacity and/or default size

I'm using this image ip generator from codefuture, which is giving me an image with the IP adresse.
I would like to change the Opacity and the default size of it as I'm using it as a watermark over a video. So I can't use css nore html or javascript resize and opacity.
Here is the PHP code:
// Image color setup
$outerBorder = "000000"; // ob=b9b9b9
$innerBorder = "000000"; // ib=ffffff
$leftFill = "ffffff"; // lf=cccccc
$leftTextColor = "000000"; // ltc=555555
$rightFill = "000000"; // rf=dddddd
$rightTextColor = "ffffff"; // rtc=555555
// on-the-fly color settings
// <img src="ip.php?ob=b9b9b9&ib=ffffff&lf=cccccc&ltc=555555&rf=dddddd&rtc=555555" />
// image quality from 0-100
$scaleQuality = 80;
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
// Do not edit beyond this line
// get on-the-fly color settings
if(isset($_GET['ob'])) $outerBorder = $_GET['ob'];
if(isset($_GET['ib'])) $innerBorder = $_GET['ib'];
if(isset($_GET['lf'])) $leftFill = $_GET['lf'];
if(isset($_GET['ltc'])) $leftTextColor = $_GET['lt'];
if(isset($_GET['rf'])) $rightFill = $_GET['rf'];
if(isset($_GET['rtc'])) $rightTextColor = $_GET['rt'];
// draw the image
DrawButton($outerBorder,$innerBorder,$leftFill,$leftTextColor,$rightFill,$rightTextColor,$scaleQuality);
// Functions
function ImageColorAllocateHex($image,$hex) {
for( $i=0; $i<3; $i++ ) {
$temp = substr($hex, 2*$i, 2);
$rgb[$i] = 16 * hexdec( substr($temp, 0, 1) ) + hexdec(substr($temp, 1, 1));
}
return ImageColorAllocate ( $image, $rgb[0], $rgb[1], $rgb[2] );
}
function getRGB($hex) {
for( $i=0; $i<3; $i++ ) {
$temp = substr($hex, 2*$i, 2);
$rgb[$i] = 16 * hexdec( substr($temp, 0, 1) ) + hexdec(substr($temp, 1, 1));
}
return $rgb;
}
function DrawButton($ob,$ib,$lf,$ltc,$rf,$rtc,$sq){
$font['image'] = 'iVBORw0KGgoAAAANSUhEUgAAAEYAAAAFCAMAAADPPGp0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAZQTFRFAAAA////pdmf3QAAAAJ0Uk5T/wDltzBKAAAAUElEQVR42myQgQoAMQhC9f9/+hh2TWUwmjxKIwAk4ZWj9ZWOepo1pSGBwbIx+PN+xsfGMpTt+zF72gaVvf21wVIUv2KzkdmIS5Cv25jfJ8AAoLwA7HynlYYAAAAASUVORK5CYII=';
$font['xy']= array(46 => array("x"=>59, "y"=>0, "w"=>2),48 => array("x"=>53, "y"=>0, "w"=>5),49 => array("x"=>0, "y"=>0, "w"=>5),50 => array("x"=>5, "y"=>0, "w"=>5),51 => array("x"=>11, "y"=>0, "w"=>5),52 => array("x"=>17, "y"=>0, "w"=>5),
53 => array("x"=>23, "y"=>0, "w"=>5),54 => array("x"=>29, "y"=>0, "w"=>5),55 => array("x"=>35, "y"=>0, "w"=>5),56 => array("x"=>41, "y"=>0, "w"=>5),57 => array("x"=>47, "y"=>0, "w"=>5),73 => array("x"=>62, "y"=>0, "w"=>2),80 => array("x"=>65, "y"=>0, "w"=>5));
header ("Content-type: image/png");
$im = #imagecreatetruecolor(80, 15) or die ("Cannot Initialize new GD image stream");
imagerectangle($im, 0, 0, 79, 14, ImageColorAllocateHex($im, $ob));
imagerectangle($im, 1, 1, 78, 13, ImageColorAllocateHex($im, $ib));
imageline ($im, 10, 1, 10, 12, ImageColorAllocateHex($im, $ib));
imagefilledrectangle($im, 2, 2, 9, 12, ImageColorAllocateHex($im, $lf));
imagefilledrectangle($im, 11, 2, 77, 12, ImageColorAllocateHex($im, $rf));
$im = right2img($ltc,strtoupper('IP'),3,$font['image'],$font['xy'],$im);
$im = right2img($rtc,strtoupper(getIpAddress()),(strlen($_SERVER['REMOTE_ADDR'])<15?15:12),$font['image'],$font['xy'],$im);
imagepng($im,NULL,(9 - round(($sq/100) * 9)),NULL);
imagedestroy($im);
}
function right2img($color,$text,$pos,$font,$fontxy,$im){
$letters = imagecreatefromstring(base64_decode($font));
$rgb = getRGB($color);
$index = imagecolorexact($letters, 0, 0, 0);
imagecolorset ($letters, $index, $rgb[0], $rgb[1], $rgb[2]);
for($i=0;$i<strlen($text);$i++){
$c = ord($text[$i]);
imagecopy ($im, $letters, $pos, 5, $fontxy[$c]["x"], $fontxy[$c]["y"], $fontxy[$c]["w"], 5);
$pos+=$fontxy[$c]["w"];
}
return $im;
}
function getIpAddress() {
$check = array('HTTP_CLIENT_IP','HTTP_X_FORWARDED_FOR','HTTP_X_FORWARDED','HTTP_X_CLUSTER_CLIENT_IP','HTTP_FORWARDED_FOR','HTTP_FORWARDED','REMOTE_ADDR');
$ip = '0.0.0.0';
foreach ($check as $key) {
if (isset($_SERVER[$key])) {
list ($ip) = explode(',', $_SERVER[$key]);
break;
}
}
return $ip;
}
Thanks in advance for helping me with this.
Antoine

GET , will not receive my POST ? PHP

I have created a dynamic signature maker for my online game.
You can create the sig manually via
http://pernix-rsps.com/sig/pcard.php?user=usernamehere
I tried to make a userbox and submit , so that people does not have to visit
http://pernix-rsps.com/sig/pcard.php?user=USERNAME
and edit it, i want it to create the link for them upon entering username
my code for the username box
<center>
<form name="sig" id="sig" method="get" action="pcard.php">
<table border="0">
<tr><td colspan="2"><?php echo isset($_GET["user"])?$_GET["user"]:"";?> </td></tr>
<tr><td width="30">Username</td><td width="249"><input name="username" type="text" id="username" width="150px" placeholder="Username" /> </td></tr>
<tr><td></td><td><input name="btnsubmit" type="submit" id="btnsubmit" title="create sig" /></td></tr>
</table>
</form>
</center>
And then pcard.php
<?php
if (isset($_GET['user'])) {
$image_path = "img/saved_cards/".$_GET['user'].".png";
if (file_exists($image_path)) {
if (time() < filemtime($image_path) + 300) { // every 5 minutes ?
pullFromCache($image_path);
exit;
}
}
generate();
}
function pullFromCache($image_path) {
header("Content-type: image/png");
$image = imagecreatefrompng($image_path);
imagepng($image);
}
function generate() {
$DB_HOST = "localhost";
$DB_USER = "";
$DB_PASS = "";
$DB_NAME = "";
$user = clean($_GET['user']);
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME) or die($con->error);
$res = $con->query("SELECT * FROM hs_users WHERE username='$user'");
if($res->num_rows > 0) {
header("Content-type: image/png");
getSig($res->fetch_assoc());
} else {
header("Content-type: image/png");
$image = imagecreatefrompng('./img/sigbg.png');
$color = imagecolorallocate($image, 255, 255, 255);
imagestring($image, 3, 251, 10, 'Invalid User', $color);
imagepng($image);
}
}
function getSig($row) {
$image = imagecreatefrompng('./img/sigbg.png');
$color = imagecolorallocate($image, 255, 255, 255);
$yellow = imagecolorallocate($image, 255, 255, 0);
$total = getTotalLevel($row);
$combat = getCombatLevel($row);
imagestring($image, 5, 250, 10, ''.$row['username'].'', $yellow);
imagestring($image, 2, 250, 26, 'Exp: '.number_format($row['overall_xp']).'', $color);
imagestring($image, 2, 250, 39, 'Total: '.number_format($total).'', $color);
imagestring($image, 2, 250, 51, 'Pernix-Rsps.com ', $color);
$array = array("Attack", "Defence", "Strength", "hitpoints", "Range", "Prayer", "Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", "Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecrafting", "Hunter", "pk", "Summoning", "Dungeoneering");
$baseX = 28;
$baseY = 4;
foreach ($array as $i => $value) {
imagestring($image, 2, $baseX, $baseY, ''.getRealLevel($row[''.strtolower($array[$i]).'_xp'], strtolower($array[$i])).'', $color);
$baseY += 15;
if ($baseY > 64) {
$baseY = 4;
$baseX += 45;
}
}
ImagePNG($image, "img/saved_cards/".$row['username'].".png");
imagepng($image);
}
function getTotalLevel($row) {
$total = 0;
$array = array("Attack", "Defence", "Strength", "Hitpoints", "Range", "Prayer", "Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", "Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecrafting", "Hunter", "pk", "Summoning", "Dungeoneering");
foreach ($array as $i => $value) {
$skillName = strtolower($array[$i]);
$total += getRealLevel($row[$skillName.'_xp'], strtolower($skillName));
}
return $total;
}
function getLevel($exp) {
$points = 0;
$output = 0;
for ($lvl = 1; $lvl <= 99; $lvl++) {
$points += floor($lvl + 300.0 * pow(2.0, $lvl / 7.0));
$output = (int) floor($points / 4);
if (($output - 1) >= $exp) {
return $lvl;
}
}
return 99;
}
function getRealLevel($exp, $skill) {
$points = 0;
$output = 0;
$skillId = $skill == "dungeoneering" ? 1 : 0;
for ($lvl = 1; $lvl <= ($skillId == 1 ? 120 : 99); $lvl++) {
$points += floor($lvl + 300.0 * pow(2.0, $lvl / 7.0));
$output = (int) floor($points / 4);
if (($output - 1) >= $exp) {
return $lvl;
}
}
return ($skillId == 1 ? 120 : 99);
}
function getDungLevel($exp) {
$points = 0;
$output = 0;
for ($lvl = 1; $lvl <= 120; $lvl++) {
$points += floor($lvl + 300.0 * pow(2.0, $lvl / 7.0));
$output = (int) floor($points / 4);
if (($output - 1) >= $exp) {
return $lvl;
}
}
return 120;
}
function clean($string) {
return preg_replace('/[^A-Za-z0-9 \-]/', '', $string);
}
function getCombatLevel($row) {
$attack = getLevel($row['attack_xp']);
$defence = getLevel($row['defence_xp']);
$strength = getLevel($row['strength_xp']);
$hp = getLevel($row['hitpoints_xp']);
$prayer = getLevel($row['prayer_xp']);
$ranged = getLevel($row['range_xp']);
$magic = getLevel($row['magic_xp']);
$combatLevel = (int) (($defence + $hp + floor($prayer / 2)) * 0.25) + 1;
$melee = ($attack + $strength) * 0.325;
$ranger = floor($ranged * 1.5) * 0.325;
$mage = floor($magic * 1.5) * 0.325;
if ($melee >= $ranger && $melee >= $mage) {
$combatLevel += $melee;
} else if ($ranger >= $melee && $ranger >= $mage) {
$combatLevel += $ranger;
} else if ($mage >= $melee && $mage >= $ranger) {
$combatLevel += $mage;
}
return (int)$combatLevel;
}
?>
upon entering and submiting the username in the box, it just takes you to the pcard.php without image being made
any ideas
You are using the wrong fieldname in your PHP. In your form you use the fieldname username:
<input name="username" ... />
And in your PHP you try to get GET['user']. Change that in GET['username'] and everything should work (the getting the value part that is ;)).

Categories