コード例 #1
0
 /**
  * Action - image
  * display images in the predetermined size or in the natural size
  *
  * Access to the action is possible in the following paths:
  * - /utility/image
  *
  * @return void
  */
 public function imageAction()
 {
     $request = $this->getRequest();
     $response = $this->getResponse();
     $username = $request->getQuery('username');
     $id = (int) $request->getQuery('id');
     $w = (int) $request->getQuery('w');
     $h = (int) $request->getQuery('h');
     $hash = $request->getQuery('hash');
     $realHash = Default_Model_DbTable_BlogPostImage::GetImageHash($id, $w, $h);
     // disable autorendering since we're outputting an image
     $this->_helper->viewRenderer->setNoRender();
     $image = new Default_Model_DbTable_BlogPostImage($this->db);
     if ($hash != $realHash || !$image->load($id)) {
         // image not found
         $response->setHttpResponseCode(404);
         return;
     }
     try {
         $fullpath = $image->createThumbnail($w, $h, $username);
     } catch (Exception $ex) {
         $fullpath = $image->getFullPath($username);
     }
     $info = getImageSize($fullpath);
     $response->setHeader('content-type', $info['mime']);
     $response->setHeader('content-length', filesize($fullpath));
     echo file_get_contents($fullpath);
 }
コード例 #2
0
/**
 * Get an image file
 *
 * @param array $params
 * @param Smarty $smarty
 * @return string
 */
function smarty_function_imagefilename($params, $smarty)
{
    if (!isset($params['id'])) {
        $params['id'] = 0;
    }
    if (!isset($params['w'])) {
        $params['w'] = 0;
    }
    if (!isset($params['w'])) {
        $params['h'] = 0;
    }
    require_once $smarty->_get_plugin_filepath('function', 'geturl');
    $hash = Default_Model_DbTable_BlogPostImage::GetImageHash($params['id'], $params['w'], $params['h']);
    $options = array('controller' => 'utility', 'action' => 'image');
    return sprintf('%s?username=%s&id=%d&w=%d&h=%d&hash=%s', smarty_function_geturl($options, $smarty), $params['username'], $params['id'], $params['w'], $params['h'], $hash);
}
コード例 #3
0
ファイル: BlogPostImage.php プロジェクト: bsa-git/zf-myblog
 /**
  * Initialization form
  */
 public function init()
 {
     parent::init();
     //---------------- Форма ----------------
     // Указываем action формы
     $urlAction = $this->getUrl('images', 'blogmanager');
     $this->setAction($urlAction);
     //Зададим метод передачи данных
     $this->setMethod('post');
     // Зададим тип передачи данных на сервер
     $this->setAttrib('enctype', 'multypart/form-data');
     // Задаем атрибут class для формы
     $this->setAttrib('class', 'myfrm');
     $this->setAttrib('id', 'blogpostimage-form');
     //--------- Элемент Hidden -----------------//
     //Добавим скрытый элемент для перенаправления входа пользователя
     //        $elId = new Zend_Form_Element_Hidden('id');
     //        $this->addElement($elId);
     //
     //         if ($this->post_id) {
     //            $this->setDefault('id', $this->post_id);
     //        }
     //--------- Элемент Файл -----------------//
     $elFile = new Zend_Form_Element_File('image');
     $elFile->setLabel('Выбрать файл с локального компьютера');
     $path = Default_Model_DbTable_BlogPostImage::GetUploadPath();
     $elFile->setDestination($path);
     //Будем грузить только один файл
     $elFile->addValidator('Count', false, 1);
     //Будем грузить файл размером - 1Мб
     $elFile->addValidator('Size', false, 1024000);
     //Будем грузить файл типа: JPEG, PNG, GIF
     $elFile->addValidator('Extension', false, 'jpg,png,gif');
     //$elFile->setDecorators(array('ViewHelper'));
     $this->addElement($elFile);
     //--------- Кнопка submit -----------------//
     //Добавим кнопку
     $this->addElement('submit', 'upload', array('ignore' => true, 'label' => 'Загрузить изображение'));
     $this->getElement('upload')->setAttrib('class', 'btn btn-primary');
     $this->getElement('upload')->setDecorators(array('ViewHelper'));
 }
コード例 #4
0
ファイル: BlogController.php プロジェクト: bsa-git/zf-myblog
 /**
  * Get the number of rows in the table
  *
  * @param array $options
  *
  * @return int
  */
 public function getCountRowsTable($options = NULL)
 {
     $request = $this->getRequest();
     $params = $request->getParams();
     $table = $params['table'];
     //---------------------------
     if ($table == 'admin.blog_posts') {
         return Default_Model_DbTable_BlogPost::GetPostsCount($this->db, $options);
     }
     if ($table == 'admin.blog_posts_tags') {
         $post_ids = Default_Model_DbTable_BlogPost::GetPostsIds_Array($this->db, $options);
         return Default_Model_DbTable_BlogPostTag::GetPostsTags_Count($this->db, array('post_id' => $post_ids));
     }
     if ($table == 'admin.blog_posts_images') {
         $post_ids = Default_Model_DbTable_BlogPost::GetPostsIds_Array($this->db, $options);
         return Default_Model_DbTable_BlogPostImage::GetPostsImages_Count($this->db, array('post_id' => $post_ids));
     }
     if ($table == 'admin.blog_posts_audio') {
         $post_ids = Default_Model_DbTable_BlogPost::GetPostsIds_Array($this->db, $options);
         return Default_Model_DbTable_BlogPostAudio::GetPostsAudio_Count($this->db, array('post_id' => $post_ids));
     }
     if ($table == 'admin.blog_posts_video') {
         $post_ids = Default_Model_DbTable_BlogPost::GetPostsIds_Array($this->db, $options);
         return Default_Model_DbTable_BlogPostVideo::GetPostsVideo_Count($this->db, array('post_id' => $post_ids));
     }
     if ($table == 'admin.blog_posts_locations') {
         $post_ids = Default_Model_DbTable_BlogPost::GetPostsIds_Array($this->db, $options);
         return Default_Model_DbTable_BlogPostLocation::GetPostsLocations_Count($this->db, array('post_id' => $post_ids));
     }
 }
コード例 #5
0
ファイル: BlogPost.php プロジェクト: bsa-git/zf-myblog
 /**
  * Get the array of posts satisfying the criteria specified in the parameter $options
  *
  * @param Zend_Db_Adapter_Abstract $db
  * @param array $options
  * @return array
  */
 public static function GetPosts_Array($db, $options = array())
 {
     $arrPosts = FALSE;
     $user_ids = array();
     //----------------------
     // initialize the options
     $defaults = array('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);
     // set the fields to select
     $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);
     }
     $strSelect = $select->__toString();
     //------ Применить кеширование -------
     $dbCache = Default_Plugin_SysBox::getCache('db');
     if ($dbCache->getOption('caching')) {
         // Получим TAG для кеширования
         $arrItems = array($select, $options);
         $strSerialize = serialize($arrItems);
         $tagCache = md5($strSerialize);
         // Очистим кеш
         if (Default_Plugin_SysBox::isCleanCache()) {
             $dbCache->clean(Zend_Cache::CLEANING_MODE_ALL);
         }
         // Получим данные из кеша по тегу $tagCache
         $arrPosts = $dbCache->load($tagCache);
     }
     // проверка, есть ли уже данные в кэше:
     if ($arrPosts === FALSE) {
         // fetch user data from database
         $data = $db->fetchAll($select);
         // turn data into array of DatabaseObject_User objects
         $posts = parent::BuildMultiple_Array($db, __CLASS__, $data);
         if (count($posts) == 0) {
             return $posts;
         }
         $post_ids = array_keys($posts);
         // load the profile data for loaded posts
         $profiles = Default_Model_Profile::BuildMultiple_Array($db, 'Default_Model_DbTable_BlogPostProfile', array($post_ids));
         $arrPosts = array();
         foreach ($posts as $post_id => $post) {
             if (array_key_exists($post_id, $profiles)) {
                 $arrPosts[$post_id] = $posts[$post_id] + $profiles[$post_id];
             } else {
                 $arrPosts[$post_id] = $posts[$post_id];
             }
             // Получим ids пользователей для всех сообщениий
             $user_ids[] = $post['user_id'];
         }
         // Уберем повторяющиеся значения из массива
         $user_ids = array_unique($user_ids);
         // Получим всех пользователей
         $options = array('user_id' => $user_ids);
         $users = Default_Model_DbTable_User::GetUsers_Array($db, $options);
         // Добавим пользователя для каждого сообщения
         foreach ($posts as $post_id => $post) {
             $postuser_id = $post['user_id'];
             foreach ($users as $user) {
                 $user_id = $user['id'];
                 if ($user_id == $postuser_id) {
                     $arrPosts[$post_id]['_user_'] = $user;
                     break;
                 }
             }
         }
         // Загрузим изображения для каждого сообщения
         $options = array('post_id' => $post_ids);
         $images = Default_Model_DbTable_BlogPostImage::GetImages_Array($db, $options);
         foreach ($images as $image) {
             $post_id = $image['post_id'];
             $image_id = $image['id'];
             $arrPosts[$post_id]['_images_'][$image_id] = $image;
         }
         // Загрузим координаты для каждого сообщения
         $locations = Default_Model_DbTable_BlogPostLocation::GetLocations_Array($db, $options);
         foreach ($locations as $location) {
             $post_id = $location['post_id'];
             $location_id = $location['id'];
             $arrPosts[$post_id]['_locations_'][$location_id] = $location;
         }
         // Загрузим метки для каждого сообщения
         $tags = Default_Model_DbTable_BlogPostTag::GetTags_Array($db, $options);
         foreach ($tags as $tag) {
             $post_id = $tag['post_id'];
             $tag_id = $tag['id'];
             $arrPosts[$post_id]['_tags_'][$tag_id] = $tag;
         }
         // Загрузим audio для каждого сообщения
         $audios = Default_Model_DbTable_BlogPostAudio::GetAudio_Array($db, $options);
         foreach ($audios as $audio) {
             $post_id = $audio['post_id'];
             $audio_id = $audio['id'];
             $arrPosts[$post_id]['_audio_'][$audio_id] = $audio;
         }
         // Загрузим video для каждого сообщения
         $videos = Default_Model_DbTable_BlogPostVideo::GetVideo_Array($db, $options);
         foreach ($videos as $video) {
             $post_id = $video['post_id'];
             $video_id = $video['id'];
             $arrPosts[$post_id]['_video_'][$video_id] = $video;
         }
         // Загрузим comments для каждого сообщения
         $comments = Default_Model_DbTable_BlogPostComment::GetComments_Array($db, $options);
         foreach ($comments as $comment) {
             $post_id = $comment['post_id'];
             $comment_id = $comment['id'];
             $arrPosts[$post_id]['_comments_'][$comment_id] = $comment;
         }
         // Если разрешено кеширование, то сохраним данные в кеше
         if ($dbCache->getOption('caching')) {
             $dbCache->save($arrPosts, $tagCache);
         }
     } else {
         $result = $arrPosts;
     }
     return $arrPosts;
 }
コード例 #6
0
 /**
  * Action - images
  * upload/download/ordering images
  * 
  * Access to the action is possible in the following paths:
  * - /blogmanager/images
  *
  * @return void
  */
 public function imagesAction()
 {
     $json = array();
     $filterSanitize = new Default_Form_Filter_Sanitize();
     //-----------------------
     // Получим обьект записи
     $request = $this->getRequest();
     $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'
     // и выполним ее
     if ($request->getPost('upload')) {
         // Загрузка файла через форму, если javascript отключен...
         $allParams = $this->_getAllParams();
         $formBlogPostImage = new Default_Form_BlogPostImage($post->getId());
         $result = $formBlogPostImage->isValid($allParams);
         if ($result) {
             // Проверим загружен ли файл?
             if ($formBlogPostImage->image->receive()) {
                 // Создадим обьект изображения для базы данных
                 $image = new Default_Model_DbTable_BlogPostImage($post->getDb());
                 $image->post_id = $post->getId();
                 $filename = $formBlogPostImage->image->getFileName();
                 if (!is_array($filename)) {
                     $image->uploadFile($filename);
                     $image->filename = basename($filename);
                     $image->comment = $request->getPost('comment');
                     $image->save();
                     // Определим признак ajax_upload
                     $this->_flashMessenger->addMessage($this->Translate('Изображение загружено'));
                 } else {
                     $class_message = 'warning';
                     $message = $this->Translate('Файл не выбран');
                     $this->_flashMessenger->addMessage($this->Translate('Файл не выбран'));
                 }
             } else {
                 $class_message = 'warning';
                 $message = $this->Translate('Ошибка получения файла');
                 $this->_flashMessenger->addMessage($this->Translate('Ошибка загрузки файла'));
             }
         } else {
             // Ошибка загрузки изображения
             $class_message = 'warning';
             $message = $this->getFormMessagesToString($formBlogPostImage);
             $this->_flashMessenger->addMessage($this->Translate('Ошибка формы! Неверно введены данные в форму.'));
         }
         // Загрузить файл с помощью FileUploader
     } else {
         if (Default_Plugin_FileUploader::isFileUploader()) {
             // Загрузка файла через FileUploader, если javascript включен...
             // Получим вид загрузчика - Iframe или Xhr
             $fileUploader = Default_Plugin_FileUploader::isFileUploader();
             // list of valid extensions, ex. array("jpeg", "xml", "bmp")
             $allowedExtensions = explode(';', $request->getParam('allowedExtensions'));
             // max file size in bytes
             $sizeLimit = (int) $request->getParam('sizeLimit');
             // Получим обьект загрузчика файлов
             try {
                 $uploader = new Default_Plugin_FileUploader($allowedExtensions, $sizeLimit);
                 // Определим путь загрузки файлов
                 $path = Default_Model_DbTable_BlogPostImage::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'])) {
                 // OK
                 // Создадим обьект изображения
                 try {
                     $image = new Default_Model_DbTable_BlogPostImage($post->getDb());
                     $image->post_id = $post->getId();
                     $filename = $path . $uploader->file->getName();
                     $image->uploadFile($filename);
                     $image->filename = basename($filename);
                     $image->save();
                     $json['success'] = $result['success'];
                     $json['image_id'] = $image->getId();
                     $json['filename'] = $image->filename;
                     $json['post_id'] = $image->post_id;
                     $json['url_image'] = $image->createThumbnail(200, 65);
                     $json['form_action'] = $this->getUrl('images', 'blogmanager');
                 } 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('reorder')) {
                 $order = $request->getPost('preview-images');
                 $post->setImageOrder($order);
             } else {
                 if ($request->getPost('delete')) {
                     $image_id = (int) $request->getPost('image');
                     $image = new Default_Model_DbTable_BlogPostImage($this->db);
                     if ($image->loadForPost($post->getId(), $image_id)) {
                         $image->delete();
                         // Определим кол. оставшихся изображений
                         $count_images = count($post->images) - 1;
                         if ($this->_isAjaxRequest) {
                             $json = array('deleted' => true, 'image_id' => $image_id, 'count_images' => $count_images);
                         } else {
                             $this->_flashMessenger->addMessage($this->Translate('Изображение удалено'));
                         }
                     }
                 } else {
                     if ($request->getPost('comment_update')) {
                         $image_id = (int) $request->getPost('image');
                         $image = new Default_Model_DbTable_BlogPostImage($this->db);
                         if ($image->loadForPost($post->getId(), $image_id)) {
                             $comment = $request->getPost('comment');
                             $comment = $filterSanitize->filter($comment);
                             $image->comment = $comment;
                             $image->save();
                             if ($this->_isAjaxRequest) {
                                 $json = array('commented' => true, 'title' => '', 'comment' => $image->comment);
                             } else {
                                 $this->_flashMessenger->addMessage($this->Translate('Комментарий к изображению обновился'));
                             }
                         }
                     } else {
                         if ($request->getPost('download_images')) {
                             // Загрузим изображения в виде HTML на страницу
                             // Получим изображения для статьи
                             $images = Default_Model_DbTable_BlogPostImage::GetImages($this->db, array('post_id' => $post_id));
                             // Создадим обьект шаблона
                             $templater = Default_Plugin_SysBox::createViewSmarty();
                             //Установим параметры шаблона
                             $templater->images = $images;
                             $templater->post_id = $post_id;
                             // Получим результат шаблона
                             $html = $templater->render('blogmanager/lib/download-images.tpl');
                             if ($this->_isAjaxRequest) {
                                 $json = array('downloaded' => true, 'html' => $html);
                             }
                         }
                     }
                 }
             }
         }
     }
     if ($this->_isAjaxRequest) {
         $this->sendJson($json);
     } else {
         if (Default_Plugin_FileUploader::isFileUploader() == 'Iframe') {
             $this->sendJson_Html($json);
         } else {
             if ($message) {
                 $getParams = '?id=' . $post->getId() . '&message=' . $message . '&class_message=' . $class_message;
             } else {
                 $getParams = '?id=' . $post->getId();
             }
             $this->_redirect('/blogmanager/preview' . $getParams);
         }
     }
 }
コード例 #7
0
ファイル: UserController.php プロジェクト: bsa-git/zf-myblog
 /**
  * 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;
     }
 }