/**
  * Stash a file in a temp directory and record that we did this in the database, along with other metadata.
  *
  * @param $path String: path to file you want stashed
  * @param $sourceType String: the type of upload that generated this file (currently, I believe, 'file' or null)
  * @param $key String: optional, unique key for this file. Used for directory hashing when storing, otherwise not important
  * @throws UploadStashBadPathException
  * @throws UploadStashFileException
  * @throws UploadStashNotLoggedInException
  * @return UploadStashFile: file, or null on failure
  */
 public function stashFile($path, $sourceType = null, $key = null)
 {
     if (!file_exists($path)) {
         wfDebug(__METHOD__ . " tried to stash file at '{$path}', but it doesn't exist\n");
         throw new UploadStashBadPathException("path doesn't exist");
     }
     $fileProps = File::getPropsFromPath($path);
     wfDebug(__METHOD__ . " stashing file at '{$path}'\n");
     // we will be initializing from some tmpnam files that don't have extensions.
     // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
     $extension = self::getExtensionForPath($path);
     if (!preg_match("/\\.\\Q{$extension}\\E\$/", $path)) {
         $pathWithGoodExtension = "{$path}.{$extension}";
         if (!rename($path, $pathWithGoodExtension)) {
             throw new UploadStashFileException("couldn't rename {$path} to have a better extension at {$pathWithGoodExtension}");
         }
         $path = $pathWithGoodExtension;
     }
     // If no key was supplied, make one.  a mysql insertid would be totally reasonable here, except
     // that some users of this function might expect to supply the key instead of using the generated one.
     if (is_null($key)) {
         // some things that when combined will make a suitably unique key.
         // see: http://www.jwz.org/doc/mid.html
         list($usec, $sec) = explode(' ', microtime());
         $usec = substr($usec, 2);
         $key = wfBaseConvert($sec . $usec, 10, 36) . '.' . wfBaseConvert(mt_rand(), 10, 36) . '.' . $this->userId . '.' . $extension;
     }
     $this->fileProps[$key] = $fileProps;
     if (!preg_match(self::KEY_FORMAT_REGEX, $key)) {
         throw new UploadStashBadPathException("key '{$key}' is not in a proper format");
     }
     wfDebug(__METHOD__ . " key for '{$path}': {$key}\n");
     // if not already in a temporary area, put it there
     $storeStatus = $this->repo->storeTemp(basename($path), $path);
     if (!$storeStatus->isOK()) {
         // It is a convention in MediaWiki to only return one error per API exception, even if multiple errors
         // are available. We use reset() to pick the "first" thing that was wrong, preferring errors to warnings.
         // This is a bit lame, as we may have more info in the $storeStatus and we're throwing it away, but to fix it means
         // redesigning API errors significantly.
         // $storeStatus->value just contains the virtual URL (if anything) which is probably useless to the caller
         $error = $storeStatus->getErrorsArray();
         $error = reset($error);
         if (!count($error)) {
             $error = $storeStatus->getWarningsArray();
             $error = reset($error);
             if (!count($error)) {
                 $error = array('unknown', 'no error recorded');
             }
         }
         throw new UploadStashFileException("error storing file in '{$path}': " . implode('; ', $error));
     }
     $stashPath = $storeStatus->value;
     // fetch the current user ID
     if (!$this->isLoggedIn) {
         throw new UploadStashNotLoggedInException(__METHOD__ . ' No user is logged in, files must belong to users');
     }
     // insert the file metadata into the db.
     wfDebug(__METHOD__ . " inserting {$stashPath} under {$key}\n");
     $dbw = $this->repo->getMasterDb();
     // select happens on the master so this can all be in a transaction, which
     // avoids a race condition that's likely with multiple people uploading from the same
     // set of files
     $dbw->begin();
     // first, check to see if it's already there.
     $row = $dbw->selectRow('uploadstash', 'us_user, us_timestamp', array('us_key' => $key), __METHOD__);
     // The current user can't have this key if:
     // - the key is owned by someone else and
     // - the age of the key is less than REPO_AGE
     if (is_object($row)) {
         if ($row->us_user != $this->userId && $row->wfTimestamp(TS_UNIX, $row->us_timestamp) > time() - UploadStash::REPO_AGE * 3600) {
             $dbw->rollback();
             throw new UploadStashWrongOwnerException("Attempting to upload a duplicate of a file that someone else has stashed");
         }
     }
     $this->fileMetadata[$key] = array('us_user' => $this->userId, 'us_key' => $key, 'us_orig_path' => $path, 'us_path' => $stashPath, 'us_size' => $fileProps['size'], 'us_sha1' => $fileProps['sha1'], 'us_mime' => $fileProps['mime'], 'us_media_type' => $fileProps['media_type'], 'us_image_width' => $fileProps['width'], 'us_image_height' => $fileProps['height'], 'us_image_bits' => $fileProps['bits'], 'us_source_type' => $sourceType, 'us_timestamp' => $dbw->timestamp(), 'us_status' => 'finished');
     // if a row exists but previous checks on it passed, let the current user take over this key.
     $dbw->replace('uploadstash', 'us_key', $this->fileMetadata[$key], __METHOD__);
     $dbw->commit();
     // store the insertid in the class variable so immediate retrieval (possibly laggy) isn't necesary.
     $this->fileMetadata[$key]['us_id'] = $dbw->insertId();
     # create the UploadStashFile object for this file.
     $this->initFile($key);
     return $this->getFile($key);
 }
Example #2
0
 function getFileProps($fileName)
 {
     if (FileRepo::isVirtualUrl($fileName)) {
         list($repoName, , ) = $this->splitVirtualUrl($fileName);
         if ($repoName === '') {
             $repoName = 'local';
         }
         $repo = $this->getRepo($repoName);
         return $repo->getFileProps($fileName);
     } else {
         return File::getPropsFromPath($fileName);
     }
 }
Example #3
0
 /**
  * Get properties of a file with a given virtual URL
  * The virtual URL must refer to this repo
  */
 function getFileProps($virtualUrl)
 {
     $path = $this->resolveVirtualUrl($virtualUrl);
     return File::getPropsFromPath($path);
 }
Example #4
0
 /**
  * Verifies that it's ok to include the uploaded file
  *
  * @return mixed true of the file is verified, array otherwise.
  */
 protected function verifyFile()
 {
     # get the title, even though we are doing nothing with it, because
     # we need to populate mFinalExtension
     $this->getTitle();
     $this->mFileProps = File::getPropsFromPath($this->mTempPath, $this->mFinalExtension);
     $this->checkMacBinary();
     # check mime type, if desired
     $mime = $this->mFileProps['file-mime'];
     $status = $this->verifyMimeType($mime);
     if ($status !== true) {
         return $status;
     }
     # check for htmlish code and javascript
     if (self::detectScript($this->mTempPath, $mime, $this->mFinalExtension)) {
         return array('uploadscripted');
     }
     if ($this->mFinalExtension == 'svg' || $mime == 'image/svg+xml') {
         if ($this->detectScriptInSvg($this->mTempPath)) {
             return array('uploadscripted');
         }
     }
     /**
      * Scan the uploaded file for viruses
      */
     $virus = $this->detectVirus($this->mTempPath);
     if ($virus) {
         return array('uploadvirus', $virus);
     }
     $handler = MediaHandler::getHandler($mime);
     if ($handler) {
         $handlerStatus = $handler->verifyUpload($this->mTempPath);
         if (!$handlerStatus->isOK()) {
             $errors = $handlerStatus->getErrorsArray();
             return reset($errors);
         }
     }
     wfRunHooks('UploadVerifyFile', array($this, $mime, &$status));
     if ($status !== true) {
         return $status;
     }
     wfDebug(__METHOD__ . ": all clear; passing.\n");
     return true;
 }
Example #5
0
 /**
  * Stash a file in a temp directory and record that we did this in the session, along with other metadata.
  * We store data in a flat key-val namespace because that's how UploadBase did it. This also means we have to
  * ensure that the key-val pairs in $data do not overwrite other required fields.
  *
  * @param $path String: path to file you want stashed
  * @param $data Array: optional, other data you want associated with the file. Do not use 'mTempPath', 'mFileProps', 'mFileSize', or 'version' as keys here
  * @param $key String: optional, unique key for this file in this session. Used for directory hashing when storing, otherwise not important
  * @throws UploadStashBadPathException
  * @throws UploadStashFileException
  * @return UploadStashFile: file, or null on failure
  */
 public function stashFile($path, $data = array(), $key = null)
 {
     if (!file_exists($path)) {
         wfDebug("UploadStash: tried to stash file at '{$path}', but it doesn't exist\n");
         throw new UploadStashBadPathException("path doesn't exist");
     }
     $fileProps = File::getPropsFromPath($path);
     // we will be initializing from some tmpnam files that don't have extensions.
     // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
     $extension = self::getExtensionForPath($path);
     if (!preg_match("/\\.\\Q{$extension}\\E\$/", $path)) {
         $pathWithGoodExtension = "{$path}.{$extension}";
         if (!rename($path, $pathWithGoodExtension)) {
             throw new UploadStashFileException("couldn't rename {$path} to have a better extension at {$pathWithGoodExtension}");
         }
         $path = $pathWithGoodExtension;
     }
     // If no key was supplied, use content hash. Also has the nice property of collapsing multiple identical files
     // uploaded this session, which could happen if uploads had failed.
     if (is_null($key)) {
         $key = $fileProps['sha1'] . "." . $extension;
     }
     if (!preg_match(self::KEY_FORMAT_REGEX, $key)) {
         throw new UploadStashBadPathException("key '{$key}' is not in a proper format");
     }
     // if not already in a temporary area, put it there
     $status = $this->repo->storeTemp(basename($path), $path);
     if (!$status->isOK()) {
         // It is a convention in MediaWiki to only return one error per API exception, even if multiple errors
         // are available. We use reset() to pick the "first" thing that was wrong, preferring errors to warnings.
         // This is a bit lame, as we may have more info in the $status and we're throwing it away, but to fix it means
         // redesigning API errors significantly.
         // $status->value just contains the virtual URL (if anything) which is probably useless to the caller
         $error = reset($status->getErrorsArray());
         if (!count($error)) {
             $error = reset($status->getWarningsArray());
             if (!count($error)) {
                 $error = array('unknown', 'no error recorded');
             }
         }
         throw new UploadStashFileException("error storing file in '{$path}': " . implode('; ', $error));
     }
     $stashPath = $status->value;
     // required info we always store. Must trump any other application info in $data
     // 'mTempPath', 'mFileSize', and 'mFileProps' are arbitrary names
     // chosen for compatibility with UploadBase's way of doing this.
     $requiredData = array('mTempPath' => $stashPath, 'mFileSize' => $fileProps['size'], 'mFileProps' => $fileProps, 'version' => UploadBase::SESSION_VERSION);
     // now, merge required info and extra data into the session. (The extra data changes from application to application.
     // UploadWizard wants different things than say FirefoggChunkedUpload.)
     wfDebug(__METHOD__ . " storing under {$key}\n");
     $_SESSION[UploadBase::SESSION_KEYNAME][$key] = array_merge($data, $requiredData);
     return $this->getFile($key);
 }
	/**
	 * Get properties of a file with a given virtual URL
	 * The virtual URL must refer to this repo
	 */
	function getFileProps( $virtualUrl ) {
		$path = $this->resolveVirtualUrl( $virtualUrl );
		$ret = File::getPropsFromPath( $path );
		unlink( $path );
		return $ret;
	}
Example #7
0
 private function doUpload($title, $file, $msg, $comment)
 {
     global $wgTmpDirectory;
     /* @var File $fileObj */
     $fileObj = wfLocalFile($title);
     $dir = sys_get_temp_dir();
     $path = tempnam($wgTmpDirectory, 'MTG');
     $f = fopen($path, 'w');
     fwrite($f, $file);
     fclose($f);
     $props = File::getPropsFromPath($path);
     $fileObj->upload($path, $comment, $msg, File::DELETE_SOURCE, $props);
 }
 function internalProcessUpload(&$resultDetails)
 {
     global $wgUser;
     /* Check for PHP error if any, requires php 4.2 or newer */
     if ($this->mCurlError == 1) {
         return self::LARGE_FILE_SERVER;
     }
     /**
      * If there was no filename or a zero size given, give up quick.
      */
     if (trim($this->mSrcName) == '' || empty($this->mFileSize)) {
         return self::EMPTY_FILE;
     }
     # Chop off any directories in the given filename
     if ($this->mDesiredDestName) {
         $basename = $this->mDesiredDestName . '.' . $this->mParameterExt;
         $this->mStoredDestName = $this->mDesiredDestName;
     } else {
         $basename = $this->mSrcName;
     }
     $filtered = wfBaseName($basename);
     /**
      * We'll want to blacklist against *any* 'extension', and use
      * only the final one for the whitelist.
      */
     list($partname, $ext) = $this->splitExtensions($filtered);
     if (count($ext)) {
         $finalExt = $ext[count($ext) - 1];
     } else {
         $finalExt = '';
     }
     # If there was more than one "extension", reassemble the base
     # filename to prevent bogus complaints about length
     if (count($ext) > 1) {
         for ($i = 0; $i < count($ext) - 1; $i++) {
             $partname .= '.' . $ext[$i];
         }
     }
     if (strlen($partname) < 1) {
         return self::MIN_LENGTH_PARTNAME;
     }
     /**
      * Filter out illegal characters, and try to make a legible name
      * out of it. We'll strip some silently that Title would die on.
      */
     $filtered = preg_replace("/[^" . Title::legalChars() . "]|:/", '-', $filtered);
     $nt = Title::makeTitleSafe(NS_IMAGE, $filtered);
     if (is_null($nt)) {
         $resultDetails = array('filtered' => $filtered);
         return self::ILLEGAL_FILENAME;
     }
     $this->mLocalFile = wfLocalFile($nt);
     $this->mDestName = $this->mLocalFile->getName();
     /**
      * If the image is protected, non-sysop users won't be able
      * to modify it by uploading a new revision.
      */
     if (!$nt->userCan('edit')) {
         return self::PROTECTED_PAGE;
     }
     /**
      * In some cases we may forbid overwriting of existing files.
      */
     // here starts the interesting part...
     // we overwrite mDestName and give it a new twist
     $timestamp = '';
     $img_found = wfFindFile($this->mDestName);
     if ($img_found) {
         // ehhh...
         // we'll do it hard way then...
         $timestamp = $this->mDestName;
     } else {
         // this timestamp should not repeat...
         $timestamp = 'invalid';
     }
     $tempname = '';
     $tmpcount = 0;
     while ($img_found && $timestamp != $this->mLastTimestamp) {
         $tmpcount++;
         $file_ext = explode('.', $this->mDestName);
         $file_ext = $file_ext[0];
         $tmpdestname = $file_ext;
         $tempname = $tmpdestname . $tmpcount . '.' . $this->mParameterExt;
         $timestamp = $tempname;
         $img_found = wfFindFile($tempname);
     }
     if ($tmpcount > 0) {
         wfLocalFile($title);
         $tempname = preg_replace("/[^" . Title::legalChars() . "]|:/", '-', $tempname);
         $nt = Title::makeTitleSafe(NS_FILE, $tempname);
         $this->mLocalFile = wfLocalFile($nt);
         $this->mDestName = $this->mLocalFile->getName();
         $this->mDesiredDestName = $this->mStoredDestName . $tmpcount . '.' . $this->mParameterExt;
     } else {
         // append the extension anyway
         $this->mDesiredDestName = $this->mStoredDestName . '.' . $this->mParameterExt;
     }
     $overwrite = $this->checkOverwrite($this->mDestName);
     if ($overwrite !== true) {
         $resultDetails = array('overwrite' => $overwrite);
         return self::OVERWRITE_EXISTING_FILE;
     }
     /* Don't allow users to override the blacklist (check file extension) */
     global $wgStrictFileExtensions, $wgFileExtensions, $wgFileBlacklist;
     if ($finalExt == '') {
         return self::FILETYPE_MISSING;
     } elseif ($this->checkFileExtensionList($ext, $wgFileBlacklist) || $wgStrictFileExtensions && !$this->checkFileExtension($finalExt, $wgFileExtensions)) {
         $resultDetails = array('finalExt' => $finalExt);
         return self::FILETYPE_BADTYPE;
     }
     /**
      * Look at the contents of the file; if we can recognize the
      * type but it's corrupt or data of the wrong type, we should
      * probably not accept it.
      */
     if (!$this->mStashed) {
         $this->mFileProps = File::getPropsFromPath($this->mTempPath, $finalExt);
         $this->checkMacBinary();
         $veri = $this->verify($this->mTempPath, $finalExt);
         if ($veri !== true) {
             // it's a wiki error...
             $resultDetails = array('veri' => $veri);
             return self::VERIFICATION_ERROR;
         }
         /**
          * Provide an opportunity for extensions to add further checks
          */
         $error = '';
     }
     /**
      * Check for non-fatal conditions
      */
     if (!$this->mIgnoreWarning) {
         $warning = '';
         global $wgCapitalLinks;
         if ($wgCapitalLinks) {
             $filtered = ucfirst($filtered);
         }
         if ($basename != $filtered) {
             $warning .= '<li>' . wfMsgHtml('badfilename', htmlspecialchars($this->mDestName)) . '</li>';
         }
         global $wgCheckFileExtensions;
         if ($wgCheckFileExtensions) {
             if (!$this->checkFileExtension($finalExt, $wgFileExtensions)) {
                 $warning .= '<li>' . wfMsgExt('filetype-badtype', array('parseinline'), htmlspecialchars($finalExt), implode(', ', $wgFileExtensions)) . '</li>';
             }
         }
         global $wgUploadSizeWarning;
         if ($wgUploadSizeWarning && $this->mFileSize > $wgUploadSizeWarning) {
             $skin = $wgUser->getSkin();
             $wsize = $skin->formatSize($wgUploadSizeWarning);
             $asize = $skin->formatSize($this->mFileSize);
             $warning .= '<li>' . wfMsgHtml('large-file', $wsize, $asize) . '</li>';
         }
         if ($this->mFileSize == 0) {
             $warning .= '<li>' . wfMsgHtml('emptyfile') . '</li>';
         }
         if (!$this->mDestWarningAck) {
             $warning .= self::getExistsWarning($this->mLocalFile);
         }
         if ($warning != '') {
             /**
              * Stash the file in a temporary location; the user can choose
              * to let it through and we'll complete the upload then.
              */
             $resultDetails = array('warning' => $warning);
             return self::UPLOAD_WARNING;
         }
     }
     /**
      * Try actually saving the thing...
      * It will show an error form on failure.
      */
     $pageText = self::getInitialPageText($this->mComment, $this->mLicense, $this->mCopyrightStatus, $this->mCopyrightSource);
     $status = $this->mLocalFile->upload($this->mTempPath, $this->mComment, $pageText, File::DELETE_SOURCE, $this->mFileProps);
     if (!$status->isGood()) {
         $this->showError($status->getWikiText());
     } else {
         if ($this->mWatchthis) {
             global $wgUser;
             $wgUser->addWatch($this->mLocalFile->getTitle());
         }
         // Success, redirect to description page
         $this->mReturnedTimestamp = $this->getQuickTimestamp($this->mDestName);
         $img = null;
         // @todo: added to avoid passing a ref to null - should this be defined somewhere?
         return self::SUCCESS;
     }
 }
Example #9
0
 /**
  * Really do the upload
  * Checks are made in SpecialUpload::execute()
  *
  * @param array $resultDetails contains result-specific dict of additional values
  *
  * @access private
  */
 function internalProcessUpload(&$resultDetails)
 {
     global $wgUser;
     if (!wfRunHooks('UploadForm:BeforeProcessing', array(&$this))) {
         wfDebug("Hook 'UploadForm:BeforeProcessing' broke processing the file.\n");
         return self::BEFORE_PROCESSING;
     }
     /**
      * If there was no filename or a zero size given, give up quick.
      */
     if (trim($this->mSrcName) == '' || empty($this->mFileSize)) {
         return self::EMPTY_FILE;
     }
     /* Check for curl error */
     if ($this->mCurlError) {
         return self::BEFORE_PROCESSING;
     }
     /**
      * Chop off any directories in the given filename. Then
      * filter out illegal characters, and try to make a legible name
      * out of it. We'll strip some silently that Title would die on.
      */
     if ($this->mDesiredDestName) {
         $basename = $this->mDesiredDestName;
     } else {
         $basename = $this->mSrcName;
     }
     $filtered = wfStripIllegalFilenameChars($basename);
     /* Normalize to title form before we do any further processing */
     $nt = Title::makeTitleSafe(NS_FILE, $filtered);
     if (is_null($nt)) {
         $resultDetails = array('filtered' => $filtered);
         return self::ILLEGAL_FILENAME;
     }
     $filtered = $nt->getDBkey();
     /**
      * We'll want to blacklist against *any* 'extension', and use
      * only the final one for the whitelist.
      */
     list($partname, $ext) = $this->splitExtensions($filtered);
     if (count($ext)) {
         $finalExt = $ext[count($ext) - 1];
     } else {
         $finalExt = '';
     }
     # If there was more than one "extension", reassemble the base
     # filename to prevent bogus complaints about length
     if (count($ext) > 1) {
         for ($i = 0; $i < count($ext) - 1; $i++) {
             $partname .= '.' . $ext[$i];
         }
     }
     if (strlen($partname) < 1) {
         return self::MIN_LENGTH_PARTNAME;
     }
     $this->mLocalFile = wfLocalFile($nt);
     $this->mDestName = $this->mLocalFile->getName();
     /**
      * If the image is protected, non-sysop users won't be able
      * to modify it by uploading a new revision.
      */
     $permErrors = $nt->getUserPermissionsErrors('edit', $wgUser);
     $permErrorsUpload = $nt->getUserPermissionsErrors('upload', $wgUser);
     $permErrorsCreate = $nt->exists() ? array() : $nt->getUserPermissionsErrors('create', $wgUser);
     if ($permErrors || $permErrorsUpload || $permErrorsCreate) {
         // merge all the problems into one list, avoiding duplicates
         $permErrors = array_merge($permErrors, wfArrayDiff2($permErrorsUpload, $permErrors));
         $permErrors = array_merge($permErrors, wfArrayDiff2($permErrorsCreate, $permErrors));
         $resultDetails = array('permissionserrors' => $permErrors);
         return self::PROTECTED_PAGE;
     }
     /**
      * In some cases we may forbid overwriting of existing files.
      */
     $overwrite = $this->checkOverwrite($this->mDestName);
     if ($overwrite !== true) {
         $resultDetails = array('overwrite' => $overwrite);
         return self::OVERWRITE_EXISTING_FILE;
     }
     /* Don't allow users to override the blacklist (check file extension) */
     global $wgCheckFileExtensions, $wgStrictFileExtensions;
     global $wgFileExtensions, $wgFileBlacklist;
     if ($finalExt == '') {
         return self::FILETYPE_MISSING;
     } elseif ($this->checkFileExtensionList($ext, $wgFileBlacklist) || $wgCheckFileExtensions && $wgStrictFileExtensions && !$this->checkFileExtension($finalExt, $wgFileExtensions)) {
         $resultDetails = array('finalExt' => $finalExt);
         return self::FILETYPE_BADTYPE;
     }
     /**
      * Look at the contents of the file; if we can recognize the
      * type but it's corrupt or data of the wrong type, we should
      * probably not accept it.
      */
     if (!$this->mStashed) {
         $this->mFileProps = File::getPropsFromPath($this->mTempPath, $finalExt);
         $this->checkMacBinary();
         $veri = $this->verify($this->mTempPath, $finalExt);
         if ($veri !== true) {
             //it's a wiki error...
             $resultDetails = array('veri' => $veri);
             return self::VERIFICATION_ERROR;
         }
         /**
          * Provide an opportunity for extensions to add further checks
          */
         $error = '';
         if (!wfRunHooks('UploadVerification', array($this->mDestName, $this->mTempPath, &$error))) {
             $resultDetails = array('error' => $error);
             return self::UPLOAD_VERIFICATION_ERROR;
         }
     }
     /**
      * Check for non-fatal conditions
      */
     if (!$this->mIgnoreWarning) {
         $warning = '';
         $comparableName = str_replace(' ', '_', $basename);
         global $wgCapitalLinks, $wgContLang;
         if ($wgCapitalLinks) {
             $comparableName = $wgContLang->ucfirst($comparableName);
         }
         if ($comparableName !== $filtered) {
             $warning .= '<li>' . wfMsgHtml('badfilename', htmlspecialchars($this->mDestName)) . '</li>';
         }
         global $wgCheckFileExtensions;
         if ($wgCheckFileExtensions) {
             if (!$this->checkFileExtension($finalExt, $wgFileExtensions)) {
                 global $wgLang;
                 $warning .= '<li>' . wfMsgExt('filetype-unwanted-type', array('parseinline'), htmlspecialchars($finalExt), $wgLang->commaList($wgFileExtensions), $wgLang->formatNum(count($wgFileExtensions))) . '</li>';
             }
         }
         global $wgUploadSizeWarning;
         if ($wgUploadSizeWarning && $this->mFileSize > $wgUploadSizeWarning) {
             $skin = $wgUser->getSkin();
             $wsize = $skin->formatSize($wgUploadSizeWarning);
             $asize = $skin->formatSize($this->mFileSize);
             $warning .= '<li>' . wfMsgHtml('large-file', $wsize, $asize) . '</li>';
         }
         if ($this->mFileSize == 0) {
             $warning .= '<li>' . wfMsgHtml('emptyfile') . '</li>';
         }
         if (!$this->mDestWarningAck) {
             $warning .= self::getExistsWarning($this->mLocalFile);
         }
         $warning .= $this->getDupeWarning($this->mTempPath, $finalExt, $nt);
         if ($warning != '') {
             /**
              * Stash the file in a temporary location; the user can choose
              * to let it through and we'll complete the upload then.
              */
             $resultDetails = array('warning' => $warning);
             return self::UPLOAD_WARNING;
         }
     }
     /**
      * Try actually saving the thing...
      * It will show an error form on failure.
      */
     if (!$this->mForReUpload) {
         $pageText = self::getInitialPageText($this->mComment, $this->mLicense, $this->mCopyrightStatus, $this->mCopyrightSource);
     }
     $status = $this->mLocalFile->upload($this->mTempPath, $this->mComment, $pageText, File::DELETE_SOURCE, $this->mFileProps);
     if (!$status->isGood()) {
         $resultDetails = array('internal' => $status->getWikiText());
         return self::INTERNAL_ERROR;
     } else {
         if ($this->mWatchthis) {
             global $wgUser;
             $wgUser->addWatch($this->mLocalFile->getTitle());
         }
         // Success, redirect to description page
         $img = null;
         // @todo: added to avoid passing a ref to null - should this be defined somewhere?
         wfRunHooks('UploadComplete', array(&$this));
         return self::SUCCESS;
     }
 }
Example #10
0
 private function handleAttachmentCallBack($fileName, $attachmentMP, $mailFrom, $mailId, $mailDate, $extraContent, $conflictPolicy, $termImportName)
 {
     global $smwgDIIP;
     $success = true;
     $logMsgs = array();
     $tiBot = new TermImportBot();
     global $smwgEnableRichMedia;
     if ($smwgEnableRichMedia) {
         global $wgNamespaceByExtension;
         $fileNameArray = explode(".", $fileName);
         $ext = $fileNameArray[count($fileNameArray) - 1];
         if (array_key_exists($ext, $wgNamespaceByExtension)) {
             $ns = $wgNamespaceByExtension[$ext];
         } else {
             $ns = NS_IMAGE;
         }
     } else {
         $ns = NS_IMAGE;
     }
     $fileArticleTitle = Title::makeTitleSafe($ns, $fileName);
     if ($fileArticleTitle == null) {
         return $this->createCallBackResult(false, array(array('id' => SMW_GARDISSUE_CREATION_FAILED, 'title' => wfMsg('smw_ti_import_error'))));
     }
     $termAnnotations = $tiBot->getExistingTermAnnotations($fileArticleTitle);
     if ($fileArticleTitle->exists() && !$conflictPolicy) {
         echo wfMsg('smw_ti_articleNotUpdated', $fileArticleTitle->getFullText()) . "\n";
         $article = new Article($fileArticleTitle);
         $article->doEdit($article->getContent() . "\n[[WasIgnoredDuringTermImport::" . $termImportName . "| ]]", wfMsg('smw_ti_creationComment'));
         return $this->createCallBackResult(true, array(array('id' => SMW_GARDISSUE_UPDATE_SKIPPED, 'title' => $fileArticleTitle->getFullText())));
     } else {
         if ($fileArticleTitle->exists()) {
             $termAnnotations['updated'][] = $termImportName;
             $updated = true;
         } else {
             $termAnnotations['added'][] = $termImportName;
             $updated = false;
         }
     }
     // outcommented because the extra attachments mapping policy does not exist anymore
     // $mappingPolicy = Title::newFromText($attachmentMP);
     // if(!$mappingPolicy->exists()){
     // 	throw new Exception("The attachment mapping policy \"".$attachmentMP."\" does not exist.");
     //
     // 	return $this->createCallBackResult(false,
     // 	array(array('id' => SMW_GARDISSUE_MAPPINGPOLICY_MISSING,
     // 		'title' => $attachmentMP)));
     // }
     $fileNameArray = explode(".", $fileName);
     $ext = $fileNameArray[count($fileNameArray) - 1];
     $fileFullPath = $smwgDIIP . '/specials/TermImport/DAL/attachments/' . $fileName;
     $mFileProps = File::getPropsFromPath($fileFullPath, $ext);
     $local = wfLocalFile($fileName);
     if ($local == null) {
         return $this->createCallBackResult(false, array(array('id' => SMW_GARDISSUE_CREATION_FAILED, 'title' => $fileArticleTitle->getFullText())));
     }
     $termAnnotations = "\n\n\n" . $tiBot->createTermAnnotations($termAnnotations);
     $status = $local->upload($fileFullPath, wfMsg('smw_ti_creationComment'), "", File::DELETE_SOURCE, $mFileProps);
     if (isset($status->failureCount) && $status->failureCount > 0) {
         throw new Exception("The file \"" . $fileFullPath . "\" could not be uploaded.");
         return $this->createCallBackResult(false, array(array('id' => SMW_GARDISSUE_CREATION_FAILED, 'title' => $fileArticleTitle->getFullText())));
     }
     // outcommented because the extra attachments mapping policy does not exist anymore
     // $mappingPolicy = new Article($mappingPolicy);
     // $mappingPolicy = $mappingPolicy->getContent();
     //
     // $term = array();
     // if(trim($mailFrom != "")){
     // 	$term["FROM"] = array();
     // 	$term["FROM"][] = array("value" => $mailFrom);
     // }
     // if(trim($mailId != "")){
     // 	$term["MESSAGE_ID"] = array();
     // 	$term["MESSAGE_ID"][] = array("value" => $mailId);
     // }
     // if(trim($mailDate != "")){
     // 	$term["DATE"] = array();
     // 	$term["DATE"][] = array("value" => $mailDate);
     // }
     //
     // if($extraContent != ""){
     // 	$sxe = new SimpleXMLElement("<vc>".
     // 		htmlspecialchars_decode($extraContent)."</vc>", LIBXML_NOCDATA);
     // 	foreach($sxe->children() as $property => $value){
     // 		$term[strtoupper($property)] = array();
     // 		$term[strtoupper($property)][] = array("value" => $value);
     // 	}
     // }
     $content = "";
     $local->load();
     global $smwgEnableUploadConverter;
     echo "UCONV\n";
     if ($smwgEnableUploadConverter) {
         $fileContent = UploadConverter::getFileContent($local);
         $content = $fileContent;
         //echo("\n\n####\n".substr($fileContent,0,200));
         if (strlen($fileContent) > 0) {
             // 	$term["CONTENT"] = array();
             // 	$term["CONTENT"][] = array("value" => $fileContent);
         }
     }
     // $content = $tiBot->createContent($term, $mappingPolicy);
     echo "\n\n###title\n" . $fileArticleTitle->getFullText();
     echo "\n\n###content\n" . substr($fileContent, 0, 300);
     $fileArticleTitle = Title::newFromText($fileArticleTitle->getText(), $fileArticleTitle->getNamespace());
     $article = new Article($fileArticleTitle);
     $result = $article->doEdit(ltrim($content . $termAnnotations), wfMsg('smw_ti_creationComment'));
     echo "\n\n###result\n" . print_r($result, true);
     echo $updated == true ? " updated\n" : " created.\n";
     if ($updated) {
         return $this->createCallBackResult(true, array(array('id' => SMW_GARDISSUE_UPDATED_ARTICLE, 'title' => $fileArticleTitle->getFullText())));
     } else {
         return $this->createCallBackResult(true, array(array('id' => SMW_GARDISSUE_ADDED_ARTICLE, 'title' => $fileArticleTitle->getFullText())));
     }
 }