public function execute() { $this->params = $this->extractRequestParams(); // Extract the file and archiveName from the request parameters $this->validateParameters(); // Check whether we're allowed to revert this file $this->checkPermissions($this->getUser()); $sourceUrl = $this->file->getArchiveVirtualUrl($this->archiveName); $status = $this->file->upload($sourceUrl, $this->params['comment'], $this->params['comment'], 0, false, false, $this->getUser()); if ($status->isGood()) { $result = array('result' => 'Success'); } else { $result = array('result' => 'Failure', 'errors' => $this->getResult()->convertStatusToArray($status)); } $this->getResult()->addValue(null, $this->getModuleName(), $result); }
/** * Handle image upload * * Returns array with uploaded files details or error details */ public function uploadImage($uploadFieldName = self::DEFAULT_FILE_FIELD_NAME, $destFileName = null, $forceOverwrite = false) { global $IP, $wgRequest, $wgUser; wfProfileIn(__METHOD__); $ret = false; // check whether upload is enabled (RT #53714) if (!WikiaPhotoGalleryHelper::isUploadAllowed()) { $ret = array('error' => true, 'message' => wfMsg('uploaddisabled')); wfProfileOut(__METHOD__); return $ret; } $imageName = stripslashes(!empty($destFileName) ? $destFileName : $wgRequest->getFileName($uploadFieldName)); // validate name and content of uploaded photo $nameValidation = $this->checkImageName($imageName, $uploadFieldName); if ($nameValidation == UploadBase::SUCCESS) { // get path to uploaded image $imagePath = $wgRequest->getFileTempName($uploadFieldName); // check if image with this name is already uploaded if ($this->imageExists($imageName) && !$forceOverwrite) { // upload as temporary file $this->log(__METHOD__, "image '{$imageName}' already exists!"); $tempName = $this->tempFileName($wgUser); $title = Title::makeTitle(NS_FILE, $tempName); $localRepo = RepoGroup::singleton()->getLocalRepo(); $file = new FakeLocalFile($title, $localRepo); $file->upload($wgRequest->getFileTempName($uploadFieldName), '', ''); // store uploaded image in GarbageCollector (image will be removed if not used) $tempId = $this->tempFileStoreInfo($tempName); // generate thumbnail (to fit 200x200 box) of temporary file $width = min(WikiaPhotoGalleryHelper::thumbnailMaxWidth, $file->width); $height = min(WikiaPhotoGalleryHelper::thumbnailMaxHeight, $file->height); $thumbnail = $file->transform(array('height' => $height, 'width' => $width)); // split uploaded file name into name + extension (foo-bar.png => foo-bar + png) list($fileName, $extensionsName) = UploadBase::splitExtensions($imageName); $extensionName = !empty($extensionsName) ? end($extensionsName) : ''; $this->log(__METHOD__, 'upload successful'); $ret = array('conflict' => true, 'name' => $imageName, 'nameParts' => array($fileName, $extensionName), 'tempId' => $tempId, 'size' => array('height' => $file->height, 'width' => $file->width), 'thumbnail' => array('height' => $thumbnail->height, 'url' => $thumbnail->url, 'width' => $thumbnail->width)); } else { // use regular MW upload $this->log(__METHOD__, "image '{$imageName}' is new one - uploading as MW file"); $this->log(__METHOD__, "uploading '{$imagePath}' as File:{$imageName}"); // create title and file objects for MW image to create $imageTitle = Title::newFromText($imageName, NS_FILE); $imageFile = new LocalFile($imageTitle, RepoGroup::singleton()->getLocalRepo()); // perform upload $result = $imageFile->upload($imagePath, '', ''); $this->log(__METHOD__, !empty($result->ok) ? 'upload successful' : 'upload failed'); $ret = array('success' => !empty($result->ok), 'name' => $imageName, 'size' => array('height' => !empty($result->ok) ? $imageFile->getHeight() : 0, 'width' => !empty($result->ok) ? $imageFile->getWidth() : 0)); } } else { $reason = $nameValidation; $this->log(__METHOD__, "upload failed - file name is not valid (error #{$reason})"); $ret = array('error' => true, 'reason' => $reason, 'message' => $this->translateError($reason)); } wfProfileOut(__METHOD__); return $ret; }
/** * Upload given file into MW */ public function uploadIntoMW($imagePath, $imageName) { wfProfileIn(__METHOD__); $this->log(__METHOD__, "uploading '{$imagePath}' as File:{$imageName}"); // create title and file objects for MW image to create $imageTitle = Title::newFromText($imageName, NS_FILE); $imageFile = new LocalFile($imageTitle, RepoGroup::singleton()->getLocalRepo()); // perform upload $result = $imageFile->upload($imagePath, '', ''); wfProfileOut(__METHOD__); return !empty($result->ok); }
private function executeImage() { if (empty($this->mParams['tempName'])) { $this->dieUsageMsg('The tempName parameter must be set'); } $tempFile = new FakeLocalFile(Title::newFromText($this->mParams['tempName'], 6), RepoGroup::singleton()->getLocalRepo()); $duplicate = $this->getFileDuplicate($tempFile->getLocalRefPath()); if ($duplicate) { return array('title' => $duplicate->getTitle()->getText()); } else { $title = $this->getUniqueTitle(wfStripIllegalFilenameChars($this->mParams['title'])); if (isset($this->mParams['license'])) { $pageText = SpecialUpload::getInitialPageText('', $this->mParams['license']); } $file = new LocalFile($title, RepoGroup::singleton()->getLocalRepo()); $file->upload($tempFile->getPath(), '', $pageText ? $pageText : ''); return array('title' => $file->getTitle()->getText()); } }
public function saveSettings($settings, $cityId = null) { global $wgCityId, $wgUser; $cityId = empty($cityId) ? $wgCityId : $cityId; // Verify wordmark length ( CONN-116 ) if (!empty($settings['wordmark-text'])) { $settings['wordmark-text'] = trim($settings['wordmark-text']); } if (empty($settings['wordmark-text'])) { // Do not save wordmark if its empty. unset($settings['wordmark-text']); } else { if (mb_strlen($settings['wordmark-text']) > 50) { $settings['wordmark-text'] = mb_substr($settings['wordmark-text'], 0, 50); } } if (isset($settings['favicon-image-name']) && strpos($settings['favicon-image-name'], 'Temp_file_') === 0) { $temp_file = new LocalFile(Title::newFromText($settings['favicon-image-name'], 6), RepoGroup::singleton()->getLocalRepo()); $file = new LocalFile(Title::newFromText(self::FaviconImageName, 6), RepoGroup::singleton()->getLocalRepo()); $file->upload($temp_file->getPath(), '', ''); $temp_file->delete(''); Wikia::invalidateFavicon(); $settings['favicon-image-url'] = $file->getURL(); $settings['favicon-image-name'] = $file->getName(); $file->repo->forceMaster(); $history = $file->getHistory(1); if (count($history) == 1) { $oldFaviconFile = array('url' => $history[0]->getURL(), 'name' => $history[0]->getArchiveName()); } } if (isset($settings['wordmark-image-name']) && strpos($settings['wordmark-image-name'], 'Temp_file_') === 0) { $temp_file = new LocalFile(Title::newFromText($settings['wordmark-image-name'], 6), RepoGroup::singleton()->getLocalRepo()); $file = new LocalFile(Title::newFromText(self::WordmarkImageName, 6), RepoGroup::singleton()->getLocalRepo()); $file->upload($temp_file->getPath(), '', ''); $temp_file->delete(''); $settings['wordmark-image-url'] = $file->getURL(); $settings['wordmark-image-name'] = $file->getName(); $file->repo->forceMaster(); $history = $file->getHistory(1); if (count($history) == 1) { $oldFile = array('url' => $history[0]->getURL(), 'name' => $history[0]->getArchiveName()); } } if (isset($settings['background-image-name']) && strpos($settings['background-image-name'], 'Temp_file_') === 0) { $temp_file = new LocalFile(Title::newFromText($settings['background-image-name'], 6), RepoGroup::singleton()->getLocalRepo()); $file = new LocalFile(Title::newFromText(self::BackgroundImageName, 6), RepoGroup::singleton()->getLocalRepo()); $file->upload($temp_file->getPath(), '', ''); $temp_file->delete(''); $settings['background-image'] = $file->getURL(); $settings['background-image-name'] = $file->getName(); $settings['background-image-width'] = $file->getWidth(); $settings['background-image-height'] = $file->getHeight(); $imageServing = new ImageServing(null, 120, array("w" => "120", "h" => "65")); $settings['user-background-image'] = $file->getURL(); $settings['user-background-image-thumb'] = wfReplaceImageServer($file->getThumbUrl($imageServing->getCut($file->getWidth(), $file->getHeight(), "origin") . "-" . $file->getName())); $file->repo->forceMaster(); $history = $file->getHistory(1); if (count($history) == 1) { $oldBackgroundFile = array('url' => $history[0]->getURL(), 'name' => $history[0]->getArchiveName()); } } $reason = wfMsg('themedesigner-reason', $wgUser->getName()); // update history if (!empty($GLOBALS[self::WikiFactoryHistory])) { $history = $GLOBALS[self::WikiFactoryHistory]; $lastItem = end($history); $revisionId = intval($lastItem['revision']) + 1; } else { $history = array(); $revisionId = 1; } // #140758 - Jakub // validation // default color values foreach (ThemeDesignerHelper::getColorVars() as $sColorVar => $sDefaultValue) { if (!isset($settings[$sColorVar]) || !ThemeDesignerHelper::isValidColor($settings[$sColorVar])) { $settings[$sColorVar] = $sDefaultValue; } } // update WF variable with current theme settings WikiFactory::setVarByName(self::WikiFactorySettings, $cityId, $settings, $reason); // add entry $history[] = array('settings' => $settings, 'author' => $wgUser->getName(), 'timestamp' => wfTimestampNow(), 'revision' => $revisionId); // limit history size to last 10 changes $history = array_slice($history, -self::HistoryItemsLimit); if (count($history) > 1) { for ($i = 0; $i < count($history) - 1; $i++) { if (isset($oldFaviconFile) && isset($history[$i]['settings']['favicon-image-name'])) { if ($history[$i]['settings']['favicon-image-name'] == self::FaviconImageName) { $history[$i]['settings']['favicon-image-name'] = $oldFaviconFile['name']; $history[$i]['settings']['favicon-image-url'] = $oldFaviconFile['url']; } } if (isset($oldFile) && isset($history[$i]['settings']['wordmark-image-name'])) { if ($history[$i]['settings']['wordmark-image-name'] == self::WordmarkImageName) { $history[$i]['settings']['wordmark-image-name'] = $oldFile['name']; $history[$i]['settings']['wordmark-image-url'] = $oldFile['url']; } } if (isset($oldBackgroundFile) && isset($history[$i]['settings']['background-image-name'])) { if ($history[$i]['settings']['background-image-name'] == self::BackgroundImageName) { $history[$i]['settings']['background-image-name'] = $oldBackgroundFile['name']; } } } } WikiFactory::setVarByName(self::WikiFactoryHistory, $cityId, $history, $reason); }
public function processUploadedFile($srcFileName) { if ($this->isValid()) { // do not upload invalid filenames $this->fileChanged = true; $dst_file_title = Title::newFromText($this->getPathname(), NS_FILE); $temp_file = RepoGroup::singleton()->getLocalRepo()->getUploadStash()->getFile($srcFileName); $file = new LocalFile($dst_file_title, RepoGroup::singleton()->getLocalRepo()); $file->upload($temp_file->getPath(), '', ''); $temp_file->remove(); } return $this; }
function execute($par) { global $wgOut, $wgUser, $wgRequest; global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview; if ($wgUser->isBlocked()) { $wgOut->blockedPage(); return; } if ($wgUser->getID() == 0) { $wgOut->setRobotpolicy('noindex,nofollow'); $wgOut->showErrorPage('nosuchspecialpage', 'nospecialpagetext'); return; } if (!in_array('staff', $wgUser->getGroups())) { $wgOut->setRobotpolicy('noindex,nofollow'); $wgOut->showErrorPage('nosuchspecialpage', 'nospecialpagetext'); return; } $this->errorFile = ""; $this->errorTitle = ""; if ($wgRequest->getVal('delete')) { $wgOut->setArticleBodyOnly(true); $hpid = str_replace('delete_', '', $wgRequest->getVal('delete')); $html = self::deleteHPImage($hpid); $wgOut->addHTML($html); return; } $this->postSuccessful = true; if ($wgRequest->wasPosted()) { if ($wgRequest->getVal("updateActive")) { $dbw = wfGetDB(DB_MASTER); //first clear them all $dbw->update(WikihowHomepageAdmin::HP_TABLE, array('hp_active' => 0, 'hp_order' => 0), '*', __METHOD__); $images = $wgRequest->getArray("hp_images"); $count = 1; foreach ($images as $image) { if (!$image) { continue; } $dbw->update(WikihowHomepageAdmin::HP_TABLE, array('hp_active' => 1, 'hp_order' => $count), array('hp_id' => $image)); $count++; } } else { $title = WikiPhoto::getArticleTitleNoCheck($wgRequest->getVal('articleName')); if (!$title->exists()) { $this->postSuccessful = false; $this->errorTitle = "* That article does not exist."; } if ($this->postSuccessful) { //keep going $imageTitle = Title::newFromText($wgRequest->getVal('wpDestFile'), NS_IMAGE); $file = new LocalFile($imageTitle, RepoGroup::singleton()->getLocalRepo()); $file->upload($wgRequest->getFileTempName('wpUploadFile'), '', ''); $filesize = $file->getSize(); if ($filesize > 0) { $dbw = wfGetDB(DB_MASTER); $dbw->insert(WikihowHomepageAdmin::HP_TABLE, array('hp_page' => $title->getArticleID(), 'hp_image' => $imageTitle->getArticleID())); $article = new Article($imageTitle); $limit = array(); $limit['move'] = "sysop"; $limit['edit'] = "sysop"; $protectResult = $article->updateRestrictions($limit, "Used on homepage"); } else { $this->postSuccessful = false; $this->errorFile = "* We encountered an error uploading that file."; } } } } $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck; $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview; $adc = wfBoolToStr($useAjaxDestCheck); $alp = wfBoolToStr($useAjaxLicensePreview); $wgOut->setPageTitle('WikiHow Homepage Admin'); $wgOut->addScript("<script type=\"text/javascript\">\nwgAjaxUploadDestCheck = {$adc};\nwgAjaxLicensePreview = {$alp};\n</script>"); $wgOut->addScript(HtmlSnips::makeUrlTags('js', array('jquery-ui-1.8.custom.min.js'), 'extensions/wikihow/common/ui/js', false)); $wgOut->addScript(HtmlSnips::makeUrlTags('js', array('wikihowhomepageadmin.js'), 'extensions/wikihow/homepage', false)); $wgOut->addScript(HtmlSnips::makeUrlTags('css', array('wikihowhomepageadmin.css'), 'extensions/wikihow/homepage', false)); $wgOut->addScript(HtmlSnips::makeUrlTags('js', array('upload.js'), 'skins/common', false)); $this->displayHomepageData(); $this->displayForm(); }
public function saveHeroData() { wfProfileIn(__METHOD__); $success = false; $this->getResponse()->setFormat('json'); $wikiData = $this->request->getVal('wikiData', []); $wikiDataModel = new WikiDataModel(Title::newMainPage()->getText()); $wikiDataModel->setFromAttributes($wikiData); $imageChanged = !empty($wikiData['imagechanged']); $imageName = !empty($wikiData['imagename']) ? $wikiData['imagename'] : null; if ($imageChanged && $imageName) { wfProfileIn(__METHOD__ . '::uploadStart'); $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash(); $temp_file = $stash->getFile($imageName); $file = new LocalFile(static::HERO_IMAGE_FILENAME, RepoGroup::singleton()->getLocalRepo()); $status = $file->upload($temp_file->getPath(), '', ''); wfProfileIn(__METHOD__ . '::uploadEnd'); if ($status->isOK()) { $wikiDataModel->setImageName($file->getTitle()->getDBKey()); $wikiDataModel->setImagePath($file->getFullUrl()); $success = $this->setWikiData($wikiDataModel); //clean up stash $stash->removeFile($imageName); } } else { $wikiDataModel->setImageNameFromProps(); $success = $this->setWikiData($wikiDataModel); } if (!$success) { $wikiDataModel->getFromProps(); } $this->getResponse()->setVal('success', $success); $this->getResponse()->setVal('wikiData', $wikiDataModel); wfProfileOut(__METHOD__); }
/** * Add a new image file into the mediawiki infrastructure so that it can * be accessed as [[Image:filename.jpg]] */ private static function addMediawikiImage($articleID, &$image, $userIsScreenshotter) { // check if we've already uploaded this image $dupTitle = DupImage::checkDupImage($image['filename']); // if we've already uploaded this image, just return that filename if ($dupTitle) { $image['mediawikiName'] = $dupTitle; return true; } // find name for image; change filename to Filename 1.jpg if // Filename.jpg already existed $regexp = '/[^' . Title::legalChars() . ']+/'; $first = preg_replace($regexp, '', $image['first']); $ext = $image['ext']; $newName = $first . '.' . $ext; $i = 1; do { $title = Title::newFromText($newName, NS_IMAGE); if ($title && !$title->exists()) { break; } $newName = $first . ' Version ' . ++$i . '.' . $ext; } while ($i <= 1000); // insert image into wikihow mediawiki repos if (!$userIsScreenshotter) { $comment = '{{' . self::PHOTO_LICENSE . '}}'; } else { $comment = '{{' . self::SCREENSHOT_LICENSE . '}}'; } // next 6 lines taken and modified from // extensions/wikihow/eiu/Easyimageupload.body.php $title = Title::makeTitleSafe(NS_IMAGE, $newName); if (!$title) { return false; } $file = new LocalFile($title, RepoGroup::singleton()->getLocalRepo()); if (!$file) { return false; } $ret = $file->upload($image['filename'], $comment, $comment); if (!$ret->ok) { return false; } // instruct later processing about which mediawiki name was used $image['mediawikiName'] = $newName; // Add our uploaded image to the dup table so it's no uploaded again DupImage::addDupImage($image['filename'], $image['mediawikiName']); // Keep a log of where images were uploaded in wikiphoto_image_names table $dbw = self::getDB('write'); $imgname = $articleID . '/' . $image['name']; $sql = 'INSERT INTO wikiphoto_image_names SET filename=' . $dbw->addQuotes($imgname) . ', wikiname=' . $dbw->addQuotes($image['mediawikiName']); $dbw->query($sql, __METHOD__); return true; }
/** * Add a new image file into the mediawiki infrastructure so that it can * be accessed as [[Image:filename.jpg]] */ private static function addMediawikiImage($articleID, &$image) { // Download the preview image and set the filename to the temporarary location $err = self::downloadImagePreview($image); if ($err) { return $err; } // check if we've already uploaded this image $dupTitle = DupImage::checkDupImage($image['filename']); // if we've already uploaded this image, just return that filename if ($dupTitle) { //$image['dupTitle'] = true; $image['mediawikiName'] = $dupTitle; return ''; } // find name for image; change filename to Filename 1.jpg if // Filename.jpg already existed $regexp = '/[^' . Title::legalChars() . ']+/'; $first = preg_replace($regexp, '', $image['first']); $ext = $image['ext']; $newName = $first . '-preview.' . $ext; $i = 1; do { $title = Title::newFromText($newName, NS_IMAGE); if ($title && !$title->exists()) { break; } $newName = $first . '-preview Version ' . ++$i . '.' . $ext; } while ($i <= 1000); // insert image into wikihow mediawiki repos $comment = '{{' . self::PHOTO_LICENSE . '}}'; // next 6 lines taken and modified from // extensions/wikihow/eiu/Easyimageupload.body.php $title = Title::makeTitleSafe(NS_IMAGE, $newName); if (!$title) { return "Couln't Make a title"; } $file = new LocalFile($title, RepoGroup::singleton()->getLocalRepo()); if (!$file) { return "Couldn't make a local file"; } $ret = $file->upload($image['filename'], $comment, $comment); if (!$ret->ok) { return "Couldn't upload file " . $image['filename']; } // instruct later processing about which mediawiki name was used $image['mediawikiName'] = $newName; // Add our uploaded image to the dup table so it's no uploaded again DupImage::addDupImage($image['filename'], $image['mediawikiName']); return ''; }
protected function insertImage($name, $mwname, $result) { global $wgRequest, $wgImageMagickConvertCommand, $wgServer; if (!$result) { $result = array(); } elseif ($result['error']) { return $result; } $fromPage = $wgRequest->getVal('viapage'); if (!empty($mwname) && !empty($name)) { $name = trim(urldecode($name)); $dateTime = new DateTime(); $mwDate = wfTimestamp(TS_MW); // Mediawiki timestamp: 'YmdHis' list($first, $ext) = self::splitFilenameExt($name); $ext = strtolower($ext); $validExts = array('GIF', 'JPG', 'JPEG', 'PNG'); if (!in_array(strtoupper($ext), $validExts)) { $result['error'] = 'Error: Invalid file extension ' . strtoupper($ext) . '. Valid extensions are:'; foreach ($validExts as $validExt) { $result['error'] .= ' ' . strtoupper($validExt); } $result['error'] .= '.'; return $result; } $saveName = false; $titleExists = false; $suffixNum = 1; while (!$saveName || $titleExists) { $saveName = 'User Completed Image ' . $fromPage . ' ' . $dateTime->format('Y.m.d H.i.s') . ' ' . $suffixNum . '.' . $ext; $title = Title::makeTitleSafe(NS_IMAGE, $saveName); $newFile = true; $titleExists = $title->exists(); $suffixNum++; } $temp_file = new TempLocalImageFile(Title::newFromText($mwname, NS_IMAGE), RepoGroup::singleton()->getLocalRepo()); if (!$temp_file || !$temp_file->exists()) { $result['error'] = 'Error: A server error has occurred. Please try again.'; return $result; } // Image orientation is a bit wonky on some mobile devices; use ImageMagick's auto-orient to try fixing it. $tempFilePath = $temp_file->getPath(); $cmd = $wgImageMagickConvertCommand . ' ' . $tempFilePath . ' -auto-orient ' . $tempFilePath; exec($cmd); // Use a CC license $comment = '{{Self}}'; $file = new LocalFile($title, RepoGroup::singleton()->getLocalRepo()); $file->upload($tempFilePath, $comment, $comment); if (!$file || !$file->exists()) { $result['error'] = 'Error: A server error has occurred. Please try again.'; return $result; } $temp_file->delete(''); $fileTitle = $file->getTitle(); $fileURL = $file->url; $thumbURL = ''; $thumb = $file->getThumbnail(200, -1, true, true); if (!$thumb) { $result['error'] = 'Error: A server error has occurred. Please try again.'; $file->delete(''); return $result; } $thumbURL = $thumb->url; $result['titleText'] = $fileTitle->getText(); $result['titleDBkey'] = substr($fileTitle->getDBkey(), 21); // Only keep important info $result['titlePreText'] = '/' . $fileTitle->getPrefixedText(); $result['titleArtID'] = $fileTitle->getArticleID(); $result['timestamp'] = $mwDate; $result['fromPage'] = $wgRequest->getVal('viapage'); $result['thumbURL'] = $thumbURL; $result['fileURL'] = $wgServer . $fileURL; } return $result; }
/** * Insert an image upload into the mediawiki database tables. If the * image insert was successful, a page showing the wiki text for their * image is shown. Otherwise, if the image file name already exists in * the database, a conflict page is returned to the user. * * @param $type string with either 'overwrite' or blank -- specifies * whether to force-overwrite an existing image * @param $name filename chosen by user for uploaded image * @param $mwname filename of the file in mediawiki DB * @param $fromIIA true iff source of call is Special:IntroImageAdder * @param $image_comment a comment attached to the image upload (only * used if $fromIIA == true) * @return outputs either a wikitext results page (if image filename * didn't exist or force overwrite was selected) or a conflict page. * Returns an error string or empty string if no error. */ private function insertImage($type, $name, $mwname, $fromIIA = false, $image_comment = '') { global $wgRequest, $wgUser, $wgOut, $wgFileExtensions; if (!$fromIIA) { $license = $wgRequest->getVal('wpLicense', ''); if (!empty($license)) { $attrib = $wgRequest->getVal('attribution'); $comment = '{{' . $license . (!empty($attrib) ? '|' . $attrib : '') . '}}'; if ($license != '') { $wgUser->setOption('image_license', $license); $wgUser->saveSettings(); } } else { $comment = $wgRequest->getVal('ImageAttribution', ''); } } else { $comment = $image_comment; } if (wfReadOnly()) { return wfMsg('eiu-readonly'); } if (!empty($mwname) && !empty($name)) { $name = urldecode($name); $name = preg_replace('/[^' . Title::legalChars() . ']|[:\\/\\\\]|\\?/', '-', $name); $name = preg_replace('@&@', '&', $name); $name = trim($name); // did they give no extension at all when they changed the name? list($first, $ext) = self::splitFilenameExt($name); $ext = strtolower($ext); $title = Title::makeTitleSafe(NS_IMAGE, $name); if (is_null($title) || !in_array($ext, $wgFileExtensions)) { return wfMsg('eiu-filetype-incorrect'); } $newFile = true; $titleExists = $title->exists(); if (!$titleExists || $fromIIA) { // // DB entry for file doesn't exist. User renamed their // upload or it never existed. // if ($titleExists) { $suggestedName = self::generateNewFilename($name); $title = Title::makeTitleSafe(NS_IMAGE, $suggestedName); } // is the target protected? $permErrors = $title->getUserPermissionsErrors('edit', $wgUser); $permErrorsUpload = $title->getUserPermissionsErrors('upload', $wgUser); if ($permErrors || $permErrorsUpload) { return wfMsg('This image is protected'); } $temp_file = new LocalFile(Title::newFromText($mwname, NS_IMAGE), RepoGroup::singleton()->getLocalRepo()); $file = new LocalFile($title, RepoGroup::singleton()->getLocalRepo()); $file->upload($temp_file->getPath(), $comment, $comment); $temp_file->delete(''); } elseif ($type == 'overwrite') { // // DB entry exists and user selected to overwrite it // $title = Title::newFromText($name, NS_IMAGE); // is the target protected? $permErrors = $title->getUserPermissionsErrors('edit', $wgUser); $permErrorsUpload = $title->getUserPermissionsErrors('upload', $wgUser); $permErrorsCreate = $title->exists() ? array() : $title->getUserPermissionsErrors('create', $wgUser); if ($permErrors || $permErrorsUpload || $permErrorsCreate) { return wfMsg('This image is protected'); } $file_name = new LocalFile($title, RepoGroup::singleton()->getLocalRepo()); $file_mwname = new TempLocalFile(Title::newFromText($mwname, NS_IMAGE), RepoGroup::singleton()->getLocalRepo()); $file_name->upload($file_mwname->getPath(), $comment, $comment); $file_mwname->delete(''); $newFile = false; } elseif ($type == 'existing') { // // DB entry exists and user doesn't want to overwrite or // rename, so they use the existing file from the DB. // $title = Title::newFromText($name, NS_IMAGE); } else { // // There was a conflict with an existing file in the // DB. Title exists and overwrite action not taken yet. // $data = array('wpUpload' => 1, 'wpSourceType' => 'web', 'wpUploadFileURL' => ''); $form = new UploadForm(new FauxRequest($data, true)); // generate title if current one is taken $suggestedName = self::generateNewFilename($name); // extensions check list($first, $ext) = self::splitFilenameExt($suggestedName); $title = Title::newFromText($name, NS_IMAGE); $file = wfFindFile($title); $vars = array('suggestedFirstPart' => $first, 'extension' => strtolower($ext), 'name' => $name, 'mwname' => $mwname, 'file' => $file, 'image_comment' => $comment); $wgOut->setStatusCode(200); $wgOut->addHTML(EasyTemplate::html('eiu_conflict.tmpl.php', $vars)); // return no error return ''; } // add watch to file is user needs it if ($wgUser->getOption('watchdefault') || $newFile && $wgUser->getOption('watchcreations')) { $wgUser->addWatch($title); } $db =& wfGetDB(DB_MASTER); $db->commit(); } elseif (empty($mwname)) { $title = Title::makeTitleSafe(NS_IMAGE, $name); } elseif ($name !== null) { return WfMsg('eiu-warn3'); } else { // name === null $title = Title::newFromText($mwname, NS_IMAGE); } $file = wfFindFile($title); if (!is_object($file)) { return wfMsg('File not found'); } $details = self::splitValuePairs($wgRequest->getVal('image-details')); $tag = self::makeImageWikiTag($title, $file, $details); $vars = array('tag' => $tag, 'file' => $file, 'width' => $details['chosen-width'], 'height' => $details['chosen-height'], 'imageFilename' => $title->getText()); if (!$fromIIA) { $vars['details'] = $details; $html = EasyTemplate::html('eiu_upload_summary.tmpl.php', $vars); } else { $html = IntroImageAdder::addIntroImage($vars); } $wgOut->setStatusCode(200); $wgOut->addHTML($html); // return no error return ''; }
/** * @param LocalFile $file * @param string $url * @param string $comment * @return FileRepoStatus */ private function uploadFromUrl($file, $url, $comment) { $tmpFile = tempnam(wfTempDir(), 'upload'); // fetch an asset $res = Http::get($url, 'default', ['noProxy' => true]); $this->assertTrue($res !== false, 'File from <' . $url . '> should be uploaded'); file_put_contents($tmpFile, $res); $this->assertTrue(is_readable($tmpFile), 'Temp file for HTTP upload should be created and readable'); Wikia::log(__METHOD__, false, sprintf('uploading %s (%.2f kB) as %s', $tmpFile, filesize($tmpFile) / 1024, $file->getName()), true); $res = $file->upload($tmpFile, $comment, ''); #unlink( $tmpFile ); return $res; }
/** * This functions handle the third step of the WMU, image insertion * * @return bool|String */ function insertImage() { global $wgRequest, $wgUser, $wgContLang; $type = $wgRequest->getVal('type'); $name = $wgRequest->getVal('name'); $mwname = $wgRequest->getVal('mwname'); $tempid = $wgRequest->getVal('tempid'); $gallery = $wgRequest->getVal('gallery', ''); $title_main = urldecode($wgRequest->getVal('article', '')); $ns = $wgRequest->getVal('ns', ''); $link = urldecode($wgRequest->getVal('link', '')); // Are we in the ck editor? $ck = $wgRequest->getVal('ck'); $extraId = $wgRequest->getVal('extraId'); $newFile = true; $file = null; if ($name !== NULL) { $name = urldecode($name); if ($name == '') { header('X-screen-type: error'); return WfMsg('wmu-warn3'); } else { $name = preg_replace("/[^" . Title::legalChars() . "]|:/", '-', $name); // did they give no extension at all when they changed the name? $ext = explode('.', $name); array_shift($ext); if (count($ext)) { $finalExt = $ext[count($ext) - 1]; } else { $finalExt = ''; } if ('' == $finalExt) { header('X-screen-type: error'); return wfMsg('wmu-filetype-missing'); } $title = Title::makeTitleSafe(NS_IMAGE, $name); if (is_null($title)) { header('X-screen-type: error'); return wfMsg('wmu-filetype-incorrect'); } if ($title->exists()) { if ($type == 'overwrite') { $title = Title::newFromText($name, 6); // is the target protected? $permErrors = $title->getUserPermissionsErrors('edit', $wgUser); $permErrorsUpload = $title->getUserPermissionsErrors('upload', $wgUser); $permErrorsCreate = $title->exists() ? array() : $title->getUserPermissionsErrors('create', $wgUser); if ($permErrors || $permErrorsUpload || $permErrorsCreate) { header('X-screen-type: error'); return wfMsg('wmu-file-protected'); } $file_name = new LocalFile($title, RepoGroup::singleton()->getLocalRepo()); $file_mwname = new FakeLocalFile(Title::newFromText($mwname, 6), RepoGroup::singleton()->getLocalRepo()); if (!empty($extraId)) { $flickrResult = $this->getFlickrPhotoInfo($extraId); $nsid = $flickrResult['owner']['nsid']; // e.g. 49127042@N00 $username = $flickrResult['owner']['username']; // e.g. bossa67 $license = $flickrResult['license']; $caption = '{{MediaWiki:Flickr' . intval($license) . '|1=' . wfEscapeWikiText($extraId) . '|2=' . wfEscapeWikiText($nsid) . '|3=' . wfEscapeWikiText($username) . '}}'; } else { $caption = ''; } $file_name->upload($file_mwname->getPath(), '', $caption); $file_mwname->delete(''); $this->tempFileClearInfo($tempid); $newFile = false; } else { if ($type == 'existing') { $file = wfFindFile(Title::newFromText($name, 6)); if (!empty($file)) { header('X-screen-type: existing'); $props = array(); $props['file'] = $file; $props['mwname'] = $name; $props['default_caption'] = Wikia::getProps($file->getTitle()->getArticleID(), 'default_caption'); return $this->detailsPage($props); } else { header('X-screen-type: error'); return wfMsg('wmu-file-error'); } } else { header('X-screen-type: conflict'); $tmpl = new EasyTemplate(dirname(__FILE__) . '/templates/'); // extensions check list($partname, $ext) = UploadBase::splitExtensions($name); if (count($ext)) { $finalExt = $ext[count($ext) - 1]; } else { $finalExt = ''; } // for more than one "extension" if (count($ext) > 1) { for ($i = 0; $i < count($ext) - 1; $i++) { $partname .= '.' . $ext[$i]; } } $tmpl->set_vars(array('partname' => $partname, 'extension' => strtolower($finalExt), 'mwname' => $mwname, 'extraId' => $extraId)); return $tmpl->render('conflict'); } } } else { // is the target protected? $permErrors = $title->getUserPermissionsErrors('edit', $wgUser); $permErrorsUpload = $title->getUserPermissionsErrors('upload', $wgUser); $permErrorsCreate = $title->exists() ? array() : $title->getUserPermissionsErrors('create', $wgUser); if ($permErrors || $permErrorsUpload || $permErrorsCreate) { header('X-screen-type: error'); return wfMsg('wmu-file-protected'); } $temp_file = new FakeLocalFile(Title::newFromText($mwname, 6), RepoGroup::singleton()->getLocalRepo()); $file = new LocalFile($title, RepoGroup::singleton()->getLocalRepo()); if (!empty($extraId)) { $flickrResult = $this->getFlickrPhotoInfo($extraId); $nsid = $flickrResult['owner']['nsid']; // e.g. 49127042@N00 $username = $flickrResult['owner']['username']; // e.g. bossa67 $license = $flickrResult['license']; $caption = '{{MediaWiki:Flickr' . intval($license) . '|1=' . wfEscapeWikiText($extraId) . '|2=' . wfEscapeWikiText($nsid) . '|3=' . wfEscapeWikiText($username) . '}}'; } else { // get the supplied license value $license = $wgRequest->getVal('ImageUploadLicense'); if ($license != '') { $caption = '== ' . wfMsgForContent('license') . " ==\n" . '{{' . $license . '}}' . "\n"; } else { $caption = ""; } } $file->upload($temp_file->getPath(), '', $caption); $temp_file->delete(''); $this->tempFileClearInfo($tempid); } if ($wgUser->getGLobalPreference('watchdefault') || $newFile && $wgUser->getGlobalPreference('watchcreations')) { $wgUser->addWatch($title); } $db =& wfGetDB(DB_MASTER); $db->commit(); } } else { $title = Title::newFromText($mwname, 6); } if (is_null($file)) { $file = wfFindFile($title); } if (!is_object($file)) { header('X-screen-type: error'); return wfMessage('wmu-file-not-found')->plain(); } // Test if this violates the size requirements we've been given if ($msg = $this->invalidSize($file)) { header('X-screen-type: error'); return $msg; } $ns_img = $wgContLang->getFormattedNsText(NS_IMAGE); if (-2 == $gallery && !$ck) { // this went in from the single placeholder... $name = $title->getText(); $size = $wgRequest->getVal('size'); $width = $wgRequest->getVal('width'); $layout = $wgRequest->getVal('layout'); // clear the old caption for upload $caption = $wgRequest->getVal('caption'); $slider = $wgRequest->getVal('slider'); $title_obj = Title::newFromText($title_main, $ns); $article_obj = new Article($title_obj); $text = $article_obj->getContent(); wfRunHooks('WikiaMiniUpload::fetchTextForImagePlaceholder', array(&$title_obj, &$text)); $box = $wgRequest->getVal('box', ''); $placeholder = MediaPlaceholderMatch($text, $box); $success = false; if ($placeholder) { $our_gallery = $placeholder[0]; $gallery_split = explode(':', $our_gallery); $thumb = false; $tag = $gallery_split[0] . ":" . $name; if ($size != 'full') { $tag .= '|thumb'; $thumb = true; } if (isset($width)) { $tag .= '|' . $width; } $tag .= '|' . $layout; if ($link != '') { $tag .= '|link=' . $link; } if ($caption != '') { $tag .= '|' . $caption; } $tag .= "]]"; $text = substr_replace($text, $tag, $placeholder[1], strlen($our_gallery)); // return the proper embed code with all fancies around it $embed_code = $this->generateImage($file, $name, $title_obj, $thumb, (int) str_replace('px', '', $width), $layout, $caption); $message = wfMsg('wmu-success'); Wikia::setVar('EditFromViewMode', true); $summary = wfMsg('wmu-added-from-plc'); $success = $article_obj->doEdit($text, $summary); } if ($success) { header('X-screen-type: summary'); } else { // failure signal opens js alert (BugId:4935) header('X-screen-type: error'); return; } } else { header('X-screen-type: summary'); $size = $wgRequest->getVal('size'); $width = $wgRequest->getVal('width'); $layout = $wgRequest->getVal('layout'); $caption = $wgRequest->getVal('caption'); $slider = $wgRequest->getVal('slider'); $tag = '[[' . $ns_img . ':' . $title->getDBkey(); if ($size != 'full' && ($file->getMediaType() == 'BITMAP' || $file->getMediaType() == 'DRAWING')) { $tag .= '|thumb'; if ($layout != 'right') { $tag .= '|' . $layout; } if ($slider == 'true') { $tag .= '|' . $width; } } if ($link != '' && $size == 'full') { $tag .= '|link=' . $link; } if ($caption != '') { if ($size == 'full') { $tag .= '|frame'; if ($layout != 'right') { $tag .= '|' . $layout; } } $tag .= '|' . $caption . ']]'; } else { if ($size == 'full') { $tag .= '|' . $layout; } $tag .= ']]'; } } $message = wfMsg('wmu-success'); if ($wgRequest->getVal('update_caption') == 'on') { Wikia::setProps($title->getArticleID(), array('default_caption' => $caption)); } $tmpl = new EasyTemplate(dirname(__FILE__) . '/templates/'); $tmpl->set_vars(array('tag' => $tag, 'filename' => $ns_img . ':' . $title->getDBkey(), 'message' => $message, 'code' => isset($embed_code) ? $embed_code : '')); return $tmpl->render('summary'); }
/** * Accept a request to upload an image either via POST data (user upload) * or via flickr or google / wikimedia.org search. * * @param $src string with value 'upload', 'flickr' or 'wiki' * @return html outputs image details page */ private function uploadImage($src) { global $wgRequest, $wgUser, $IP, $wgOut; $error = ''; $debugInfo = array(); if ($src == 'upload') { $tempname = self::createTempFilename(); $tempUser = self::getTempFileUser(); $file = new LocalFile(Title::newFromText($tempname, NS_IMAGE), RepoGroup::singleton()->getLocalRepo()); $name = $wgRequest->getFileName('wpUploadFile'); $comment = ''; $file->upload($wgRequest->getFileTempName('wpUploadFile'), $comment, '', 0, false, false, $tempUser); $filesize = $file->getSize(); if (!$filesize) { $error = wfMsg('eiu-upload-error'); } } elseif ($src == 'flickr' || $src == 'wiki') { $sourceName = $src == 'flickr' ? 'Flickr' : 'Mediawiki Commons'; $tempname = self::createTempFilename(); $file = new LocalFile(Title::newFromText($tempname, NS_IMAGE), RepoGroup::singleton()->getLocalRepo()); $details = (array) json_decode($wgRequest->getVal('img-details')); $name = $details['name']; // scrape the file using curl $filename = '/tmp/tmp-curl-' . mt_rand(0, 100000000) . '.jpg'; $remoteFile = strlen($details['url_l']) ? $details['url_l'] : $details['url']; $ch = curl_init($remoteFile); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $fp = fopen($filename, 'w'); curl_setopt($ch, CURLOPT_FILE, $fp); $ret = curl_exec($ch); $err = curl_error($ch); curl_close($ch); fclose($fp); if ($err) { $debugInfo['curl'] = $err; } $filesize = @filesize($filename); if ($filesize) { if ($src == 'flickr' || preg_match('@^http://[^/]*flickr@', $details['url'])) { require_once $IP . '/extensions/3rdparty/phpFlickr-2.3.1/phpFlickr.php'; $flickr = new phpFlickr(WH_FLICKR_API_KEY); $photo = $flickr->photos_getInfo($details['photoid']); $err = $flickr->getErrorMsg(); if ($err) { $debugInfo['flickrAPI'] = $err; } $license = $photo['license']; $username = $photo['owner']['username']; $comment = '{{flickr' . intval($license) . '|' . wfEscapeWikiText($details['photoid']) . '|' . wfEscapeWikiText($details['ownerid']) . '|' . wfEscapeWikiText($username) . '}}'; } else { $comment = self::getWPLicenseTag($details['url']); } // finish initializing the $file obj $tempUser = self::getTempFileUser(); $status = $file->upload($filename, '', '', 0, false, false, $tempUser); if (!$status->ok) { $error = wfMsg('eiu-upload-error'); } } else { $error = wfMsg('eiu-download-error', $sourceName); } } if ($error) { $html = EasyTemplate::html('eiu_file_error.tmpl.php', array('error' => $error)); $wgOut->addHTML($html); error_log("file from {$src} error msgs: " . print_r($debugInfo, true)); } else { $mwname = $tempname; $props = array('src' => $src, 'name' => $name, 'mwname' => $mwname, 'is_image' => $file->getMediaType() == 'BITMAP' || $file->getMediaType() == 'DRAWING', 'width' => $file->getWidth(), 'height' => $file->getHeight(), 'upload_file' => $file, 'image_comment' => $comment, 'license' => $wgUser->getOption('image_license'), 'file' => $file); $html = EasyTemplate::html('eiu_image_details.tmpl.php', $props); $wgOut->addHTML($html); } }
} if (!defined("AMAZON_AWS_SECRET")) { die("Please define the AMAZON_AWS_SECRET in your config\n"); } if (!defined("STORAGE_METHOD") || STORAGE_METHOD !== "LocalFile") { die("Please define STORAGE_METHOD to be LocalFile\n"); } $total_s3_files = db()->getValue("SELECT max(id) FROM s3_files"); print "Files to convert: " . $total_s3_files . "\n"; $rows_to_remove = array(); for ($s3_id = 1; $s3_id <= $total_s3_files; $s3_id++) { // Grab the s3 file // Verify the file exists. // If it exists, download it // If it doesn't, add it to the rows to be removed // Set all of the correct variables $s3_file = new S3File($s3_id); if ($s3_file->exists()) { $local_file = new LocalFile($s3_id); $temp_file = tempnam("/tmp", "BQ"); $s3_file->download($s3_file->get('path'), $temp_file); $local_file->upload($temp_file, $s3_file->get('path')); $local_file->id = $s3_id; $percent_completed = sprintf("%01.2f", $s3_id * 100 / $total_s3_files); print sprintf("%6s", $percent_completed) . "% => File #" . $s3_id . "\n"; } else { print "File #" . $s3_id . " doesn't exist\n"; $rows_to_remove[] = $s3_id; } } print count($rows_to_remove) . " files were no longer in S3\n";
public static function uploadBadge($destinationFileName, $badgeLevel) { global $wgRequest, $wgUser; $upload = new UploadAchievementsFromFile(); $upload->initialize($destinationFileName, $wgRequest->getUpload('wpUploadFile')); $details = $upload->verifyUpload(); //ignore warnings about existing files, they MUST be silently overwritten if ($details['status'] != UploadBase::OK) { return false; } else { $warnings = $upload->checkWarnings(); if ($warnings && (empty($warnings['exists']) && empty($warnings['duplicate']) && empty($warnings['duplicate-archive']))) { return false; } } // badge data $badgeFile = $wgRequest->getUpload('wpUploadFile')->getTempName(); // validate image using GD $badgeImage = imagecreatefromstring(file_get_contents($badgeFile)); if (!is_resource($badgeImage)) { return false; } // get dimensions of uploaded image $badgeWidth = imagesx($badgeImage); $badgeHeight = imagesy($badgeImage); // resize uploaded image if needed if ($badgeWidth > 128 || $badgeHeight > 128) { // calculate new badge dimensions $ratioWidth = $badgeWidth / 128; $ratioHeight = $badgeHeight / 128; $ratio = min($ratioWidth, $ratioHeight); // don't scale up $ratio = max($ratio, 1); $newWidth = round($badgeWidth / $ratio); $newHeight = round($badgeHeight / $ratio); } else { $newWidth = $badgeWidth; $newHeight = $badgeHeight; $ratio = 1; } // resize and crop uploaded image / center inside a badge $tmp = imagecreatetruecolor(128, 128); // transparent background imagesavealpha($tmp, true); imagealphablending($tmp, false); $bgColor = imagecolorallocatealpha($tmp, 0, 0, 0, 127); imagefilledrectangle($tmp, 0, 0, 127, 127, $bgColor); // calculate crop / resize $dstX = max(0, 128 - $newWidth >> 1); $dstY = max(0, 128 - $newHeight >> 1); $srcX = max(0, $badgeWidth - 128 * $ratio >> 1); $srcY = max(0, $badgeHeight - 128 * $ratio >> 1); imagecopyresampled($tmp, $badgeImage, $dstX, $dstY, $srcX, $srcY, $newWidth, $newHeight, $badgeWidth, $badgeHeight); // use resized badge imagedestroy($badgeImage); $badgeImage = $tmp; // load images $badgesFragments = dirname(__FILE__) . '/../images/badges/fragments'; $badgeBottom = "{$badgesFragments}/{$badgeLevel}-bottom-128.png"; $badgeTop = "{$badgesFragments}/{$badgeLevel}-top-128.png"; $img = array('bottom' => imagecreatefrompng($badgeBottom), 'top' => imagecreatefrompng($badgeTop), 'user' => $badgeImage); // create image for badge $badge = imagecreatetruecolor(128, 128); // put bottom layer self::merge_images($badge, $img['bottom']); // put user's image self::merge_images($badge, $img['user']); // put top layer self::merge_images($badge, $img['top']); // now let's fix badge transparency self::merge_alphamask($badge, $img['top'], $img['bottom']); // save badge $ret = imagepng($badge, $badgeFile, 9, PNG_ALL_FILTERS); wfDebug(__METHOD__ . ": generated badge saved as {$badgeFile}\n"); // collect garbage imagedestroy($badge); foreach ($img as $i) { imagedestroy($i); } // upload generated badge $file = new LocalFile(Title::newFromText($destinationFileName, 6), RepoGroup::singleton()->getLocalRepo()); $file->upload($badgeFile, '/* comment */', '/* page text */'); return $file; }