public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media = null)
 {
     // If we are on a private node, we won't do any remote calls (just as a precaution until
     // we can configure this from config.php for the private nodes)
     if (common_config('site', 'private')) {
         return true;
     }
     if ($media !== 'image') {
         return true;
     }
     // If there is a local filename, it is either a local file already or has already been downloaded.
     if (!empty($file->filename)) {
         return true;
     }
     $this->checkWhitelist($file->getUrl());
     // First we download the file to memory and test whether it's actually an image file
     $imgData = HTTPClient::quickGet($file->getUrl());
     common_debug(sprintf('Downloading remote file id==%u with URL: %s', $file->id, $file->getUrl()));
     $info = @getimagesizefromstring($imgData);
     if ($info === false) {
         throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $file->getUrl());
     } elseif (!$info[0] || !$info[1]) {
         throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
     }
     $filehash = hash(File::FILEHASH_ALG, $imgData);
     try {
         // Exception will be thrown before $file is set to anything, so old $file value will be kept
         $file = File::getByHash($filehash);
         //FIXME: Add some code so we don't have to store duplicate File rows for same hash files.
     } catch (NoResultException $e) {
         $filename = $filehash . '.' . common_supported_mime_to_ext($info['mime']);
         $fullpath = File::path($filename);
         // Write the file to disk if it doesn't exist yet. Throw Exception on failure.
         if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
             throw new ServerException(_('Could not write downloaded file to disk.'));
         }
         // Updated our database for the file record
         $orig = clone $file;
         $file->filehash = $filehash;
         $file->filename = $filename;
         $file->width = $info[0];
         // array indexes documented on php.net:
         $file->height = $info[1];
         // https://php.net/manual/en/function.getimagesize.php
         // Throws exception on failure.
         $file->updateWithKeys($orig, 'id');
     }
     // Get rid of the file from memory
     unset($imgData);
     $imgPath = $file->getPath();
     return false;
 }
 /**
  * Crop an image file to a square thumbnail.
  * The thumbnail will be saved with the suffix "<width>_thumb_square"
  * @param File $basefile the file to crop.
  * @param number $maxDimension limit maximum with/height.
  * @return string the thumbnail's url or null if an error occured.
  */
 public static function getSquareThumbnailUrlFromFile($basefile = null, $maxDimension = 1000)
 {
     if ($basefile === null) {
         return;
     }
     $suffix = $maxDimension . '_thumb_square';
     $originalFilename = $basefile->getStoredFilePath();
     $previewFilename = $basefile->getStoredFilePath($suffix);
     // already generated
     if (is_file($previewFilename)) {
         return $basefile->getUrl($suffix);
     }
     // Check file exists & has valid mime type
     if ($basefile->getMimeBaseType() != "image" || !is_file($originalFilename)) {
         return "";
     }
     $imageInfo = @getimagesize($originalFilename);
     // check valid image dimesions
     if (!isset($imageInfo[0]) || !isset($imageInfo[1])) {
         return "";
     }
     // Check if image type is supported
     if ($imageInfo[2] != IMAGETYPE_PNG && $imageInfo[2] != IMAGETYPE_JPEG && $imageInfo[2] != IMAGETYPE_GIF) {
         return "";
     }
     $dim = min($imageInfo[0], $imageInfo[1], $maxDimension);
     ImageConverter::Resize($originalFilename, $previewFilename, array('mode' => 'force', 'width' => $dim, 'height' => $dim));
     return $basefile->getUrl($suffix);
 }
Example #3
0
 public function themeImage()
 {
     $this->uploader->setRequest(Request::createFromGlobals());
     $result = $this->uploader->uploadImageFile();
     $file = new File($result['upload_file_id']);
     $answer = array('file' => array('url' => $file->getUrl(), 'id' => $file->id));
     echo json_encode($answer);
 }
 /**
  * Get the link to the file.
  * Overridden by RevDelArchivedFileItem.
  * @return string
  */
 protected function getLink()
 {
     $date = htmlspecialchars($this->list->getLanguage()->userTimeAndDate($this->file->getTimestamp(), $this->list->getUser()));
     if (!$this->isDeleted()) {
         # Regular files...
         return Html::rawElement('a', array('href' => $this->file->getUrl()), $date);
     }
     # Hidden files...
     if (!$this->canViewContent()) {
         $link = $date;
     } else {
         $link = Linker::link(SpecialPage::getTitleFor('Revisiondelete'), $date, array(), array('target' => $this->list->title->getPrefixedText(), 'file' => $this->file->getArchiveName(), 'token' => $this->list->getUser()->getEditToken($this->file->getArchiveName())));
     }
     return '<span class="history-deleted">' . $link . '</span>';
 }
Example #5
0
 /*
 $latestVersions = array();
 foreach($versions as $version_item) {
 	if ($version_item['APPROVED']) {
 		$tmpFile = new File($id, $version_item['VERSION']);
 		$tmpFileInfo = $tmpFile->get();
 		if ($version_item['VERSION'] == $tmpFileInfo['VIEWVERSION']) {
 			array_push($latestVersions, $version_item);
 		}
 	}
 }
 $versions = $latestVersions;
 */
 $fileinfo = $file->get();
 $name = $fileinfo["NAME"];
 $url = $file->getUrl();
 $views = $file->views->getAssigned();
 $viewinfo = $file->views->getGeneratedViewInfo($views[0]["ID"]);
 $views[0]['WIDTH'] = $viewinfo[0]["WIDTH"];
 $views[0]['HEIGHT'] = $viewinfo[0]["HEIGHT"];
 $viewid = false;
 if ($view != "") {
     for ($i = 0; $i < count($views); $i++) {
         if ($views[$i]["IDENTIFIER"] == $view) {
             $viewid = $views[$i]["ID"];
         }
     }
 }
 if ($viewid == false) {
     $viewid = $views[0]["ID"];
 }
 static function fromFile(File $file)
 {
     $object = new ActivityObject();
     if (Event::handle('StartActivityObjectFromFile', array($file, &$object))) {
         $object->type = self::mimeTypeToObjectType($file->mimetype);
         $object->id = TagURI::mint(sprintf("file:%d", $file->id));
         $object->link = common_local_url('attachment', array('attachment' => $file->id));
         if ($file->title) {
             $object->title = $file->title;
         }
         if ($file->date) {
             $object->date = $file->date;
         }
         try {
             $thumbnail = $file->getThumbnail();
             $object->thumbnail = $thumbnail;
         } catch (UseFileAsThumbnailException $e) {
             $object->thumbnail = null;
         } catch (UnsupportedMediaException $e) {
             $object->thumbnail = null;
         }
         switch (self::canonicalType($object->type)) {
             case 'image':
                 $object->largerImage = $file->getUrl();
                 break;
             case 'video':
             case 'audio':
                 $object->stream = $file->getUrl();
                 break;
         }
         Event::handle('EndActivityObjectFromFile', array($file, &$object));
     }
     return $object;
 }
    echo $category->title;
    ?>
</div>
				<ul class="media-list">
					<?php 
    foreach ($items[$category->id] as $item) {
        ?>
						<?php 
        if ($item->href == '') {
            $files = File::getFilesOfObject($item);
            $file = array_pop($files);
            // If there is no file attached, deliver a dummy object. That's better than completely breaking the rendering.
            if (!is_object($file)) {
                $file = new File();
            }
            $item->href = $file->getUrl();
        }
        ?>
						<li id="library-widget-item_<?php 
        echo $item->id;
        ?>
"><a href="<?php 
        echo $item->href;
        ?>
" title="<?php 
        echo $item->description;
        ?>
" target="_blank"><?php 
        echo $item->title;
        ?>
</a></li>
Example #8
0
 /**
  * Get the link to the file.
  * Overridden by RevDel_ArchivedFileItem.
  */
 protected function getLink()
 {
     $date = $this->list->getLang()->timeanddate($this->file->getTimestamp(), true);
     if ($this->isDeleted()) {
         # Hidden files...
         if (!$this->canViewContent()) {
             $link = $date;
         } else {
             $revdelete = SpecialPage::getTitleFor('Revisiondelete');
             $link = Linker::link($revdelete, $date, array(), array('target' => $this->list->title->getPrefixedText(), 'file' => $this->file->getArchiveName(), 'token' => $this->list->getUser()->editToken($this->file->getArchiveName())));
         }
         return '<span class="history-deleted">' . $link . '</span>';
     } else {
         # Regular files...
         return Xml::element('a', array('href' => $this->file->getUrl()), $date);
     }
 }
 /**
  * Get a ThumbnailImage that respresents an image that will be scaled
  * client side
  *
  * @param File $image File associated with this thumbnail
  * @param array $scalerParams Array with scaler params
  * @return ThumbnailImage
  *
  * @todo FIXME: No rotation support
  */
 protected function getClientScalingThumbnailImage($image, $scalerParams)
 {
     $params = ['width' => $scalerParams['clientWidth'], 'height' => $scalerParams['clientHeight']];
     return new ThumbnailImage($image, $image->getUrl(), null, $params);
 }
Example #10
0
 /**
  * Handles a single upload by given CUploadedFile and returns an array
  * of informations.
  *
  * The 'error' attribute of the array, indicates there was an error.
  *
  * Informations on error:
  *       - error: true
  *       - errorMessage: some message
  *       - name: name of the file
  *       - size: file size
  *
  * Informations on success:
  *      - error: false
  *      - name: name of the uploaded file
  *      - size: file size
  *      - guid: of the file
  *      - url: url to the file
  *      - thumbnailUrl: url to the thumbnail if exists
  *
  * @param type $cFile
  * @return Array Informations about the uploaded file
  */
 protected function handleFileUpload($cFile, $object = null, $publicAccess = false)
 {
     $output = array();
     $file = new File();
     $file->setUploadedFile($cFile);
     $file->public_access = $publicAccess;
     if ($object != null) {
         $file->object_id = $object->getPrimaryKey();
         $file->object_model = get_class($object);
     }
     if ($file->validate() && $file->save()) {
         $output['error'] = false;
         $output['guid'] = $file->guid;
         $output['name'] = $file->file_name;
         $output['title'] = $file->title;
         $output['size'] = $file->size;
         $output['mimeIcon'] = HHtml::getMimeIconClassByExtension($file->getExtension());
         $output['mimeBaseType'] = $file->getMimeBaseType();
         $output['mimeSubType'] = $file->getMimeSubType();
         $output['url'] = $file->getUrl("", false);
         $output['thumbnailUrl'] = $file->getPreviewImageUrl(200, 200);
     } else {
         $output['error'] = true;
         $output['errors'] = $file->getErrors();
     }
     $output['name'] = $file->file_name;
     $output['size'] = $file->size;
     $output['deleteUrl'] = "";
     $output['deleteType'] = "";
     $output['thumbnailUrl'] = "";
     return $output;
 }
Example #11
0
 public function testGetUrl()
 {
     $this->context->expects($this->once())->method('getBaseUrl')->will($this->returnValue('http://example.com/'));
     $this->context->expects($this->once())->method('getPath')->will($this->returnValue('static'));
     $this->assertEquals('http://example.com/static/Magento_Module/dir/file.css', $this->object->getUrl());
 }
 public function onThumbnailImageHTML($options, $linkAttribs, $imageAttribs, File $file, &$html)
 {
     $this->wf->profileIn(__METHOD__);
     if (empty($options['custom-url-link']) && empty($options['custom-title-link']) && !empty($options['desc-link']) && self::$isOasis || self::$isWikiaMobile) {
         $fullImageUrl = false;
         $link = null;
         if (is_array($linkAttribs)) {
             if (!empty($file)) {
                 $title = $file->getTitle();
                 if ($title instanceof Title) {
                     $linkAttribs['data-image-name'] = $title->getText();
                 }
                 $linkAttribs['href'] = $this->wf->ReplaceImageServer($file->getUrl(), $file->getTimestamp());
                 $fullImageUrl = $linkAttribs['href'];
             }
             if (!empty($options['custom-url-link'])) {
                 $link = $options['custom-url-link'];
             } elseif (!empty($options['custom-title-link']) && $options['custom-title-link'] instanceof Title) {
                 $title = $options['custom-title-link'];
                 $linkAttribs['title'] = $title->getFullText();
                 $link = $title->getLinkUrl();
             } elseif (!empty($options['file-link']) && empty($options['desc-link'])) {
                 $linkAttribs['href'] = $this->wf->ReplaceImageServer($file->getUrl(), $file->getTimestamp());
             }
             //override any previous value if title is passed as an option
             if (!empty($options['title'])) {
                 $linkAttribs['title'] = $options['title'];
             }
         }
         //remove the empty alt attribute which we print pretty everywhere (meh)
         if (empty($imageAttribs['alt'])) {
             unset($imageAttribs['alt']);
         }
         $contents = Xml::element('img', $imageAttribs);
         if (self::$isWikiaMobile) {
             $imageParams = array();
             if (!empty($link)) {
                 $linkAttribs['href'] = $link;
             }
             if (empty($linkAttribs['class'])) {
                 $linkAttribs['class'] = 'image';
             }
             if (!empty($linkAttribs['data-image-name'])) {
                 $imageParams['name'] = $linkAttribs['data-image-name'];
             }
             if (!empty($fullImageUrl)) {
                 $imageParams['full'] = $fullImageUrl;
             } else {
                 $imageParams['full'] = $imageAttribs['src'];
             }
             if (!empty($options['caption'])) {
                 $imageParams['capt'] = true;
             }
             //images set to be less than 64px are probably
             //being used as icons in templates
             //do not resize them
             if ((!empty($imageAttribs['width']) && $imageAttribs['width'] > 64 || empty($imageAttribs['width'])) && $file instanceof File) {
                 $size = WikiaMobileMediaService::calculateMediaSize($file->getWidth(), $file->getHeight());
                 $thumb = $file->transform($size);
                 $imageAttribs['src'] = wfReplaceImageServer($thumb->getUrl(), $file->getTimestamp());
                 $imageAttribs['width'] = $size['width'];
                 $imageAttribs['height'] = $size['height'];
             }
             /**
              *WikiaMobile: lazy loading images in a SEO-friendly manner
              *@author Federico "Lox" Lucignano <federico@wikia-inc.com
              */
             $html = $this->app->sendRequest('WikiaMobileMediaService', 'renderImageTag', array('attributes' => $imageAttribs, 'parameters' => array($imageParams), 'anchorAttributes' => $linkAttribs, 'linked' => !empty($link), 'noscript' => $contents), true)->toString();
         } else {
             $html = $linkAttribs ? Xml::tags('a', $linkAttribs, $contents) : $contents;
         }
     }
     $this->wf->profileOut(__METHOD__);
     return true;
 }
Example #13
0
 /**
  * Create a direct link to a given uploaded file.
  * This will make a broken link if $file is false.
  *
  * @since 1.16.3
  * @param Title $title
  * @param File|bool $file File object or false
  * @param string $html Pre-sanitized HTML
  * @return string HTML
  *
  * @todo Handle invalid or missing images better.
  */
 public static function makeMediaLinkFile(Title $title, $file, $html = '')
 {
     if ($file && $file->exists()) {
         $url = $file->getUrl();
         $class = 'internal';
     } else {
         $url = self::getUploadUrl($title);
         $class = 'new';
     }
     $alt = $title->getText();
     if ($html == '') {
         $html = $alt;
     }
     $ret = '';
     $attribs = ['href' => $url, 'class' => $class, 'title' => $alt];
     if (!Hooks::run('LinkerMakeMediaLinkFile', [$title, $file, &$html, &$attribs, &$ret])) {
         wfDebug("Hook LinkerMakeMediaLinkFile changed the output of link " . "with url {$url} and text {$html} to {$ret}\n", true);
         return $ret;
     }
     return Html::rawElement('a', $attribs, $html);
 }
Example #14
0
 public function scan($id)
 {
     $scanner = new ScanAssets();
     $file_id = (int) $id;
     $file = new File();
     $file->findFileById($file_id);
     $success = false;
     $icon = File::getIconFromMime($file->getMime());
     if ($scanner->scanFile($file->getId())) {
         $success = true;
     }
     if ($icon === false) {
         $icon = $file->getUrl();
     }
     if ($success) {
         // we need to reload the file because scanner might have updated fields
         // and our object is out of date
         $file->findFileById($file_id);
         // move file to S3
         try {
             File::s3Upload($file->getRealPath(), APP_ATTACHMENT_PATH . $file->getFileName(), true, $file->getTitle());
             $file->setUrl(APP_ATTACHMENT_URL . $file->getFileName());
             $file->save();
             // delete the physical file now it is in S3
             unlink($file->getRealPath());
         } catch (Exception $e) {
             $success = false;
             $error = 'There was a problem uploading your file';
             error_log(__FILE__ . ": Error uploading images to S3:\n{$e}");
         }
     }
     return $this->setOutput(array('success' => $success, 'error' => isset($error) ? $error : '', 'fileid' => $file->getId(), 'url' => $file->getUrl(), 'icon' => $icon));
 }
Example #15
0
 /**
  * @param $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 = array('action' => 'delete');
             if (!$iscur) {
                 $q['oldimage'] = $img;
             }
             $row .= Linker::linkKnown($this->title, $this->msg($iscur ? 'filehist-deleteall' : 'filehist-deleteone')->escaped(), array(), $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 = array('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(), array(), array('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), array(), array('target' => $this->title->getPrefixedText(), 'file' => $img, 'token' => $user->getEditToken($img)));
         } else {
             $url = $lang->userTimeAndDate($timestamp, $user);
         }
         $row .= '<span class="history-deleted">' . $url . '</span>';
     } else {
         $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl($img);
         $row .= Xml::element('a', array('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')->plain();
     $row .= '<span style="white-space: nowrap;">';
     $row .= $this->msg('parentheses')->rawParams(Linker::formatSize($file->getSize()))->plain();
     $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 .= $this->msg('word-separator')->plain();
             $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;
     wfRunHooks('ImagePageFileHistoryLine', array($this, $file, &$row, &$rowClass));
     $classAttr = $rowClass ? " class='{$rowClass}'" : '';
     return "<tr{$classAttr}>{$row}</tr>\n";
 }
 /**
  * @param ImageOptions|null $options
  *
  * @return string
  *
  * @api
  */
 public function getUrl(ImageOptions $options = null)
 {
     $query = $options !== null ? '?' . $options->getQueryString() : '';
     return parent::getUrl() . $query;
 }
Example #17
0
 public function add($name)
 {
     $this->view = null;
     try {
         $user = User::find(Session::uid());
         if (!$user->getId() || !$user->getIs_admin()) {
             throw new Exception('Action not allowed.');
         }
         if (!preg_match('/^\\d*[-a-zA-Z][-a-zA-Z0-9]*$/', $name)) {
             throw new Exception('The name of the project can only contain alphanumeric characters plus dashes and must have 1 alpha character at least');
         }
         try {
             $project = Project::find($name);
         } catch (Exception $e) {
         }
         if (is_object($project) && $project->getProjectId($name)) {
             throw new Exception('Project with the same name already exists!');
         }
         $file = new File();
         $logo = '';
         if (!empty($_POST['logo'])) {
             $file->findFileById($_POST['logo']);
             $logo = basename($file->getUrl());
         }
         $project = new Project();
         $project->setName($name);
         $project->setDescription($_POST['description']);
         $project->setWebsite($_POST['website']);
         $project->setContactInfo($user->getUsername());
         $project->setOwnerId($user->getId());
         $project->setActive(true);
         $project->setInternal(true);
         $project->setRequireSandbox(true);
         $project->setLogo($logo);
         $project->setRepo_type('git');
         $project->setRepository($_POST['github_repo_url']);
         $project->setGithubId($_POST['github_client_id']);
         $project->setGithubSecret($_POST['github_client_secret']);
         $project->save();
         if ($file->getId()) {
             $file->setProjectId($project->getProjectId());
             $file->save();
         }
         $journal_message = '@' . $user->getNickname() . ' added project *' . $name . '*';
         Utils::systemNotification($journal_message);
         echo json_encode(array('success' => true, 'message' => $journal_message));
     } catch (Exception $e) {
         $error = $e->getMessage();
         echo json_encode(array('success' => false, 'message' => $error));
     }
 }