PageRenderTime 50ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/web/studio/ASC.Web.Studio/Products/CRM/HttpHandlers/WebToLeadFromHandler.ashx.cs

https://github.com/dc0d/ONLYOFFICE-Server
C# | 376 lines | 274 code | 75 blank | 27 comment | 55 complexity | f13a1a906b84233d8e2d11e9117e58ea MD5 | raw file
Possible License(s): GPL-2.0, MPL-2.0-no-copyleft-exception
  1. /*
  2. (c) Copyright Ascensio System SIA 2010-2014
  3. This program is a free software product.
  4. You can redistribute it and/or modify it under the terms
  5. of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software
  6. Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended
  7. to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of
  8. any third-party rights.
  9. This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty
  10. of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see
  11. the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
  12. You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021.
  13. The interactive user interfaces in modified source and object code versions of the Program must
  14. display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3.
  15. Pursuant to Section 7(b) of the License you must retain the original Product logo when
  16. distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under
  17. trademark law for use of our trademarks.
  18. All the Product's GUI elements, including illustrations and icon sets, as well as technical writing
  19. content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0
  20. International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
  21. */
  22. using System;
  23. using System.Collections.Specialized;
  24. using System.Text;
  25. using System.Web;
  26. using ASC.CRM.Core;
  27. using ASC.CRM.Core.Entities;
  28. using ASC.Core;
  29. using ASC.MessagingSystem;
  30. using ASC.Web.CRM.Classes;
  31. using System.Collections.Generic;
  32. using System.Linq;
  33. using System.Xml.Linq;
  34. using ASC.Web.CRM.Services.NotifyService;
  35. using Newtonsoft.Json.Linq;
  36. using ASC.Web.CRM.Resources;
  37. using log4net;
  38. using ASC.Web.Core;
  39. using ASC.Web.CRM.Configuration;
  40. using ASC.Web.CRM.Core.Enums;
  41. namespace ASC.Web.CRM.HttpHandlers
  42. {
  43. public class WebToLeadFromHandler : IHttpHandler
  44. {
  45. private HttpContext _context;
  46. private String GetValue(String propertyName)
  47. {
  48. return _context.Request.Form[propertyName];
  49. }
  50. private bool CheckPermission()
  51. {
  52. try
  53. {
  54. var webFromKey = GetValue("web_form_key");
  55. if (String.IsNullOrEmpty(webFromKey))
  56. return false;
  57. var webFromKeyAsGuid = new Guid(webFromKey);
  58. return Global.TenantSettings.WebFormKey == webFromKeyAsGuid;
  59. }
  60. catch(Exception)
  61. {
  62. return false;
  63. }
  64. }
  65. public void ProcessRequest(HttpContext context)
  66. {
  67. try
  68. {
  69. _context = context;
  70. SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
  71. if (!CheckPermission())
  72. {
  73. throw new Exception(CRMSettingResource.WebToLeadsForm_InvalidKeyException);
  74. }
  75. var productInfo = WebItemSecurity.GetSecurityInfo(ProductEntryPoint.ID.ToString());
  76. if (!productInfo.Enabled)
  77. {
  78. throw new Exception(CRMCommonResource.CRMProductIsDisabled);
  79. }
  80. Contact contact;
  81. var fieldCollector = new NameValueCollection();
  82. var addressTemplate = new JObject();
  83. foreach (String addressPartName in Enum.GetNames(typeof(AddressPart)))
  84. addressTemplate.Add(addressPartName.ToLower(), "");
  85. var addressTemplateStr = addressTemplate.ToString();
  86. var isCompany = false;
  87. var isCompanyString = GetValue("is_company");
  88. var firstName = GetValue("firstName");
  89. var lastName = GetValue("lastName");
  90. var companyName = GetValue("companyName");
  91. if (!String.IsNullOrEmpty(isCompanyString))
  92. {
  93. if (!Boolean.TryParse(isCompanyString, out isCompany))
  94. {
  95. throw new ArgumentException();
  96. }
  97. }
  98. else //old scheme
  99. {
  100. if (!(String.IsNullOrEmpty(firstName) || String.IsNullOrEmpty(lastName)))
  101. {
  102. isCompany = false;
  103. }
  104. else if (!String.IsNullOrEmpty(companyName))
  105. {
  106. isCompany = true;
  107. }
  108. else
  109. {
  110. throw new ArgumentException();
  111. }
  112. }
  113. if (isCompany)
  114. {
  115. contact = new Company();
  116. ((Company)contact).CompanyName = companyName;
  117. fieldCollector.Add(CRMContactResource.CompanyName, companyName);
  118. }
  119. else
  120. {
  121. contact = new Person();
  122. ((Person)contact).FirstName = firstName;
  123. ((Person)contact).LastName = lastName;
  124. ((Person)contact).JobTitle = GetValue("jobTitle");
  125. fieldCollector.Add(CRMContactResource.FirstName, firstName);
  126. fieldCollector.Add(CRMContactResource.LastName, lastName);
  127. if (!String.IsNullOrEmpty(GetValue("jobTitle")))
  128. fieldCollector.Add(CRMContactResource.JobTitle, ((Person)contact).JobTitle);
  129. }
  130. contact.About = GetValue("about");
  131. if (!String.IsNullOrEmpty(contact.About))
  132. fieldCollector.Add(CRMContactResource.About, contact.About);
  133. if (!String.IsNullOrEmpty(GetValue("is_shared")))
  134. {
  135. contact.ShareType = Convert.ToBoolean(GetValue("is_shared")) ? ShareType.ReadWrite : ShareType.None;
  136. }
  137. else
  138. {
  139. contact.ShareType = (ShareType)(Convert.ToInt32(GetValue("share_type")));
  140. }
  141. contact.ID = Global.DaoFactory.GetContactDao().SaveContact(contact);
  142. var messageAction = contact is Company ? MessageAction.CompanyCreatedWithWebForm : MessageAction.PersonCreatedWithWebForm;
  143. MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction, contact.GetTitle());
  144. var contactInfos = new List<ContactInfo>();
  145. foreach (var key in _context.Request.Form.AllKeys)
  146. {
  147. if (key.StartsWith("customField_"))
  148. {
  149. var fieldID = Convert.ToInt32(key.Split(new[] {'_'})[1]);
  150. String fieldValue = GetValue(key);
  151. if (String.IsNullOrEmpty(fieldValue)) continue;
  152. var customField = Global.DaoFactory.GetCustomFieldDao().GetFieldDescription(fieldID);
  153. if (customField == null ||
  154. !(customField.EntityType == EntityType.Contact ||
  155. customField.EntityType == EntityType.Company && isCompany ||
  156. customField.EntityType == EntityType.Person && !isCompany)) continue;
  157. if (customField.FieldType == CustomFieldType.CheckBox)
  158. {
  159. fieldValue = fieldValue == "on" || fieldValue == "true" ? "true" : "false";
  160. }
  161. fieldCollector.Add(customField.Label, fieldValue);
  162. Global.DaoFactory.GetCustomFieldDao().SetFieldValue(isCompany ? EntityType.Company : EntityType.Person, contact.ID, fieldID, fieldValue);
  163. }
  164. else if (key.StartsWith("contactInfo_"))
  165. {
  166. var nameParts = key.Split(new[] {'_'}).Skip(1).ToList();
  167. var contactInfoType = (ContactInfoType)Enum.Parse(typeof(ContactInfoType), nameParts[0]);
  168. var category = Convert.ToInt32(nameParts[1]);
  169. bool categoryIsExists = Enum.GetValues(ContactInfo.GetCategory(contactInfoType)).Cast<object>()
  170. .Any(categoryEnum => (int)categoryEnum == category);
  171. if (!categoryIsExists)
  172. throw new ArgumentException(String.Format("Category for {0} not found", nameParts[0]));
  173. if (contactInfoType == ContactInfoType.Address)
  174. {
  175. var addressPart = (AddressPart)Enum.Parse(typeof(AddressPart), nameParts[2]);
  176. var findedAddress = contactInfos.Find(item => (category == item.Category) && (item.InfoType == ContactInfoType.Address));
  177. if (findedAddress == null)
  178. {
  179. findedAddress = new ContactInfo
  180. {
  181. Category = category,
  182. InfoType = contactInfoType,
  183. Data = addressTemplateStr,
  184. ContactID = contact.ID
  185. };
  186. contactInfos.Add(findedAddress);
  187. }
  188. var addressParts = JObject.Parse(findedAddress.Data);
  189. addressParts[addressPart.ToString().ToLower()] = GetValue(key);
  190. findedAddress.Data = addressParts.ToString();
  191. continue;
  192. }
  193. var fieldValue = GetValue(key);
  194. if (String.IsNullOrEmpty(fieldValue)) continue;
  195. contactInfos.Add(new ContactInfo
  196. {
  197. Category = category,
  198. InfoType = contactInfoType,
  199. Data = fieldValue,
  200. ContactID = contact.ID,
  201. IsPrimary = true
  202. });
  203. }
  204. else if (String.Compare(key, "tag", true) == 0)
  205. {
  206. var tags = _context.Request.Form.GetValues("tag");
  207. Global.DaoFactory.GetTagDao().SetTagToEntity(EntityType.Contact, contact.ID, tags);
  208. }
  209. }
  210. contactInfos.ForEach(item => fieldCollector[item.InfoType.ToLocalizedString()] = PrepareteDataToView(item.InfoType, item.Data));
  211. Global.DaoFactory.GetContactInfoDao().SaveList(contactInfos);
  212. var notifyList = GetValue("notify_list");
  213. if (!String.IsNullOrEmpty(notifyList))
  214. NotifyClient.Instance.SendAboutCreateNewContact(
  215. notifyList
  216. .Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
  217. .Select(item => new Guid(item)).ToList(), contact.ID, contact.GetTitle(), fieldCollector);
  218. var managersList = GetValue("managers_list");
  219. SetPermission(contact, managersList);
  220. if (contact is Person && !String.IsNullOrEmpty(companyName))
  221. AssignPersonToCompany((Person)contact, companyName, managersList);
  222. if (contact is Company && !String.IsNullOrEmpty(firstName) && !String.IsNullOrEmpty(lastName))
  223. AssignCompanyToPerson((Company)contact, firstName, lastName, managersList);
  224. SecurityContext.Logout();
  225. var newURL = new UriBuilder(GetValue("return_url")).Uri.AbsoluteUri;
  226. context.Response.Buffer = true;
  227. context.Response.Status = "302 Object moved";
  228. context.Response.AddHeader("Location", newURL);
  229. context.Response.Write("<HTML><Head>");
  230. context.Response.Write(String.Format("<META HTTP-EQUIV=Refresh CONTENT=\"0;URL={0}\">", newURL));
  231. context.Response.Write(String.Format("<Script>window.location='{0}';</Script>", newURL));
  232. context.Response.Write("</Head>");
  233. context.Response.Write("</HTML>");
  234. }
  235. catch(Exception error)
  236. {
  237. LogManager.GetLogger("ASC.CRM").Error(error);
  238. context.Response.StatusCode = 400;
  239. context.Response.Write(HttpUtility.HtmlEncode(error.Message));
  240. }
  241. }
  242. private String PrepareteDataToView(ContactInfoType contactInfoType, String data)
  243. {
  244. if (contactInfoType != ContactInfoType.Address) return data;
  245. var addressParts = JObject.Parse(data);
  246. var address = new StringBuilder();
  247. foreach (AddressPart addressPartEnum in Enum.GetValues(typeof(AddressPart)))
  248. address.Append(addressParts[addressPartEnum.ToString().ToLower()] + " ");
  249. return address.ToString();
  250. }
  251. public bool IsReusable
  252. {
  253. get { return false; }
  254. }
  255. protected void SetPermission(Contact contact, String privateList)
  256. {
  257. if (String.IsNullOrEmpty(privateList)) return;
  258. var selectedUsers = privateList
  259. .Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
  260. .Select(item => new Guid(item)).ToList();
  261. CRMSecurity.SetAccessTo(contact, selectedUsers);
  262. }
  263. protected void AssignCompanyToPerson(Company company, String firstName, String lastName, String privateList)
  264. {
  265. var person = new Person
  266. {
  267. FirstName = firstName,
  268. LastName = lastName,
  269. CompanyID = company.ID
  270. };
  271. person.ID = Global.DaoFactory.GetContactDao().SaveContact(person);
  272. SetPermission(person, privateList);
  273. }
  274. protected void AssignPersonToCompany(Person person, String companyName, String privateList)
  275. {
  276. Company company;
  277. var findedCompanies = Global.DaoFactory.GetContactDao().GetContactsByName(companyName)
  278. .Where(item => item is Company).ToList();
  279. if (findedCompanies.Count == 0)
  280. {
  281. company = new Company
  282. {
  283. CompanyName = companyName
  284. };
  285. company.ID = Global.DaoFactory.GetContactDao().SaveContact(company);
  286. SetPermission(company, privateList);
  287. }
  288. else
  289. {
  290. company = (Company)findedCompanies[0];
  291. }
  292. Global.DaoFactory.GetContactDao().AddMember(person.ID, company.ID);
  293. }
  294. }
  295. }