timthumb not working after site migration - migration

I just move my site from xfactorapp.com and any new uploaded picture has no thumbnail. Image is on server but thumbnail is not generated.
How can i change that code to make thumbnail visible from new server?
function href_t`imthumb($file, $set = null, $xf = true) {
if (!$set || !$xf) {
$timthumb = webpath_assets('/timthumb.php');
$href = $timthumb . '?src=' . $file;
if (xcount($set) > 0) {
foreach ($set as $k => $v) {
$href .= '&' . $k . '=' . $v;
}
}
return $href;
} else {
$param['w'] = 150;
$param['h'] = 150;
$param['zc'] = 0;
$param['q'] = 90;
if (DEV) {
$app = DEV_PREFIX . APP_VERSION;
} else {
$app = LIVE_PREFIX . APP_VERSION;
}
if (xcount($set) > 0) {
foreach ($set as $k => $v) {
$param[$k] = $v;
}
$file = '/' . $app . $file;
$protocol = 'http';
if (isSSL()) {
$protocol = 'https';
}
return $protocol . '://thumb.xfactorapp.com/tt/' . implode('/', $param) . $file;
}
}
}
wich give me:
<img class="img-responsive" alt="building" src="http://thumb.xfactorapp.com/tt/263/147/2/90/v3/uploads/_lifttec/cms/58529051881f8f0d87ab1401/5947fffeac28b_200-ATJ-Platforma-autoridicatoare-articulata.jpg">
i wish to change code to take thumbnail with parnam properties but from upload not from thumb.xfactorapp.com
Thanks

Just change $xf from true to false $xf = false.

If you changed server, May be GD Library is missing,So Install and Restart Apache then check your file permission.
// To install GD Library
sudo apt-get install php5.6-gd
// To Restart Apache2
sudo /etc/init.d/apache2 restart

Related

Image upload type for Graphql magento2

Is there any way to upload image using graphql without using base64 format in magento2
public function uploadFile($fileData)
{
// convert base64 string to image and save as file on server.
$uploadedFileName = "";
$fileName = '';
if (isset($fileData['name'])) {
$fileName = $fileData['name'];
} else {
$fileName = rand() . time();
}
if (isset($fileData['filecontent'])) {
$mediaPath = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
$originalPath = 'ModuleName/Attachments/';
$mediaFullPath = $mediaPath . $originalPath;
if (!file_exists($mediaFullPath)) {
mkdir($mediaFullPath, 0775, true);
}
/* Check File is exist or not */
$fullFilepath = $mediaFullPath . $fileName;
if ($this->fileDriver->isExists($fullFilepath)) {
$fileName = rand() . time() . $fileName;
}
$fileContent = base64_decode($fileData['filecontent']);
$savedFile = fopen($mediaFullPath . $fileName, "wb");
fwrite($savedFile, $fileContent);
fclose($savedFile);
$uploadedFileName = "/" . $fileName ;
}
return $uploadedFileName;
}
See more: https://magento.stackexchange.com/a/351629/101754

How to validate files with Yii2 getInstancesByName uploaded from API?

I'm working on a mobile app, the Yii2 is used as backend API, the problem that I can not validate the uploaded files, any idea how I can do it?
public static function uploadPicture ($vid) {
$model = new Pictures ();
$model->load(\Yii::$app->getRequest()->getBodyParams(), '');
$model->vid_image = \yii\web\UploadedFile::getInstancesByName('vid_image');
$imageDir = Yii::$app->params[ 'uploadDir' ];
//if ( $model->validate() AND !empty($model->vid_image) ) { //does not work
if ( !empty($model->vid_image) ) {
foreach ( $model->vid_image as $images => $image) {
$model->name = "t_" . time() . "_i_" . uniqid() . '.' . $image->extension;
$model->vid = $vid;
echo $image->hasError;//return empty
//Yii::$app->end();
//if ( $model->save() and $model->validate() ) { // does not work
if(1==1 and $model->validate()){ // $model->validate() always empty!!!
$image->saveAs($imageDir . '/' . $model->name);
Yii::$app->getResponse()->setStatusCode(201);
$id = implode(',', array_values($model->getPrimaryKey(true)));
Yii::info("[pic.21] image: " . $model->name . " uploaded to: " . $imageDir, __METHOD__);
} elseif ( $model->hasErrors() ) {
$response = \Yii::$app->getResponse();
$response->setStatusCode(500);
throw new ServerErrorHttpException('Failed to create the object for unknown reason. [APIx001]');
}
}
}
return $model;
}
The files are uploaded without validation.
Thanks,

PHP 7 SSH2.SFTP stat() bug work around

I have an app the uses an SFTP connection to download files. It was working correctly in PHP 5.6, not so much in PHP 7. The error I get is as follows:
PHP Warning: filesize(): stat failed for ssh2.sftp ...
My code is as follows:
public function retrieveFiles($downloadTargetFolder,$remoteFolder = '.') {
$fileCount = 0;
echo "\nSftpFetcher retrieveFiles\n";
$con = ssh2_connect($this->host,$this->port) or die("Couldn't connect\n");
if($this->pubKeyFile){
$isAuth = ssh2_auth_pubkey_file($con, $this->user, $this->pubKeyFile, $this->privKeyFile);
} else {
$isAuth = ssh2_auth_password($con, $this->user, $this->pass);
};
if ($isAuth) {
$sftp = ssh2_sftp($con);
$rd = "ssh2.sftp://{$sftp}{$remoteFolder}";
if (!$dir = opendir($rd)) {
echo "\nCould not open the remote directory\n";
} else {
$files = array();
while (false != ($file = readdir($dir))) {
if ($file == "." || $file == "..")
continue;
$files[] = $file;
}
if (is_array($files)) {
foreach ($files as $remoteFile) {
echo "\ncheck file: $remoteFile vs filter: " . $this->filter."\n";
if ($this->filter !== null && strpos($remoteFile,$this->filter) === false) {
continue;
}
echo "file matched\n";
$localFile = $downloadTargetFolder . DIRECTORY_SEPARATOR . basename($remoteFile);
//$result = ftp_get($con,$localFile,$remoteFile,FTP_BINARY);
$result = true;
// Remote stream
if (!$remoteStream = #fopen($rd."/".$remoteFile, 'r')) {
echo "Unable to open the remote file $remoteFolder/$remoteFile\n";
$return = false;
} else {
// Local stream
if (!$localStream = #fopen($localFile, 'w')) {
echo "Unable to open the local file $localFile\n";
$return = false;
} else {
// Write from our remote stream to our local stream
$read = 0;
$fileSize = filesize($rd."/".$remoteFile);
while ($read < $fileSize && ($buffer = fread($remoteStream, $fileSize - $read))) {
$read += strlen($buffer);
if (fwrite($localStream, $buffer) === FALSE) {
echo "Unable to write the local file $localFile\n";
$return = false;
break;
}
}
echo "File retrieved";
// Close
fclose($localStream);
fclose($remoteStream);
}
}
if ($result) {
$fileCount++;
}
}
}
ssh2_exec($con, 'exit');
unset($con);
}
} else {
echo "Error authenticating the user ".$this->user."\n";
}
return $fileCount;
}
}
After some research I found there was an issue with stat():
http://dougal.gunters.org/blog/2016/01/18/wordpress-php7-and-updates-via-php-ssh2/
https://bugs.php.net/bug.php?id=71376
My question
Is there a workaround to allow me to download via SFTP given my current code or is there another library someone can recommend to use instead?
My PHP version:
PHP 7.0.8-0ubuntu0.16.04.3 (cli) ( NTS )
Quoting PHP ssh2.sftp opendir/readdir fix,
Instead of using "ssh2.sftp://$sftp" as a stream path, convert $sftp to an integer like so: "ssh2.sftp://" . intval($sftp) . "/". Then it will work just fine.
The reason for the change is as follows:
PHP 5.6.28 (and apparently 7.0.13) introduced a security fix to URL parsing, that caused the string interpolation of the $sftp resource handle to no-longer be recognized as a valid URL. In turn, that causes opendir(), readdir(), etc. to fail when you use an $sftp resource in the path string, after an upgrade to one of those PHP versions.
As for other libraries... only other library I'm aware of is phpseclib, which has an emulator of sorts for libssh2:
https://github.com/phpseclib/libssh2-compatibility-layer
That "emulator" could certainly be improved upon tho. Like a composer.json file ought to be added, etc.
I had the same issue with php 8.0.
Try putting the filesize command before the fopens.

yii phpexcel file reader no response

I have a piece of code that is
$excelFile = '/tmp/sheet.xls' ;
Yii::import('application.vendors.PHPExcel',true);
$inputFileType = PHPExcel_IOFactory::identify($excelFile);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($excelFile);
$objWorkSheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorkSheet->getHighestRow();
$hightestColumn = $objWorkSheet->getHightestColumn();
$hightestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
echo '<table>'."\n" ;
for($row=2; $row<$highestRow ; ++$row){
echo '<tr>'."\n" ;
for($col=0; $col < $highestColumnIndex ; ++$col){
echo '<td>'.$objWorksheet->getCellByColumnAndRow($col,$row)->getValue().'</td>'."\n";
}
echo '</tr>'."\n" ;
}
echo '</table>'."\n" ;
But when this code execute I do not get any file display. I also tried to put debugs to check where it failed, I could localize the error to getActiveSheet.
Any help would be appreciated
Thanks
Try import PHPExcel like this:
spl_autoload_unregister(array('YiiBase', 'autoload'));
Yii::import('application.vendors.PHPExcel', true);
$this->objPHPExcel = new PHPExcel();
spl_autoload_register(array('YiiBase', 'autoload'));
Here is how i display the imported excel file and works:
spl_autoload_unregister(array('YiiBase','autoload'));
Yii::import("application.vendors.phpexcel.Classes.PHPExcel", true);
$inputFileType = PHPExcel_IOFactory::identify($path);
$objReader = PHPExcel_IOFactory::createReader($inputFileType); //Excel5);
$objPHPExcel = $objReader->load($path);
spl_autoload_register(array('YiiBase','autoload'));
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
foreach ($worksheet->getRowIterator() as $row) {
$rowIndex=$row->getRowIndex();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
foreach ($cellIterator as $cellIndex=>$cell) {
if (!is_null($cell)) {
if($rowIndex >1 && $cellIndex<=55){
$cellVal=$cell->getCalculatedValue();
echo $cellVal;
}
}
}
}
}

How can I set gzip compression in zend framework website

I am new to zend. I have developed a website using zend framework. Now, I want to set gzip compression in my website. Would you please guide me step wise to implement this.
Thanks in advance.
kamal Arora
There are two methods to gzip output in your website.
Using Webserver.If your webserver is apache you can refer here for a good documentation on how to enable mod_deflate on your server.
Using zend framework. Try the following code which is from this website.
Create a gzip compressed string in your bootstrap file.
Code:
try {
$frontController = Zend_Controller_Front::getInstance();
if (#strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
ob_start();
$frontController->dispatch();
$output = gzencode(ob_get_contents(), 9);
ob_end_clean();
header('Content-Encoding: gzip');
echo $output;
} else {
$frontController->dispatch();
}
} catch (Exeption $e) {
if (Zend_Registry::isRegistered('Zend_Log')) {
Zend_Registry::get('Zend_Log')->err($e->getMessage());
}
$message = $e->getMessage() . "\n\n" . $e->getTraceAsString();
/* trigger event */
}
GZIP does not compress images, just the raw HTML/CSS/JS/XML/JSON code from the site being sent to the user.
I made for zend framework 2 (zf2) with your tip
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach("finish", array($this, "compressOutput"), 100);
}
public function compressOutput($e)
{
$response = $e->getResponse();
$content = $response->getBody();
$content = str_replace(" ", " ", str_replace("\n", " ", str_replace("\r", " ", str_replace("\t", " ", $content))));
if(#strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false)
{
header('Content-Encoding: gzip');
$content = gzencode($content, 9);
}
$response->setContent($content);
}
Honoring the answer of Bruno Pitteli, I think you can compress in the following way:
$search = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'#(?://)?<![CDATA[(.*?)(?://)?]]>#s' //leave CDATA alone
);
$replace = array(
'>',
'<',
'\\1',
"//<![CDATA[n".'1'."n//]]>"
);
$content = preg_replace($search, $replace, $content);
So the full code sample now looks like:
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach("finish", array($this, "compressOutput"), 100);
}
public function compressOutput($e)
{
$response = $e->getResponse();
$content = $response->getBody();
$content = preg_replace(array('/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s', '#(?://)?<![CDATA[(.*?)(?://)?]]>#s'), array('>', '<', '\\1', "//<![CDATA[n".'1'."n//]]>"), $content);
if (#strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
header('Content-Encoding: gzip');
$content = gzencode($content, 9);
}
$response->setContent($content);
}