예제 #1
0
 public function outOffering(Offering $offering)
 {
     $rs = $this->container->get('review');
     $name = '[' . $offering->getCourse()->getName() . ']' . '(' . $offering->getUrl() . ')';
     if ($offering->getInitiative() == null) {
         $initiative = 'Others';
     } else {
         $initiative = $offering->getInitiative()->getName();
     }
     $startDate = $offering->getDisplayDate();
     $length = 'NA';
     if ($offering->getCourse()->getLength() != 0) {
         $length = $offering->getCourse()->getLength();
     }
     // Rating
     $courseRating = round($rs->getRatings($offering->getCourse()->getId()), 1);
     $courseReviews = $rs->getReviewsArray($offering->getCourse()->getId());
     $reviewText = '';
     if ($courseRating == 0) {
         $courseRating = 'NA';
     } else {
         $reviewText = sprintf("(%d %s)", $courseReviews['count'], $courseReviews['count'] == 1 ? 'review' : 'reviews');
     }
     $url = 'https://www.class-central.com' . $this->router->generate('ClassCentralSiteBundle_mooc', array('id' => $offering->getCourse()->getId(), 'slug' => $offering->getCourse()->getSlug()));
     $url .= '#reviews';
     $ratingStars = ReviewUtility::getRatingStars($courseRating);
     $rating = "{$ratingStars} [{$reviewText}]({$url})";
     $this->output->writeln("{$name}|{$startDate}|{$length}|{$initiative}|{$rating}");
 }
예제 #2
0
 public function outOffering(Offering $offering)
 {
     $rs = $this->container->get('review');
     $name = '[' . $offering->getCourse()->getName() . ']' . '(' . $offering->getUrl() . ')';
     if ($offering->getInitiative() == null) {
         $initiative = 'Others';
     } else {
         $initiative = $offering->getInitiative()->getName();
     }
     $startDate = $offering->getDisplayDate();
     $startDate = array_shift(explode(',', $startDate));
     // Do not show the year to save characters
     $length = 'NA';
     if ($offering->getCourse()->getLength() != 0) {
         $length = $offering->getCourse()->getLength();
     }
     // Rating
     $courseRating = round($rs->getRatings($offering->getCourse()->getId()), 1);
     $courseReviews = $rs->getReviewsArray($offering->getCourse()->getId());
     $reviewText = '';
     if ($courseRating == 0) {
         $courseRating = 'NA';
     } else {
         $reviewText = sprintf("(%d)", $courseReviews['count']);
     }
     $url = 'https://www.class-central.com' . $this->router->generate('reviews_short_url', array('courseId' => $offering->getCourse()->getId()));
     $url .= '#reviews';
     $ratingStars = ReviewUtility::getRatingStars($courseRating);
     if ($courseRating > 0) {
         $rating = "{$ratingStars} [{$reviewText}]({$url})";
     } else {
         $rating = "{$ratingStars}";
     }
     $this->output->writeln("{$name} via **{$initiative}**|{$startDate}|{$length}|{$rating}");
 }
예제 #3
0
 /**
  * HTML format for the blog
  * @param Course $course
  */
 public function blogFormat(Course $course)
 {
     $router = $this->container->get('router');
     $rs = $this->container->get('review');
     $line1 = '';
     // Course name
     $line2 = '';
     // Institution name
     $line3 = '';
     // Next Session
     $ratings = $rs->getRatings($course->getId());
     $reviews = $rs->getReviews($course->getId());
     // LINE 1
     $url = 'https://www.class-central.com' . $router->generate('ClassCentralSiteBundle_mooc', array('id' => $course->getId(), 'slug' => $course->getSlug()));
     $name = $course->getName();
     $line1 = "<a href='{$url}'><b>{$name}</b></a>";
     // LINE 2
     if ($course->getInstitutions()->count() > 0) {
         $ins = $course->getInstitutions()->first();
         $insName = $ins->getName();
         $line2 = "{$insName}";
     }
     if ($course->getInitiative()) {
         $line2 .= ' via ' . $course->getInitiative()->getName();
     } else {
         $line2 .= ' via Independent';
     }
     $line2 = "<i>{$line2}</i>";
     // LINE 3
     $nextOffering = CourseUtility::getNextSession($course);
     if ($nextOffering) {
         $displayDate = $nextOffering->getDisplayDate();
         $directUrl = $nextOffering->getUrl();
         $states = CourseUtility::getStates($nextOffering);
         if (in_array('past', $states)) {
             $displayDate = 'TBA';
         }
         if (in_array('selfpaced', $states)) {
             $displayDate = 'Self Paced';
         }
         $ratingsLine = '';
         if ($ratings > 0) {
             $formattedRatings = ReviewUtility::getRatingStars($ratings);
             $numRatings = $reviews['ratingCount'];
             $post = $numRatings == 1 ? 'rating' : 'ratings';
             $ratingsLine = " | {$formattedRatings} (<a href='{$url}#course-all-reviews'>{$numRatings} {$post}</a>) ";
         }
         $lineDesc = '';
         if ($course->getOneliner()) {
             $lineDesc = $course->getOneliner() . "<br/>";
         } elseif ($course->getDescription()) {
             $lineDesc = $course->getDescription() . "<br/>";
         }
         $line3 = "<b> <a href='{$directUrl}' target='_blank'>Go To Class</a> {$ratingsLine} | Next Session : {$displayDate} </b><br/>";
     }
     return $line1 . '<br/>' . $line2 . '<br/>' . $lineDesc . $line3 . '<br/>';
 }
예제 #4
0
 public function outOffering(Offering $offering)
 {
     $course = $offering->getCourse();
     $rs = $this->container->get('review');
     // Figure out whether the course is new
     $oneMonthAgo = new \DateTime();
     $oneMonthAgo->sub(new \DateInterval("P30D"));
     $newCourse = false;
     if ($course->getCreated() >= $oneMonthAgo) {
         $newCourse = true;
     }
     // Is it being offered for he first time
     if (count($course->getOfferings()) == 1 and $offering->getCreated() > $oneMonthAgo) {
         $newCourse = true;
     }
     if (count($course->getOfferings()) == 1 and $offering->getStatus() != Offering::COURSE_OPEN) {
         $newCourse = true;
     }
     $name = '[' . $offering->getCourse()->getName() . ']' . '(' . $offering->getUrl() . ')';
     if ($offering->getInitiative() == null) {
         $initiative = 'Others';
     } else {
         $initiative = $offering->getInitiative()->getName();
     }
     $startDate = $offering->getDisplayDate();
     $startDate = array_shift(explode(',', $startDate));
     // Do not show the year to save characters
     $length = 'NA';
     if ($offering->getCourse()->getLength() != 0) {
         $length = $offering->getCourse()->getLength();
     }
     // Rating
     $courseRating = round($rs->getRatings($offering->getCourse()->getId()), 1);
     $courseReviews = $rs->getReviewsArray($offering->getCourse()->getId());
     $reviewText = '';
     if ($courseRating == 0) {
         $courseRating = 'NA';
     } else {
         $reviewText = sprintf("(%d)", $courseReviews['count']);
     }
     $url = 'https://www.class-central.com' . $this->router->generate('reviews_short_url', array('courseId' => $offering->getCourse()->getId()));
     //$url .= '#reviews';
     $ratingStars = ReviewUtility::getRatingStars($courseRating);
     if ($courseRating > 0) {
         $rating = "{$ratingStars} [{$reviewText}]({$url})";
     } else {
         $rating = "{$ratingStars}";
     }
     $new = '';
     if ($newCourse) {
         $new = "[NEW]";
     }
     $this->output->writeln("{$new} {$name} via **{$initiative}**|{$startDate}|{$length}|{$rating}");
 }
 /**
  * Must return an object of type SchedulerJobStatus
  * @param $args
  * @return SchedulerJobStatus
  */
 public function perform($args)
 {
     $em = $this->getContainer()->get('doctrine')->getManager();
     $userId = $this->getJob()->getUserId();
     $user = $em->getRepository('ClassCentralSiteBundle:User')->findOneBy(array('id' => $userId));
     $cache = $this->getContainer()->get('cache');
     // Get counts for self paced and recently started courses
     $navController = new NavigationController();
     $counts = $navController->getNavigationCounts($this->getContainer());
     $rs = $this->getContainer()->get('review');
     /**
      * Send notifications only for user courses
      */
     if (isset($args[UserCourse::LIST_TYPE_INTERESTED])) {
         $courseIds = $args[UserCourse::LIST_TYPE_INTERESTED];
         $numCourses = count($courseIds);
         if ($numCourses == 1) {
             $courseId = $courseIds[0];
             $course = $em->getRepository('ClassCentralSiteBundle:Course')->find($courseId);
             $subject = $course->getName() . ' - New session added';
         } else {
             // Multiple courses
             $subject = "Course Notification: New sessions added for {$numCourses} courses";
         }
         // Build a list of courses for which notifications are being sent for
         $courses = array();
         foreach ($courseIds as $cid) {
             $course = $em->getRepository('ClassCentralSiteBundle:Course')->find($cid);
             $courseArray = $em->getRepository('ClassCentralSiteBundle:Course')->getCourseArray($course);
             $courseArray['rating'] = $rs->getRatings($course->getId());
             $courseArray['ratingStars'] = ReviewUtility::getRatingStars($courseArray['rating']);
             $rArray = $rs->getReviewsArray($course->getId());
             $courseArray['reviewsCount'] = $rArray['count'];
             $courses[] = array('interested' => true, 'id' => $cid, 'course' => $courseArray);
         }
         $templating = $this->getContainer()->get('templating');
         $html = $templating->renderResponse('ClassCentralMOOCTrackerBundle:NewSession:newSession.inlined.html', array('results' => $courses, 'baseUrl' => $this->getContainer()->getParameter('baseurl'), 'user' => $user, 'loginToken' => $this->getContainer()->get('user_service')->getLoginToken($user), 'numCourses' => $numCourses, 'showDesc' => $numCourses <= 10, 'coursesHidden' => $numCourses > 40, 'counts' => $counts, 'unsubscribeToken' => CryptUtility::getUnsubscribeToken($user, UserPreference::USER_PREFERENCE_MOOC_TRACKER_COURSES, $this->getContainer()->getParameter('secret')), 'utm' => array('medium' => Mailgun::UTM_MEDIUM, 'campaign' => 'mt_new_sessions_reminder', 'source' => Mailgun::UTM_SOURCE_PRODUCT)))->getContent();
         $campaignId = self::MAILGUN_MT_NEW_SESSION;
         return $this->sendEmail($subject, $html, $user, $campaignId, $numCourses);
     } else {
         // Don't send an email
         return SchedulerJobStatus::getStatusObject(SchedulerJobStatus::SCHEDULERJOB_STATUS_FAILED, "No courses found for user {$userId}");
     }
 }
 /**
  * Must return an object of type SchedulerJobStatus
  * @param $args
  * @return SchedulerJobStatus
  */
 public function perform($args)
 {
     $em = $this->getContainer()->get('doctrine')->getManager();
     $reviewService = $this->getContainer()->get('review');
     $userId = $this->getJob()->getUserId();
     $user = $em->getRepository('ClassCentralSiteBundle:User')->findOneBy(array('id' => $userId));
     if (!$user) {
         return SchedulerJobAbstract::getStatusObject(SchedulerJobStatus::SCHEDULERJOB_STATUS_FAILED, "User with id {$userId} not found");
     }
     $courses = array();
     $reviews = array();
     foreach (array(2161, 361, 461, 889, 442) as $courseId) {
         $courses[] = $em->getRepository('ClassCentralSiteBundle:Course')->find($courseId);
         $review = $reviewService->getReviewsArray($courseId);
         $rating = $reviewService->getBayesianAverageRating($courseId);
         $reviews[$courseId] = array_merge($review, array('starRating' => ReviewUtility::getRatingStars($rating)));
     }
     $emailContent = $this->getFollowUpEmail($user, $courses, $reviews);
     return $this->sendEmail('Dhawal from Class Central', $emailContent, $user);
 }
예제 #7
0
 /**
  * Wrapper around static function so that it can be accessed from twig
  * @param $rating
  * @return float
  */
 public function formatRating($rating)
 {
     return ReviewUtility::formatRating($rating);
 }
예제 #8
0
 /**
  *
  * @param $id Row id for the course
  * @param $slug descriptive url for the course
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function moocAction(Request $request, $id, $slug)
 {
     // Autologin if a token exists
     $this->get('user_service')->autoLogin($request);
     $em = $this->getDoctrine()->getManager();
     $rs = $this->get('review');
     // Review service
     $cache = $this->get('Cache');
     $courseId = intval($id);
     $course = $cache->get('course_' . $courseId, array($this, 'getCourseDetails'), array($courseId, $em));
     if (!$course) {
         // TODO: render a error page
         return;
     }
     // Check if the course is a duplicate
     if (isset($course['duplicate'])) {
         // Exists - redirect to the original course
         return $this->redirect($this->get('router')->generate('ClassCentralSiteBundle_mooc', array('id' => $course['duplicate']['id'], 'slug' => $course['duplicate']['slug'])), 301);
     }
     // If the slug is not the same, then redirect to the correct url
     if ($course['slug'] !== $slug) {
         $url = $this->container->getParameter('baseurl') . $this->get('router')->generate('ClassCentralSiteBundle_mooc', array('id' => $course['id'], 'slug' => $course['slug']));
         return $this->redirect($url, 301);
     }
     if ($course['status'] == 100) {
         throw new NotFoundHttpException("Course not found");
     }
     // Get query params
     $redirect = $request->query->get('direct');
     if (!empty($redirect)) {
         // Get the url of next session
         return $this->redirect($course['nextOffering']['url']);
     }
     // Save the course and user tracking for generating recommendations later on
     if ($this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
         $user = $this->get('security.context')->getToken()->getUser();
         $sessionId = $user->getId();
     } else {
         $session = $this->getRequest()->getSession();
         if (!$session->isStarted()) {
             // Start the session if its not already started
             $session->start();
         }
         $sessionId = $session->getId();
     }
     $em->getConnection()->executeUpdate("INSERT INTO user_courses_tracking(user_identifier,course_id)\n                                VALUES ('{$sessionId}', {$courseId})");
     $rankings = $this->get('cache')->get('course_rankings', array($this, 'generateCourseRankings'));
     $courseRank = isset($rankings[$courseId]) ? $rankings[$courseId] : array();
     // Recently viewed
     $userSession = $this->get('user_session');
     $recentlyViewedCourseIds = $userSession->getRecentlyViewed();
     $recentlyViewedCourses = array();
     if (!empty($recentlyViewedCourseIds)) {
         foreach ($recentlyViewedCourseIds as $id) {
             $recentlyViewedCourses[] = $this->get('Cache')->get('course_' . $id, array($this, 'getCourseDetails'), array($id, $em));
         }
     }
     $userSession->saveRecentlyViewed($courseId);
     // URL of the current page
     $course['pageUrl'] = $this->container->getParameter('baseurl') . $this->get('router')->generate('ClassCentralSiteBundle_mooc', array('id' => $course['id'], 'slug' => $course['slug']));
     // Page Title/Twitter card title
     $titlePrefix = '';
     if (!empty($course['initiative']['name'])) {
         $titlePrefix = ' from ' . $course['initiative']['name'];
     }
     $course['pageTitle'] = $course['name'] . $titlePrefix;
     // Figure out if there is course in the future.
     $nextSession = null;
     $nextSessionStart = '';
     if (count($course['offerings']['upcoming']) > 0) {
         $nextSession = $course['offerings']['upcoming'][0];
         $nextSessionStart = $nextSession['displayDate'];
     }
     // Get reviews and ratings
     $rating = $rs->getRatings($courseId);
     $reviews = $rs->getReviews($courseId);
     // Breadcrumbs
     $breadcrumbs = array();
     if (!empty($course['initiative']['name'])) {
         $breadcrumbs[] = Breadcrumb::getBreadCrumb($course['initiative']['name'], $this->generateUrl('ClassCentralSiteBundle_initiative', array('type' => $course['initiative']['code'])));
     } else {
         $breadcrumbs[] = Breadcrumb::getBreadCrumb('Others', $this->generateUrl('ClassCentralSiteBundle_initiative', array('type' => 'others')));
     }
     $breadcrumbs[] = Breadcrumb::getBreadCrumb($course['name']);
     $recommendations = $this->get('Cache')->get('course_recommendation_' . $courseId, array($this, 'getCourseRecommendations'), array($courseId));
     $interestedUsers = $em->getRepository('ClassCentralSiteBundle:Course')->getInterestedUsers($courseId);
     // Only for admin users. Detect potential duplicates
     $potentialDuplicates = array();
     if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
         // Run a keyword search with the course
         $cl = $this->get('course_listing');
         $potentialDuplicates = $cl->search($course['name'], $request);
         $potentialDuplicates['courses']['hits']['hits'] = array_slice($potentialDuplicates['courses']['hits']['hits'], 0, 5);
     }
     return $this->render('ClassCentralSiteBundle:Course:mooc.html.twig', array('page' => 'course', 'course' => $course, 'offeringTypes' => Offering::$types, 'offeringTypesOrder' => array('upcoming', 'ongoing', 'selfpaced', 'past'), 'nextSession' => $nextSession, 'nextSessionStart' => $nextSessionStart, 'recentlyViewedCourses' => $recentlyViewedCourses, 'listTypes' => UserCourse::$lists, 'rating' => $rating, 'reviews' => $reviews, 'breadcrumbs' => $breadcrumbs, 'recommendations' => $recommendations, 'providersWithLogos' => Course::$providersWithFavicons, 'isYoutube' => $this->isYouTubeVideo($course['videoIntro']), 'courseImage' => $this->getCourseImage($courseId), 'ratingStars' => ReviewUtility::getRatingStars($rating), 'interestedUsers' => $interestedUsers, 'courseRank' => $courseRank, 'potentialDuplicates' => $potentialDuplicates));
 }
 public function getBody()
 {
     $indexer = $this->container->get('es_indexer');
     $em = $this->container->get('doctrine')->getManager();
     $rs = $this->container->get('review');
     $body = array();
     $c = $this->entity;
     // Alias for entity
     $body['name'] = $c->getName();
     $body['id'] = $c->getId();
     $body['videoIntro'] = $c->getVideoIntro();
     $body['length'] = $c->getLength();
     $body['slug'] = $c->getSlug();
     $body['description'] = $c->getDescription();
     $body['longDescription'] = $c->getLongDescription();
     $body['syllabus'] = $c->getSyllabus();
     $body['searchDesc'] = $c->getSearchDesc();
     $body['status'] = $c->getStatus();
     $body['certificate'] = $c->getCertificate();
     $body['verifiedCertificate'] = $c->getVerifiedCertificate();
     $body['url'] = $c->getUrl();
     if ($c->getCreated()) {
         $body['created'] = $c->getCreated()->format(DATE_ISO8601);
     }
     // Tags
     $tags = array();
     foreach ($c->getTags() as $tag) {
         $tags[] = strtolower($tag->getName());
     }
     $body['tags'] = $tags;
     // Instructors
     $body['instructors'] = array();
     foreach ($c->getInstructors() as $instructor) {
         $body['instructors'][] = $instructor->getName();
     }
     // Language
     $body['language'] = array();
     $lang = $c->getLanguage();
     if ($lang) {
         $body['language']['name'] = $lang->getName();
         $body['language']['id'] = $lang->getId();
         $body['language']['slug'] = $lang->getSlug();
     } else {
         // Set the default to english
         $l = $em->getRepository('ClassCentralSiteBundle:Language')->findOneBy(array('slug' => 'english'));
         $body['language']['name'] = $l->getName();
         $body['language']['id'] = $l->getId();
         $body['language']['slug'] = $l->getSlug();
     }
     // Institutions
     $body['institutions'] = array();
     foreach ($c->getInstitutions() as $ins) {
         $iDoc = new InstitutionDocumentType($ins, $this->container);
         $body['institutions'][] = $iDoc->getBody();
     }
     // Provider
     $body['provider'] = array();
     if ($c->getInitiative()) {
         $provider = $c->getInitiative();
     } else {
         // create an independent provider
         $provider = new Initiative();
         $provider->setName('Independent');
         $provider->setCode('independent');
     }
     $pDoc = new ProviderDocumentType($provider, $this->container);
     $body['provider'] = $pDoc->getBody();
     // Get the next session
     $body['nextSession'] = array();
     $ns = CourseUtility::getNextSession($c);
     if ($ns) {
         $nsDoc = new SessionDocumentType($ns, $this->container);
         $body['nextSession'] = $nsDoc->getBody();
     }
     // Subject
     $subjects = array();
     $sub = $c->getStream();
     if ($sub->getParentStream()) {
         // Add the parent stream first
         $psDoc = new SubjectDocumentType($sub->getParentStream(), $this->container);
         $subjects[] = $psDoc->getBody();
     }
     $sDoc = new SubjectDocumentType($sub, $this->container);
     $subjects[] = $sDoc->getBody();
     $body['subjects'] = $subjects;
     // Sessions. Add sessions to the records
     $sessions = array();
     $body['sessions'] = array();
     foreach ($c->getOfferings() as $session) {
         // Ignore invalid session
         if ($session->getStatus() == Offering::COURSE_NA) {
             continue;
         }
         $sDoc = new SessionDocumentType($session, $this->container);
         $sessions[] = $sDoc->getBody();
     }
     $body['sessions'] = $sessions;
     $body['numSessions'] = count($sessions);
     $body['rating'] = $rs->getRatings($c->getId());
     $body['ratingSort'] = $rs->getBayesianAverageRating($c->getId());
     $rArray = $rs->getReviewsArray($c->getId());
     $body['reviewsCount'] = $rArray['count'];
     $body['ratingStars'] = ReviewUtility::getRatingStars($body['rating']);
     $body['formattedRating'] = ReviewUtility::formatRating($body['rating']);
     // Get Followed count
     $courseRepo = $this->container->get('doctrine')->getManager()->getRepository('ClassCentralSiteBundle:Course');
     $body['followed'] = intval($courseRepo->getListedCount($c));
     // Check if the course being offered is new
     // Definition of new - created 30 days ago
     $oneMonthAgo = new \DateTime();
     $oneMonthAgo->sub(new \DateInterval("P30D"));
     $newCourse = false;
     if ($c->getCreated() >= $oneMonthAgo) {
         $newCourse = true;
     }
     $body['new'] = intval($newCourse);
     $startingSoon = false;
     $oneMonthLater = new \DateTime();
     $oneMonthLater->add(new \DateInterval("P30D"));
     if ($ns && !in_array('selfpaced', $body['nextSession']['states']) && in_array('upcoming', $body['nextSession']['states'])) {
         if ($ns->getStartDate() < $oneMonthLater and $ns->getStatus() != Offering::START_DATES_UNKNOWN) {
             $startingSoon = true;
         }
     }
     $body['startingSoon'] = intval($startingSoon);
     // Get the Credential
     $credential = array();
     if (!$c->getCredentials()->isEmpty()) {
         $cred = $c->getCredentials()->first();
         if ($cred->getStatus() < 100) {
             $credential['id'] = $cred->getId();
             $credential['name'] = $cred->getName();
             $credential['slug'] = $cred->getSlug();
             $credential['certificateName'] = '';
             $credential['certificateSlug'] = '';
             $credFormatter = $cred->getFormatter();
             $credential['certificateName'] = $credFormatter->getCertificateName();
             $credential['certificateSlug'] = $credFormatter->getCertificateSlug();
         }
     }
     $body['credential'] = $credential;
     return $body;
 }
예제 #10
0
 public function getCredentialReviews($slug)
 {
     $em = $this->container->get('doctrine')->getManager();
     $credential = $em->getRepository('ClassCentralCredentialBundle:Credential')->findOneBy(array('slug' => $slug));
     if (!$credential) {
         throw new \Exception("{$slug} is not a valid credential");
     }
     $rating = $this->calculateAverageRating($credential);
     $reviewEntities = $em->createQuery("\n               SELECT r,LENGTH (r.text) as reviewLength from ClassCentralCredentialBundle:CredentialReview r JOIN r.credential c WHERE c.slug = '{$slug}'\n                ORDER BY r.rating DESC, reviewLength DESC")->getResult();
     $reviewCount = 0;
     $ratingCount = 0;
     $r = array();
     foreach ($reviewEntities as $review) {
         $review = $review[0];
         if ($review->getStatus() < Review::REVIEW_NOT_SHOWN_STATUS_LOWER_BOUND) {
             $ratingCount++;
             $reviewCount++;
             $r[] = $this->getCredentialReviewArray($review);
         }
     }
     $reviews = array();
     $reviews['count'] = $ratingCount;
     $reviews['ratingCount'] = $ratingCount;
     $reviews['reviewCount'] = $reviewCount;
     $reviews['rating'] = $rating['rating'];
     $reviews['formattedRating'] = ReviewUtility::formatRating($rating['rating']);
     $reviews['reviews'] = $r;
     return $reviews;
 }
 public function substantialReviewsAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $query = $em->createQueryBuilder();
     $created = new \DateTime();
     $created->modify('-2 month');
     $query->add('select', 'r')->add('from', 'ClassCentralSiteBundle:Review r')->andWhere('r.status < :status AND r.created > :created')->setParameter('status', Review::REVIEW_NOT_SHOWN_STATUS_LOWER_BOUND)->setParameter('created', $created->format('Y-m-d'));
     $allReviews = $query->getQuery()->getResult();
     $reviews = array();
     foreach ($allReviews as $review) {
         if ($review->getUser()->getId() == User::REVIEW_USER_ID) {
             continue;
         }
         if (strlen($review->getReview()) > 200 && $review->getRating() >= 4) {
             $reviews[] = ReviewUtility::getReviewArray($review);
         }
     }
     return $this->render('ClassCentralSiteBundle:Review:substantialReviews.html.twig', array('reviews' => $reviews));
 }
 /**
  * Renders the users profile
  * @param $slug user id or username
  */
 public function profileAction(Request $request, $slug, $tab)
 {
     $tabs = array('transcript', 'interested', 'reviews', 'edit-profile');
     $em = $this->getDoctrine()->getManager();
     $cl = $this->get('course_listing');
     $userService = $this->get('user_service');
     $loggedInUser = $this->getUser();
     if (!in_array($tab, $tabs)) {
         // Invalid tab. Do a 301 redirect
         return $this->redirect($this->get('router')->generate('user_profile', array('slug' => $slug)), 301);
     }
     if (is_numeric($slug)) {
         $user_id = intval($slug);
         // Do not show profile pages for these user ids
         if ($user_id == User::SPECIAL_USER_ID || $user_id == User::REVIEW_USER_ID) {
             // User not found
             throw new \Exception("User {$slug} not found");
         }
         $user = $em->getRepository('ClassCentralSiteBundle:User')->find($user_id);
         if ($user->getHandle()) {
             // Redirect the user to the profile url
             $url = $this->get('router')->generate('user_profile_handle', array('slug' => $user->getHandle(), 'tab' => $tab == 'transcript' ? null : $tab));
             return $this->redirect($url, 301);
         }
     } else {
         $user = $em->getRepository('ClassCentralSiteBundle:User')->findOneBy(array('handle' => $slug));
     }
     if (!$user) {
         // User not found
         throw new \Exception("User {$slug} not found");
     }
     // if tab is edit-profile. Do some security checks
     if ($tab == 'edit-profile') {
         if ($this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
             // Logged in user
             $loggedInUser = $this->get('security.context')->getToken()->getUser();
             if ($user->getId() != $loggedInUser->getId()) {
                 // Does not have access to the edit profile tab. Redirect to transcript
                 return $this->redirect($this->get('router')->generate('user_profile', array('slug' => $user->getId())), 301);
             }
         } else {
             // Does not have access to the edit profile tab. Redirect to transcript
             return $this->redirect($this->get('router')->generate('user_profile', array('slug' => $user->getId())), 301);
         }
     }
     // User might have a private prifle
     if ($user->getIsPrivate() && !$this->isCurrentUser($user)) {
         throw $this->createNotFoundException("Page does not exist");
     }
     // User might not have a profile
     $profile = $user->getProfile() ? $user->getProfile() : new Profile();
     // Get users course listing. This is the same function on My Courses page
     // and contains additional information related to pagination
     $clDetails = $cl->userLibrary($user, $request);
     $reviews = array();
     foreach ($user->getReviews() as $review) {
         $r = ReviewUtility::getReviewArray($review);
         $reviews[$r['course']['id']] = $r;
     }
     $reviewedCourses = array();
     if (!empty($clDetails['reviewedCourses']['hits']['hits'])) {
         foreach ($clDetails['reviewedCourses']['hits']['hits'] as $reviewedCourse) {
             $reviewedCourses[$reviewedCourse['_source']['id']] = $reviewedCourse['_source'];
         }
     }
     // Check if a change of email has been issued
     $changeEmail = null;
     $userPrefs = $user->getUserPreferencesByTypeMap();
     if ($this->isCurrentUser($user) && isset($userPrefs[UserPreference::USER_PROFILE_UPDATE_EMAIL])) {
         // An change of email request was issued. Check whether it is still valid
         $pref = $userPrefs[UserPreference::USER_PROFILE_UPDATE_EMAIL];
         $values = json_decode($pref->getValue(), true);
         $verifyTokenService = $this->get('verification_token');
         $tokenEntity = $verifyTokenService->get($values['token']);
         if ($tokenEntity) {
             // Email has been changed and the token is still valid
             $changeEmail = $values['email'];
         }
     }
     // Show a message if the profile is marked for deletion
     $deleteAccount = false;
     if ($this->isCurrentUser($user) && isset($userPrefs[UserPreference::USER_PROFILE_DELETE_ACCOUNT])) {
         $deleteAccount = true;
     }
     // Build an array for credential details.
     $credService = $this->get('es_credentials');
     $credReviews = $user->getCredentialReviews();
     $creds = array();
     foreach ($credReviews as $credReview) {
         $creds[] = array('cred' => $credService->findBySlug($credReview->getCredential()->getSlug()), 'review' => $credReview);
     }
     return $this->render('ClassCentralSiteBundle:Profile:profile.html.twig', array('user' => $user, 'profile' => $profile, 'listTypes' => UserCourse::$transcriptList, 'coursesByLists' => $clDetails['coursesByLists'], 'reviews' => $reviews, 'reviewedCourses' => $reviewedCourses, 'degrees' => Profile::$degrees, 'profilePic' => $userService->getProfilePic($user->getId()), 'changeEmail' => $changeEmail, 'deleteAccount' => $deleteAccount, 'tab' => $tab, 'userCreds' => $creds));
 }
예제 #13
0
 public function getBody()
 {
     $indexer = $this->container->get('es_indexer');
     $em = $this->container->get('doctrine')->getManager();
     $rs = $this->container->get('review');
     $body = array();
     $c = $this->entity;
     // Alias for entity
     $body['name'] = $c->getName();
     $body['id'] = $c->getId();
     $body['videoIntro'] = $c->getVideoIntro();
     $body['length'] = $c->getLength();
     $body['slug'] = $c->getSlug();
     $body['description'] = $c->getDescription();
     $body['longDescription'] = $c->getLongDescription();
     $body['syllabus'] = $c->getSyllabus();
     $body['searchDesc'] = $c->getSearchDesc();
     $body['status'] = $c->getStatus();
     $body['certificate'] = $c->getCertificate();
     $body['verifiedCertificate'] = $c->getVerifiedCertificate();
     $body['url'] = $c->getUrl();
     // Tags
     $tags = array();
     foreach ($c->getTags() as $tag) {
         $tags[] = strtolower($tag->getName());
     }
     $body['tags'] = $tags;
     // Instructors
     $body['instructors'] = array();
     foreach ($c->getInstructors() as $instructor) {
         $body['instructors'][] = $instructor->getName();
     }
     // Language
     $body['language'] = array();
     $lang = $c->getLanguage();
     if ($lang) {
         $body['language']['name'] = $lang->getName();
         $body['language']['id'] = $lang->getId();
         $body['language']['slug'] = $lang->getSlug();
     } else {
         // Set the default to english
         $l = $em->getRepository('ClassCentralSiteBundle:Language')->findOneBy(array('slug' => 'english'));
         $body['language']['name'] = $l->getName();
         $body['language']['id'] = $l->getId();
         $body['language']['slug'] = $l->getSlug();
     }
     // Institutions
     $body['institutions'] = array();
     foreach ($c->getInstitutions() as $ins) {
         $iDoc = new InstitutionDocumentType($ins, $this->container);
         $body['institutions'][] = $iDoc->getBody();
     }
     // Provider
     $body['provider'] = array();
     if ($c->getInitiative()) {
         $provider = $c->getInitiative();
     } else {
         // create an independent provider
         $provider = new Initiative();
         $provider->setName('Independent');
         $provider->setCode('independent');
     }
     $pDoc = new ProviderDocumentType($provider, $this->container);
     $body['provider'] = $pDoc->getBody();
     // Get the next session
     $body['nextSession'] = array();
     $ns = CourseUtility::getNextSession($c);
     if ($ns) {
         $nsDoc = new SessionDocumentType($ns, $this->container);
         $body['nextSession'] = $nsDoc->getBody();
     }
     // Subject
     $subjects = array();
     $sub = $c->getStream();
     if ($sub->getParentStream()) {
         // Add the parent stream first
         $psDoc = new SubjectDocumentType($sub->getParentStream(), $this->container);
         $subjects[] = $psDoc->getBody();
     }
     $sDoc = new SubjectDocumentType($sub, $this->container);
     $subjects[] = $sDoc->getBody();
     $body['subjects'] = $subjects;
     // Sessions. Add sessions to the records
     $sessions = array();
     $body['sessions'] = array();
     foreach ($c->getOfferings() as $session) {
         // Ignore invalid session
         if ($session->getStatus() == Offering::COURSE_NA) {
             continue;
         }
         $sDoc = new SessionDocumentType($session, $this->container);
         $sessions[] = $sDoc->getBody();
     }
     $body['sessions'] = $sessions;
     $body['rating'] = $rs->getRatings($c->getId());
     $body['ratingSort'] = $rs->getBayesianAverageRating($c->getId());
     $rArray = $rs->getReviewsArray($c->getId());
     $body['reviewsCount'] = $rArray['count'];
     $body['ratingStars'] = ReviewUtility::getRatingStars($body['rating']);
     $body['formattedRating'] = ReviewUtility::formatRating($body['rating']);
     // Get the Credential
     $credential = array();
     if (!$c->getCredentials()->isEmpty()) {
         $cred = $c->getCredentials()->first();
         if ($cred->getStatus() < 100) {
             $credential['id'] = $cred->getId();
             $credential['name'] = $cred->getName();
             $credential['slug'] = $cred->getSlug();
             $credential['certificateName'] = '';
             $credential['certificateSlug'] = '';
             $credFormatter = $cred->getFormatter();
             $credential['certificateName'] = $credFormatter->getCertificateName();
             $credential['certificateSlug'] = $credFormatter->getCertificateSlug();
         }
     }
     $body['credential'] = $credential;
     return $body;
 }
 public function getBody()
 {
     $body = array();
     $credentialService = $this->container->get('credential');
     $c = $this->entity;
     // Alias for entity
     $formatter = $c->getFormatter();
     $body['name'] = $c->getName();
     $body['id'] = $c->getId();
     $body['slug'] = $c->getSlug();
     $body['oneLiner'] = $c->getOneLiner();
     $body['subTitle'] = $c->getSubTitle();
     $body['price'] = $c->getPrice();
     $body['pricePeriod'] = $c->getPricePeriod();
     $body['displayPrice'] = $formatter->getPrice();
     $body['durationMin'] = $c->getDurationMin();
     $body['durationMax'] = $c->getDurationMax();
     $body['displayDuration'] = $formatter->getDuration();
     $body['workloadMin'] = $c->getWorkloadMin();
     $body['workloadMax'] = $c->getDurationMax();
     $body['workloadType'] = $c->getWorkloadType();
     $body['displayWorkload'] = $formatter->getWorkload();
     $body['url'] = $c->getUrl();
     $body['description'] = $c->getDescription();
     $body['status'] = $c->getStatus();
     $body['image'] = $credentialService->getImage($c);
     $body['cardImage'] = $credentialService->getCardImage($c);
     $body['subjectSlug'] = null;
     $body['subject'] = null;
     if ($c->getSubject()) {
         $body['subjectSlug'] = $c->getSubject();
         $body['subject'] = Credential::$SUBJECTS[$c->getSubject()];
     }
     $orgs = array();
     // Array of names of organizations who are involved in creating the credential
     // Provider
     $body['provider'] = array();
     if ($c->getInitiative()) {
         $provider = $c->getInitiative();
         $body['certificateName'] = $formatter->getCertificateName();
         $body['certificateSlug'] = $formatter->getCertificateSlug();
         $bulletOrg = "{$formatter->getCertificateName()} via ";
         $orgs[] = $provider->getName();
         // Populate the organization list
     } else {
         // create an independent provider
         $provider = new Initiative();
         $provider->setName('Independent');
         $provider->setCode('independent');
     }
     $pDoc = new ProviderDocumentType($provider, $this->container);
     $body['provider'] = $pDoc->getBody();
     // Institutions
     $body['institutions'] = array();
     $institutions = array();
     foreach ($c->getInstitutions() as $ins) {
         $iDoc = new InstitutionDocumentType($ins, $this->container);
         $body['institutions'][] = $iDoc->getBody();
         $orgs[] = $ins->getName();
         // Populate the organization list
     }
     // Get the ratings
     $rating = $credentialService->calculateAverageRating($this->entity);
     $body['rating'] = $rating['rating'];
     $body['formattedRating'] = ReviewUtility::formatRating($rating['rating']);
     // Rounds the rating to the nearest 0.5
     $body['numRatings'] = $rating['numRatings'];
     $courses = array();
     foreach ($this->entity->getCourses() as $course) {
         $cDoc = new CourseDocumentType($course, $this->container);
         $courses[] = $cDoc->getBody();
     }
     $body['courses'] = $courses;
     $body['isSponsered'] = $c->isSponsored();
     // Build the bullet points in the array
     $bulletPoints = array();
     $bulletPoints[] = $bulletOrg . UniversalHelper::commaSeparateList($orgs);
     // Bullet Price and Duration
     $bulletPriceAndDuration = $formatter->getPrice();
     $displayDuration = $formatter->getDuration();
     if ($displayDuration) {
         $bulletPriceAndDuration .= ' for ' . $displayDuration;
     }
     $bulletPoints[] = $bulletPriceAndDuration;
     // Bullet effort
     $effort = $formatter->getWorkload();
     if ($effort) {
         $bulletPoints[] = $effort . ' of effort';
     }
     if ($provider->getName() == 'Coursera') {
         $bulletPoints[] = count($body['courses']) - 1 . ' courses + capstone project ';
     } elseif ($provider->getName() == 'HBX') {
         $bulletPoints[] = '3 courses and a final exam. Application Required';
     }
     if ($formatter->getEnrollment()) {
         $bulletPoints[] = $formatter->getEnrollment();
     }
     $body['bulletPoints'] = $bulletPoints;
     return $body;
 }
예제 #15
0
 /**
  * Wrapper around static function so that it can be accessed from twig
  * @param $rating
  * @return string
  */
 public function getRatingStars($rating)
 {
     return ReviewUtility::getRatingStars($rating);
 }
예제 #16
0
 public function tableRowFormat(Course $course)
 {
     $followColumn = '';
     $courseNameColumn = '';
     $startDateColumn = '';
     $ratingColumn = '';
     $router = $this->container->get('router');
     $rs = $this->container->get('review');
     //
     $courseUrl = 'https://www.class-central.com' . $router->generate('ClassCentralSiteBundle_mooc', array('id' => $course->getId(), 'slug' => $course->getSlug()));
     $courseName = $course->getName();
     // COLUMN 1 - FOLLOW
     $followUrl = $courseUrl . '?follow=true';
     $followColumn = "<td width='30px' style='vertical-align: top'><a href='{$followUrl}' style='color: red;font-size: 25px;text-decoration: none' target='_blank'>♥</a></td>";
     // COLUMN 2 - COURSE NAME
     $providerLine = '';
     if ($course->getInstitutions()->count() > 0) {
         $ins = $course->getInstitutions()->first();
         $providerLine = $ins->getName();
         $providerLine = "{$providerLine}";
     }
     if ($course->getInitiative()) {
         $providerLine .= ' via ' . $course->getInitiative()->getName();
     } else {
         $providerLine .= ' via Independent';
     }
     $providerLine = "<i>{$providerLine}</i>";
     $courseNameColumn = "<td><a href='{$courseUrl}'>{$courseName}</a><br/>{$providerLine}</td>";
     // COLUMN 3 - START DATE
     $nextOffering = CourseUtility::getNextSession($course);
     if (!$nextOffering) {
         return '';
     }
     $displayDate = $nextOffering->getDisplayDate();
     $states = CourseUtility::getStates($nextOffering);
     if (in_array('past', $states)) {
         $displayDate = 'TBA';
     }
     if (in_array('selfpaced', $states)) {
         $displayDate = 'Self Paced';
     }
     $startDateColumn = "<td>{$displayDate}</td>";
     // COLUMN 4 - RATING
     $ratings = $rs->getRatings($course->getId());
     $reviews = $rs->getReviews($course->getId());
     $ratingsLine = ReviewUtility::getRatingStars(0);
     // Default value
     if ($ratings > 0) {
         $formattedRatings = ReviewUtility::getRatingStars($ratings);
         $numRatings = $reviews['ratingCount'];
         $post = $numRatings == 1 ? 'rating' : 'ratings';
         $ratingsLine = "{$formattedRatings} (<a href='{$courseUrl}#reviews'>{$numRatings}</a>) ";
     }
     $ratingColumn = "<td>{$ratingsLine}</td>";
     return "<tr>" . $followColumn . $courseNameColumn . $ratingColumn . "</tr>";
 }