CakePHP how send email notification - email

I'm trying to send email notification to some users via cron job in my app.
After a few hours of reading, I've understood that the best way to do that is using Shell.
Please can someone help me to understand how to do that, how can I use one myShell class's different actions to send different notifications? I mean that how can cron access to myShell different actions.
for example.
<?php
class MyShell extends Shell {
function send_task_notifications(){
.... //this must send email every day at 00:00 am
}
function send_new_post_notifications() {
.... //this must send email every week//
}
}
?>
Both of this actions are in MyShell class.
So how can I call one of them via Cron and is this MyShell class accessible by the URL?

Your shell need to change in the following way, you need to pass a parameters based on that parameters it will execute email notification/push notification. Move your functions to a component it will work
<?php
class MyShell extends Shell {
function main()
{
$option = !empty($this->args[0]) ? $this->args[0] : ”;
echo ‘Cron started without any issue.’;
App::import(‘Component’, 'MyOwnComponent');
$this->MyOwnComponent = &new MyOwnComponent();
switch ($option)
{
case 'task_notifications':
$this->MyOwnComponent->send_task_notifications();
break;
case 'post_notifications':
$this->MyOwnComponent->send_new_post_notifications();
break;
default:
echo 'No Parameters passed .';
}
}
}
?>
Your Component file as follows
<?php
class MyOwnComponent extends Object
{
function send_task_notifications(){
.... //this must send email every day at 00:00 am
}
function send_new_post_notifications() {
.... //this must send email every week//
}
}
?>
For more details refer the link http://cakephpsaint.wordpress.com/2013/05/15/6-steps-to-create-cron-jobs-in-cakephp/

Related

Form redirect for confirmation

Form redirect for confirmation can be currently managed using one of these two options:
1/ Flash message: using flashbag on the form page or another page like this:
$this->addFlash('success', 'Thank you');
return $this->redirectToRoute('confirmation_page');
2/ Confirmation page: using a dedicated confirmation like this:
return $this->redirectToRoute('confirmation_page');
BUT using option 2 makes the confirmation_page directly accessible from the browser without having submitted the form before. I am currently using flashbag mechanism to fix it by adding a $this->addFlash('success', true); before the redirection in the form and then checking the flashbag content in the confirmation page so that the route is accessible only once after being successfully redirected from the form.
Is there any best practice or more appropriate way to manage it?
/**
* #Route("/confirmation", methods="GET", name="confirmation_page")
*/
public function confirmation(): Response
{
$flashbag = $this->get('session')->getFlashBag();
$success = $flashbag->get("success");
if (!$success) {
return $this->redirectToRoute('app_home');
}
return $this->render('templates/confirmation.html.twig');
}
Flash Message is designed to display messages. Instead, use sessions in your application.
When submitting the confirmation form, create a variable in the session before the redirect
$this->requestStack->getSession()->set('verifyed',true);
return $this->redirectToRoute('confirmation_page');
Use the created variable in your method
public function confirmation(): Response
{
if (!$this->requestStack->getSession()->get('verifyed')) {
return $this->redirectToRoute('app_home');
}
return $this->render('templates/confirmation.html.twig');
}
Don't forget to inject the RequestStack into your controller
private RequestStack $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}

typo3 fe-manager how to get different admin emails

i have a question about fe-manager. In this extension it is possible to send a confirmation email to a admin. But it is always the same email. i like to send emails to various admins. for example: if the new user is from germany the receiving adress should be some#thing.de. if the new user is from switzerland the adress should be some#thing.ch.
any idea how to approach this?
any hints/solutions are more than welcome.
current state:
extension is created. i copied the finalCreate-Method from the AbstractController to my NewController. i changed the makeEmailArray() from:
Div::makeEmailArray(
$this->settings['new']['notifyAdmin'],
$this->settings['new']['email']['createAdminNotify']['receiver']['name']['value']
),
to:
Div::makeEmailArray('xxx#xxx.ch',
$this->settings['new']['email']['createAdminNotify']['receiver']['name']['value']
),
the ts setup.txt file is located in femanager_extended/Configuration/TypoScript/setup.txt
and contains the following code:
config.tx_extbase.objects {
In2\Femanager\Controller\NewController.className = Lbaumann\FemanagerExtended\Controller\NewController
}
is this the right approach?
There is no TypoScriptConfig for this behaiviour, but you can easily override the ControllerMethod and extend it with your needs.
Create your own extension like Vender "Vendor" (company/customername) and key "femanager_extended" with the extension_builder.
femanager_extended/Classes/Controller/NewController.php
<?php
namespace Vendor\FemanagerExtended\Controller;
class NewController extends \In2\Femanager\Controller\NewController
{
public function finalCreate($user, $action, $redirectByActionName, $login = true)
{
// own business logic
// replace the first Div::makeEmailArray...
// with your selected Admin-email-address
// see parent::finalCreate($user, $action, $redirectByActionName, $login);
}
}
femanager_extened/ext_typoscript_setup.txt
config.tx_extbase.objects {
In2\Femanager\Controller\NewController.className = Vendor\FemanagerExtended\Controller\NewController
}
I hope this will help you and i don´t forgot any settings.

Using Zend2 Flashmessenger Controller/Plugin to show success msg

I am using FlashMessenger Controller/Plugin to show error messages, and that works fine. I am trying to show success messages by setting the namespace to success.
$this->flashMessenger()->addSuccessMessage('Success msg!');
$successMessages = $this->flashMessenger()->hasSuccessMessages();
print_r($successMessages);exit;
$view = new ViewModel(array('success' => $successMessages));
When i print $successMessages it shows Array() as there are no messages to show.
Same is if i try to set namespace like this.
$this->flashMessenger()->setNamespace('success')->addSuccessMessage('Success msg!');
$successMessages = $this->flashMessenger()->setNamespace('success')->getMessages();
Is this the propper way to set namespace and how to show the message on view?
I am using this to show error messages, but it doesn't work with success messages.
<?php if (!empty($this->messages)): ?>
<?php foreach ($this->messages as $msg) : ?>
<div class="error-box"><?php echo $this->translate($msg) ?></div>
<?php endforeach; ?>
<?php endif; ?>
This is my FlashMessenger class.
It looks like you are writing and reading the messages in the same request.
Think that flashMessenger is mainly meant to save messages for later, as you can read in the old but meaningful ZF1 docs:
The FlashMessenger helper allows you to pass messages that the user
may need to see on the next request.
For example, you are in a request that comes from a form that is meant to add records to a list, in the controller/action that receives the form you save a record, write the message to the flashmessenger, and redirect the user to the controller/action that show the list of records again.
Something that you can see in this example from the ZF2 mvc plugins docs:
public function processAction()
{
// ... do some work ...
$this->flashMessenger()->addMessage('You are now logged in.');
return $this->redirect()->toRoute('user-success');
}
public function successAction()
{
$return = array('success' => true);
$flashMessenger = $this->flashMessenger();
if ($flashMessenger->hasMessages()) {
$return['messages'] = $flashMessenger->getMessages();
}
return $return;
}
If what you need is to read the messages in the same request (something that is also really common) you have to use the "Current Messages" methods of the helper. So, instead of calling
$this->flashMessenger()->hasSuccessMessages()
you should call
$this->flashMessenger()->hasCurrentSuccessMessages()
and instead of calling
$this->flashMessenger()->getSuccessMessages()
you should call
$this->flashMessenger()->getCurrentSuccessMessages()
You can take a look at the full list of functions, if you go to the Zend.Mvc.Controller.Plugin.FlashMessenger API docs and you search for "Current"
UPDATE
To show the messages in the view, you can use 2 approaches:
Retrieve the messages in the controller and send it to the view
In the controller
public function yourAction() {
return array (
'$successMessages'
=> $this->flashMessenger()->getCurrentSuccessMessages()
);
}
In the view
//note that getCurrentSuccessMessages() returns an array,
//so in the vew $successMessages is an array
foreach ($successMessages as $m) {
echo $m;
}
Retrieving directly in the view. The first thing that comes to mind is to use the FlashMessenger view helper (Zend\View\Helper \FlashMessenger), but im afraid it doesnt have a function to get the current messages. So, you can extend it, or even more, you can write your own view helper. You have here a good tutorial on how to do exactly this.
I just tested the following in a Controller:
$this->flashMessenger()->addSuccessMessage('test');
if ($this->flashMessenger()->hasSuccessMessages()) {
print_r($this->flashMessenger()->getSuccessMessages());
}
This resulted in Array ( [0] => test )
Based on your question it appears you have not yet called on getSuccessMessages()
To get the messages into your ViewModel you could do something like this:
$viewModel = new ViewModel();
$viewModel->setVariable('messages', ($this->flashMessenger()->hasSuccessMessages()) ? $this->flashMessenger()->getSuccessMessages() : null);
And in your View you could do this:
if (!is_null($this->messages)) {
foreach ($this->messages as $message) {
echo $message . "\n";
}
}
Try reloading the page a few times to ensure that the message is visible. I personally use the EventManager (in my Controller) to check and handle messages stored in the flashMessenger(). For example:
public function setEventManager(EventManagerInterface $events)
{
parent::setEventManager($events);
$events->attach('dispatch', function () {
$this->getServiceLocator()->get('translator')->setLocale('en');
if ($this->flashMessenger()->hasMessages()) {
$this->Flash()->Display($this->flashMessenger()->getMessages()); // Custom Controller Plugin
}
}, 100);
}
Hope this helps you out!

create invoice and email in Magento

I want to automate the creation of invoice and email in Magento. Invoice creation seems to work but I am having getting the email part working...
Mage::app();
$order = Mage::getModel('sales/order')->loadByIncrementId($orderid);
try
{
if(!$order->canInvoice()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
}
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transactionSave->save();
}
catch (Mage_Core_Exception $e) {
}
}
I know my reaction is kinda late but for others who find this page:
You need to add the code for sending the email.
Do this after the register line:
$invoice->register();
$invoice->getOrder()->setCustomerNoteNotify(true);
$invoice->getOrder()->setIsInProcess(true);
$invoice->sendEmail();
setCustomerNoteNotify is used to say if the customer has to get the email.
setIsInProcess will change the order state to processing

silverstripe external authentification

there is a custom login form that should give users access to certain contents on the same page. That works so far with Users stored as Members in the SS database and I was checking after Login if the user has permissions like this in the Page Class:
function isAllowed() {
if (Member::currentUser()) {
$PresseGroup = DataObject::get_one('Group', "Code = 'presse'");
$AdminGroup = DataObject::get_one('Group', "Code = 'administrators'");
if (Member::currentUser()->inGroup($PresseGroup->ID) || Member::currentUser()->inGroup($AdminGroup->ID)) {
return true;
}
}
}
in the Template I just did this:
<% if isAllowed %>
SecretContent
<% end_if %>
OK so far, but now the users will not be stored in the silverstripe database - they are stored on a another server.
On that external server is running a little php script accepting the username and password. The script just returns user has permission: true or false.
I´m calling that script via cURL.
I planned to overwrite the dologin Function of MemberLoginForm. Now I just wonder how to check after Login that the User got the permission and display the contents... I tried to set a variable in the controller of the Page or should I set a session Variable? Thats my attempt (CustomLoginForm extends MemberLoginForm):
public function dologin($data) {
if(userHasPermission("user1", "pw")==true){
$this->controller->Test("test");
}
$link = $this->controller->Link();
$this->performLogin($data);
$this->controller->redirect($link);
}
I hope someone can help me with that - I know very specific - problem.
Many thanx,
Florian
In SilverStripe you can create a custom authenticator, which means users can log in on your website with accounts that are stored somewhere else, or even just a hard coded user and password.
You can check out the OpenID Authentication Module for example code on how to do it
But for your task this might even be to complex of a solution, how about after login just do something like Session::set('isAllowed', true); and to check if the user is allowed to view:
function isAllowed() {
if (Member::currentUser()) {
$PresseGroup = DataObject::get_one('Group', "Code = 'presse'");
$AdminGroup = DataObject::get_one('Group', "Code = 'administrators'");
if (Member::currentUser()->inGroup($PresseGroup->ID) || Member::currentUser()->inGroup($AdminGroup->ID)) {
return true;
}
}
// if Member::currentUser() is not allowed to view,
// return the session, which is either set to true or it returns null if not set
return Session::get('isAllowed');
}