Example #1
0
 /**
  * @param User $user
  * @param null $src
  */
 public function recordSignups(\ClassCentral\SiteBundle\Entity\User $user, $src = null)
 {
     try {
         $this->keenClient->addEvent('signups', array('user_id' => $user->getId(), 'type' => $user->getSignupTypeString(), 'src' => $src));
     } catch (\Exception $e) {
     }
 }
 /**
  * Gets the recommended courses for the personalized recommendations
  * page for the user
  * @param User $user
  * @param $params
  */
 public function getRecommendations(UserEntity $user, $params)
 {
     $cl = $this->container->get('course_listing');
     $follows = $user->getFollowsCategorizedByItem();
     $must = array('terms' => array('subjects.id' => $follows[Item::ITEM_TYPE_SUBJECT]));
     $data = $cl->byFollows($follows, $params, $must);
     return $data;
 }
 private function getMustNot(UserEntity $user)
 {
     $mustNot = array();
     $courseIds = $user->getUserCourseIds();
     if (!empty($courseIds)) {
         $mustNot = array('terms' => array('course.id' => $courseIds));
     }
     return $mustNot;
 }
 private function sendEmail($subject, $html, User $user, $campaignId, $count)
 {
     $mailgun = $this->getContainer()->get('mailgun');
     $response = $mailgun->sendMessage(array('from' => '"Class Central\'s MOOC Tracker" <*****@*****.**>', 'to' => $user->getEmail(), 'subject' => $subject, 'html' => $html, 'o:campaign' => $campaignId));
     if (!($response && $response->http_response_code == 200)) {
         // Failed
         return SchedulerJobStatus::getStatusObject(SchedulerJobStatus::SCHEDULERJOB_STATUS_FAILED, $response && $response->http_response_body ? $response->http_response_body->message : "Mailgun error");
     }
     return SchedulerJobStatus::getStatusObject(SchedulerJobStatus::SCHEDULERJOB_STATUS_SUCCESS, "Course New Session notification sent for {$count} courses to user with id {$user->getId()}");
 }
 private function sendEmail($subject, $html, User $user)
 {
     $mailgun = $this->getContainer()->get('mailgun');
     $response = $mailgun->sendMessage(array('from' => '"Dhawal Shah" <*****@*****.**>', 'to' => $user->getEmail(), 'subject' => $subject, 'html' => $html, 'o:campaign' => self::NEW_USER_FOLLOW_UP_CAMPAIGN_ID));
     if (!($response && $response->http_response_code == 200)) {
         // Failed
         return SchedulerJobStatus::getStatusObject(SchedulerJobStatus::SCHEDULERJOB_STATUS_FAILED, $response && $response->http_response_body ? $response->http_response_body->message : "Mailgun error");
     }
     return SchedulerJobStatus::getStatusObject(SchedulerJobStatus::SCHEDULERJOB_STATUS_SUCCESS, "Email sent");
 }
Example #6
0
 public function migrate()
 {
     $em = $this->container->get('Doctrine')->getManager();
     $u = new User();
     $u->setName('Anonymous');
     $u->setEmail(User::REVIEW_USER_EMAIL);
     $u->setPassword('NEVERLOGSIN' . $this->generateRandomString());
     $em->persist($u);
     $em->flush();
 }
 public function testUnsubscribeTokenEncryptDecrypt()
 {
     $uid = 26;
     $u = new User();
     $u->setId($uid);
     $token = CryptUtility::getUnsubscribeToken($u, UserPreference::USER_PREFERENCE_MOOC_TRACKER_COURSES, $this->key);
     $details = CryptUtility::decryptUnsubscibeToken($token, $this->key);
     $this->assertEquals($uid, $details['userId']);
     $this->assertEquals(UserPreference::USER_PREFERENCE_MOOC_TRACKER_COURSES, $details['prefId']);
 }
 public function testTemplatesAreBeingRendered()
 {
     $t = $this->container->get('templating');
     $u = new User();
     $u->setName('Dummy User');
     $u->setEmail('*****@*****.**');
     $courses = array();
     $course = array('id' => 5, 'name' => 'Dummy Course', 'shortDesc' => 'Dummy Course', 'initiative' => array('name' => 'Independent', 'code' => 'Independent'), 'slug' => 'fake_slug', 'nextOffering' => array('displayDate' => '2014-05-05', 'url' => 'http://example.com'), 'institutions' => array());
     $courses[] = array('interested' => false, 'id' => 5, 'course' => $course);
     $counts = array('offeringCount' => array('recent' => '50', 'selfpaced' => '100'));
     $html = $t->renderResponse('ClassCentralMOOCTrackerBundle:Reminder:multiple.courses.inlined.html', array('courses' => $courses, 'baseUrl' => $this->container->getParameter('baseurl'), 'user' => $u, 'jobType' => CourseStartReminderJob::JOB_TYPE_1_DAY_BEFORE, 'counts' => $counts, 'unsubscribeToken' => CryptUtility::getUnsubscribeToken($u, UserPreference::USER_PREFERENCE_MOOC_TRACKER_COURSES, $this->container->getParameter('secret'))))->getContent();
     $this->assertNotEmpty($html);
     $html = $t->renderResponse('ClassCentralMOOCTrackerBundle:Reminder:single.course.inlined.html', array('course' => $course, 'baseUrl' => $this->container->getParameter('baseurl'), 'interested' => false, 'user' => $u, 'counts' => $counts, 'jobType' => CourseStartReminderJob::JOB_TYPE_1_DAY_BEFORE, 'unsubscribeToken' => CryptUtility::getUnsubscribeToken($u, UserPreference::USER_PREFERENCE_MOOC_TRACKER_COURSES, $this->container->getParameter('secret'))))->getContent();
     $this->assertNotEmpty($html);
 }
 private function sendEmail($subject, $html, User $user, $campaignId, $deliveryTime)
 {
     $mailgun = $this->getContainer()->get('mailgun');
     $email = $user->getEmail();
     $env = $this->getContainer()->getParameter('kernel.environment');
     if ($env !== 'prod') {
         $email = $this->getContainer()->getParameter('test_email');
     }
     try {
         $response = $mailgun->sendMessage(array('from' => '"Class Central" <*****@*****.**>', 'to' => $email, 'subject' => $subject, 'html' => $html, 'o:campaign' => $campaignId, 'o:deliverytime' => $deliveryTime));
         if (!($response && $response->http_response_code == 200)) {
             // Failed
             return SchedulerJobStatus::getStatusObject(SchedulerJobStatus::SCHEDULERJOB_STATUS_FAILED, $response && $response->http_response_body ? $response->http_response_body->message : "Mailgun error");
         }
     } catch (\Exception $e) {
         // Probably a email validation error
         // Failed
         return SchedulerJobStatus::getStatusObject(SchedulerJobStatus::SCHEDULERJOB_STATUS_FAILED, 'Mailgun Exception');
     }
     return SchedulerJobStatus::getStatusObject(SchedulerJobStatus::SCHEDULERJOB_STATUS_SUCCESS, "Email sent");
 }
 private function sendEmail($html, UserEntity $user, $numCourses, $campaignId, $deliveryTime)
 {
     $mailgun = $this->getContainer()->get('mailgun');
     $email = $user->getEmail();
     $env = $this->getContainer()->getParameter('kernel.environment');
     if ($env !== 'prod') {
         $email = $this->getContainer()->getParameter('test_email');
     }
     try {
         $response = $mailgun->sendMessage(array('from' => '"Class Central" <*****@*****.**>', 'to' => $email, 'subject' => $numCourses . ' brand new courses for you to join', 'html' => $html, 'o:campaign' => $campaignId, 'o:deliverytime' => $deliveryTime));
         if (!($response && $response->http_response_code == 200)) {
             // Failed
             return SchedulerJobStatus::getStatusObject(SchedulerJobStatus::SCHEDULERJOB_STATUS_FAILED, $response && $response->http_response_body ? $response->http_response_body->message : "Mailgun error");
         }
     } catch (\Exception $e) {
         // Probably a email validation error
         // Failed
         return SchedulerJobStatus::getStatusObject(SchedulerJobStatus::SCHEDULERJOB_STATUS_FAILED, 'Mailgun Exception - ' . $e->getMessage());
     }
     return SchedulerJobStatus::getStatusObject(SchedulerJobStatus::SCHEDULERJOB_STATUS_SUCCESS, "Email sent for job " . self::NEW_COURSES_EMAIL_JOB_TYPE . " with user " . $user->getId());
 }
 public function moocTrackerSignupAction(Request $request)
 {
     $userSession = $this->get('user_session');
     $userService = $this->get('user_service');
     $session = $this->get('session');
     $em = $this->get('doctrine')->getManager();
     // Redirect user if already logged in
     if ($this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
         return $this->redirect($this->generateUrl('user_library'));
     }
     $email = $userSession->getNewsletterUserEmail();
     $emailEntity = $em->getRepository('ClassCentralSiteBundle:Email')->findOneByEmail($email);
     if (empty($emailEntity)) {
         // Redirect to signup page
         $this->redirect($this->generateUrl('signup'));
     }
     $password = $request->request->get('password');
     if (empty($password)) {
         $session->getFlashBag()->add('newsletter_signup_invalid_password', "Please enter a password");
         return $this->redirect($this->generateUrl('newsletter_subscribed'));
     }
     $name = $request->request->get('name');
     if (empty($name)) {
         $session->getFlashBag()->add('newsletter_signup_invalid_password', "Please enter a name");
         return $this->redirect($this->generateUrl('newsletter_subscribed'));
     }
     // Password-Email are accurate. Create a user
     $user = new User();
     $user->setEmail($email);
     $user->setPassword($password);
     $user->setName($name);
     foreach ($emailEntity->getNewsletters() as $newsletter) {
         $user->addNewsletter($newsletter);
     }
     $user = $userService->signup($user, false);
     // don't send an email verification.
     // Clean the email entities subscriptions
     $newsletters = $emailEntity->getNewsletters();
     $newsletters->clear();
     $em->persist($emailEntity);
     $em->flush();
     // Redirect to MOOC Tracker page
     return $this->redirect($this->generateUrl('user_profile', array('slug' => $user->getId(), 'tab' => 'edit-profile', 'ref' => 'user_created', 'src' => 'newsletter')));
 }
Example #12
0
 /**
  * Creates/Updates a review
  * @param $courseId
  * @param $reviewData
  */
 public function saveReview($courseId, \ClassCentral\SiteBundle\Entity\User $user, $reviewData, $isAdmin = false)
 {
     $em = $this->em;
     $newReview = false;
     $course = $em->getRepository('ClassCentralSiteBundle:Course')->find($courseId);
     if (!$course) {
         return $this->getAjaxResponse(false, 'Course not found');
     }
     // Get the review object if it exists
     $review = null;
     if (isset($reviewData['reviewId']) && is_numeric($reviewData['reviewId'])) {
         // Its an edit. Get the review
         // Get the review
         $review = $em->getRepository('ClassCentralSiteBundle:Review')->find($reviewData['reviewId']);
         if (!$review) {
             return $this->getAjaxResponse(false, 'Review does not exist');
         }
         // Check if the user has access to edit the review
         // Either the user is an admin or the person who created the review
         $admin = $this->container->get('security.context')->isGranted('ROLE_ADMIN');
         if (!$admin && $user->getId() != $review->getUser()->getId()) {
             return $this->getAjaxResponse(false, 'User does not have access to edit the review');
         }
     } else {
         $newReview = true;
         $review = $em->getRepository('ClassCentralSiteBundle:Review')->findOneBy(array('user' => $user, 'course' => $course));
         // Admins can create multiple reviews - for adding external reviews
         if ($review && !$isAdmin) {
             return $this->getAjaxResponse(false, 'Review already exists');
         }
         $review = new \ClassCentral\SiteBundle\Entity\Review();
         $review->setUser($user);
         $review->setCourse($course);
     }
     // Get the offering
     if (isset($reviewData['offeringId']) && $reviewData['offeringId'] != -1) {
         $offering = $em->getRepository('ClassCentralSiteBundle:Offering')->find($reviewData['offeringId']);
         $review->setOffering($offering);
     }
     // check if the rating valid
     if (!isset($reviewData['rating']) && !is_numeric($reviewData['rating'])) {
         return $this->getAjaxResponse(false, 'Rating is required and expected to be a number');
     }
     // Check if the rating is in range
     if (!($reviewData['rating'] >= 1 && $reviewData['rating'] <= 5)) {
         return $this->getAjaxResponse(false, 'Rating should be between 1 to 5');
     }
     // If review exists its length should be atleast 20 words
     if (!empty($reviewData['reviewText']) && str_word_count($reviewData['reviewText']) < 20) {
         return $this->getAjaxResponse(false, 'Review should be at least 20 words long');
     }
     $review->setRating($reviewData['rating']);
     $review->setReview($reviewData['reviewText']);
     // Progress is required
     if (!isset($reviewData['progress'])) {
         return $this->getAjaxResponse(false, 'Progress is required');
     }
     // Progress
     if (isset($reviewData['progress']) && array_key_exists($reviewData['progress'], UserCourse::$progress)) {
         $review->setListId($reviewData['progress']);
         // Add/update the course to users library
         if (!$isAdmin) {
             // Do not add this t
             $userService = $this->container->get('user_service');
             $uc = $userService->addCourse($user, $course, $reviewData['progress']);
         }
     }
     // Difficulty
     if (isset($reviewData['difficulty']) && array_key_exists($reviewData['difficulty'], \ClassCentral\SiteBundle\Entity\Review::$difficulty)) {
         $review->setDifficultyId($reviewData['difficulty']);
     }
     // Level
     if (isset($reviewData['level']) && array_key_exists($reviewData['level'], \ClassCentral\SiteBundle\Entity\Review::$levels)) {
         $review->setLevelId($reviewData['level']);
     }
     // Effort
     if (isset($reviewData['effort']) && is_numeric($reviewData['effort']) && $reviewData['effort'] > 0) {
         $review->setHours($reviewData['effort']);
     }
     if ($isAdmin) {
         // Status
         if (isset($reviewData['status']) && array_key_exists($reviewData['status'], \ClassCentral\SiteBundle\Entity\Review::$statuses)) {
             $review->setStatus($reviewData['status']);
         }
         // External reviewer name
         if (isset($reviewData['externalReviewerName'])) {
             $review->setReviewerName($reviewData['externalReviewerName']);
         }
         // External review link
         if (isset($reviewData['externalReviewLink']) && filter_var($reviewData['externalReviewLink'], FILTER_VALIDATE_URL)) {
             $review->setExternalLink($reviewData['externalReviewLink']);
         }
     }
     $user->addReview($review);
     $em->persist($review);
     $em->flush();
     $this->clearCache($courseId);
     // If its an actual user and not an anonymous user update the session information
     if ($user->getEmail() != \ClassCentral\SiteBundle\Entity\User::REVIEW_USER_EMAIL) {
         //Update the users review history in session
         $userSession = $this->container->get('user_session');
         $userSession->saveUserInformationInSession();
         $showNotification = true;
         if (isset($reviewData['showNotification'])) {
             $showNotification = $reviewData['showNotification'];
         }
         if ($showNotification) {
             if ($newReview) {
                 $userSession->notifyUser(UserSession::FLASH_TYPE_SUCCESS, 'Review created', sprintf("Review for <i>%s</i> created successfully", $review->getCourse()->getName()));
             } else {
                 $userSession->notifyUser(UserSession::FLASH_TYPE_SUCCESS, 'Review updated', sprintf("Your review for <i>%s</i> has been updated successfully", $review->getCourse()->getName()));
             }
         }
     }
     // Send a message in Slack
     if ($newReview) {
         $message = ReviewUtility::getRatingStars($review->getRating()) . "\nReview {$review->getId()} created for Course *" . $review->getCourse()->getName() . "*" . "\n *{$review->getUser()->getDisplayName()}*" . ReviewUtility::getReviewTitle($review);
         if ($review->getReview()) {
             $message .= "\n\n" . $review->getReview();
         }
         $message .= "\n" . $this->container->getParameter('baseurl') . $this->container->get('router')->generate('review_edit', array('reviewId' => $review->getId()));
         $message = str_replace('<strong>', '_', $message);
         $message = str_replace('</strong>', '_', $message);
         $this->container->get('slack_client')->to('#cc-activity-user')->from($review->getUser()->getDisplayName())->withIcon($this->container->get('user_service')->getProfilePic($review->getUser()->getId()))->send($message);
     }
     return $review;
 }
Example #13
0
 /**
  * Saves all the items a user follows in the session
  */
 public function saveFollowInformation(User $user)
 {
     $follows = array();
     // Initialize the array
     foreach (Item::$items as $item) {
         $follows[$item] = array();
     }
     foreach ($user->getFollows() as $follow) {
         $follows[$follow->getItem()][$follow->getItemId()] = 1;
     }
     $this->session->set(self::USER_FOLLOWS, $follows);
 }
Example #14
0
 /**
  * Uploads the facebook profile picture as a users profile picture
  * @param User $user
  * @param $username
  */
 private function uploadFacebookProfilePic(User $user, $fbId)
 {
     try {
         $kuber = $this->get('kuber');
         $url = sprintf("https://graph.facebook.com/v2.3/%s/picture?type=large", $fbId);
         //Get the extension
         $size = getimagesize($url);
         $extension = image_type_to_extension($size[2]);
         $imgFile = '/tmp/' . $fbId;
         file_put_contents($imgFile, file_get_contents($url));
         // Gets a silhouette if image does not exist
         // Upload the file to S3 using Kuber
         $kuber->upload($imgFile, Kuber::KUBER_ENTITY_USER, Kuber::KUBER_TYPE_USER_PROFILE_PIC, $user->getId(), ltrim($extension, '.'));
         // Clear the cache for profile pic
         $this->get('cache')->deleteCache('user_profile_pic_' . $user->getId());
         // Delete the temporary file
         unlink($imgFile);
     } catch (\Exception $e) {
         $this->get('logger')->error("Failed uploading Facebook Profile Picture for user id " . $user->getId() . ' with error: ' . $e->getMessage());
     }
 }
 public static function getUnsubscribeToken(User $user, $preference, $key)
 {
     $dt = new \DateTime();
     $str = sprintf("userPreference::%d::%d::%d", $user->getId(), $preference, $dt->getTimestamp());
     return self::encrypt($str, $key);
 }
 /**
  * Sends an email to verify the email address
  * @param User $user
  * @param $newEmail
  */
 private function sendChangeEmailAddressVerificationEmail(User $user, $newEmail)
 {
     $tokenService = $this->get('verification_token');
     $mailgun = $this->get('mailgun');
     $templating = $this->get('templating');
     $logger = $this->get('logger');
     $value = array('email' => $newEmail, 'verify_change' => 1, 'user_id' => $user->getId());
     $token = $tokenService->create($value, VerificationToken::EXPIRY_1_WEEK);
     if ($this->container->getParameter('kernel.environment') != 'test') {
         // Don't send email in test environment
         $html = $templating->renderResponse('ClassCentralSiteBundle:Mail:changeOfEmailAddressVerification.html.twig', array('token' => $token->getToken()))->getContent();
         $mailgunResponse = $mailgun->sendSimpleText($newEmail, "*****@*****.**", "Change of email address", $html);
         if (!isset($mailgunResponse['id'])) {
             $logger->error('Error sending change of email address verification email', array('user_id' => $user->getId(), 'mailgun_response' => $mailgunResponse));
         } else {
             $logger->info('Change of email address verification mail sent', array('user_id' => $user->getId(), 'mailgun_response' => $mailgunResponse));
         }
     }
     return $token->getToken();
 }
Example #17
0
 public function userLibrary(User $user, Request $request)
 {
     $finder = $this->container->get('course_finder');
     $userCourses = $user->getUserCourses();
     $courseIds = array();
     $courseIdsByList = array();
     $coursesByLists = array();
     $listCounts = array();
     $lists = Filter::getUserList($request->query->all());
     foreach ($lists as $list) {
         $listCounts[$list] = 0;
         $courseIdsByList[$list] = array();
     }
     foreach ($userCourses as $userCourse) {
         $list = $userCourse->getList();
         if (in_array($list['slug'], $lists)) {
             $courseIds[] = $userCourse->getCourse()->getId();
             $listCounts[$list['slug']]++;
             $courseIdsByList[$list['slug']][] = $userCourse->getCourse()->getId();
         }
     }
     extract($this->getInfoFromParams($request->query->all()));
     foreach ($lists as $list) {
         if (!empty($courseIdsByList[$list])) {
             $coursesByLists[$list] = $finder->byCourseIds($courseIdsByList[$list], $filters, $sort, -1);
         } else {
             $coursesByLists[$list] = array();
         }
     }
     $courses = $finder->byCourseIds($courseIds, $filters, $sort, $pageNo);
     extract($this->getFacets($courses));
     // Get the search terms
     $userSession = $this->container->get('user_session');
     $searchTerms = $userSession->getMTSearchTerms();
     $showInstructions = false;
     if (empty($searchTerms) && empty($lists)) {
         $showInstructions = true;
     }
     // Get Reviewed Courses
     $reviewedCourseIds = array();
     foreach ($user->getReviews() as $review) {
         $reviewedCourseIds[] = $review->getCourse()->getId();
     }
     $reviewedCourses = array();
     if (!empty($reviewedCourseIds)) {
         $reviewedCourses = $finder->byCourseIds($reviewedCourseIds);
     }
     return compact('allSubjects', 'allLanguages', 'allSessions', 'courses', 'sortField', 'sortClass', 'pageNo', 'lists', 'listCounts', 'coursesByLists', 'showInstructions', 'searchTerms', 'reviewedCourses');
 }
Example #18
0
 public function unSubscribeUser(\ClassCentral\SiteBundle\Entity\Newsletter $newsLetter, \ClassCentral\SiteBundle\Entity\User $user)
 {
     return $this->unsubscribe($newsLetter->getCode(), $user->getEmail());
 }
 private function getSearchTerms(User $user)
 {
     $st = array();
     foreach ($user->getMoocTrackerSearchTerms() as $s) {
         $st[] = $s->getSearchTerm();
     }
     return $st;
 }
Example #20
0
 public function calculateProfileScore(\ClassCentral\SiteBundle\Entity\User $user)
 {
     $score = 0;
     $profile = $user->getProfile();
     if (!$profile) {
         return $score;
     }
     $img = $this->getProfilePic($user->getId());
     if ($img != Profile::DEFAULT_PROFILE_PIC) {
         $score += 5;
     }
     if ($profile->getAboutMe()) {
         $score += 1;
     }
     return $score;
 }