Returns "hours ago" result with absolute diff in hours

@param DateDiffRequest $request
@return DateDiffResult
429008
public static function calculateHoursAgo(DateDiffRequest $request)
    {
        return new DateDiffResult($request, self::HOURS_AGO, (int)floor(abs($request->getDiffInSeconds()) / Unit::HOUR));
    }
603765
public function retrieveCurrent(Request $request)
    {
        if (ConfigQuery::isRewritingEnable()) {
            $view = $request->attributes->get('_view', null);

            $viewLocale = $this->getViewLocale($request);

            $viewId = $view === null ? null : $request->query->get($view . '_id', null);

            $allOtherParameters = $request->query->all();
            if ($view !== null) {
                unset($allOtherParameters['view']);
                if ($viewId !== null) {
                    unset($allOtherParameters[$view . '_id']);
                }
            }
            if ($viewLocale !== null) {
                unset($allOtherParameters['lang']);
                unset($allOtherParameters['locale']);
            }

            $this->retriever->loadSpecificUrl($view, $viewLocale, $viewId, $allOtherParameters);
        } else {
            $allParametersWithoutView = $request->query->all();
            $view = $request->attributes->get('_view');
            if (isset($allOtherParameters['view'])) {
                unset($allOtherParameters['view']);
            }
            $this->retriever->rewrittenUrl = null;
            $this->retriever->url = URL::getInstance()->viewUrl($view, $allParametersWithoutView);
        }

        return $this->retriever;
    }
989759
public function cgetAction(Request $request)
    {
        $locale = $this->getLocale($request);

        // if the type parameter is falsy, assign NULL to $type
        $type = $request->query->get('type', null) ?: null;

        $idsString = $request->get('ids');

        if ($idsString) {
            $ids = explode(',', $idsString);
            $snippets = $this->snippetRepository->getSnippetsByUuids($ids, $locale);
            $total = count($snippets);
        } else {
            $snippets = $this->snippetRepository->getSnippets(
                $locale,
                $type,
                $this->listRestHelper->getOffset(),
                $this->listRestHelper->getLimit(),
                $this->listRestHelper->getSearchPattern(),
                $this->listRestHelper->getSortColumn(),
                $this->listRestHelper->getSortOrder()
            );

            $total = $this->snippetRepository->getSnippetsAmount(
                $locale,
                $type,
                $this->listRestHelper->getSearchPattern(),
                $this->listRestHelper->getSortColumn(),
                $this->listRestHelper->getSortOrder()
            );
        }

        $data = new ListRepresentation(
            $snippets,
            'snippets',
            'get_snippets',
            $request->query->all(),
            $this->listRestHelper->getPage(),
            $this->listRestHelper->getLimit(),
            $total
        );

        return $this->viewHandler->handle(View::create($data));
    }
1268296
public function index(Request $request)
    {
        $limit = 20;
        $prev = null;
        $user = $request->user();

        $this->validate($request, [
            'since'     => 'iso8601',
            'until'     => 'iso8601',
            'cursor'    => 'uuid',
            'tag_id'    => 'uuid',
            'source_id' => 'uuid',
            ]);

        $dids = $user->dids()
            ->fullTextSearchFilter($request->q, $user->id)
            ->tagFilter($request->tag_id)
            ->sourceFilter($request->source_id)
            ->cursorFilter($request->cursor)
            ->dateFilter($request->since, $request->until)
            ->with(['tags', 'source'])
            ->orderBy(DB::raw('uuid_v1_timestamp(id)'), 'DESC')
            ->limit($limit)->get();

        // if the cursor is being passed in then we need to obtain the previous id.
        if(!empty($request->cursor)){
            $dids_prev = $user->dids()
                ->fullTextSearchFilter($request->q, $user->id)
                ->tagFilter($request->tag_id)
                ->sourceFilter($request->source_id)
                ->prevFilter($request->cursor)
                ->dateFilter($request->since, $request->until)
                ->orderBy(DB::raw('uuid_v1_timestamp(id)'), 'ASC')
                ->limit($limit)->get();

            if($dids_prev->count() == $limit) $prev = $dids_prev->last()->id;
        }

        $results = fractal()
            ->collection($dids, new DidTransformer())
            ->withCursor(new Cursor($request->cursor, $prev, $dids, $limit));

        return response()->json($results);
    }
1193279
protected function hasNotExpired($request) : bool
  {
    if (!isset($_SESSION['_cksal'])) return false;

    $this->createUrl($request, 'expire');

    if (in_array($request->path(), $this->canExpire)) return true;

    $time = $_SESSION['_cksal'];
    $time = base64_decode($time);

    $expire = config('auth.expire.session_token');

    if(strtotime($time) < strtotime("-$expire")) {
      $this->hasExpired = true;
      return false;
    }

    return true;
  }
170663
public function getIndexNamesForSearch(SearchEventsRequest $request): array
    {
        /** @var \DateTime $after */
        /** @var \DateTime $before */
        $after = $request->get('occurred_after');
        $before = $request->get('occurred_before');

        /*
         * when no lower bound is used, we must assume they meant to search
         * all events to the beginning of time.  this could take forever.
         */
        if (null === $after) {
            return [$this->indexPrefix . '*'];
        }

        // if no upper bound is present, make one up
        $end = $before ?: new \DateTime('now', new \DateTimeZone('UTC'));

        /*
         * now, while start is less than end... accumulate the intervals as indices
         * if the span results in too many indices, use a wildcard to prevent urls
         * being too long for a GET request (multi-index searches have index in url)
         */
        $indices = [];
        $start = clone $after;

        do {
            $indices[$this->indexPrefix . $this->getIndexIntervalSuffix($start)] = true;
            $start = $start->modify('+1 week');
        } while ($start < $end);
        $indices[$this->indexPrefix . $this->getIndexIntervalSuffix($start)] = true;

        if (count($indices) > 9) {
            $start = clone $after;
            $indices = [];
            do {
                $indices[$this->indexPrefix . $start->format('Y') . '*'] = true;
                $start = $start->modify('+1 year');
            } while ($start < $end);
        }

        return array_keys($indices);
    }
806825
public static function calculateDaysAgo(DateDiffRequest $request)
    {
        return new DateDiffResult($request, self::DAYS_AGO, $request->getInterval()->days);
    }
677503
public function forecast(Request $request)
    {
        $lowm = new LaravelOWM();
        $tz = new \DateTimeZone(config('app.timezone'));

        $city = $request->get('city');
        $coordinates = $request->get('coord');
        $lang = $request->get('lang', 'en');
        $units = $request->get('units', 'metric');
        $days = $request->get('days', 5);

        if ($city === null && $coordinates == null) {
            abort('400','City or coordinates cannot be undefined.');
        }

        $query = ($city) ?: $coordinates;

        try {
            $forecast = $lowm->getWeatherForecast($query, $lang, $units, $days, true);
        } catch(\Exception $e){
            return response()->json(['status' => 'error', 'message' => $e->getMessage(), 'code' => $e->getCode()]);
        }

        $data = [
            'city' => [
                'id' => $forecast->city->id,
                'name' => $forecast->city->name,
                'lat' => $forecast->city->lat,
                'lon' => $forecast->city->lon,
                'country' => $forecast->city->country,
                'population' => $forecast->city->population
            ],
            'sun' => [
                'rise' => [
                    'date' => $forecast->sun->rise->setTimezone($tz)->format('Y-m-d H:i:s'),
                    'timestamp' => $forecast->sun->rise->setTimezone($tz)->getTimestamp()
                ],
                'set' => [
                    'date' => $forecast->sun->set->setTimezone($tz)->format('Y-m-d H:i:s'),
                    'timestamp' => $forecast->sun->set->setTimezone($tz)->getTimestamp()
                ]
            ],
            'lastUpdate' => [
                'date' => $forecast->lastUpdate->setTimezone($tz)->format('Y-m-d H:i:s'),
                'timestamp' => $forecast->lastUpdate->setTimezone($tz)->getTimestamp()
            ]
        ];

        foreach ($forecast as $obj) {

            $day = $obj->time->day->setTimezone($tz);
            $from = $obj->time->from->setTimezone($tz);
            $to = $obj->time->to->setTimezone($tz);

            $temp = [

                'time' => [
                    'from' => [
                        'date' => $from->format('Y-m-d H:i:s'),
                        'timestamp' => $from->getTimestamp()
                    ],
                    'to' => [
                        'date' => $to->format('Y-m-d H:i:s'),
                        'timestamp' => $to->getTimestamp()
                    ],
                    'day' => [
                        'date' => $day->format('Y-m-d H:i:s'),
                        'timestamp' => $day->getTimestamp()
                    ],
                ],

                'lastUpdate' => [
                    'date' => $obj->lastUpdate->setTimezone($tz)->format('Y-m-d H:i:s'),
                    'timestamp' => $obj->lastUpdate->setTimezone($tz)->getTimestamp()
                ]
            ];

            if (isset($last_day)) {

                if($day->format('Y-m-d H:i:s') == $last_day){

                    // ISO-8601 numeric representation of the day of the week
                    // 1 (for Monday) through 7 (for Sunday)
                    $day_key = $day->format('N');

                    // The OWM API returns 3 hour forecast data, it means for each day you requested you'll
                    // get weather data each 3 hours in this order:
                    // 06:00 - 09:00, 09:00 - 12:00, 12:00 - 15:00, 15:00 - 18:00, 18:00 - 21:00, 21:00 - 00:00.
                    // So to maintain a well-ordered info I built a key depending on the hours range
                    // (ie: ['06-09'] => [ ... ]).
                    $time_key = $from->format('H').'-'.$to->format('H');

                    $data['days'][$day_key][$time_key] = array_merge($temp, $this->parseData($obj));
                }
            }

            $last_day = $day->format('Y-m-d H:i:s');
        }

        return response()->json(['status' => 'ok', 'data' => $data]);
    }
39819
public function adminSchoolPeriodeAddAction(Request $request)
    {
        $this->checkOpen();
        $periode = new Periode();
        $form = $this->createForm(new PeriodeType, $periode);

        if ($request->getMethod() === 'POST') {
            $form->handleRequest($request);

            if ($form->isValid()) {
                $this->em->persist($periode);
                $this->em->flush();
            }
        }
        return array('form' => $form->createView(), 'action' => $this->generateUrl('laurentBulletinPeriodeAdd'));
    }
351312
public function postIndex(Request $request) {
		//regular login
		if (DB::table(config('center.db.users'))->count()) {
			//attempt auth
			if (Auth::attempt(['email'=>$request->input('email'), 'password'=>$request->input('password')], true)) {

				DB::table(config('center.db.users'))->where('id', Auth::user()->id)->update([
					'last_login'=>new DateTime
				]);
												
				return redirect()->intended(action('\LeftRight\Center\Controllers\TableController@index'));
				
			}
			return redirect()->action('\LeftRight\Center\Controllers\TableController@index')->with('error', trans('center::site.login_invalid'));
		} 
		
		//installing, make user
		$user_id = DB::table(config('center.db.users'))->insertGetId([
			'name'			=> $request->input('name'),
			'email'			=> $request->input('email'),
			'password'		=> Hash::make($request->input('password')),
			'last_login'	=> new DateTime,
			'updated_at'	=> new DateTime,
			'updated_by'	=> 1,
		]);
				
		Auth::loginUsingId($user_id, true);

		return redirect()->action('\LeftRight\Center\Controllers\TableController@index');
	}
461132
public function fetchAction(Request $request)
    {
        $reference = strtoupper($request->query->get('reference', null));
        $remote = (bool)$request->query->get('remote', 1);

        if (0 < strlen($reference) && $remote) {
            $remoteEndPoints = $this->container->getParameter('ekyna_setting.helper_remotes');
            foreach ($remoteEndPoints as $remoteEndPoint) {
                // remote=0 prevent infinite loop/recursion
                $url = $remoteEndPoint . '?reference=' . $reference . '&remote=0';
                $headers = $request->headers->all();
                if (null !== $response = $this->getRemoteResponse($url, $headers)) {
                    return $response;
                }
            }
        }

        $ttl = 7 * 24 * 3600;
        $response = new Response();
        $response
            ->setPublic()
            ->headers->add(['Content-Type' => 'application/xml; charset=utf-8'])
        ;

        if (0 < strlen($reference)) {
            $repository = $this->getDoctrine()->getRepository('EkynaSettingBundle:Helper');
            if (null !== $helper = $repository->findOneBy(['reference' => $reference])) {
                $response->setLastModified($helper->getUpdatedAt());
                if ($response->isNotModified($request)) {
                    return $response;
                }
                $response->setContent($this->renderView('EkynaSettingBundle:Helper:show.xml.twig', [
                    'helper' => $helper,
                ]));
                return $this->configureSharedCache($response, [$helper->getEntityTag()], $ttl);
            }
        }

        $expires = new \DateTime();
        $expires->modify('+7 days');
        return $response
            ->setMaxAge($ttl)
            ->setExpires($expires)
            ->setContent($this->renderView('EkynaSettingBundle:Helper:show.xml.twig'))
        ;
    }
700876
public static function calculateSecondsAgo(DateDiffRequest $request)
    {
        return new DateDiffResult($request, self::SECONDS_AGO, abs($request->getDiffInSeconds()));
    }
684411
protected function find($request)
    {
        $max = 20;
        if (isset($request['max'])) {
            $max = $request['max'];
        }

        $offset = 0;
        if (isset($request['offset'])) {
            $offset = $request['offset'];
        }

        $filters = array();
        foreach (array('utime', 'datetime', 'ip', 'uri', 'method') as $key) {
            if (isset($request[$key])) {
                $filters[$key] = $request[$key];
            }
        }

        return $this->debugBar->getStorage()->find($filters, $max, $offset);
    }
905795
public function sortListingDurations(Request $request)
    {
        $this->validate(
            $request,
            [
                'listing_durations' => 'required|array',
            ]
        );

        foreach ($request->input('listing_durations') as $listing_duration_id => $sort) {
            $listing_duration = ListingDuration::find($listing_duration_id);

            $listing_duration->sort = $sort;

            $listing_duration->save();
        }

        return redirect()->back()->withStatus(trans('mustard::admin.listing_durations_sorted'));
    }
1330706
public function getDateDifference($created)
    {
        $now = $this->datetime->gmtDate();

        return strtotime($now) - strtotime($created);
    }
569311
public function getSchedulerAction(Request $request)
    {
        /** @var LiveInformation $information */
        $information = $this->app['task-manager.live-information'];
        $data = $information->getManager();

        return Result::create($request, [
            'scheduler' => [
                'configuration' => $data['configuration'],
                'state' => $data['actual'],
                'status' => $data['actual'],
                'pid' => $data['process-id'],
                'process-id' => $data['process-id'],
                'updated_on' => (new \DateTime())->format(DATE_ATOM),
            ],
        ])->createResponse();
    }
30919
public function postCancel(Request $request)
    {
        $item = Item::findOrFail($request->input('item_id'));

        if ($item->userId != Auth::user()->userId) {
            return redirect()->back()->withErrors(['You can only end your own items.']);
        }

        if ($item->endDate < time()) {
            return redirect()->back()->withErrors(['This item has already ended.']);
        }

        $item->cancel();

        return redirect('/inventory/unsold')
            ->withStatus($item->name.' has been cancelled.');
    }