Legacy code - returns array [id, sha256]

Returns false for any number of failures, for better detail, use
validateUpload() before calling this to do the actual upload.
494686
public static function uploadFileToBlob($FILE_DESCRIPTOR, $SAFETY_CHECK=true)
    {
        global $CFG, $CONTEXT, $LINK, $PDOX;

        $test_key = self::isTestKey($CONTEXT->key);

        if( $FILE_DESCRIPTOR['error'] == 1) return false;

        if( $FILE_DESCRIPTOR['error'] == 0)
        {
            $filename = basename($FILE_DESCRIPTOR['name']);
            if ( $SAFETY_CHECK && ! self::safeFileSuffix($filename) ) {
                return false;
            }

            $blob_id = null;
            $blob_name = null;
            $sha256 = hash_file('sha256', $FILE_DESCRIPTOR['tmp_name']);

            // Check if the blob is in the single instance store
            $stmt = $PDOX->queryDie(
                "SELECT blob_id FROM {$CFG->dbprefix}blob_blob WHERE blob_sha256 = :SHA",
                array(":SHA" => $sha256)
            );
            $row = $stmt->fetch(\PDO::FETCH_ASSOC);
            if ( $row !== false ) {
                error_log("Already had instance of $filename");
                $blob_id = $row['blob_id']+0;  // Make sure the id is an integer
            }

            // Don't store test_key (i.e. 12345) as new blobs on disk
            if (! $blob_id && isset($CFG->dataroot) && $CFG->dataroot ) {
                $blob_folder = BlobUtil::mkdirSha256($sha256);
                if ( $blob_folder ) {
                    $blob_name =  $blob_folder . '/' . $sha256;
                    if ( file_exists( $blob_name ) ) {
                        error_log("Already had file on disk $filename => $blob_name");
                    } else if ( $test_key ) { // Don't add to the disk
                        $blob_name = null;
                    } else { // Put the file into the blob space if we can
                        if ( ! (move_uploaded_file($FILE_DESCRIPTOR['tmp_name'],$blob_name))) {
                            error_log("Move fail $filename to $blob_name ");
                            $blob_name = null;
                        }
                    }
                }
            }

            // If not on disk store in the single instance table
            if (! $blob_id && ! $blob_name ) {
                $fp = fopen($FILE_DESCRIPTOR['tmp_name'], "rb");
                $stmt = $PDOX->prepare("INSERT INTO {$CFG->dbprefix}blob_blob
                    (blob_sha256, content, created_at)
                    VALUES (?, ?, NOW())");

                $stmt->bindParam(1, $sha256);
                $stmt->bindParam(2, $fp, \PDO::PARAM_LOB);
                // $stmt->bindParam(5, $data, \PDO::PARAM_LOB);
                $PDOX->beginTransaction();
                $stmt->execute();
                $blob_id = 0+$PDOX->lastInsertId();
                $PDOX->commit();
                fclose($fp);
            }

            // Blob is safe somewhere, insert the file record with pointers
            if ( $blob_id || $blob_name ) {
                $stmt = $PDOX->prepare("INSERT INTO {$CFG->dbprefix}blob_file
                    (context_id, link_id, file_sha256, file_name, contenttype, path, blob_id, created_at)
                    VALUES (:CID, :LID, :SHA, :NAME, :TYPE, :PATH, :BID, NOW())");
                $stmt->execute(array(
                    ":CID" => $CONTEXT->id,
                    ":LID" => $LINK->id,
                    ":SHA" => $sha256,
                    ":NAME" => $filename,
                    ":TYPE" => $FILE_DESCRIPTOR['type'],
                    ":PATH" => $blob_name,
                    ":BID" => $blob_id
                ));
                $id = 0+$PDOX->lastInsertId();
                return array($id, $sha256);
            }

            // Somehow we were unable to store the blob
            error_log("Error: Unable to store blob $filename ".$CONTEXT->id."\n");
            return false;
        }
        return false;
    }
1360743
def validate_id(tx_body):
        
        # NOTE: Remove reference to avoid side effects
        tx_body = deepcopy(tx_body)
        try:
            proposed_tx_id = tx_body['id']
        except KeyError:
            raise InvalidHash('No transaction id found!')

        tx_body['id'] = None

        tx_body_serialized = Transaction._to_str(tx_body)
        valid_tx_id = Transaction._to_hash(tx_body_serialized)

        if proposed_tx_id != valid_tx_id:
            err_msg = ("The transaction's id '{}' isn't equal to "
                       "the hash of its body, i.e. it's not valid.")
            raise InvalidHash(err_msg.format(proposed_tx_id))
978059
function(id) {
            var size = options.getSize(id),
                name = options.getName(id);

            log("All chunks have been uploaded for " + id + " - finalizing....");
            handler.finalizeChunks(id).then(
                function(response, xhr) {
                    log("Finalize successful for " + id);

                    var normaizedResponse = upload.normalizeResponse(response, true);

                    options.onProgress(id, name, size, size);
                    handler._maybeDeletePersistedChunkData(id);
                    upload.cleanup(id, normaizedResponse, xhr);
                },
                function(response, xhr) {
                    var normalizedResponse = upload.normalizeResponse(response, false);

                    log("Problem finalizing chunks for file ID " + id + " - " + normalizedResponse.error, "error");

                    if (
                        normalizedResponse.reset ||
                        (xhr && options.chunking.success.resetOnStatus.indexOf(xhr.status) >= 0)
                    ) {
                        chunked.reset(id);
                    }

                    if (!options.onAutoRetry(id, name, normalizedResponse, xhr)) {
                        upload.cleanup(id, normalizedResponse, xhr);
                    }
                }
            );
        }
1095517
def validate_upload_file(ctx, opts, owner, repo, filepath, skip_errors):
    """"""
    filename = click.format_filename(filepath)
    basename = os.path.basename(filename)

    click.echo(
        "Checking %(filename)s file upload parameters ... "
        % {"filename": click.style(basename, bold=True)},
        nl=False,
    )

    context_msg = "Failed to validate upload parameters!"
    with handle_api_exceptions(
        ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
    ):
        with maybe_spinner(opts):
            md5_checksum = validate_request_file_upload(
                owner=owner, repo=repo, filepath=filename
            )

    click.secho("OK", fg="green")

    return md5_checksum
1297794
def _post_md5_skip_on_check(self, key, md5_match):
        # type: (Uploader, str, bool) -> None
        
        with self._md5_meta_lock:
            src, rfile = self._md5_map.pop(key)
        uid = blobxfer.operations.upload.Uploader.create_unique_id(src, rfile)
        if md5_match:
            with self._upload_lock:
                self._upload_set.remove(uid)
                self._upload_total -= 1
            if self._general_options.dry_run:
                logger.info('[DRY RUN] MD5 match, skipping: {} -> {}'.format(
                    src.absolute_path, rfile.path))
        else:
            if self._general_options.dry_run:
                with self._upload_lock:
                    self._upload_set.remove(uid)
                    self._upload_total -= 1
                logger.info('[DRY RUN] MD5 mismatch, upload: {} -> {}'.format(
                    src.absolute_path, rfile.path))
            else:
                self._add_to_upload_queue(src, rfile, uid)
1161745
protected function getClientChecksum()
    {
        $checksumHeader = $this->getRequest()->header('Upload-Checksum');

        if (empty($checksumHeader)) {
            return '';
        }

        list($checksumAlgorithm, $checksum) = explode(' ', $checksumHeader);

        $checksum = base64_decode($checksum);

        if ( ! in_array($checksumAlgorithm, hash_algos()) || false === $checksum) {
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
        }

        return $checksum;
    }
124566
function resendAuthCode($validationHash, $identifierType)
    {
        $response = $this->call( new Command\Recover\ResendCode($validationHash, $identifierType) );
        if ( $ex = $response->hasException() )
            throw $ex;

        $r = $response->expected();
        $r = ($r instanceof iDataEntity) ? $r->get('result') : $r;
        return $r;
    }
103217
protected function verifyUploadSize() : bool
    {
        $maxUploadSize = $this->getMaxUploadSize();

        if ($maxUploadSize > 0 && $this->getRequest()->header('Upload-Length') > $maxUploadSize) {
            return false;
        }

        return true;
    }
309867
private final boolean verify() throws Exception {
        String dataStr = this.getUserData().toString();
        byte[] data = Base64Coder.getBytes(dataStr);
        return verify(data, signature, publicKey);
    }
1093109
function createFilenameHash(uploadDir, files) {
    let hashPath = path.resolve(uploadDir, 'name.json');
    let hashContent;
    let result = [];

    if (hashFileExist || fs.existsSync(hashPath)) {
      try {
        let content = fs.readFileSync(hashPath, 'utf8');
        hashContent = JSON.parse(content);
      } catch (err) {
        debug('get hash file failed:' + err);
      }
    } else {
      hashContent = {};
    }

    for (let item in files) {
      let fileName = files[item].name;
      let hashName = getUniqueId(0, hashContent, fileName);

      let fileItem = getFileItem(files[item], uploadDir)
      hashContent[hashName] = fileItem;
      result.push(util._extend(fileItem, {
        filename: hashName
      }))
    }

    try {
      let file = JSON.stringify(hashContent, null, 2);
      fs.writeFileSync(hashPath, file);
    } catch (err) {
      debug('write hash file failed:' + err);
    }

    hashFileExist = true;

    return result;
  }
310532
private UploadResult uploadInOneChunk() {
        PutObjectResult putObjectResult = s3.putObject(origReq);

        UploadResult uploadResult = new UploadResult();
        uploadResult.setBucketName(origReq.getBucketName());
        uploadResult.setKey(origReq.getKey());
        uploadResult.setETag(putObjectResult.getETag());
        uploadResult.setVersionId(putObjectResult.getVersionId());
        return uploadResult;
    }
1056518
def valid?(csdl, boolResponse = true)
      requires({ :csdl => csdl })
      res = DataSift.request(:POST, 'validate', @config, :csdl => csdl )
      boolResponse ? res[:http][:status] == 200 : res
    end
575919
function sha256(data) {
    if (!data.byteLength) {
        return Promise.resolve(ByteUtils.arrayToBuffer(ByteUtils.hexToBytes(EmptySha256)));
    }
    if (subtle) {
        return subtle.digest({ name: 'SHA-256' }, data);
    } else if (nodeCrypto) {
        return new Promise(function(resolve) {
            var sha = nodeCrypto.createHash('sha256');
            var hash = sha.update(Buffer.from(data)).digest();
            resolve(hash.buffer);
        });
    } else {
        return Promise.reject(new KdbxError(Consts.ErrorCodes.NotImplemented, 'SHA256 not implemented'));
    }
}
1147517
def upload_verify(self, file_location, dataset=None):
        """"""

        path = '/api/1.0/upload/verify'
        query = 'doNotGenerateAdvanceReport=true&filePath={}'.format(file_location)
        if dataset:
            query = 'doNotGenerateAdvanceReport=true&filePath={}&datasetId={}'.format(file_location, dataset)

        return self._api_get(definition.UploadVerifyResponse, path, query)
425518
def _upload_simple(self, upload_info, _=None):
        

        upload_result = self._api.upload_simple(
            upload_info.fd,
            upload_info.name,
            folder_key=upload_info.folder_key,
            filedrop_key=upload_info.filedrop_key,
            path=upload_info.path,
            file_size=upload_info.size,
            file_hash=upload_info.hash_info.file,
            action_on_duplicate=upload_info.action_on_duplicate)

        logger.debug("upload_result: %s", upload_result)

        upload_key = upload_result['doupload']['key']

        return self._poll_upload(upload_key, 'upload/simple')
741389
public function upload()
    {
        $file = Input::file($this->field);
        if ( ! $this->validate($file)) {
            return false;
        }

        $originalFileName  = $file->getClientOriginalName();
        $encryptedFileName = $this->getUniqueFilename($originalFileName);
        $mimeType          = $file->getMimeType();

        $size = $file->getSize();
        if ($file->move($this->getDestination(), $encryptedFileName)) {
            $this->uploadedFileInfo = [
                $this->originalImageNameField => $originalFileName,
                $this->field                  => $encryptedFileName,
                $this->uploadDir              => $this->getUploadPath(),
                'size'                        => $size,
                'extension'                   => $file->getClientOriginalExtension(),
                'mime_type'                   => $mimeType,
            ];

            return true;
        }

        return false;
    }
554475
function getSha256Hash (stringToSign, format) {
	if(!format) {
		stringToSign = naclInstance.encode_utf8(stringToSign);
	} else if(format === 'utf8') {
		stringToSign = naclInstance.encode_utf8(stringToSign);
	} else if(format === 'hex') {
		stringToSign = naclInstance.from_hex(stringToSign);
	}

	return naclInstance.crypto_hash_sha256(stringToSign);
	// return crypto.createHash('sha256').update(stringToSign, format).digest();
}