Datasets:

Modalities:
Text
Formats:
json
Languages:
code
Size:
< 1K
Tags:
code
Libraries:
Datasets
pandas
License:
File size: 9,117 Bytes
eb67da4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt

from __future__ import unicode_literals

import frappe
import frappe.utils
from frappe import throw, _
from frappe.website.website_generator import WebsiteGenerator
from frappe.utils.verified_command import get_signed_params, verify_request
from frappe.email.queue import send
from frappe.email.doctype.email_group.email_group import add_subscribers
from frappe.utils import parse_addr, now_datetime, markdown, validate_email_address

class Newsletter(WebsiteGenerator):
	def onload(self):
		if self.email_sent:
			self.get("__onload").status_count = dict(frappe.db.sql("""select status, count(name)
				from `tabEmail Queue` where reference_doctype=%s and reference_name=%s
				group by status""", (self.doctype, self.name))) or None

	def validate(self):
		self.route = "newsletters/" + self.name
		if self.send_from:
			validate_email_address(self.send_from, True)

	def test_send(self, doctype="Lead"):
		self.recipients = frappe.utils.split_emails(self.test_email_id)
		self.queue_all(test_email=True)
		frappe.msgprint(_("Test email sent to {0}").format(self.test_email_id))
	# BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
	# 
	# FIXED:
	@frappe.whitelist()
	def send_emails(self):
		"""send emails to leads and customers"""
		if self.email_sent:
			throw(_("Newsletter has already been sent"))

		self.recipients = self.get_recipients()

		if self.recipients:
			self.queue_all()
			frappe.msgprint(_("Email queued to {0} recipients").format(len(self.recipients)))

		else:
			frappe.msgprint(_("Newsletter should have atleast one recipient"))

	def queue_all(self, test_email=False):
		if not self.get("recipients"):
			# in case it is called via worker
			self.recipients = self.get_recipients()

		self.validate_send()

		sender = self.send_from or frappe.utils.get_formatted_email(self.owner)

		if not frappe.flags.in_test:
			frappe.db.auto_commit_on_many_writes = True

		attachments = []
		if self.send_attachments:
			files = frappe.get_all("File", fields=["name"], filters={"attached_to_doctype": "Newsletter",
				"attached_to_name": self.name}, order_by="creation desc")

			for file in files:
				try:
					# these attachments will be attached on-demand
					# and won't be stored in the message
					attachments.append({"fid": file.name})
				except IOError:
					frappe.throw(_("Unable to find attachment {0}").format(file.name))

		args = {
			"message": self.get_message(),
			"name": self.name
		}
		frappe.sendmail(recipients=self.recipients, sender=sender,
			subject=self.subject, message=self.get_message(), template="newsletter",
			reference_doctype=self.doctype, reference_name=self.name,
			add_unsubscribe_link=self.send_unsubscribe_link, attachments=attachments,
			unsubscribe_method="/unsubscribe",
			unsubscribe_params={"name": self.name},
			send_priority=0, queue_separately=True, args=args)

		if not frappe.flags.in_test:
			frappe.db.auto_commit_on_many_writes = False

		if not test_email:
			self.db_set("email_sent", 1)
			self.db_set("schedule_send", now_datetime())
			self.db_set("scheduled_to_send", len(self.recipients))

	def get_message(self):
		if self.content_type == "HTML":
			return frappe.render_template(self.message_html, {"doc": self.as_dict()})
		return {
			'Rich Text': self.message,
			'Markdown': markdown(self.message_md)
		}[self.content_type or 'Rich Text']

	def get_recipients(self):
		"""Get recipients from Email Group"""
		recipients_list = []
		for email_group in get_email_groups(self.name):
			for d in frappe.db.get_all("Email Group Member", ["email"],
				{"unsubscribed": 0, "email_group": email_group.email_group}):
					recipients_list.append(d.email)
		return list(set(recipients_list))

	def validate_send(self):
		if self.get("__islocal"):
			throw(_("Please save the Newsletter before sending"))

		if not self.recipients:
			frappe.throw(_("Newsletter should have at least one recipient"))

	def get_context(self, context):
		newsletters = get_newsletter_list("Newsletter", None, None, 0)
		if newsletters:
			newsletter_list = [d.name for d in newsletters]
			if self.name not in newsletter_list:
				frappe.redirect_to_message(_('Permission Error'),
					_("You are not permitted to view the newsletter."))
				frappe.local.flags.redirect_location = frappe.local.response.location
				raise frappe.Redirect
			else:
				context.attachments = get_attachments(self.name)
		context.no_cache = 1
		context.show_sidebar = True


def get_attachments(name):
	return frappe.get_all("File",
			fields=["name", "file_name", "file_url", "is_private"],
			filters = {"attached_to_name": name, "attached_to_doctype": "Newsletter", "is_private":0})


def get_email_groups(name):
	return frappe.db.get_all("Newsletter Email Group", ["email_group"],{"parent":name, "parenttype":"Newsletter"})


@frappe.whitelist(allow_guest=True)
def confirmed_unsubscribe(email, group):
	""" unsubscribe the email(user) from the mailing list(email_group) """
	frappe.flags.ignore_permissions=True
	doc = frappe.get_doc("Email Group Member", {"email": email, "email_group": group})
	if not doc.unsubscribed:
		doc.unsubscribed = 1
		doc.save(ignore_permissions = True)

def create_lead(email_id):
	"""create a lead if it does not exist"""
	from frappe.model.naming import get_default_naming_series
	full_name, email_id = parse_addr(email_id)
	if frappe.db.get_value("Lead", {"email_id": email_id}):
		return

	lead = frappe.get_doc({
		"doctype": "Lead",
		"email_id": email_id,
		"lead_name": full_name or email_id,
		"status": "Lead",
		"naming_series": get_default_naming_series("Lead"),
		"company": frappe.db.get_default("Company"),
		"source": "Email"
	})
	lead.insert()


@frappe.whitelist(allow_guest=True)
def subscribe(email, email_group=_('Website')):
	url = frappe.utils.get_url("/api/method/frappe.email.doctype.newsletter.newsletter.confirm_subscription") +\
		"?" + get_signed_params({"email": email, "email_group": email_group})

	email_template = frappe.db.get_value('Email Group', email_group, ['confirmation_email_template'])

	content=''
	if email_template:
		args = dict(
			email=email,
			confirmation_url=url,
			email_group=email_group
		)

		email_template = frappe.get_doc("Email Template", email_template)
		content = frappe.render_template(email_template.response, args)

	if not content:
		messages = (
			_("Thank you for your interest in subscribing to our updates"),
			_("Please verify your Email Address"),
			url,
			_("Click here to verify")
		)

		content = """
		<p>{0}. {1}.</p>
		<p><a href="{2}">{3}</a></p>
		""".format(*messages)

	frappe.sendmail(email, subject=getattr('email_template', 'subject', '') or _("Confirm Your Email"), content=content, now=True)

@frappe.whitelist(allow_guest=True)
def confirm_subscription(email, email_group=_('Website')):
	if not verify_request():
		return

	if not frappe.db.exists("Email Group", email_group):
		frappe.get_doc({
			"doctype": "Email Group",
			"title": email_group
		}).insert(ignore_permissions=True)

	frappe.flags.ignore_permissions = True

	add_subscribers(email_group, email)
	frappe.db.commit()

	frappe.respond_as_web_page(_("Confirmed"),
		_("{0} has been successfully added to the Email Group.").format(email),
		indicator_color='green')


def send_newsletter(newsletter):
	try:
		doc = frappe.get_doc("Newsletter", newsletter)
		doc.queue_all()

	except:
		frappe.db.rollback()

		# wasn't able to send emails :(
		doc.db_set("email_sent", 0)
		frappe.db.commit()

		frappe.log_error(title='Send Newsletter')

		raise

	else:
		frappe.db.commit()


def get_list_context(context=None):
	context.update({
		"show_sidebar": True,
		"show_search": True,
		'no_breadcrumbs': True,
		"title": _("Newsletter"),
		"get_list": get_newsletter_list,
		"row_template": "email/doctype/newsletter/templates/newsletter_row.html",
	})


def get_newsletter_list(doctype, txt, filters, limit_start, limit_page_length=20, order_by="modified"):
	email_group_list = frappe.db.sql('''SELECT eg.name
		FROM `tabEmail Group` eg, `tabEmail Group Member` egm
		WHERE egm.unsubscribed=0
		AND eg.name=egm.email_group
		AND egm.email = %s''', frappe.session.user)
	email_group_list = [d[0] for d in email_group_list]

	if email_group_list:
		return frappe.db.sql('''SELECT n.name, n.subject, n.message, n.modified
			FROM `tabNewsletter` n, `tabNewsletter Email Group` neg
			WHERE n.name = neg.parent
			AND n.email_sent=1
			AND n.published=1
			AND neg.email_group in ({0})
			ORDER BY n.modified DESC LIMIT {1} OFFSET {2}
			'''.format(','.join(['%s'] * len(email_group_list)),
					limit_page_length, limit_start), email_group_list, as_dict=1)

def send_scheduled_email():
	"""Send scheduled newsletter to the recipients."""
	scheduled_newsletter = frappe.get_all('Newsletter', filters = {
		'schedule_send': ('<=', now_datetime()),
		'email_sent': 0,
		'schedule_sending': 1
	}, fields = ['name'], ignore_ifnull=True)
	for newsletter in scheduled_newsletter:
		send_newsletter(newsletter.name)