Log viewer.

@param \Illuminate\Http\Request     $request
@param \Yajra\DataTables\DataTables $dataTables
@return \Illuminate\Http\JsonResponse
@throws \Exception
973118
public function logs(Request $request, DataTables $dataTables)
    {
        if ($request->input('l')) {
            LaravelLogViewer::setFile(base64_decode($request->input('l')));
        }

        if ($request->input('dl')) {
            return response()->download(LaravelLogViewer::pathToLogFile(base64_decode($request->input('dl'))));
        } elseif ($request->has('del')) {
            File::delete(LaravelLogViewer::pathToLogFile(base64_decode($request->input('del'))));

            return redirect()->to($request->url());
        }

        $logs = LaravelLogViewer::all();

        if ($request->wantsJson()) {
            return $dataTables->collection(collect($logs))
                              ->editColumn('stack', '{!! nl2br($stack) !!}')
                              ->editColumn('level', function ($log) {
                                  $content = html()->tag('span', '', [
                                      'class' => "glyphicon glyphicon-{$log['level_img']}-sign",
                                  ]);

                                  $content .= '&nbsp;' . $log['level'];

                                  return html()->tag('span', $content, ['class' => "text-{$log['level_class']}"]);
                              })
                              ->addColumn('content', function ($log) {
                                  $html = '';
                                  if ($log['stack']) {
                                      $html = '<a class="pull-right expand btn btn-default btn-xs"><span class="glyphicon glyphicon-search"></span></a>';
                                  }

                                  $html .= $log['text'];

                                  if (isset($log['in_file'])) {
                                      $html .= '<br>' . $log['in_file'];
                                  }

                                  return $html;
                              })
                              ->rawColumns(['content'])
                              ->toJson();
        }

        return view('administrator.utilities.log', [
            'logs'         => $logs,
            'files'        => LaravelLogViewer::getFiles(true),
            'current_file' => LaravelLogViewer::getFileName(),
        ]);
    }
740371
public function showAction(Request $request)
    {
        $gridSource = $this->get('dtc_grid.manager.source')->get($request->get('id'));
        $id = $request->get('identifier');
        $result = $gridSource->find($id);

        $responseResult = [];
        if (!$result) {
            return new Response('Not Found', 404);
        }
        if (is_array($result)) {
            foreach ($result as $key => $value) {
                $responseResult[$this->fromCamelCase($key)] = $value;
            }
        } elseif (method_exists($gridSource, 'getClassMetadata')) {
            $classMetadata = $gridSource->getClassMetadata();
            $fieldNames = $classMetadata->getFieldNames();
            foreach ($fieldNames as $fieldName) {
                $method = 'get'.ucfirst($fieldName);
                if (method_exists($result, $method)) {
                    $responseResult[$this->fromCamelCase($fieldName)] = $result->$method();
                }
            }
        }

        return new JsonResponse($responseResult);
    }
1155165
public function userActionsListAction(Request $request)
    {
        $query = $this->addOrganizationFilter($request->query->all());
        $userList = $this->logManager->getUserActionsList($query);

        return new JsonResponse($userList);
    }
133477
public function searchAction(Request $request)
    {
        if ($request->get('admin') && $request->isXmlHttpRequest()) {
            try {
                $admin = $this->getAdminPool()->getAdminByAdminCode($request->get('admin'));
            } catch (ServiceNotFoundException $e) {
                throw new \RuntimeException('Unable to find the Admin instance', $e->getCode(), $e);
            }

            if (!$admin instanceof AdminInterface) {
                throw new \RuntimeException('The requested service is not an Admin instance');
            }

            $handler = $this->getSearchHandler();

            $results = array();

            if ($pager = $handler->search($admin, $request->get('q'), $request->get('page'), $request->get('offset'))) {
                foreach ($pager->getResults() as $result) {
                    $results[] = array(
                        'label' => $admin->toString($result),
                        'link'  => $admin->generateObjectUrl('show', $result),  // Sonata uses "edit", we prefer "show"
                        'id'    => $admin->id($result),
                    );
                }
            }

            $response = new JsonResponse(array(
                'results' => $results,
                'page'    => $pager ? (int) $pager->getPage() : false,
                'total'   => $pager ? (int) $pager->getNbResults() : false,
            ));
            $response->setPrivate();

            return $response;
        }

        return $this->render($this->container->get('sonata.admin.pool')->getTemplate('search'), array(
            'base_template'       => $this->getBaseTemplate(),
            'breadcrumbs_builder' => $this->get('sonata.admin.breadcrumbs_builder'),
            'admin_pool'          => $this->container->get('sonata.admin.pool'),
            'query'               => $request->get('q'),
            'groups'              => $this->getAdminPool()->getDashboardGroups(),
        ));
    }
1162189
public function search(HTTPRequest $request)
    {
        // Detect Ajax:
        
        if (!$request->isAjax()) {
            return;
        }
        
        // Initialise:
        
        $data = ['results' => []];
        
        // Create Data List:
        
        $list = $this->getList();
        
        // Filter Data List:
        
        if ($term = $request->getVar('term')) {
            $list = $list->filterAny($this->getSearchFilters($term))->exclude($this->getExclude());
        }
        
        // Sort Data List:
        
        if ($sort = $this->getSortBy()) {
            $list = $list->sort($sort);
        }
        
        // Limit Data List:
        
        if ($limit = $this->getLimit()) {
            $list = $list->limit($limit);
        }
        
        // Define Results:
        
        foreach ($list as $record) {
            $data['results'][] = $this->getResultData($record);
        }
        
        // Answer JSON Response:
        
        return $this->respond($data);
    }
796907
public function index(Request $request)
    {
        $rows = $this->noticiaRepo->findAndPaginate($request);
        $categorias = $this->categoriaRepo->listPub();

        return view('admin.noticias.list', compact('rows','categorias'));
    }
397665
public function getResult($table, Request $request)
    {
        $attributes = new Attribute($table);
        if ($request->ajax()) {
            return response()->json($attributes->getAttributes(), 200);
        }
    }
1003458
public function listAction(Request $request)
    {
        $query = $this->addOrganizationFilter($request->query->all());

        return new JsonResponse($this->finder->search(
            $this->getClass(),
            $query,
            []
        ));
    }
28549
private static function readLogs(LogReadRequest $request) {
    $response = new LogReadResponse();
    try {
      ApiProxy::makeSyncCall('logservice', 'Read', $request, $response);
    } catch (ApplicationError $e) {
      throw self::applicationErrorToException($e);
    }
    return $response;
  }
197341
public function handle(HttpRequest $request)
    {
        $routeClass = Loader::load('route');

        $route = new $routeClass($this->route, $request->method());
        $controllerClassMethod = $route->resolve();
        if (false === $controllerClassMethod) {
            throw new Exception('Can\t resolve route.'); // TODO: Change to 404 response
        }

        $controllerClass = array_shift($controllerClassMethod);
        $controllerMethod = array_shift($controllerClassMethod);

        $controller = new $controllerClass($request);
        if (method_exists($controller, $controllerMethod)) {
            $output = call_user_func_array(array($controller, $controllerMethod), $route->get());
        } else {
            throw new ApplicationException(sprintf('Method "%s" doesn\'t exists in class "%s".', $method, $controllerClass)); // TODO: Change to 404 response
        }

        if ($request->isAjax()) {
            return json_encode($output);
        } else {
            return $output;
        }
    }
680998
public function resolveRequest(Request $request)
    {
        $format = $request->attributes->get(
            'format',
            $request->attributes->get('_format', 'html')
        );
        
        switch ($format) {
            case 'html':
            case 'page':
                return new DefaultHtmlRenderer();
                break;
            case 'api':
            case 'json':
                return new JsonApiRenderer();
                break;
            default:
                throw new InvalidConfigurationException(sprintf("Unsupported response format %s", $format));
        }
    }
320545
public function handleRequest(TableInterface $table, Request $request)
    {
        // execute query with filters
        $rows = $this->getRows($table, $request);

        // params for twig parts
        $twigParams = array(
            'table' => $table,
            'rows' => $rows,
        );

        $template = $this->twig->loadTemplate($table->getTemplate());

        $responseParams = array(
            'page' => $table->getPage(),
            'rowsPerPage' => $table->getRowsPerPage(),
            'totalRows' => $table->getTotalRows(),
            'filteredRows' => $table->getFilteredRows(),
            'lastPage' => $table->getLastPage(),
            'tableBody' => $template->renderBlock(
                'tableBody',
                array_merge($twigParams, array('tableRenderBody' => true), $table->getTemplateParams())
            ),
            //"tableFoot"=>$template->renderBlock("tableFoot", $twigParams),
            'tableStats' => $template->renderBlock(
                'tableStatsAjax',
                array_merge($twigParams, array('tableRenderStats' => true))
            ),
            'tablePagination' => $template->renderBlock(
                'tablePaginationAjax',
                array_merge($twigParams, array('tableRenderPagination' => true))
            ),
        );

        // encode response
        $response = new Response(json_encode($responseParams));

        return $response;
    }
1341177
protected function logException($request, $exception)
    {
        if (!$this->getConfig('log')) {
            return;
        }

        foreach ((array)$this->getConfig('skipLog') as $class) {
            if ($exception instanceof $class) {
                return;
            }
        }

        Log::error($this->getMessage($request, $exception));
    }
386249
public function getAjaxList(Request $request) // GET THE SLUG, ex. 'posts', 'pages', etc.
    {
        // GET THE SLUG, ex. 'posts', 'pages', etc.
        $slug = $request->slug;

        // GET THE DataType based on the slug
        $dataType = Admin::model('DataType')->where('slug', '=', $slug)->first();

        // Check permission
        $this->authorize('browse', app($dataType->model_name));

        $model = app($dataType->model_name);
        $query = $model->select('*');

        if (method_exists($model, 'adminList')) {
            $query = $model->adminList()->select('*');
        }

        if (!isset($request->order)) {
            if ($model->timestamps) {
                $query = $query->latest($model::CREATED_AT);
            } else {
                $relationships = $this->getRelationships($dataType);
                $query = $query->with($relationships)->orderBy($model->getKeyName(), 'DESC');
            }
        }

        $query = DataTables::of($query);

        foreach ($dataType->ajaxList() as $dataRow) {
            $query->editColumn($dataRow->field, function($dataTypeContent) use($request, $slug, $dataRow){
                $content = $dataTypeContent->{$dataRow->field};

                $handler = AbstractHandler::initial($dataRow->type);

                if (method_exists($handler, 'getContentForList')) {
                    $content = $handler->getContentForList($request, $slug, $dataRow, $dataTypeContent);
                }

                return $content;
            });

            if ($dataRow->type == 'relationship') {
                $query->filterColumn($dataRow->field, function ($query, $keyword) use($dataRow){
                    $relationship = json_decode($dataRow->details);
                    $ids = app($relationship->model)->where($relationship->label, 'like', "%$keyword%")->pluck($relationship->key);
                    $query->whereIn($relationship->column, $ids);
                });
            }
        }

        return $query
            ->addColumn('delete_checkbox', function($dataTypeContent) {
                return '<input type="checkbox" name="row_id" id="checkbox_' . $dataTypeContent->id . '" value="' . $dataTypeContent->id . '">';

            })
            ->addColumn('actions', function($dataTypeContent) use($dataType){
                return Admin::view('admin::list.datatable.buttons', ['data' => $dataTypeContent, 'dataType' => $dataType]);
            })
            ->rawColumns(array_merge($dataType->ajaxListFields(), ['delete_checkbox', 'actions']))
            ->make(true);
    }
1174966
public function render($request, Exception $e)
    {
        if ($this->isHttpException($e))
        {
            if ($request->segment(1) == config('expendable.admin_base_uri') && !config('app.debug'))
            {
                return app('Distilleries\Expendable\Http\Controllers\Backend\Base\ErrorController')->callAction("display", [$e, $e->getStatusCode()]);
            }
        }

        return parent::render($request, $e);
    }
26261
protected function generateDataRequest(WebRequest $request, TableAbstract $table, $numberOfEntries)
    {
        $sortBy = 'name';
        $sortByDirection = 'ASC';
        
        // If the session has a data request object for the table, load it and refresh the data.
        $savedDataRequestKey = get_class($table) . '.DataRequest.Saved';
        $dataRequest = false;
        if ($table->shouldSaveDataRequest() && $request->getSessionData($savedDataRequestKey) !== false) {
            $dataRequest = unserialize($request->getSessionData($savedDataRequestKey));
        }
        
        // Check if the data request is valid
        if ($dataRequest === false) {
            $dataRequest = new DataRequest(1, $numberOfEntries, $sortBy, $sortByDirection);
        }
        
        // Save the data request to the session if needed
        if ($table->shouldSaveDataRequest()) {
            $request->setSessionData($savedDataRequestKey, serialize($dataRequest));
        }

        return $dataRequest;
    }
862863
public function previewAction(Request $request, DataInterface $data)
    {
        return $this->editAction($request, $data, $data->getFamily());
    }