Add Pre default text in phalcon flash messages - phalcon

In phalcon default flash messaging service only provide with default error div.
<div class="alert alert-warning">Our message</div>
But i want to add something inside div box like this.
<div class="alert alert-warning"> <button class="close">x</button> Our Message </div>
However, phalcon we are only allow to set only class of each message as per my knowledge.
$di->set('flash', function () {
return new FlashSession([
'error' => 'alert alert-danger alert-dismissible',
'success' => 'alert alert-success alert-dismissible',
'notice' => 'alert alert-info alert-dismissible',
'warning' => 'alert alert-warning alert-dismissible'
]);
});
Is there any configuration or any other way to add that close button on every message. I want something like
message = '<button class="close-btn">x</button>'+message
However i don't want to add this close button on every flash message because in future may be i need to change the class of close button so that in that case i need to change in all from the project.

You can do this by extending the Phalcon\FlashSession class and overriding the outputMessage() method, or by creating your own flash component to output the HTML you desire. Example of a custom flash component is below, we use a similar class when we develop with Falcon, this component assumes the existence of a session component in the DI.
This is untested but the code in principle would give you the ability to add a close button to the output HTML, or you can set specific HTML content for each message type in the relevant methods (error, success, warning, info).
Example usage:
// settings messages in your controllers / components
// 2nd param defines a position
$this->flashMessage->error('Something is bad!', 'form_top');
$this->flashMessage->success('Something is right!');
$this->flashMessage->info('Something is interesting!');
$this->flashMessage->warning('Something is worrying!');
// rendering messages in your views
// 1st param will render messages for a specific position if a position was set
$this->flashMessage->render();
$this->flashMessage->render('form_top');
Example class:
class FlashMessage extends Phalcon\Mvc\User\Component
{
/**
* #var array
**/
public $classmap = array();
/**
* Sets defaults for the class map (optional)
*
* #param array $classmap
**/
public function __construct($classmap = array()) {
// -- set the defaults
$this->classmap = array(
'error' => 'flash_message-error',
'success' => 'flash_message-success',
'info' => 'flash_message-info',
'warning' => 'flash_message-warning'
);
// -- set new class map options (also optional)
if (!empty($classmap)) {
foreach ($classmap as $key => $value) {
$this->classmap[$key] = $value;
}
}
}
/**
* error(), success(), info(), warning()
* Sets the flash messages
*
* #param string message
* #param string position
* #return string
**/
public function error($message, $position = '')
{
$this->session->flashMessage = array(
'position' => $position,
'message' => '<div class="' . $this->classmap['error'] . '">
' . $message . '
</div>
');
}
public function success($message, $position = '')
{
$this->session->flashMessage = array(
'position' => $position,
'message' => '<div class="' . $this->classmap['success'] . '">
' . $message . '
</div>
');
}
public function info($message, $position = '')
{
$this->session->flashMessage = array(
'position' => $position,
'message' => '<div class="' . $this->classmap['info'] . '">
' . $message . '
</div>
');
}
public function warning($message, $position = '')
{
$this->session->flashMessage = array(
'position' => $position,
'message' => '<div class="' . $this->classmap['warning'] . '">
' . $message . '
</div>
');
}
/**
* Check if theres messages in the session to render
*
* #param string $position
* #return bool
**/
public function hasMessage($position = null)
{
if (isset($this->session->flashMessage) && !empty($position)) {
return $this->session->flashMessage['position'] == $position ? true : false ;
} else {
return $this->session->flashMessage ? true : false ;
}
}
/**
* Renders the flash message
*
* #param string $position
* #return string
**/
public function render($position = null)
{
// -- store the message locally
$message = $this->session->flashMessage;
// -- check if there is in fact a flashed message
if (empty($message))
return;
// -- then remove from the session
$this->session->remove('FlashMessage');
// -- if no position the just return the message
if (is_null($position)) {
return $message['message'];
// -- else return the requested position
} elseif ($position == $message['position']) {
return $message['message'];
}
}
}

I am using something like this, you can extend it like you want. But this is just the gist of how it works:
class Messenger extends Component
{
protected static $_messageCloseHtml = '×';
/**
* #param array|string $messages
*/
public static function flashError($messages)
{
$messages = !is_array($messages) ? [$messages] : $messages;
foreach ($messages as $message) {
\Phalcon\Di::getDefault()->get('flashSession')->error(self::_getBody($message));
}
}
/**
* #param string $message
* #return string
*/
protected static function _getBody($message)
{
return self::$_messageCloseHtml . $message;
}
}
For every message, you can add some HTML code to the message.
My flashError is for the error messages. You can add the same method code for the warning, info and success.
So basically you extend the (existing) FlashSession and when assigning the messages you call a global method which adds additional text or html to your message.

Related

Symfony 4 - Problem sending email after change my DNS

Click here
to see my diagram app.
Hey, my client change her DNS (like that : xxx-dns.com to dns.com) and this is ok, except one problem.. In react native app, I have contact form for send message to pro "partner", and this pro partner are in the process of switching their emails from xxx-dns.com to dns.com.
BUT the contact form provide by SwitchMailer doesn't work with the new DNS, I have check all configuration files, same for the server, the controller is (I think) ok.
Please help me, it's been a week
I have var_dump() all information in my controller, check api endpoint, navigate into my server and check configuration files.
This is my contact controller :
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Twig\Environment as Twig;
class ContactController extends AbstractController
{
/**
* #var string
*/
private $mailFrom;
/**
* #var string
*/
private $backUrl;
private $tokenStorage;
public function __construct(string $mailFrom, string $backUrl, TokenStorageInterface $tokenStorage)
{
$this->mailFrom = $mailFrom;
$this->backUrl = $backUrl;
$this->tokenStorage = $tokenStorage;
}
/**
* #Route("/contact", name="app_send_contact")
*/
public function sendAction(\Swift_Mailer $mailer, Twig $twig, Request $request)
{
// Retrieve user
$currentUser = $this->tokenStorage->getToken()->getUser();
if (!$currentUser) {
return $this->json(array('success' => false, 'message' => 'Utilisateur introuvable.'));
}
// Prepare parameters
$contactObject = $request->request->get('object');
$contactMessage = $request->request->get('message');
// Retrieve establishment
$establishment = $currentUser->getEstablishments()->first();
if (!$establishment) {
return $this->json(array('success' => false, 'message' => 'Etablissement introuvable.'));
}
// Prepare mail
$mailTitle = $currentUser->getFirstname() . ' ' . $currentUser->getLastname() . ' vous a envoyé un message : ' . $contactObject;
// Send mail to establishment
$message = (new \Swift_Message($mailTitle))
->setFrom($this->mailFrom)
->setTo($establishment->getEmail())
->setReplyTo($currentUser->getEmail(), $currentUser->getFirstname() . ' ' . $currentUser->getLastname())
->setBody(
$twig->render(
'emails/contact.html.twig',
array(
'user' => $currentUser,
'establishment' => $establishment,
'contact_object' => $contactObject,
'contact_message' => $contactMessage,
'back_url' => $this->backUrl,
)
),
'text/html'
);
$mailer->send($message);
// Prepare mail
$mailTitle = 'Confirmation de demande de contact';
// Send mail to parent
$message = (new \Swift_Message($mailTitle))
->setFrom($this->mailFrom)
->setTo($currentUser->getEmail())
->setBody(
$twig->render(
'emails/contact_confirmation.html.twig',
array(
'user' => $currentUser,
'establishment' => $establishment,
'contact_object' => $contactObject,
'contact_message' => $contactMessage,
'back_url' => $this->backUrl,
)
),
'text/html'
);
$mailer->send($message);
return $this->json(array('success' => true));
}
}```

sending notification in pusher private channel to selected users laravel8

I'm sending notifications using the public pusher channel in laravel8 .. How can I turn it to a private channel in order to send notifications just to the selected user.. which the admin selected from the dropdown menu?
here is my controller
public function notification(MessageRequest $request){
$data =[
'title' => $request->title,
'body' => $request->body,
// 'users' => $request->users,
];
event(new NewNotification($data));
return redirect()->back()->with(['success'=>'success']);
}
My event :
class NewNotification implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* #return void
*/
public $title;
public $body;
// public $users;
public function __construct($data=[])
{
$this->title = $data['title'];
$this->body = $data['body'];
// $this->users = $data['users'];
}
/**
* Get the channels the event should broadcast on.
*
* #return Channel|array
*/
public function broadcastOn()
{
return new Channel('notification');
}
}
this is layout:
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://js.pusher.com/7.0/pusher.min.js"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher('e7a414640973c420f866', {
// cluster: 'mt1'
});
</script>
<script src="{{asset('js/pusherNotifications.js')}}"></script>
and javascript file is :
var notificationsWrapper = $('.dropdown-notifications');
var notificationsToggle = notificationsWrapper.find('a[data-toggle]');
var notificationsCountElem = notificationsToggle.find('span[data-count]');
var notificationsCount = parseInt(notificationsCountElem.data('count'));
var notifications = notificationsWrapper.find('li.scrollable-container');
// Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe('notification');
// Bind a function to a Event (the full Laravel class)
channel.bind('App\\Events\\NewNotification', function (data) {
var existingNotifications = notifications.html();
var newNotificationHtml = `<a href="`+data.title+`">
<div class="media-body"><h6 class="media-heading text-right">` + data.title + `</h6>
<p class="notification-text font-small-3 text-muted text-right">` + data.body + `</p><small style="direction: ltr;">
</small></div></div></a>`;
notifications.html(newNotificationHtml + existingNotifications);
notificationsCount += 1;
notificationsCountElem.attr('data-count', notificationsCount);
notificationsWrapper.find('.notif-count').text(notificationsCount);
notificationsWrapper.show();
});
any help please,

My file not in uploads directory after upload was successful

I try to upload file using Yii2 file upload and the file path was successful saved to the database but the file was not saved to the directory I specify.. below is my code..
<?php
namespace backend\models;
use yii\base\Model;
use yii\web\UploadedFile;
use yii\Validators\FileValidator;
use Yii;
class UploadForm extends Model
{
/**
* #var UploadedFile
*/
public $image;
public $randomCharacter;
public function rules(){
return[
[['image'], 'file', 'skipOnEmpty' => false, 'extensions'=> 'png, jpg,jpeg'],
];
}
public function upload(){
$path = \Yii::getAlias("#backend/web/uploads/");
$randomString = "";
$length = 10;
$character = "QWERTYUIOPLKJHGFDSAZXCVBNMlkjhgfdsaqwertpoiuyzxcvbnm1098723456";
$randomString = substr(str_shuffle($character),0,$length);
$this->randomCharacter = $randomString;
if ($this->validate()){
$this->image->saveAs($path .$this->randomCharacter .'.'.$this->image->extension);
//$this->image->saveAs(\Yii::getAlias("#backend/web/uploads/{$randomString}.{$this->image->extension}"));
return true;
}else{
return false;
}
}
}
The controller to create the fileupload
namespace backend\controllers;
use Yii;
use backend\models\Product;
use backend\models\ProductSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\UploadForm;
use yii\web\UploadedFile;
public function actionCreate()
{
$addd_at = time();
$model = new Product();
$upload = new UploadForm();
if($model->load(Yii::$app->request->post())){
//get instance of the uploaded file
$model->image = UploadedFile::getInstance($model, 'image');
$upload->upload();
$model->added_at = $addd_at;
$model->image = 'uploads/' .$upload->randomCharacter .'.'.$model->image->extension;
$model->save();
return $this->redirect(['view', 'product_id' => $model->product_id]);
} else{
return $this->render('create', [
'model' => $model,
]);
}
}
Does it throw any errors?
This is propably permission issue. Try changing the "uploads" directory permission to 777 (for test only).
You load your Product ($model) with form data.
if($model->load(Yii::$app->request->post()))
But Uploadform ($upload) never gets filled in your script. Consequently, $upload->image will be empty.
Since you declare 'skipOnEmpty' => false in the file validator of the UploadForm rules, the validation on $upload will fail.
That is why your if statement in the comments above (if($upload->upload()) doesn't save $model data.
I don't see why you would need another model to serve this purpose. It only complicates things, so I assume its because you copied it from a tutorial. To fix and make things more simple, just do the following things:
Add property to Product model
public $image;
Add image rule to Product model
[['image'], 'file', 'skipOnEmpty' => false, 'extensions'=> 'png, jpg,jpeg'],
Adjust controller create action
public function actionCreate()
{
$model = new Product();
if($model->load(Yii::$app->request->post()) && $model->validate()) {
// load image
$image = UploadedFile::getInstance($model, 'image');
// generate random filename
$rand = Yii::$app->security->generateRandomString(10);
// define upload path
$path = 'uploads/' . $rand . '.' . $image->extension;
// store image to server
$image->saveAs('#webroot/' . $path);
$model->added_at = time();
$model->image = $path;
if($model->save()) {
return $this->redirect(['view', 'product_id' => $model->product_id]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Something like this should do the trick.
Your UploadForm class is already on Backend so on function upload of UploadForm Class it should be like this:
Change this line:
$path = \Yii::getAlias("#backend/web/uploads/");
to this:
$path = \Yii::getAlias("uploads")."/";

Is there a way to get the last error in php4

PHP 5 has error_get_last. Is there any way to completely or at least partially replicate the same functionality in PHP4.3?
Ripped from the PHP manual (courtesy of php at joert dot net):
<?php
if( !function_exists('error_get_last') ) {
set_error_handler(
create_function(
'$errno,$errstr,$errfile,$errline,$errcontext',
'
global $__error_get_last_retval__;
$__error_get_last_retval__ = array(
\'type\' => $errno,
\'message\' => $errstr,
\'file\' => $errfile,
\'line\' => $errline
);
return false;
'
)
);
function error_get_last() {
global $__error_get_last_retval__;
if( !isset($__error_get_last_retval__) ) {
return null;
}
return $__error_get_last_retval__;
}
}
?>
Yes it is, but you will have to do some programming, you need to attach error handler
$er_handler = set_error_handler("myErrorHandler");
but before this you need to write your "myErrorHandler"
function myErrorHandler($errNumber, $errString, $errFile, $errLine)
{
/*now add it to session so you can access it from anywhere, or if you have class with the static variable you can save it there */
$_SESSION["Error.LastError"] = $errNumber . '<br>' . $errString . '<br>' . $errFile . '<br>' . $errLine;
}
Now when error is occured you can get it by
if(isset($_SESSION["Error.LastError"]))
$str = $_SESSION["Error.LastError"];
now to replicate your method you need to create function
function get_last_error()
{
$str = "";
if(isset($_SESSION["Error.LastError"]))
$str = $_SESSION["Error.LastError"];
return $str;
}

Customizing Joomla PDF output

In Joomla 1.5 constructor of JDocumentPDF class has an array parameter to setup some parameter of generated PDF.
function __construct($options = array()) {
parent::__construct($options);
if (isset($options['margin-header'])) {
$this->_margin_header = $options['margin-header'];
}
if (isset($options['margin-footer'])) {
$this->_margin_footer = $options['margin-footer'];
}
if (isset($options['margin-top'])) {
$this->_margin_top = $options['margin-top'];
}
...
}
_createDocument() function of JFactory class instantiates JDocumentPDF object, but doesn't pass any options that useful for PDF generation:
function &_createDocument() {
...
$attributes = array (
'charset' => 'utf-8',
'lineend' => 'unix',
'tab' => ' ',
'language' => $lang->getTag(),
'direction' => $lang->isRTL() ? 'rtl' : 'ltr'
);
$doc =& JDocument::getInstance($type, $attributes);
return $doc;
}
So I don't understand how it works and where can I set this options (margin-header, margin-footer etc)?
To set and get any properties of JDocumentPDF
you can call set and get function on object. For example
$obj = JFactory::getDocument();
$marginHeader = $obj->get('_margin_header');
$obj->set('_margin_header', $value);