Advertisement
Guest User

Untitled

a guest
Jul 26th, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.58 KB | None | 0 0
  1. private $id;
  2. private $username;
  3. private $email;
  4. private $firstName;
  5. private $lastName;
  6. private $uniqueURLId;
  7. private $password;
  8. private $mostRecentProject;
  9. private $previousProject;
  10. private $lastProject;
  11.  
  12. private $date;
  13.  
  14. /**
  15. * User_test constructor.
  16. * @param $user
  17. */
  18. public function __construct($user)
  19. {
  20. $this->id = $user['USR_UserId']; //required
  21. $this->username = $user['USR_Username']; //required
  22. $this->email = $user['USR_Email']; //required
  23. $this->firstName = $user['USR_FirstName']; //required
  24. $this->lastName = $user['USR_LastName']; //required
  25. $this->uniqueURLId = $user['USR_UniqueURLId'];
  26. $this->password = $user['USR_Password']; //required
  27. $this->mostRecentProject = $user['USR_ProjectMostRecent'];
  28. $this->previousProject = $user['USR_ProjectPrevious'];
  29. $this->lastProject = $user['USR_ProjectLast'];
  30. }
  31.  
  32. /**
  33. * checkURLId
  34. * Checks if UniqueURLId is null and sets it if it is.
  35. *
  36. * @param int $projectId Integer ID referencing specific project to be concatenated onto the URLId
  37. */
  38. private function checkURLId($projectId) {
  39. if(is_null($this->uniqueURLId)) {
  40. $db = new DBManager();
  41. $this->uniqueURLId = RandomObjectGeneration::random_str(15) . $projectId;
  42. $sql = "UPDATE gaig_users.users SET USR_UniqueURLId=? WHERE USR_UserId=?;";
  43. $bindings = array($this->uniqueURLId,$this->id);
  44. $db->query($sql,$bindings);
  45. }
  46. }
  47.  
  48. /**
  49. * pushUser
  50. * Pushes $this onto the provided array if it is valid.
  51. *
  52. * @param array $validUsers Array of User_test objects
  53. * @param int $periodInWeeks Period to check in validation of user
  54. * @param TemplateConfiguration $templateConfig Template Configuration for validation
  55. */
  56. public function pushUser($validUsers, $periodInWeeks, TemplateConfiguration $templateConfig) {
  57. try {
  58. $this->checkURLId($templateConfig->getProjectId());
  59. if($this->isValid($periodInWeeks,$templateConfig)) {
  60. $validUsers[] = $this;
  61. }
  62. } catch(Exception $e) {
  63.  
  64. }
  65. }
  66.  
  67. /**
  68. * isValid
  69. * Verifies the user is valid according to the verification algorithm defined in the check... functions.
  70. *
  71. * @param int $periodInWeeks Period to check in validation of user
  72. * @param TemplateConfiguration $templateConfig Template Configuration for validation
  73. * @return bool
  74. */
  75. private function isValid($periodInWeeks, TemplateConfiguration $templateConfig) {
  76. try {
  77. $db = new DBManager();
  78. $sql = "
  79. SELECT MAX(SML_SentTimestamp) AS 'timestamp_check'
  80. FROM gaig_users.sent_email
  81. WHERE SML_UserId = ? AND SML_ProjectName = ?;";
  82. $bindings = array($this->id,$this->mostRecentProject);
  83. $data = $db->query($sql,$bindings);
  84. if($data->rowCount() > 0) {
  85. $result = $data->fetch();
  86. $this->date = date('Y-m-d',strtotime('-' . $periodInWeeks . ' weeks')) . ' 00:00:00';
  87. if($this->checkPeriod($this->date,$result['timestamp_check'])) {
  88. return true;
  89. }
  90. $sql = "SELECT * FROM gaig_users.projects WHERE PRJ_ProjectId = ?;";
  91. $data = $db->query($sql,array($this->mostRecentProject));
  92. $mostRecentProj = new Project($data->fetch());
  93. $newComplexity = $templateConfig->getTemplateComplexityType();
  94. $newTarget = $templateConfig->getTemplateTargetType();
  95. if($this->checkMRP($mostRecentProj,$newComplexity,$newTarget)) {
  96. return false;
  97. }
  98. $data = $db->query($sql,array($this->previousProject));
  99. $previousProj = new Project($data->fetch());
  100. if($this->checkPP($mostRecentProj,$previousProj,$newComplexity)) {
  101. return false;
  102. }
  103. $data = $db->query($sql,array($this->lastProject));
  104. $lastProj = new Project($data->fetch());
  105. if($this->checkLP($mostRecentProj,$previousProj,$lastProj,$newTarget)) {
  106. return false;
  107. }
  108. }
  109. return true;
  110. } catch(Exception $e) {
  111. //unsure how to manage any exceptions thrown yet, if at all. further design to come
  112. }
  113. }
  114.  
  115. /**
  116. * checkPeriod - Verification Algorithm
  117. * Verifies if the period is outside of periodInWeeks zone.
  118. *
  119. * @param string $date Date in format 'Y-m-d h:i:s'
  120. * @param string $timestamp Date retrieved from PDOStatement
  121. * @return bool
  122. */
  123. private function checkPeriod($date,$timestamp) {
  124. return $timestamp <= $date;
  125. }
  126.  
  127. /**
  128. * checkMRP - Verification Algorithm
  129. * Checks the Most Recent Project to see if identical.
  130. *
  131. * @param Project $mrp Project object representing the Most Recent Project
  132. * @param string $complexity Complexity type of requested template
  133. * @param string $target Target type of requested template
  134. * @return bool
  135. */
  136. private function checkMRP(Project $mrp, $complexity, $target) {
  137. return $complexity == $mrp->getTemplateComplexityType() &&
  138. $target == $mrp->getTemplateTargetType();
  139. }
  140.  
  141. /**
  142. * checkPP - Verification Algorithm
  143. * Checks the Previous Project and Most Recent Project for identical complexity type.
  144. *
  145. * @param Project $mrp Project object representing the Most Recent Project
  146. * @param Project $pp Project object representing the Previous Project
  147. * @param string $complexity Complexity type of requested template
  148. * @return bool
  149. */
  150. private function checkPP(Project $mrp, Project $pp, $complexity) {
  151. return !is_null($pp) &&
  152. $complexity == $mrp->getTemplateComplexityType() &&
  153. $complexity == $pp->getTemplateComplexityType();
  154. }
  155.  
  156. /**
  157. * checkLP - Verification Algorithm
  158. * Checks the Last Project, Previous Project, and Most Recent Project for identical target type.
  159. *
  160. * @param Project $mrp Project object representing the Most Recent Project
  161. * @param Project $pp Project object representing the Previous Project
  162. * @param Project $lp Project object representing the Last Project
  163. * @param string $target Target type of requested template
  164. * @return bool
  165. */
  166. private function checkLP(Project $mrp, Project $pp, Project $lp, $target) {
  167. return !is_null($lp) &&
  168. !is_null($pp) &&
  169. $target == $mrp->getTemplateTargetType() &&
  170. $target == $pp->getTemplateTargetType() &&
  171. $target == $lp->getTemplateTargetType();
  172. }
  173.  
  174. public function getLastName() {
  175. return $this->lastName;
  176. }
  177.  
  178. public function getUsername() {
  179. return $this->username;
  180. }
  181.  
  182. public function getUniqueURLId() {
  183. return $this->uniqueURLId;
  184. }
  185.  
  186. public function getEmail() {
  187. return $this->email;
  188. }
  189.  
  190. /**
  191. * getValidUsers
  192. * Retrieves all users from the database and validates them through the User_test object.
  193. *
  194. * @param array $returnUsers Array of User_test objects
  195. * @param int $periodInWeeks Period to check for instant sending of email
  196. * @return array
  197. */
  198. public function getValidUsers($returnUsers, $periodInWeeks) {
  199. $db = new DBManager();
  200. $sql = "SELECT * FROM gaig_users.users;";
  201. $users = $db->query($sql,array(),array('PDO::ATTR_CURSOR'),array('PDO::CURSOR_SCROLL'));
  202. $usersIterator = new PDOIterator($users);
  203. foreach($usersIterator as $user) {
  204. $tempUser = new User_Test($user);
  205. $tempUser->pushUser($returnUsers,$periodInWeeks,$this);
  206. }
  207. return $returnUsers;
  208. }
  209.  
  210. /**
  211. * sendEmail
  212. * Function mapped to Laravel route. Defines variable arrays and calls Email Class executeEmail.
  213. *
  214. * @param Request $request Request object passed via AJAX from client.
  215. */
  216. public function sendEmail(Request $request) {
  217. try {
  218. $templateConfig = new TemplateConfiguration(
  219. array(
  220. 'templateName'=>$request->input('emailTemplate'),
  221. 'companyName'=>$request->input('companyName'),
  222. 'projectName'=>$request->input('projectData')['projectName'],
  223. 'projectId'=>intval($request->input('projectData')['projectId'])
  224. )
  225. );
  226.  
  227. $periodInWeeks = 4;
  228. $users = array();
  229. $emailConfig = new EmailConfiguration(
  230. array(
  231. 'host'=>$request->input('hostName'),
  232. 'port'=>$request->input('port'),
  233. 'authUsername'=>$request->input('username'),
  234. 'authPassword'=>$request->input('password'),
  235. 'fromEmail'=>$request->input('fromEmail'),
  236. 'subject'=>$request->input('subject'),
  237. 'users'=>$templateConfig->getValidUsers($users,$periodInWeeks)
  238. )
  239. );
  240.  
  241. Email::executeEmail($emailConfig,$templateConfig);
  242. } catch(ConfigurationException $ce) {
  243. //will be doing something here - what still has yet to be defined (likely just log the exception)
  244. } catch(EmailException $ee) {
  245. //will be doing something here - what still has yet to be defined (likely just log the exception)
  246. }
  247. }
  248.  
  249. private static $templateConfig;
  250. private static $emailConfig;
  251.  
  252. /**
  253. * executeEmail
  254. * Public-facing method to send an email to a database of users if they are a valid recipient.
  255. *
  256. * @param EmailConfiguration $emailConfig Email Configuration object containing required information to send an email
  257. * @param TemplateConfiguration $templateConfig Template Configuration object containing required information to build a template
  258. * @throws EmailException Custom Exception to embody any exceptions thrown in this class
  259. */
  260. public static function executeEmail(
  261. EmailConfiguration $emailConfig,
  262. TemplateConfiguration $templateConfig)
  263. {
  264. self::setTemplateConfig($templateConfig);
  265. self::setEmailConfig($emailConfig);
  266.  
  267. try {
  268. foreach($emailConfig->getUsers() as $user) {
  269. self::sendEmail($user);
  270. self::updateUserProjects($user);
  271. }
  272. } catch(Exception $e) {
  273. throw new EmailException(__CLASS__ . ' Exception',0,$e);
  274. }
  275. }
  276.  
  277. /**
  278. * updateUserProjects
  279. * Updates the user with the newest project and rotates the old projects down one.
  280. *
  281. * @param array $user User array extracted from PDOStatement
  282. */
  283. private function updateUserProjects($user) {
  284. $db = new DBManager();
  285. $sql = "UPDATE gaig_users.users SET USR_ProjectMostRecent=?, USR_ProjectPrevious=?,
  286. USR_ProjectLast=? WHERE USR_Username=?;";
  287. $bindings = array(self::$templateConfig->getProjectName(),
  288. $user['USR_ProjectMostRecent'],
  289. $user['USR_ProjectPrevious'],
  290. $user['USR_Username']
  291. );
  292. $db->query($sql,$bindings);
  293. }
  294.  
  295. /**
  296. * sendEmail
  297. * Sends them an email to the specified user.
  298. *
  299. * @param User_test $user User object
  300. * @throws FailureException
  301. */
  302. private static function sendEmail($user) {
  303. $templateData = array(
  304. 'companyName'=>self::$templateConfig->getCompanyName(),
  305. 'projectName'=>self::$templateConfig->getProjectName(),
  306. 'projectId'=>self::$templateConfig->getProjectId(),
  307. 'lastName'=>$user->getLastName(),
  308. 'username'=>$user->getUsername(),
  309. 'urlId'=>$user->getUniqueURLId()
  310. );
  311. $subject = self::$emailConfig->getSubject();
  312. $from = self::$emailConfig->getFromEmail();
  313. $to = $user->getEmail();
  314. $mailResult = Mail::send(
  315. ['html' => self::$templateConfig->getTemplate()],
  316. $templateData,
  317. function($m) use ($from, $to, $subject) {
  318. $m->from($from);
  319. $m->to($to)
  320. ->subject($subject);
  321. }
  322. );
  323. if(!$mailResult) {
  324. throw new FailureException('Email failed to send to ' . $to . ', from ' . $from);
  325. }
  326. }
  327.  
  328. private static function setTemplateConfig(TemplateConfiguration $templateConfig) {
  329. self::$templateConfig = $templateConfig;
  330. }
  331.  
  332. private static function setEmailConfig(EmailConfiguration $emailConfig) {
  333. self::$emailConfig = $emailConfig;
  334. }
  335.  
  336. class RandomObjectGeneration
  337. {
  338. /**
  339. * random_str
  340. * Generates a random string.
  341. *
  342. * @param int $length Length of string to be returned
  343. * @param string $keyspace Allowed characters to be used in string
  344. * @return string
  345. */
  346. public static function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
  347. {
  348. if(is_null($length) || !is_numeric($length)) {
  349. throw new Exception();
  350. }
  351. $str = '';
  352. $max = mb_strlen($keyspace) - 1;
  353. for ($i = 0; $i < $length; ++$i) {
  354. $str .= $keyspace[random_int(0, $max)];
  355. }
  356. return $str;
  357. }
  358. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement