/**
  * Action - video
  * upload/download/ordering video
  * 
  * Access to the action is possible in the following paths:
  * - /blogmanager/video
  *
  * @return void
  */
 public function videoAction()
 {
     $json = array();
     $filterSanitize = new Default_Form_Filter_Sanitize();
     //-----------------------
     // Получим обьект записи
     $request = $this->getRequest();
     $params = $request->getParams();
     $post_id = (int) $request->getPost('id');
     if (!$post_id) {
         $post_id = (int) $request->getParam('id');
     }
     $post = new Default_Model_DbTable_BlogPost($this->db);
     // Если конкретной записи нет, то перейдем к странице по умолчанию
     if (!$post->loadForUser($this->_identity->user_id, $post_id)) {
         $this->_redirect('/blogmanager');
     }
     // Определим тип операции над видео: 'upload', 'reorder', 'delete'
     // Загрузка файла с помощью - FileUploader
     if (Default_Plugin_FileUploader::isFileUploader()) {
         // Получим вид загрузчика - Iframe или Xhr
         $fileUploader = Default_Plugin_FileUploader::isFileUploader();
         // list of valid extensions, ex. array("jpeg", "xml", "bmp")
         $allowedExtensions = $params['allowedExtensions'];
         $allowedExtensions = str_replace(' ', '', $allowedExtensions);
         $arrAllowedExtensions = explode(';', $allowedExtensions);
         // max file size in bytes
         $sizeLimit = (int) $request->getParam('sizeLimit');
         // Получим обьект загрузчика файлов
         try {
             $uploader = new Default_Plugin_FileUploader($arrAllowedExtensions, $sizeLimit);
             // Определим путь загрузки файлов
             $path = Default_Model_DbTable_BlogPostVideo::GetUploadPath();
             $path .= '/';
             //Загрузим файлы
             $result = $uploader->handleUpload($path);
         } catch (Exception $e) {
             $json = array('class_message' => 'warning', 'messages' => array('<em>' . $this->Translate('Ошибка загрузки файла') . '</em>', Default_Plugin_SysBox::getMessageError($e)));
             if ($fileUploader == 'Iframe') {
                 $this->sendJson_Html($json);
             } else {
                 $this->sendJson($json);
             }
             return;
         }
         if (isset($result['success'])) {
             // Создадим обьект изображения
             try {
                 $filename = $path . $uploader->file->getName();
                 $pathinfo = pathinfo($filename);
                 $ext = $pathinfo['extension'];
                 $video = new Default_Model_DbTable_BlogPostVideo($post->getDb());
                 $video->post_id = $post->getId();
                 $video->uploadFile($filename);
                 $video->identifier = basename($filename);
                 $video->type = 'file-' . $ext;
                 if (!$video->save()) {
                     $json = array('class_message' => 'warning', 'messages' => array('<em>' . $this->Translate('Ошибка при сохранении данных') . '</em>'));
                     if ($fileUploader == 'Iframe') {
                         $this->sendJson_Html($json);
                     } else {
                         $this->sendJson($json);
                     }
                     return;
                 }
                 $json['success'] = $result['success'];
                 $json['video_id'] = $video->getId();
                 $json['filename'] = $video->identifier;
                 $json['post_id'] = $video->post_id;
                 $json['form_action'] = $this->getUrl('video', 'blogmanager');
                 // Определим путь к изображению для видео
                 $srcImage = 'images/media/thumbs/' . $video->type . '.png';
                 $json['url_image'] = $this->getUrlRes($srcImage) . '?id=' . $video->getId();
             } catch (Exception $e) {
                 $json = array('class_message' => 'warning', 'messages' => array('<em>' . $this->Translate('Ошибка загрузки файла') . '</em>', Default_Plugin_SysBox::getMessageError($e)));
                 if ($fileUploader == 'Iframe') {
                     $this->sendJson_Html($json);
                 } else {
                     $this->sendJson($json);
                 }
                 return;
             }
         } else {
             // Error
             $json = array('class_message' => 'warning', 'messages' => array('<em>' . $this->Translate('Ошибка загрузки файла') . '</em>', $result['error']));
             if ($fileUploader == 'Iframe') {
                 $this->sendJson_Html($json);
             } else {
                 $this->sendJson($json);
             }
             return;
         }
     } else {
         if ($request->getPost('add_video_url')) {
             // Создадим обьект изображения
             try {
                 $strInfoVideo = $request->getPost('info_video');
                 $strInfoVideo = stripslashes($strInfoVideo);
                 $arrInfoVideo = Zend_Json::decode($strInfoVideo);
                 $video = new Default_Model_DbTable_BlogPostVideo($post->getDb());
                 $video->post_id = $post->getId();
                 $video->identifier = $arrInfoVideo['url'];
                 $video->type = $arrInfoVideo['type'];
                 if (!$video->save()) {
                     $json = array('class_message' => 'warning', 'messages' => array('<em>' . $this->Translate('Ошибка при сохранении данных') . '</em>'));
                     $this->sendJson($json);
                     return;
                 }
                 // Определим путь к изображению для видео
                 $srcImage = 'images/media/thumbs/' . $video->type . '.png';
                 $json['video_id'] = $video->getId();
                 $json['filename'] = $video->identifier;
                 $json['post_id'] = $video->post_id;
                 $json['url_image'] = $this->getUrlRes($srcImage) . '?id=' . $video->getId();
                 $json['form_action'] = $this->getUrl('video', 'blogmanager');
                 $json['result'] = $this->Translate('URL на ресурс добавлен');
             } catch (Exception $e) {
                 $json = array('class_message' => 'warning', 'messages' => array('<em>' . $this->Translate('Ошибка загрузки файла') . '</em>', Default_Plugin_SysBox::getMessageError($e)));
                 $this->sendJson($json);
                 return;
             }
         } else {
             if ($request->getPost('reorder')) {
                 $order = $request->getPost('preview-video');
                 $post->setVideoOrder($order);
             } else {
                 if ($request->getPost('delete')) {
                     $video_id = (int) $request->getPost('image');
                     $video = new Default_Model_DbTable_BlogPostVideo($this->db);
                     if ($video->loadForPost($post->getId(), $video_id)) {
                         $video->delete();
                         // Определим кол. оставшихся изображений
                         $count_videos = count($post->video) - 1;
                         $json = array('deleted' => true, 'image_id' => $video_id, 'count_images' => $count_videos);
                     }
                 } else {
                     if ($request->getPost('comment_update')) {
                         $video_id = (int) $request->getPost('image');
                         $video = new Default_Model_DbTable_BlogPostVideo($this->db);
                         if ($video->loadForPost($post->getId(), $video_id)) {
                             $comment = $request->getPost('comment');
                             // Отфильтруем ненужные теги в комментарии
                             $comment = $filterSanitize->filter($comment);
                             // Выделим название и комментарий
                             $arrComment = explode('#', $comment);
                             // Если тип видео -> 'url-godtv', то важно получить точное название видео
                             // это название должно точно соответствовать пути к загрузочной странице этого видео
                             // пр. http://god-tv.ru/%D0%A0%D0%B5%D1%88%D0%B0%D1%8E%D1%89%D0%B8%D0%B9-%D1%80%D1%8B%D0%B2%D0%BE%D0%BA-%D1%81%D0%BC%D0%BE%D1%82%D1%80%D0%B5%D1%82%D1%8C-%D0%BE%D0%BD%D0%BB%D0%B0%D0%B9%D0%BD
                             // или так %D0%A0%D0%B5%D1%88%D0%B0%D1%8E%D1%89%D0%B8%D0%B9-%D1%80%D1%8B%D0%B2%D0%BE%D0%BA-%D1%81%D0%BC%D0%BE%D1%82%D1%80%D0%B5%D1%82%D1%8C-%D0%BE%D0%BD%D0%BB%D0%B0%D0%B9%D0%BD
                             // или так "Решающий-рывок-смотреть-онлайн"
                             if ($video->type == 'url-godtv') {
                                 $tmpName = urldecode($arrComment[0]);
                                 $tmpNames = explode('/', $tmpName);
                                 $tmpName = $tmpNames[count($tmpNames) - 1];
                                 $arrComment[0] = $tmpName;
                             }
                             if (count($arrComment) > 1) {
                                 $video->name = $arrComment[0];
                                 $video->comment = $arrComment[1];
                             } else {
                                 $video->name = $arrComment[0];
                             }
                             // Сохраним в базе данных
                             if (!$video->save()) {
                                 $json = array('class_message' => 'warning', 'messages' => array('<em>' . $this->Translate('Ошибка при сохранении данных') . '</em>'));
                                 $this->sendJson($json);
                                 return;
                             }
                             $json = array('commented' => true, 'title' => $video->name, 'comment' => $video->comment);
                         }
                     } else {
                         if ($request->getPost('download_images')) {
                             // Загрузим изображения в виде HTML на страницу
                             // Получим файлы видео для статьи
                             $videos = Default_Model_DbTable_BlogPostVideo::GetVideo($this->db, array('post_id' => $post_id));
                             // Создадим обьект шаблона
                             $templater = Default_Plugin_SysBox::createViewSmarty();
                             //Установим параметры шаблона
                             $templater->videos = $videos;
                             $templater->post_id = $post_id;
                             // Получим результат шаблона
                             $html = $templater->render('blogmanager/lib/download-video.tpl');
                             $json = array('downloaded' => true, 'html' => $html);
                         }
                     }
                 }
             }
         }
     }
     if ($this->_isAjaxRequest) {
         $this->sendJson($json);
     } else {
         $this->sendJson_Html($json);
     }
 }
示例#2
0
 /**
  * Get the array of records satisfying the criteria specified in the parameter $options using Zend_Paginator
  * 
  * @param Zend_Db_Adapter_Abstract $db
  * @param array $options
  * @return array  Default_Model_DbTable_BlogPost objects
  */
 public static function GetPaginatorPosts($db, $options = array())
 {
     $arrResult = array();
     $_config = Zend_Registry::get('config');
     $itemCountPerPage = (int) $_config['paginator']['itemCountPerPage'];
     $pagesInRange = (int) $_config['paginator']['pagesInRange'];
     //---------------------------------------------------------
     // инициализация опций
     $defaults = array('itemCountPerPage' => $itemCountPerPage, 'pagesInRange' => $pagesInRange, 'page' => 1, 'offset' => 0, 'limit' => 0, 'order' => 'p.ts_created', 'sort' => true);
     foreach ($defaults as $k => $v) {
         $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
     }
     $select = self::_GetBaseQuery($db, $options);
     // установим поля таблицы для запроса
     $select->from(null, 'p.*');
     // set the offset, limit, and ordering of results
     if ($options['limit'] > 0) {
         $select->limit($options['limit'], $options['offset']);
     }
     // Установим параметры сортировки для таблицы
     if ($options['sort']) {
         $select = self::GetSelectForSort($select, $options);
     }
     //------ Создадим обьект Zend_Paginator ---------
     $strSelect = $select->__toString();
     $adapter = new Zend_Paginator_Adapter_DbSelect($select);
     $count = self::GetPostsCount($db, $options);
     $adapter->setRowCount($count);
     $paginator = new Zend_Paginator($adapter);
     // Установим максимальное количество отображаемых на странице элементов
     $paginator->setItemCountPerPage($options['itemCountPerPage']);
     // Установи массив страниц, возвращенный текущим стилем прокрутки
     $paginator->setPageRange($options['pagesInRange']);
     // Установим текущую страницу
     $paginator->setCurrentPageNumber($options['page']);
     //----- Конфигурирование кеша для Paginator -----
     $pgCache = Default_Plugin_SysBox::getCache('paginator');
     if ($pgCache->getOption('caching')) {
         // Установим кеш для Paginator
         Zend_Paginator::setCache($pgCache);
         // Очищение кеша
         if (Default_Plugin_SysBox::isCleanCache()) {
             $paginator->clearPageItemCache();
         }
     }
     // получим данные в виде массива обьектов Default_Model_DbTable_BlogPost
     $posts = self::BuildMultiple($db, __CLASS__, $paginator);
     $post_ids = array_keys($posts);
     if (count($post_ids) == 0) {
         return array();
     }
     // получим данные о загруженных сообщениях
     $profiles = Default_Model_Profile::BuildMultiple($db, 'Default_Model_DbTable_BlogPostProfile', array($post_ids));
     foreach ($posts as $post_id => $post) {
         if (array_key_exists($post_id, $profiles) && $profiles[$post_id] instanceof Default_Model_DbTable_BlogPostProfile) {
             $posts[$post_id]->profile = $profiles[$post_id];
         } else {
             $posts[$post_id]->profile->setPostId($post_id);
         }
         //!!!!------ Начало установки признака сортировки -----!!!!!
         if (isset($options['sortColumn'])) {
             $posts[$post_id]->sortColumn = $options['sortColumn'];
         }
         if (isset($options['ascDescFlg'])) {
             $posts[$post_id]->ascDescFlg = $options['ascDescFlg'];
         }
         //!!!!------ Конец установки признака сортировки -----!!!!!
     }
     // load the images for each post
     $options = array('post_id' => $post_ids);
     $images = Default_Model_DbTable_BlogPostImage::GetImages($db, $options);
     foreach ($images as $image) {
         $posts[$image->post_id]->images[$image->getId()] = $image;
     }
     // load the locations for each post
     $locations = Default_Model_DbTable_BlogPostLocation::GetLocations($db, $options);
     foreach ($locations as $l) {
         $posts[$l->post_id]->locations[$l->getId()] = $l;
     }
     // load the audio for each post
     $audios = Default_Model_DbTable_BlogPostAudio::GetAudio($db, $options);
     foreach ($audios as $audio) {
         $posts[$audio->post_id]->audio[$audio->getId()] = $audio;
     }
     // load the video for each post
     $videos = Default_Model_DbTable_BlogPostVideo::GetVideo($db, $options);
     foreach ($videos as $video) {
         $posts[$video->post_id]->video[$video->getId()] = $video;
     }
     // load the comments for each post
     $comments = Default_Model_DbTable_BlogPostComment::GetComments($db, $options);
     foreach ($comments as $comment) {
         $posts[$comment->post_id]->comments[$comment->getId()] = $comment;
     }
     $arrResult['pages'] = $paginator->getPages();
     $arrResult['items'] = $posts;
     return $arrResult;
 }
示例#3
0
 /**
  * Action - videos
  * Actions with the videos. Get a list of videos.
  *
  * Access to the action is possible in the following paths:
  * router pattern - user/:username/post/:post_id/videos/*
  * 
  * - /user/user1/post/27/videos
  *
  * @return void
  */
 public function videosAction()
 {
     $playlist = array();
     //-----------------------
     // Получим файл конфигурации
     $ini = Zend_Registry::get('config');
     $adapter = $ini['http']['adapter'];
     $proxy_host = $ini['proxy']['host'];
     // Получим обьект запроса
     $request = $this->getRequest();
     $params = $request->getParams();
     $type_action = $params['type_action'];
     $username = trim($request->getUserParam('username'));
     $post_id = (int) $request->getUserParam('post_id');
     if ($type_action == 'playlist') {
         // Получим файлы видео для сообщения
         $videos = Default_Model_DbTable_BlogPostVideo::GetVideo($this->db, array('post_id' => $post_id));
         // Получим список видео данных для статьи
         foreach ($videos as $video) {
             // Получим URL ресурса
             $type = $video->type;
             $arrType = explode('-', $type);
             if ($arrType[0] == 'file') {
                 $url = $video->getFullUrl_Res($username);
             } else {
                 $url = $video->identifier;
             }
             $path = $video->GetUploadPath($username) . '/' . $video->getId() . '.json';
             if (is_file($path)) {
                 $strJson = file_get_contents($path);
                 $strJson = stripslashes($strJson);
                 try {
                     // Получим пути к изобржаениям и флеш для пользователя
                     $pathImages = Default_Model_DbTable_BlogPostImage::GetUploadUrl($username);
                     $pathFlash = Default_Model_DbTable_BlogPostVideo::GetUploadUrlForFlash($username);
                     // Преобразуем Json в PHP массив
                     $itemPlaylist = Zend_Json::decode($strJson);
                     // Изменим данные в массиве
                     $itemPlaylist['clip_id'] = $video->getId();
                     $itemPlaylist['clip_type'] = $video->type;
                     $itemPlaylist['url'] = $url;
                     $itemPlaylist['title'] = $video->name;
                     if (isset($itemPlaylist['cuepoints'])) {
                         $cuepoints = $itemPlaylist['cuepoints'];
                         $newCuepoints = array();
                         foreach ($cuepoints as $cuepoint) {
                             if (isset($cuepoint['image'])) {
                                 $cuepoint['image'] = $this->getUrlRes($pathImages . '/' . ltrim($cuepoint['image'], '/'));
                             }
                             if (isset($cuepoint['flash'])) {
                                 $cuepoint['flash'] = $this->getUrlRes($pathFlash . '/' . ltrim($cuepoint['flash'], '/'));
                             }
                             $newCuepoints[] = $cuepoint;
                         }
                         $itemPlaylist['cuepoints'] = $newCuepoints;
                     }
                 } catch (Exception $exc) {
                     $jsons = array('class_message' => 'warning', 'messages' => array('<em>' . $this->Translate('Ошибка получения видео') . '</em>', Default_Plugin_SysBox::getMessageError($exc)));
                     $this->sendJson($jsons);
                     return;
                 }
             } else {
                 $itemPlaylist = array();
                 $itemPlaylist['clip_id'] = $video->getId();
                 $itemPlaylist['clip_type'] = $video->type;
                 $itemPlaylist['url'] = $url;
                 $itemPlaylist['title'] = $video->name;
                 $itemPlaylist['description'] = $video->comment;
             }
             $playlist[] = $itemPlaylist;
         }
         if ($this->_isAjaxRequest) {
             $this->sendJson($playlist);
         }
     } elseif ($type_action == 'godtv_url') {
         // Получим параметры клипа
         $clip_name = $params['clip_name'];
         $clip_id = $params['clip_id'];
         // Получим файлы видео для сообщения
         $videos = Default_Model_DbTable_BlogPostVideo::GetVideo($this->db, array('post_id' => $post_id));
         // Найдем нужное видео и обновим "identifier"
         foreach ($videos as $video) {
             if ($video->getId() == $clip_id) {
                 // Получим уникальный URL для фильма
                 $arrBox = new Default_Plugin_ArrayBox();
                 $url_video = $arrBox->set($video->identifier, '/')->getLast();
                 // Получим новый URL для этого видео
                 $new_url = $this->_getGodtvURL($clip_name, $url_video);
                 if ($new_url === FALSE) {
                     $jsons = array('class_message' => 'warning', 'messages' => array('<em>' . $this->Translate('Ошибка URL') . '</em>', $this->Translate('Ошибка получения URL для видео')));
                     $this->sendJson($jsons);
                     return;
                 }
                 $video->identifier = $new_url;
                 if ($video->save()) {
                     $json = array('url' => $new_url);
                 } else {
                     $json = array('class_message' => 'warning', 'messages' => array('<em>' . $this->Translate('Ошибка при сохранении данных') . '</em>'));
                 }
                 $this->sendJson($json);
                 return;
             }
         }
     } elseif ($type_action == 'play') {
         $json = array('result' => 'OK');
         $this->sendJson($json);
         return;
     }
 }