Ejemplo n.º 1
1
 /**
  * {@inheritdoc}
  */
 public function apply(base $appbox, Application $app)
 {
     $conn = $app['phraseanet.appbox']->get_connection();
     $sql = 'SELECT date, login, ip, locked
             FROM badlog
             ORDER BY id ASC';
     $stmt = $conn->prepare($sql);
     $stmt->execute();
     $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
     $stmt->closeCursor();
     $n = 1;
     foreach ($rs as $row) {
         $date = Datetime::createFromFormat('Y-m-d h:i:s', $row['date']);
         $failure = new AuthFailure();
         if ($date) {
             $failure->setCreated($date);
         }
         $failure->setIp($row['ip']);
         $failure->setLocked(!!$row['locked']);
         $failure->setUsername($row['login']);
         $app['EM']->persist($failure);
         if (0 === $n++ % 1000) {
             $app['EM']->flush();
             $app['EM']->clear();
         }
     }
     $app['EM']->flush();
     $app['EM']->clear();
     return true;
 }
 private function groupAbsencesByMonth($absences)
 {
     $grouped_by_month = array();
     foreach ($absences as &$a) {
         $a["start"] = \Datetime::createFromFormat('Y-m-d', $a["start"]);
         $a["end"] = \Datetime::createFromFormat('Y-m-d', $a["end"]);
         $a["count"] = 1;
         if ($a["start"] < $a["end"]) {
             $a["count"] = $a["start"]->diff($a["end"])->format("%a") + 0;
         }
         $grouped_by_month[$a["month"]][] = $a;
     }
     $table_array = array();
     foreach ($grouped_by_month as $month_number => $absences) {
         $count = 0;
         $table_array[$month_number] = array();
         foreach ($absences as $absence) {
             $table_array[$month_number][$absence["type"]][] = $absence;
         }
     }
     $final_table_array = array();
     foreach ($table_array as $month => $grouped_by_month) {
         $final_table_array[$month] = array();
         $final_table_array[$month]["total"] = 0;
         foreach ($grouped_by_month as $type => $grouped_by_type) {
             $final_table_array[$month][$type] = array();
             $final_table_array[$month][$type]["total"] = 0;
             $final_table_array[$month][$type]["times"] = 0;
             $final_table_array[$month][$type]["with_pay"] = 0;
             $final_table_array[$month][$type]["without_pay"] = 0;
             foreach ($grouped_by_type as $absence) {
                 $final_table_array[$month][$type]["total"] += $absence["count"];
                 $final_table_array[$month][$type]["times"]++;
                 if ($absence["with_pay"]) {
                     $final_table_array[$month][$type]["with_pay"]++;
                 } else {
                     $final_table_array[$month][$type]["without_pay"]++;
                 }
                 $final_table_array[$month]["total"] += $absence["count"];
             }
         }
     }
     return $final_table_array;
 }
Ejemplo n.º 3
0
 /**
  * Get version
  *
  * @access public
  * @return Datetime $version
  */
 public function get_version()
 {
     $classname = get_class($this);
     // Migration_20150922_203123_Init
     list($migration, $date, $time, $name) = explode('_', $classname);
     return \Datetime::createFromFormat('YmdHis', $date . $time);
 }
Ejemplo n.º 4
0
 public function createParticipation($user, $drink)
 {
     $dDrink = \Datetime::createFromFormat('Y-m-d H:i:s', $drink['day'] . ' ' . $drink['hour']);
     $dEndDrink = clone $dDrink;
     $dEndDrink->modify('+3 hours');
     $dateFormat = 'Ymd\\THis';
     $icsInvite = \Swift_Attachment::newInstance()->setContentType('text/calendar;charset=UTF-8;method=REQUEST')->setBody($this->twig->render('drink/invite_ics.twig', array('user' => $user, 'drink' => $drink, 'datetimes' => array('start' => $dDrink->format($dateFormat), 'end' => $dEndDrink->format($dateFormat), 'current' => date($dateFormat)))))->setEncoder(\Swift_Encoding::getQpEncoding());
     return $this->mailer->createMessage()->setSubject('[Aperophp.net] Inscription à un ' . $drink['kind'])->setFrom(array('*****@*****.**'))->setTo(array($user['email']))->setBody($this->twig->render('drink/participation_mail.html.twig', array('user' => $user, 'drink' => $drink)), 'text/html')->attach($icsInvite);
 }
Ejemplo n.º 5
0
 /**
  * Transforme une chaine date au format time CDA
  *
  * @param String $date      String
  * @param bool   $naissance false
  *
  * @return string
  */
 function getTimeToUtc($date, $naissance = false)
 {
     if (!$date) {
         return null;
     }
     if ($naissance) {
         $date = Datetime::createFromFormat("Y-m-d", $date);
         return $date->format("Ymd");
     }
     $timezone = new DateTimeZone(CAppUI::conf("timezone"));
     $date = new DateTime($date, $timezone);
     return $date->format("YmdHisO");
 }
 public function saveAction(Request $request)
 {
     $params = $request->all();
     $params['day'] = Date::conversion($params['day']);
     $request->replace($params);
     unset($params['_token'], $params['q']);
     $routeBack = $request->get('redirect', false);
     if (!$routeBack) {
         $routeBack = 'hours-control.new';
         if (isset($params['id']) && (int) $params['id'] > 0) {
             $routeBack = 'hours-control.edit';
         }
     }
     if ($request->getMethod() == 'POST') {
         // saving data!
         $isValid = $this->repository->validateRequest($request);
         if (!is_bool($isValid)) {
             $request->session()->flash('message', "Invalid data, please check the following errors: ");
             $request->session()->flash('validationErrros', $isValid);
             $formattedDate = \Datetime::createFromFormat('Y-m-d', $request->get('day'));
             $request->replace(['day' => $formattedDate->format('d/m/Y')]);
             return redirect()->route($routeBack, [$routeBack == 'hours-control.edit' ? $params['id'] : null])->withInput()->with('validationErrors', $isValid);
         }
         //update
         if ($routeBack == 'hours-control.edit') {
             $hourControl = $this->repository->findById($params['id']);
             if (!$hourControl) {
                 $request->session()->flash('message', "Register [{$params['id']}] not found");
                 return redirect('hours-control');
             }
             $hourControl = HoursControl::findOrNew($params['id']);
             $hourControl->fill($params);
             $hourControl->update();
             $request->session()->flash('message', "Register [{$hourControl->task}] updated successfully!");
             $request->session()->flash('success', true);
             return redirect('hours-control');
         }
         //insert
         $hourControls = new HoursControl();
         $hourControls->create($params);
         $request->session()->flash('message', "Successfully created register");
         $request->session()->flash('success', true);
         $redirect = $request->get('redirect', false) != false ? $request->get('redirect') : 'hours-control';
         return redirect()->route($redirect);
     }
     $request->session()->flash('message', "Method not allowed");
     return redirect('hours-control');
 }
Ejemplo n.º 7
0
 /**
  * @param array $input
  * @return mixed
  */
 public function __invoke(array $input)
 {
     if (!isset($input['month'])) {
         return $this->payload->setStatus(PayloadStatus::ERROR)->setInput($input)->setOutput("Month cannot be blank e.g. '?month=2016-02'");
     }
     if (!\Datetime::createFromFormat('Y-m', $input['month'])) {
         return $this->payload->setStatus(PayloadStatus::ERROR)->setInput($input)->setOutput("Month is incorrect format e.g. '?month=2016-02'");
     }
     $month_start = Carbon::createFromFormat('Y-m', $input['month'])->startOfMonth();
     $month_end = Carbon::createFromFormat('Y-m', $input['month'])->endOfMonth();
     $shifts = $this->shift->where('employee_id', '=', $input['id'])->where('start_time', '>=', $month_start)->where('start_time', '<=', $month_end)->get();
     $hours = ['total_shifts' => $shifts->count(), 'total_hours' => 0];
     foreach ($shifts as $shift) {
         $hours['total_hours'] += $shift->start_time->diffInHours($shift->end_time);
     }
     return $this->payload->setStatus(PayloadStatus::SUCCESS)->setOutput($hours);
 }
Ejemplo n.º 8
0
 /**
  * convert date to timestamp
  * @param string $value
  * @param string $format
  * @return string
  */
 public static function dateToTimestamp($value, $format)
 {
     if ($value == '') {
         return 0;
     }
     if (strpos($format, '%') !== false) {
         $date = strptime($value, $format);
         if (is_array($date)) {
             return mktime($date['tm_hour'], $date['tm_min'], $date['tm_sec'], $date['tm_mon'] + 1, $date['tm_mday'], 1900 + $date['tm_year']);
         } else {
             return 0;
         }
     } else {
         $date = \Datetime::createFromFormat($format, $value);
         return $date->getTimestamp();
     }
 }
Ejemplo n.º 9
0
 public function calendarAction()
 {
     $calendar = $this->getServiceLocator()->get('calendar');
     $date = $this->params('date');
     $startDay = \Datetime::createFromFormat('Ymd H:i:s', $date . ' 08:00:00');
     $endDay = \Datetime::createFromFormat('Ymd H:i:s', $date . ' 21:00:00');
     $optParams = ['orderBy' => 'startTime', 'singleEvents' => TRUE, 'timeMin' => $startDay->format(\Datetime::ATOM), 'timeMax' => $endDay->format(\Datetime::ATOM)];
     $config = $this->getServiceLocator()->get('config');
     $results = $calendar->events->listEvents($config['api']['googleapi']['calendarId'], $optParams);
     if ($startDay->format('l') == 'Monday') {
         $dates = [0 => 'Heure', 10 => '10h00', 11 => '11h00', 12 => '12h00', 13 => '13h00', 15 => '15h00', 16 => '16h00', 17 => '17h00', 18 => '18h00', 19 => '19h00', 20 => '20h00'];
     } else {
         $dates = [0 => 'Heure', 9 => '09h00', 10 => '10h00', 11 => '11h00', 12 => '12h00', 13 => '13h00', 15 => '15h00', 16 => '16h00'];
     }
     if (count($results->getItems())) {
         foreach ($results->getItems() as $event) {
             if ($start = $event->start->dateTime) {
                 $end = $event->end->dateTime;
                 $startDate = \Datetime::createFromFormat(\Datetime::ATOM, $start);
                 if (!in_array($startDate->format('l'), ['Monday', 'Tuesday'])) {
                     continue;
                 }
                 $endDate = \Datetime::createFromFormat(\Datetime::ATOM, $end);
                 for ($i = $startDate->format('H'); $i < $endDate->format('H'); $i++) {
                     unset($dates[$i]);
                 }
             } else {
                 if ($start = $event->start->date) {
                     $dates = [0 => 'Aucune Place'];
                 }
             }
         }
     }
     if (count($dates) == 1) {
         $dates = [0 => 'Aucune Place'];
     }
     $view = new ViewModel(array('result' => $dates));
     $view->setTerminal(true);
     $view->setTemplate('app/index/json.phtml');
     return $view;
 }
Ejemplo n.º 10
0
 public function PostEvent(Request $request)
 {
     $eventId = $request->input('event_id');
     $article = $request->input('article');
     $startDate = $request->input('start_date');
     $startTime = $request->input('start_time');
     $endDate = $request->input('end_date');
     $endTime = $request->input('end_time');
     $format = 'Y-m-d H:i';
     $startDateTime = \Datetime::createFromFormat($format, $startDate . ' ' . $startTime);
     $endDateTime = \Datetime::createFromFormat($format, $endDate . ' ' . $endTime);
     $errors = array();
     if (Article::find($article) == null) {
         array_push($errors, "L'article séléctionné n'est pas valide.");
     }
     if ($startDateTime > $endDateTime) {
         array_push($errors, "La date de fin ne peut pas être antérieure à la date de début.");
     }
     if ($endDateTime < new \Datetime('NOW')) {
         array_push($errors, "La date de fin ne peut pas être antérieure à la date actuelle.");
     }
     if (count($errors) == 0) {
         if ($eventId == null) {
             $event = new Event();
             $motif = 'ajouté';
         } else {
             $event = Event::find($eventId);
             $motif = 'modifié';
         }
         $event->article_id = $article;
         $event->start_date = $startDateTime;
         $event->end_date = $endDateTime;
         $event->save();
         Session::flash('success', 'Evenement #' . $event->id . ' ' . $motif . ' avec succès.');
         return redirect()->route('adminEvents');
     }
     Session::flash('errors', $errors);
     return redirect()->back()->withInput();
 }
Ejemplo n.º 11
0
            echo "<SCRIPT language=\"javascript\">";
            echo "top.location.href=\"/src/series2/accueil.php\";";
            echo "</SCRIPT>";
            return;
        }
    }
}
$data = $pool->getConfigPool($id_pool, $id_saison);
$nbre_periode = $data["nbre_periodes"];
$last_position_series = $data["last_position_series"];
$nbre_teams_in_alignement = $data["nbre_team"];
$allPlayersActive = $data['all_players_active'];
$str_fil_ariane = "Accueil";
// date de la derniere maj
$dateSec = $pool->getLastMAJ($id_pool);
$_mydate = Datetime::createFromFormat('Y-m-d H:i:s', $dateSec, $pool->timeZone);
$jour = $_mydate->format('j');
$jour_semaine = $_mydate->format('D');
switch ($jour_semaine) {
    case "Mon":
        $jour_semaine = "Lun.";
        break;
    case "Tue":
        $jour_semaine = "Mar.";
        break;
    case "Wed":
        $jour_semaine = "Mer.";
        break;
    case "Thu":
        $jour_semaine = "Jeu.";
        break;
Ejemplo n.º 12
0
 public function connect(Application $app)
 {
     $controllers = $app['controllers_factory'];
     // *******
     // ** Save/Update participation
     // *******
     $controllers->post('{drinkId}/register.html', function (Request $request, $drinkId) use($app) {
         $returnValue = $request->isXmlHttpRequest() ? 'redirect' : $app->redirect($app['url_generator']->generate('_showdrink', array('id' => $drinkId)));
         $drink = $app['drinks']->find($drinkId);
         if (!$drink) {
             $app->abort(404, 'Cet événement n\'existe pas.');
         }
         $now = new \Datetime('now');
         $dDrink = \Datetime::createFromFormat('Y-m-d H:i:s', $drink['day'] . ' ' . $drink['hour']);
         if ($now > $dDrink) {
             $app['session']->getFlashBag()->add('error', 'L\'événement est terminé.');
             return $returnValue;
         }
         $user = $app['session']->get('user');
         $form = $app['form.factory']->create('drink_participate');
         $form->bind($request->request->get('drink_participate'));
         if ($form->isValid()) {
             $data = $form->getData();
             $member = $app['session']->get('member');
             $user = $app['session']->get('user');
             if (null === $user) {
                 $data['user']['token'] = sha1(md5(rand()) . microtime(true) . md5(rand()));
                 try {
                     $app['users']->insert($data['user']);
                 } catch (\Exception $e) {
                     $app->abort(500, 'Impossible de vous créer un compte. Merci de réessayer plus tard.');
                 }
                 // Load User in session
                 $id = $app['users']->lastInsertId();
                 $user = $app['users']->find($id);
                 $app['session']->set('user', $user);
             } elseif (null === $member) {
                 try {
                     $app['users']->update($data['user'], array('id' => $user['id']));
                 } catch (\Exception $e) {
                     $app->abort(500, 'Impossible de modifier votre compte. Merci de réessayer plus tard.');
                 }
             }
             // Already participating?
             $participation = $app['drink_participants']->findOne($drinkId, $user['id']);
             if (false !== $participation) {
                 $participation['percentage'] = $data['percentage'];
                 $participation['reminder'] = $data['reminder'];
                 try {
                     $app['drink_participants']->update($participation, array('drink_id' => $drinkId, 'user_id' => $user['id']));
                 } catch (\Exception $e) {
                     $app->abort(500, 'Impossible de sauvegarder votre participation. Merci de réessayer plus tard.');
                 }
                 $app['session']->getFlashBag()->add('success', 'Participation modifiée.');
                 return $returnValue;
             }
             $participation['percentage'] = $data['percentage'];
             $participation['reminder'] = (bool) $data['reminder'];
             $participation['user_id'] = $user['id'];
             $participation['drink_id'] = $drinkId;
             try {
                 $app['drink_participants']->insert($participation);
             } catch (\Exception $e) {
                 $app->abort(500, 'Impossible de sauvegarder votre participation. Merci de réessayer plus tard.');
             }
             $app['session']->getFlashBag()->add('success', 'Participation ajoutée.');
             if ($participation['percentage'] > 0) {
                 $app['mailer']->send($app['mail_factory']->createParticipation($user, $drink));
             }
             return $returnValue;
         }
         $app['session']->getFlashBag()->add('error', 'Le formulaire de participation est mal remplis.');
         return $returnValue;
     })->bind('_participatedrink');
     // *******
     // *******
     // ** Delete participation
     // *******
     $controllers->get('{drinkId}/delete.html/{email}/{token}', function (Request $request, $drinkId, $email, $token) use($app) {
         $drink = $app['drinks']->find($drinkId);
         if (!$drink) {
             $app->abort(404, 'Cet événement n\'existe pas.');
         }
         $now = new \Datetime('now');
         $dDrink = \Datetime::createFromFormat('Y-m-d H:i:s', $drink['day'] . ' ' . $drink['hour']);
         if ($now > $dDrink) {
             $app['session']->getFlashBag()->add('error', 'L\'événement est terminé.');
             return $app->redirect($app['url_generator']->generate('_showdrink', array('id' => $drinkId)));
         }
         if (!$app['session']->has('user')) {
             if (null === $email || null === $token) {
                 $app['session']->getFlashBag()->add('error', 'Connectez-vous ou utilisez le lien reçu par mail.');
                 return $app->redirect($app['url_generator']->generate('_showdrink', array('id' => $drinkId)));
             }
             if (!($user = $app['users']->findOneByEmailToken($email, $token))) {
                 $app['session']->getFlashBag()->add('error', 'Couple email/jeton invalide.');
                 return $app->redirect($app['url_generator']->generate('_showdrink', array('id' => $drinkId)));
             }
             $app['session']->set('user', $user);
         }
         $user = $app['session']->get('user');
         $participation = $app['drink_participants']->findOne($drinkId, $user['id']);
         if (false === $participation) {
             $app['session']->getFlashBag()->add('error', 'Participation inexistante.');
             return $app->redirect($app['url_generator']->generate('_showdrink', array('id' => $drinkId)));
         }
         try {
             $app['drink_participants']->delete(array('drink_id' => $participation['drink_id'], 'user_id' => $participation['user_id']));
         } catch (\Exception $e) {
             $app->abort(500, 'Impossible de sauvegarder votre participation. Merci de réessayer plus tard.');
         }
         $app['session']->getFlashBag()->add('success', 'Participation supprimée avec succès.');
         return $request->isXmlHttpRequest() ? 'redirect' : $app->redirect($app['url_generator']->generate('_showdrink', array('id' => $drinkId)));
     })->value('email', null)->value('token', null)->bind('_deleteparticipatedrink');
     // *******
     // ** Request to resend an user token
     // *******
     $controllers->match('{drinkId}/forget.html', function (Request $request, $drinkId) use($app) {
         if ($app['session']->has('member')) {
             $app['session']->getFlashBag()->add('error', 'Vous êtes déjà authentifié.');
             return $app->redirect($app['url_generator']->generate('_showdrink', array('id' => $drinkId)));
         }
         $drink = $app['drinks']->find($drinkId);
         if (!$drink) {
             $app->abort(404, 'Cet événement n\'existe pas.');
         }
         $form = $app['form.factory']->create('participation_forget', array());
         // If it's not POST method, just display void form
         if ('POST' === $request->getMethod()) {
             $form->bind($request->request->get('participation_forget'));
             if ($form->isValid()) {
                 $data = $form->getData();
                 $user = $app['users']->findOneByEmail($data['email']);
                 if (!$user) {
                     $app['session']->getFlashBag()->add('error', 'Aucun utilisateur ne possède cet adresse email.');
                     return $app->redirect($app['url_generator']->generate('_forgetparticipatedrink', array('drinkId' => $drinkId)));
                 }
                 $participation = $app['drink_participants']->findOne($drink['id'], $user['id']);
                 if (false === $participation) {
                     $app['session']->getFlashBag()->add('error', 'Participation inexistante.');
                     return $app->redirect($app['url_generator']->generate('_forgetparticipatedrink', array('drinkId' => $drinkId)));
                 }
                 try {
                     $app['mailer']->send($app['mailer']->createMessage()->setSubject('[Aperophp.net] Rappel de votre participation à un ' . $drink['kind'])->setFrom(array('*****@*****.**'))->setTo(array($user['email']))->setBody($app['twig']->render('drink/forget_mail.html.twig', array('user' => $user, 'drink' => $drink)), 'text/html'));
                 } catch (\Exception $e) {
                     $app->abort(500, 'Impossible de vous envoyer à nouveau votre jeton. Merci de réessayer plus tard.');
                 }
                 $app['session']->getFlashBag()->add('success', 'Vous allez recevoir un email dans quelques instants contenant votre participation.');
                 return $app->redirect($app['url_generator']->generate('_showdrink', array('id' => $drinkId)));
             }
             $app['session']->getFlashBag()->add('error', 'Quelque chose n\'est pas valide.');
         }
         return $app['twig']->render('drink/forget.html.twig', array('form' => $form->createView(), 'drinkId' => $drinkId));
     })->bind('_forgetparticipatedrink')->method('GET|POST');
     return $controllers;
 }
Ejemplo n.º 13
0
 function getHeureLimiteAlignement($id_pool, $id_saison, $id_gerant, $periode)
 {
     $query = "SELECT hour_max_visitor,hour_max_home,date_begin,date_alignement\n\t               FROM periodes\n\t\t\t\tWHERE id_pool = {$id_pool}\n\t\t\t\tAND periode = {$periode}\n\t\t\t\tAND saison_id = {$id_saison}";
     $resultID = mysql_query($query, $this->handle);
     $data = mysql_fetch_array($resultID, MYSQL_ASSOC);
     mysql_free_result($resultID);
     $hour_max_visitor = $data["hour_max_visitor"];
     $hour_max_home = $data["hour_max_home"];
     $date_begin = $data["date_begin"];
     $date_alignement = $data["date_alignement"];
     if ($date_alignement == "0000-00-00") {
         list($my_year, $my_month, $my_day) = split("-", $date_begin);
         $_mydate = Datetime::createFromFormat('Y-m-d', $date_begin, $this->timeZone);
     } else {
         list($my_year, $my_month, $my_day) = split("-", $date_alignement);
         $_mydate = Datetime::createFromFormat('Y-m-d', $date_alignement, $this->timeZone);
     }
     $day = $_mydate->format('j');
     $month = $_mydate->format('F');
     $month = $this->date_getMois($month);
     $year = $_mydate->format('Y');
     $jour = $_mydate->format('l');
     $jour = $this->date_getJour($jour);
     $query = "select gerant_home,gerant_visitor\n                    from schedule_pool\n                    where id_pool = {$id_pool}\n                    and saison_id = {$id_saison}\n                    and periode = {$periode}\n                    and (gerant_home = {$id_gerant} or gerant_visitor = {$id_gerant})";
     $resultID = mysql_query($query, $this->handle);
     $data = mysql_fetch_array($resultID, MYSQL_ASSOC);
     mysql_free_result($resultID);
     if ($id_gerant == $data["gerant_home"]) {
         $hour_max = $hour_max_home;
     } else {
         $hour_max = $hour_max_visitor;
     }
     list($hour, $min, $sec) = split(":", $hour_max);
     $str = "{$jour} {$day} {$month} {$year}, " . $hour . "H" . $min;
     unset($query, $resultID, $data, $hour_max_visitor, $hour_max_home, $date_begin, $date_alignement, $date, $day, $month, $year, $jour, $hour_max, $pool, $sess);
     return $str;
 }
Ejemplo n.º 14
0
echo $date;
// update the validTo column to the current timestamp
$validTo = "UPDATE bfaTable SET validTo={$date} WHERE name={$name}";
// echo 'validTo: ';
// echo $date;
// TEMPORARILY SET TIME WHEN USER LOGGED IN
// fetch the valid from and to columns from the DB for the current user
// fetch the validFrom column from DB and assign the current timestamp
$validFrom = "SELECT validFrom FROM bfaTable WHERE name={$name}";
// find name in DB from form
$dateFrom = "";
// prepare the var for use later
if (mysqli_query($conn, $validFrom)) {
    // if database gave us the validFrom, do this:
    $currDate = new DateTime($validFrom["validFrom"]);
    $dateFrom = Datetime::createFromFormat('Y-m-d H:i:s', $currDate)->format('Y-m-d h:i:s');
} else {
    print_r('Error with validFrom');
}
echo $dateFrom;
// get that updated dateFrom
// THEN, create a variable that captures the validTo and validFrom
$totalTime = $date - $dateFrom;
// difference * 60
// round( abs( $dateFrom - $dateTo ), 0 ). " ";
echo $totalTime;
// Add THE totalTIME IN DATABASE
$updateTotalTime = "UPDATE bfaTable SET timeLogged=`timeLogged` + {$totalTime} WHERE name='{$name}' ";
// find name in DB from form
// now activate the query
$conn->query($updateTotalTime);
Ejemplo n.º 15
0
 public function providerTestValues()
 {
     return array('Nominal' => array("(id, name) VALUES (42, 'poney')", array('id' => 42, 'name' => 'poney')), 'empty value' => array("(id, name) VALUES (42, '')", array('id' => 42, 'name' => '')), 'null empty value' => array("(id, name) VALUES (42, NULL)", array('id' => 42, 'name' => null)), 'value integer as string' => array("(id) VALUES ('42')", array('id' => '42')), 'value float' => array("(id, name, score) VALUES (42, 'poney', 13.37)", array('id' => 42, 'name' => 'poney', 'score' => 13.37)), 'value datetime' => array("(id, name, date) VALUES (42, 'poney', '2014-03-07 13:37:42')", array('id' => 42, 'name' => 'poney', 'date' => \Datetime::createFromFormat('Y-m-d H:i:s', '2014-03-07 13:37:42'))), 'value boolean' => array("(id, name, flag) VALUES (42, 'poney', 1)", array('id' => 42, 'name' => 'poney', 'flag' => true)));
 }
Ejemplo n.º 16
0
 $jn = $item["jn"];
 //$predict_pool = $item["predict_pool"];
 $preference = $item["preference"];
 $actif = $item["actif"];
 $ajustement = $item["ajustement"];
 $resultat = $item["resultat"];
 $resultat2 = $resultat + $ajustement;
 // si la case à cochée afficher_rapport est cochée, on n'affiche pas le joueur.
 if ($kit_afficher_rapport && $actif == "N") {
     continue;
 }
 $compteur++;
 echo "<input type=\"hidden\" name=\"kit_predict_pool[{$id_player}]\" value=\"{$predict_pool}\"/>\n";
 // âge du joueur
 if ($birthday != "0000-00-00") {
     $_mydate = Datetime::createFromFormat('Y-m-d', $birthday, $pool->timeZone);
     $age = $_mydate->diff($pool->todayDate)->y;
     $age = "({$age})";
 } else {
     $age = "";
 }
 // dernière année de contrat...
 if ($contrat_fin > 0) {
     $year = $pool->todayDate->format('Y');
     $month = $pool->todayDate->format('n');
     if ($month >= 7) {
         if ($year == $contrat_fin || $year + 1 == $contrat_fin) {
             //$style2 = "color:blue;";
             switch ($ufa_rfa) {
                 case "ufa":
                     $show_ufa_rfa = "\$\$\$";
Ejemplo n.º 17
0
}
$time = split(" ", $time);
$time = $time[0];
$query = "select id,logo,siteWeb from teams\n          where id in ({$home},{$visitor})";
$data = DB::dbSelect($query);
foreach ($data as $itemA) {
    $id_team = $itemA['id'];
    if ($id_team == $home) {
        $logo_home = $itemA['logo'];
        $siteWeb_home = $itemA['siteWeb'];
    } else {
        $logo_visitor = $itemA['logo'];
        $siteWeb_visitor = $itemA['siteWeb'];
    }
}
$_mydate = Datetime::createFromFormat('Y-m-d', $date, new DateTimeZone('America/Montreal'));
$day_of_week = $ar_dayOfWeek[$_mydate->format('l')];
echo "<table cellpadding=2 cellspacing=2>\n";
//echo "<tr>\n";
//echo "<th colspan=10>$day_of_week, $day " . $ar_month[$month] . " $year</td>\n";
//echo "</tr>\n";
echo "<tr>\n";
echo "<td align='center'><a href=\"{$siteWeb_visitor}\" target=\"_blank\"><img src=\"{$logo_visitor}\" border=0 /></a></td>\n";
if ($result != "-") {
    // le match a déjà eu lieu
    echo "<td align='center' {$style_visitor}>{$goals_visitor}</td>\n";
} elseif ($date == $today->format('Y-m-d') && $time < $today->format("H:i")) {
    // match en cours
    $query = "select id from nhl_players where team = {$home} and pos = 'TM'";
    $data = DB::dbSelect($query);
    $data = $data[0];
Ejemplo n.º 18
0
 /**
  * api-interface for transferring jobs
  * @return JsonModel
  */
 public function saveAction()
 {
     $services = $this->serviceLocator;
     /* @var \Zend\Http\PhpEnvironment\Request $request */
     $request = $this->getRequest();
     $params = $this->params();
     $p = $params->fromPost();
     $user = $services->get('AuthenticationService')->getUser();
     $repositories = $services->get('repositories');
     /* @var \Jobs\Repository\Job $repositoriesJob */
     $repositoriesJob = $repositories->get('Jobs/Job');
     $log = $services->get('Core/Log');
     $result = array('token' => session_id(), 'isSaved' => false, 'message' => '', 'portals' => array());
     try {
         if (isset($user) && !empty($user->login)) {
             $formElementManager = $services->get('FormElementManager');
             /* @var \Jobs\Form\Import $form */
             $form = $formElementManager->get('Jobs/Import');
             $id = $params->fromPost('id');
             // determine Job from Database
             /* @var \Jobs\Entity\Job $entity */
             $entity = null;
             $createdJob = true;
             if (empty($id)) {
                 $applyId = $params->fromPost('applyId');
                 if (empty($applyId)) {
                     $entity = $repositoriesJob->create();
                 } else {
                     $entity = $repositoriesJob->findOneBy(array("applyId" => (string) $applyId));
                     if (!isset($entity)) {
                         // new Job (the more likely branch)
                         $entity = $repositoriesJob->create(array("applyId" => (string) $applyId));
                     } else {
                         $createdJob = false;
                     }
                 }
             } else {
                 $repositoriesJob->find($id);
                 $createdJob = false;
             }
             //$services->get('repositories')->get('Jobs/Job')->store($entity);
             $form->bind($entity);
             if ($request->isPost()) {
                 $loginSuffix = '';
                 $event = $this->getEvent();
                 $loginSuffixResponseCollection = $this->getEventManager()->trigger('login.getSuffix', $event);
                 if (!$loginSuffixResponseCollection->isEmpty()) {
                     $loginSuffix = $loginSuffixResponseCollection->last();
                 }
                 $params = $request->getPost();
                 $params->datePublishStart = \Datetime::createFromFormat("Y-m-d", $params->datePublishStart);
                 $result['post'] = $_POST;
                 $form->setData($params);
                 if ($form->isValid()) {
                     if (isset($params['description'])) {
                         $templateValues = new TemplateValues();
                         $description = Json::decode($params->description);
                         $entity->setTemplateValues($templateValues->setDescription(strip_tags($description)));
                     }
                     $entity->setStatus($params['status']);
                     /*
                      * Search responsible user via contactEmail
                      */
                     $users = $repositories->get('Auth/User');
                     $responsibleUser = $users->findByEmail($params['contactEmail']);
                     $entity->setUser($responsibleUser ?: $user);
                     $group = $user->getGroup($entity->getCompany());
                     if ($group) {
                         $entity->getPermissions()->grant($group, PermissionsInterface::PERMISSION_VIEW);
                     }
                     $result['isSaved'] = true;
                     $log->info('Jobs/manage/saveJob [user: '******']:' . var_export($p, true));
                     if (!empty($params->companyId)) {
                         $companyId = $params->companyId . $loginSuffix;
                         $repOrganization = $repositories->get('Organizations/Organization');
                         $hydratorManager = $services->get('hydratorManager');
                         /* @var \Organizations\Entity\Hydrator\OrganizationHydrator $hydrator */
                         $hydrator = $hydratorManager->get('Hydrator/Organization');
                         $entityOrganizationFromDB = $repOrganization->findbyRef($companyId);
                         //$permissions              = $entityOrganizationFromDB->getPermissions();
                         $data = array('externalId' => $companyId, 'organizationName' => $params->company, 'image' => $params->logoRef, 'user' => $user);
                         //$permissions->grant($user, PermissionsInterface::PERMISSION_CHANGE);
                         $entityOrganization = $hydrator->hydrate($data, $entityOrganizationFromDB);
                         if ($responsibleUser && $user !== $responsibleUser) {
                             /*
                              * We cannot use custom collections yet
                              * @todo if we updated Mongo ODM to >1.0.5, we must move this to
                              *       a custom collection class
                              */
                             $employees = $entityOrganization->getEmployees();
                             $contained = false;
                             /*
                              * this is o(n) and should propably be optimized when the custom collection is created.
                              * It's not very performant to load the whole user entity, when all we need is the ID.
                              * Maybe store the id as reference in the Employees Entity.
                              */
                             foreach ($employees as $employee) {
                                 if ($employee->getUser()->getId() == $responsibleUser->getId()) {
                                     $contained = true;
                                     break;
                                 }
                             }
                             if (!$contained) {
                                 $employees->add(new Employee($responsibleUser));
                             }
                         }
                         $repositories->store($entityOrganization);
                         $entity->setOrganization($entityOrganization);
                     } else {
                         $result['message'] = '';
                     }
                     if (!empty($params->locations)) {
                         $locations = \Zend\Json\Json::decode($params->locations, \Zend\Json\Json::TYPE_ARRAY);
                         $jobLocations = $entity->getLocations();
                         $jobLocations->clear();
                         foreach ($locations as $locData) {
                             $location = new Location();
                             $coords = array_map(function ($i) {
                                 return (double) $i;
                             }, $locData['coordinates']);
                             $location->setCountry($locData['country'])->setRegion($locData['region'])->setCity($locData['city'])->setCoordinates(new Point($coords));
                             $jobLocations->add($location);
                         }
                     }
                     $repositoriesJob->store($entity);
                     $id = $entity->getId();
                     if (!empty($id)) {
                         $jobEvent = $services->get('Jobs/Event');
                         $jobEvent->setJobEntity($entity);
                         $extra = [];
                         foreach (array('channels', 'positions', 'branches', 'keywords', 'description') as $paramName) {
                             $data = $params->get($paramName);
                             if ($data) {
                                 $data = Json::decode($data, Json::TYPE_ARRAY);
                                 if ('channels' == $paramName) {
                                     foreach (array_keys($data) as $portalName) {
                                         $jobEvent->addPortal($portalName);
                                     }
                                 }
                                 $extra[$paramName] = $data;
                             }
                         }
                         $jobEvent->setParam('extraData', $extra);
                         if ($createdJob || true) {
                             /* @var $jobEvents \Zend\EventManager\EventManager */
                             $jobEvents = $services->get('Jobs/Events');
                             $jobEvent->setName(JobEvent::EVENT_JOB_ACCEPTED)->setTarget($this);
                             $responses = $jobEvents->trigger($jobEvent);
                             foreach ($responses as $response) {
                                 // responses from the portals
                                 // @TODO, put this in some conclusion and meaningful messages
                                 if (!empty($response)) {
                                     if ($response instanceof JobResponse) {
                                         if (!array_key_exists('log', $result)) {
                                             $result['log'] = '';
                                         }
                                         //$message = $response->getMessage();
                                         //$result['log'] .= $response->getMessage() . PHP_EOL;
                                         $status = $response->getStatus();
                                         $portal = $response->getPortal();
                                         if (empty($portal)) {
                                             throw new \RuntimeException('Publisher-Events (internal error): There is an unregistered publisher listening');
                                         }
                                         switch ($status) {
                                             case JobResponse::RESPONSE_FAIL:
                                             case JobResponse::RESPONSE_NOTIMPLEMENTED:
                                             case JobResponse::RESPONSE_ERROR:
                                                 $result['isSaved'] = false;
                                                 break;
                                             case JobResponse::RESPONSE_DENIED:
                                             case JobResponse::RESPONSE_OK:
                                             case JobResponse::RESPONSE_OKANDSTOP:
                                             case JobResponse::RESPONSE_DEPRECATED:
                                                 break;
                                         }
                                         if (array_key_exists($portal, $result['portals'])) {
                                             throw new \RuntimeException('Publisher-Events (internal error): There are two publisher registered for ' . $portal);
                                         }
                                         $result['portals'][$portal] = $status;
                                     } else {
                                         throw new \RuntimeException('Publisher-Events (internal error): Response must be from the class Jobs\\Listener\\Response\\JobResponse');
                                     }
                                 } else {
                                     throw new \RuntimeException('Publisher-Events (internal error): Response must be set');
                                 }
                             }
                         }
                     }
                 } else {
                     $log->info('Jobs/manage/saveJob [error: ' . $form->getMessages() . ']:' . var_export($p, true));
                     $result['valid Error'] = $form->getMessages();
                 }
             }
         } else {
             $log->info('Jobs/manage/saveJob [error: session lost]:' . var_export($p, true));
             $result['message'] = 'session_id is lost';
         }
     } catch (\Exception $e) {
         $result['message'] = 'exception occured: ' . $e->getMessage();
     }
     //$services->get('Core/Log')->info('Jobs/manage/saveJob result:' . PHP_EOL . var_export($p, True));
     return new JsonModel($result);
 }
Ejemplo n.º 19
0
 }
 list($year, $month, $day) = split("-", $today);
 $opponent = $playoffs2->getOpponentTeamInfo($id_pool, $team_id, $id_saison, $pool);
 $opponentA = split(" ", $opponent);
 $adv_abbr = $opponentA[0];
 if ($adv_abbr[0] == "@") {
     $adv_abbr = $opponentA[1];
     $timeTV = $opponentA[3];
 } else {
     $timeTV = $opponentA[2];
 }
 $timeA = split(":", $timeTV);
 $hour = $timeA[0];
 $minutes = $timeA[1];
 //$heure_debut_match = mktime($hour,$minutes,00,$month,$day,$year);
 $heure_debut_match = Datetime::createFromFormat('Y-m-d H:i', "{$year}-{$month}-{$day} {$hour}:{$minutes}", new DateTimeZone('America/Montreal'));
 if (!$en_cours && !$gm_finished || $pool->todayDate < $heure_debut_match) {
     echo "<TD class=\"tableCellRidge2\" NOWRAP style=\"padding-left:5px;padding-right:5px;\">{$opponent}</td>\n";
     echo "<script type=\"text/javascript\">\n";
     echo "var my_live_pts_visitor_td = eval(\"document.getElementById('live_pts_home_\" + {$id_gerant} + \"_\" + {$compteur_for_live_pts_td} + \"')\");\n";
     echo "my_live_pts_visitor_td.style.backgroundColor=\"transparent\";";
     echo "my_live_pts_visitor_td.innerHTML=\"-\";";
     echo "</script>\n";
 } else {
     if ($adv_team[0] == "@") {
         echo "<TD class=\"tableCellRidge2\" NOWRAP style=\"padding-left:5px;padding-right:5px;{$style_gm_finished};\" onmouseover=\"this.style.cursor='pointer';\" " . "onclick=\"window.open('{$gs_link}','NHL GS','width={$hist_window_width},height={$hist_window_height},resizable=yes,scrollbars=yes,status=no');\">" . "{$team_abbr} {$team_goals}, {$adv_abbr} {$adv_goals} - {$temps_ecoule}</td>\n";
     } else {
         echo "<TD class=\"tableCellRidge2\" NOWRAP style=\"padding-left:5px;padding-right:5px;{$style_gm_finished};\" onmouseover=\"this.style.cursor='pointer';\" " . "onclick=\"window.open('{$gs_link}','NHL GS','width={$hist_window_width},height={$hist_window_height},resizable=yes,scrollbars=yes,status=no');\">" . "{$adv_abbr} {$adv_goals}, {$team_abbr} {$team_goals} - {$temps_ecoule}</td>\n";
     }
 }
 echo "</tr>\n";
Ejemplo n.º 20
0
 function affichage_scoreboard()
 {
     //// TEST TEST TEST
     //$this->today = '2008-03-29';
     $hist_window_width = "";
     $hist_window_height = "";
     /*
     Je vais le faire de la manière suivante: avant 10h00 am, je vais afficher les résultats de la veille et le clic du match
     ira sur la page de tous les scores de la veille.
     Après 10h00, je vais afficher les matchs du jour, que ce soit en cours, à venir ou terminé.
     Une fois les matchs du jour terminé, j'afficherai les matchs à venir.
     */
     echo "<div id=\"gameReel\">\n";
     echo "<div id=\"hdrSB\">";
     echo "<div class=\"hdrSBLeftRule\"></div>\n";
     $SB_max = 14;
     $compteur_SB = 0;
     if ($this->todayDate->format('H') <= "06") {
         $today = $this->yesterday;
         $link_to_gs = "individuel";
         $journee = "Aujourd'hui";
     } elseif ($this->todayDate->format('H') <= "09") {
         $today = $this->yesterday;
         $link_to_gs = "global";
         $journee = "Hier";
     } else {
         $today = $this->today;
         $journee = "Aujourd'hui";
     }
     if ($journee == "Hier") {
         // premièrement, affichage des résultats de la veille...
         $query = "select home,visitor,time,game_result\n                         from schedule_nhl\n                         where date = '{$today}'\n                         order by time asc";
         $resultID = mysql_query($query, $this->handle);
         while ($data = mysql_fetch_array($resultID, MYSQL_ASSOC)) {
             $home_team = $data['home'];
             $visitor_team = $data['visitor'];
             $game_time = $data['time'];
             $game_result = $data['game_result'];
             // abbréviation des équipes...
             $query2 = "select abbr from teams where id = {$home_team}";
             $resultID2 = mysql_query($query2, $this->handle);
             $data2 = mysql_fetch_array($resultID2, MYSQL_ASSOC);
             mysql_free_result($resultID2);
             $abbr_home = $data2['abbr'];
             $query2 = "select abbr from teams where id = {$visitor_team}";
             $resultID2 = mysql_query($query2, $this->handle);
             $data2 = mysql_fetch_array($resultID2, MYSQL_ASSOC);
             mysql_free_result($resultID2);
             $abbr_visitor = $data2['abbr'];
             $game_resultA = split(" ", $game_result);
             $goals_visitor = $game_resultA[0];
             $goals_home = $game_resultA[2];
             $ot_str = $game_resultA[3];
             //echo "<div class=\"hdrSBFinalGame\" onmouseover=\"this.style.cursor='pointer';\" " .
             //     "onclick=\"window.open('http://www.nhl.com/scores/index.html','NHL //GS','width=$hist_window_width,height=$hist_window_height,resizable=yes,scrollbars=yes,status=no');\">\n";
             echo "<div class=\"hdrSBFinalGame\">\n";
             echo "<table cellpadding=0 cellspacing=0 border=0 width=58>\n";
             echo "<tr>\n";
             echo "<td colspan=2 valign=\"bottom\" class=\"hdrSBLink\"><span class=\"hdrSBRed\">{$journee}</span></td>\n";
             echo "</tr>\n";
             echo "<tr>\n";
             echo "<td><span class=\"hdrSBStrg\">{$abbr_visitor}</span></td>\n";
             echo "<td align=\"right\"><span class=\"hdrSBStrg\">{$goals_visitor}</span></td>\n";
             echo "</tr>\n";
             echo "<tr>\n";
             echo "<td><span class=\"hdrSBStrg\">{$abbr_home}</span></td>\n";
             echo "<td align=\"right\"><span class=\"hdrSBStrg\">{$goals_home}</span></td>\n";
             echo "</tr>\n";
             echo "<tr>\n";
             echo "<td colspan=2 valign=\"top\"><span class=\"hdrSBRed\">FINAL {$ot_str}</span></td>\n";
             echo "</tr>\n";
             echo "</table>\n";
             echo "</div>\n";
             $compteur_SB++;
             unset($ot_str, $game_time);
         }
         mysql_free_result($resultID);
         if ($compteur_SB > 0) {
             echo "<div class=\"hdrSBRule\"></div>\n";
             echo "<div class=\"hdrSBRule\"></div>\n";
         }
         // Ensuite, les matchs du jour
         $query = "select home,visitor,time\n                         from schedule_nhl\n                         where date = '{$this->today}'\n                         order by time asc";
         $resultID = mysql_query($query, $this->handle);
         while ($data = mysql_fetch_array($resultID, MYSQL_ASSOC)) {
             if ($compteur_SB > $SB_max) {
                 break;
             }
             $home_team = $data['home'];
             $visitor_team = $data['visitor'];
             $game_timeA = split(" ", $data['time']);
             $game_time = $game_timeA[0];
             isset($data['match_no']) ? $match_no = $data['match_no'] : ($match_no = "");
             // abbréviation des équipes...
             $query2 = "select abbr from teams where id = {$home_team}";
             $resultID2 = mysql_query($query2, $this->handle);
             $data2 = mysql_fetch_array($resultID2, MYSQL_ASSOC);
             mysql_free_result($resultID2);
             $abbr_home = $data2['abbr'];
             $query2 = "select abbr from teams where id = {$visitor_team}";
             $resultID2 = mysql_query($query2, $this->handle);
             $data2 = mysql_fetch_array($resultID2, MYSQL_ASSOC);
             mysql_free_result($resultID2);
             $abbr_visitor = $data2['abbr'];
             //echo "<div class=\"hdrSBTodayGame\" onmouseover=\"this.style.cursor='pointer';\" " .
             //     "onclick=\"window.open('http://www.nhl.com/scores/index.html','NHL //GS','width=$hist_window_width,height=$hist_window_height,resizable=yes,scrollbars=yes,status=no');\">\n";
             echo "<div class=\"hdrSBTodayGame\">\n";
             echo "<table cellpadding=0 cellspacing=0 border=0 width=58>\n";
             echo "<tr>\n";
             echo "<td colspan=2 valign=\"bottom\" class=\"hdrSBLink\"><span class=\"hdrSBYellow\">Aujourd'hui</span></td>\n";
             echo "</tr>\n";
             echo "<tr>\n";
             echo "<td><span class=\"hdrSBStrg\">{$abbr_visitor}</span></td>\n";
             echo "<td align=\"right\"><span class=\"hdrSBStrg\">-</span></td>\n";
             echo "</tr>\n";
             echo "<tr>\n";
             echo "<td><span class=\"hdrSBStrg\">{$abbr_home}</span></td>\n";
             echo "<td align=\"right\"><span class=\"hdrSBStrg\">-</span></td>\n";
             echo "</tr>\n";
             echo "<tr>\n";
             echo "<td colspan=2 valign=\"top\"><span class=\"hdrSBYellow\">{$game_time}</span></td>\n";
             echo "</tr>\n";
             echo "</table>\n";
             echo "</div>\n";
             $compteur_SB++;
             unset($ot_str, $game_time);
         }
         mysql_free_result($resultID);
         // Finalement, si le compteur du scoreboard n'est pas à son maximum, on affiche les matchs
         // à venir jusqu'à la limite du compteur.
         if ($compteur_SB < $SB_max) {
             if ($compteur_SB > 0) {
                 echo "<div class=\"hdrSBRule\"></div>\n";
                 echo "<div class=\"hdrSBRule\"></div>\n";
             }
             $nbre_de_sb_a_ajouter = $SB_max - $compteur_SB;
             if ($this->todayDate->format('H') <= "09") {
                 list($year, $month, $day) = split("-", $this->today);
                 $_mydate = Datetime::createFromFormat('Y-m-d', $this->today, $this->timeZone);
                 $_mydate->modify("+1 day");
                 $tomorrow = $_mydate->format('Y-m-d');
             } else {
                 list($year, $month, $day) = split("-", $today);
                 $_mydate = Datetime::createFromFormat('Y-m-d', $today, $this->timeZone);
                 $_mydate->modify("+1 day");
                 $tomorrow = $_mydate->format('Y-m-d');
             }
             $query = "select home,visitor,time,date\n                              from schedule_nhl\n                              where date >= '{$tomorrow}'\n                              order by date asc,time asc\n                              limit {$nbre_de_sb_a_ajouter}";
             $resultID = mysql_query($query, $this->handle);
             $date_en_traitement = "";
             while ($data = mysql_fetch_array($resultID, MYSQL_ASSOC)) {
                 $home_team = $data['home'];
                 $visitor_team = $data['visitor'];
                 $game_timeA = split(" ", $data['time']);
                 $game_time = $game_timeA[0];
                 $game_date = $data['date'];
                 $match_no = isset($data['match_no']) ? $data['match_no'] : "";
                 if ($game_time == "") {
                     $game_time = "TBD";
                 }
                 // abbréviation des équipes...
                 $query2 = "select abbr from teams where id = {$home_team}";
                 $resultID2 = mysql_query($query2, $this->handle);
                 $data2 = mysql_fetch_array($resultID2, MYSQL_ASSOC);
                 mysql_free_result($resultID2);
                 $abbr_home = $data2['abbr'];
                 $query2 = "select abbr from teams where id = {$visitor_team}";
                 $resultID2 = mysql_query($query2, $this->handle);
                 $data2 = mysql_fetch_array($resultID2, MYSQL_ASSOC);
                 mysql_free_result($resultID2);
                 $abbr_visitor = $data2['abbr'];
                 if ($date_en_traitement == "") {
                     $date_en_traitement = $game_date;
                 }
                 if ("{$game_date}" != "{$date_en_traitement}") {
                     echo "<div class=\"hdrSBRule\"></div>\n";
                     echo "<div class=\"hdrSBRule\"></div>\n";
                     $date_en_traitement = $game_date;
                 }
                 $_mydate = Datetime::createFromFormat('Y-m-d', $game_date, $this->timeZone);
                 $day = $_mydate->format("j");
                 $day_str = $_mydate->format("D");
                 switch ($day_str) {
                     case "Mon":
                         $day_str = "Lun";
                         break;
                     case "Tue":
                         $day_str = "Mar";
                         break;
                     case "Wed":
                         $day_str = "Mer";
                         break;
                     case "Thu":
                         $day_str = "Jeu";
                         break;
                     case "Fri":
                         $day_str = "Ven";
                         break;
                     case "Sat":
                         $day_str = "Sam";
                         break;
                     case "Sun":
                         $day_str = "Dim";
                         break;
                 }
                 //echo "<div class=\"hdrSBFutureGame\" onmouseover=\"this.style.cursor='pointer';\" " .
                 //     "onclick=\"window.open('http://www.nhl.com/scores/index.html','NHL //GS','width=$hist_window_width,height=$hist_window_height,resizable=yes,scrollbars=yes,status=no');\">\n";
                 echo "<div class=\"hdrSBFutureGame\">\n";
                 echo "<table cellpadding=0 cellspacing=0 border=0 width=58>\n";
                 echo "<tr>\n";
                 echo "<td colspan=2 valign=\"bottom\" class=\"hdrSBLink\"><span class=\"hdrSBGrey\">{$day_str} {$day}/{$month}</span></td>\n";
                 echo "</tr>\n";
                 echo "<tr>\n";
                 echo "<td><span class=\"hdrSBStrg\">{$abbr_visitor}</span></td>\n";
                 echo "<td align=\"right\"><span class=\"hdrSBStrg\">-</span></td>\n";
                 echo "</tr>\n";
                 echo "<tr>\n";
                 echo "<td><span class=\"hdrSBStrg\">{$abbr_home}</span></td>\n";
                 echo "<td align=\"right\"><span class=\"hdrSBStrg\">-</span></td>\n";
                 echo "</tr>\n";
                 echo "<tr>\n";
                 echo "<td colspan=2 valign=\"top\"><span class=\"hdrSBGrey\">{$game_time}</span></td>\n";
                 echo "</tr>\n";
                 echo "</table>\n";
                 echo "</div>\n";
                 $compteur_SB++;
                 unset($ot_str, $game_time);
             }
         }
     } else {
         // schedule du jour
         $query = "select home,visitor,time\n                         from schedule_nhl\n                         where date = '{$today}'\n                         order by time asc";
         $resultID = mysql_query($query, $this->handle);
         //Pour avoir les parties terminées en premier, suivi des parties en cours et finalement,
         // les parties qui vont se jouer plus tard, on va créer des arrays afin de vérifier
         // les données de la tables 'live'. Les games finished seront placées au début d'une nouvelle
         // array et c'est cette dernière que je vais traiter par la suite.
         $homeTeamA = array();
         while ($data = mysql_fetch_array($resultID, MYSQL_ASSOC)) {
             $home_team = $data['home'];
             $visitor_team = $data['visitor'];
             $game_timeA = split(" ", $data['time']);
             $game_time = $game_timeA[0];
             isset($data['match_no']) ? $match_no = $data['match_no'] : ($match_no = "");
             $homeTeamA[] = $home_team;
             $visitorTeamA[] = $visitor_team;
             $gameTimeA[] = $game_time;
             $match_noA[] = $match_no;
         }
         mysql_free_result($resultID);
         unset($homeTeamBonOrderA, $visitorTeamBonOrdreA, $gameTimeBonOrdreA);
         $index_array = 20;
         $first_index_array = 20;
         if (count($homeTeamA) > 0) {
             foreach ($homeTeamA as $index => $home_team) {
                 $query = "select temps_ecoule\n                                   from live_stats.statsPlayers_live\n                                   where id_team = {$home_team}\n                                   limit 1";
                 $resultID = mysql_query($query, $this->handle);
                 $data = mysql_fetch_array($resultID, MYSQL_ASSOC);
                 mysql_free_result($resultID);
                 if (eregi("Final", $data['temps_ecoule'])) {
                     $first_index_array--;
                     $homeTeamBonOrderA[$first_index_array] = $home_team;
                     $visitorTeamBonOrdreA[$first_index_array] = $visitorTeamA[$index];
                     $gameTimeBonOrdreA[$first_index_array] = $gameTimeA[$index];
                     $match_noBonOrdreA[$first_index_array] = $match_noA[$index];
                 } else {
                     $homeTeamBonOrderA[$index_array] = $home_team;
                     $visitorTeamBonOrdreA[$index_array] = $visitorTeamA[$index];
                     $gameTimeBonOrdreA[$index_array] = $gameTimeA[$index];
                     $match_noBonOrdreA[$index_array] = $match_noA[$index];
                     $index_array++;
                 }
             }
             ksort($homeTeamBonOrderA);
             ksort($visitorTeamBonOrdreA);
             ksort($gameTimeBonOrdreA);
             ksort($match_noBonOrdreA);
             foreach ($homeTeamBonOrderA as $index => $home_team) {
                 $visitor_team = $visitorTeamBonOrdreA[$index];
                 $game_time = $gameTimeBonOrdreA[$index];
                 $match_no = $match_noBonOrdreA[$index];
                 // abbréviation des équipes...
                 $query2 = "select abbr from teams where id = {$home_team}";
                 $resultID2 = mysql_query($query2, $this->handle);
                 $data2 = mysql_fetch_array($resultID2, MYSQL_ASSOC);
                 mysql_free_result($resultID2);
                 $abbr_home = $data2['abbr'];
                 $query2 = "select abbr from teams where id = {$visitor_team}";
                 $resultID2 = mysql_query($query2, $this->handle);
                 $data2 = mysql_fetch_array($resultID2, MYSQL_ASSOC);
                 mysql_free_result($resultID2);
                 $abbr_visitor = $data2['abbr'];
                 // si l'heure actuelle est plus petite que l'heure du match...
                 list($heure, $minute) = split(":", $game_time);
                 $previous_game_was_finished = "";
                 if ($today == $this->today && ($this->todayDate->format('H') < "{$heure}" || $this->todayDate->format('H') == "{$heure}" && $this->todayDate->format('i') < "{$minute}")) {
                     if ($previous_game_was_finished != "") {
                         echo "<div class=\"hdrSBRule\"></div>\n";
                         echo "<div class=\"hdrSBRule\"></div>\n";
                         $previous_game_was_finished = "";
                     }
                     //echo "<div class=\"hdrSBTodayGame\" onmouseover=\"this.style.cursor='pointer';\" " .
                     //     "onclick=\"window.open('http://www.nhl.com/scores/index.html','NHL //GS','width=$hist_window_width,height=$hist_window_height,resizable=yes,scrollbars=yes,status=no');\">\n";
                     echo "<div class=\"hdrSBTodayGame\">\n";
                     echo "<table cellpadding=0 cellspacing=0 border=0 width=58>\n";
                     echo "<tr>\n";
                     echo "<td colspan=2 valign=\"bottom\" class=\"hdrSBLink\"><span class=\"hdrSBYellow\">Aujourd'hui</span></td>\n";
                     echo "</tr>\n";
                     echo "<tr>\n";
                     echo "<td><span class=\"hdrSBStrg\">{$abbr_visitor}</span></td>\n";
                     echo "<td align=\"right\"><span class=\"hdrSBStrg\">-</span></td>\n";
                     echo "</tr>\n";
                     echo "<tr>\n";
                     echo "<td><span class=\"hdrSBStrg\">{$abbr_home}</span></td>\n";
                     echo "<td align=\"right\"><span class=\"hdrSBStrg\">-</span></td>\n";
                     echo "</tr>\n";
                     echo "<tr>\n";
                     echo "<td colspan=2 valign=\"top\"><span class=\"hdrSBYellow\">{$game_time}</span></td>\n";
                     echo "</tr>\n";
                     echo "</table>\n";
                     echo "</div>\n";
                 } else {
                     // le match est soit en cours, soit terminé.
                     $query = "select team_goals,adv_goals,temps_ecoule,gs_link\n                                        from live_stats.statsPlayers_live\n                                        where id_team = {$home_team}\n                                        limit 1";
                     $resultID = mysql_query($query, $this->handle);
                     $data = mysql_fetch_array($resultID, MYSQL_ASSOC);
                     mysql_free_result($resultID);
                     $my_team_goals = $data['team_goals'];
                     $my_adv_goals = $data['adv_goals'];
                     $my_temps_ecoule = $data['temps_ecoule'];
                     $my_gs_link = $data['gs_link'];
                     if (eregi("Final", $my_temps_ecoule)) {
                         $previous_game_was_finished = "oui";
                         echo "<div class=\"hdrSBFinalGame\" onmouseover=\"this.style.cursor='pointer';\" " . "onclick=\"window.open('{$my_gs_link}','NHL GS','width=1280,height=1024,resizable=yes,scrollbars=yes,status=no');\">\n";
                         echo "<table cellpadding=0 cellspacing=0 border=0 width=58>\n";
                         echo "<tr>\n";
                         echo "<td colspan=2 valign=\"bottom\" class=\"hdrSBLink\"><span class=\"hdrSBRed\">Aujourd'hui</span></td>\n";
                         echo "</tr>\n";
                         echo "<tr>\n";
                         echo "<td><span class=\"hdrSBStrg\">{$abbr_visitor}</span></td>\n";
                         echo "<td align=\"right\"><span class=\"hdrSBStrg\">{$my_adv_goals}</span></td>\n";
                         echo "</tr>\n";
                         echo "<tr>\n";
                         echo "<td><span class=\"hdrSBStrg\">{$abbr_home}</span></td>\n";
                         echo "<td align=\"right\"><span class=\"hdrSBStrg\">{$my_team_goals}</span></td>\n";
                         echo "</tr>\n";
                         echo "<tr>\n";
                         echo "<td colspan=2 valign=\"top\"><span class=\"hdrSBRed\">" . $my_temps_ecoule . "</span></td>\n";
                         echo "</tr>\n";
                         echo "</table>\n";
                         echo "</div>\n";
                     } else {
                         // le match est en cours...
                         if ($previous_game_was_finished != "") {
                             echo "<div class=\"hdrSBRule\"></div>\n";
                             echo "<div class=\"hdrSBRule\"></div>\n";
                             $previous_game_was_finished = "";
                         }
                         $str_temps_ecoule = "";
                         if ($my_temps_ecoule == "") {
                             $str_temps_ecoule = "???";
                             $period = 0;
                         } else {
                             $str_temps_ecoule = $my_temps_ecoule;
                         }
                         /*
                         if (eregi("remaining",$my_temps_ecoule)) {
                              $totoA = split(" ",$my_temps_ecoule);
                              if ($totoA[0] == "Period") {
                                   $period = $totoA[1];
                                   $time_remaining = $totoA[2];
                              } else {
                                   $period = $totoA[0];
                                   $time_remaining = $totoA[1];
                              }
                              $time_remaining = substr($time_remaining,1,strlen($time_remaining)-1);
                              $str_temps_ecoule = "$time_remaining ";
                         }
                         
                         if (eregi("end of",$my_temps_ecoule)) {
                              $totoA = split(" ",$my_temps_ecoule);
                              $period = $totoA[count($totoA)-1];
                              $str_temps_ecoule = "END ";
                         }
                         
                         switch($period) {
                              case "0":
                                   break;
                              case "1":
                                   $str_temps_ecoule .= "1st";
                                   break;
                              case "2":
                                   $str_temps_ecoule .= "2nd";
                                   break;
                              case "3":
                                   $str_temps_ecoule .= "3rd";
                                   break;
                              case "4":
                                   $str_temps_ecoule .= "1st OT";
                                   break;
                              case "5":
                                   $str_temps_ecoule .= "2nd OT";
                                   break;
                              case "6":
                                   $str_temps_ecoule .= "3rd OT";
                                   break;
                              case "7":
                                   $str_temps_ecoule .= "4th OT";
                                   break;
                              case "8":
                                   $str_temps_ecoule .= "5th OT";
                                   break;
                              case "9":
                                   $str_temps_ecoule .= "6th OT";
                                   break;
                              default:
                                   $str_temps_ecoule .= "OT";
                                   break;
                         }
                         */
                         echo "<div class=\"hdrSBTodayGame\" onmouseover=\"this.style.cursor='pointer';\" " . "onclick=\"window.open('{$my_gs_link}','NHL GS','width=1280,height=1024,resizable=yes,scrollbars=yes,status=no');\">\n";
                         echo "<table cellpadding=0 cellspacing=0 border=0 width=58>\n";
                         echo "<tr>\n";
                         echo "<td colspan=2 valign=\"bottom\" class=\"hdrSBLink\"><span class=\"hdrSBYellow\">En cours...</span></td>\n";
                         echo "</tr>\n";
                         echo "<tr>\n";
                         echo "<td><span class=\"hdrSBStrg\">{$abbr_visitor}</span></td>\n";
                         echo "<td align=\"right\"><span class=\"hdrSBStrg\">{$my_adv_goals}</span></td>\n";
                         echo "</tr>\n";
                         echo "<tr>\n";
                         echo "<td><span class=\"hdrSBStrg\">{$abbr_home}</span></td>\n";
                         echo "<td align=\"right\"><span class=\"hdrSBStrg\">{$my_team_goals}</span></td>\n";
                         echo "</tr>\n";
                         echo "<tr>\n";
                         echo "<td colspan=2 valign=\"top\"><span class=\"hdrSBYellow\">{$str_temps_ecoule}</span></td>\n";
                         echo "</tr>\n";
                         echo "</table>\n";
                         echo "</div>\n";
                     }
                 }
                 $compteur_SB++;
                 unset($ot_str, $journee, $game_time);
             }
         }
         // Finalement, si le compteur du scoreboard n'est pas à son maximum, on affiche les matchs
         // à venir jusqu'à la limite du compteur.
         if ($compteur_SB < $SB_max) {
             if ($compteur_SB > 0) {
                 echo "<div class=\"hdrSBRule\"></div>\n";
                 echo "<div class=\"hdrSBRule\"></div>\n";
             }
             $nbre_de_sb_a_ajouter = $SB_max - $compteur_SB;
             list($year, $month, $day) = split("-", $today);
             $_mydate = Datetime::createFromFormat('Y-m-d', $today, $this->timeZone);
             $_mydate->modify("+1 day");
             $tomorrow = $_mydate->format('Y-m-d');
             $query = "select home,visitor,time,date\n                              from schedule_nhl\n                              where date >= '{$tomorrow}'\n                              order by date asc,time asc\n                              limit {$nbre_de_sb_a_ajouter}";
             $resultID = mysql_query($query, $this->handle);
             $date_en_traitement = "";
             while ($data = mysql_fetch_array($resultID, MYSQL_ASSOC)) {
                 $home_team = $data['home'];
                 $visitor_team = $data['visitor'];
                 $game_timeA = split(" ", $data['time']);
                 $game_time = $game_timeA[0];
                 $game_date = $data['date'];
                 //$match_no = $data['match_no'];
                 if ($game_time == "") {
                     $game_time = "TBD";
                 }
                 // abbréviation des équipes...
                 $query2 = "select abbr from teams where id = {$home_team}";
                 $resultID2 = mysql_query($query2, $this->handle);
                 $data2 = mysql_fetch_array($resultID2, MYSQL_ASSOC);
                 mysql_free_result($resultID2);
                 $abbr_home = $data2['abbr'];
                 $query2 = "select abbr from teams where id = {$visitor_team}";
                 $resultID2 = mysql_query($query2, $this->handle);
                 $data2 = mysql_fetch_array($resultID2, MYSQL_ASSOC);
                 mysql_free_result($resultID2);
                 $abbr_visitor = $data2['abbr'];
                 if ($date_en_traitement == "") {
                     $date_en_traitement = $game_date;
                 }
                 if ("{$game_date}" != "{$date_en_traitement}") {
                     echo "<div class=\"hdrSBRule\"></div>\n";
                     echo "<div class=\"hdrSBRule\"></div>\n";
                     $date_en_traitement = $game_date;
                 }
                 $_mydate = Datetime::createFromFormat('Y-m-d', $game_date, $this->timeZone);
                 $day = $_mydate->format("j");
                 $day_str = $_mydate->format("D");
                 switch ($day_str) {
                     case "Mon":
                         $day_str = "Lun";
                         break;
                     case "Tue":
                         $day_str = "Mar";
                         break;
                     case "Wed":
                         $day_str = "Mer";
                         break;
                     case "Thu":
                         $day_str = "Jeu";
                         break;
                     case "Fri":
                         $day_str = "Ven";
                         break;
                     case "Sat":
                         $day_str = "Sam";
                         break;
                     case "Sun":
                         $day_str = "Dim";
                         break;
                 }
                 //echo "<div class=\"hdrSBFutureGame\" onmouseover=\"this.style.cursor='pointer';\" " .
                 //     "onclick=\"window.open('http://www.nhl.com/scores/index.html','NHL //GS','width=$hist_window_width,height=$hist_window_height,resizable=yes,scrollbars=yes,status=no');\">\n";
                 echo "<div class=\"hdrSBFutureGame\">\n";
                 echo "<table cellpadding=0 cellspacing=0 border=0 width=58>\n";
                 echo "<tr>\n";
                 echo "<td colspan=2 valign=\"bottom\" class=\"hdrSBLink\"><span class=\"hdrSBGrey\">{$day_str} {$day}/{$month}</span></td>\n";
                 echo "</tr>\n";
                 echo "<tr>\n";
                 echo "<td><span class=\"hdrSBStrg\">{$abbr_visitor}</span></td>\n";
                 echo "<td align=\"right\"><span class=\"hdrSBStrg\">-</span></td>\n";
                 echo "</tr>\n";
                 echo "<tr>\n";
                 echo "<td><span class=\"hdrSBStrg\">{$abbr_home}</span></td>\n";
                 echo "<td align=\"right\"><span class=\"hdrSBStrg\">-</span></td>\n";
                 echo "</tr>\n";
                 echo "<tr>\n";
                 echo "<td colspan=2 valign=\"top\"><span class=\"hdrSBGrey\">{$game_time}</span></td>\n";
                 echo "</tr>\n";
                 echo "</table>\n";
                 echo "</div>\n";
                 $compteur_SB++;
                 unset($ot_str, $journee, $game_time);
             }
         }
     }
     echo "<div class=\"hdrSBRule\"></div>\n";
     echo "</div>\n";
     echo "</div>\n";
     unset($SB_max, $compteur_SB, $today, $link_to_gs, $journee, $query, $resultID, $home_team, $visitor_team, $game_time, $game_result, $query2, $resultID2, $data2, $abbr_home, $abbr_visitor, $game_resultA, $goals_visitor, $goals_home, $ot_str, $game_timeA, $match_no, $nbre_de_sb_a_ajouter, $tomorrow, $date_en_traitement, $game_date, $game_date_2, $day, $day_str, $homeTeamA, $visitorTeamA, $gameTimeA, $match_noA, $index_array, $first_index_array, $data, $homeTeamBonOrderA, $visitorTeamBonOrdreA, $gameTimeBonOrdreA, $match_noBonOrdreA, $previous_game_was_finished, $my_team_goals, $my_adv_goals, $my_temps_ecoule, $my_gs_link, $str_temps_ecoule, $period, $totoA, $time_remaining, $pool, $sess);
 }
Ejemplo n.º 21
0
 $game_result = $itemA[7];
 $visitor_team_link = $itemA[8];
 $home_team_link = $itemA[9];
 $match_no = $itemA[10];
 if ($time == "") {
     $time = "TBD";
 }
 if ($ontv == "") {
     $ontv = "&nbsp;";
 }
 $dateA = explode("-", $date);
 $day = $dateA[2];
 if ($day[0] == 0) {
     $day = $day[1];
 }
 $_mydate = Datetime::createFromFormat('Y-m-d', $date, $pool->timeZone);
 $day_of_week = $_mydate->format('l');
 switch ($day_of_week) {
     case "Sunday":
         $day_of_week = "Dimanche";
         break;
     case "Monday":
         $day_of_week = "Lundi";
         break;
     case "Tuesday":
         $day_of_week = "Mardi";
         break;
     case "Wednesday":
         $day_of_week = "Mercredi";
         break;
     case "Thursday":
Ejemplo n.º 22
0
 public function formatDados($val, $type, $start = '0', $lenght = '0')
 {
     switch ($type) {
         case 'int':
             return (int) $val;
             break;
         case 'string':
             return $val;
             break;
         case 'date':
             return \Datetime::createFromFormat('Y-m-d', $val)->format('d/m/Y');
             break;
         case 'datetime':
             return \Datetime::createFromFormat('Y-m-d  H:i:s', $val)->format('d/m/Y H:i:s');
             break;
         case 'float':
             return number_format(doubleval($val), 2, ',', '.');
             break;
         case 'corte':
             break;
         case 'uper':
             return strtoupper($val);
             break;
         case 'lower':
             return strtolower($val);
             break;
         case is_array($type):
             return $type[intval($val)];
             break;
     }
 }
Ejemplo n.º 23
0
 /**
  * api-interface for transferring jobs
  * @return JsonModel
  */
 public function saveAction()
 {
     $services = $this->getServiceLocator();
     $config = $services->get('Config');
     if (True && isset($config['debug']) && isset($config['debug']['import.job']) && $config['debug']['import.job']) {
         // Test
         $this->request->setMethod('post');
         $params = new Parameters(array('applyId' => '71022', 'company' => 'Holsten 4', 'companyId' => '1745', 'contactEmail' => '*****@*****.**', 'title' => 'Fuhrparkleiter/-in', 'location' => 'Bundesland, Bayern, DE', 'link' => 'http://anzeigen.jobsintown.de/job/1/79161.html', 'datePublishStart' => '2013-11-15', 'status' => 'active', 'reference' => '2130010128', 'atsEnabled' => '1', 'logoRef' => 'http://anzeigen.jobsintown.de/companies/logo/image-id/3263', 'publisher' => 'http://anzeigen.jobsintown.de/feedbackJobPublish/' . '2130010128', 'imageUrl' => 'http://th07.deviantart.net/fs71/PRE/i/2014/230/5/8/a_battle_with_the_elements_by_lordljcornellphotos-d7vns0p.jpg'));
         $this->getRequest()->setPost($params);
     }
     $params = $this->params();
     $p = $params->fromPost();
     $user = $services->get('AuthenticationService')->getUser();
     $repositories = $services->get('repositories');
     $repositoriesJob = $repositories->get('Jobs/Job');
     $log = $services->get('Core/Log');
     //if (isset($user)) {
     //    $services->get('Core/Log')->info('Jobs/manage/saveJob ' . $user->login);
     //}
     $result = array('token' => session_id(), 'isSaved' => False, 'message' => '', 'portals' => array());
     try {
         if (isset($user) && !empty($user->login)) {
             $formElementManager = $services->get('FormElementManager');
             $form = $formElementManager->get('Jobs/Import');
             $id = $params->fromPost('id');
             // determine Job from Database
             $entity = Null;
             $createdJob = True;
             if (empty($id)) {
                 $applyId = $params->fromPost('applyId');
                 if (empty($applyId)) {
                     // new Job (propably this branch is never used since all Jobs should have an apply-Id)
                     $entity = $repositoriesJob->create();
                 } else {
                     $entity = $repositoriesJob->findOneBy(array("applyId" => (string) $applyId));
                     if (!isset($entity)) {
                         // new Job (the more likely branch)
                         $entity = $repositoriesJob->create(array("applyId" => (string) $applyId));
                     } else {
                         $createdJob = False;
                     }
                 }
             } else {
                 $repositoriesJob->find($id);
                 $createdJob = False;
             }
             //$services->get('repositories')->get('Jobs/Job')->store($entity);
             $form->bind($entity);
             if ($this->request->isPost()) {
                 $loginSuffix = '';
                 $event = $this->getEvent();
                 $loginSuffixResponseCollection = $this->getEventManager()->trigger('login.getSuffix', $event);
                 if (!$loginSuffixResponseCollection->isEmpty()) {
                     $loginSuffix = $loginSuffixResponseCollection->last();
                 }
                 $params = $this->getRequest()->getPost();
                 $params->datePublishStart = \Datetime::createFromFormat("Y-m-d", $params->datePublishStart);
                 $result['post'] = $_POST;
                 $form->setData($params);
                 if ($form->isValid()) {
                     $entity->setStatus($params['status']);
                     /*
                      * Search responsible user via contactEmail
                      */
                     $users = $repositories->get('Auth/User');
                     $responsibleUser = $users->findByEmail($params['contactEmail']);
                     $entity->setUser($responsibleUser ?: $user);
                     $group = $user->getGroup($entity->getCompany());
                     if ($group) {
                         $entity->getPermissions()->grant($group, PermissionsInterface::PERMISSION_VIEW);
                     }
                     $result['isSaved'] = true;
                     $log->info('Jobs/manage/saveJob [user: '******']:' . var_export($p, True));
                     if (!empty($params->companyId)) {
                         $companyId = $params->companyId . $loginSuffix;
                         $repOrganization = $repositories->get('Organizations/Organization');
                         $hydratorManager = $services->get('hydratorManager');
                         $hydrator = $hydratorManager->get('Hydrator/Organization');
                         $entityOrganizationFromDB = $repOrganization->findbyRef($companyId);
                         //$permissions              = $entityOrganizationFromDB->getPermissions();
                         $data = array('externalId' => $companyId, 'organizationName' => $params->company, 'image' => $params->logoRef, 'user' => $user);
                         //$permissions->grant($user, PermissionsInterface::PERMISSION_CHANGE);
                         $entityOrganization = $hydrator->hydrate($data, $entityOrganizationFromDB);
                         if ($user !== $responsibleUser) {
                             $entityOrganization->getEmployees()->add(new Employee($responsibleUser));
                         }
                         $repositories->store($entityOrganization);
                         $entity->setOrganization($entityOrganization);
                     } else {
                         $result['message'] = '';
                     }
                     $repositoriesJob->store($entity);
                     $id = $entity->getId();
                     if (!empty($id)) {
                         $jobEvent = $services->get('Jobs/Event');
                         $jobEvent->setJobEntity($entity);
                         $jobEvent->addPortal('XING');
                         if ($createdJob || True) {
                             $responses = $this->getEventManager()->trigger(JobEvent::EVENT_JOB_ACCEPTED, $jobEvent);
                             foreach ($responses as $response) {
                                 // responses from the portals
                                 // @TODO, put this in some conclusion and meaningful messages
                                 if (!empty($response)) {
                                     if ($response instanceof JobResponse) {
                                         if (!array_key_exists('log', $result)) {
                                             $result['log'] = '';
                                         }
                                         //$message = $response->getMessage();
                                         //$result['log'] .= $response->getMessage() . PHP_EOL;
                                         $status = $response->getStatus();
                                         $portal = $response->getPortal();
                                         if (empty($portal)) {
                                             throw new \RuntimeException('Publisher-Events (internal error): There is an unregistered publisher listening');
                                         }
                                         switch ($status) {
                                             case JobResponse::RESPONSE_FAIL:
                                             case JobResponse::RESPONSE_NOTIMPLEMENTED:
                                             case JobResponse::RESPONSE_ERROR:
                                                 $result['isSaved'] = false;
                                                 break;
                                             case JobResponse::RESPONSE_DENIED:
                                             case JobResponse::RESPONSE_OK:
                                             case JobResponse::RESPONSE_OKANDSTOP:
                                             case JobResponse::RESPONSE_DEPRECATED:
                                                 break;
                                         }
                                         if (array_key_exists($portal, $result['portals'])) {
                                             throw new \RuntimeException('Publisher-Events (internal error): There are two publisher registered for ' . $portal);
                                         }
                                         $result['portals'][$portal] = $status;
                                     } else {
                                         throw new \RuntimeException('Publisher-Events (internal error): Response must be from the class Jobs\\Listener\\Response\\JobResponse');
                                     }
                                 } else {
                                     throw new \RuntimeException('Publisher-Events (internal error): Response must be set');
                                 }
                             }
                         }
                     }
                 } else {
                     $log->info('Jobs/manage/saveJob [error: ' . $form->getMessages() . ']:' . var_export($p, True));
                     $result['valid Error'] = $form->getMessages();
                 }
             }
         } else {
             $log->info('Jobs/manage/saveJob [error: session lost]:' . var_export($p, True));
             $result['message'] = 'session_id is lost';
         }
     } catch (\Exception $e) {
         $result['message'] = 'exception occured: ' . $e->getMessage();
     }
     //$services->get('Core/Log')->info('Jobs/manage/saveJob result:' . PHP_EOL . var_export($p, True));
     return new JsonModel($result);
 }
Ejemplo n.º 24
0
 public function connect(Application $app)
 {
     $controllers = $app['controllers_factory'];
     // *******
     // ** Homepage
     // *******
     $controllers->get('/', function () use($app) {
         $app['session']->set('menu', 'home');
         $drinks = $app['drinks']->findNext(10);
         return $app['twig']->render('drink/index.html.twig', array('drinks' => $drinks));
     })->bind('_homepagedrinks');
     // *******
     // *******
     // ** List
     // *******
     $controllers->get('list.{format}', function ($format) use($app) {
         $app['session']->set('menu', 'listdrinks');
         //TODO pagination
         $drinks = $app['drinks']->findAll(25);
         return $app['twig']->render('drink/list.' . $format . '.twig', array('drinks' => $drinks));
     })->assert('format', 'html|atom')->bind('_listdrinks');
     // *******
     // *******
     // ** Add a drink
     // *******
     $controllers->match('new.html', function (Request $request) use($app) {
         if (!$app['session']->has('member')) {
             $app['session']->getFlashBag()->add('error', 'Vous devez être authentifié pour créer un événement.');
             return $app->redirect($app['url_generator']->generate('_signinmember'));
         }
         $app['session']->set('menu', 'newdrink');
         $form = $app['form.factory']->create('drink');
         if ('POST' === $request->getMethod()) {
             $form->bind($request->request->get('drink'));
             if ($form->isValid()) {
                 $data = $form->getData();
                 $member = $app['session']->get('member');
                 $data['member_id'] = $member['id'];
                 unset($data['captcha']);
                 try {
                     $app['drinks']->insert($data);
                 } catch (\Exception $e) {
                     $app->abort(500, 'Impossible de créer l\'événement. Merci de réessayer plus tard.');
                 }
                 $app['session']->getFlashBag()->add('success', 'L\'événement a été créé avec succès.');
                 return $app->redirect($app['url_generator']->generate('_showdrink', array('id' => $app['drinks']->lastInsertId())));
             }
         }
         return $app['twig']->render('drink/new.html.twig', array('form' => $form->createView()));
     })->bind('_newdrink')->method('GET|POST');
     // *******
     // *******
     // ** Edit a drink
     // *******
     $controllers->get('{id}/edit.html', function (Request $request, $id) use($app) {
         $app['session']->set('menu', null);
         $drink = $app['drinks']->find($id);
         if (!$drink) {
             $app->abort(404, 'Cet événement n\'existe pas.');
         }
         $now = new \Datetime('now');
         $dDrink = \Datetime::createFromFormat('Y-m-d H:i:s', $drink['day'] . ' ' . $drink['hour']);
         if ($now > $dDrink) {
             $app['session']->getFlashBag()->add('error', 'L\'événement est terminé.');
             return $app->redirect($app['url_generator']->generate('_showdrink', array('id' => $id)));
         }
         $member = $app['session']->get('member');
         if (!$member) {
             $app['session']->getFlashBag()->add('error', 'Vous devez être authentifié pour pouvoir éditer cet événement.');
             return $app->redirect($app['url_generator']->generate('_signinmember'));
         }
         if ($drink['member_id'] != $member['id']) {
             $app['session']->getFlashBag()->add('error', 'Vous devez être organisateur de cet événement pour pouvoir l\'éditer.');
             return $app->redirect($app['url_generator']->generate('_showdrink', array('id' => $id)));
         }
         $form = $app['form.factory']->create('drink', $drink);
         if ('POST' === $request->getMethod()) {
             $form->bind($request->request->get('drink'));
             if ($form->isValid()) {
                 $data = $form->getData();
                 $data['member_id'] = $member['id'];
                 unset($data['captcha']);
                 try {
                     $app['drinks']->update($data, array('id' => $drink['id']));
                 } catch (\Exception $e) {
                     $app->abort(500, 'Impossible de modifier l\'événement. Merci de réessayer plus tard.');
                 }
                 $app['session']->getFlashBag()->add('success', 'L\'événement a été modifié avec succès.');
                 return $app->redirect($app['url_generator']->generate('_showdrink', array('id' => $id)));
             } else {
                 $app['session']->getFlashBag()->add('error', 'Il y a des erreurs dans le formulaire.');
                 return $app->redirect($app['url_generator']->generate('_editdrink', array('id' => $id)));
             }
         }
         return $app['twig']->render('drink/edit.html.twig', array('form' => $form->createView(), 'id' => $id));
     })->bind('_editdrink')->method('GET|POST');
     // *******
     // *******
     // ** See a drink
     // *******
     $controllers->get('{id}/view.html/{email}/{token}', function ($id) use($app) {
         $app['session']->set('menu', null);
         $drink = $app['drinks']->find($id);
         if (!$drink) {
             $app->abort(404, 'Cet événement n\'existe pas.');
         }
         $member = $app['session']->get('member');
         $hideSpam = !($member && $member['id'] == $drink['member_id']);
         $participants = $app['drink_participants']->findByDrinkId($drink['id']);
         $presences = $app['drink_participants']->findAllPresencesInAssociativeArray();
         $comments = $app['drink_comments']->findByDrinkId($drink['id'], $hideSpam);
         $textProcessor = new \Michelf\Markdown();
         $textProcessor->no_markup = true;
         $textProcessor->no_entities = true;
         foreach ($comments as &$comment) {
             $comment['content'] = str_replace('href="javascript:', 'href="', substr($textProcessor->transform($comment['content']), 3, -5));
         }
         $user = $app['session']->get('user');
         // First, deal with participation
         $isParticipating = false;
         $data = array();
         if (null !== $user) {
             $data = array('user' => $user);
             if (false !== ($participation = $app['drink_participants']->findOne($id, $user['id']))) {
                 $data += $participation;
                 $isParticipating = true;
             }
         }
         // Avoid transformer error
         $data['reminder'] = (bool) array_key_exists('reminder', $data) ? (bool) $data['reminder'] : false;
         $participationForm = $app['form.factory']->create('drink_participate', $data);
         // If member is authenticated, prefill form.
         $data = array();
         if (null !== $user) {
             $data = array('user' => $user);
         }
         $commentForm = $app['form.factory']->create('drink_comment', $data);
         $now = new \Datetime('now');
         $dDrink = \Datetime::createFromFormat('Y-m-d H:i:s', $drink['day'] . ' ' . $drink['hour']);
         $drink['description'] = str_replace('href="javascript:', 'href="', substr($textProcessor->transform($drink['description']), 3, -5));
         return $app['twig']->render('drink/view.html.twig', array('drink' => $drink, 'participants' => $participants, 'comments' => $comments, 'commentForm' => $commentForm->createView(), 'participationForm' => $participationForm->createView(), 'isFinished' => $now > $dDrink, 'isParticipating' => $isParticipating, 'isConnected' => null !== $user, 'presences' => $presences));
     })->value('email', null)->value('token', null)->bind('_showdrink');
     // *******
     return $controllers;
 }
    private function genAdminForm($timeCutoff, $after, $rowsPerPage, $gridView, $copyVioFilter)
    {
        global $wgRequest, $wgServer;
        $columnsPerRow = $this->defaultColumnsPerRow;
        $totalImages = $rowsPerPage * ($gridView ? $columnsPerRow : 1);
        $basepage = '/' . Title::makeTitle(NS_SPECIAL, $this->specialPage);
        $html = '';
        $dateTimeTmp = Datetime::createFromFormat('YmdHis', $timeCutoff);
        $timePrintFormat = 'd M Y, H:i:s (T)';
        if (!$dateTimeTmp) {
            // Timestamp is not in MediaWiki format
            if (ctype_digit($timeCutoff)) {
                // Just interpret it as UNIX time.
                $timeCutoffPrint = Datetime::createFromFormat('U', $timeCutoff)->format($timePrintFormat);
            } else {
                // Not numeric? Ignore it and use current time
                $timeCutoff = wfTimestamp(TS_MW);
                $timeCutoffPrint = Datetime::createFromFormat('YmdHis', $timeCutoff)->format($timePrintFormat);
            }
        } else {
            $timeCutoffPrint = $dateTimeTmp->format($timePrintFormat);
        }
        $tDirection = $after ? '>' : '<';
        $tDirectionPrint = $after ? 'after' : 'before';
        $firstTime = $timeCutoff;
        $lastTime = $timeCutoff;
        $html .= <<<HHTML
<div>
\tShowing {$totalImages} results submitted {$tDirectionPrint} {$timeCutoffPrint}.<br />
\t[[NAVIGATIONLINKS]]
</div>
HHTML;
        $whereClause = array();
        $whereClause[] = 'uci_timestamp ' . $tDirection . ' ' . $timeCutoff;
        // $whereClause['uci_is_deleted'] = '0';
        if ($copyVioFilter) {
            $whereClause['uci_copyright_checked'] = '1';
            $whereClause['uci_copyright_violates'] = '1';
        } elseif ($wgRequest->getVal('hideCprViolations')) {
            $whereClause['uci_copyright_violates'] = '0';
            // $whereClause['uci_copyright_checked'] = '1';
        } elseif ($wgRequest->getVal('onlyCprChecked')) {
            $whereClause['uci_copyright_checked'] = '1';
        }
        $dbr = wfGetDB(DB_SLAVE);
        $res = $dbr->select('user_completed_images', '*', $whereClause, __METHOD__, array('ORDER BY' => 'uci_timestamp ' . ($after ? 'ASC' : 'DESC'), 'LIMIT' => $totalImages)) or die("Error, DB query failed.");
        if ($res->numRows() == 0) {
            $html .= '<br /><div align="center"><hr style="width: 80%; color: #e4e4e4; background-color: #e4e4e4; border: 1px; border-color: #e4e4e4; border-style: dashed;" /><br /></div>';
            $html .= 'No images found<br/><br/>';
        } else {
            $res_arr = array();
            foreach ($res as $row) {
                $resArr[] = $row;
            }
            if ($after) {
                $resArr = array_reverse($resArr);
            }
            $first = true;
            $imageIndex = 0;
            $thumbnailW = $gridView ? 216 : 480;
            $thumbnailH = $gridView ? 216 : -1;
            if ($gridView) {
                $html .= '<br /><div align="center"><hr style="width: 80%; color: #e4e4e4; background-color: #e4e4e4; border: 1px; border-color: #e4e4e4; border-style: dashed;" /><br /></div>';
                $html .= '<table>';
            }
            foreach ($resArr as $row) {
                $imgName = 'User-Completed-Image-' . $row->uci_image_name;
                $imgTitle = Title::makeTitleSafe(NS_IMAGE, $imgName);
                $imgPageURL = '/' . $imgTitle->getPrefixedUrl();
                $articleName = str_replace('-', ' ', $row->uci_article_name);
                $articleURL = '/' . Title::makeTitleSafe(NS_MAIN, $row->uci_article_name)->getPartialUrl();
                $user = $row->uci_user_text;
                $userURL = '/' . Title::makeTitleSafe(NS_USER, $user);
                $userPrint = "<a href=\"{$userURL}\" rel=\"nofollow\">{$user}</a>";
                $date = Datetime::createFromFormat('YmdHis', $row->uci_timestamp)->format($timePrintFormat);
                $deleteName = urlencode($imgName);
                $lastTime = $row->uci_timestamp;
                if ($first) {
                    $first = false;
                    $firstTime = $row->uci_timestamp;
                }
                $cprChecked = $row->uci_copyright_checked;
                $cprError = $row->uci_copyright_error;
                $cprViolates = $row->uci_copyright_violates;
                $cprSources = $row->uci_copyright_top_hits;
                $notfound = false;
                if (!$imgTitle) {
                    $notfound = true;
                } else {
                    $file = wfFindFile($imgTitle);
                    if (!$file) {
                        $notfound = true;
                    }
                    if ($wgRequest->getVal('updateDBFileURLs')) {
                        $fileURL = $wgServer . $file->url;
                        $dbw = wfGetDB(DB_MASTER);
                        $dbw->update('user_completed_images', array('uci_image_url' => $fileURL), array('uci_image_name' => $row->uci_image_name), __METHOD__);
                        $dbw->commit();
                    }
                }
                if ($gridView) {
                    if ($imageIndex % $columnsPerRow == 0) {
                        $html .= '<tr>';
                    }
                    $html .= '<td class="image-view-td">';
                }
                if ($notfound) {
                    $html .= <<<IMGHTML
<div id="image-{$imageIndex}" class="image-view">
\t<br />
\t<div align="center" class="image-view-elem image-not-found">
\t\t<hr style="width: 80%; color: #e4e4e4; background-color: #e4e4e4; border: 1px; border-color: #e4e4e4; border-style: dashed;" /><br />
\t</div>
\t<div class="image-view-text image-view-not-found">
\t\tAn entry for the image <a href="{$imgPageURL}" rel="nofollow">{$imgTitle}</a> was found in the database, but not found on wikiHow. The image might recently have been deleted on wikiHow without updating the database. The image was uploaded in <a href="{$articleURL}" rel="nofollow">{$articleName}</a> on {$date} by {$userPrint} according to the database entry.
\t</div>
</div>

IMGHTML;
                    if ($gridView) {
                        $html .= '</td>';
                        if (($imageIndex + 1) % $columnsPerRow == 0) {
                            $html .= '</tr>';
                        }
                    }
                    $imageIndex += 1;
                    continue;
                }
                $thumb = $file->getThumbnail($thumbnailW, $thumbnailH, true, true);
                $thumbURL = $thumb->url;
                $copyrightUnchecked = '';
                $copyrightText = '';
                $copyrightRefs = '';
                if (!$cprChecked) {
                    $copyrightUnchecked = "<div class='image-view-copyright-unchecked'>";
                    $copyrightUnchecked .= "Copyright not yet checked</div>";
                } else {
                    $copyrightText = "<div class='image-view-copyright-vio'>";
                    if ($cprError) {
                        $copyrightText .= "Error during copyright check</div>";
                    } elseif ($cprViolates) {
                        $copyrightText .= "Copyright violation detected ({$row->uci_copyright_matches} matches)</div>";
                        $copyrightRefs = "<div class='image-view-copyright-refs'>";
                        if ($cprSources) {
                            $cprRefData = json_decode($cprSources);
                            $cprRefRefs = array();
                            $cprRefImgs = array();
                            foreach ($cprRefData as $cprRefRow) {
                                $cprRefRefs[] = $cprRefRow->ref;
                                $cprRefImgs[] = $cprRefRow->img;
                            }
                            $copyrightRefs .= 'Pages: ';
                            $i = 1;
                            foreach ($cprRefRefs as $cprRefRef) {
                                $copyrightRefs .= "<a href='{$cprRefRef}'>{$i}</a> ";
                                $i++;
                            }
                            $copyrightRefs .= '<br/>Images: ';
                            $i = 1;
                            foreach ($cprRefImgs as $cprRefImg) {
                                $copyrightRefs .= "<a href='{$cprRefImg}'>{$i}</a> ";
                                $i++;
                            }
                        } else {
                            $copyrightRefs = 'No sources registered.';
                        }
                        $copyrightRefs .= '</div>';
                    } else {
                        $copyrightText = '';
                    }
                    $copyrightUnchecked = '';
                }
                $flaggedDeletion = '';
                if ($row->uci_is_deleted) {
                    $flaggedDeletion = '<div class="image-view-is-deleted">';
                    $flaggedDeletion .= 'Flagged for deletion!</div>';
                }
                $html .= <<<IMGHTML
<div id="image-{$imageIndex}" class="image-view">
\t<br />
\t<div align="center" class="image-view-elem">
\t\t<hr style="width: 80%; color: #e4e4e4; background-color: #e4e4e4; border: 1px; border-color: #e4e4e4; border-style: dashed;" /><br />
\t</div>
\t<div align="center">
\t\t<a href="{$imgPageURL}" rel="nofollow"><img src="{$thumbURL}" /></a>
\t</div>
\t<br />
\t<div class="image-view-text">
\t\t<a href="{$imgPageURL}" rel="nofollow">Image</a> uploaded in <a href="{$articleURL}" rel="nofollow">{$articleName}</a> on {$date} by {$userPrint}.
\t</div>
\t<div class="image-view-delete">(<a href="/Special:ImageUploadHandler?delete={$deleteName}" id="delete-image-{$imageIndex}" class="delete-link">Delete</a>)</div>
\t{$copyrightUnchecked}
\t{$copyrightText}
\t{$copyrightRefs}
\t{$flaggedDeletion}
</div>

IMGHTML;
                if ($gridView) {
                    $html .= '</td>';
                    if (($imageIndex + 1) % $columnsPerRow == 0) {
                        $html .= '</tr>';
                    }
                }
                $imageIndex += 1;
            }
            if ($gridView) {
                $html .= '</table>';
            }
            $html .= '<br />';
        }
        $html .= '<div align="center"><hr style="width: 80%; color: #e4e4e4; background-color: #e4e4e4; border: 1px; border-color: #e4e4e4; border-style: dashed;" /><br /></div>';
        $html .= '<style>';
        if ($gridView) {
            $html .= '.image-view {display: inline;} ';
            $html .= '.image-view-elem {display: none;} ';
            $html .= '.image-view-text {font-size: 9px;} ';
            $html .= '.image-view-td {width: 228px; border: 1px dashed #d8d8d8; background-color: #f4f4f4;} ';
            $html .= '.image-view-delete {font-size: 13px; text-align: center;} ';
            $html .= '.image-view-not-found {color: #940000;} ';
        } else {
            $html .= '.image-view-delete {font-size: 16px;} ';
        }
        $html .= '.image-view-copyright-unchecked {font-size: 10px; color: #aaaaaa;} ';
        $html .= '.image-view-copyright-vio {font-size: 11px; color: #b40000;} ';
        $html .= '.image-view-copyright-refs {font-size: 10px; color: #666666;} ';
        $html .= '.image-view-is-deleted {font-size: 11px; color: #b40000;} ';
        $html .= '</style>';
        $prevPage = $after || $wgRequest->getVal('t') ? '<a href="' . $basepage . '?t=' . $firstTime . '&a=1&r=' . $rowsPerPage . '&g=' . $gridView . '&c=' . $copyVioFilter . '" rel="nofollow">Previous</a>' : 'Previous';
        $nextPage = !$after || $wgRequest->getVal('t') ? '<a href="' . $basepage . '?t=' . $lastTime . '&a=0&r=' . $rowsPerPage . '&g=' . $gridView . '&c=' . $copyVioFilter . '" rel="nofollow">Next</a>' : 'Next';
        $newestPage = $after || $wgRequest->getVal('t') ? '<a href="' . $basepage . '?r=' . $rowsPerPage . '&g=' . $gridView . '&c=' . $copyVioFilter . '" rel="nofollow">Newest</a>' : 'Newest';
        $oldestPage = !$after || $wgRequest->getVal('t') ? '<a href="' . $basepage . '?t=0&a=1&r=' . $rowsPerPage . '&g=' . $gridView . '&c=' . $copyVioFilter . '" rel="nofollow">Oldest</a>' : 'Oldest';
        $gridToggle = '<a href="' . $basepage . '?t=' . $timeCutoff . '&a=' . $after . '&r=' . $rowsPerPage . '&g=' . !(bool) $gridView . '&c=' . $copyVioFilter . '" rel="nofollow">Toggle grid view</a>';
        $cvfToggle = '<a href="' . $basepage . '?t=' . $timeCutoff . '&a=' . $after . '&r=' . $rowsPerPage . '&g=' . $gridView . '&c=' . !(bool) $copyVioFilter . '" rel="nofollow">Toggle copyvio filter</a>';
        $ppArrVals = array(10, 25, 50, 100);
        $perPage = "<select id='ppsel'>\n";
        foreach ($ppArrVals as $ppVal) {
            $ppDisp = $ppVal * ($gridView ? $columnsPerRow : 1);
            $perPage .= "  <option value='{$basepage}?t={$timeCutoff}&a={$after}&r={$ppVal}&g={$gridView}' id='ppopt{$ppVal}'>{$ppDisp} per page</option>\n";
        }
        $perPage .= "</select>\n";
        $navLinks1 = join(' | ', array($prevPage, $nextPage, $newestPage, $oldestPage, $perPage, $gridToggle, $cvfToggle));
        $navLinks2 = join(' | ', array($prevPage, $nextPage, $newestPage, $oldestPage, $gridToggle, $cvfToggle));
        $html .= "{$navLinks2}\n";
        $html = str_replace('[[NAVIGATIONLINKS]]', $navLinks1, $html);
        $onDelete = "";
        if ($gridView) {
            $onDelete = "outerdiv.html('Deleted');";
            $onDelete .= "outertd.css('background-color', '#fafafa');";
            $onDelete .= "outerdiv.css('color', '#a4a4a4');";
            $onDelete .= "outertd.css('width','228px');";
            $onDelete .= "outertd.css('text-align', 'center');";
            $onDelete .= "outertd.css('vertical-align', 'middle');";
        } else {
            $onDelete = "outerdiv.hide();";
        }
        $html .= <<<JSHTML
<script type="text/javascript">
var rowsPerPage = {$rowsPerPage};
var select = document.getElementById('ppsel');
var match = false;
for (var opt, i = 0; opt = select.options[i]; i++) {
\tif (opt.id == "ppopt" + rowsPerPage) {
\t\tselect.selectedIndex = i;
\t\tmatch = true;
\t}
}
if (!match)
\tselect.selectedIndex = 0;
select.onchange = function() { window.location = this.value; }

\$('.delete-link').click(function(e) {
\tvar url = \$(this).attr('href');
\tvar outerdiv = \$(this).parent().parent();
\tvar outertd = outerdiv.parent();
\t\$.get(
\t\turl,
\t\tfunction (data) {
\t\t\tdata = JSON.parse(data);
\t\t\tif (data.hasOwnProperty('error')) {
\t\t\t\talert(data.error);
\t\t\t} else if (data.hasOwnProperty('success')) {
\t\t\t\t{$onDelete}
\t\t\t} else {
\t\t\t\talert('Unknown or network error');
\t\t\t}
\t\t\treturn false;
\t\t}
\t);
\treturn false;
});
</script>
JSHTML;
        return $html;
    }
Ejemplo n.º 26
0
<?php

for ($i = 1; $i < 999; $i++) {
    $datetime = Datetime::createFromFormat("u", sprintf("%06ld", $i));
    $res = $datetime->format("u");
    if ($res != $i) {
        echo "{$i} != {$res}\n";
    }
}
echo "Done";
Ejemplo n.º 27
0
    public function displayTags($field)
    {
        $post_id = get_the_ID();
        ?>
<div class='tagchecklist'><?php 
        if ($field['key'] == $field['taxonomy']) {
            if (has_term('', $field['taxonomy'], $post_id)) {
                $terms = get_the_terms($post_id, $field['taxonomy']);
                $i = 0;
                foreach ($terms as $term) {
                    // Checks if the current set term is wholly numeric (in this case a timestamp)
                    if (is_numeric($term->name)) {
                        if ($field['type'] == 'date') {
                            $natdate = date('j F Y', intval($term->name));
                        } elseif ($field['type'] == 'time') {
                            $natdate = date('h:ia T', intval($term->name));
                        } else {
                            $natdate = date('F j Y h:ia T', intval($term->name));
                        }
                        ?>
<span><a id="<?php 
                        echo esc_attr($field['taxonomy']);
                        ?>
" data-term-tag-num="<?php 
                        echo esc_attr($i);
                        ?>
"
								  class="tagdelbutton" data-term="<?php 
                        echo esc_attr($term->name);
                        ?>
"><?php 
                        echo esc_attr($term->name);
                        ?>
</a><?php 
                        ?>
&nbsp;<?php 
                        echo esc_attr($natdate);
                        ?>
</span><?php 
                    } else {
                        $date = Datetime::createFromFormat(Datetime::ISO8601, $term->name);
                        $data_term = $date ? $date->format('c') : $term->name;
                        $display = $date ? $date->format('F j Y h:ia T') : $term->name;
                        ?>
<span><a id="<?php 
                        echo esc_attr($field['taxonomy']);
                        ?>
" data-term-tag-num="<?php 
                        echo esc_attr($i);
                        ?>
"
								  class="tagdelbutton" data-term="<?php 
                        echo esc_attr($data_term);
                        ?>
"><?php 
                        echo esc_attr($data_term);
                        ?>
</a><?php 
                        ?>
&nbsp;<?php 
                        echo esc_attr($display);
                        ?>
</span><?php 
                    }
                    $this->hidden('rm_' . $field['key'] . '_' . $i, null, null);
                    $i++;
                }
            }
        }
        ?>
</div><?php 
    }
Ejemplo n.º 28
0
 public function actionRss()
 {
     $path = Yii::getAlias('@vendor/zelenin/rss-generator/Feed.php');
     require_once $path;
     $dataProvider = new \yii\data\ActiveDataProvider(['query' => \sircovsw\blog\models\BlogPost::find()->where(['status' => \sircovsw\blog\models\Status::STATUS_ACTIVE])->orderBy(['created_at' => SORT_DESC]), 'pagination' => ['pageSize' => 10]]);
     $response = Yii::$app->getResponse();
     $headers = $response->getHeaders();
     $headers->set('Content-Type', 'application/rss+xml; charset=utf-8');
     echo \Zelenin\yii\extensions\Rss\RssView::widget(['dataProvider' => $dataProvider, 'channel' => ['title' => Yii::$app->name, 'link' => Url::toRoute('/', true), 'description' => 'Блог LinkOnAvt - помощь, справочные материалы, обсуждения', 'language' => function ($widget, \Zelenin\Feed $feed) {
         return Yii::$app->language;
     }, 'image' => function ($widget, \Zelenin\Feed $feed) {
         $feed->addChannelImage('http://' . Yii::$app->params["domain"] . '/img/logo.png', 'http://' . Yii::$app->params["domain"], 100, 100, 'Продвижение сайта самостоятельно');
     }], 'items' => ['title' => function ($model, $widget, \Zelenin\Feed $feed) {
         return $model->title;
     }, 'description' => function ($model, $widget, \Zelenin\Feed $feed) {
         return StringHelper::truncateWords($model->brief, 50);
     }, 'link' => function ($model, $widget, \Zelenin\Feed $feed) {
         $url = 'http://' . Yii::$app->params["domain"] . '/blog/view/' . $model->surname;
         return $url;
         //return Yii::$app->getUrlManager()->createUrl(['blog/default/view', 'surname' => $model->surname]);
         //return Url::toRoute(['blog/default/view', 'surname' => $model->surname], true);
     }, 'author' => function ($model, $widget, \Zelenin\Feed $feed) {
         return $model->user->email . ' (' . $model->user->username . ')';
     }, 'guid' => function ($model, $widget, \Zelenin\Feed $feed) {
         $date = date('d.m.Y H:i:s', $model->created_at);
         $url = 'http://' . Yii::$app->params["domain"] . '/blog/view/' . $model->surname;
         return $url;
         //.' '.\Datetime::createFromFormat('d.m.Y H:i:s', $date)->format(DATE_RSS);
         //return Url::toRoute(['blog/default/view', 'surname' => $model->surname], true).' '.\Datetime::createFromFormat('d.m.Y H:i:s', $date)->format(DATE_RSS);
     }, 'pubDate' => function ($model, $widget, \Zelenin\Feed $feed) {
         $date = date('d.m.Y H:i:s', $model->created_at);
         return \Datetime::createFromFormat('d.m.Y H:i:s', $date)->format(DATE_RSS);
     }]]);
 }
Ejemplo n.º 29
0
<?php 
if ($periode > $last_periode_trades) {
    echo "\n          <BR>\n               <CENTER>\n                    <FONT STYLE=\"font-family:Tahoma, Verdana;font-size:18px\">La période limite des transactions est passée.</FONT>\n               </CENTER>\n     ";
    return;
}
//if ($gerant != 1) {
if ($trade_before_draft == "Y") {
    if ($pool->today < $trade_before_draft_dateBegin) {
        $_mydate = Datetime::createFromFormat('Y-m-d', $trade_before_draft_dateBegin, $pool->timeZone);
        $dateBeginMonth = $_mydate->format('m');
        $dateBeginMonth = $pool->conv_mois_numeric_to_text($dateBeginMonth);
        $dateBeginDay = $_mydate->format('j');
        $dateBeginDayText = $_mydate->format('l');
        $dateBeginDayText = $pool->date_getJour($dateBeginDayText);
        $dateBeginText = "{$dateBeginDayText}, {$dateBeginDay} {$dateBeginMonth}";
        $_mydate = Datetime::createFromFormat('Y-m-d', $trade_before_draft_dateEnd, $pool->timeZone);
        $dateEndMonth = $_mydate->format('m');
        $dateEndMonth = $pool->conv_mois_numeric_to_text($dateEndMonth);
        $dateEndDay = $_mydate->format('j');
        $dateEndDayText = $_mydate->format('l');
        $dateEndDayText = $pool->date_getJour($dateEndDayText);
        $dateEndText = "{$dateEndDayText}, {$dateEndDay} {$dateEndMonth}";
        echo "\n               <BR>\n                    <CENTER>\n                         <FONT STYLE=\"font-family:Tahoma, Verdana;font-size:18px\">La période de transaction 'avant repêchage' aura lieu du <font style=\"color:red;\">{$dateBeginText}.</font> au <font style=\"color:red;\">{$dateEndText}.</font></FONT>\n                    </CENTER>\n          ";
        return;
    }
    if ($pool->today > $trade_before_draft_dateEnd && $pool->today < $trade_date_debut) {
        echo "\n               <BR>\n                    <CENTER>\n                         <FONT STYLE=\"font-family:Tahoma, Verdana;font-size:18px\">TradeCenter sera disponible à compter du début de la saison.</FONT>\n                    </CENTER>\n          ";
        return;
    }
}
//}
Ejemplo n.º 30
0
 function getDateToStr($game_date, $game_time)
 {
     $_mydate = Datetime::createFromFormat('Y-m-d', $game_date, $ptr_pool->timeZone);
     $day_text = $_mydate->format('D');
     $day = $_mydate->format('j');
     $month_text = $_mydate->format('M');
     switch ($day_text) {
         case "Mon":
             $day_text = "Lun.";
             break;
         case "Tue":
             $day_text = "Mar.";
             break;
         case "Wed":
             $day_text = "Mer.";
             break;
         case "Thu":
             $day_text = "Jeu.";
             break;
         case "Fri":
             $day_text = "Ven.";
             break;
         case "Sat":
             $day_text = "Sam.";
             break;
         case "Sun":
             $day_text = "Dim.";
             break;
     }
     switch ($month_text) {
         case "Apr":
             $month_text = "Avr.";
             break;
         case "May":
             $month_text = "Mai";
             break;
         case "Jun":
             $month_text = "Juin";
             break;
     }
     if ($game_time == "") {
         $game_time = "TBD";
     }
     if ($day == $pool->todayDate->format('j') && $_mydate->format('m') == $ptr_pool->todayDate->format('m')) {
         $str = "Aujourd\\'hui, {$game_time}";
     } else {
         $str = "{$day_text} {$day} {$month_text}, {$game_time}";
     }
     return $str;
 }