/** Recibe una peticion Ajax para actualiza la foto de perfil de un usuario
  * 
  * @param Request $request
  * @return type
  */
 function ajaxUpdateAvatar(Request $request)
 {
     if (!$request->ajax() || !Auth::check()) {
         return json_encode(array());
     }
     $extensions = array("png", "jpg", "jpeg");
     $avatar = $request->file("upload-avatar");
     $extension = strtolower($avatar->getClientOriginalExtension());
     //Valida la extension del archivo
     if (!in_array($extension, $extensions)) {
         return json_encode(array("error" => "Extension de archivo no permitida"));
     }
     //Valida el tamaño del archivo
     if ($avatar->getSize() > 2000000) {
         return json_encode(array("error" => "Tamaño del archivo excesivo"));
     }
     //Almacena la imagen subida por el usuario en la carpeta temporal
     $filename = DateUtil::getTimeStamp() . "." . $extension;
     $temp = Auth::user()->getPathTemporal();
     $avatar->move($temp, $filename);
     //Crear carpeta de usuario predeterminada
     $image = new Image(url($temp . $filename));
     $url_avatar = $image->createCopy(200, 200, DateUtil::getTimeStamp(), public_path(Auth::user()->getPathUploads()), false);
     //Elimina el archivo temporal
     unlink(Util::convertUrltoPath(url($temp . $filename)));
     //Registra el nuevo avatar en la base de datos
     $user = User::findOrNew(Auth::user()->id);
     //Si el usuario tiene definido un avatar, lo elimina
     if (!is_null($user->avatar)) {
         unlink(Util::convertUrltoPath($user->avatar));
     }
     $user->avatar = $url_avatar;
     $user->save();
     return json_encode(array("url" => $url_avatar));
 }
 function setImageProduction($production_id)
 {
     if (!isset($_GET["poster"])) {
         return "Sin poster";
     }
     /**
      *  MODIFICAR LA IMAGEN DE UNA PRODUCCION
      */
     $production = Production::find($production_id);
     $data[Production::ATTR_IMAGE] = "";
     $data[Production::ATTR_POSTER] = "http://" . $_GET["poster"];
     $path_image = public_path("assets/db/images/") . md5($production->title_original . $production->year);
     copy($data[Production::ATTR_POSTER], $path_image . "-poster.jpg");
     $production->poster = Util::convertPathToUrl($path_image . "-poster.jpg");
     if (strlen($data[Production::ATTR_IMAGE]) > 9) {
         copy($data[Production::ATTR_IMAGE], $path_image . ".jpg");
         $production->image = Util::convertPathToUrl($path_image . ".jpg");
     } else {
         $title_md5 = md5($production->title_original . $production->year);
         $image = new Image($production->poster);
         $production->image = $image->createCopy(214, 334, $title_md5, public_path("assets/db/images/"), false);
     }
     $production->save();
     return "REALIZADO EXITOSAMENTE";
 }
 function postCreate(Request $request)
 {
     $data = $request->all();
     //SLUG
     $data[Production::ATTR_SLUG] = Util::createSlug($data[Production::ATTR_TITLE] . " " . $data[Production::ATTR_YEAR]);
     $data[Production::ATTR_STATE] = Production::STATE_IN_WAIT;
     $production = new Production();
     $production->fill($data);
     $production->save();
     //Asigna las Categorias
     foreach ($data as $index => $value) {
         if (strpos($index, "cat-") !== false) {
             $production->terms()->attach($value);
         }
     }
     /*
      * OBTIENES LAS IMAGENES DE LA PRODUCCION
      */
     $path_image = public_path("assets/db/images/") . md5($production->title_original . $production->year);
     copy($data[Production::ATTR_POSTER], $path_image . "-poster.jpg");
     $production->poster = Util::convertPathToUrl($path_image . "-poster.jpg");
     if (strlen($data[Production::ATTR_IMAGE]) > 9) {
         copy($data[Production::ATTR_IMAGE], $path_image . ".jpg");
         $production->image = Util::convertPathToUrl($path_image . ".jpg");
     } else {
         $title_md5 = md5($production->title_original . $production->year);
         $image = new Image($production->poster);
         $production->image = $image->createCopy(214, 334, $title_md5, public_path("assets/db/images/"), false);
     }
     $production->save();
     //Cola de procesamiento
     $queue = new QueueProductions();
     //Si existe
     if (QueueProductions::existsByLink($data["imdb"])) {
         $queue = QueueProductions::where(QueueProductions::ATTR_LINK, $data["imdb"])->get()[0];
     } else {
         $queue->name = $data[Production::ATTR_TITLE_ORIGINAL];
         $queue->link = $data["imdb"];
         $queue->date_creation = DateUtil::getCurrentTime();
     }
     $queue->production_id = $production->id;
     $queue->date_processed = DateUtil::getCurrentTime();
     $queue->save();
     return redirect("manager/productions/edit/" . $production->id);
 }
 /**
  * Carga los atributos de la produccion dado por el contenido proveido en la URL
  */
 private function loadAttributes()
 {
     //Obtiene la tabla de referencia de información de la produccion
     if (!preg_match_all('/<table[^>]*id=["\']title-overview-widget-layout*["\']\\>(.*?)<\\/table>/', $this->htmlContent, $match)) {
         return;
     }
     $match_content = $match[0][0];
     //(TITULO)**********************************/
     //
     //Obtiene el encabezado para extraer la información mas importante
     if (!preg_match_all('/<h1 [^>]*class=["\']header*["\']\\>(.*?)<\\/h1>/i', $match_content, $match, PREG_SET_ORDER)) {
         return;
     }
     //Obtiene la referencia al titulo de la produccion
     if (!preg_match_all('/<span[^>]*class=["\']itemprop*["\'] itemprop=["\']name*["\']\\>(.*?)<\\/span>/i', $match[0][0], $match_title, PREG_SET_ORDER)) {
         return;
     }
     //Asigna el titulo de la produccion
     $this->title = strip_tags(isset($match_title[0][1]) ? $this->getLatinTitle($match_title[0][1]) : null);
     $title_ori = $match_title[0][1];
     //(AÑO)*************************************/
     //Obtiene el año de lanzamiento de la produccion
     if (!preg_match_all('/<span[^>]*class=["\']nobr*["\']\\>(.*?)<\\/span>/i', $match[0][0], $match_year, PREG_SET_ORDER)) {
         return;
     }
     $this->year = str_replace(array("(", ")"), "", strip_tags(isset($match_year[0][1]) ? $match_year[0][1] : null));
     //(TITULO ORIGINAL)*************************/
     //Busca el titulo original de la produccion, si no lo encuentra asigna el titulo encontrado
     if (preg_match_all('/<span[^>]*itemprop=["\']name*["\']\\>(.*?)<\\/span>/i', $match[0][0], $match_title_original, PREG_SET_ORDER)) {
         $this->title_original = str_replace(array("\"", "(original title)", "  "), "", strip_tags(isset($match_title_original[0][0]) ? $match_title_original[0][0] : null));
     } else {
         $this->title_original = $title_ori;
     }
     //(SLUG)*************************/
     $this->slug = Util::createSlug(trim($this->title) . " " . $this->year);
     //(DESCRIPCION)*************************/
     if (!preg_match_all('/<p[^>]*itemprop=["\']description*["\']\\>(.*?)<\\/p>/i', $match_content, $match_description, PREG_SET_ORDER)) {
         return;
     }
     $this->description = Util::traslateText(strip_tags(isset($match_description[0][1]) ? $match_description[0][1] : null));
     //SECCION INFOBAR PARA EXTRAER - DURACION - CATEGORIAS
     if (!preg_match_all('/<div[^>]*class=["\']infobar*["\']\\>(.*?)<\\/div>/i', $match_content, $match_infobar, PREG_SET_ORDER)) {
         return;
     }
     //(DURACION)*************************/
     if (preg_match_all('/<time[^>]*itemprop=["\']duration*["\'](.*?)\\>(.*?)<\\/time>/i', $match_infobar[0][1], $match_duration, PREG_SET_ORDER)) {
         $this->duration = intval(preg_replace("/[^0-9-.]/", "", strip_tags($match_duration[0][2])));
     }
     //(CATEGORIAS)*************************/
     if (!preg_match_all('/<a\\s+.*?href=[\\"\']\\/genre\\/(.+?)[\\"\']?[^>]*>(.*?)<\\/a>/i', $match_infobar[0][1], $match_categories, PREG_SET_ORDER)) {
         return;
     }
     foreach ($match_categories as $category) {
         $cat = strip_tags($category[2]);
         $this->categories[] = Util::textDecodetoSimply($cat);
     }
     //RATING
     if (preg_match_all('/<div[^>]*class=["\']titlePageSprite star-box-giga-star*["\']\\>(.*?)<\\/div>/i', $match_content, $match_rating, PREG_SET_ORDER)) {
         $this->rating_rel = trim(strip_tags($match_rating[0][1]));
     }
     //IMAGEN
     if (!preg_match_all('/<img\\s+.*?src=[\\"\']?([^\\"\' >]*)[\\"\']?[^>]*>/i', $match_content, $match_image, PREG_SET_ORDER)) {
         return;
     }
     $path_image = public_path("assets/db/images/") . md5($this->title_original . $this->year);
     try {
         if (Util::UrlExist(strip_tags($match_image[0][1]))) {
             copy(strip_tags($match_image[0][1]), $path_image . ".jpg");
             $this->image = Util::convertPathToUrl($path_image . ".jpg");
         } else {
             $this->image = null;
         }
     } catch (Exception $e) {
         $this->image = null;
     }
     //POSTER
     $search = new BingSearchImage($this->title_original . " poster " . $this->year, 1700, 1200);
     $images = $search->getResult();
     //Verifica que la url este bien
     $i = -1;
     do {
         $i++;
         $url_poster = $images[$i];
     } while (!Util::UrlExist($url_poster));
     try {
         if (is_array(@getimagesize($url_poster))) {
             copy($url_poster, $path_image . "-poster.jpg");
             $this->poster = Util::convertPathToUrl($path_image . "-poster.jpg");
         } else {
             $this->poster = null;
         }
     } catch (Exception $e) {
         $this->poster = null;
     }
     if (is_null($this->image) && !is_null($this->poster)) {
         $md5 = md5($this->title_original . $this->year);
         $image = new Image($this->poster);
         $this->image = $image->createCopy(214, 334, $md5, public_path("assets/db/images/"), false);
     }
     //(PERSONAL DE LA PRODUCCION)*************************************
     if (!preg_match_all('/<div\\s+.*?itemprop=[\\"\']director[\\"\']?[^>]*>(.*?)<\\/div>/i', $match_content, $match_director_bar, PREG_SET_ORDER)) {
         return;
     }
     //DIRECTOR
     if (!preg_match_all('/<a[^>]*href=["\']\\/name\\/.*["\']*itemprop=["\']url*["\']\\>(.*?)<\\/a>/i', $match_director_bar[0][1], $match_director, PREG_SET_ORDER)) {
         return;
     }
     $this->director = array(trim(strip_tags($match_director[0][1])), $this->extractLinkPerson($match_director[0][0]));
     //Actores
     if (!preg_match_all('/<table[^>]*class=["\']cast_list*["\']\\>(.*?)<\\/table>/', $this->htmlContent, $match_cast)) {
         return;
     }
     if (!preg_match_all('/(<a)?[^>]*href=["\']\\/name\\/(.*?)itemprop=["\']url*(.*?)<span[^>]*class=["\']itemprop*["\'] itemprop=["\']name*["\']\\>(.*?)<\\/span><\\/a>/i', $match_cast[0][0], $match_actors, PREG_SET_ORDER)) {
         return;
     }
     foreach ($match_actors as $actor) {
         $this->actors[] = array(trim(strip_tags($actor[0])), $this->extractLinkPerson($actor[0]));
     }
 }