function getInfo($slug)
 {
     $production = Production::where(Production::ATTR_SLUG, $slug)->get();
     if (count($production) == 0) {
         //Verifica en el log el slug
         if (is_null($id = Slug::getIdProduction($slug))) {
             return abort(404);
         } else {
             return redirect("production/" . Production::findOrNew($id)->slug);
         }
     }
     $production = $production[0];
     //Visitantes
     if (!Auth::check()) {
         return view("frontend/contents/production/play-forbbiden")->with("production", $production)->with("message", view("ui/msg/contents/info-production-login")->with("production", $production)->render());
     }
     $categories = $production->terms;
     $director = $production->staff()->count() > 0 ? $production->staff()->where(Person::ATTR_PIVOT_ROLE, Person::ROLE_DIRECTOR)->get()[0] : null;
     $staff = $production->staff()->count() > 0 ? $production->staff()->where(Person::ATTR_PIVOT_ROLE, Person::ROLE_ACTOR)->get() : null;
     $isVideoMain = $production->haveVideoMain() && $production->state == Production::STATE_ACTIVE;
     $chapters = $production->chapters;
     $rating_count = $production->ratings()->count();
     $rating = number_format($production->ratings()->avg('rating') * 100 / 5, 0);
     $userIsRated = ProductionRating::userIsRated($production->id);
     $inFav = Production::inFavorites($production->id);
     $view = view("frontend/contents/production/info")->with("production", $production)->with("categories", $categories)->with("staff", $staff)->with("director", $director)->with("isVideoMain", $isVideoMain)->with("chapters", $chapters)->with("rating", $rating)->with("rating_count", $rating_count)->with("userIsRated", $userIsRated)->with("inFav", $inFav);
     //Muestra un mensaje para indicarle al usuario que debe activar su cuenta
     if (Auth::user()->state == User::STATE_UNCONFIRMED_ACCOUNT) {
         Session::put(\App\System\Library\Complements\UI::modalMessage("¡ACTIVA TU CUENTA!", view("ui/msg/contents/activa-tu-cuenta")->render()));
     }
     return $view;
 }
 function postReportProblem(Request $request)
 {
     $extensions = array("png", "jpg", "jpeg");
     $data = $request->all();
     if (!isset($data[Report::ATTR_TYPE]) || !isset($data[Report::ATTR_DESCRIPTION])) {
         return redirect()->back();
     }
     $report = new Report();
     $report->user_id = Auth::user()->id;
     $report->type = $data[Report::ATTR_TYPE];
     $report->date = DateUtil::getCurrentTime();
     $report->description = Util::trimText(strip_tags($data[Report::ATTR_DESCRIPTION]), 500);
     $report->image = null;
     if ($request->hasFile(Report::ATTR_IMAGE)) {
         $image = $request->file(Report::ATTR_IMAGE);
         $extension = strtolower($image->getClientOriginalExtension());
         //Valida la extension del archivo
         if (!in_array($extension, $extensions)) {
             return redirect()->back()->with(UI::message(UI::MESSAGE_TYPE_ERROR, "Extension de archivo no permitida, no es una imagen valida."));
         }
         //Valida el tamaño del archivo
         if ($image->getSize() > 2000000) {
             return redirect()->back()->with(UI::message(UI::MESSAGE_TYPE_ERROR, "Tamaño del archivo excesivo. Maximo 2MB"));
         }
         //Almacena la imagen subida por el usuario en la carpeta temporal
         $filename = DateUtil::getTimeStamp() . "." . $extension;
         $image->move(Auth::user()->getPathUploads(), $filename);
         $report->image = url(Auth::user()->getPathUploads() . $filename);
     }
     $report->save();
     return redirect("browser")->with(UI::modalMessage("¡Gracias por tu reporte!", "Tus comentarios acerca de tu experencia ayudan a mejorar la plataforma de Bandicot. Nos pondremos en contacto contigo por correo electrónico si necesitamos saber más detalles del problema.", "Cerrar"));
 }
 function getDeleteProcess($id_process)
 {
     $process = AutoProcess::find($id_process);
     if (is_null($process)) {
         return abort(403);
     }
     $process->delete();
     return redirect()->back()->with(UI::message(UI::MESSAGE_TYPE_INFO, trans("sec.autoProcess.delete.msj.success"), null, 2));
 }
 public function postLogin(Request $request)
 {
     $data = $request->all();
     //Login aceptado
     if (Auth::attempt([User::AUTH_EMAIL => $data[User::AUTH_EMAIL], User::AUTH_PASSWORD => $data[User::AUTH_PASSWORD]], isset($data[User::AUTH_REMEMBER]))) {
         return redirect("manager/dashboard");
         //Login Incorrecto
     } else {
         return redirect()->back()->withInput()->with(UI::message(UI::MESSAGE_TYPE_WARNING, trans("msg.login.error")));
     }
 }
 /**
  * Verifica el estado Premium del usuario y su tiempo. 
  */
 public function checkStatePremium($request)
 {
     $description = "<p class='caption'>Lamentamos informarte que el tiempo de cuenta premium para disfrutar sin limites en bandicot se ha terminado. Queremos agradecerte por usar nuestra plataforma y pasar tu tiempo con nosotros.</p>" . "<h2 class='text-center' style='margin-top: 45px;margin-bottom: 30px;'>¿Quieres continuar sin limitaciones con una cuenta premium?</h2>" . "<div class='text-center'><img style='width: 23%;' src='" . url("assets/images/logo-premium.png") . "'/><br/><br/><a href='" . url("premium") . "' class='btn btn-primary'><span class='glyphicon glyphicon-arrow-up'></span> ¡Actualizar a cuenta premium!</a></div>";
     if (Auth::user()->role == User::ROLE_SUSCRIPTOR_PREMIUM) {
         $time = DateUtil::difSec(DateUtil::getCurrentTime(), Auth::user()->premium_to);
         if ($time <= 0) {
             Auth::user()->role = User::ROLE_SUSCRIPTOR;
             Auth::user()->save();
             $request->session()->put(UI::modalMessage("<span class='glyphicon glyphicon-time'></span> ¡Tu tiempo de cuenta premium se ha terminado!", $description, "Cerrar"));
         }
     }
 }
 function postCreate(Request $request)
 {
     $data = $request->all();
     //Registra una nueva cuenta de videocloud
     $account = new VideoCloudAccount();
     $account->email = $data["email"];
     $account->token = $data["token"];
     $account->player = $data["player"];
     $date = new DateUtil(DateUtil::getCurrentTime());
     $account->date = $date->getCurrentTime();
     $account->end = $date->addMonths(1);
     $account->save();
     return redirect()->back()->with(UI::message(UI::MESSAGE_TYPE_SUCCESS, "Cuenta creada exitosamente"));
 }
 public function postEditPassword(Request $request)
 {
     $data = $request->all();
     if (strlen($data["pass-new"]) <= 5) {
         return redirect()->back()->with(UI::message(UI::MESSAGE_TYPE_ERROR, trans("msg.editPass.error.pass.new.invalid"), null, 2));
     }
     if ($data["pass-new"] != $data["pass-rep"]) {
         return redirect()->back()->with(UI::message(UI::MESSAGE_TYPE_ERROR, trans("msg.editPass.error.pass.new.not.match"), null, 2));
     }
     if (User::editPassword($data["pass"], $data["pass-new"])) {
         return redirect()->back()->with(UI::message(UI::MESSAGE_TYPE_SUCCESS, trans("msg.editPass.success"), null, 2));
     } else {
         return redirect()->back()->with(UI::message(UI::MESSAGE_TYPE_ERROR, trans("msg.editPass.error.pass.current"), null, 2));
     }
 }
 /** Recibe un peticion para crear una cuenta de usuario
  * 
  * @param Request $request
  * @return string
  */
 function postCreateAccount(Request $request)
 {
     $data = $request->all();
     // return redirect()->back()->with("error","El registro de usuarios no esta habilitado en este momento.");
     if (strlen($data[User::ATTR_NAME]) == 0 || strlen($data[User::ATTR_LASTNAME]) == 0 || !filter_var($data[User::ATTR_EMAIL], FILTER_VALIDATE_EMAIL) || strlen($data[User::ATTR_PASSWORD]) < 6) {
         return redirect()->back()->with(User::ATTR_NAME, $data[User::ATTR_NAME])->with(User::ATTR_LASTNAME, $data[User::ATTR_LASTNAME])->with(User::ATTR_EMAIL, $data[User::ATTR_EMAIL])->with("error", trans("gen.info.error"));
     }
     //*******************************************
     //CONTROL DE CAPTCHA
     //*******************************************
     //   $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6LdEcQ4TAAAAABgMkSCLV3iVH-sXXk5Xqb79dfNt&response=".$data["g-recaptcha-response"]."&remoteip=".$_SERVER['REMOTE_ADDR']);
     $reCaptcha = new ReCaptcha("6LdEcQ4TAAAAABgMkSCLV3iVH-sXXk5Xqb79dfNt");
     // si se detecta la respuesta como enviada
     if (!$data["g-recaptcha-response"]) {
         return redirect()->back()->with(User::ATTR_NAME, $data[User::ATTR_NAME])->with(User::ATTR_LASTNAME, $data[User::ATTR_LASTNAME])->with(User::ATTR_EMAIL, $data[User::ATTR_EMAIL])->with("error-captcha", trans("gen.error.captcha"));
     }
     $response = $reCaptcha->verifyResponse($_SERVER["REMOTE_ADDR"], $data["g-recaptcha-response"]);
     //Valida el captcha
     if ($response == null || !$response->success) {
         return redirect()->back()->with(User::ATTR_NAME, $data[User::ATTR_NAME])->with(User::ATTR_LASTNAME, $data[User::ATTR_LASTNAME])->with(User::ATTR_EMAIL, $data[User::ATTR_EMAIL])->with("error-captcha", trans("gen.error.captcha"));
     }
     //Verifica si el corre ingresado existe
     if (User::existEmail($data[User::ATTR_EMAIL])) {
         return redirect()->back()->with(User::ATTR_NAME, $data[User::ATTR_NAME])->with(User::ATTR_LASTNAME, $data[User::ATTR_LASTNAME])->with(User::ATTR_EMAIL, $data[User::ATTR_EMAIL])->with("error", "El correo electrónico ingresado ya esta registrado");
     }
     $keyActivation = \hash("sha256", $data[User::ATTR_EMAIL]);
     $user = new User();
     $user->name = ucfirst($data[User::ATTR_NAME]);
     $user->lastname = ucfirst($data[User::ATTR_LASTNAME]);
     $user->email = $data[User::ATTR_EMAIL];
     $user->password = bcrypt($data[User::ATTR_PASSWORD]);
     $user->state = User::STATE_UNCONFIRMED_ACCOUNT;
     $user->role = User::ROLE_SUSCRIPTOR;
     $user->keyActivation = $keyActivation;
     $user->save();
     //Crea las carpetas de manejo de archivos del usuarios
     mkdir(public_path($user->getPathTemporal()));
     mkdir(public_path($user->getPathUploads()));
     $activationLink = url("user/confirm/email/" . $keyActivation);
     $description = "<p>Este correo electrónico ha sido asociado a una nueva cuenta en bandicot&#46;com, para poder usar esta cuenta es necesario activarla confirmando este correo electrónico.</p>" . "<p>Para confirmar este correo electrónico debes hacer clic en botón \"Activar cuenta\" que se muestra a continuación:<br/><br/>" . "<a style='display: block;padding: 10px;border: 1px black solid;width: 200px;text-align: center;color: white;background: red;-webkit-border-radius: 5px;-moz-border-radius: 5px;border-radius: 5px;font-style: normal;text-transform: uppercase;margin: auto;' href='" . $activationLink . "' target='_blank'>Activar cuenta</a></p>" . "<p>Si el botón no funciona, copia y pega el siguiente enlace para activar tu cuenta:<br/><br/>{$activationLink}</p>" . "<p><i><b>Atención:<b/> Si crees que se ha tratado de una equivocación, por favor ignora este mensaje.</i></p>";
     $email = new Email("Activación de cuenta", $data[User::ATTR_EMAIL], [Email::VAR_NAME => $user->name, Email::VAR_DESCRIPTION => $description]);
     $email->send();
     Auth::loginUsingId($user->id);
     return redirect("user/dashboard")->with(UI::modalMessage("¡Bienvenido a Bandicot.com!", view("ui/msg/contents/bienvenido-a-bandicot-com")->render()));
 }
 function postEdit(Request $request)
 {
     $data = $request->all();
     $production = Production::findOrNew($data[Production::ATTR_ID]);
     $data[Production::ATTR_SLUG] = Util::createSlug($data[Production::ATTR_TITLE] . " " . $data[Production::ATTR_YEAR]);
     $production->fill($data);
     $production->save();
     $terms = $production->terms;
     //Categorias
     $cats = array();
     foreach ($data as $index => $value) {
         if (strpos($index, "cat-") !== false) {
             $cats[] = $value;
         }
     }
     $terms_id = array();
     foreach ($terms as $term) {
         $terms_id[] = $term->id;
     }
     //Obtiene los terminos a disociar
     $unset = array_diff($terms_id, $cats);
     //Obtiene los termino a asociar
     $set = array_diff($cats, $terms_id);
     foreach ($unset as $index => $value) {
         $production->terms()->detach($value);
     }
     foreach ($set as $index => $value) {
         $production->terms()->attach($value);
     }
     return redirect()->back()->with(UI::message(UI::MESSAGE_TYPE_WARNING, trans("msg.info.change.saved"), null, 2));
 }
 /** Activa la cuenta del usuario dirigida desde el link con el codigo enviado por correo al usuario
  * 
  * @param Request $request
  */
 function getActivateAccount($token)
 {
     if (Auth::user()->state == User::STATE_ACTIVED_ACCOUNT) {
         return redirect("");
     }
     if (!is_null(User::where(User::ATTR_EMAIL, Auth::user()->email)->where(User::ATTR_KEY_ACTIVATION, $token)->get())) {
         $user = User::findOrNew(Auth::user()->id);
         $user[User::ATTR_STATE] = User::STATE_ACTIVED_ACCOUNT;
         $user->save();
         return redirect("user/dashboard")->with(UI::modalMessage("¡Gracias por activar tu cuenta!", view("ui/msg/contents/gracias-por-activar-tu-cuenta")->render()));
     }
     return redirect("");
 }
 public function postSetResetPassword(Request $request)
 {
     $data = $request->all();
     if (!isset($data[PasswordReset::ATTR_TOKEN]) || !isset($data[User::ATTR_EMAIL]) || strlen($data[PasswordReset::ATTR_TOKEN]) == 0 || strlen($data[User::ATTR_EMAIL]) == 0 || !isset($data["password"])) {
         return redirect("user/auth/recovery?request=send-mail&form=token")->with(User::ATTR_EMAIL, $data[User::ATTR_EMAIL])->with(UI::message(UI::MESSAGE_TYPE_ERROR, "Error: Solicitud invalida"));
     }
     $email = $data[PasswordReset::ATTR_EMAIL];
     $token = $data[PasswordReset::ATTR_TOKEN];
     if (is_null($pet = PasswordReset::where(PasswordReset::ATTR_EMAIL, $email)->where(PasswordReset::ATTR_TOKEN, $token)->where(PasswordReset::ATTR_ACTIVE, Util::convertBooleanToInt(true))->get())) {
         return redirect("user/auth/recovery?request=send-mail&form=token")->with(User::ATTR_EMAIL, $data[User::ATTR_EMAIL])->with(UI::message(UI::MESSAGE_TYPE_ERROR, "Error: Solicitud invalida"));
     }
     if (DateUtil::difSec($pet[0]->created_at, DateUtil::getCurrentTime()) > 60 * 60 * 2) {
         $pet[0]->active = Util::convertBooleanToInt(false);
         $pet->save();
         return redirect("user/auth/recovery?request=send-mail&form=token")->with(User::ATTR_EMAIL, $data[User::ATTR_EMAIL])->with(UI::message(UI::MESSAGE_TYPE_ERROR, "Error: El código de seguridad ha expirado. <a href='" . url("user/auth/recovery") . "'>¿Realizar una nueva solicitud?</a>"));
     }
     $user = User::where(User::ATTR_EMAIL, $email)->get()[0];
     $user->password = bcrypt($data["password"]);
     $user->save();
     return redirect("user/auth/login")->withInput()->with(UI::message(UI::MESSAGE_TYPE_SUCCESS, "Tu nueva contraseña ha sido establecida, ya puedes iniciar sesión"))->with(User::ATTR_EMAIL, $data[User::ATTR_EMAIL]);
 }
 /** Recibe la peticion del estado de la transaccion realizada
  * 
  * @return type
  */
 public function getStatus()
 {
     // Get the payment ID before session clear
     $payment_id = \Session::get('paypal_payment_id');
     $payment_quantity = Session::get('payment_quantity');
     // clear the session payment ID
     Session::forget('paypal_payment_id');
     $payerId = isset($_GET['PayerID']) ? $_GET['PayerID'] : null;
     $token = isset($_GET['token']) ? $_GET['token'] : null;
     if (is_null($payerId) || is_null($token)) {
         return redirect()->back()->with(UI::modalMessage("Pago cancelado", "<div class='text-center'><img width='150px;' src='" . url('assets/images/sad.png') . "'><p style='font-size: 15pt;margin-top:20px;'>Parece ser que has cancelado el pago. ¿Quieres intentarlo de nuevo?</p></div>", "Cerrar"));
     }
     $payment = Payment::get($payment_id, $this->_api_context);
     $execution = new PaymentExecution();
     $execution->setPayerId($payerId);
     $result = $payment->execute($execution, $this->_api_context);
     if ($result->getState() == 'approved') {
         PayM::newRecord($token, $payerId, $payment_id, $payment_quantity);
         $date = new DateUtil(Auth::user()->premium_to);
         $message = view("ui/msg/contents/muchas-gracias-usuario")->with("date_premium", $date->getDay() . " de " . $date->getMonth() . " del " . $date->getYear())->render();
         $email = new Email("¡Gracias " . Auth::user()->name . " por tu aporte!", Auth::user()->email);
         $email->setDescription($message);
         $email->setName(Auth::user()->name);
         //Envia un correo de agredecimiento
         $email->queue();
         return redirect("user/contributions")->with(UI::modalMessage("Pago realizado. ¡Muchas gracias " . Auth::user()->name . "!", $message, "De nada, es un placer"));
     }
     return redirect()->back()->with(UI::modalMessage("ERROR", "<div class='text-center'><img width='150px;' src='" . url('assets/images/alert.png') . "'><p style='font-size: 15pt;margin-top:20px;'>Parece que hubo un problema al realizar el pago. ¿No tienes fondos?</p></div>", "Cerrar"));
 }