PHPExcel export "Unreadable Content" Excel File in yii2 - php

I used PHPExcel extension in Yii2 project and i have created component of PHPExcel object but this component export "Unreadable Content" Excel file.
I have read all possible solution for this issue from these links:
PHPExcel - .xlsx file downloads unreadable content
PHPExcel creates 'unreadable content'
https://stackoverflow.com/questions/32103447/excel-found-unreadable-content-with-phpexcel
PHPExcel unreadable content
I getting following "Unreadable content" Excel file :
And my code is,
component ExcelGrid.php :
<?php
namespace app\components;
use Yii;
use Closure;
use yii\i18n\Formatter;
use yii\base\InvalidConfigException;
use yii\helpers\Url;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;
use yii\widgets\BaseListView;
use yii\base\Model;
use \PHPExcel;
use \PHPExcel_IOFactory;
use \PHPExcel_Settings;
use \PHPExcel_Style_Fill;
use \PHPExcel_Writer_IWriter;
use \PHPExcel_Worksheet;
class ExcelGrid extends \yii\grid\GridView
{
public $columns_array;
public $properties;
public $filename='excel';
public $extension='xlsx';
private $_provider;
private $_visibleColumns;
private $_beginRow = 1;
private $_endRow;
private $_endCol;
private $_objPHPExcel;
private $_objPHPExcelSheet;
private $_objPHPExcelWriter;
public function init(){
parent::init();
}
public function run(){
//$this->test();
if (function_exists('mb_internal_encoding')) {
$oldEncoding=mb_internal_encoding();
mb_internal_encoding('utf8');
}
ob_start();
$this->init_provider();
$this->init_excel_sheet();
$this->initPHPExcelWriter('Excel2007');
$this->generateHeader();
$row = $this->generateBody();
$writer = $this->_objPHPExcelWriter;
$this->setHttpHeaders();
ob_end_clean();
$writer->save('php://output');
if (function_exists('mb_internal_encoding'))
mb_internal_encoding($oldEncoding);
exit;
Yii::$app->end();
//$writer->save('test.xlsx');
parent::run();
}
public function init_provider(){
$this->_provider = clone($this->dataProvider);
}
public function init_excel_sheet(){
$this->_objPHPExcel=new PHPExcel();
$creator = '';
$title = '';
$subject = '';
$description = 'Excel Grid';
$category = '';
$keywords = '';
$manager = '';
$created = date("Y-m-d H:i:s");
$lastModifiedBy = '';
extract($this->properties);
$this->_objPHPExcel->getProperties()
->setCreator($creator)
->setTitle($title)
->setSubject($subject)
->setDescription($description)
->setCategory($category)
->setKeywords($keywords)
->setManager($manager)
//->setCompany($company)
->setCreated($created)
->setLastModifiedBy($lastModifiedBy);
$this->_objPHPExcelSheet = $this->_objPHPExcel->getActiveSheet();
}
public function initPHPExcelWriter($writer)
{
$this->_objPHPExcelWriter = PHPExcel_IOFactory::createWriter(
$this->_objPHPExcel,
$writer
);
}
public function generateHeader(){
$this->setVisibleColumns();
$sheet = $this->_objPHPExcelSheet;
$colFirst = self::columnName(1);
$this->_endCol = 0;
foreach ($this->_visibleColumns as $column) {
$this->_endCol++;
$head = ($column instanceof \yii\grid\DataColumn) ? $this->getColumnHeader($column) : $column->header;
$cell = $sheet->setCellValue(self::columnName($this->_endCol) . $this->_beginRow, $head, true);
}
$sheet->freezePane($colFirst . ($this->_beginRow + 1));
}
public function generateBody()
{
$columns = $this->_visibleColumns;
$models = array_values($this->_provider->getModels());
if (count($columns) == 0) {
$cell = $this->_objPHPExcelSheet->setCellValue('A1', $this->emptyText, true);
$model = reset($models);
return 0;
}
$keys = $this->_provider->getKeys();
$this->_endRow = 0;
foreach ($models as $index => $model) {
$key = $keys[$index];
$this->generateRow($model, $key, $index);
$this->_endRow++;
}
// Set autofilter on
$this->_objPHPExcelSheet->setAutoFilter(
self::columnName(1) .
$this->_beginRow .
":" .
self::columnName($this->_endCol) .
$this->_endRow
);
return ($this->_endRow > 0) ? count($models) : 0;
}
public function generateRow($model, $key, $index)
{
$cells = [];
/* #var $column Column */
$this->_endCol = 0;
foreach ($this->_visibleColumns as $column) {
if ($column instanceof \yii\grid\SerialColumn || $column instanceof \yii\grid\ActionColumn) {
continue;
} else {
$format = $column->format;
$value = ($column->content === null) ?
$this->formatter->format($column->getDataCellValue($model, $key, $index), $format) :
call_user_func($column->content, $model, $key, $index, $column);
}
if (empty($value) && !empty($column->attribute) && $column->attribute !== null) {
$value =ArrayHelper::getValue($model, $column->attribute, '');
}
$this->_endCol++;
$cell = $this->_objPHPExcelSheet->setCellValue(self::columnName($this->_endCol) . ($index + $this->_beginRow + 1),
strip_tags($value), true);
}
}
protected function setVisibleColumns()
{
$cols = [];
foreach ($this->columns as $key => $column) {
if ($column instanceof \yii\grid\SerialColumn || $column instanceof \yii\grid\ActionColumn) {
continue;
}
$cols[] = $column;
}
$this->_visibleColumns = $cols;
}
public function getColumnHeader($col)
{
if(isset($this->columns_array[$col->attribute]))
return $this->columns_array[$col->attribute];
/* #var $model yii\base\Model */
if ($col->header !== null || ($col->label === null && $col->attribute === null)) {
return trim($col->header) !== '' ? $col->header : $col->grid->emptyCell;
}
$provider = $this->dataProvider;
if ($col->label === null) {
if ($provider instanceof ActiveDataProvider && $provider->query instanceof ActiveQueryInterface) {
$model = new $provider->query->modelClass;
$label = $model->getAttributeLabel($col->attribute);
} else {
$models = $provider->getModels();
if (($model = reset($models)) instanceof Model) {
$label = $model->getAttributeLabel($col->attribute);
} else {
$label =$col->attribute;
}
}
} else {
$label = $col->label;
}
return $label;
}
public static function columnName($index)
{
$i = $index - 1;
if ($i >= 0 && $i < 26) {
return chr(ord('A') + $i);
}
if ($i > 25) {
return (self::columnName($i / 26)) . (self::columnName($i % 26 + 1));
}
return 'A';
}
protected function setHttpHeaders()
{
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Type: application/{$this->extension}; charset=utf-8");
header("Content-Disposition: attachment; filename={$this->filename}.{$this->extension}");
header("Expires: 0");
}
}
View file countryExcel.php :
<?php
\app\components\ExcelGrid::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'extension'=>'xlsx',
'filename'=>'country-list'.date('Y-m-dH:i:s'),
'properties' =>[
//'creator' =>'',
//'title' => '',
//'subject' => '',
//'category' => '',
//'keywords' => '',
//'manager' => '',
],
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'country_name',
[
'attribute' => 'created_at',
'value' => function ($data) {
return Yii::$app->formatter->asDateTime($data->created_at);
},
],
[
'attribute' => 'created_by',
'value' => 'createdBy.user_login_id',
],
[
'attribute' => 'updated_at',
'value' => function ($data) {
return (!empty($data->updated_at) ? Yii::$app->formatter->asDateTime($data->updated_at) : Yii::t('stu', ' (not set) '));
},
],
[
'attribute' => 'updated_by',
'value' => 'updatedBy.user_login_id',
],
],
]);
?>
Controller File CountryController.php :
<?php
class CountryController extends Controller
{
.....
.......
public function actionExcel()
{
$searchModel = new CountrySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->renderPartial('CountryExportExcel', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
........
.....
}
?>
Thanks in Advance.

Its not a valid solution but it works for me..
header("Content-Disposition: attachment; filename=\"$filename\"");
$export =\moonland\phpexcel\Excel::export([
'models' => $exportData,
'columns' => $exportColumns,
'headers' => [
'created_at' => dtTZ()
],
]);

Your file seems a correct xlsx file opened with an editor like notepad++
could be a charcter encoding problem
Try change the encode
if (function_exists('mb_internal_encoding')) {
$oldEncoding=mb_internal_encoding();
mb_internal_encoding('utf8');
}
using a value for cp1250 -- to cp1258
encoding for microsoft in US-EN
(I hope your excel country installation config )

Related

Auto Merge Row Data in Maatwebsite Export Excel

I have dynamic data that will be exported into excel using maatwebsite. I have a case where I need to merge the same data. How can I do it from a collection?
From This:
To This:
class PerencanaanExport implements
FromCollection,
WithCustomStartCell,
WithEvents,
ShouldAutoSize,
WithStyles
{
/**
* #return \Illuminate\Support\Collection
*/
public function __construct(string $tahun)
{
$this->tahun = $tahun;
}
public function startCell(): string
{
return "A3";
}
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
/** #var Sheet $sheet */
$tahun =
$this->tahun == "null"
? ""
: ($this->tahun == "all"
? ""
: $this->tahun);
$sheet = $event->sheet;
$sheet->mergeCells("A1:E1");
$sheet->setCellValue("A1", "Kode");
$sheet->setCellValue("A2", "Urusan");
$sheet->setCellValue("B2", "Bidang Urusan");
$sheet->setCellValue("C2", "Program");
$sheet->setCellValue("D2", "Kegiatan");
$sheet->setCellValue("E2", "Sub Kegiatan");
$sheet->mergeCells("F1:F2");
$sheet->setCellValue(
"F1",
"Urusan/ Bidang Urusan Pemerintahan Daerah dan Program Kegiatan"
);
$sheet->mergeCells("G1:G2");
$sheet->setCellValue(
"G1",
"Indikator Kinerja Program/ Kegiatan"
);
$sheet->mergeCells("H1:K1");
$sheet->setCellValue("H1", "Rencana Tahun " . $tahun);
$sheet->setCellValue("H2", "LOKASI");
$sheet->setCellValue("I2", "TARGET KINERJA");
$sheet->setCellValue("J2", "ANGGARAN");
$sheet->setCellValue("K2", "SUMBER DANA");
$styleArray = [
"borders" => [
"allBorders" => [
"borderStyle" =>
\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
"color" => ["argb" => "000000"],
],
],
];
$cellRange = "A1:K" . $sheet->getHighestRow(); // All headers
$event->sheet
->getDelegate()
->getStyle($cellRange)
->applyFromArray($styleArray);
$event->sheet
->getStyle("A1:K2")
->getAlignment()
->setVertical(StyleAlignment::VERTICAL_TOP)
->setHorizontal(StyleAlignment::VERTICAL_CENTER)
->setWrapText(true);
},
];
}
public function collection()
{
$arr = [];
$tahun = $this->tahun;
$jointahun = "";
if ($tahun) {
$jointahun = " AND d.tahun =" . $tahun;
}
$query = "XXXXX";
$query .= "XXXXX";
$data = DB::select($query);
$oldProgram = "";
$oldKegiatan = "";
foreach ($data as $key => $value) {
if ($key != 0) {
$oldProgram = $data[$key - 1]->program;
$oldKegiatan = $data[$key - 1]->kegiatan;
}
if ($oldProgram != $value->program) {
array_push($arr, [
$value->kode_urusan,
$value->kode_bidang_urusan,
$value->kode_program,
"",
"",
$value->program,
]);
}
if ($oldKegiatan != $value->kegiatan) {
array_push($arr, [
$value->kode_urusan,
$value->kode_bidang_urusan,
$value->kode_program,
$value->kode_kegiatan,
"",
$value->kegiatan,
$value->indikator_kegiatan,
]);
}
array_push($arr, [
$value->kode_urusan,
$value->kode_bidang_urusan,
$value->kode_program,
$value->kode_kegiatan,
$value->kode_sub_kegiatan,
$value->sub_kegiatan,
$value->indikator_perencanaan,
$value->lokasi,
$value->target_kinerja,
$value->anggaran,
$value->sumber_dana,
]);
}
return collect($arr);
}
public function styles(Worksheet $sheet)
{
$sheet
->getStyle("1:2")
->getFont()
->setBold(true);
}

Laravel Model Removing html attribute

Created a simple miniCMS in a portal for content creation. The issue at first was in TinyMCE stripping of id attribute from html tag I've resolved that using valid_elements now the request is being sent to Model as is with no issues however in the Model level it's stripping the id again
Example
<div id="agreement">text ......... </div>
Being Saved in model as
<div>text ......... </div>
The controller code:
public function frontendContent(Request $request, $key)
{
$purifier = new \HTMLPurifier();
$valInputs = $request->except('_token', 'image_input', 'key', 'status', 'type');
foreach ($valInputs as $keyName => $input) {
if (gettype($input) == 'array') {
$inputContentValue[$keyName] = $input;
continue;
}
$inputContentValue[$keyName] = $purifier->purify($input);
}
$type = $request->type;
if (!$type) {
abort(404);
}
$imgJson = #getPageSections()->$key->$type->images;
$validation_rule = [];
$validation_message = [];
foreach ($request->except('_token', 'video') as $input_field => $val) {
if ($input_field == 'has_image' && $imgJson) {
foreach ($imgJson as $imgValKey => $imgJsonVal) {
$validation_rule['image_input.'.$imgValKey] = ['nullable','image','mimes:jpeg,jpg,png,svg'];
$validation_message['image_input.'.$imgValKey.'.image'] = inputTitle($imgValKey).' must be an image';
$validation_message['image_input.'.$imgValKey.'.mimes'] = inputTitle($imgValKey).' file type not supported';
}
continue;
}elseif($input_field == 'seo_image'){
$validation_rule['image_input'] = ['nullable', 'image', new FileTypeValidate(['jpeg', 'jpg', 'png'])];
continue;
}
$validation_rule[$input_field] = 'required';
}
$request->validate($validation_rule, $validation_message, ['image_input' => 'image']);
if ($request->id) {
$content = Frontend::findOrFail($request->id);
} else {
$content = Frontend::where('data_keys', $key . '.' . $request->type)->first();
if (!$content || $request->type == 'element') {
$content = Frontend::create(['data_keys' => $key . '.' . $request->type]);
}
}
if ($type == 'data') {
$inputContentValue['image'] = #$content->data_values->image;
if ($request->hasFile('image_input')) {
try {
$inputContentValue['image'] = uploadImage($request->image_input,imagePath()['seo']['path'], imagePath()['seo']['size'], #$content->data_values->image);
} catch (\Exception $exp) {
$notify[] = ['error', 'Could not upload the Image.'];
return back()->withNotify($notify);
}
}
}else{
if ($imgJson) {
foreach ($imgJson as $imgKey => $imgValue) {
$imgData = #$request->image_input[$imgKey];
if (is_file($imgData)) {
try {
$inputContentValue[$imgKey] = $this->storeImage($imgJson,$type,$key,$imgData,$imgKey,#$content->data_values->$imgKey);
} catch (\Exception $exp) {
$notify[] = ['error', 'Could not upload the Image.'];
return back()->withNotify($notify);
}
} else if (isset($content->data_values->$imgKey)) {
$inputContentValue[$imgKey] = $content->data_values->$imgKey;
}
}
}
}
$content->update(['data_values' => $inputContentValue]);
$notify[] = ['success', 'Content has been updated.'];
return back()->withNotify($notify);
}
When I dd the request
as dd($request) I can see the html tag in full
<div id="agreement">text ......... </div>
But when I dd the content
as dd($content) I can see that the id attribute is stripped
<div>text ......... </div>
The model part
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Frontend extends Model
{
protected $guarded = ['id'];
protected $table = "frontends";
protected $casts = [
'data_values' => 'object'
];
public static function scopeGetContent($data_keys)
{
return Frontend::where('data_keys', $data_keys);
}
}
Kindly asking for help, thank you!
While checking the forum here at SOF I found a solution with a remark from #FarhanIbnWahid thanks to him.
$config = HTMLPurifier_Config::createDefault();
$config->set('Attr.EnableID', true);
$purifier = new \HTMLPurifier($config);
This will resolve the issue.

How to make hyperlink from author name in Wordpress?

I'm a total newbie to Wordpress and having a hard time figuring things out.
I'm using plugin called "WP-Pro-Quiz", a quiz plugin, and within the plugin there's an option to show "Leaderboard" of all users who completed the quiz. In the leaderboard on the frontend, there's user id, time, points and user's Display Name, etc for each user..
What I want to achieve is to make Display name clickable (and then to go to author's profile once clicked). That is, to connect Display Name with author profile who took the quiz, to create hyperlink from Display Name.
This is from controller WpProQuiz_Controller_Toplist.php :
<?php
class WpProQuiz_Controller_Toplist extends WpProQuiz_Controller_Controller
{
public function route()
{
$quizId = $_GET['id'];
$action = isset($_GET['action']) ? $_GET['action'] : 'show';
switch ($action) {
default:
$this->showAdminToplist($quizId);
break;
}
}
private function showAdminToplist($quizId)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
wp_die(__('You do not have sufficient permissions to access this page.'));
}
$view = new WpProQuiz_View_AdminToplist();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$view->quiz = $quiz;
$view->show();
}
public function getAddToplist(WpProQuiz_Model_Quiz $quiz)
{
$userId = get_current_user_id();
if (!$quiz->isToplistActivated()) {
return null;
}
$data = array(
'userId' => $userId,
'token' => wp_create_nonce('wpProQuiz_toplist'),
'canAdd' => $this->preCheck($quiz->getToplistDataAddPermissions(), $userId),
);
if ($quiz->isToplistDataCaptcha() && $userId == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$data['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$data['captcha']['code'] = $captcha->getPrefix();
}
}
return $data;
}
private function handleAddInToplist(WpProQuiz_Model_Quiz $quiz)
{
if (!wp_verify_nonce($this->_post['token'], 'wpProQuiz_toplist')) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!isset($this->_post['points']) || !isset($this->_post['totalPoints'])) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$quizId = $quiz->getId();
$userId = get_current_user_id();
$points = (int)$this->_post['points'];
$totalPoints = (int)$this->_post['totalPoints'];
$name = !empty($this->_post['name']) ? trim($this->_post['name']) : '';
$email = !empty($this->_post['email']) ? trim($this->_post['email']) : '';
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
$captchaAnswer = !empty($this->_post['captcha']) ? trim($this->_post['captcha']) : '';
$prefix = !empty($this->_post['prefix']) ? trim($this->_post['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
if ($quiz == null || $quiz->getId() == 0 || !$quiz->isToplistActivated()) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!$this->preCheck($quiz->getToplistDataAddPermissions(), $userId)) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$numPoints = $quizMapper->sumQuestionPoints($quizId);
if ($totalPoints > $numPoints || $points > $numPoints) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$clearTime = null;
if ($quiz->isToplistDataAddMultiple()) {
$clearTime = $quiz->getToplistDataAddBlock() * 60;
}
if ($userId > 0) {
if ($toplistMapper->countUser($quizId, $userId, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
$user = wp_get_current_user();
$email = $user->user_email;
$name = $user->display_name;
} else {
if ($toplistMapper->countFree($quizId, $name, $email, $ip, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
if (empty($name) || empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return array('text' => __('No name or e-mail entered.', 'wp-pro-quiz'), 'clear' => false);
}
if (strlen($name) > 15) {
return array('text' => __('Your name can not exceed 15 characters.', 'wp-pro-quiz'), 'clear' => false);
}
if ($quiz->isToplistDataCaptcha()) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
if (!$captcha->check($prefix, $captchaAnswer)) {
return array('text' => __('You entered wrong captcha code.', 'wp-pro-quiz'), 'clear' => false);
}
}
}
}
$toplist = new WpProQuiz_Model_Toplist();
$toplist->setQuizId($quizId)
->setUserId($userId)
->setDate(time())
->setName($name)
->setEmail($email)
->setPoints($points)
->setResult(round($points / $totalPoints * 100, 2))
->setIp($ip);
$toplistMapper->save($toplist);
return true;
}
private function preCheck($type, $userId)
{
switch ($type) {
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ALL:
return true;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_ANONYM:
return $userId == 0;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_USER:
return $userId > 0;
}
return false;
}
public static function ajaxAdminToplist($data)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
return json_encode(array());
}
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$j = array('data' => array());
$limit = (int)$data['limit'];
$start = $limit * ($data['page'] - 1);
$isNav = isset($data['nav']);
$quizId = $data['quizId'];
if (isset($data['a'])) {
switch ($data['a']) {
case 'deleteAll':
$toplistMapper->delete($quizId);
break;
case 'delete':
if (!empty($data['toplistIds'])) {
$toplistMapper->delete($quizId, $data['toplistIds']);
}
break;
}
$start = 0;
$isNav = true;
}
$toplist = $toplistMapper->fetch($quizId, $limit, $data['sort'], $start);
foreach ($toplist as $tp) {
$j['data'][] = array(
'id' => $tp->getToplistId(),
'name' => $tp->getName(),
'email' => $tp->getEmail(),
'type' => $tp->getUserId() ? 'R' : 'UR',
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
if ($isNav) {
$count = $toplistMapper->count($quizId);
$pages = ceil($count / $limit);
$j['nav'] = array(
'count' => $count,
'pages' => $pages ? $pages : 1
);
}
return json_encode($j);
}
public static function ajaxAddInToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$ctn = new WpProQuiz_Controller_Toplist();
$quizId = isset($data['quizId']) ? $data['quizId'] : 0;
$prefix = !empty($data['prefix']) ? trim($data['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$r = $ctn->handleAddInToplist($quiz);
if ($quiz->isToplistActivated() && $quiz->isToplistDataCaptcha() && get_current_user_id() == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$captcha->remove($prefix);
$captcha->cleanup();
if ($r !== true) {
$r['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$r['captcha']['code'] = $captcha->getPrefix();
}
}
}
if ($r === true) {
$r = array('text' => __('You signed up successfully.', 'wp-pro-quiz'), 'clear' => true);
}
return json_encode($r);
}
public static function ajaxShowFrontToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$quizIds = empty($data['quizIds']) ? array() : array_unique((array)$data['quizIds']);
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$j = array();
foreach ($quizIds as $quizId) {
$quiz = $quizMapper->fetch($quizId);
if ($quiz == null || $quiz->getId() == 0) {
continue;
}
$toplist = $toplistMapper->fetch($quizId, $quiz->getToplistDataShowLimit(), $quiz->getToplistDataSort());
foreach ($toplist as $tp) {
$j[$quizId][] = array(
'name' => $tp->getName(),
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
}
return json_encode($j);
}
}
and from model WpProQuiz_Model_Toplist.php:
<?php
class WpProQuiz_Model_Toplist extends WpProQuiz_Model_Model
{
protected $_toplistId;
protected $_quizId;
protected $_userId;
protected $_date;
protected $_name;
protected $_email;
protected $_points;
protected $_result;
protected $_ip;
public function setToplistId($_toplistId)
{
$this->_toplistId = (int)$_toplistId;
return $this;
}
public function getToplistId()
{
return $this->_toplistId;
}
public function setQuizId($_quizId)
{
$this->_quizId = (int)$_quizId;
return $this;
}
public function getQuizId()
{
return $this->_quizId;
}
public function setUserId($_userId)
{
$this->_userId = (int)$_userId;
return $this;
}
public function getUserId()
{
return $this->_userId;
}
public function setDate($_date)
{
$this->_date = (int)$_date;
return $this;
}
public function getDate()
{
return $this->_date;
}
public function setName($_name)
{
$this->_name = (string)$_name;
return $this;
}
public function getName()
{
return $this->_name;
}
public function setEmail($_email)
{
$this->_email = (string)$_email;
return $this;
}
public function getEmail()
{
return $this->_email;
}
public function setPoints($_points)
{
$this->_points = (int)$_points;
return $this;
}
public function getPoints()
{
return $this->_points;
}
public function setResult($_result)
{
$this->_result = (float)$_result;
return $this;
}
public function getResult()
{
return $this->_result;
}
public function setIp($_ip)
{
$this->_ip = (string)$_ip;
return $this;
}
public function getIp()
{
return $this->_ip;
}
}

Inserting data from session using codeigniter

I'm just practicing using session in Codeigniter and i've got a Problem here's my controller
public function ajax_Addfees()
{
if($this->input->is_ajax_request())
{
$input = $this->input->post();
if($this->session->userdata('html')){
$html = $this->session->userdata('html');
}
$id = explode($input['fno']);
$html[$id] = ['amount' => $input['amount'], 'oldamount' => $input['deduction']];
$this->session->set_userdata('html', $html);
}
}
public function savetuition()
{
$this->Tuition_model->savefees();
redirect('tuitionsetup_con');
}
This is my model
public function savefees()
{
$fees = $this->session->userdata('html');
$feeslist = [];
if( !empty($fees) ) {
foreach ($fees as $key =>$value) {
array_push($feeslist, [
'amount' => $value['amount'],
'oldamount' => $value['oldamount'],
'f_no' => $key,
'sy_no' => $this->session->userdata('sy'),
'level_no' => $this->session->userdata('lvl'),
'id' => $this->session->userdata('id')
]);
$this->db->insert_batch('tuition', $feeslist);
} }
}
Well what I'm trying to do is to save data from session->set_userdata('html') to my database using codeigniter.
There's no error but it doesn't save data to database
You need to modify your model as:
public function savefees() {
$fees = $this->session->userdata('html');
$feeslist = array();
if( !empty($fees) ) {
foreach ($fees as $key =>$value) {
$feeslist[$key]["amount"] = $value['amount'];
$feeslist[$key]["oldamount"] = $value['oldamount'];
$feeslist[$key]["f_no"] = $key;
$feeslist[$key]["sy_no"] = $this->session->userdata('sy');
$feeslist[$key]["level_no"] = $this->session->userdata('lvl') ;
$feeslist[$key]["id"] = $this->session->userdata('id') ;
}
}
$this->db->insert_batch('tuition', $feeslist);
}

How can I trim white space off image with Intervention?

I have a class that takes photos I download before reuploading to S3 for long-term storage and I want to trim the white space. When I store the temporary image (which works fine), I then try to call the Intervention trim() on it in my storeTempFile() method but that doesn't trim the white space. I'm thinking it could be the placement in my code?
class PhotoProcessor
{
public function __construct(Listing $listing, $photoData)
{
$this->bucket = 'real-estate-listings';
$this->s3 = App::make('aws')->get('s3');
$this->tempFileName = 'app/storage/processing/images/retsphotoupload';
$this->photoData = $photoData;
$this->listing = $listing;
$this->photo = new RetsPhoto;
}
public function process()
{
$this->storeTempFile();
$this->storeFileInfo();
$this->buildPhoto();
$success = $this->pushToS3();
// if Result has the full URL or you want to build it, add it to $this->photo
DB::connection()->disableQueryLog();
$this->listing->photos()->save($this->photo);
$this->removeTempFile();
unset ($this->photoData);
return $success;
}
private function storeTempFile()
{
// return File::put($this->tempFileName, $this->photoData['Data']) > 0;
File::put($this->tempFileName, $this->photoData['Data']);
Image::make($this->tempFileName)->trim('top-left', null, 60);
return($this->tempFileName) > 0;
}
private function storeFileInfo()
{
$fileInfo = getimagesize($this->tempFileName);
// Could even be its own object
$this->fileInfo = [
'width' => $fileInfo[0],
'height' => $fileInfo[1],
'mimetype' => $fileInfo['mime'],
'extension' => $this->getFileExtension($fileInfo['mime'])
];
}
private function buildPhoto()
{
$this->photo->number = $this->photoData['Object-ID']; // Storing this because it is relevant order wise
$this->photo->width = $this->fileInfo['width'];
$this->photo->height = $this->fileInfo['height'];
$this->photo->path = $this->getFilePath();
}
private function getFilePath()
{
$path = [];
if ($this->listing->City == NULL)
{
$path[] = Str::slug('No City');
}
else
{
$path[] = Str::slug($this->listing->City, $separator = '-');
}
if ($this->listing->Subdivision->subdivision_display_name == NULL)
{
$path[] = Str::slug('No Subdivision');
}
else
{
$path[] = Str::slug($this->listing->Subdivision->subdivision_display_name, $separator = '-');
}
if ($this->listing->MLSNumber == NULL)
{
$path[] = Str::slug('No MLSNumber');
}
else
{
$path[] = Str::slug($this->listing->MLSNumber, $separator = '-');
}
$path[] = $this->photoData['Object-ID'].'.'.$this->fileInfo['extension'];
return strtolower(join('/', $path));
}
private function pushToS3()
{
return $this->s3->putObject([
'Bucket' => $this->bucket,
'Key' => $this->photo->path,
'ContentType'=> $this->fileInfo['mimetype'],
'SourceFile' => $this->tempFileName
]);
}
private function getFileExtension($mime)
{
// Use better algorithm than this
$ext = str_replace('image/', '', $mime);
return $ext == 'jpeg' ? 'jpg' : $ext;
}
private function removeTempFile()
{
return File::delete($this->tempFileName);
}
}
trim() returns the trimmed image, but you are doing nothing with the return value. Try calling save() to persist the image to the filesystem:
Image::make($this->tempFileName)->trim('top-left', null, 60)->save();
// ^^^^^^

Categories