user.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. <?php
  2. /**
  3. * Class User
  4. *
  5. * @property int $id
  6. * @property string $email
  7. * @property int $old_id
  8. * @property int $referrer_id
  9. * @property string $password
  10. * @property bool $activated
  11. * @property int $level
  12. * @property int $score
  13. * @property string $title
  14. * @property string $first_name
  15. * @property string $last_name
  16. * @property string $gender
  17. * @property string $date_of_birth
  18. * @property string $locale
  19. * @property bool $reported
  20. * @property string $reported_comment
  21. * @property bool $can_claim
  22. * @property string $phone
  23. * @property string $verify_token
  24. * @property string $reset_token
  25. * @property bool $terms_accepted
  26. * @property bool $newsletter_consent
  27. * @property int $preferred_payment_method
  28. * @property string $bank_name
  29. * @property string $bank_sort_code
  30. * @property string $bank_account_number
  31. * @property string $paypal_email
  32. * @property string $dts_registered
  33. * @property string $dts_last_seen
  34. * @property string $dts_verified
  35. * @property string $dts_deleted
  36. * @property int $verifier_id
  37. * @property string $verifier_notes
  38. */
  39. class User extends Model {
  40. protected static $table = "user";
  41. protected static $id_field = "id";
  42. protected static $fillable_fields = ["email", "old_id", "referrer_id", "password", "activated", "level", "score", "title", "first_name", "last_name", "gender", "date_of_birth", "locale", "reported", "reported_comment", "can_claim", "phone", "verify_token", "reset_token", "terms_accepted", "newsletter_consent", "preferred_payment_method", "bank_name", "bank_sort_code", "bank_account_number", "paypal_email", "dts_registered", "dts_last_seen", "dts_verified", "dts_deleted", "verifier_id", "verifier_notes"];
  43. // Constants
  44. const LEVEL_BANNED = 0;
  45. const LEVEL_REGISTERED = 1;
  46. const LEVEL_UNVERIFIED = 2;
  47. const LEVEL_DEACTIVATED = 4;
  48. const LEVEL_TESTER = 8;
  49. const LEVEL_VENUE = 16;
  50. const LEVEL_CUSTOMER = 32;
  51. const LEVEL_TESTER_MANAGER = 48;
  52. const LEVEL_ADMIN = 64;
  53. const LEVEL_SUPERADMIN = 128;
  54. const LEVELS = [
  55. 0 => "Banned",
  56. 1 => "Registered",
  57. 2 => "Unverified",
  58. 4 => "Deactivated",
  59. 8 => "Tester",
  60. 16 => "Venue",
  61. 32 => "Customer",
  62. 48 => "Tester Manager",
  63. 64 => "Admin",
  64. 128 => "Super Admin",
  65. ];
  66. const PAYMENT_METHOD_BANK_TRANSFER = 1;
  67. const PAYMENT_METHOD_PAYPAL = 2;
  68. const PAYMENT_METHODS = [
  69. 1 => "Bank Transfer",
  70. 2 => "PayPal",
  71. ];
  72. // Static methods
  73. /**
  74. * @return array
  75. */
  76. public static function titles(): array {
  77. return [
  78. "Miss" => MISS,
  79. "Mr" => MR,
  80. "Ms" => MS,
  81. "Dr" => DR
  82. ];
  83. }
  84. /**
  85. * @return array
  86. */
  87. public static function genders(): array {
  88. return [
  89. "Female" => FEMALE,
  90. "Male" => MALE,
  91. "Unspecified" => UNSPECIFIED
  92. ];
  93. }
  94. /**
  95. * @param string $password
  96. * @return bool
  97. */
  98. public static function validatePassword(string $password): bool {
  99. $lowercase = preg_match("/[a-z]/", $password);
  100. $uppercase = preg_match("/[A-Z]/", $password);
  101. $number = preg_match("/[0-9]/", $password);
  102. $special = preg_match("/[^0-9a-zA-Z]/", $password);
  103. $length = strlen($password) >= 6;
  104. return ($lowercase && $uppercase && $number && $special && $length);
  105. }
  106. // Object methods
  107. /**
  108. * @return bool
  109. */
  110. public function hasValidPaymentMethod(): bool {
  111. switch($this->preferred_payment_method) {
  112. case User::PAYMENT_METHOD_BANK_TRANSFER: {
  113. if(empty($this->bank_name)) return false;
  114. if(empty($this->bank_sort_code)) return false;
  115. if(empty($this->bank_account_number)) return false;
  116. break;
  117. }
  118. case User::PAYMENT_METHOD_PAYPAL: {
  119. if(empty($this->paypal_email)) return false;
  120. break;
  121. }
  122. }
  123. return true;
  124. }
  125. /**
  126. * @return bool
  127. * @throws Exception
  128. */
  129. public function sendActivationEmail() {
  130. $this->verify_token = bin2hex(random_bytes(16));
  131. $this->commit();
  132. // Content
  133. $name = htmlspecialchars($this->first_name);
  134. $link = htmlspecialchars(PROTOCOL . "://" . DOMAIN . "/verify-email/" . $this->verify_token);
  135. // Build
  136. $builder = new EmailBuilder;
  137. $builder->addParagraph("<b>" . sprintf(__("Hi %s"), $name) . "</b>");
  138. $builder->addLeadParagraph(__("Thanks for registering!"));
  139. $builder->addParagraph(sprintf(__("Welcome to %s! Before you can log in, you will need to verify your email address. You can do so by tapping the following link:"), APP_NAME));
  140. $builder->addParagraph("<a href=\"$link\">$link</a>");
  141. $content = $builder->build();
  142. // Send
  143. $mail = new Email;
  144. $mail->setHtmlContent($content);
  145. $mail->setFrom(EMAIL_NO_REPLY, EMAIL_FROM_NAME);
  146. $mail->addAddress($this->email, $this->getDisplayName());
  147. $mail->setSubject(__("Verify your email address"));
  148. $mail->send();
  149. return true;
  150. }
  151. /**
  152. * @return bool
  153. * @throws Exception
  154. */
  155. public function sendWelcomeEmail() {
  156. // Content
  157. $name = htmlspecialchars($this->first_name);
  158. $link = htmlspecialchars(PROTOCOL . "://" . DOMAIN . "/account/submit-id");
  159. // Build
  160. $builder = new EmailBuilder;
  161. $builder->addParagraph("<b>" . sprintf(__("Hi %s"), $name) . "</b>");
  162. $builder->addLeadParagraph(__("Thanks for verifying your email address!"));
  163. $builder->addParagraph(sprintf(__("Welcome to %s! Before you can take part in tests, you will need to provide us with some ID. You can do so by tapping the following link:"), APP_NAME));
  164. $builder->addParagraph("<a href=\"$link\">$link</a>");
  165. $content = $builder->build();
  166. // Send
  167. $mail = new Email;
  168. $mail->setHtmlContent($content);
  169. $mail->setFrom(EMAIL_NO_REPLY, EMAIL_FROM_NAME);
  170. $mail->addAddress($this->email, $this->getDisplayName());
  171. $mail->setSubject(sprintf(__("Welcome to %s"), APP_NAME));
  172. $mail->send();
  173. return true;
  174. }
  175. /**
  176. * @return bool
  177. * @throws Exception
  178. */
  179. public function sendIDPassEmail() {
  180. // Content
  181. $name = htmlspecialchars($this->first_name);
  182. // Build
  183. $builder = new EmailBuilder;
  184. $builder->addParagraph("<b>" . sprintf(__("Hi %s"), $name) . "</b>");
  185. $builder->addLeadParagraph(__("Your application has been successful!"));
  186. $builder->addParagraph(sprintf(__("Welcome to %s! In order to get you a test as soon as possible, we need one final confirmation. Please log in to your account and have a quick read of the documents that explain what we need you to do during a test."), APP_NAME));
  187. $builder->addParagraph(__("When you're ready to try a Practice test, in your account and select the \"Practice\" option."));
  188. $builder->addParagraph(__("1. As it is a Practice test, you can reset and start over as many times as you like because it doesn't count but lets you see what the real thing is like."));
  189. $builder->addParagraph(sprintf(__("2. Email us at %s and let us know that you're ready."), "contact@" . DOMAIN));
  190. $builder->addParagraph(__("3. We will allocate a test to you as soon as possible."));
  191. $builder->addParagraph(__("Remember to check your online account for when tests become available."));
  192. $builder->addParagraph(__("Keep an eye out for emails inviting you to accept a test via the email or log in to your account where you can see your available tests."));
  193. $builder->addParagraph(__("If you accept to do a test within the agreed period (usually 7 days) please click Accept to confirm that you would like to do the test within the agreed period."));
  194. $builder->addParagraph(__("If you can't make it (it's too far or you'll be away), please Reject the test or email us with other suitable dates."));
  195. $builder->addParagraph(__("After you click Accept, you will be given the option to Begin the test whenever you want. Just log in to your account and click Begin on the test."));
  196. $builder->addParagraph(sprintf(__("Once again welcome to %s - Accept, Begin, Complete and get paid for up to 8 minutes work!"), APP_NAME));
  197. $content = $builder->build();
  198. // Send
  199. $mail = new Email;
  200. $mail->setHtmlContent($content);
  201. $mail->setFrom(EMAIL_NO_REPLY, EMAIL_FROM_NAME);
  202. $mail->addAddress($this->email, $this->getDisplayName());
  203. $mail->setSubject(__("ID accepted and verified"));
  204. $mail->send();
  205. return true;
  206. }
  207. /**
  208. * @param string $reason
  209. * @return bool
  210. * @throws Exception
  211. */
  212. public function sendIDFailEmail($reason = "No reason given.") {
  213. // Content
  214. $name = htmlspecialchars($this->first_name);
  215. $reason = htmlspecialchars($reason);
  216. // Build
  217. $builder = new EmailBuilder;
  218. $builder->addParagraph("<b>" . sprintf(__("Hi %s"), $name) . "</b>");
  219. $builder->addLeadParagraph(__("Thank you for submitting your ID details."));
  220. $builder->addParagraph(__("Unfortunately we could not verify and accept your documents and/or image."));
  221. $builder->addParagraph(sprintf(__("The reason for this is: %s"), $reason));
  222. $builder->addParagraph(__("Please log in again, resubmit and we will try again."));
  223. $builder->addParagraph(__("We look forward to welcoming you onboard soon!"));
  224. $content = $builder->build();
  225. // Send
  226. $mail = new Email;
  227. $mail->setHtmlContent($content);
  228. $mail->setFrom(EMAIL_NO_REPLY, EMAIL_FROM_NAME);
  229. $mail->addAddress($this->email, $this->getDisplayName());
  230. $mail->setSubject(__("We could not verify your ID details"));
  231. $mail->send();
  232. return true;
  233. }
  234. /**
  235. * @return bool
  236. * @throws Exception
  237. */
  238. public function sendPasswordResetEmail() {
  239. $this->reset_token = bin2hex(random_bytes(16));
  240. $this->commit();
  241. // Content
  242. $name = htmlspecialchars($this->first_name);
  243. $link = htmlspecialchars(PROTOCOL . "://" . DOMAIN . "/reset-password/" . $this->reset_token);
  244. // Build
  245. $builder = new EmailBuilder;
  246. $builder->addParagraph("<b>" . sprintf(__("Hi %s"), $name) . "</b>");
  247. $builder->addLeadParagraph(__("A reset password request has been received."));
  248. $builder->addParagraph(__("To reset your password, please tap on the following link:"));
  249. $builder->addParagraph("<a href=\"$link\">$link</a>");
  250. $builder->addParagraph(sprintf(__("If you %sdid not%s request for your password to be reset, please ignore this email."), '<strong>', '</strong>'));
  251. $content = $builder->build();
  252. // Send
  253. $mail = new Email;
  254. $mail->setHtmlContent($content);
  255. $mail->setFrom(EMAIL_NO_REPLY, EMAIL_FROM_NAME);
  256. $mail->addAddress($this->email, $this->getDisplayName());
  257. $mail->setSubject(__("Password reset instructions"));
  258. $mail->send();
  259. return true;
  260. }
  261. /**
  262. * @return bool
  263. */
  264. public function canAdmin() {
  265. return $this->level >= User::LEVEL_ADMIN;
  266. }
  267. /**
  268. * @return User|null
  269. * @throws Exception
  270. */
  271. public function getReferrer(): ?User {
  272. return is_null($this->referrer_id) ? null : User::get($this->referrer_id);
  273. }
  274. public function getDirectory() {
  275. $directory = ROOT_DIR . "/files/users/" . $this->id;
  276. if(!file_exists($directory)) mkdir($directory, 0777, true);
  277. return $directory;
  278. }
  279. public function getLevelText() {
  280. return User::LEVELS[$this->level];
  281. }
  282. public function getLevelClass() {
  283. switch($this->level) {
  284. case User::LEVEL_BANNED: return "danger";
  285. case User::LEVEL_REGISTERED: return "secondary";
  286. case User::LEVEL_UNVERIFIED: return "warning";
  287. case User::LEVEL_DEACTIVATED: return "secondary";
  288. case User::LEVEL_TESTER: return "success";
  289. case User::LEVEL_VENUE: return "info";
  290. case User::LEVEL_CUSTOMER: return "info";
  291. case User::LEVEL_ADMIN: return "info";
  292. case User::LEVEL_SUPERADMIN: return "info";
  293. default:
  294. return "primary";
  295. }
  296. }
  297. public function isAdmin() {
  298. return ($this->level == User::LEVEL_ADMIN || $this->level == User::LEVEL_SUPERADMIN);
  299. }
  300. public function isCustomer() {
  301. return $this->level == User::LEVEL_CUSTOMER;
  302. }
  303. public function isTester() {
  304. return $this->level == User::LEVEL_TESTER;
  305. }
  306. public function isDeactivated() {
  307. return $this->level == User::LEVEL_DEACTIVATED;
  308. }
  309. public function getGenderText() {
  310. if($this->gender == "M") return MALE;
  311. if($this->gender == "F") return FEMALE;
  312. return "Unspecified";
  313. }
  314. /**
  315. * @return int|string
  316. * @throws Exception
  317. */
  318. public function getAge() {
  319. if(is_null($this->date_of_birth)) return __("N/A");
  320. $now = new DateTime("now");
  321. $dob = new DateTime($this->date_of_birth);
  322. return $dob->diff($now)->y;
  323. }
  324. public function getDisplayName() {
  325. if(empty($this->email)) return __("Deleted User");
  326. $parts = array_filter([$this->first_name, $this->last_name]);
  327. return implode(" ", $parts);
  328. }
  329. /**
  330. * @param $object
  331. * @return bool
  332. * @throws Exception
  333. */
  334. public function hasPermission($object): bool {
  335. if($this->isAdmin()) return true;
  336. $customers = $this->getCustomers();
  337. $customer_ids = array_column($customers, "id");
  338. if($object instanceof Customer) {
  339. return in_array($object->id, $customer_ids);
  340. }
  341. if($object instanceof Location) {
  342. return in_array($object->customer_id, $customer_ids);
  343. }
  344. if($object instanceof Project) {
  345. return in_array($object->customer_id, $customer_ids);
  346. }
  347. if($object instanceof Template) {
  348. return in_array($object->customer_id, $customer_ids);
  349. }
  350. return false;
  351. }
  352. /**
  353. * @return bool
  354. * @throws Exception
  355. */
  356. public function deactivate() {
  357. // Decline all pending tests
  358. $pending_tests = $this->getPendingTests();
  359. foreach($pending_tests as $test) {
  360. $test->decline();
  361. }
  362. // Set user level to Deactivated
  363. $this->level = User::LEVEL_DEACTIVATED;
  364. return $this->commit();
  365. }
  366. /**
  367. * @return bool
  368. * @throws Exception
  369. */
  370. public function softDelete(): bool {
  371. // Delete identification documents
  372. $this->deleteIDFiles();
  373. // Delete addresses
  374. $this->deleteAddresses();
  375. // Decline all pending tests
  376. $pending_tests = $this->getPendingTests();
  377. foreach($pending_tests as $test) {
  378. $test->decline();
  379. }
  380. // Delete personal information
  381. $this->email = null;
  382. $this->title = null;
  383. $this->first_name = null;
  384. $this->last_name = null;
  385. $this->phone = null;
  386. $this->bank_name = null;
  387. $this->bank_sort_code = null;
  388. $this->bank_account_number = null;
  389. $this->paypal_email = null;
  390. // Set deleted time
  391. $this->dts_deleted = Util::getDateTime();
  392. return $this->commit();
  393. }
  394. /**
  395. * @return bool
  396. * @throws Exception
  397. */
  398. public function deleteIDFiles(): bool {
  399. $files = UserFile::query([
  400. "user_id" => $this->id,
  401. "type" => [UserFile::TYPE_ID, UserFile::TYPE_PHOTO]
  402. ]);
  403. foreach($files as $file) {
  404. $path = $this->getDirectory() . "/" . $file->id . ".jpg";
  405. if(file_exists($path)) unlink($path);
  406. $file->delete();
  407. }
  408. return true;
  409. }
  410. /**
  411. * @return bool
  412. * @throws Exception
  413. */
  414. public function deleteAddresses(): bool {
  415. $addresses = $this->getAddresses();
  416. foreach($addresses as $address) {
  417. $address->delete();
  418. }
  419. return true;
  420. }
  421. /**
  422. * @return UserAddress[]
  423. * @throws Exception
  424. */
  425. public function getAddresses(): array {
  426. $addresses = UserAddress::query([
  427. "user_id" => $this->id,
  428. ], [
  429. "sort" => "name"
  430. ]);
  431. return $addresses;
  432. }
  433. /**
  434. * @return UserAddress|null
  435. * @throws Exception
  436. */
  437. public function getInvoiceAddress(): ?UserAddress {
  438. $addresses = UserAddress::query([
  439. "user_id" => $this->id,
  440. ]);
  441. foreach($addresses as $address) {
  442. if($address->invoice) return $address;
  443. }
  444. // If only one address in account, just return it
  445. if(count($addresses) == 1) return array_shift($addresses);
  446. return null;
  447. }
  448. /**
  449. * @return Customer[]
  450. * @throws Exception
  451. */
  452. public function getCustomers() {
  453. if($this->level >= User::LEVEL_ADMIN) {
  454. return Customer::query([], ["sort" => "name"]);
  455. }
  456. if($this->level == User::LEVEL_CUSTOMER) {
  457. $links = UserCustomer::query(["user_id" => $this->id]);
  458. return Customer::query([
  459. "id" => array_column($links, "customer_id")
  460. ], ["sort" => "name"]);
  461. }
  462. return [];
  463. }
  464. /**
  465. * @return Test[]
  466. * @throws Exception
  467. */
  468. public function getPendingTests(): array {
  469. return Test::query([
  470. "tester_id" => $this->id,
  471. "status" => [Test::STATUS_ASSIGNED, Test::STATUS_CONFIRMED, Test::STATUS_STARTED, Test::STATUS_PENDING_VERIFICATION],
  472. ], [
  473. "sort" => "dts_assigned",
  474. "order" => "desc"
  475. ]);
  476. }
  477. /**
  478. * @return Test[]
  479. * @throws Exception
  480. */
  481. public function getCompletedTests(): array {
  482. return Test::query([
  483. "tester_id" => $this->id,
  484. "status" => [Test::STATUS_CANCELLED, Test::STATUS_COMPLETED],
  485. ], [
  486. "sort" => "dts_start",
  487. "order" => "desc"
  488. ]);
  489. }
  490. /**
  491. * @return User[]
  492. * @throws Exception
  493. */
  494. public function getReferrals(): array {
  495. return User::query([
  496. "referrer_id" => $this->id
  497. ]);
  498. }
  499. /**
  500. * @return string
  501. */
  502. public function getPreferredPaymentMethodText(): string {
  503. return User::PAYMENT_METHODS[$this->preferred_payment_method];
  504. }
  505. /**
  506. * @return string
  507. */
  508. public function getURL(): string {
  509. return "/account/users/{$this->id}";
  510. }
  511. public function isUnverified() {
  512. return $this->level == User::LEVEL_UNVERIFIED;
  513. }
  514. public function isRegistered() {
  515. return $this->level == User::LEVEL_REGISTERED;
  516. }
  517. }