public function run()
 {
     $ids = array_reverse($_POST['File']);
     $files = new MediaFile('sort');
     $case = SqlHelper::arrToCase('id', array_flip($ids), 't');
     $arr = implode(',', $ids);
     Yii::app()->db->getCommandBuilder()->createSqlCommand("UPDATE {$files->tableName()} AS t SET t.order = {$case} WHERE t.id IN ({$arr})")->execute();
 }
Example #2
0
 /**
  * Show a Twitpic-like response with the ID of the media file
  * and a (hopefully) shortened URL for it.
  *
  * @param MediaFile $upload  the uploaded file
  *
  * @return void
  */
 function showResponse(MediaFile $upload)
 {
     $this->initDocument();
     $this->elementStart('rsp', array('stat' => 'ok'));
     $this->element('mediaid', null, $upload->fileRecord->id);
     $this->element('mediaurl', null, $upload->shortUrl());
     $this->elementEnd('rsp');
     $this->endDocument();
 }
 public function actionManage()
 {
     $file = new MediaFile('search', 'youTube');
     $model = $file->getApi();
     if (isset($_GET[get_class($model)])) {
         $model->setAttributes($_GET[get_class($model)], false);
     }
     $this->render('manage', ["model" => $model]);
 }
 /**
  * Show a Twitpic-like response with the ID of the media file
  * and a (hopefully) shortened URL for it.
  *
  * @param MediaFile $upload  the uploaded file
  *
  * @return void
  */
 function showResponse(MediaFile $upload)
 {
     $this->initDocument();
     $this->elementStart('rsp', array('stat' => 'ok', 'xmlns:atom' => Activity::ATOM));
     $this->element('mediaid', null, $upload->fileRecord->id);
     $this->element('mediaurl', null, $upload->shortUrl());
     $enclosure = $upload->fileRecord->getEnclosure();
     $this->element('atom:link', array('rel' => 'enclosure', 'href' => $enclosure->url, 'type' => $enclosure->mimetype));
     $this->elementEnd('rsp');
     $this->endDocument();
 }
 public function findAllAttaches()
 {
     $model = $this->getOwner();
     $object_id = $model->isNewRecord ? $this->_tmpPrefix() : $model->id;
     MediaFile::model()->findAllByAttributes(array('object_id' => $object_id, 'model_id' => get_class($model)));
     return MediaFile::model()->findAllByAttributes(array('object_id' => $object_id, 'model_id' => get_class($model)));
 }
 /**
  * Handle the request
  *
  * Grab the file from the 'media' param, then store, and shorten
  *
  * @todo Upload throttle!
  *
  * @param array $args $_REQUEST data (unused)
  *
  * @return void
  */
 function handle($args)
 {
     parent::handle($args);
     if ($_SERVER['REQUEST_METHOD'] != 'POST') {
         $this->clientError(_('This method requires a POST.'), 400, $this->format);
         return;
     }
     // Workaround for PHP returning empty $_POST and $_FILES when POST
     // length > post_max_size in php.ini
     if (empty($_FILES) && empty($_POST) && $_SERVER['CONTENT_LENGTH'] > 0) {
         $msg = _('The server was unable to handle that much POST ' . 'data (%s bytes) due to its current configuration.');
         $this->clientError(sprintf($msg, $_SERVER['CONTENT_LENGTH']));
         return;
     }
     $upload = null;
     try {
         $upload = MediaFile::fromUpload('media', $this->auth_user);
     } catch (ClientException $ce) {
         $this->clientError($ce->getMessage());
         return;
     }
     if (isset($upload)) {
         $this->showResponse($upload);
     } else {
         $this->clientError('Upload failed.');
         return;
     }
 }
 public function video_player_requestv2()
 {
     $this->skip_page_view = true;
     $this->layout = "ajax";
     $data = array();
     $data['playlist'] = array();
     $media_file_id = isset($this->request->params['named']['media_file_id']) ? $this->request->params['named']['media_file_id'] : '4d6ed946-4d48-4735-8272-37a20ab5431b';
     $MediaFile = $this->MediaFile->find("first", array("conditions" => array("MediaFile.id" => $media_file_id), "contain" => array()));
     $handheld = false;
     if ($this->request->is('mobile') && preg_match('/(iPhone|iPod)/', $_SERVER['HTTP_USER_AGENT']) || isset($_GET['handheld'])) {
         $handheld = false;
     }
     if (isset($this->request->params['named']['dailyop_id'])) {
         $Post = $this->Dailyop->find("first", array("fields" => array("Dailyop.id", "Dailyop.name", "Dailyop.sub_title", "Dailyop.uri", "DailyopSection.name", "DailyopSection.uri"), "conditions" => array("Dailyop.id" => $this->request->params['named']['dailyop_id']), "contain" => array("DailyopSection")));
     }
     if (!empty($MediaFile['MediaFile']['preroll_label'])) {
         $data['playlist'][]['prerollUrl'] = MediaFile::formatVastUrl($MediaFile['MediaFile']['preroll_label']);
     }
     unset($MediaFile['MediaFile']['created'], $MediaFile['MediaFile']['modified']);
     $MediaFile['MediaFile']['jw_url'] = $MediaFile['MediaFile']['file_url'] = "http://berrics.vo.llnwd.net/o45/" . $MediaFile['MediaFile']['limelight_file'];
     $data['playlist'][] = array("Video" => array("MediaFile" => $MediaFile['MediaFile'], 'Dailyop' => isset($Post['Dailyop']['id']) ? false : $Post['Dailyop']));
     if (!empty($MediaFile['MediaFile']['postroll_label'])) {
         $data['playlist'][]['postrollUrl'] = MediaFile::formatVastUrl($MediaFile['MediaFile']['postroll_label']);
     }
     $this->insertMediaHit($MediaFile['MediaFile']['id']);
     $this->set(compact("data"));
     die(json_encode($data['playlist']));
 }
Example #8
0
    public function getSearchInfo()
    {
        return ['video' => ['sql' => '
                    SELECT
                        media_files.id,
                        media_files.id as object_id, "MediaFile" as model_id,
                        media_files.title, media_files.descr

                        FROM  ' . MediaFile::model()->tableName() . '
                        WHERE media_files.type="video"
                    '], 'audio' => ['sql' => '
                    SELECT
                        media_files.id,
                        media_files.id as object_id, "MediaFile" as model_id,
                        media_files.title, media_files.descr

                        FROM  ' . MediaFile::model()->tableName() . '
                        WHERE media_files.type="audio"
                    '], 'albums' => ['sql' => '
                    SELECT
                        media_albums.id,
                        media_albums.id as object_id, "MediaAlbum" as model_id,
                        media_albums.title, media_albums.descr

                        FROM  ' . MediaAlbum::model()->tableName() . '
                    ']];
    }
Example #9
0
 /**
  * Handle the request
  *
  * Grab the file from the 'media' param, then store, and shorten
  *
  * @todo Upload throttle!
  *
  * @param array $args $_REQUEST data (unused)
  *
  * @return void
  */
 function handle($args)
 {
     parent::handle($args);
     if ($_SERVER['REQUEST_METHOD'] != 'POST') {
         $this->clientError(_('This method requires a POST.'), 400, $this->format);
         return;
     }
     // Workaround for PHP returning empty $_POST and $_FILES when POST
     // length > post_max_size in php.ini
     if (empty($_FILES) && empty($_POST) && $_SERVER['CONTENT_LENGTH'] > 0) {
         // TRANS: Client error displayed when the number of bytes in a POST request exceeds a limit.
         // TRANS: %s is the number of bytes of the CONTENT_LENGTH.
         $msg = _m('The server was unable to handle that much POST data (%s byte) due to its current configuration.', 'The server was unable to handle that much POST data (%s bytes) due to its current configuration.', intval($_SERVER['CONTENT_LENGTH']));
         $this->clientError(sprintf($msg, $_SERVER['CONTENT_LENGTH']));
         return;
     }
     $upload = null;
     try {
         $upload = MediaFile::fromUpload('media', $this->auth_user);
     } catch (Exception $e) {
         $this->clientError($e->getMessage(), $e->getCode());
         return;
     }
     if (isset($upload)) {
         $this->showResponse($upload);
     } else {
         $this->clientError(_('Upload failed.'));
         return;
     }
 }
Example #10
0
 public function init()
 {
     if ($this->dataProvider === null) {
         $this->dataProvider = MediaFile::getDataProvider($this->model, $this->tag);
     }
     $this->assets = Yii::app()->getModule('media')->assetsUrl();
     parent::init();
 }
 protected function saveGallery($gallery)
 {
     $album = new MediaAlbum();
     $album->title = $gallery['title'];
     $album->model_id = 'sherdog.com';
     $album->object_id = $gallery['id'];
     $album->save(false);
     foreach ($gallery['imgs'] as $img) {
         $file = new MediaFile('create', 'remote');
         $file->model_id = get_class($album);
         $file->object_id = $album->id;
         $file->tag = 'images';
         $file->title = $img['title'];
         $file->remote_id = $img['img'];
         $file->save(false);
     }
 }
 public function actionManage($user_id = null, $q = null)
 {
     if ($user_id === null) {
         $this->user = new User();
         $this->page_title = 'Видео';
     } else {
         $this->user = User::model()->throw404IfNull()->findByPk($user_id);
         $this->page_title = 'Видео пользователя: ' . $this->user->getLink();
     }
     $file = new MediaFile();
     if ($q) {
         $file->getDbCriteria()->compare('title', $q, true, 'OR');
         $file->getDbCriteria()->compare('descr', $q, true, 'OR');
     }
     $dp = new ActiveDataProvider($file, ['criteria' => $file->parentModel($this->user)->type(MediaFile::TYPE_VIDEO)->getDbCriteria(), 'pagination' => false]);
     $this->render('manage', ['model' => $this->user, 'is_my' => Yii::app()->user->id && Yii::app()->user->id == $user_id, 'dp' => $dp]);
 }
Example #13
0
 public function deleteFiles()
 {
     // delete cached files
     foreach ($this->listCachedFiles() as $cachedFilename) {
         @unlink($cachedFilename);
     }
     return parent::deleteFiles();
 }
Example #14
0
 public function refetch_files()
 {
     foreach (EpisodeAsset::all() as $asset) {
         if ($file = MediaFile::find_by_episode_id_and_episode_asset_id($this->id, $asset->id)) {
             $file->determine_file_size();
             $file->save();
         }
     }
 }
Example #15
0
 /**
  * @dataProvider fileTypeCases
  *
  */
 public function testUploadedFileType($filename, $expectedType)
 {
     if (!file_exists($filename)) {
         throw new Exception("WTF? {$filename} test file missing");
     }
     $tmp = tmpfile();
     fwrite($tmp, file_get_contents($filename));
     $type = MediaFile::getUploadedFileType($tmp, basename($filename));
     $this->assertEquals($expectedType, $type);
 }
Example #16
0
 function handle_message($rawmessage)
 {
     list($from, $to, $msg, $attachments) = $this->parse_message($rawmessage);
     if (!$from || !$to || !$msg) {
         // TRANS: Error message in incoming mail handler used when an incoming e-mail cannot be processed.
         $this->error(null, _('Could not parse message.'));
     }
     common_log(LOG_INFO, "Mail from {$from} to {$to} with " . count($attachments) . ' attachment(s): ' . substr($msg, 0, 20));
     $user = $this->user_from_header($from);
     if (!$user) {
         // TRANS: Error message in incoming mail handler used when an incoming e-mail is not from a registered user.
         $this->error($from, _('Not a registered user.'));
         return false;
     }
     if (!$this->user_match_to($user, $to)) {
         // TRANS: Error message in incoming mail handler used when an incoming e-mail is not from a user's incoming e-mail address.
         $this->error($from, _('Sorry, that is not your incoming email address.'));
         return false;
     }
     if (!$user->emailpost) {
         // TRANS: Error message in incoming mail handler used when no incoming e-mail is allowed.
         $this->error($from, _('Sorry, no incoming email allowed.'));
         return false;
     }
     $response = $this->handle_command($user, $from, $msg);
     if ($response) {
         return true;
     }
     $msg = $this->cleanup_msg($msg);
     $msg = $user->shortenLinks($msg);
     if (Notice::contentTooLong($msg)) {
         // TRANS: Error message in incoming mail handler used when an incoming e-mail contains too many characters.
         $this->error($from, sprintf(_m('That\'s too long. Maximum notice size is %d character.', 'That\'s too long. Maximum notice size is %d characters.', Notice::maxContent()), Notice::maxContent()));
     }
     $mediafiles = array();
     foreach ($attachments as $attachment) {
         $mf = null;
         try {
             $mf = MediaFile::fromFileHandle($attachment, $user);
         } catch (ClientException $ce) {
             $this->error($from, $ce->getMessage());
         }
         $msg .= ' ' . $mf->shortUrl();
         array_push($mediafiles, $mf);
         fclose($attachment);
     }
     $err = $this->add_notice($user, $msg, $mediafiles);
     if (is_string($err)) {
         $this->error($from, $err);
         return false;
     } else {
         return true;
     }
 }
 public function actionDownloadFile($hash)
 {
     list($hash, $id) = explode('x', $hash);
     $model = MediaFile::model()->findByPk(intval($id));
     if (!$model || $model->getHash() != $hash || !$model->getIsFileExist()) {
         $this->pageNotFound();
     }
     if ($this->x_send_file_enabled) {
         Yii::app()->request->xSendFile($model->server_path, ['saveName' => $model->name, 'terminate' => false]);
     } else {
         $this->request->sendFile($model->name, $model->content);
     }
 }
 public function actionView($id)
 {
     $model = MediaAlbum::model()->throw404IfNull()->findByPk($id);
     $this->user = $model->getParentModel();
     $this->page_title = 'Альбом: ' . $model->title;
     $form = new Form('Media.UploadFilesForm', $model);
     $dp = MediaFile::model()->getDataProvider($model, 'files');
     $dp->getPagination()->pageSize = 18;
     if (Yii::app()->request->isAjaxRequest) {
         $this->renderPartial('view', ['model' => $model, 'form' => $form, 'dp' => $dp]);
     } else {
         $this->render('view', ['model' => $model, 'form' => $form, 'dp' => $dp]);
     }
 }
 public function run()
 {
     $file = new MediaFile('search', 'local');
     $file->getDbCriteria()->mergeWith(['condition' => 'target_api IS NOT NULL AND status=:status', 'params' => ['status' => MediaFile::STATUS_ACTIVE]]);
     $files = $file->findAll();
     foreach ($files as $file) {
         $local_api = $file->getApi();
         if ($local_api instanceof LocalApi) {
             $file->setApi($file->target_api);
             $file->convertFromLocal($local_api);
             $file->target_api = null;
             $file->save();
         }
     }
 }
Example #20
0
 public static function dropdown($data, $selected = NULL, $extra = '')
 {
     // standardize the $data as an array, strings default to the class_type
     if (!is_array($data)) {
         $data = array('name' => $data);
     }
     // add in all the defaults if they are not provided
     $defaults = array('nullOption' => FALSE);
     $data = arr::merge($defaults, $data);
     $options = MediaFile::catalog();
     if ($data['nullOption']) {
         array_unshift($options, $data['nullOption']);
     }
     $data = array_diff($data, $defaults);
     // use kohana helper to generate the markup
     return form::dropdown($data, $options, $selected, $extra);
 }
 public function browse()
 {
     $this->Paginator->settings = array();
     $this->Paginator->settings['MediaFile'] = array("limit" => 50, "order" => array("MediaFile.modified" => "DESC"), "contain" => array("Website"));
     if (isset($this->request->params['named']['MediaFile.name'])) {
         $this->request->data['MediaFile']['name'] = urldecode($this->request->params['named']['MediaFile.name']);
         $this->Paginator->settings['MediaFile']['conditions']['MediaFile.name LIKE'] = "%" . str_replace(" ", "%", urldecode($this->request->params['named']['MediaFile.name']));
     }
     if (isset($this->request->params['named']['MediaFile.media_type'])) {
         $this->request->data['MediaFile']['media_type'] = urldecode($this->request->params['named']['MediaFile.media_type']);
         $this->Paginator->settings['MediaFile']['conditions']['MediaFile.media_type'] = urldecode($this->request->params['named']['MediaFile.media_type']);
     }
     if (isset($this->request->params['named']['MediaFile.website_id'])) {
         $this->Paginator->settings['MediaFile']['conditions']['MediaFile.website_id'] = $this->request->data['MediaFile']['website_id'] = $this->request->params['named']['MediaFile.website_id'];
     } else {
         //default it at the berrics
         //$this->request->data['MediaFile']['website_id'] =
         //$this->Paginator->settings['MediaFile']['conditions']['MediaFile.website_id'] = 1;
     }
     $websites = $this->MediaFile->Website->dropdown();
     $mediaTypes = MediaFile::mediaFileTypes();
     $files = $this->paginate("MediaFile");
     $this->set(compact("files", "websites", "mediaTypes"));
 }
 /**
  * Handle the request
  *
  * Make a new notice for the update, save it, and show it
  *
  * @return void
  */
 protected function handle()
 {
     parent::handle();
     // Workaround for PHP returning empty $_POST and $_FILES when POST
     // length > post_max_size in php.ini
     if (empty($_FILES) && empty($_POST) && $_SERVER['CONTENT_LENGTH'] > 0) {
         // TRANS: Client error displayed when the number of bytes in a POST request exceeds a limit.
         // TRANS: %s is the number of bytes of the CONTENT_LENGTH.
         $msg = _m('The server was unable to handle that much POST data (%s byte) due to its current configuration.', 'The server was unable to handle that much POST data (%s bytes) due to its current configuration.', intval($_SERVER['CONTENT_LENGTH']));
         $this->clientError(sprintf($msg, $_SERVER['CONTENT_LENGTH']));
     }
     if (empty($this->status)) {
         // TRANS: Client error displayed when the parameter "status" is missing.
         $this->clientError(_('Client must provide a \'status\' parameter with a value.'));
     }
     if (is_null($this->scoped)) {
         // TRANS: Client error displayed when updating a status for a non-existing user.
         $this->clientError(_('No such user.'), 404);
     }
     /* Do not call shortenlinks until the whole notice has been build */
     // Check for commands
     $inter = new CommandInterpreter();
     $cmd = $inter->handle_command($this->auth_user, $this->status);
     if ($cmd) {
         if ($this->supported($cmd)) {
             $cmd->execute(new Channel());
         }
         // Cmd not supported?  Twitter just returns your latest status.
         // And, it returns your last status whether the cmd was successful
         // or not!
         $this->notice = $this->auth_user->getCurrentNotice();
     } else {
         $reply_to = null;
         if (!empty($this->in_reply_to_status_id)) {
             // Check whether notice actually exists
             $reply = Notice::getKV($this->in_reply_to_status_id);
             if ($reply) {
                 $reply_to = $this->in_reply_to_status_id;
             } else {
                 // TRANS: Client error displayed when replying to a non-existing notice.
                 $this->clientError(_('Parent notice not found.'), 404);
             }
         }
         $upload = null;
         try {
             $upload = MediaFile::fromUpload('media', $this->scoped);
         } catch (NoUploadedMediaException $e) {
             // There was no uploaded media for us today.
         }
         if (isset($upload)) {
             $this->status .= ' ' . $upload->shortUrl();
             /* Do not call shortenlinks until the whole notice has been build */
         }
         // in Qvitter we shorten _before_ posting, so disble shortening here
         $status_shortened = $this->status;
         if (Notice::contentTooLong($status_shortened)) {
             if ($upload instanceof MediaFile) {
                 $upload->delete();
             }
             // TRANS: Client error displayed exceeding the maximum notice length.
             // TRANS: %d is the maximum lenth for a notice.
             $msg = _m('Maximum notice size is %d character, including attachment URL.', 'Maximum notice size is %d characters, including attachment URL.', Notice::maxContent());
             /* Use HTTP 413 error code (Request Entity Too Large)
              * instead of basic 400 for better understanding
              */
             $this->clientError(sprintf($msg, Notice::maxContent()), 413);
         }
         $content = html_entity_decode($status_shortened, ENT_NOQUOTES, 'UTF-8');
         $options = array('reply_to' => $reply_to);
         // -------------------------------------------------------------
         // -------- Qvitter's post-to-the-right-group stuff! -----------
         // -------------------------------------------------------------
         // guess the groups by the content first, if we don't have group id:s as meta data
         $profile = Profile::getKV('id', $this->scoped->id);
         $guessed_groups = User_group::groupsFromText($content, $profile);
         // if the user has specified any group id:s, correct the guesswork
         if (strlen($this->post_to_groups) > 0) {
             // get the groups that the user wants to post to
             $group_ids = explode(':', $this->post_to_groups);
             $correct_groups = array();
             foreach ($group_ids as $group_id) {
                 $correct_groups[] = User_group::getKV('id', $group_id);
             }
             // correct the guesses
             $corrected_group_ids = array();
             foreach ($guessed_groups as $guessed_group) {
                 $id_to_keep = $guessed_group->id;
                 foreach ($correct_groups as $k => $correct_group) {
                     if ($correct_group->nickname == $guessed_group->nickname) {
                         $id_to_keep = $correct_group->id;
                         unset($correct_groups[$k]);
                         break;
                     }
                 }
                 $corrected_group_ids[$id_to_keep] = true;
             }
             // but we still want to post to all of the groups that the user specified by id
             // even if we couldn't use it to correct a bad guess
             foreach ($correct_groups as $correct_group) {
                 $corrected_group_ids[$correct_group->id] = true;
             }
             $options['groups'] = array_keys($corrected_group_ids);
         } else {
             $guessed_ids = array();
             foreach ($guessed_groups as $guessed_group) {
                 $guessed_ids[$guessed_group->id] = true;
             }
             $options['groups'] = array_keys($guessed_ids);
         }
         // -------------------------------------------------------------
         // ------ End of Qvitter's post-to-the-right-group stuff! ------
         // -------------------------------------------------------------
         if ($this->scoped->shareLocation()) {
             $locOptions = Notice::locationOptions($this->lat, $this->lon, null, null, $this->scoped);
             $options = array_merge($options, $locOptions);
         }
         try {
             $this->notice = Notice::saveNew($this->scoped->id, $content, $this->source, $options);
         } catch (Exception $e) {
             $this->clientError($e->getMessage(), $e->getCode());
         }
         if (isset($upload)) {
             $upload->attachToNotice($this->notice);
         }
     }
     $this->showNotice();
 }
 /**
  * Handle the request
  *
  * Make a new notice for the update, save it, and show it
  *
  * @return void
  */
 protected function handle()
 {
     parent::handle();
     // Workaround for PHP returning empty $_POST and $_FILES when POST
     // length > post_max_size in php.ini
     if (empty($_FILES) && empty($_POST) && $_SERVER['CONTENT_LENGTH'] > 0) {
         // TRANS: Client error displayed when the number of bytes in a POST request exceeds a limit.
         // TRANS: %s is the number of bytes of the CONTENT_LENGTH.
         $msg = _m('The server was unable to handle that much POST data (%s byte) due to its current configuration.', 'The server was unable to handle that much POST data (%s bytes) due to its current configuration.', intval($_SERVER['CONTENT_LENGTH']));
         $this->clientError(sprintf($msg, $_SERVER['CONTENT_LENGTH']));
     }
     if (empty($this->status)) {
         // TRANS: Client error displayed when the parameter "status" is missing.
         $this->clientError(_('Client must provide a \'status\' parameter with a value.'));
     }
     if (is_null($this->scoped)) {
         // TRANS: Client error displayed when updating a status for a non-existing user.
         $this->clientError(_('No such user.'), 404);
     }
     /* Do not call shortenLinks until the whole notice has been build */
     // Check for commands
     $inter = new CommandInterpreter();
     $cmd = $inter->handle_command($this->auth_user, $this->status);
     if ($cmd) {
         if ($this->supported($cmd)) {
             $cmd->execute(new Channel());
         }
         // Cmd not supported?  Twitter just returns your latest status.
         // And, it returns your last status whether the cmd was successful
         // or not!
         $this->notice = $this->auth_user->getCurrentNotice();
     } else {
         $reply_to = null;
         if (!empty($this->in_reply_to_status_id)) {
             // Check whether notice actually exists
             $reply = Notice::getKV($this->in_reply_to_status_id);
             if ($reply) {
                 $reply_to = $this->in_reply_to_status_id;
             } else {
                 // TRANS: Client error displayed when replying to a non-existing notice.
                 $this->clientError(_('Parent notice not found.'), 404);
             }
         }
         $upload = null;
         try {
             $upload = MediaFile::fromUpload('media', $this->scoped);
             $this->status .= ' ' . $upload->shortUrl();
             /* Do not call shortenLinks until the whole notice has been build */
         } catch (NoUploadedMediaException $e) {
             // There was no uploaded media for us today.
         }
         /* Do call shortenlinks here & check notice length since notice is about to be saved & sent */
         $status_shortened = $this->auth_user->shortenLinks($this->status);
         if (Notice::contentTooLong($status_shortened)) {
             if ($upload instanceof MediaFile) {
                 $upload->delete();
             }
             // TRANS: Client error displayed exceeding the maximum notice length.
             // TRANS: %d is the maximum lenth for a notice.
             $msg = _m('Maximum notice size is %d character, including attachment URL.', 'Maximum notice size is %d characters, including attachment URL.', Notice::maxContent());
             /* Use HTTP 413 error code (Request Entity Too Large)
              * instead of basic 400 for better understanding
              */
             $this->clientError(sprintf($msg, Notice::maxContent()), 413);
         }
         $content = html_entity_decode($status_shortened, ENT_NOQUOTES, 'UTF-8');
         $options = array('reply_to' => $reply_to);
         if ($this->scoped->shareLocation()) {
             $locOptions = Notice::locationOptions($this->lat, $this->lon, null, null, $this->scoped);
             $options = array_merge($options, $locOptions);
         }
         try {
             $this->notice = Notice::saveNew($this->scoped->id, $content, $this->source, $options);
         } catch (Exception $e) {
             $this->clientError($e->getMessage(), $e->getCode());
         }
         if (isset($upload)) {
             $upload->attachToNotice($this->notice);
         }
     }
     $this->showNotice();
 }
 public static function total_by_episode_id($episode_id, $start = null, $end = null)
 {
     global $wpdb;
     $sql = "\n\t\t\tSELECT\n\t\t\t\tCOUNT(*)\n\t\t\tFROM\n\t\t\t\t" . self::table_name() . " di\n\t\t\t\tINNER JOIN " . MediaFile::table_name() . " mf ON mf.id = di.media_file_id\n\t\t\tWHERE\n\t\t\t\tepisode_id = %d\n\t\t\t\tAND " . self::sql_condition_from_time_strings($start, $end) . "\n\t\t";
     return $wpdb->get_var($wpdb->prepare($sql, $episode_id));
 }
 /**
  * Handle the request
  *
  * @return void
  */
 protected function handle()
 {
     parent::handle();
     $profile = $this->user->getProfile();
     $base64img = $this->img;
     if (stristr($base64img, 'image/jpeg')) {
         $base64img_mime = 'image/jpeg';
     } elseif (stristr($base64img, 'image/png')) {
         // should convert to jpg here!!
         $base64img_mime = 'image/png';
     }
     $base64img = str_replace('data:image/jpeg;base64,', '', $base64img);
     $base64img = str_replace('data:image/png;base64,', '', $base64img);
     $base64img = str_replace(' ', '+', $base64img);
     $base64img_hash = md5($base64img);
     $base64img = base64_decode($base64img);
     $base64img_basename = basename('avatar');
     $base64img_filename = File::filename($profile, $base64img_basename, $base64img_mime);
     $base64img_path = File::path($base64img_filename);
     $base64img_success = file_put_contents($base64img_path, $base64img);
     $base64img_mimetype = MediaFile::getUploadedMimeType($base64img_path, $base64img_filename);
     $mediafile = new MediaFile($profile, $base64img_filename, $base64img_mimetype);
     $imagefile = new ImageFile($mediafile->fileRecord->id, File::path($mediafile->filename));
     $imagefile->resizeTo(File::path($mediafile->filename), array('width' => $this->cropW, 'height' => $this->cropH, 'x' => $this->cropX, 'y' => $this->cropY, 'w' => $this->cropW, 'h' => $this->cropH));
     $type = $imagefile->preferredType();
     $filename = Avatar::filename($profile->id, image_type_to_extension($type), null, common_timestamp());
     $filepath = Avatar::path($filename);
     $imagefile->copyTo($filepath);
     $profile = $this->user->getProfile();
     $profile->setOriginal($filename);
     $mediafile->delete();
     $twitter_user = $this->twitterUserArray($profile, true);
     $this->initDocument('json');
     $this->showJsonObjects($twitter_user);
     $this->endDocument('json');
 }
Example #26
0
 /**
  * Fetch an attachment from Yammer and save it into our system.
  * Unlike avatars, the attachment URLs are guarded by authentication,
  * so we need to run the HTTP hit through our OAuth API client.
  *
  * @param string $url
  * @param User $user
  * @return MediaFile
  *
  * @throws Exception on low-level network or HTTP error
  */
 private function saveAttachment($url, User $user)
 {
     // Fetch the attachment...
     // WARNING: file must fit in memory here :(
     $body = $this->client->fetchUrl($url);
     // Save to a temporary file and shove it into our file-attachment space...
     $temp = tmpfile();
     fwrite($temp, $body);
     try {
         $upload = MediaFile::fromFileHandle($temp, $user);
         fclose($temp);
         return $upload;
     } catch (Exception $e) {
         fclose($temp);
         throw $e;
     }
 }
 /**
  * Handle the request
  *
  * Make a new notice for the update, save it, and show it
  *
  * @param array $args $_REQUEST data (unused)
  *
  * @return void
  */
 function handle($args)
 {
     parent::handle($args);
     if ($_SERVER['REQUEST_METHOD'] != 'POST') {
         $this->clientError(_('This method requires a POST.'), 400, $this->format);
         return;
     }
     // Workaround for PHP returning empty $_POST and $_FILES when POST
     // length > post_max_size in php.ini
     if (empty($_FILES) && empty($_POST) && $_SERVER['CONTENT_LENGTH'] > 0) {
         $msg = _('The server was unable to handle that much POST ' . 'data (%s bytes) due to its current configuration.');
         $this->clientError(sprintf($msg, $_SERVER['CONTENT_LENGTH']));
         return;
     }
     if (empty($this->status)) {
         $this->clientError('Client must provide a \'status\' parameter with a value.', 400, $this->format);
         return;
     }
     if (empty($this->auth_user)) {
         $this->clientError(_('No such user.'), 404, $this->format);
         return;
     }
     $status_shortened = common_shorten_links($this->status);
     if (Notice::contentTooLong($status_shortened)) {
         // Note: Twitter truncates anything over 140, flags the status
         // as "truncated."
         $this->clientError(sprintf(_('That\'s too long. Max notice size is %d chars.'), Notice::maxContent()), 406, $this->format);
         return;
     }
     // Check for commands
     $inter = new CommandInterpreter();
     $cmd = $inter->handle_command($this->auth_user, $status_shortened);
     if ($cmd) {
         if ($this->supported($cmd)) {
             $cmd->execute(new Channel());
         }
         // Cmd not supported?  Twitter just returns your latest status.
         // And, it returns your last status whether the cmd was successful
         // or not!
         $this->notice = $this->auth_user->getCurrentNotice();
     } else {
         $reply_to = null;
         if (!empty($this->in_reply_to_status_id)) {
             // Check whether notice actually exists
             $reply = Notice::staticGet($this->in_reply_to_status_id);
             if ($reply) {
                 $reply_to = $this->in_reply_to_status_id;
             } else {
                 $this->clientError(_('Not found.'), $code = 404, $this->format);
                 return;
             }
         }
         $upload = null;
         try {
             $upload = MediaFile::fromUpload('media', $this->auth_user);
         } catch (ClientException $ce) {
             $this->clientError($ce->getMessage());
             return;
         }
         if (isset($upload)) {
             $status_shortened .= ' ' . $upload->shortUrl();
             if (Notice::contentTooLong($status_shortened)) {
                 $upload->delete();
                 $msg = _('Max notice size is %d chars, ' . 'including attachment URL.');
                 $this->clientError(sprintf($msg, Notice::maxContent()));
             }
         }
         $content = html_entity_decode($status_shortened, ENT_NOQUOTES, 'UTF-8');
         $options = array('reply_to' => $reply_to);
         if ($this->auth_user->shareLocation()) {
             $locOptions = Notice::locationOptions($this->lat, $this->lon, null, null, $this->auth_user->getProfile());
             $options = array_merge($options, $locOptions);
         }
         try {
             $this->notice = Notice::saveNew($this->auth_user->id, $content, $this->source, $options);
         } catch (Exception $e) {
             $this->clientError($e->getMessage());
             return;
         }
         if (isset($upload)) {
             $upload->attachToNotice($this->notice);
         }
     }
     $this->showNotice();
 }
Example #28
0
 private function upload($tmpfile, $shortname, $description = '', $replace = false)
 {
     try {
         $audioInfo = MediaScanner::getAudioInfo($tmpfile);
     } catch (Exception $e) {
         message::set('File error: ' . $e->getMessage());
         return FALSE;
     }
     $destfile = Media::getMediaFilename($shortname, $audioInfo['rates'][0], FALSE);
     // Get whatever the proper name should be
     $dir = dirname($destfile);
     /* can we write to the target folder? */
     if (!filesystem::is_writable($dir)) {
         message::set('The path ' . $dir . ' is not writable!');
         return FALSE;
     }
     $this->createFolder($dir);
     if (!is_writable(dirname($destfile)) or file_exists($destfile) and !is_writable($destfile)) {
         message::set(dirname($destfile) . ' is not writable');
         return FALSE;
     }
     try {
         move_uploaded_file($tmpfile, $destfile);
     } catch (Exception $e) {
         message::set('Unable to move uploaded file into ' . $destfile . '. ' . $e->getMessage());
         return FALSE;
     }
     // See if this is in the DB
     $mediaFile = Doctrine::getTable('MediaFile')->findOneByFile($shortname);
     if ($mediaFile) {
         // Note that this is a bit dangerous and could use improvement.
         // We assume that all other properties in the file we just found match the file already uploaded.
         // That means if someone uploads the wrong audio file, it kinda messes things up big time.
         if (!in_array($audioInfo['byterate'], (array) $mediaFile['registry']['rates'])) {
             Kohana::log('debug', 'Updating ' . $shortname . "...");
             $registry = (array) $mediaFile['registry'];
             $registry['rates'][] = $audioInfo['byterate'];
             $mediaFile['registry'] = $registry;
             $mediaFile['description'] = strlen($description) > 0 ? $description : $mediaFile['description'];
             $mediaFile->save();
         } else {
             if (strcmp($mediaFile['description'], $description)) {
                 $mediaFile['description'] = $description;
                 $mediaFile->save();
             } else {
                 Kohana::log('debug', 'SKIPPED DB UPDATE - Nothing to update on ' . $shortname . " with sample rate " . $audioInfo['byterate'] . "... ");
             }
         }
         message::set('Successfully updated audio file in the system.', 'success');
         url::redirect(Router_Core::$controller . '/index');
     } else {
         // NEW FILE! Do lots of stuff
         // Save info about file
         $mediaFile = new MediaFile();
         $mediaFile['file'] = $shortname;
         $mediaFile['path'] = dirname($mediaFile['file']);
         // We track the path separately to ease searching
         $mediaFile['account_id'] = 1;
         // See if we know this filename, description & category from the XML info
         if (isset($descriptions[$shortname])) {
             $mediaFile['description'] = $descriptions[$shortname];
         } else {
             if (strlen($description) > 0) {
                 $mediaFile['description'] = $description;
             } else {
                 $mediaFile['description'] = 'Unknown';
             }
         }
         Kohana::log('debug', 'Adding ' . $mediaFile['file'] . " to the database.");
         $mediaFile['registry'] += $audioInfo;
         $mediaFile->save();
         message::set('Successfully added audio file to the system.', 'success');
         url::redirect(Router_Core::$controller . '/index');
     }
 }
 /**
  * Find all post_ids associated with this feed.
  * 
  * @return array
  */
 function post_ids()
 {
     global $wpdb;
     $allowed_status = array("publish");
     $allowed_status = apply_filters("podlove_feed_post_ids_allowed_status", $allowed_status);
     $sql = "\n\t\t\tSELECT\n\t\t\t\tp.ID\n\t\t\tFROM\n\t\t\t\t" . $wpdb->posts . " p\n\t\t\t\tINNER JOIN " . Episode::table_name() . " e ON e.post_id = p.ID\n\t\t\t\tINNER JOIN " . MediaFile::table_name() . " mf ON mf.`episode_id` = e.id\n\t\t\t\tINNER JOIN " . EpisodeAsset::table_name() . " a ON a.id = mf.`episode_asset_id`\n\t\t\tWHERE\n\t\t\t\ta.id = %d\n\t\t\t\tAND\n\t\t\t\tp.post_status IN (" . implode(',', array_map(function ($s) {
         return "'{$s}'";
     }, $allowed_status)) . ")\n\t\t\tORDER BY\n\t\t\t\tp.post_date DESC\n\t\t";
     return $wpdb->get_col($wpdb->prepare($sql, $this->episode_asset()->id));
 }
 /**
  * Handle the request
  *
  * @return void
  */
 protected function handle()
 {
     parent::handle();
     $profile = $this->user->getProfile();
     $base64img = $this->img;
     if (stristr($base64img, 'image/jpeg')) {
         $base64img_mime = 'image/jpeg';
     } elseif (stristr($base64img, 'image/png')) {
         // should convert to jpg here!!
         $base64img_mime = 'image/png';
     }
     $base64img = str_replace('data:image/jpeg;base64,', '', $base64img);
     $base64img = str_replace('data:image/png;base64,', '', $base64img);
     $base64img = str_replace(' ', '+', $base64img);
     $base64img_hash = md5($base64img);
     $base64img = base64_decode($base64img);
     $base64img_basename = basename('bg');
     $base64img_filename = File::filename($profile, $base64img_basename, $base64img_mime);
     $base64img_path = File::path($base64img_filename);
     $base64img_success = file_put_contents($base64img_path, $base64img);
     $base64img_mimetype = MediaFile::getUploadedMimeType($base64img_path, $base64img_filename);
     $mediafile = new MediaFile($profile, $base64img_filename, $base64img_mimetype);
     $imagefile = new ImageFile($mediafile->fileRecord->id, File::path($mediafile->filename));
     $imagefile->resizeTo(File::path($mediafile->filename), array('width' => 1280, 'height' => 1280, 'x' => $this->cropX, 'y' => $this->cropY, 'w' => $this->cropW, 'h' => $this->cropH));
     $result['url'] = File::url($mediafile->filename);
     Profile_prefs::setData($profile, 'qvitter', 'background_image', $result['url']);
     $this->initDocument('json');
     $this->showJsonObjects($result);
     $this->endDocument('json');
 }