public function ajaxStoreEventAction(Request $request)
 {
     if ($request->isXMLHttpRequest()) {
         $em = $this->getDoctrine()->getManager();
         $playerIds = $request->get('player_ids');
         //actually emails
         $eventId = $request->get('event_id');
         $event = $this->getDoctrine()->getRepository("SportnetzwerkSpnBundle:Events")->findById($eventId);
         $event[0]->setEventStatus(1);
         //set activation flag
         $created = $event[0]->getCreated();
         foreach ($playerIds as $k => $p) {
             $player = $this->getDoctrine()->getRepository("SportnetzwerkSpnBundle:Player")->findByEmail($p);
             $token = md5($eventId . $player[0]->getName() . $player[0]->getEmail() . $created);
             $playerEvent = new PlayerEvents();
             $playerEvent->setEvent($event[0]);
             $playerEvent->setPlayer($player[0]);
             $playerEvent->setToken($token);
             $em->persist($playerEvent);
             $em->flush();
             $token = $this->getDoctrine()->getRepository("SportnetzwerkSpnBundle:PlayerEvents")->getEventToken($player[0], $eventId);
             $message = \Swift_Message::newInstance()->setSubject('Event invitation - Sportnetzwerk')->setFrom('*****@*****.**')->setTo($player[0]->getEmail())->setBody($this->render('SportnetzwerkSpnBundle:Events:eventInvitationEmail.txt.twig', array('player' => $player[0], 'token' => $token, 'newschedule' => true)));
             $this->get('mailer')->send($message);
         }
         return new JsonResponse(true);
     }
     return new Response('No ajax here', 400);
 }
 public function getCalendarDataAction(Request $req)
 {
     if ($req->isXMLHttpRequest()) {
         $start = $req->get('start');
         $end = $req->get('end');
         $em = $this->getDoctrine()->getManager();
         $events = $em->getRepository('AGILHallBundle:AgilEvent')->getEventDataStartEnd($start, $end);
         return new JsonResponse($events);
     }
     return new Response("Erreur !");
 }
Example #3
0
 /**
  * Add a new time
  *
  * @param Request $request
  *
  * @return JsonResponse A Response instance
  */
 public function addAction(Request $request)
 {
     $timeTracker = new TimeTracker();
     $timeTrackerForm = $this->createForm(new TimeTrackerType(), $timeTracker);
     if ($request->isXMLHttpRequest() && $request->isMethod('POST')) {
         $timeTrackerForm->handleRequest($request);
         if ($timeTrackerForm->isValid()) {
             $timeTrackerManager = $this->get('jumph_time_tracker.time_tracker_manager');
             $timeTrackerManager->create($timeTracker);
             return new JsonResponse(array('status' => 'success', 'html' => $this->renderView('JumphTimeTrackerBundle:TimeTracker:_time_line.html.twig', array('timeTracker' => $timeTracker))));
         }
     }
     return new JsonResponse(array('status' => 'error', 'error' => $timeTrackerForm->getErrorsAsString()));
 }
 public function instructorAction(Request $request)
 {
     $time_start = $this->container->getParameter('current_time_start');
     $time_end = $this->container->getParameter('current_time_end');
     if ($request->isXMLHttpRequest()) {
         $instructorId = $request->query->get('id', '');
         $em = $this->getDoctrine()->getManager();
         $instructor = $em->getRepository('ApplicationSonataUserBundle:User')->findOneBy(array('id' => $instructorId));
         $courses = $em->getRepository('QTUTkbBundle:Course')->findCourseByInstructor($instructorId, $time_start, $time_end);
         return $this->render('QTUTkbBundle:MyTimeTable:timetable_instructor.html.twig', array('courses' => $courses, 'instructor' => $instructor));
     } else {
         throw new NotFoundHttpException("Page not found");
     }
 }
Example #5
0
 /**
  * @Route("/check-connection", name="check-db-connection")
  */
 public function asyncDBCheck(Request $request)
 {
     if ($request->isXMLHttpRequest()) {
         $databaseArgs = array('name' => $request->request->get('name'));
         $connectionStatus = $this->checkConnection($databaseArgs);
         $response = new JsonResponse();
         if ($connectionStatus) {
             $response->setData(array('action' => 'db_check', 'status' => 'success'));
         } else {
             $response->setData(array('action' => 'db_check', 'status' => 'failure'));
         }
         return $response;
     }
     return new Response('This is not ajax!', 400);
 }
 /**
  * @Route("/code",name="recherchecode")
  * 
  * 
  */
 public function RechercheCode(Request $request)
 {
     if ($request->isXMLHttpRequest()) {
         $code = $request->get('code');
         $codeInfo = $this->container->get('formatecode')->FormateCode($code);
         if ($codeInfo) {
             return new Response(200);
             // Code 200  == ok,, make sure it has the correct content t
         } else {
             return new Response(201);
             //Code 201 == doublons
         }
     } else {
         return new Response(400);
     }
 }
 /**                                                                                   
  * @Method({"GET", "POST"})
  */
 public function listAction(Request $request)
 {
     if ($request->isXMLHttpRequest()) {
         $idcategories = $request->request->get("idcategories");
         $code = "";
         $repository = $this->getRepository('SWDocManagerBundle:Category');
         foreach ($idcategories as $idcategory) {
             if ($idcategory > -1) {
                 $code .= $repository->getCode($idcategory);
             }
         }
         $repDoc = $this->getRepository('SWDocManagerBundle:Document');
         $documents = $repDoc->getByCode($code);
         $documentsJson = $this->encodeJson($documents);
         return new JsonResponse(array('code' => $code, 'documents' => json_decode($documentsJson)));
     }
     return $this->redirect($this->generateUrl('sw_doc_manager_homepage'));
 }
Example #8
0
 public function ajaxAction(Request $request)
 {
     if ($request->isXMLHttpRequest()) {
         $repository = $this->getDoctrine()->getRepository('AppBundle:Prepod');
         $ids = $request->request->get('ids');
         if (sizeof($ids) == 0) {
             $prepods = $repository->findAll();
         } else {
             $prepods = $repository->createQueryBuilder('n')->where('n.id NOT IN (:status)')->setParameter('status', $ids)->getQuery()->getResult();
         }
         $prepod = $prepods[array_rand($prepods)];
         if ($prepod->getId() == 2) {
             return new JsonResponse(array('winner' => 2, 'img' => $prepod->getFoto(), 'name' => $prepod->getName(), 'text' => $prepod->getDescription()));
         }
         if (sizeof($ids) == 2) {
             return new JsonResponse(array('winner' => 1, 'img' => $prepod->getFoto(), 'name' => $prepod->getName(), 'text' => $prepod->getDescription()));
         }
         return new JsonResponse(array('winner' => 0, 'img' => $prepod->getFoto(), 'ids' => $prepod->getId()));
     }
     return new Response('This is not ajax!', 400);
 }
 /**
  * @Route(
  *    "/list/{page}/{markViewed}",
  *    requirements = {
  *        "page" = "\d+",
  *        "markViewed" = "0|1"
  *    },
  *    defaults = {
  *        "page" = 1,
  *        "markViewed" = 0
  *    },
  *    name="icap_notification_view"
  * )
  * @Template()
  * @ParamConverter("user", options={"authenticatedUser" = true})
  */
 public function listAction(Request $request, $user, $page, $markViewed)
 {
     $notificationManager = $this->getNotificationManager();
     $systemName = $notificationManager->getPlatformName();
     if ($request->isXMLHttpRequest()) {
         $result = $notificationManager->getDropdownNotifications($user->getId());
         $result['systemName'] = $systemName;
         $unviewedNotifications = $notificationManager->countUnviewedNotifications($user->getId());
         $result['unviewedNotifications'] = $unviewedNotifications;
         return $this->render('IcapNotificationBundle:Templates:notificationDropdownList.html.twig', $result);
     } else {
         $category = $request->get('category');
         if ($markViewed == true) {
             $notificationManager->markAllNotificationsAsViewed($user->getId());
         }
         $result = $notificationManager->getPaginatedNotifications($user->getId(), $page, $category);
         $result['systemName'] = $systemName;
         $result['category'] = $category;
         return $result;
     }
 }
Example #10
0
 public function classFilterAction(Request $request)
 {
     $time_start = $this->container->getParameter('current_time_start');
     $time_end = $this->container->getParameter('current_time_end');
     //        var_dump($time_start);die;
     if ($request->isXMLHttpRequest()) {
         $className = $request->query->get('class', '');
         $em = $this->getDoctrine()->getManager();
         if ($className != '') {
             $classP = $em->getRepository('QTUTkbBundle:ClassP')->findOneBy(array('stillStudy' => true, 'name' => $className));
             if ($classP) {
                 //get all course of this class
                 $courses = $em->getRepository('QTUTkbBundle:Course')->findCourseByClass($className, $time_start, $time_end);
                 //                    var_dump($courses);die;
                 return $this->render('QTUTkbBundle:Default:timetable_class_filter.html.twig', array('courses' => $courses));
             }
         }
         var_dump($courses);
         return $this->render('QTUTkbBundle:Default:timetable_class_empty.html.twig');
     } else {
         throw new NotFoundHttpException("Page not found");
     }
 }
Example #11
0
 /**
  * Displays a form to edit an existing Tasks entity.
  *
  * @Route("/{id}/edit", name="tasks_edit")
  * @Method({"GET", "POST"})
  */
 public function editAction(Request $request, Tasks $task)
 {
     $em = $this->getDoctrine()->getManager();
     if ($request->isXMLHttpRequest()) {
         $task->setCompleted($request->get('completed'));
         if ($task->getCompleted()) {
             $task->setCompletedAt(new \DateTime());
         } else {
             $task->setCompletedAt(null);
         }
         $em->flush();
         return new \Symfony\Component\HttpFoundation\JsonResponse();
     }
     $deleteForm = $this->createDeleteForm($task);
     $editForm = $this->createForm(TasksType::class, $task);
     $editForm->handleRequest($request);
     if ($editForm->isSubmitted() && $editForm->isValid()) {
         $em = $this->getDoctrine()->getManager();
         $em->persist($task);
         $em->flush();
         return $this->redirect($this->generateUrl('focus') . '#task_' . $task->getId());
     }
     return $this->render('tasks/edit.html.twig', array('task' => $task, 'task_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView()));
 }
 public function inviteFriendAction(Request $request)
 {
     $user = $this->getUser();
     if (!is_object($user) || !$user instanceof UserInterface) {
         throw new AccessDeniedException('This user does not have access to this section.');
     }
     $response = array('success' => 'false');
     if ($request->isXMLHttpRequest() && null !== $request->request->get('email')) {
         $emailTo = $request->request->get('email');
         $emailConstraint = new Assert\Email();
         $emailConstraint->message = 'Invalid email address';
         // use the validator to validate the value
         $errorList = $this->get('validator')->validate($emailTo, $emailConstraint);
         if (0 === count($errorList)) {
             try {
                 $message = \Swift_Message::newInstance()->setSubject('Join CreateSafe')->setFrom(array('*****@*****.**' => 'CreateSafe'))->setTo($emailTo)->setBody($this->renderView('email/inviteFriends.html.twig', array('confirmationUrl' => '/', 'user' => $this->getUser())), 'text/html');
                 $this->get('mailer')->send($message);
                 $response['success'] = 'true';
             } catch (\Exception $e) {
                 $response['success'] = 'false';
                 //use for debugging purposes
                 //$response['error'] = $e->getMessage();
             }
         } else {
             $response['invalidEmail'] = true;
         }
     }
     $encoders = array(new XmlEncoder(), new JsonEncoder());
     $normalizers = array(new ObjectNormalizer());
     $serializer = new Serializer($normalizers, $encoders);
     return new Response($serializer->serialize($response, 'json'));
 }
Example #13
0
 /**
  * @Route("/wotr/ajax/units/{id}")
  * @ParamConverter("post", class="WotRBundle:Game", options={"repository_method" = "getCurrentGame"})
  * @param Game $game
  * @param Request $request
  * @return JsonResponse|Response
  */
 public function ajaxUnitsAction(Game $game, Request $request)
 {
     if ($request->isXMLHttpRequest()) {
         $units = $game->getUnits();
         $outputArr = array();
         /** @var Unit $u */
         foreach ($units as $u) {
             if ($u->getLocation()) {
                 $outputArr[$u->getId()] = array('unitName' => $u->getName(), 'loc' => $u->getLocation()->getId(), 'sideId' => $u->getSide()->getId());
             }
         }
         $response = new JsonResponse();
         $response->setData(array('data' => $outputArr));
         return $response;
     }
     return new Response('This is not ajax!', 400);
     $unitTable = 'units';
     $request = new Request();
     switch ($request->getProperty('request')) {
         case 'units':
             $sql = "SELECT {$unitTable}.id, loc, unit.name as unitName, unitType.name as type, " . "nation.side_id as sideId, nation.name as nation FROM {$unitTable} " . "LEFT JOIN unit ON unit_id = unit.id " . "LEFT JOIN nation ON nation_id = nation.id " . "LEFT JOIN unitType on unitType_id = unitType.id " . "WHERE loc != 0 " . "ORDER BY {$unitTable}.loc";
             $unitsQ = DBP::query($sql);
             $outputArr = array();
             foreach ($unitsQ->rows as $unit) {
                 $outputArr[$unit->id] = array('unitName' => $unit->unitName, 'loc' => $unit->loc, 'type' => $unit->type, 'nation' => $unit->nation, 'sideId' => $unit->sideId);
             }
             echo json_encode($outputArr);
             break;
         case 'recruitable':
             $sql = "SELECT {$unitTable}.id, IF( ISNULL(unit.name),CONCAT(nation.name, ' ', unitType.name, ' (', COUNT({$unitTable}.id), ' remaining)'),unit.name) AS unitName " . "FROM {$unitTable} " . "LEFT JOIN unit ON {$unitTable}.unit_id = unit.id " . "LEFT JOIN nation ON nation.id = nation_id " . "LEFT JOIN unitType ON unitType.id = unitType_id " . "WHERE loc = 0 AND ( side_id = 2 || casualty != 1 ) AND unit.unitType_id <= 4 " . "GROUP BY CONCAT(nation.name, ' ', unitType.name) " . "UNION ALL " . "SELECT {$unitTable}.id, unit.name AS unitName FROM {$unitTable} " . "LEFT JOIN unit ON {$unitTable}.unit_id = unit.id " . "LEFT JOIN nation ON nation.id = nation_id " . "LEFT JOIN unitType ON unitType.id = unitType_id " . "WHERE loc = 0 AND casualty != 1 AND unit.unitType_id >= 5 " . "ORDER BY id";
             $units = DBP::query($sql, NULL, NULL, 'keyPair');
             echo json_encode($units->rows);
             break;
         case 'recruit':
             $unitID = $request->getProperty('unit');
             $regionID = $request->getProperty('region');
             if ($regionID && $unitID) {
                 $sql = "UPDATE {$unitTable} SET loc = ? WHERE id = ?";
                 $pA = array($regionID, $unitID);
                 DBP::query($sql, $pA);
                 echo "Unit recruited.";
             } else {
                 echo "Please select a unit to recruit.";
             }
             break;
         case 'move':
             $unitIDs = $request->getProperty('selectedUnits');
             $dest = $request->getProperty('dest');
             if (is_array($unitIDs)) {
                 $qMarks = str_repeat('?,', count($unitIDs) - 1) . '?';
                 $sql = "UPDATE {$unitTable} SET loc = ? WHERE id IN ({$qMarks})";
                 array_unshift($unitIDs, $dest);
                 DBP::query($sql, $unitIDs);
                 echo "Units moved";
             } else {
                 echo "Please select units to move";
             }
             break;
         case 'remove':
             $unitIDs = $request->getProperty('selectedUnits');
             $casualty = $request->getProperty('casualty');
             if (is_array($unitIDs)) {
                 $qMarks = str_repeat('?,', count($unitIDs) - 1) . '?';
                 $sql = "UPDATE {$unitTable} SET loc = 0, casualty = ? WHERE id IN ({$qMarks})";
                 array_unshift($unitIDs, $casualty);
                 DBP::query($sql, $unitIDs);
                 echo "Units removed";
             } else {
                 echo "Please select units to remove";
             }
             break;
         case 'reduce':
             $unitIDs = $request->getProperty('selectedUnits');
             $regionID = $request->getProperty('region');
             $return = '';
             foreach ($unitIDs as $unitID) {
                 $sql = "SELECT nation_id FROM {$unitTable} " . "LEFT JOIN unit ON {$unitTable}.unit_id = unit.id " . "WHERE {$unitTable}.id = ?";
                 $result = DBP::query($sql, array($unitID));
                 $nation = $result->nation_id;
                 $sql = "SELECT {$unitTable}.id, casualty FROM {$unitTable} " . "LEFT JOIN unit ON {$unitTable}.unit_id = unit.id " . "WHERE nation_id = ? AND loc = 0 AND unitType_id = 1 " . "ORDER BY casualty DESC";
                 $regulars = DBP::query($sql, array($nation));
                 if ($regulars->getRows()) {
                     $sql = "UPDATE {$unitTable} SET loc = 0, casualty = 1 WHERE id = ?";
                     $pA = array($unitID);
                     DBP::query($sql, $pA);
                     $sql = "UPDATE {$unitTable} SET loc = ?, casualty = 0 WHERE id = ?";
                     $pA = array($regionID, $regulars->id);
                     DBP::query($sql, $pA);
                     $return = 'Elite reduced';
                 } else {
                     $return = 'No regular to reduce elite';
                 }
             }
             echo $return;
     }
 }
Example #14
0
 /**
  * @Route("/admin/page/row/update/template/{id}", name = "page_update_sect_template" )
  * @Template
  */
 public function UpdateTemplateBlocRowAction($id, Request $request)
 {
     $class = $request->request->get('contenu');
     if (!is_numeric($class)) {
         return new Response('error', 400);
     }
     $em = $this->getDoctrine()->getManager();
     if ($request->isXMLHttpRequest()) {
         $section = $em->getRepository('PageBundle:PgBlocrow')->find($id);
         if ($class == 0) {
             if (!$section) {
                 return new Response('error', 400);
             }
             $section->setTemplate(NULL);
             $em->flush();
             return new Response('ok');
         } else {
             $template = $em->getRepository('PageBundle:PgRowTemplate')->find($class);
             if ($template) {
                 if (!$section) {
                     return new Response('error', 400);
                 }
                 $section->setTemplate($template);
                 $em->flush();
                 return new Response('ok');
             } else {
                 return new Response('template(' . $class . ')', 400);
             }
         }
     }
     return new Response('error', 400);
 }
Example #15
0
 /**
  * @Route("/add/site/{id}", name="address_site_add")
  * @Template()
  */
 public function addFromSiteAction(Request $request, $id)
 {
     if ($request->isXMLHttpRequest()) {
     }
     if ($id == 0) {
         throw new Exception('id is needed in the function addAction from AddressController');
     }
     $address = new Address();
     $form = $this->createForm(new AddressType(), $address);
     $form->add('save', 'submit');
     if ($form->handleRequest($request)->isValid() || $request->isXMLHttpRequest()) {
         $em = $this->getDoctrine()->getManager();
         $site = $em->getRepository('SiteBundle:Site')->find($id);
         if ($site == null) {
             throw new Exception('siteId is invalid  in the function addAction from AddressController');
         }
         $site->addAddress($address);
         $address->setSite($site);
         $em->persist($address);
         $em->flush();
         return $this->redirect($this->generateUrl('site_show', array('id' => $site->getId()), 301));
     }
     return $this->render('CoordinateBundle:Address:add.html.twig', array('form' => $form->createView()));
 }
Example #16
0
 public function saveAction(Request $request)
 {
     if ($request->isXMLHttpRequest()) {
         $em = $this->getDoctrine()->getManager();
         $newData = json_decode($request->get('newdata', ''));
         $delData = json_decode($request->get('deldata', ''));
         $noticeInstructor_id = array();
         $noticeInstructors = array();
         $noticeClass_id = array();
         $noticeClasses = array();
         //add new data
         foreach ($newData as $new) {
             foreach ($new->detail as $detail_data) {
                 $detail = new ScheduleDetail();
                 $course = $em->getRepository('QTUTkbBundle:Course')->find(intval($new->id));
                 $room = $em->getRepository('QTUTkbBundle:Room')->find(intval($detail_data->room));
                 $ok = true;
                 if ($course != null) {
                     $detail->setCourse($course);
                 } else {
                     $ok = false;
                 }
                 if ($room != null) {
                     $detail->setRoom($room);
                 } else {
                     $ok = false;
                 }
                 if ($ok) {
                     //                        $detail->setDateOccur(date("d-m-Y", $this->converDate($detail_data->dateOccur)));
                     $detail->setDateOccur(\DateTime::createFromFormat('d/m/Y', $detail_data->dateOccur));
                     //                        var_dump(date("d-m-Y", $this->converDate($detail_data->dateOccur)));
                     $detail->setPeriod($detail_data->period);
                     $detail->setTypeDetail($detail_data->type);
                     $em->persist($detail);
                     //get instructors list to mail
                     foreach ($course->getInstructors() as $instructor) {
                         if (!in_array($instructor->getId(), $noticeInstructor_id)) {
                             $noticeInstructor_id[] = $instructor->getId();
                             $noticeInstructors[] = $instructor;
                         }
                     }
                     //get classes list to mail
                     foreach ($course->getClasses() as $class) {
                         if (!in_array($class->getId(), $noticeClass_id)) {
                             $noticeClass_id[] = $class->getId();
                             $noticeClasses[] = $class;
                         }
                     }
                 }
             }
         }
         //deldata
         foreach ($delData as $idData) {
             $detail = $em->getRepository('QTUTkbBundle:ScheduleDetail')->find($idData);
             if ($detail != null) {
                 $em->remove($detail);
                 //get instructors list to mail
                 $instructors = $detail->getCourse()->getInstructors();
                 foreach ($instructors as $instructor) {
                     if (!in_array($instructor->getId(), $noticeInstructor_id)) {
                         $noticeInstructor_id[] = $instructor->getId();
                         $noticeInstructors[] = $instructor;
                     }
                 }
                 //get classes list to mail
                 $classes = $detail->getCourse()->getClasses();
                 foreach ($classes as $class) {
                     if (!in_array($class->getId(), $noticeClass_id)) {
                         $noticeClass_id[] = $class->getId();
                         $noticeClasses[] = $class;
                     }
                 }
             }
         }
         $em->flush();
         //mail to Instructors
         foreach ($noticeInstructors as $instructor) {
             if ($instructor->getEmail() != '') {
                 $message = \Swift_Message::newInstance()->setSubject('[TKB] THÔNG BÁO THAY ĐỔI LỊCH GIẢNG')->setFrom('*****@*****.**')->setTo($instructor->getEmail())->setBody($this->renderView('QTUTkbBundle:SwiftMailer:changetimetable.html.twig', array('user' => $instructor)));
                 $message->setContentType("text/html");
                 $this->get('mailer')->send($message);
             }
         }
         //mail to class
         foreach ($noticeClasses as $class) {
             $emails = array_filter(explode(',', str_replace(' ', '', $class->getEmail())));
             if (count($emails) > 0) {
                 $message = \Swift_Message::newInstance()->setSubject('[TKB] THÔNG BÁO THAY ĐỔI LỊCH GIẢNG')->setFrom('*****@*****.**')->setTo($emails)->setBody($this->renderView('QTUTkbBundle:SwiftMailer:changetimetable_class.html.twig', array('classP' => $class)));
                 $message->setContentType("text/html");
                 $this->get('mailer')->send($message);
             }
         }
         $response = new JsonResponse(array('success' => 'success'));
         $response->headers->set('Content-Type', 'application/json');
         return $response;
     }
 }
Example #17
0
 /**
  * @Route("/ajax/saleorderline/number/{productNumber}", name="_saleorderline_product_by_number", options={"expose"=true})
  */
 public function getProductByProductNumber(Request $request, $productNumber)
 {
     $repository = $this->getDoctrine()->getRepository('AppBundle:Product');
     if ($request->isXMLHttpRequest()) {
         // Get Product
         $product = $repository->findOneByProductNumber($productNumber);
         if (!$product) {
             return new JsonResponse(json_encode(array()));
         }
         $arr = array();
         $arr['productNumber'] = $product->getProductNumber();
         $arr['name'] = $product->getShortName();
         $arr['basePrice'] = $product->getBasePrice();
         $arr['mwstSatz'] = $product->getMwstSatz();
         $json = json_encode($arr);
         return new JsonResponse($json);
     }
     return new Response('This is not ajax!', 400);
 }
 private function persistCommentUpdate(Request $request, Blog $blog, Post $post, Comment $comment, User $user, array $messages)
 {
     $form = $this->createForm($this->get('icap_blog.form.comment'), $comment);
     if ($request->isXMLHttpRequest()) {
         return $this->render('IcapBlogBundle:Comment:inlineEdit.html.twig', array('_resource' => $blog, 'post' => $post, 'comment' => $comment, 'workspace' => $blog->getResourceNode()->getWorkspace(), 'form' => $form->createView()));
     } else {
         if ("POST" === $request->getMethod()) {
             $form->handleRequest($request);
             if ($form->isValid()) {
                 $flashBag = $this->get('session')->getFlashBag();
                 $entityManager = $this->getDoctrine()->getManager();
                 try {
                     $unitOfWork = $entityManager->getUnitOfWork();
                     $unitOfWork->computeChangeSets();
                     $changeSet = $unitOfWork->getEntityChangeSet($comment);
                     $entityManager->persist($comment);
                     $entityManager->flush();
                     $this->dispatchCommentUpdateEvent($post, $comment, $changeSet);
                     $flashBag->add('success', $messages['success']);
                 } catch (\Exception $exception) {
                     $flashBag->add('error', $messages['error']);
                 }
                 return $this->redirect($this->generateUrl('icap_blog_post_view', array('blogId' => $blog->getId(), 'postSlug' => $post->getSlug())));
             }
         }
     }
     return array('_resource' => $blog, 'bannerForm' => $this->getBannerForm($blog->getOptions()), 'user' => $user, 'post' => $post, 'comment' => $comment, 'form' => $form->createView());
 }
 /**
  * @Route("/wp-install-plugin", name="_wp-install-plugin")
  */
 public function installPlugins(Request $request)
 {
     if ($request->isXMLHttpRequest()) {
         $session = $request->getSession();
         $userDir = $session->get('user_folder');
         $response = new JsonResponse();
         // Load WordPress Plugin API
         require_once EIconfig::$coreDirectoryPath . $userDir . 'wordpress/wp-load.php';
         require_once EIconfig::$coreDirectoryPath . $userDir . 'wordpress/wp-admin/includes/plugin.php';
         $plugins = $request->request->get('user_plugins');
         // Create a temporary directory for the theme ZIPs
         $tmp_dir_path = EIconfig::$coreDirectoryPath . $userDir . '_tmp/';
         mkdir($tmp_dir_path, 0755);
         /** Download plugin ZIPs, unpack them inside the temporary directory
             move the unpacked folders to /wordpress/wp-content/plugins/ and activate if needed
              */
         foreach ($plugins as $plugin) {
             $plugin = json_decode(json_encode($plugin));
             // Extract ZIP name from URL
             $keys = parse_url($plugin->url);
             $urlPath = explode("/", $keys['path']);
             $zipName = end($urlPath);
             // Get theme directory name
             $pluginDir = strtok($zipName, ".");
             // Download ZIP
             file_put_contents($tmp_dir_path . $zipName, file_get_contents(trim($plugin->url)));
             if (EIcmsHelper::unzipFile($tmp_dir_path . $zipName, $tmp_dir_path)) {
                 // Move plugin directory to wordpress/wp-content/plugins/
                 rename($tmp_dir_path . $pluginDir, EIconfig::$coreDirectoryPath . $userDir . 'wordpress/wp-content/plugins/' . $pluginDir);
             } else {
                 $response->setData(array('action' => 'Installing User Plugins', 'status' => 'error'));
             }
         }
         // Remove temporary directory
         rmdir($tmp_dir_path);
         $response->setData(array('action' => 'Installing User Plugins', 'status' => 'success'));
         return $response;
     }
     return new Response('This is not ajax!', 400);
 }
 /**
  * @Route(
  *      "/{resourceId}/edit/deletecriterion/{page}/{criterionId}/{number}",
  *      name="icap_dropzone_edit_delete_criterion",
  *      requirements={"resourceId" = "\d+", "criterionId" = "\d+", "page" = "\d+", "number" = "\d+"}
  * )
  * @ParamConverter("dropzone", class="IcapDropzoneBundle:Dropzone", options={"id" = "resourceId"})
  * @ParamConverter("criterion", class="IcapDropzoneBundle:Criterion", options={"id" = "criterionId"})
  * @Template()
  */
 public function editDeleteCriterionAction(Request $request, Dropzone $dropzone, $page, $criterion, $number)
 {
     $this->get('icap.manager.dropzone_voter')->isAllowToOpen($dropzone);
     $this->get('icap.manager.dropzone_voter')->isAllowToEdit($dropzone);
     $form = $this->createForm(new CriterionDeleteType(), $criterion);
     $nbCorrection = $this->getDoctrine()->getManager()->getRepository('IcapDropzoneBundle:Correction')->countByDropzone($dropzone->getId());
     if ($request->isXMLHttpRequest()) {
         return $this->render('IcapDropzoneBundle:Criterion:editDeleteCriterionModal.html.twig', array('workspace' => $dropzone->getResourceNode()->getWorkspace(), '_resource' => $dropzone, 'dropzone' => $dropzone, 'criterion' => $criterion, 'form' => $form->createView(), 'page' => $page, 'number' => $number, 'nbCorrection' => $nbCorrection));
     }
     return array('workspace' => $dropzone->getResourceNode()->getWorkspace(), '_resource' => $dropzone, 'dropzone' => $dropzone, 'criterion' => $criterion, 'form' => $form->createView(), 'page' => $page, 'number' => $number, 'nbCorrection' => $nbCorrection);
 }
Example #21
0
 public function ajaxLocationsAction(Request $request)
 {
     if ($request->isXMLHttpRequest()) {
         $locations = $this->getDoctrine()->getRepository("SportnetzwerkSpnBundle:Locations")->getLocations($request->get('zip'), $request->get('sportsId'));
         //trigger_error(var_export($locations, true));
         return new JsonResponse($locations);
     }
     return new Response('No ajax here', 400);
 }
 public function getDataTableAction(Request $req)
 {
     if ($req->isXMLHttpRequest()) {
         $idTable = $req->get('id_table');
         $em = $this->getDoctrine()->getManager();
         $chatTableRepository = $em->getRepository('AGILChatBundle:AgilChatTable');
         $chatTable = $chatTableRepository->find($idTable);
         $table = array('id' => $chatTable->getChatTableId(), 'pwd' => $chatTable->getChatTablePassword());
         return new Response(json_encode($table));
     }
     return new Response("erreur...");
 }
 /**
  * @Route(
  *      "choice-move/{resourceId}/{chapterId}",
  *      name="icap_lesson_choice_move_chapter",
  *      requirements={"resourceId" = "\d+", "chapterId" = "\d+"},
  *      options = {"expose"=true}
  * )
  * @Template()
  * @ParamConverter("lesson", class="IcapLessonBundle:Lesson", options={"id" = "resourceId"})
  */
 public function choiceMoveChapterAction($lesson, $chapterId, Request $request)
 {
     $this->checkAccess('EDIT', $lesson);
     $chapter = $this->findChapter($lesson, $chapterId);
     $form = $this->createForm($this->get('icap.lesson.movechaptertype'), $chapter, array('attr' => array('filter' => 1)));
     $form->handleRequest($this->container->get('request_stack')->getCurrentRequest());
     //for ajaxification
     if ($request->isXMLHttpRequest()) {
         return $this->render('IcapLessonBundle:Lesson:choiceMoveChapterAjaxified.html.twig', array('_resource' => $lesson, 'chapter' => $chapter, 'form' => $form->createView(), 'workspace' => $lesson->getResourceNode()->getWorkspace()));
     }
     return array('_resource' => $lesson, 'chapter' => $chapter, 'form' => $form->createView(), 'workspace' => $lesson->getResourceNode()->getWorkspace());
 }
 /**
  * @Route("/ajax")
  */
 public function ajaxAction(Request $request)
 {
     # Process scores and return top 10 and worst 10 results (with scores).
     $scoresArrayPre = $request->request->all();
     # Format underscores to spaces.
     $scoresArray = array();
     foreach ($scoresArrayPre as $game => $score) {
         $newGame = str_replace("_", " ", $game);
         $scoresArray[$newGame] = $score;
     }
     $jsonFile = fopen("resources/gamedata.json", "r");
     $jsonPhp = json_decode(fread($jsonFile, filesize("resources/gamedata.json")), true);
     fclose($jsonFile);
     # Find critics that have at least one game in common.
     $userGames = array_keys($scoresArray);
     $commonCritics = array();
     foreach ($jsonPhp as $critic => $gameData) {
         $criticGames = array_keys($gameData);
         if (count(array_intersect($userGames, $criticGames)) != 0) {
             $commonCritics[$critic] = $gameData;
         }
     }
     # Compare each commonCritics to userGames and compile similarity scores via Pearson correlation coefficient.
     $scores = array();
     $testArray = array();
     foreach ($commonCritics as $critic => $gameData) {
         $commonGames = array_intersect($userGames, array_keys($gameData));
         $userSum = 0;
         $criticSum = 0;
         $userSumSq = 0;
         $criticSumSq = 0;
         $prodSum = 0;
         foreach ($commonGames as $game) {
             $userSum += $scoresArray[$game];
             $criticSum += $commonCritics[$critic][$game];
             $userSumSq += pow($scoresArray[$game], 2);
             $criticSumSq += pow($commonCritics[$critic][$game], 2);
             $prodSum += $scoresArray[$game] * $commonCritics[$critic][$game];
         }
         # array_push($testArray, array($userSum, $criticSum, $userSumSq, $criticSumSq, $prodSum));
         # Calculate Pearson.
         # !? Zero Denominator! ?!
         $numerator = $prodSum - $userSum * $criticSum / count($commonGames);
         $denominator = sqrt(($userSumSq - pow($userSum, 2) / count($commonGames)) * ($criticSumSq - pow($criticSum, 2) / count($commonGames)));
         if ($denominator == 0) {
             $pearsonScore = -1;
         } else {
             $pearsonScore = $numerator / $denominator;
         }
         $scores[$critic] = $pearsonScore;
     }
     # Rank critics by score (highest to lowest).
     arsort($scores);
     # Produce weighed list of critic reviewed games.
     $weighedScores = array();
     foreach ($scores as $criticName => $weight) {
         $newGameArray = array();
         $toChange = $commonCritics[$criticName];
         foreach ($toChange as $game => $score) {
             if (in_array($game, $userGames) === false) {
                 $newScore = $score * $weight;
                 $newGameArray[$game] = $newScore;
             }
         }
         $weighedScores[$criticName] = $newGameArray;
     }
     # Clear some memory.
     $jsonPhp = "";
     $commonCritics = "";
     # Add and average game totals to generate recommendation list.
     # {Game: {Total Points, Total Weight}}
     $gameArrayPre = array();
     foreach ($weighedScores as $critic => $gameData) {
         $currentGames = array_keys($gameArrayPre);
         foreach ($gameData as $game => $score) {
             if (in_array($game, $currentGames)) {
                 $oldPoints = $gameArrayPre[$game][0];
                 $oldWeight = $gameArrayPre[$game][1];
                 $newPoints = $oldPoints + $score;
                 $newWeight = $oldWeight + $scores[$critic];
                 $updatedArray = array($newPoints, $newWeight);
                 $gameArrayPre[$game] = $updatedArray;
             } else {
                 $points = $score;
                 $weight = $scores[$critic];
                 $newArray = array($points, $weight);
                 $gameArrayPre[$game] = $newArray;
             }
         }
     }
     # Average. {Game: Recommended Points}
     $gameArray = array();
     foreach ($gameArrayPre as $game => $toDivide) {
         if ($toDivide[1] == 0) {
             $dividedAmt = 0;
         } else {
             $dividedAmt = $toDivide[0] / $toDivide[1];
             #? Move? ?
             $gameArray[$game] = $dividedAmt;
         }
     }
     arsort($gameArray);
     # Return top 10 and bottom 10 as {Game: Score} JSON array.
     $returnArray = array();
     if (count($gameArray) >= 20) {
         $keys = array_keys($gameArray);
         for ($i = 0; $i < 10; $i++) {
             $nameIndex = $keys[$i];
             array_push($returnArray, array($nameIndex, $gameArray[$nameIndex]));
         }
         $reverse = array_reverse($gameArray);
         $keys = array_keys($reverse);
         for ($i = 0; $i < 10; $i++) {
             $nameIndex = $keys[$i];
             array_push($returnArray, array($nameIndex, $reverse[$nameIndex]));
         }
     }
     if ($request->isXMLHttpRequest()) {
         return new JsonResponse($returnArray);
     }
     return new Response("This in not ajax!", 400);
 }
Example #25
-1
 /**
  * @Route("/set/{_locale}", name="orkestro_backend_locale_set")
  * @Method("POST")
  */
 public function setLocaleAction(Request $request)
 {
     if ($request->isXMLHttpRequest()) {
         return new Response(json_encode(array('status' => 0)));
     }
     throw $this->createNotFoundException();
 }