/** * Indexes document that was set in __construct. */ public function indexCrawledDocuments() { $sFileName = $this->oFile->getName(); $oFileMinorDocType = $this->oDbr->selectRow('image', 'img_minor_mime', array('img_name' => $sFileName, 'img_major_mime' => 'application')); if ($oFileMinorDocType === false) { return; } $sFileDocType = $this->mimeDecoding($oFileMinorDocType->img_minor_mime, $sFileName); if (!$this->checkDocType($sFileDocType, $sFileName)) { return; } $sFileTimestamp = $this->oFile->getTimestamp(); $sVirtualFilePath = $this->oFile->getPath(); $oFileRepoLocalRef = $this->oFile->getRepo()->getLocalReference($sVirtualFilePath); if (!is_null($oFileRepoLocalRef)) { $sFilePath = $oFileRepoLocalRef->getPath(); } if ($this->checkExistence($sVirtualFilePath, 'repo', $sFileTimestamp, $sFileName)) { return; } $sFileText = $this->getFileText($sFilePath, $sFileName); $doc = $this->makeRepoDocument($sFileDocType, $sFileName, $sFileText, $sFilePath, $sFileTimestamp, $sVirtualFilePath); if ($doc) { // mode and ERROR_MSG_KEY are only passed for the case when addDocument fails $this->oMainControl->addDocument($doc, $this->mode, self::S_ERROR_MSG_KEY); } }
public function executeImage(sfWebRequest $request) { $member = $this->getRoute()->getMember(); if (!$member) { return sfView::NONE; } $message = $request->getMailMessage(); $images = $message->getImages(); foreach ($images as $image) { $count = $member->getMemberImage()->count(); if ($count >= 3) { return sfView::ERROR; } $validator = new opValidatorImageFile(); $validFile = $validator->clean($image); $file = new File(); $file->setFromValidatedFile($validFile); $file->setName('m_' . $member->getId() . '_' . $file->getName()); $memberImage = new MemberImage(); $memberImage->setMember($member); $memberImage->setFile($file); if (!$count) { $memberImage->setIsPrimary(true); } $memberImage->save(); } return sfView::NONE; }
public function executeImage(sfWebRequest $request) { $member = $this->getRoute()->getMember(); if (!$member) { return sfView::NONE; } $community = Doctrine::getTable('Community')->find($request->getParameter('id')); if (!$community) { return sfView::ERROR; } $isAdmin = Doctrine::getTable('CommunityMember')->isAdmin($member->getId(), $community->getId()); if (!$isAdmin || $community->getImageFileName()) { return sfView::ERROR; } $message = $request->getMailMessage(); if ($images = $message->getImages()) { $image = array_shift($images); $validator = new opValidatorImageFile(); $validFile = $validator->clean($image); $file = new File(); $file->setFromValidatedFile($validFile); $file->setName('c_' . $community->getId() . '_' . $file->getName()); $community->setFile($file); $community->save(); } return sfView::NONE; }
/** * Get the name of the file * * If there is no processed file in the file system (as the original file did not have to be modified e.g. * when the original image is in the boundaries of the maxW/maxH stuff) * then just return the name of the original file * * @return string */ public function getName() { if ($this->usesOriginalFile()) { return $this->originalFile->getName(); } else { return $this->name; } }
/** * Runs the test. */ public function test() { $path = DIR_FILES . '/mail/logo.gif'; $name = 'logo.gif'; $mimeType = 'image/gif'; $attachment = new File($path, $name, $mimeType); $this->assertEquals(file_get_contents($path), $attachment->getContent()); $this->assertEquals($name, $attachment->getName()); $this->assertEquals($mimeType, $attachment->getMimeType()); $this->assertEquals(\Jyxo\Mail\Email\Attachment::DISPOSITION_ATTACHMENT, $attachment->getDisposition()); $this->assertFalse($attachment->isInline()); $this->assertEquals('', $attachment->getCid()); $this->assertEquals('', $attachment->getEncoding()); }
public function save() { $file = new File(); $file->setFromValidatedFile($this->getValue('file')); $file->setName('b_' . $file->getName()); if ($this->isNew()) { $bannerImage = new BannerImage(); } else { $bannerImage = $this->getObject(); } $bannerImage->setFile($file); $bannerImage->setUrl($this->getValue('url')); $bannerImage->setName($this->getValue('name')); return $bannerImage->save(); }
public function control() { $this->redirectToSternIndiaEndPoint(); $config = Config::getInstance(); if (isset($_POST['upload']) && $_POST['upload'] == 'Upload') { $target_dir = new FileSystem('upload/'); $file = new File('foo', $target_dir); $name = date('D_d_m_Y_H_m_s_'); $name = $name . $file->getName(); $file->setName($name); $config = Config::getInstance(); $file->addValidations(array(new Mimetype($config->getMimeTypes()), new Size('5M'))); $data = array('name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5()); try { // /Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__,$data); $file->upload(); //Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__,$data); } catch (Exception $e) { $errors = $file->getErrors(); } $csvReader = new CSVReader(); $destinationFile = $target_dir->directory . $file->getNameWithExtension(); $data = $csvReader->parse_file($destinationFile); //$country= DAOFactory::getDAO('LocationDAO'); foreach ($data as $loc_arr) { Utils::processLocation($loc_arr); } //Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__); $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if (isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if ($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } } return $this->generateView(); }
/** * Override handling of action=purge */ public function doPurge() { $this->loadFile(); if ($this->mFile->exists()) { wfDebug('ImagePage::doPurge purging ' . $this->mFile->getName() . "\n"); $update = new HTMLCacheUpdate($this->mTitle, 'imagelinks'); $update->doUpdate(); $this->mFile->upgradeRow(); $this->mFile->purgeCache(array('forThumbRefresh' => true)); } else { wfDebug('ImagePage::doPurge no image for ' . $this->mFile->getName() . "; limiting purge to cache only\n"); // even if the file supposedly doesn't exist, force any cached information // to be updated (in case the cached information is wrong) $this->mFile->purgeCache(array('forThumbRefresh' => true)); } return parent::doPurge(); }
public function save() { $count = $this->member->getMemberImage()->count(); if ($count >= 3) { throw new opRuntimeException('Cannot add an image any more.'); } $file = new File(); $file->setFromValidatedFile($this->getValue('file')); $file->setName('m_' . $this->member->getId() . '_' . $file->getName()); $memberImage = new MemberImage(); $memberImage->setMember($this->member); $memberImage->setFile($file); if (!$count) { $memberImage->setIsPrimary(true); } return $memberImage->save(); }
public function save() { if ($this->getValue('file')) { if ($this->community->getFile()) { $this->community->getFile()->delete(); } $file = new File(); $file->setFromValidatedFile($this->getValue('file')); $file->setName('c_' . $this->community->getId() . '_' . $file->getName()); $this->community->setFile($file); } elseif ($this->getValue('file_delete')) { $this->community->getFile()->delete(); $this->community->setFile(null); } else { return; } $this->community->save(); }
/** * Performs a transform with VIPS * * @see VipsScaler::onTransform * * @param BitmapHandler $handler * @param File $file * @param array $params * @param array $options * @param MediaTransformOutput &$mto * @return bool */ public static function doTransform( $handler, $file, $params, $options, &$mto ) { wfDebug( __METHOD__ . ': scaling ' . $file->getName() . " using vips\n" ); $vipsCommands = self::makeCommands( $handler, $file, $params, $options ); if ( count( $vipsCommands ) == 0 ) { return true; } # Execute the commands foreach ( $vipsCommands as $i => $command ) { # Set input/output files if ( $i == 0 && count( $vipsCommands ) == 1 ) { # Single command, so output directly to dstPath $command->setIO( $params['srcPath'], $params['dstPath'] ); } elseif ( $i == 0 ) { # First command, input from srcPath, output to temp $command->setIO( $params['srcPath'], 'v', VipsCommand::TEMP_OUTPUT ); } elseif ( $i + 1 == count( $vipsCommands ) ) { # Last command, output to dstPath $command->setIO( $vipsCommands[$i - 1], $params['dstPath'] ); } else { $command->setIO( $vipsCommands[$i - 1], 'v', VipsCommand::TEMP_OUTPUT ); } $retval = $command->execute(); if ( $retval != 0 ) { wfDebug( __METHOD__ . ": vips command failed!\n" ); $mto = $handler->getMediaTransformError( $params, $command->getErrorString() ); return false; } } # Set comment if ( !empty( $options['setcomment'] ) && !empty( $params['comment'] ) ) { self::setJpegComment( $params['dstPath'], $params['comment'] ); } # Set the output variable $mto = new ThumbnailImage( $file, $params['dstUrl'], $params['clientWidth'], $params['clientHeight'], $params['dstPath'] ); # Stop processing return false; }
public function updateObject($values = null) { if (is_null($values)) { $values = $this->getValues(); } $image = null; if (array_key_exists('image', $values)) { $image = $values['image']; unset($values['image']); } $obj = parent::updateObject($values); if ($image instanceof sfValidatedFile) { unset($obj->Image); $file = new File(); $file->setFromValidatedFile($image); $file->setName('oauth_' . $obj->getId() . '_' . $file->getName()); $obj->setImage($file); } }
/** * Override handling of action=purge * @return bool */ public function doPurge() { $this->loadFile(); if ($this->mFile->exists()) { wfDebug('ImagePage::doPurge purging ' . $this->mFile->getName() . "\n"); DeferredUpdates::addUpdate(new HTMLCacheUpdate($this->mTitle, 'imagelinks')); $this->mFile->purgeCache(['forThumbRefresh' => true]); } else { wfDebug('ImagePage::doPurge no image for ' . $this->mFile->getName() . "; limiting purge to cache only\n"); // even if the file supposedly doesn't exist, force any cached information // to be updated (in case the cached information is wrong) $this->mFile->purgeCache(['forThumbRefresh' => true]); } if ($this->mRepo) { // Purge redirect cache $this->mRepo->invalidateImageRedirect($this->mTitle); } return parent::doPurge(); }
/** * Override handling of action=purge */ public function doPurge() { global $wgCityId; $this->loadFile(); if ($this->mFile->exists()) { wfDebug('ImagePage::doPurge purging ' . $this->mFile->getName() . "\n"); // Wikia Change Start @author Scott Rabin (srabin@wikia-inc.com) $task = (new \Wikia\Tasks\Tasks\HTMLCacheUpdateTask())->wikiId($wgCityId)->title($this->mTitle); $task->call('purge', 'imagelinks'); $task->queue(); // Wikia Change End $this->mFile->upgradeRow(); $this->mFile->purgeCache(array('forThumbRefresh' => true)); } else { wfDebug('ImagePage::doPurge no image for ' . $this->mFile->getName() . "; limiting purge to cache only\n"); // even if the file supposedly doesn't exist, force any cached information // to be updated (in case the cached information is wrong) $this->mFile->purgeCache(array('forThumbRefresh' => true)); } return parent::doPurge(); }
function get_gallery() { $gallery_name = Params::get("gallery_name"); $result = array(); $result["gallery_name"] = $gallery_name; $d = new Dir(self::GALLERY_ROOT_PATH . $gallery_name); $files = $d->listFiles(); $image_list = array(); foreach ($files as $f) { if ($f->isFile() && $f->getExtension() != ".ini") { $image = array(); $image["path"] = $f->getPath(); $image["title"] = str_replace("_", " ", $f->getName()); $image_list[$f->getFilename()] = $image; } } $gallery_dir = new Dir(self::GALLERY_ROOT_PATH . $gallery_name . DS); $found_files = $gallery_dir->findFilesEndingWith("gallery.ini"); if (count($found_files) > 0) { $gallery_ini_file = $found_files[0]; $gallery_props = PropertiesUtils::readFromFile($gallery_ini_file, true); $enhanced_image_list = array(); foreach ($section as $s) { $path = $s["path"]; if (strpos($path, "DS") === 0) { $new_image["path"] = $path; } else { $new_image["path"] = self::GALLERY_ROOT_PATH . $gallery_name . $s["path"]; } $f = new File($new_image["path"]); $new_image["title"] = isset($s["title"]) ? $s["title"] : str_replace("_", " ", $f->getName()); $new_image["description"] = isset($s["description"]) ? $s["description"] : null; $enhanced_image_list[] = $new_image; } $result["image_list"] = $enhanced_image_list; } else { $result["image_list"] = $image_list; } return $result; }
/** * View the file * */ function view() { if ($this->active_file->isNew()) { $this->httpError(HTTP_ERR_NOT_FOUND); } // if if (!$this->active_file->canView($this->logged_user)) { $this->httpError(HTTP_ERR_FORBIDDEN); } // if $last_revision = $this->active_file->getLastRevision(); if (!instance_of($last_revision, 'Attachment')) { flash_error('Invalid file - last revision was not found'); $this->redirectToUrl(assemble_url('mobile_access')); } // if ProjectObjectViews::log($this->active_file, $this->logged_user); ProjectObjectViews::log($last_revision, $this->logged_user); $this->smarty->assign(array('revisions' => $this->active_file->getRevisions(), 'last_revision' => $last_revision, 'page_back_url' => assemble_url('mobile_access_view_files', array('project_id' => $this->active_project->getId())))); $this->addBreadcrumb(str_excerpt(clean($this->active_file->getName()), 10), mobile_access_module_get_view_url($this->active_file)); $this->addBreadcrumb(lang('View')); }
public function setImage($data) { $form = new MemberImageForm(array(), array('member' => $this->member)); $imageUri = ''; $pathList = array('media/image/default', 'media/image/aspect11', 'media/image/aspect43', 'media/image/aspect34'); foreach ($pathList as $v) { $img = $this->getValue($data, $v); if ($img) { $imageUri = $img; break; } } if ($imageUri) { $client = new Zend_Http_Client(array_shift($imageUri)); $response = $client->request(); if (!$response->isError()) { $type = $response->getHeader('Content-type'); if (is_array($type)) { $type = array_shift($type); } $tmppath = tempnam(sys_get_temp_dir(), 'IMG'); $fh = fopen($tmppath, 'w'); fwrite($fh, $response->getBody()); fclose($fh); $image = array('tmp_name' => $tmppath, 'type' => $type); $validator = new opValidatorImageFile(); $validFile = $validator->clean($image); $file = new File(); $file->setFromValidatedFile($validFile); $file->setName('m_' . $this->member->getId() . '_' . $file->getName()); $memberImage = new MemberImage(); $memberImage->setMember($this->member); $memberImage->setFile($file); $memberImage->setIsPrimary(true); $memberImage->save(); } } }
public function save() { foreach ($this->getValues() as $k => $v) { if (0 !== strpos($k, 'photo_')) { continue; } if (empty($v['file'])) { continue; } $file = new File(); $file->setFromValidatedFile($v['file']); if (empty($v['description'])) { $description = $file->getName(); } else { $description = $v['description']; } $albumImage = new AlbumImage(); $albumImage->setAlbum($this->albumInstance); $albumImage->setFile($file); $albumImage->setDescription($description); $albumImage->save(); } }
/** * Add a post */ public function iframe_add() { $this->setView('iframe_add.php'); @set_time_limit(0); $uploaded_files = array(); try { if (!isset(User_Model::$auth_data)) { throw new Exception(__('POST_ADD_ERROR_SESSION_EXPIRED')); } $is_student = isset(User_Model::$auth_data['student_number']); // Message $message = isset($_POST['message']) ? trim($_POST['message']) : ''; if ($message == '' || $message == __('PUBLISH_DEFAULT_MESSAGE')) { throw new Exception(__('POST_ADD_ERROR_NO_MESSAGE')); } $message = preg_replace('#\\n{2,}#', "\n\n", $message); // Category if (!isset($_POST['category']) || !ctype_digit($_POST['category'])) { throw new Exception(__('POST_ADD_ERROR_NO_CATEGORY')); } $category = (int) $_POST['category']; // Official post (in a group) $official = isset($_POST['official']); // Group $group = isset($_POST['group']) && ctype_digit($_POST['group']) ? (int) $_POST['group'] : 0; if ($group == 0) { $group = null; $official = false; } else { $groups_auth = Group_Model::getAuth(); if (isset($groups_auth[$group])) { if ($official && !$groups_auth[$group]['admin']) { throw new Exception(__('POST_ADD_ERROR_OFFICIAL')); } } else { throw new Exception(__('POST_ADD_ERROR_GROUP_NOT_FOUND')); } } // Private message $private = isset($_POST['private']); if ($private && !$is_student) { throw new Exception(__('POST_ADD_ERROR_PRIVATE')); } $attachments = array(); // Photos if (isset($_FILES['attachment_photo']) && is_array($_FILES['attachment_photo']['name'])) { foreach ($_FILES['attachment_photo']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_PHOTO) { throw new Exception(__('POST_ADD_ERROR_PHOTO_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_PHOTO)))); } } if ($filepaths = File::upload('attachment_photo')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { $name = isset($_FILES['attachment_photo']['name'][$i]) ? $_FILES['attachment_photo']['name'][$i] : ''; try { $img = new Image(); $img->load($filepath); $type = $img->getType(); if ($type == IMAGETYPE_JPEG) { $ext = 'jpg'; } else { if ($type == IMAGETYPE_GIF) { $ext = 'gif'; } else { if ($type == IMAGETYPE_PNG) { $ext = 'png'; } else { throw new Exception(); } } } if ($img->getWidth() > 800) { $img->setWidth(800, true); } $img->save($filepath); // Thumb $thumbpath = $filepath . '.thumb'; $img->thumb(Config::$THUMBS_SIZES[0], Config::$THUMBS_SIZES[1]); $img->setType(IMAGETYPE_JPEG); $img->save($thumbpath); unset($img); $attachments[] = array($filepath, $name, $thumbpath); $uploaded_files[] = $thumbpath; } catch (Exception $e) { throw new Exception(__('POST_ADD_ERROR_PHOTO_FORMAT')); } } } } // Vidéos /* @uses PHPVideoToolkit : http://code.google.com/p/phpvideotoolkit/ * @requires ffmpeg, php5-ffmpeg */ if (isset($_FILES['attachment_video']) && is_array($_FILES['attachment_video']['name'])) { foreach ($_FILES['attachment_video']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_VIDEO) { throw new Exception(__('POST_ADD_ERROR_VIDEO_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_VIDEO)))); } } if ($filepaths = File::upload('attachment_video')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { $name = isset($_FILES['attachment_video']['name'][$i]) ? $_FILES['attachment_video']['name'][$i] : ''; try { $video = new ffmpeg_movie($filepath, false); if (!$video->hasVideo()) { throw new Exception('No video stream found in the file'); } if (!$video->hasAudio()) { throw new Exception('No audio stream found in the file'); } } catch (Exception $e) { throw new Exception(__('POST_ADD_ERROR_VIDEO_FORMAT')); } // Video conversion try { $video_current_width = $video->getFrameWidth(); $video_width = min($video_current_width, Config::VIDEO_MAX_WIDTH); if ($video_width % 2 == 1) { // Even number required $video_width--; } $video_height = $video_width * $video->getFrameHeight() / $video_current_width; if ($video_height % 2 == 1) { // Even number required $video_height--; } // Extract thumb $video_thumb = $video->getFrame(round($video->getFrameCount() * 0.2)); unset($video); $video_thumb = $video_thumb->toGDImage(); $thumbpath = DATA_DIR . Config::DIR_DATA_TMP . File::getName($filepath) . '.thumb'; imagejpeg($video_thumb, $thumbpath, 95); unset($video_thumb); $img = new Image(); $img->load($thumbpath); $img->setWidth($video_width, true); $img->setType(IMAGETYPE_JPEG); $img->save($thumbpath); $uploaded_files[] = $thumbpath; unset($img); // Convert to FLV if (!preg_match('#\\.flv$#i', $filepath)) { $toolkit = new PHPVideoToolkit(); $toolkit->on_error_die = true; // Will throw exception on error $toolkit->setInputFile($filepath); $toolkit->setVideoOutputDimensions($video_width, $video_height); $toolkit->setFormatToFLV(Config::VIDEO_SAMPLING_RATE, Config::VIDEO_AUDIO_BIT_RATE); $toolkit->setOutput(DATA_DIR . Config::DIR_DATA_TMP, File::getName($filepath) . '.flv', PHPVideoToolkit::OVERWRITE_EXISTING); $toolkit->execute(false, false); // Multipass: false, Log: false File::delete($filepath); $filepath = $toolkit->getLastOutput(); $filepath = $filepath[0]; unset($toolkit); } $attachments[] = array($filepath, $name, $thumbpath); $uploaded_files[] = $filepath; } catch (Exception $e) { throw new Exception(__('POST_ADD_ERROR_VIDEO_CONVERT') . $e->getMessage()); } } } } // Audios if (isset($_FILES['attachment_audio']) && is_array($_FILES['attachment_audio']['name'])) { foreach ($_FILES['attachment_audio']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_AUDIO) { throw new Exception(__('POST_ADD_ERROR_AUDIO_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_AUDIO)))); } } if ($filepaths = File::upload('attachment_audio')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { if (!preg_match('#\\.mp3$#', $filepath)) { throw new Exception(__('POST_ADD_ERROR_AUDIO_FORMAT')); } $name = isset($_FILES['attachment_audio']['name'][$i]) ? $_FILES['attachment_audio']['name'][$i] : ''; $attachments[] = array($filepath, $name); } } } // Files if (isset($_FILES['attachment_file']) && is_array($_FILES['attachment_file']['name'])) { foreach ($_FILES['attachment_file']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_FILE) { throw new Exception(__('POST_ADD_ERROR_FILE_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_FILE)))); } } if ($filepaths = File::upload('attachment_file')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { if (!preg_match('#\\.[a-z0-9]{2,4}$#i', $filepath)) { throw new Exception(__('POST_ADD_ERROR_FILE_FORMAT')); } if (preg_match('#\\.(jpg|png|gif|mp3|flv)$#i', $filepath)) { throw new Exception(__('POST_ADD_ERROR_FILE_FORMAT2')); } $name = isset($_FILES['attachment_file']['name'][$i]) ? $_FILES['attachment_file']['name'][$i] : ''; $attachments[] = array($filepath, $name); } } } // Event if (isset($_POST['event_title']) && isset($_POST['event_start']) && isset($_POST['event_end'])) { // Title $event_title = trim($_POST['event_title']); if ($event_title == '') { throw new Exception(__('POST_ADD_ERROR_EVENT_NO_TITLE')); } // Dates if (!($event_start = strptime($_POST['event_start'], __('PUBLISH_EVENT_DATE_FORMAT')))) { throw new Exception(__('POST_ADD_ERROR_EVENT_DATE')); } if (!($event_end = strptime($_POST['event_end'], __('PUBLISH_EVENT_DATE_FORMAT')))) { throw new Exception(__('POST_ADD_ERROR_EVENT_DATE')); } $event_start = mktime($event_start['tm_hour'], $event_start['tm_min'], 0, $event_start['tm_mon'] + 1, $event_start['tm_mday'], $event_start['tm_year'] + 1900); $event_end = mktime($event_end['tm_hour'], $event_end['tm_min'], 0, $event_end['tm_mon'] + 1, $event_end['tm_mday'], $event_end['tm_year'] + 1900); if ($event_start > $event_end) { throw new Exception(__('POST_ADD_ERROR_EVENT_DATE_ORDER')); } $event = array($event_title, $event_start, $event_end); } else { $event = null; } // Survey if (isset($_POST['survey_question']) && isset($_POST['survey_end']) && isset($_POST['survey_answer']) && is_array($_POST['survey_answer'])) { // Question $survey_question = trim($_POST['survey_question']); if ($survey_question == '') { throw new Exception(__('POST_ADD_ERROR_SURVEY_NO_QUESTION')); } // Date if (!($survey_end = strptime($_POST['survey_end'], __('PUBLISH_EVENT_DATE_FORMAT')))) { throw new Exception(__('POST_ADD_ERROR_SURVEY_DATE')); } $survey_end = mktime($survey_end['tm_hour'], $survey_end['tm_min'], 0, $survey_end['tm_mon'] + 1, $survey_end['tm_mday'], $survey_end['tm_year'] + 1900); // Multiple answers $survey_multiple = isset($_POST['survey_multiple']); // Answers $survey_answers = array(); foreach ($_POST['survey_answer'] as $survey_answer) { $survey_answer = trim($survey_answer); if ($survey_answer != '') { $survey_answers[] = $survey_answer; } } if (count($survey_answers) < 2) { throw new Exception(__('POST_ADD_ERROR_SURVEY_ANSWERS')); } $survey = array($survey_question, $survey_end, $survey_multiple, $survey_answers); } else { $survey = null; } // Creation of the post $id = $this->model->addPost((int) User_Model::$auth_data['id'], $message, $category, $group, $official, $private); // Attach files foreach ($attachments as $attachment) { $this->model->attachFile($id, $attachment[0], $attachment[1], isset($attachment[2]) ? $attachment[2] : null); } // Event if (isset($event)) { $this->model->attachEvent($id, $event[0], $event[1], $event[2]); } // Survey if (isset($survey)) { $this->model->attachSurvey($id, $survey[0], $survey[1], $survey[2], $survey[3]); } $this->addJSCode(' parent.location = "' . Config::URL_ROOT . Routes::getPage('home') . '"; '); } catch (Exception $e) { // Delete all uploading files in tmp foreach ($uploaded_files as $uploaded_file) { File::delete($uploaded_file); } $this->addJSCode(' with(parent){ Post.errorForm(' . json_encode($e->getMessage()) . '); } '); } }
/** * Update the images's oi_deleted field * @param File $file * @param int $bitfield new rev_deleted bitfield value */ function updateOldFiles($file, $bitfield) { $this->dbw->update('oldimage', array('oi_deleted' => $bitfield), array('oi_name' => $file->getName(), 'oi_timestamp' => $this->dbw->timestamp($file->getTimestamp())), __METHOD__); }
private function fileEquals(File $file1, File $file2) { return $file1->getName() == $file2->getName() && $file1->getLength() == $file2->getLength() && $file1->getPartialContent() == $file2->getPartialContent(); }
/** * @param bool $iscur * @param File $file * @return string */ public function imageHistoryLine($iscur, $file) { global $wgContLang; $user = $this->getUser(); $lang = $this->getLanguage(); $timestamp = wfTimestamp(TS_MW, $file->getTimestamp()); $img = $iscur ? $file->getName() : $file->getArchiveName(); $userId = $file->getUser('id'); $userText = $file->getUser('text'); $description = $file->getDescription(File::FOR_THIS_USER, $user); $local = $this->current->isLocal(); $row = $selected = ''; // Deletion link if ($local && $user->isAllowedAny('delete', 'deletedhistory')) { $row .= '<td>'; # Link to remove from history if ($user->isAllowed('delete')) { $q = ['action' => 'delete']; if (!$iscur) { $q['oldimage'] = $img; } $row .= Linker::linkKnown($this->title, $this->msg($iscur ? 'filehist-deleteall' : 'filehist-deleteone')->escaped(), [], $q); } # Link to hide content. Don't show useless link to people who cannot hide revisions. $canHide = $user->isAllowed('deleterevision'); if ($canHide || $user->isAllowed('deletedhistory') && $file->getVisibility()) { if ($user->isAllowed('delete')) { $row .= '<br />'; } // If file is top revision or locked from this user, don't link if ($iscur || !$file->userCan(File::DELETED_RESTRICTED, $user)) { $del = Linker::revDeleteLinkDisabled($canHide); } else { list($ts, ) = explode('!', $img, 2); $query = ['type' => 'oldimage', 'target' => $this->title->getPrefixedText(), 'ids' => $ts]; $del = Linker::revDeleteLink($query, $file->isDeleted(File::DELETED_RESTRICTED), $canHide); } $row .= $del; } $row .= '</td>'; } // Reversion link/current indicator $row .= '<td>'; if ($iscur) { $row .= $this->msg('filehist-current')->escaped(); } elseif ($local && $this->title->quickUserCan('edit', $user) && $this->title->quickUserCan('upload', $user)) { if ($file->isDeleted(File::DELETED_FILE)) { $row .= $this->msg('filehist-revert')->escaped(); } else { $row .= Linker::linkKnown($this->title, $this->msg('filehist-revert')->escaped(), [], ['action' => 'revert', 'oldimage' => $img, 'wpEditToken' => $user->getEditToken($img)]); } } $row .= '</td>'; // Date/time and image link if ($file->getTimestamp() === $this->img->getTimestamp()) { $selected = "class='filehistory-selected'"; } $row .= "<td {$selected} style='white-space: nowrap;'>"; if (!$file->userCan(File::DELETED_FILE, $user)) { # Don't link to unviewable files $row .= '<span class="history-deleted">' . $lang->userTimeAndDate($timestamp, $user) . '</span>'; } elseif ($file->isDeleted(File::DELETED_FILE)) { if ($local) { $this->preventClickjacking(); $revdel = SpecialPage::getTitleFor('Revisiondelete'); # Make a link to review the image $url = Linker::linkKnown($revdel, $lang->userTimeAndDate($timestamp, $user), [], ['target' => $this->title->getPrefixedText(), 'file' => $img, 'token' => $user->getEditToken($img)]); } else { $url = $lang->userTimeAndDate($timestamp, $user); } $row .= '<span class="history-deleted">' . $url . '</span>'; } elseif (!$file->exists()) { $row .= '<span class="mw-file-missing">' . $lang->userTimeAndDate($timestamp, $user) . '</span>'; } else { $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl($img); $row .= Xml::element('a', ['href' => $url], $lang->userTimeAndDate($timestamp, $user)); } $row .= "</td>"; // Thumbnail if ($this->showThumb) { $row .= '<td>' . $this->getThumbForLine($file) . '</td>'; } // Image dimensions + size $row .= '<td>'; $row .= htmlspecialchars($file->getDimensionsString()); $row .= $this->msg('word-separator')->escaped(); $row .= '<span style="white-space: nowrap;">'; $row .= $this->msg('parentheses')->sizeParams($file->getSize())->escaped(); $row .= '</span>'; $row .= '</td>'; // Uploading user $row .= '<td>'; // Hide deleted usernames if ($file->isDeleted(File::DELETED_USER)) { $row .= '<span class="history-deleted">' . $this->msg('rev-deleted-user')->escaped() . '</span>'; } else { if ($local) { $row .= Linker::userLink($userId, $userText); $row .= '<span style="white-space: nowrap;">'; $row .= Linker::userToolLinks($userId, $userText); $row .= '</span>'; } else { $row .= htmlspecialchars($userText); } } $row .= '</td>'; // Don't show deleted descriptions if ($file->isDeleted(File::DELETED_COMMENT)) { $row .= '<td><span class="history-deleted">' . $this->msg('rev-deleted-comment')->escaped() . '</span></td>'; } else { $row .= '<td dir="' . $wgContLang->getDir() . '">' . Linker::formatComment($description, $this->title) . '</td>'; } $rowClass = null; Hooks::run('ImagePageFileHistoryLine', [$this, $file, &$row, &$rowClass]); $classAttr = $rowClass ? " class='{$rowClass}'" : ''; return "<tr{$classAttr}>{$row}</tr>\n"; }
public function executePost(sfWebRequest $request) { $body = (string) $request['body']; $this->forward400If('' === $body, 'body parameter not specified.'); $this->forward400If(mb_strlen($body) > 140, 'The body text is too long.'); $memberId = $this->getUser()->getMemberId(); $options = array(); if (isset($request['public_flag'])) { $options['public_flag'] = $request['public_flag']; } if (isset($request['in_reply_to_activity_id'])) { $options['in_reply_to_activity_id'] = $request['in_reply_to_activity_id']; } if (isset($request['uri'])) { $options['uri'] = $request['uri']; } elseif (isset($request['url'])) { $options['uri'] = $request['url']; } if (isset($request['target']) && 'community' === $request['target']) { if (!isset($request['target_id'])) { $this->forward400('target_id parameter not specified.'); } $options['foreign_table'] = 'community'; $options['foreign_id'] = $request['target_id']; } $options['source'] = 'API'; $imageFiles = $request->getFiles('images'); if (!empty($imageFiles)) { foreach ((array) $imageFiles as $imageFile) { $validator = new opValidatorImageFile(array('required' => false)); try { $obj = $validator->clean($imageFile); } catch (sfValidatorError $e) { $this->forward400('This image file is invalid.'); } if (is_null($obj)) { continue; // empty value } $file = new File(); $file->setFromValidatedFile($obj); $file->setName('ac_' . $this->getUser()->getMemberId() . '_' . $file->getName()); $file->save(); $options['images'][]['file_id'] = $file->getId(); } } $this->activity = Doctrine::getTable('ActivityData')->updateActivity($memberId, $body, $options); if ('1' === $request['forceHtml']) { // workaround for some browsers (see #3201) $this->getRequest()->setRequestFormat('html'); $this->getResponse()->setContentType('text/html'); } $this->setTemplate('object'); }
/** * Call after file copy in filelist * Copy the file to the correct folder in the database * @param File $file * @param Folder $targetFolder * @return void */ public function postFileCopy($file, $targetFolder) { $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery("uid", "tx_ameosfilemanager_domain_model_folder", "tx_ameosfilemanager_domain_model_folder.identifier like '" . $targetFolder->getIdentifier() . "'"); if (($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) !== FALSE) { if (Tools::getFolderPathFromUid($row['uid']) . '/' == $targetFolder->getIdentifier()) { $newFile = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow("uid", "sys_file", "sys_file.identifier = '" . $targetFolder->getIdentifier() . $file->getName() . "'"); $res = $GLOBALS['TYPO3_DB']->exec_UPDATEquery('sys_file_metadata', 'sys_file_metadata.file = ' . $newFile['uid'], array("folder_uid" => $row['uid']), $no_quote_fields = FALSE); } } }
protected function openShowImage() { global $wgImageLimits, $wgEnableUploads, $wgSend404Code; $this->loadFile(); $out = $this->getContext()->getOutput(); $user = $this->getContext()->getUser(); $lang = $this->getContext()->getLanguage(); $dirmark = $lang->getDirMarkEntity(); $request = $this->getContext()->getRequest(); $max = $this->getImageLimitsFromOption($user, 'imagesize'); $maxWidth = $max[0]; $maxHeight = $max[1]; if ($this->displayImg->exists()) { # image $page = $request->getIntOrNull('page'); if (is_null($page)) { $params = array(); $page = 1; } else { $params = array('page' => $page); } $renderLang = $request->getVal('lang'); if (!is_null($renderLang)) { $handler = $this->displayImg->getHandler(); if ($handler && $handler->validateParam('lang', $renderLang)) { $params['lang'] = $renderLang; } else { $renderLang = null; } } $width_orig = $this->displayImg->getWidth($page); $width = $width_orig; $height_orig = $this->displayImg->getHeight($page); $height = $height_orig; $filename = wfEscapeWikiText($this->displayImg->getName()); $linktext = $filename; wfRunHooks('ImageOpenShowImageInlineBefore', array(&$this, &$out)); if ($this->displayImg->allowInlineDisplay()) { # image # "Download high res version" link below the image # $msgsize = wfMessage( 'file-info-size', $width_orig, $height_orig, Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped(); # We'll show a thumbnail of this image if ($width > $maxWidth || $height > $maxHeight) { # Calculate the thumbnail size. # First case, the limiting factor is the width, not the height. if ($width / $height >= $maxWidth / $maxHeight) { // FIXME: Possible division by 0. bug 36911 $height = round($height * $maxWidth / $width); // FIXME: Possible division by 0. bug 36911 $width = $maxWidth; # Note that $height <= $maxHeight now. } else { $newwidth = floor($width * $maxHeight / $height); // FIXME: Possible division by 0. bug 36911 $height = round($height * $newwidth / $width); // FIXME: Possible division by 0. bug 36911 $width = $newwidth; # Note that $height <= $maxHeight now, but might not be identical # because of rounding. } $linktext = wfMessage('show-big-image')->escaped(); if ($this->displayImg->getRepo()->canTransformVia404()) { $thumbSizes = $wgImageLimits; // Also include the full sized resolution in the list, so // that users know they can get it. This will link to the // original file asset if mustRender() === false. In the case // that we mustRender, some users have indicated that they would // find it useful to have the full size image in the rendered // image format. $thumbSizes[] = array($width_orig, $height_orig); } else { # Creating thumb links triggers thumbnail generation. # Just generate the thumb for the current users prefs. $thumbSizes = array($this->getImageLimitsFromOption($user, 'thumbsize')); if (!$this->displayImg->mustRender()) { // We can safely include a link to the "full-size" preview, // without actually rendering. $thumbSizes[] = array($width_orig, $height_orig); } } # Generate thumbnails or thumbnail links as needed... $otherSizes = array(); foreach ($thumbSizes as $size) { // We include a thumbnail size in the list, if it is // less than or equal to the original size of the image // asset ($width_orig/$height_orig). We also exclude // the current thumbnail's size ($width/$height) // since that is added to the message separately, so // it can be denoted as the current size being shown. if ($size[0] <= $width_orig && $size[1] <= $height_orig && $size[0] != $width && $size[1] != $height) { $sizeLink = $this->makeSizeLink($params, $size[0], $size[1]); if ($sizeLink) { $otherSizes[] = $sizeLink; } } } $otherSizes = array_unique($otherSizes); $msgsmall = ''; $sizeLinkBigImagePreview = $this->makeSizeLink($params, $width, $height); if ($sizeLinkBigImagePreview) { $msgsmall .= wfMessage('show-big-image-preview')->rawParams($sizeLinkBigImagePreview)->parse(); } if (count($otherSizes)) { $msgsmall .= ' ' . Html::rawElement('span', array('class' => 'mw-filepage-other-resolutions'), wfMessage('show-big-image-other')->rawParams($lang->pipeList($otherSizes))->params(count($otherSizes))->parse()); } } elseif ($width == 0 && $height == 0) { # Some sort of audio file that doesn't have dimensions # Don't output a no hi res message for such a file $msgsmall = ''; } elseif ($this->displayImg->isVectorized()) { # For vectorized images, full size is just the frame size $msgsmall = ''; } else { # Image is small enough to show full size on image page $msgsmall = wfMessage('file-nohires')->parse(); } $params['width'] = $width; $params['height'] = $height; $thumbnail = $this->displayImg->transform($params); Linker::processResponsiveImages($this->displayImg, $thumbnail, $params); $anchorclose = Html::rawElement('div', array('class' => 'mw-filepage-resolutioninfo'), $msgsmall); $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1; if ($isMulti) { $out->addModules('mediawiki.page.image.pagination'); $out->addHTML('<table class="multipageimage"><tr><td>'); } if ($thumbnail) { $options = array('alt' => $this->displayImg->getTitle()->getPrefixedText(), 'file-link' => true); $out->addHTML('<div class="fullImageLink" id="file">' . $thumbnail->toHtml($options) . $anchorclose . "</div>\n"); } if ($isMulti) { $count = $this->displayImg->pageCount(); if ($page > 1) { $label = $out->parse(wfMessage('imgmultipageprev')->text(), false); // on the client side, this link is generated in ajaxifyPageNavigation() // in the mediawiki.page.image.pagination module $link = Linker::linkKnown($this->getTitle(), $label, array(), array('page' => $page - 1)); $thumb1 = Linker::makeThumbLinkObj($this->getTitle(), $this->displayImg, $link, $label, 'none', array('page' => $page - 1)); } else { $thumb1 = ''; } if ($page < $count) { $label = wfMessage('imgmultipagenext')->text(); $link = Linker::linkKnown($this->getTitle(), $label, array(), array('page' => $page + 1)); $thumb2 = Linker::makeThumbLinkObj($this->getTitle(), $this->displayImg, $link, $label, 'none', array('page' => $page + 1)); } else { $thumb2 = ''; } global $wgScript; $formParams = array('name' => 'pageselector', 'action' => $wgScript); $options = array(); for ($i = 1; $i <= $count; $i++) { $options[] = Xml::option($lang->formatNum($i), $i, $i == $page); } $select = Xml::tags('select', array('id' => 'pageselector', 'name' => 'page'), implode("\n", $options)); $out->addHTML('</td><td><div class="multipageimagenavbox">' . Xml::openElement('form', $formParams) . Html::hidden('title', $this->getTitle()->getPrefixedDBkey()) . wfMessage('imgmultigoto')->rawParams($select)->parse() . Xml::submitButton(wfMessage('imgmultigo')->text()) . Xml::closeElement('form') . "<hr />{$thumb1}\n{$thumb2}<br style=\"clear: both\" /></div></td></tr></table>"); } } elseif ($this->displayImg->isSafeFile()) { # if direct link is allowed but it's not a renderable image, show an icon. $icon = $this->displayImg->iconThumb(); $out->addHTML('<div class="fullImageLink" id="file">' . $icon->toHtml(array('file-link' => true)) . "</div>\n"); } $longDesc = wfMessage('parentheses', $this->displayImg->getLongDesc())->text(); $medialink = "[[Media:{$filename}|{$linktext}]]"; if (!$this->displayImg->isSafeFile()) { $warning = wfMessage('mediawarning')->plain(); // dirmark is needed here to separate the file name, which // most likely ends in Latin characters, from the description, // which may begin with the file type. In RTL environment // this will get messy. // The dirmark, however, must not be immediately adjacent // to the filename, because it can get copied with it. // See bug 25277. $out->addWikiText(<<<EOT <div class="fullMedia"><span class="dangerousLink">{$medialink}</span> {$dirmark}<span class="fileInfo">{$longDesc}</span></div> <div class="mediaWarning">{$warning}</div> EOT ); } else { $out->addWikiText(<<<EOT <div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">{$longDesc}</span> </div> EOT ); } $renderLangOptions = $this->displayImg->getAvailableLanguages(); if (count($renderLangOptions) >= 1) { $currentLanguage = $renderLang; $defaultLang = $this->displayImg->getDefaultRenderLanguage(); if (is_null($currentLanguage)) { $currentLanguage = $defaultLang; } $out->addHtml($this->doRenderLangOpt($renderLangOptions, $currentLanguage, $defaultLang)); } // Add cannot animate thumbnail warning if (!$this->displayImg->canAnimateThumbIfAppropriate()) { // Include the extension so wiki admins can // customize it on a per file-type basis // (aka say things like use format X instead). // additionally have a specific message for // file-no-thumb-animation-gif $ext = $this->displayImg->getExtension(); $noAnimMesg = wfMessageFallback('file-no-thumb-animation-' . $ext, 'file-no-thumb-animation')->plain(); $out->addWikiText(<<<EOT <div class="mw-noanimatethumb">{$noAnimMesg}</div> EOT ); } if (!$this->displayImg->isLocal()) { $this->printSharedImageText(); } } else { # Image does not exist if (!$this->getID()) { # No article exists either # Show deletion log to be consistent with normal articles LogEventsList::showLogExtract($out, array('delete', 'move'), $this->getTitle()->getPrefixedText(), '', array('lim' => 10, 'conds' => array("log_action != 'revision'"), 'showIfEmpty' => false, 'msgKey' => array('moveddeleted-notice'))); } if ($wgEnableUploads && $user->isAllowed('upload')) { // Only show an upload link if the user can upload $uploadTitle = SpecialPage::getTitleFor('Upload'); $nofile = array('filepage-nofile-link', $uploadTitle->getFullURL(array('wpDestFile' => $this->mPage->getFile()->getName()))); } else { $nofile = 'filepage-nofile'; } // Note, if there is an image description page, but // no image, then this setRobotPolicy is overridden // by Article::View(). $out->setRobotPolicy('noindex,nofollow'); $out->wrapWikiMsg("<div id='mw-imagepage-nofile' class='plainlinks'>\n\$1\n</div>", $nofile); if (!$this->getID() && $wgSend404Code) { // If there is no image, no shared image, and no description page, // output a 404, to be consistent with articles. $request->response()->header('HTTP/1.1 404 Not Found'); } } $out->setFileVersion($this->displayImg); }
/** * @param File $file * @param bool $dumpContents * @return string */ function writeUpload($file, $dumpContents = false) { if ($file->isOld()) { $archiveName = " " . Xml::element('archivename', null, $file->getArchiveName()) . "\n"; } else { $archiveName = ''; } if ($dumpContents) { $be = $file->getRepo()->getBackend(); # Dump file as base64 # Uses only XML-safe characters, so does not need escaping # @todo Too bad this loads the contents into memory (script might swap) $contents = ' <contents encoding="base64">' . chunk_split(base64_encode($be->getFileContents(array('src' => $file->getPath())))) . " </contents>\n"; } else { $contents = ''; } if ($file->isDeleted(File::DELETED_COMMENT)) { $comment = Xml::element('comment', array('deleted' => 'deleted')); } else { $comment = Xml::elementClean('comment', null, $file->getDescription()); } return " <upload>\n" . $this->writeTimestamp($file->getTimestamp()) . $this->writeContributor($file->getUser('id'), $file->getUser('text')) . " " . $comment . "\n" . " " . Xml::element('filename', null, $file->getName()) . "\n" . $archiveName . " " . Xml::element('src', null, $file->getCanonicalURL()) . "\n" . " " . Xml::element('size', null, $file->getSize()) . "\n" . " " . Xml::element('sha1base36', null, $file->getSha1()) . "\n" . " " . Xml::element('rel', null, $file->getRel()) . "\n" . $contents . " </upload>\n"; }
/** * @covers ::__construct * @group Email */ public function testContstruct() { $object = new File($this->mock, 'name'); $this->assertEquals('name', $object->getName()); }
/** * Filter-out "Tenp_file_" images from list of URLs to purge * * @param File $file image to purge * @param array $urls URLs to purge generated by MW core */ static function onLocalFileExecuteUrls(File $file, array &$urls) { if (strpos($file->getName(), 'Temp_file_') === 0 && $file->getExtension() === '') { wfDebug(__METHOD__ . ": removed {$file->getName()} from the purger queue\n"); $urls = []; } return true; }
/** * Callback for usort() to do file sorts by name * * @param $a File * @param $b File * * @return Integer: result of name comparison */ public static function compare(File $a, File $b) { return strcmp($a->getName(), $b->getName()); }
/** * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation * cluster, and output it to STDOUT. * Note: Unlike the usual thumbnail process, the web client never sees the * cluster URL; we do the whole HTTP transaction to the scaler ourselves * and cat the results out. * Note: We rely on NFS to have propagated the file contents to the scaler. * However, we do not rely on the thumbnail being created in NFS and then * propagated back to our filesystem. Instead we take the results of the * HTTP request instead. * Note: No caching is being done here, although we are instructing the * client to cache it forever. * * @param File $file * @param array $params Scaling parameters ( e.g. array( width => '50' ) ); * @param int $flags Scaling flags ( see File:: constants ) * @throws MWException * @return bool Success */ private function outputRemoteScaledThumb($file, $params, $flags) { // This option probably looks something like // '//upload.wikimedia.org/wikipedia/test/thumb/temp'. Do not use // trailing slash. $scalerBaseUrl = $this->getConfig()->get('UploadStashScalerBaseUrl'); if (preg_match('/^\\/\\//', $scalerBaseUrl)) { // this is apparently a protocol-relative URL, which makes no sense in this context, // since this is used for communication that's internal to the application. // default to http. $scalerBaseUrl = wfExpandUrl($scalerBaseUrl, PROTO_CANONICAL); } // We need to use generateThumbName() instead of thumbName(), because // the suffix needs to match the file name for the remote thumbnailer // to work $scalerThumbName = $file->generateThumbName($file->getName(), $params); $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() . '/' . rawurlencode($scalerThumbName); // make a curl call to the scaler to create a thumbnail $httpOptions = array('method' => 'GET', 'timeout' => 5); $req = MWHttpRequest::factory($scalerThumbUrl, $httpOptions, __METHOD__); $status = $req->execute(); if (!$status->isOK()) { $errors = $status->getErrorsArray(); $errorStr = "Fetching thumbnail failed: " . print_r($errors, 1); $errorStr .= "\nurl = {$scalerThumbUrl}\n"; throw new MWException($errorStr); } $contentType = $req->getResponseHeader("content-type"); if (!$contentType) { throw new MWException("Missing content-type header"); } return $this->outputContents($req->getContent(), $contentType); }