How to resize image by imagine extension in yii2 - yii

I use the bellow function to resize images after upload to show on my post.
but it works just for images larger than 500px 300px. when I upload image smaller than this size, my website images row breaks down.
use yii\imagine\Image;
public function upload() {
$this->pictureFile->saveAs('../files/upload/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension);
Image::thumbnail('../files/upload/' . $this->pictureFile, 500, 300)
->save('../files/upload/thumbnail-500x300/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension,
['quality' => 70]);
unlink('../files/upload/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension);
}

Instead of Image::thumbnail, try the following
$imagine = Image::getImagine();
$image = $imagine->open('../files/upload/' . $this->pictureFile);
$image->resize(new Box(500, 300))->save('../files/upload/thumbnail-500x300/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension, ['quality' => 70]);
Haven't tested it but since yii's Image is just a wrapper over Imagine library, this should work with minor changes (if at all needed).
And yes, you need to use Imagine\Image\Box; in your file before using the code above.

Use resize method as below
use yii\imagine\Image;
use Imagine\Image\Box;
public function upload() {
$this->pictureFile->saveAs('../files/upload/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension);
Image::thumbnail('../files/upload/' . $this->pictureFile, 500, 300)
->resize(new Box(500,300))
->save('../files/upload/thumbnail-500x300/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension,
['quality' => 70]);
unlink('../files/upload/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension);
}

Yii::setAlias('newsfolder', dirname(dirname(__DIR__)) . '/frontend/web/extraimages/');
$model->img = UploadedFile::getInstance($model,'img');
if (!empty($model->img)){
$model->img->saveAs( Yii::getAlias('#newsfolder/').$filename.'.'.$model->img->extension );
$model->img = $filename.'.'.$model->img->extension;
$imagine = Image::getImagine();
$image = $imagine->open(Yii::getAlias('#newsfolder/'.$model->img));
$image->resize(new Box(500, 300))->save(Yii::getAlias('#newsfolder/'.$model->img, ['quality' => 70]));
}

$imagine = Image::getImagine();
$imagine = $imagine->open($openPath);
$sizes = getimagesize ( $openPath );
/*
[0] => 604
[1] => 244
[2] => 3
[3] => width="604" height="244"
[bits] => 8
[mime] => image/png
) */
$width = 200;
$height = round($sizes[1]*$width/$sizes[0]);
$imagine = $imagine->resize(new Box($width, $height))->save($savePath, ['quality' => 60]);

Related

504 Gateway Time-out on updating order status prestashop

I get timeout when i try to change orderstatus in prestashop not sure what is missing.
<?php
$sts_id = $_POST['status_id'];
$order_box = $_POST['orderBox'];
$selected_orders = implode(",", $order_box);
$get_orders = 'SELECT id_order FROM `' . _DB_PREFIX_ . 'orders` WHERE id_order in (' . $selected_orders . ') and current_state !=' . $sts_id;
$get_order_id = Db::getInstance()->ExecuteS($get_orders);
if (count($get_order_id) > 0) {
$order_to_convert = array_column($get_order_id, 'id_order');
foreach ($order_to_convert as $odr_id) {
$objOrder = new Order($odr_id);
$history = new OrderHistory();
$history->id_order = (int) $objOrder->id;
$history->changeIdOrderState($sts_id, (int) ($objOrder->id));
}
}
Any thoughts on this ?

Adding an increment variable along with id name for a textbox not working in yii1 PHP framework

I am creating a table in controller and passing it to view as AJAX response.Inside this table there is dropdown for each rows.When I select 'Other' option value I have to show a textbox near that dropdown in same column itself and save the value in each textbox.
Inorder to make each textbox id unique I am appending an Incrementalvariable $s1 along with 'othermerits-'.e.g. - id="othermerits-2".But when I inspect the element it shows only id="othermerits".I am giving my code sample below written in my controller.Please refer 'else' part.
if (isset($_POST['date'])) {
$date = $_POST['date'];
$academic = Academic::model()>findByAttributes(array('status' => 1));
$students = Student::model()>findAllByAttributes(array('courseid' => $courseid, 'batchid' => $batchid));
$sendtable = "";
$sl = 1;
foreach ($students as $student) {//! for each student studentid,
student admission number and name is send to form
$teacher = Teachercomments::model()>findByAttributes(array('studentid' => $student->studentid, 'courseid' =>
$courseid, 'batchid' => $batchid, 'date' => $date, 'academicid' =>
$academic->academicid, 'userid' => Yii::app()->user->userid, 'usertypeid' =>
Yii::app()->user->usertypeid));
if (isset($teacher)) {
$sendtable = $sendtable . '<tr><td data-id="' .
$student->studentid . '">' . $sl . '</td><td>' . $student->student_firstname
. " " . $student->student_middlename . " " . $student->student_lastname .
'</td><td>' . '<input type="text" name="merits" id="merits" value="' .
$teacher->merit . '" class="merits"></td><td><input type="text" value="' .
$teacher->demerit . '" name="demerits" class="demerits"></td></tr>';
} else {
$sendtable = $sendtable . '<tr><td data-id="' . $students->studentid . '">'
. $sl . '</td><td>' . $students->student_firstname . " " . $students->student_middlename . " " . $students->student_lastname . '</td><td><select
name="merits" id="merits" class="merits"
onchange="GetSelectedTextValue(this,'.$s1.')"><option value="Good
Discipline">Good Discipline</option><option value="Good Listener">Good
Listener</option><option value="Other">Other</option></select><input
type="text" name="othermerits" id="othermerits-'.$s1.'" class="merits"
style=""/></td><td><select name="demerits" class="demerits"><option
value="Careless">Careless</option><option value="Bad Listener">Bad
Listener</option><option value="Other">Other</option></select></td></tr>';
}
$sl = $sl + 1;
}
echo $sendtable;
}
I don't know if it's a typo but on this tow lines you use $s1
<select name="merits" id="merits" class="merits" onchange="GetSelectedTextValue(this,'.$s1.')">
<input type="text" name="othermerits" id="othermerits-'.$s1.'" class="merits" style=""/>
and your imcrement variable is $sl
$sl = $sl + 1;

TYPO3 - Add flexform to my own extension

I am building my own extension.
I have found this page about adding Flexform to the Extension
https://gist.github.com/alrnz/c0f00b196d378f5b9150
And in my ext_tables.php i have this:
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerPlugin(
$_EXTKEY,
'Xlsxtotables',
'XLSX to tables'
);
// Include flex forms
$pluginSignature = str_replace('_', '', $_EXTKEY) . '_' . 'xlsxtotables'; // from registerPlugin(...)
$TCA['tt_content']['types']['list']['subtypes_addlist'] [$pluginSignature] = 'pi_flexform';
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPiFlexFormValue(
$pluginSignature,
'FILE:EXT:' . $_EXTKEY . '/Configuration/FlexForms/flexform_xlsxtotables.xml'
);
I know that the XML-file is in the right place, but I do not get anyting from it in TYPO3 backend.
Any suggestions?
Try replace
$pluginSignature = str_replace('_', '', $_EXTKEY) . '_' . 'xlsxtotables';
by
$extensionName = strtolower(\TYPO3\CMS\Core\Utility\GeneralUtility::underscoredToUpperCamelCase($_EXTKEY));
$pluginSignature = $extensionName.'_'.'xlsxtotables';
And dont forget to empty your general cache before you see a change with your flexform.
You can try below code in ext_tables.php file
$pluginName = 'Pi1'; // Give Your Plugin Nmae
$pluginSignature = preg_replace('/[^a-z0-9]/', '', strtolower($_EXTKEY)) . '_' . strtolower($pluginName);
// FlexForm configuration
$TCA['tt_content']['types']['list']['subtypes_addlist'][$pluginSignature] = 'pi_flexform';
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPiFlexFormValue(
$pluginSignature,
'FILE:EXT:' . $_EXTKEY . '/Configuration/FlexForms/flexformname.xml'
);
For Adding Flexforms in One or More Front-end plugins you can use Below code in ext_tables.php
$extensionName = \TYPO3\CMS\Core\Utility\GeneralUtility::underscoredToUpperCamelCase($_EXTKEY);
$frontendpluginName = 'xxx'; //Your Front-end Plugin Name
$pluginSignature = strtolower($extensionName) . '_'.strtolower($frontendpluginName);
$GLOBALS['TCA']['tt_content']['types']['list']['subtypes_addlist'][$pluginSignature] = 'pi_flexform';
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPiFlexFormValue($pluginSignature, 'FILE:EXT:' . $_EXTKEY . '/Configuration/FlexForms/xyz.xml');

Yii preventing Apple Push Notification script from running

I have a script which does an Apple push notification to an App. The script is:
$payload['aps'] = array('alert' => 'This is the alert text',
'badge' => 1, 'sound' => 'default',
'article_id'=> '110'
);
$payload = json_encode($payload);
$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsPort = 2195;
$apnsCert = '/var/www/schoolspace/apple_server/mountmercy/MountMercy-dev.pem';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$deviceToken = "xxxxxxxxxxxxxxxxxxxxxxxxx";
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
socket_close($apns);
fclose($apns);
I have created the required .pem. When I run this as a standalone script with:
php index.php
everything works and the app receives the notification. There is a warning however:
Warning: socket_close(): supplied resource is not a valid Socket resource
But it still works. However, when I run this in Yii, I get the error:
stream_socket_client() [<a href='function.stream-socket-client'>function.stream-socket-client</a>]: Unable to set private key file `/var/www/schoolspace/apple_server/mountmercy/MountMercy-dev.pem'
I get this error even when setting YII_DEBUG to false. I run this segment of code in the my Yii "Message" model in afterSave(). It's EXACTLY the same as the standalone script. But somehow Yii is preventing it from running. Any ideas?
Since you are receiving the notification that means your pem file might be okay, but
your code doesn't show where you are providing the passphrase. You can try the below code which worked for me.
$badge = 1;
$sound = 'default';
$development = false;//change it to true if in development
$passphrase='passphrase';//pass phrase of the pem file
$payload = array();
$payload['aps'] = array('alert' => $msg_text, 'badge' => intval($badge), 'sound' => $sound);
$payload = json_encode($payload);
$apns_url = NULL;
$apns_cert = NULL;
$apns_port = 2195;
if($development)
{
$apns_url = 'gateway.sandbox.push.apple.com';
$apns_cert = dirname(Yii::app()->request->scriptFile).'/file.pem';
}
else
{
$apns_url = 'gateway.push.apple.com';
$apns_cert = dirname(Yii::app()->request->scriptFile).'/file.pem';
}
$stream_context = stream_context_create();
stream_context_set_option($stream_context, 'ssl', 'local_cert', $apns_cert);
stream_context_set_option($stream_context, 'ssl', 'passphrase', $passphrase);
$apns = stream_socket_client('ssl://' . $apns_url . ':' . $apns_port, $error, $error_string, 2, STREAM_CLIENT_CONNECT, $stream_context);
$device_tokens2= "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$apns_message = chr(0) . chr(0) . chr(32) . pack('H*', $device_tokens2 ) . chr(0) . chr(strlen($payload)) . $payload;
$msg=fwrite($apns, $apns_message);
#socket_close($apns);
#fclose($apns);

Display images from protected folder

I have a protected folder within Yii and I'm looking to display some of those images within the site. I've tried the following code and it works within the site/index controller in that it returns just the image I wanted.
However when I tried to separate the code it didn't work. Any help is appreciated.
Model
public function getImage() // will take file identifier as #param
{
$imageID = '2562584569'; // will eventually be dynamically assigned
$image = Images::model()->find('tmp_name=:id', array('id' => $imageID));
$dest = Yii::getPathOfAlias('application.uploads');
$file = $dest .'/' . $image->tmp_name . '.' . $image->extension;
if(file_exists($file)){
ob_clean();
header('Content-Type:' . $image->logo_type);
readfile($file);
exit;
}
}
And in the view
CHtml::link('<img src="' . Yii::app()->request->baseUrl .'/images/image" />', array('product/index', 'id'=>$data['product_id'], 'slug'=> $data['product_slug']));
Thanks
Jonnny
"protected" folder are not accessible from the client browser. This prevents people to have access to important files, like your source code.
If you want to store images inside "protected" and want them to be accessible, you need to publish them using CAssetManager.
Usage is something like:
$path = Yii::app()->basePath.'/path-inside-protected';
$yourImageUrl = Yii::app()->assetManager->publish($path);
Yii will then use the file as an asset, coping it to the "assets" folder, sibling to "protected". After that, you can just use the url returned on your HTML.
<img src="<?php echo $yourImageUrl ?>">
I went about it like this
CHtml::link('<img src="' . $this->createUrl('/images/image', array('data'=>$data['data'])) . '" />', array('product/index', 'id'=>$data['product_id'], 'slug'=> $data['product_slug']));
Model
public function actionImage($data)
{
$image = Images::model()->find('tmp_name=:data', array('id' => $data));
$dest = Yii::getPathOfAlias('application.uploads');
$file = $dest .'/' . $image->tmp_name . '.' . $image->extension;
if(file_exists($file)){
ob_clean();
header('Content-Type:' . $image->logo_type);
readfile($file);
exit;
}
}
Thanks for all help