public function ShowAction($id = '') { global $CONFIG; $id += 0; if (!$id) { throw new ApplicationException("404 File Not Found"); } $size = reqs('size'); $is_preview = reqi('preview'); if ($is_preview) { $item = $this->model->one($id); if ($item['is_image']) { $this->model->transmit_file($id, $size, 'inline'); } else { #if it's not an image and requested preview - return std image $filepath = $CONFIG['site_root'] . '/img/att_file.png'; # TODO move to web.config or to model? header('Content-type: ' . UploadUtils::get_mime4ext($item['ext'])); $fp = fopen($filepath, 'rb'); fpassthru($fp); } } else { $this->model->transmit_file($id, $size, 'inline'); } }
public function run() { //if (Yii::app()->request->isAjaxRequest) { if (isset($_REQUEST['fid'])) { // Delete from database $file = File::model()->findByPk($_REQUEST['fid']); if (isset($file)) { if ($file->delete()) { // Delete file UploadUtils::deleteFile($file, SimpleUploadWidget::$fileDir); $result["result"] = 0; } else { $result["result"] = -1; $result["message"] = Yii::t('upload', 'Could not delete file from db'); } } else { $result["result"] = -1; $result["message"] = Yii::t('upload', 'No file with that fid'); } } else { $result["result"] = -1; $result["message"] = Yii::t('upload', 'There is no file id (nor db and no session)'); } echo CJSON::encode($result); exit(0); // To avoid loggers append things to request //} }
public function run() { if (isset($_REQUEST['fid']) && is_numeric($_REQUEST['fid'])) { // Delete from database $file = File::model()->findByPk($_REQUEST['fid']); if (isset($file)) { if ($file->delete()) { // Delete file UploadUtils::deleteFile($file, PlUploadWidget::$fileDir); $result["result"] = 0; } else { $result["result"] = -1; $result["message"] = Yii::t('upload', 'Could not delete file from db'); } } else { $result["result"] = -1; $result["message"] = Yii::t('upload', 'No file with that fid'); } } elseif (isset($_REQUEST['sid']) && is_numeric($_REQUEST['sid'])) { // Delete from session $sessionFiles = Yii::app()->session['temp_files']; $file = File::buildFromArray($sessionFiles[$_REQUEST['sid']]); unset($sessionFiles[$_REQUEST['sid']]); Yii::app()->session['temp_files'] = $sessionFiles; // Delete file UploadUtils::deleteFile($file, PlUploadWidget::$tempDir); $result["result"] = 0; } else { $result["result"] = -1; $result["message"] = Yii::t('upload', 'There is no file id (nor db and no session)'); } echo CJSON::encode($result); exit(0); // To avoid loggers append things to request }
private function _deleteTempAvatarFiles($uid) { $files = $this->_getTempAvatarFiles($uid); $path = UploadUtils::getTempAvatarPath(); foreach ($files as $fileName) { FileUtils::safeDeleteFile($path . '/' . $fileName); } }
/** File list */ public function run() { $model = $this->getOwner(); if (isset($model)) { // Temporal files in session + files associated to the model $tempFiles = UploadUtils::getSessionFiles(); $files = UploadUtils::findFiles(get_class($this->model), $this->model->getPrimaryKey(), $this->tag); $files = array_merge($files, $tempFiles); $this->getController()->renderPartial('ext.upload.plupload.views.fileList', array('files' => $files)); } elseif (isset($_REQUEST['entity']) && isset($_REQUEST['EXid'])) { $files = UploadUtils::findFiles($_REQUEST['entity'], $_REQUEST['EXid']); $this->getController()->renderPartial('ext.upload.plupload.views.fileList', array('files' => $files)); } }
protected function registerScripts() { $cs = Yii::app()->getClientScript(); $cs->registerCoreScript('jquery'); $assetsDir = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets'; $this->assetsUrlBase = Yii::app()->getAssetManager()->publish($assetsDir); $cs->registerCssFile($this->assetsUrlBase . '/magazine.css'); $cs->registerScriptFile($this->assetsUrlBase . '/swfobject.js'); $cs->registerScriptFile($this->assetsUrlBase . '/flippingbook.js'); $fileBaseUrl = UploadUtils::getUrl(UploadWidget::$fileDir); $js = "flippingBook.pages = ["; foreach ($this->files as $file) { $js .= '"' . $fileBaseUrl . '/' . $file->filename . '",'; } $js .= "];"; $js .= "flippingBook.zoomPages = ["; foreach ($this->files as $file) { $js .= '"' . $fileBaseUrl . '/' . $file->filename . '",'; } $js .= "];"; $js .= <<<EOF //flippingBook.contents = [ // [ "Portada", 1 ] //]; // define custom book settings here flippingBook.stageWidth = "100%"; flippingBook.stageHeight = "650px"; flippingBook.settings.backgroundImage = "{$this->assetsUrlBase}/bookBackground.jpg"; flippingBook.settings.pageBackgroundColor = 0xCCCCCC; flippingBook.settings.zoomUIColor = 0x956EB5; // default settings can be found in the flippingbook.js file flippingBook.create(); swfobject.embedSWF( "{$this->assetsUrlBase}/flippingBook.swf", flippingBook.containerId, flippingBook.stageWidth, flippingBook.stageHeight, "8.0.0", "{$this->assetsUrlBase}/expressInstall.swf", flippingBook.settings, {allowScriptAccess: "always", bgcolor: "#" + flippingBook.settings.backgroundColor.toString( 16 ), wmode: "transparent" }); EOF; $cs->registerScript("magazine", $js); }
public function run() { //UploadUtils::clearSessionFiles(); // $sessionFiles = UploadUtils::getSessionFiles(); // $file = new File; // $file->entity = "amparo"; // UploadUtils::addFileToSession($file); $sessionFiles = UploadUtils::getSessionFiles(); print "<h1>Debug Session</h1>"; print "\n<hr/>"; print_r($sessionFiles); print "\n<hr/>"; foreach ($sessionFiles as $file) { print $file; print "\n<br/>"; } exit(0); }
private function _runAction($res, $uid) { ($imageData = file_get_contents('php://input')) === false && ($imageData = $GLOBALS['HTTP_RAW_POST_DATA']); //$imageData = file_get_contents('http://appbyme.com/mobcentACA/resource/images/logo.jpg'); if (!empty($imageData)) { if (($savePath = UploadUtils::getTempAvatarPath()) != '') { $fileName = sprintf('%s/avatar_%s.jpg', $savePath, $uid); if (($pfile = fopen($fileName, 'wb')) != false) { if (fwrite($pfile, $imageData) !== false) { $image = $this->_uploadAvatarByUcenter($uid, $fileName, $imageData); } fclose($pfile); FileUtils::safeDeleteFile($fileName); if (!empty($image)) { return array_merge($res, array('icon_url' => '', 'pic_path' => $image)); } } } } return WebUtils::makeErrorInfo_oldVersion($res, WebUtils::t('上传文件失败')); }
public function SaveAction($form_id) { $id = $form_id + 0; $item = req('item'); if (!is_array($item)) { $item = array(); } $files = UploadUtils::get_posted_files('file1'); try { $this->Validate($id, $item, $files); #load old record if necessary #$item_old = $this->model->one($id); $itemdb = FormUtils::form2dbhash($item, $this->save_fields); if (!strlen($itemdb["iname"])) { $itemdb["iname"] = 'new file upload'; } $is_add = $id == 0; $id = $this->model_add_or_update($id, $itemdb); #Proceed upload if (count($files)) { $this->model->upload($id, $files[0], $is_add); } logger($this->fw->get_response_expected_format()); if ($this->fw->get_response_expected_format() == 'json') { $item = $this->model->one($id); return array('success' => true, 'id' => $id, 'item' => $item, 'url' => $this->model->get_url_direct($item)); } else { fw::redirect($this->base_url . '/' . $id . '/edit'); } } catch (ApplicationException $ex) { logger($this->fw->get_response_expected_format()); logger($ex->getMessage()); if ($this->fw->get_response_expected_format() == 'json') { return array('success' => false, 'err_msg' => $ex->getMessage(), 'id' => $id); } else { $this->set_form_error($ex->getMessage()); $this->route_redirect("ShowForm"); } } }
private function _doUpload($res, $type) { $config = WebUtils::getMobcentConfig('misc'); $path = $config['apnsCertfilePath']; $certfileAPNs = $path . '/' . $config['apnsCertfileName']; if ($type == 'add_certfile_apns') { $password = (string) $_POST['passphrase']; if (UploadUtils::makeBasePath($path)) { if (!empty($_FILES) && count($_FILES) && is_uploaded_file($_FILES['file']['tmp_name']) && !$_FILES['file']['error']) { FileUtils::saveFile($certfileAPNs, file_get_contents($_FILES['file']['tmp_name'])); AppbymeConfig::setAPNsCertfilePassword($password); } else { $res = $this->makeErrorInfo($res, WebUtils::t('上传失败')); } } } else { if ($type == 'del_certfile_apns') { FileUtils::safeDeleteFile($certfileAPNs); } } return $res; }
private function _transMessage($msgString) { $msg = array('type' => 'text', 'content' => ''); $matches = array(); preg_match_all('/<img.*?src="(.*?)".*?\\/>/s', $msgString, $matches, PREG_SET_ORDER); if (!empty($matches)) { foreach ($matches as $match) { $match[1] = WebUtils::getHttpFileName($match[1]); if (strpos($match[0], 'static/image/smiley') !== false || strpos($match[0], 'mobcent/app/data/phiz') !== false) { $msgString = str_replace($match[0], sprintf('[mobcent_phiz=%s]', $match[1]), $msgString); } else { $msg['type'] = 'image'; $msgString = ImageUtils::getThumbImage($match[1]); break; } } } $matches = array(); preg_match_all('/<a href="(.*?)".*?>(.*?)<\\/a>/s', $msgString, $matches, PREG_SET_ORDER); if (!empty($matches)) { foreach ($matches as $match) { $match[1] = WebUtils::getHttpFileName($match[1]); if (strpos($match[0], UploadUtils::getUploadAudioBaseUrlPath()) !== false) { $msg['type'] = 'audio'; $msgString = $match[1]; break; } else { // $msgString = str_replace($match[0], sprintf('[mobcent_url=%s]%s[/mobcent_url]', $match[1], $match[2]), $msgString); $msgString = str_replace($match[0], sprintf(' %s %s ', $match[2], $match[1]), $msgString); } } } $msg['content'] = WebUtils::emptyHtml($msgString); return $msg; }
if (!empty($_SERVER['HTTP_X_NUGET_APIKEY'])) { HttpUtils::ApiError('403', 'Invalid request'); die; } $message = ""; ?> <html><body> <script type="text/javascript"> <?php if (!$loginController->IsLoggedIn) { ?> parent.packagesUploadControllerCallback("fail-unathorized","none","none"); <?php } else { if (UploadUtils::IsUploadRequest()) { $uploader = new UploadUtils(Settings::$PackagesRoot, array("nupkg"), Settings::$MaxUploadBytes); $result = $uploader->Upload("fileName"); $fileName = basename($result["name"], ".nupkg"); $message = ""; if ($result["hasError"] == true) { $message = "Failed uploading '" . $result["name"] . "'."; $message .= "Error is: " . $result["errorMessage"]; if ($result["errorCode"] != null) { $message .= "Error code is:" . $result["errorCode"] . "."; } unlink($result["destination"]); ?> parent.packagesUploadControllerCallback(false,"none","none","<?php echo $result["errorMessage"]; ?> ");
try { if (empty($_SERVER['HTTP_X_NUGET_APIKEY'])) { HttpUtils::ApiError('403', 'Invalid API key'); die; } $token = strtoupper(trim(trim($_SERVER['HTTP_X_NUGET_APIKEY'], "{"), "}")); $db = new UserDb(); $os = new ObjectSearch(); $os->Parse("Token eq '{" . $token . "}'", $db->GetAllColumns()); $users = $db->GetAllRows(1, 0, $os); if (sizeof($users) != 1) { HttpUtils::ApiError('403', 'Invalid API key'); die; } $user = $users[0]; $uploader = new UploadUtils(Settings::$PackagesRoot, array("nupkg"), Settings::$MaxUploadBytes, true); $uploader->allowAll = true; $result = $uploader->Upload("package"); if ($result['hasError']) { throw new Exception($result['errorCode']); } $fileName = basename($result["name"], ".nupkg"); $nugetReader = new NugetManager(); $parsedNuspec = $nugetReader->LoadNuspecFromFile($result["destination"]); $parsedNuspec->UserId = $user->Id; $nuspecData = $nugetReader->SaveNuspec($result["destination"], $parsedNuspec); // All done! header('HTTP/1.1 201 Created'); } catch (Exception $ex) { if (array_key_exists("destination", $result)) { unlink($result["destination"]);
/** Delete all files associated to this model */ public function afterDelete() { UploadUtils::deleteFiles($this->getOwner(), self::$fileDir); }
public function transmit_file($id, $size = '', $disposition = 'attachment') { $item = $this->one($id); #validation if (!count($item)) { throw new ApplicationException('No file specified'); } if ($item['status'] != 0) { throw new ApplicationException('Access Denied'); } $size = UploadUtils::check_size($size); $filepath = $this->get_upload_path($id, $item['ext'], $size); $filename = str_replace('"', "'", $item['iname']); #quote filename header('Content-type: ' . UploadUtils::get_mime4ext($item['ext'])); header("Content-Length: " . filesize($filepath)); header('Content-Disposition: ' . $disposition . '; filename="' . $filename . '"'); #logger('transmit file '.$filepath." $id, $size, $disposition, ".UploadUtils::get_mime4ext($item['ext'])); $fp = fopen($filepath, 'rb'); fpassthru($fp); }
public function remove_upload($id, $ext) { UploadUtils::cleanup_upload($id, $this->get_upload_basedir(), $ext); }
private function _getPathFileName($type, $fileName) { $res = array('path' => '', 'file' => ''); $tempPath = $this->_getTempPath(); $urlBasePath = ''; switch ($type) { case 'audio': $urlBasePath = UploadUtils::getUploadAudioBaseUrlPath($tempPath); break; case 'image': $urlBasePath = UploadUtils::getUploadImageBaseUrlPath($tempPath); break; default: break; } $res['path'] = $urlBasePath . '/' . $tempPath; $res['file'] = $this->_getRondomFileName($type, $fileName); return $res; }
/** * 上传图片 * * @author HanPengyu * @access public * * @return mixed 返回状态码和信息. */ public function actionUploadIcon($type = 'uidiy') { $res = WebUtils::initWebApiResult(); // 没有上传的文件 if (empty($_FILES)) { self::makeResponse(0, '没有上传的文件,或者选择的文件太大!'); } // 创建放置图片的文件夹 $date = date('Ym/d', time()); $path = MOBCENT_UPLOAD_PATH . '/' . $type . '/' . $date; if (UploadUtils::makeBasePath($path) == '') { self::makeResponse(0, '上传目录不可写!'); } foreach ($_FILES as $file) { $file['name'] = strip_tags($file['name']); $ext = FileUtils::getFileExtension($file['name'], 'jpg'); // 检测 $imageRes = $this->checkUpload($res, $file); if (!$imageRes['errCode']) { self::makeResponse(0, $imageRes['errMsg']); } $saveName = FileUtils::getRandomUniqueFileName($path); $fileName = $saveName . '.' . $ext; if (!move_uploaded_file($file['tmp_name'], $fileName)) { self::makeResponse(0, '上传图片失败!'); } $fileName = $this->dzRootUrl . '/data/appbyme/upload/' . $type . '/' . $date . '/' . basename($fileName); ImageUtils::getThumbImageEx($fileName, 10, false, false, true); self::makeResponse(1, $fileName); } }
/** * 获取附件路径 如:data/appbyme/upload/image/201412/02 * * @param mixed $type 附件的类型 * * @return mixed Value. */ private function _getPathFileName($type) { $path = ''; $tempPath = $this->_getTempPath(); $urlBasePath = ''; switch ($type) { case 'audio': $urlBasePath = UploadUtils::getUploadAudioBaseUrlPath($tempPath); break; case 'image': $urlBasePath = UploadUtils::getUploadImageBaseUrlPath($tempPath); break; default: break; } $path = $urlBasePath . '/' . $tempPath; return $path; }
public function run() { // Settings // --------------------- $targetDir = UploadWidget::$tempDir; // --------------------- $cleanupTargetDir = false; // Remove old files $maxFileAge = 60 * 60; // Temp file age in seconds // 5 minutes execution time @set_time_limit(5 * 60); // usleep(5000); // Get parameters $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0; $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0; $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : ''; // Create unique filename $fileName = UploadUtils::createUniquefilename($fileName, $targetDir); // Create target dir if (!file_exists($targetDir)) { @mkdir($targetDir); } // Remove old temp files if (is_dir($targetDir) && ($dir = opendir($targetDir))) { while (($file = readdir($dir)) !== false) { $filePath = $targetDir . DIRECTORY_SEPARATOR . $file; // Remove temp files if they are older than the max age if (preg_match('/\\.tmp$/', $file) && filemtime($filePath) < time() - $maxFileAge) { @unlink($filePath); } } closedir($dir); } else { die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}'); } // Look for the content type header if (isset($_SERVER["HTTP_CONTENT_TYPE"])) { $contentType = $_SERVER["HTTP_CONTENT_TYPE"]; } if (isset($_SERVER["CONTENT_TYPE"])) { $contentType = $_SERVER["CONTENT_TYPE"]; } if (strpos($contentType, "multipart") !== false) { if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) { // Open temp file $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = fopen($_FILES['file']['tmp_name'], "rb"); if ($in) { while ($buff = fread($in, 4096)) { fwrite($out, $buff); } } else { die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); } fclose($out); unlink($_FILES['file']['tmp_name']); } else { die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } } else { die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'); } } else { // Open temp file $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = fopen("php://input", "rb"); if ($in) { while ($buff = fread($in, 4096)) { fwrite($out, $buff); } } else { die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); } fclose($out); } else { die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } } // --------------------- // Save the file to db $file = new File(); //$file->entity = get_class($this->getOwner()); $file->EXid = -1; $file->uid = Yii::app()->user->id; $file->tag = $_REQUEST['tag']; $file->weight = 0; $file->timestamp = time(); // Because flash labels everything with app/octet-stream // $file->filemime = $_FILES['Filedata']['type']; $file->filemime = CFileHelper::getMimeTypeByExtension($targetDir . DIRECTORY_SEPARATOR . $fileName); $file->filesize = filesize($targetDir . DIRECTORY_SEPARATOR . $fileName); $file->status = File::STATUS_TEMP; $file->filename = $fileName; // Store it in session UploadUtils::addFileToSession($file); // --------------------- // Return JSON-RPC response die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'); }
title="<?php echo $file->filename; ?> (<?php echo round($file->filesize / 1024, 2); ?> Kb)"> <?php if (UploadUtils::isImageFileMime($file->filemime)) { ?> <img height="50px" alt="<?php echo $file->filename; ?> " src="<?php echo UploadUtils::getUrl($fileDir) . "/" . $file->filename; ?> "/> <?php } else { ?> <?php echo $file->filename; ?> <?php } ?> </a> <?php } ?>
/** Creates a unique filename in the directory specified adding a counter suffix */ public static function createUniquefilename($basename, $directory) { $basename = UploadUtils::escapeStrangeChars($basename); $dest = $directory . DIRECTORY_SEPARATOR . $basename; if (file_exists($dest)) { // Destination file already exists, generate an alternative. $pos = strrpos($basename, '.'); if ($pos) { $name = substr($basename, 0, $pos); $ext = substr($basename, $pos); } else { $name = $basename; } $counter = 0; do { $dest = $directory . '/' . $name . '_' . $counter++ . $ext; } while (file_exists($dest)); } return basename($dest); }
<?php /** * Lista básica de thumbs clickable para verlos * @param @files */ $fileBaseUrl = UploadUtils::getUrl(UploadWidget::$fileDir); $cs = Yii::app()->getClientScript(); $cs->registerCss('fancyBoxImageViewer', ' .defaultItem { background-color:#fff; position: relative; padding: 4px 4px 2px 4px; margin:6px; border: 1px solid #999; /*outline: 1px solid #000;*/ -moz-box-shadow:0 0 4px 0 #333; -webkit-box-shadow: 0 0 4px #000; } .defaultItem .mask-gallery { overflow:hidden; position: relative; } '); ?> <div id="defaultImageViewer"> <?php foreach ($files as $file) {
private function _runAction($res, $uid) { if (empty($_FILES['userAvatar']['tmp_name'])) { return WebUtils::makeErrorInfo_oldVersion($res, WebUtils::t('请选择上传的文件')); } if ($_FILES['userAvatar']['error'] > 0) { return WebUtils::makeErrorInfo_oldVersion($res, WebUtils::t('上传文件失败')); } if ($_FILES['userAvatar']['size'] > 2000000) { return WebUtils::makeErrorInfo_oldVersion($res, WebUtils::t('上传文件太大')); } $savePath = UploadUtils::getTempAvatarPath(); $fileName = sprintf('%s/avatar_%s.jpg', $savePath, $uid); if (move_uploaded_file($_FILES['userAvatar']['tmp_name'], $fileName)) { $imageData = file_get_contents($fileName); $image = $this->_uploadAvatarByUcenter($uid, $fileName, $imageData); FileUtils::safeDeleteFile($fileName); if (!empty($image)) { return array_merge($res, array('icon_url' => '', 'pic_path' => $image)); } // WebUtils::httpRequestAppAPI('user/saveavatar', array('avatar' => $image, 'hacker_uid' => 1)); // die(); } return WebUtils::makeErrorInfo_oldVersion($res, WebUtils::t('上传文件失败')); }