Advertisement
Guest User

Untitled

a guest
Jul 13th, 2016
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.05 KB | None | 0 0
  1. /**
  2. * sendEmail
  3. * Function mapped to Laravel route. Defines variable arrays and calls Email Class executeEmail.
  4. *
  5. * @param Request $request Request object passed via AJAX from client.
  6. */
  7. public function sendEmail(Request $request) {
  8. $fromEmail = $request['fromEmail'];
  9. $fromPass = $request['fromPass'];
  10. $host = $request['hostName'];
  11. $port = $request['port'];
  12. $emailSettings = array($host,$port,$fromEmail,$fromPass);
  13.  
  14. $emailTemplate = 'emails.' . $request['emailTemplate'];
  15. $emailTemplateType = substr($request['emailTemplate'],0,3);
  16. $emailTemplateTarget = substr($request['emailTemplate'],3,1);
  17. $template = array($emailTemplate,$emailTemplateType,$emailTemplateTarget);
  18.  
  19. $period = 4;
  20. $subject = $request['subject'];
  21. $projectName = $request['projectName'];
  22. $projectId = intval($projectName,strpos($projectName,'_'));
  23. $projectName = substr($projectName,0,strpos($projectName,'_')-1);
  24. $companyName = $request['companyName'];
  25. $params = array($period,$projectName,$projectId,$companyName,$subject);
  26.  
  27. try {
  28. Email::executeEmail($emailSettings,$template,$params);
  29. } catch(OutOfBoundsException $oobe) {
  30. //mail server settings not valid
  31. } catch(FailureException $fee) {
  32. //email failed to be sent to server
  33. } catch(PDOException $pdoe) {
  34. DBManager::logConnectError(__CLASS__,__FUNCTION__,$pdoe->getMessage(),$pdoe->getTrace());
  35. } catch(QueryException $qe) {
  36. DBManager::logQueryError(__CLASS__,__FUNCTION__,$qe);
  37. }
  38. }
  39.  
  40. /**
  41. * executeEmail
  42. * Public-facing method to send an email to a database of users if they are a valid recipient.
  43. *
  44. * @param array $emailSettings Host, port, username, and password variables for the mail server
  45. * @param array $template Email Template, Template Type, Template Target Type for user validation
  46. * string Email Template Path to the blade.php template file from the views directory
  47. * string Template Type Specifies whether the email is an Advanced (adv) or Basic (bsc) scam
  48. * string Template Target Type Specifies whether the email is a Targeted (T) or Generic (G) scam
  49. * @param array $params Period, Project Name, Project ID, From Email Address, Company Name, Subject
  50. * int Period Number of weeks to check back for recipient validation
  51. * string Project Name Name of this project
  52. * int Project Id ID of this project
  53. * string From Email Address Email to be sent from
  54. * string Company Name Name of company sponsoring this awareness test
  55. * string Subject Subject of email
  56. * @throws OutOfBoundsException Thrown from setEmailEnvironmentSettings if a setting is not valid
  57. * @throws FailureException Thrown from sendEmail() if mail fails to be given to mail server
  58. * @throws PDOException Thrown from DBManager->query()
  59. * @throws QueryException Thrown from DBManager->query()
  60. */
  61. public static function executeEmail($emailSettings, $template, $params) {
  62. self::setEmailEnvironmentSettings($emailSettings);
  63. $db = new DBManager();
  64. $sql = "SELECT * FROM gaig_users.users;";
  65. $users = $db->query($sql,array(),array('PDO::ATTR_CURSOR'),array('PDO::CURSOR_SCROLL'));
  66. $userIterator = new PDOIterator($users);
  67. foreach($userIterator as $user) {
  68. if(self::validateUser($template[1],$template[2],$user,$params[0])) {
  69. $to = $user['USR_Email'];
  70. $urlId = self::getUrlId($user);
  71. $companyName = $params[3];
  72. $subject = $params[4];
  73. if(is_null($params[3])) {
  74. $companyName = 'your organization';
  75. }
  76. if(is_null($params[4])) {
  77. $subject = 'Corporate Communication';
  78. }
  79. $headers = array('companyName'=>$companyName,'projectName'=>$params[1],'projectId'=>$params[2],
  80. 'lastName'=>$user['USR_LastName'],'username'=>$user['USR_Username'],'urlId'=>$urlId);
  81. self::sendEmail($template[0],$headers,$to,getenv('MAIL_USERNAME'),$subject);
  82. $project_new = $params[6] . '-' . $params[4];
  83. $projects = array($project_new,$user['USR_ProjectMostRecent'],$user['USR_ProjectPrevious']);
  84. self::updateUserProjects($projects,$user);
  85. }
  86. }
  87. }
  88.  
  89. /**
  90. * setEmailEnvironmentSettings
  91. * Checks if the settings are valid settings, then sets or returns an exception.
  92. *
  93. * @param array $emailSettings Host, port, username, and password variables for the mail server
  94. * @throws OutOfBoundsException
  95. */
  96. private function setEmailEnvironmentSettings($emailSettings) {
  97. $pattern = ';(?:https?://)?(?:[a-zA-Z0-9.-]+?.(?:com|net|org|gov|edu|mil)|d+.d+.d+.d+);';
  98. if(!preg_match($pattern,$emailSettings[0]) || !filter_var($emailSettings[1],FILTER_VALIDATE_INT) ||
  99. !filter_var($emailSettings[2],FILTER_VALIDATE_EMAIL)) {
  100. $message = '';
  101. if(!preg_match($pattern,$emailSettings[0])) {
  102. $message .= 'Host is not a valid host name or IP address. host=' . $emailSettings[0] . 'n';
  103. }
  104. if(!filter_var($emailSettings[1],FILTER_VALIDATE_INT)) {
  105. $message .= 'Port is not a valid integer. port=' . $emailSettings[1] . 'n';
  106. }
  107. if(!filter_var($emailSettings[2],FILTER_VALIDATE_EMAIL)) {
  108. $message .= 'Username is not a valid email address. username=' . $emailSettings[2] . 'n';
  109. }
  110. throw new OutOfBoundsException($message);
  111. }
  112. putenv("MAIL_HOST=$emailSettings[0]");
  113. putenv("MAIL_PORT=$emailSettings[1]");
  114. putenv("MAIL_USERNAME=$emailSettings[2]");
  115. putenv("MAIL_PASSWORD=$emailSettings[3]");
  116. }
  117.  
  118. /**
  119. * validateUser
  120. * Function checks if the specified user has not received a test within the specified duration,
  121. * if the template type is the same for the last two project participants, if the template target
  122. * is the same for last three project participants, or if the last project is identical to the new project.
  123. *
  124. * @param string $templateType Specifies whether the email is an Advanced (adv) or Basic (bsc) scam
  125. * @param string $templateTarget Specifies whether the email is a Targeted (T) or Generic (G) scam
  126. * @param array $user Associative Array containing the fields associated to the user
  127. * @param int $period Number of weeks to check back for recipient validation
  128. * @return bool
  129. */
  130. private function validateUser($templateType,$templateTarget,$user,$period) {
  131. $db = new DBManager();
  132. $date = date('Y-m-d',strtotime('-' . $period . 'weeks')) . '00:00:00';
  133. $sql = "SELECT max(SML_AccessTimestamp) as 'timestamp_check' from gaig_users.sent_email where SML_UserId = ? and SML_ProjectName = ?;";
  134. $bindings = array($user['USR_UserId'],$user['USR_ProjectMostRecent']);
  135. $timestampData = $db->query($sql,$bindings);
  136. $result = $timestampData->fetch(PDO::FETCH_ASSOC);
  137. if(!filter_var($user['USR_Email'],FILTER_VALIDATE_EMAIL)) {
  138. $this->badEmailAddressWarning(['USR_Username'] . ' has a bad email address. email=' . $user['USR_Email']);
  139. return false;
  140. }
  141. if($result['timestamp_check'] <= $date) {
  142. return true;
  143. } else if($templateType == substr($user['USR_ProjectMostRecent'],-5,3) &&
  144. $templateType == substr($user['USR_ProjectPrevious'],-5,3)) {
  145. return false;
  146. } else if($templateTarget == substr($user['USR_ProjectMostRecent'],-2,1) &&
  147. $templateTarget == substr($user['USR_ProjectPrevious'],-2,1) &&
  148. $templateTarget == substr($user['USR_ProjectLast'],-2,1)) {
  149. return false;
  150. } else if($templateType.$templateTarget ==
  151. substr($user['USR_ProjectMostRecent'],strpos($user['USR_ProjectMostRecent'],'-')+1,4)) {
  152. return false;
  153. }
  154. return true;
  155. }
  156.  
  157. /**
  158. * getUrlId
  159. * Generates or retrieves the UniqueURLId of the passed user.
  160. *
  161. * @param array $user User array extracted from PDOStatement
  162. * @return string
  163. */
  164. private function getUrlId($user) {
  165. $db = new DBManager();
  166. if(!is_null($user['USR_UniqueURLId'])) {
  167. $urlId = $user['USR_UniqueURLId'];
  168. } else {
  169. $urlId = $this->random_str(15);
  170. $sql = "UPDATE gaig_users.users SET USR_UniqueURLId=?;";
  171. $bindings = array($urlId);
  172. $db->query($sql,$bindings);
  173. }
  174. return $urlId;
  175. }
  176.  
  177. /**
  178. * updateUserProjects
  179. * Updates the user with the newest project and rotates the old projects down one.
  180. *
  181. * @param array $projects Most Recent Project, Previous Project, Oldest Project
  182. * @param array $user User array extracted from PDOStatement
  183. */
  184. private function updateUserProjects($projects,$user) {
  185. $db = new DBManager();
  186. $sql = "UPDATE gaig_users.users SET USR_ProjectMostRecent=?, USR_ProjectPrevious=?,
  187. USR_ProjectLast=? WHERE USR_Username=?;";
  188. $bindings = array($projects[0],$projects[1],$projects[2],$user['USR_Username']);
  189. $db->query($sql,$bindings);
  190. }
  191.  
  192. /**
  193. * sendEmail
  194. * Iterates through the PDO Result Set of users. Calls validRecipientAlgo to validate user. Sends email if
  195. * valid and updates user if valid.
  196. * @param array $params Required parameters to pass to the email template
  197. * @param string $from Email to be sent from
  198. * @param string $subject Subject of email
  199. * @throws FatalErrorException
  200. */
  201. private function sendEmail($template, $headers, $to, $from, $subject) {
  202. if(!Mail::send(['html' => $template],$headers, function($m) use ($from, $to, $subject) {
  203. $m->from($from);
  204. $m->to($to)->subject($subject);
  205. })) {
  206. throw new FailureException('Email failed to send to ' . $to . ' from ' . $from);
  207. }
  208. }
  209.  
  210. /**
  211. * random_str
  212. * Generates a random string.
  213. *
  214. * @param int $length Length of string to be returned
  215. * @param string $keyspace Allowed characters to be used in string
  216. * @return string
  217. */
  218. private function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
  219. {
  220. $str = '';
  221. $max = mb_strlen($keyspace, '8bit') - 1;
  222. for ($i = 0; $i < $length; ++$i) {
  223. $str .= $keyspace[random_int(0, $max)];
  224. }
  225. return $str;
  226. }
  227.  
  228. /**
  229. * badEmailAddressWarning
  230. * Logs error when a bad email address is found associated with a user
  231. *
  232. * @param string $message Error message to be logged
  233. */
  234. private function badEmailAddressWarning($message) {
  235. $path = '../storage/logs/badEmailAddress' . date('m-d-Y') . '.log';
  236. if(!file_exists($path)) {
  237. $file = fopen($path,'w');
  238. fclose($file);
  239. }
  240. error_log($message,3,$path);
  241. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement