EventEmitter error after updating to NPM 3.10 - node.js

I have updated NPM and now my code is returning the following error (please see picture):
Error Message can someone please provide guidance in identifying the culprit? My suspicion is that it has to do with inheritss which I'm not familiar with.
/**
* Expose the constructor.
*/
exports = module.exports = Store;
/**
* Module dependencies.
*/
var EventEmitter = process.EventEmitter;
/**
* Store interface
*
* #api public
*/
function Store (options) {
this.options = options;
this.clients = {};
};
/**
* Inherit from EventEmitter.
*/
Store.prototype.__proto__ = EventEmitter.prototype;
/**
* Initializes a client store
*
* #param {String} id
* #api public
*/
Store.prototype.client = function (id) {
if (!this.clients[id]) {
this.clients[id] = new (this.constructor.Client)(this, id);
}
return this.clients[id];
};
/**
* Destroys a client
*
* #api {String} sid
* #param {Number} number of seconds to expire client data
* #api private
*/
Store.prototype.destroyClient = function (id, expiration) {
if (this.clients[id]) {
this.clients[id].destroy(expiration);
delete this.clients[id];
}
return this;
};
/**
* Destroys the store
*
* #param {Number} number of seconds to expire client data
* #api private
*/
Store.prototype.destroy = function (clientExpiration) {
var keys = Object.keys(this.clients)
, count = keys.length;
for (var i = 0, l = count; i < l; i++) {
this.destroyClient(keys[i], clientExpiration);
}
this.clients = {};
return this;
};
/**
* Client.
*
* #api public
*/
Store.Client = function (store, id) {
this.store = store;
this.id = id;
};

The current way to get the EventEmitter class is:
const EventEmitter = require('events');
You should not be using process.EventEmitter.
In addition, the modern way to subclass an object is using either the ES6 class syntax or using Object.create(), not using __proto__.

Related

failed to send activation message with Mythauth

I am using myth auth to signup my website, in localhost its work but when hosting, send activation to email always display error "failed to send activation message", can anyone help me?
do it like me
/**
* Resend activation account.
* #param AuthEntity $entity
*/
public
function sendActivateCodeViaEmail(AuthEntity $entity): void
{
if (is_null($entity)) $this->httpException(lang('Shared.api.validation'), ResponseInterface::HTTP_NOT_ACCEPTABLE);
$findUser = $this->userModel->where('email', $entity->email)
->where('active', 0)
->first();
if (is_null($findUser)) $this->httpException(lang('Auth.activationNoUser'), ResponseInterface::HTTP_CONFLICT);
$isSent = $this->email
->setTo($entity->email)
->setSubject(lang('Auth.activationSubject'))
->setMessage(view($this->authConfig->views['emailActivation'],
['hash' => $entity->toArray()['activate_hash']]))
->setMailType('html')->send();
if (!$isSent) {
$this->httpException(lang('Auth.unknownError'),
ResponseInterface::HTTP_BAD_REQUEST, $this->email->printDebugger(['headers']['headers'] ?? lang('Auth.unknownError')));
}
unset($entity->email);
if (!$this->userModel->update($findUser->id, $entity)) {
$this->httpException(lang('Shared.api.reject'), ResponseInterface::HTTP_BAD_REQUEST, serializeMessages($this->userModel->errors()));
}
}
email config
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Email extends BaseConfig
{
/**
* #var string
*/
public $fromEmail='admin#emaple.ir';
/**
* #var string
*/
public $fromName='admin';
/**
* #var string
*/
public $recipients;
/**
* The "user agent"
*
* #var string
*/
public $userAgent = 'CodeIgniter';
/**
* The mail sending protocol: mail, sendmail, smtp
*
* #var string
*/
public $protocol = 'smtp';
/**
* The server path to Sendmail.
*
* #var string
*/
public $mailPath = '/usr/sbin/sendmail';
/**
* SMTP Server Address
*
* #var string
*/
public $SMTPHost='mail.emaple.ir';
/**
* SMTP Username
*
* #var string
*/
public $SMTPUser='admin#emaile.ir';
/**
* SMTP Password
*
* #var string
*/
public $SMTPPass='X04r0U2ikd';
/**
* SMTP Port
*
* #var int
*/
public $SMTPPort = 25;
/**
* SMTP Timeout (in seconds)
*
* #var int
*/
public $SMTPTimeout = 5;
/**
* Enable persistent SMTP connections
*
* #var bool
*/
public $SMTPKeepAlive = false;
/**
* SMTP Encryption. Either tls or ssl
*
* #var string
*/
public $SMTPCrypto = '';
/**
* Enable word-wrap
*
* #var bool
*/
public $wordWrap = true;
/**
* Character count to wrap at
*
* #var int
*/
public $wrapChars = 76;
/**
* Type of mail, either 'text' or 'html'
*
* #var string
*/
public $mailType = 'text';
/**
* Character set (utf-8, iso-8859-1, etc.)
*
* #var string
*/
public $charset = 'UTF-8';
/**
* Whether to validate the email address
*
* #var bool
*/
public $validate = false;
/**
* Email Priority. 1 = highest. 5 = lowest. 3 = normal
*
* #var int
*/
public $priority = 3;
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*
* #var string
*/
public $CRLF = "\r\n";
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*
* #var string
*/
public $newline = "\r\n";
/**
* Enable BCC Batch Mode.
*
* #var bool
*/
public $BCCBatchMode = false;
/**
* Number of emails in each BCC batch
*
* #var int
*/
public $BCCBatchSize = 200;
/**
* Enable notify message from server
*
* #var bool
*/
public $DSN = false;
}

Call to a member function format() on string symfony 3.4

I'm trying to register a new appointment in my database, after sending an email, but it shows me an error: Call to a member function format() on string,
in vendor\doctrine\dbal\lib\Doctrine\DBAL\Types\DateTimeType.php
,
because in the booking entity, there is the date and time I need to register which are datetime types.
Here is the booking entity :
<?php
namespace Doctix\FrontBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Booking
*
* #ORM\Table(name="booking")
*
class Booking
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
*#ORM\Column(name="date_rdv", type="datetime", nullable=true)
*/
private $dateRdv;
/**
* #var \DateTime
*
*#ORM\Column(name="heure_rdv", type="datetime", nullable=true)
*/
private $heureRdv;
/**
* #var bool
*
*#ORM\Column(name="valider_rdv", type="boolean", nullable=true)
*/
private $validerRdv;
/**
* #ORM\ManyToOne(targetEntity="Doctix\MedecinBundle\Entity\Medecin")
* #ORM\JoinColumn(nullable=true)
*/
private $medecin;
/**
* #ORM\ManyToOne(targetEntity="Doctix\PatientBundle\Entity\Patient")
* #ORM\JoinColumn(nullable=true)
*/
private $patient;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set dateRdv
*
* #param \DateTime $dateRdv
*
* #return Booking
*/
public function setDateRdv($dateRdv)
{
$this->dateRdv = $dateRdv;
return $this;
}
/**
* Get dateRdv
*
* #return \DateTime
*/
public function getDateRdv()
{
return $this->dateRdv;
}
/**
* Set heureRdv
*
* #param \DateTime $heureRdv
*
* #return Booking
*/
public function setHeureRdv($heureRdv)
{
$this->heureRdv = $heureRdv;
return $this;
}
/**
* Get heureRdv
*
* #return \DateTime
*/
public function getHeureRdv()
{
return $this->heureRdv;
}
/**
* Set validerRdv
*
* #param boolean $validerRdv
*
* #return Booking
*/
public function setValiderRdv($validerRdv)
{
$this->validerRdv = $validerRdv;
return $this;
}
/**
* Get validerRdv
*
* #return bool
*/
public function getValiderRdv()
{
return $this->validerRdv;
}
/**
* Set medecin
*
* #param \Doctix\MedecinBundle\Entity\Medecin $medecin
* #return Booking
*/
public function setMedecin(\Doctix\MedecinBundle\Entity\Medecin $medecin)
{
$this->medecin = $medecin;
return $this;
}
/**
* Get medecin
*
* #return \Doctix\MedecinBundle\Entity\Medecin
*/
public function getMedecin()
{
return $this->medecin;
}
/**
* Set patient
*
* #param \Doctix\PatientBundle\Entity\Patient $patient
* #return Booking
*/
public function setPatient(\Doctix\PatientBundle\Entity\Patient $patient)
{
$this->patient = $patient;
return $this;
}
/**
* Get patient
*
* #return \Doctix\PatientBundle\Entity\Patient
*/
public function getPatient()
{
return $this->patient;
}
}
Here is the controller:
public function patientHandleBookingAction(Request $request){
$id = $request->query->get('id');
$date = $request->query->get('date');
$time = $request->query->get('time');
// $user = $this->getUser();
$em = $this->getDoctrine()->getManager();
$repoPatient = $em->getRepository('DoctixPatientBundle:Patient');
$patient = $repoPatient->findOneBy(array(
'user' => $this->getUser()
));
$repoMedecin = $em->getRepository('DoctixMedecinBundle:Medecin');
$medecin = $repoMedecin->findOneBy(array(
'id' => $request->query->get("idMedecin")));
$mailer = $this->get('mailer');
$message = (new \Swift_Message('Email de Confirmaton'))
->setFrom("medmamtest#gmail.com")
->setTo($patient->getUser()->getUsername())
->setBody(
$this->renderView(
// app/Resources/views/Emails/registration.html.twig
'Emails/registration.html.twig',
array('name' => 'mam')
),
'text/html'
);
$mailer->send($message);
if($mailer){
$booking = new Booking();
$booking->setMedecin($medecin);
$booking->setPatient($patient);
$booking->setDateRdv('date');
$booking->setHeureRdv('time');
$booking->setValiderRdv(0);
}
$em->persist($booking);
$em->flush();
// A remplacer par un contenu plus approprié
return $this->render('DoctixPatientBundle:Patient:confirm.html.twig',array(
'time' => $request->query->get("time"),
'date' => $request->query->get("date"),
'medecin' => $medecin,
'patient' => $patient,
// 'date' => $date,
// 'time' => $time
));
}
Thanks
This error is happening because you are trying to set the date and time as strings on your booking entity.
$booking->setDateRdv('date');
$booking->setHeureRdv('time');
Try to change it to:
$booking->setDateRdv(new \DateTime($date));
$booking->setHeureRdv(new \DateTime($time));

Magento2 Attribute Group Name from Attribute Collection

I need Attribute Group Name from Attribute Collection associated with attribute Id. I have Aattribute Set ID.
Thanks!
/**
* #var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory
*/
protected $_groupCollection;
public function __construct(
\Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory $groupCollectionFactory
)
{
$this->_groupCollection = $groupCollectionFactory;
}
/**
* #param $attributSetID
* #return array
*/
public function getAttributeGroupName($attributeSetID){
$groups = $this->_groupCollection->create();
$groups->setAttributeSetFilter($attributeSetID);
$groupData = [];
/* #var $group \Magento\Eav\Model\Entity\Attribute\Group */
foreach ($groups as $group) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$attributeCollection = $objectManager->create('Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection');
$attributeCollection
->setAttributeGroupFilter($group->getId())
->setAttributeSetFilter($attributeSetID);
foreach ($attributeCollection->getAllIds() as $attributeId) {
$groupData[$attributeId] = $group->getAttributeGroupName();
}
}
return $groupData;
}

Symfony2 - Using controller security for user and category

I am trying to restrict user access from accessing the CRUD access in the controller.
I have a bi-directional OneToOne relationship with User and Category. It's setup to only allow 1 user to be able to access 1 blog.
I am testing this by logging in as another user that is not related to this category. And upon clicking on new, the form loads by-passing any security I have setup.
Speculating that the problem is with the $title parameter being passed in, (trying to pass this in as the route variable) as I don't think I'm setting this up correctly.
Can someone guide me on what I'm doing wrong?
Controller code
/**
* Post controller.
*
* #Route("/category")
*/
/**
* Creates a new Post entity.
*
* #Route("/", name="category_create")
* #Method("POST")
* #Template("AcmeDemoBundle:Page:new.html.twig")
*/
public function createAction(Request $request, $title)
{
// User security
$em = $this->getDoctrine()->getManager();
$categoryRepository = $em->getRepository('AcmeDemoBundle:Category');
$category = $categoryRepository->findOneBy(array(
'title' => '$title',
));
$owner = $category->getUser();
$currentUser = $this->get('security.context')->getToken()->getUser();
if ($owner != $currentUser) {
throw new AccessDeniedException('You do not have access for this');
}
// Form creation
$post = new Post();
$form = $this->createCreateForm($post);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
return $this->redirect($this->generateUrl('category_show', array('id' => $post->getId())));
}
return array(
'post' => $post,
'form' => $form->createView(),
);
}
Category entity
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string
*
* #Gedmo\Slug(fields={"title"}, unique=false)
* #ORM\Column(length=255)
*/
private $catslug;
/**
* #ORM\OneToMany(targetEntity="Post", mappedBy="category")
*/
protected $posts;
/**
* #ORM\OneToOne(targetEntity="Acme\DemoBundle\Entity\User", inversedBy="cat")
* #ORM\JoinColumn(name="cat_id", referencedColumnName="id")
*/
protected $user;
User entity
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=255)
* #Assert\NotBlank(message="Field cannot be blank")
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank()
*/
private $email;
/**
* #ORM\Column(type="json_array")
*/
private $roles = array();
/**
* #var bool
*
* #ORM\Column(type="boolean")
*/
private $isActive = true;
/**
* #Assert\NotBlank
* #Assert\Regex(
* pattern="/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$/",
* message="Use 1 upper case letter, 1 lower case letter, and 1 number")
*/
private $plainPassword;
/**
* #ORM\OneToOne(targetEntity="Acme\DemoBundle\Entity\Category", mappedBy="user")
*/
private $cat;
You can try to create own Security Voter to check if user has a permission to this action. Sample code:
class CategoryVoter implements VoterInterface
{
const CREATE = 'create';
/**
* #param string $attribute
* #return bool
*/
public function supportsAttribute($attribute)
{
return in_array($attribute, [
self::CREATE
]);
}
/**
* #param string $class
* #return bool
*/
public function supportsClass($class)
{
$supportedClass = 'Acme\DemoBundle\Entity\Category';
return $supportedClass === $class || is_subclass_of($class, $supportedClass);
}
/**
* #param TokenInterface $token
* #param object $blog
* #param array $attributes
* #return int
*/
public function vote(TokenInterface $token, Category $category, array $attributes)
{
....
$attribute = $attributes[0];
$user = $token->getUser();
switch($attribute) {
case 'create':
if ($user->getId() === $category->getUser()->getId()) {
return VoterInterface::ACCESS_GRANTED;
}
break;
....
}
...
}
}
create action:
public function createAction(Request $request, $title)
{
$em = $this->getDoctrine()->getManager();
$categoryRepository = $em->getRepository('AcmeDemoBundle:Category');
$category = $categoryRepository->findOneBy([
'title' => '$title',
]);
...
if (false === $this->get('security.context')->isGranted('create', $category)) {
throw new AccessDeniedException('Unauthorised access!');
}
...
}

Command a2ps and Cups - Chineses Characters

Good day.
I have a problem to print files with Chinese characters directly of linux.
We use CUPS to manage your printers on linux and send the print command by a2ps.
Our files are in the encode/unicode (UTF-8 and ISO-8859), but the physical printing is not seeing the Chinese characters
example:
¸£ÌØÆû³µ½ðÈÚ£¨Öйú£©ÓÐÏÞ¹«Ë¾/
Has anyone been through this and know how I can change the unicode of the a2ps command or cups to be able to convert the files?
As a solution, I adopted perform a conversion to pdf with the correct encode and send the converted PDF to CUPS via PrintJob.java file.
public class PDFPrintService {
/**
* Printer Job.
*/
private PrinterJob printerJob = null;
/**
* File to printer.
*/
private InputStream file;
/**
* Class that represents the file to be printed.
*/
private PDFFilePrint pdfFilePrint;
/**
* File converted to PDF for printed.
*/
private PDFFile pdfFile;
/**
* Temporary directory used in the conversion to postscript used in prints.
*/
private String temporaryDirectoryPostscriptFiles;
/**
* Default Temporary Directory of Files.
*/
private String defaultTemporaryDirectoryFiles;
/**
* java.io.tmpdir
*/
private static final String JAVA_IO_TEMPDIR = "java.io.tmpdir";
/**
* Constructs the print job based on the PDFFilePrint class.
*
* #param inputStream
* #param jobName
* #throws IOException
* #throws PrinterException
*/
public PDFPrintService(PDFFilePrint pdfFilePrint) throws IOException, PrinterException {
this.pdfFilePrint = pdfFilePrint;
loadFile(pdfFilePrint.getFileName());
byte[] pdfContent = new byte[this.file.available()];
this.file.read(pdfContent, 0, this.file.available());
initialize(pdfContent, this.pdfFilePrint.getJobName());
}
/**
* Method responsible to load the file for print.
*
* #param fileName
* #throws FileNotFoundException
*/
private void loadFile(final String fileName) throws FileNotFoundException{
try {
this.file = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new FileNotFoundException("The File : " + fileName);
}
}
/**
* Initializes the job
*
* #param pdfContent
* #param jobName
* #throws IOException
* #throws PrinterException
*/
private void initialize(byte[] pdfContent, String jobName)
throws IOException, PrinterException {
ByteBuffer bb = ByteBuffer.wrap(pdfContent);
this.pdfFile = new PDFFile(bb);
PDFPrintPage pages = new PDFPrintPage(pdfFile);
this.printerJob = PrinterJob.getPrinterJob();
loadPrinterDestination();
PageFormat pageFormat = PrinterJob.getPrinterJob().defaultPage();
Book book = new Book();
book.append(pages, pageFormat, pdfFile.getNumPages());
printerJob.setPageable(book);
printerJob.setJobName(jobName);
Paper paper = new Paper();
paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
pageFormat.setPaper(paper);
}
/**
* Method responsible to get the printer.
*
* #throws PrinterException
*/
private void loadPrinterDestination() throws PrinterException {
String printerName = new String();
try {
PrintService[] services = PrinterJob.lookupPrintServices();
for (PrintService printService : services) {
printerName = printService.getName();
if (printerName.equalsIgnoreCase(this.pdfFilePrint.getPrinterName())) {
printerJob.setPrintService(printService);
break;
}
}
} catch (PrinterException e) {
e.printStackTrace();
throw new PrinterException("Printer not found : printerName " + printerName);
}
}
/**
* Method responsible to printer.
*
* #throws PrinterException
*/
public void print() throws PrinterException {
try {
loadNewTemporaryDirectoryPostscriptFiles();
this.printerJob.print(getPrinterPageSettings());
} finally {
loadDefaultTemporaryDirectoryPostscriptFiles();
closeFile();
}
}
/**
* Method responsible to load a new area for a temporary converted files in
* server.
*/
private void loadNewTemporaryDirectoryPostscriptFiles() {
this.defaultTemporaryDirectoryFiles = System.getProperty(JAVA_IO_TEMPDIR, null);
if(!temporaryDirectoryPostscriptFiles.trim().isEmpty()){
System.setProperty(JAVA_IO_TEMPDIR, temporaryDirectoryPostscriptFiles);
}
}
/**
* /**
* Method responsible to load a default temporary area of files.
*/
private void loadDefaultTemporaryDirectoryPostscriptFiles() {
String currentDirectoryUsed = System.getProperty(JAVA_IO_TEMPDIR, null);
if(!currentDirectoryUsed.equalsIgnoreCase(defaultTemporaryDirectoryFiles)){
System.setProperty(JAVA_IO_TEMPDIR, defaultTemporaryDirectoryFiles);
}
}
/**
* Method responsible to load settings of printer.
*
* #return PrintRequestAttributeSet
*/
private PrintRequestAttributeSet getPrinterPageSettings() {
PrintRequestAttributeSet printRequestAttribute = new HashPrintRequestAttributeSet();
loadPageRange(printRequestAttribute);
loadSide(printRequestAttribute);
loadOrientationPortrait(printRequestAttribute);
printRequestAttribute.add(NORMAL);
return printRequestAttribute;
}
/**
* Method responsible to close the file after the printer.
*/
private void closeFile() {
try {
this.file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Method responsible to load the orientation Portrait.
*
* #param printRequestAttribute
*/
private void loadOrientationPortrait(PrintRequestAttributeSet printRequestAttribute) {
printRequestAttribute.add(PORTRAIT);
}
/**
* Method responsible to load the Side of printer(ONE_SIDED or DUPLEX).
*
* #param printRequestAttribute
*/
private void loadSide(PrintRequestAttributeSet printRequestAttribute) {
if (!this.pdfFilePrint.isDuplexSidet()) {
printRequestAttribute.add(ONE_SIDED);
} else {
printRequestAttribute.add(DUPLEX);
}
}
/**
* Method responsible to load the page range of print.
*
* #param printRequestAttribute
*/
private void loadPageRange(PrintRequestAttributeSet printRequestAttribute) {
int lowerBound = pdfFilePrint.getLowerBound();
int upperBound = pdfFilePrint.getUpperBound();
if ((lowerBound < 1) && (upperBound < 1)) {
lowerBound = 1;
upperBound = pdfFile.getNumPages();
} else {
if ((lowerBound < 1) && (upperBound > 0)) {
lowerBound = 1;
} else {
if ((lowerBound > 0) && (upperBound < 1)) {
upperBound = pdfFile.getNumPages();
}
}
}
if (upperBound < lowerBound) {
upperBound = lowerBound;
}
if (lowerBound > pdfFile.getNumPages()) {
lowerBound = pdfFile.getNumPages();
}
if (upperBound > pdfFile.getNumPages()) {
upperBound = pdfFile.getNumPages();
}
PageRanges pageRanges = new PageRanges(lowerBound, upperBound);
printRequestAttribute.add(pageRanges);
}
/**
* Set temporaryDirectoryPostscriptFiles.
*
* #param temporaryDirectoryPostscriptFiles
*/
public void setTemporaryDirectoryPostscriptFiles(
String temporaryDirectoryPostscriptFiles) {
this.temporaryDirectoryPostscriptFiles = temporaryDirectoryPostscriptFiles;
}
}

Resources