/** * Sube el archivo a temporal * @return string */ public function upload($extenciones = array('kml', 'kmz')) { $correcto = true; $upload = new Zend_File_Transfer(); $upload->addValidator('Extension', false, $extenciones); $upload->addValidator('FilesSize', false, array('min' => '0.001kB', 'max' => '64MB')); $file = $upload->getFileInfo(); foreach ($file as $field_name => $file_data) { if (!$upload->isUploaded($field_name)) { $correcto = false; $retorno = array("correcto" => false, "mensaje" => "No se subio ningún archivo o estaba vacío"); } if (!$upload->isValid($field_name)) { $texto = "</br>"; $mensajes = $upload->getMessages(); foreach ($mensajes as $key => $txt) { $texto .= $txt . "</br>"; } $correcto = false; $retorno = array("correcto" => false, "mensaje" => "<b>El archivo es inválido</b>." . $texto); } $this->_setFileConfig($file_data["name"]); $this->_mime = $file_data["type"]; $this->_hash = $this->_ci->string_core->rand_string(20); $this->_target = $this->_dir_temp . $this->_hash . "." . $this->_file_ext; $upload->addFilter('Rename', array('target' => $this->_target, 'overwrite' => true)); } if ($correcto) { fb($upload->receive()); $retorno = $this->_saveToCache(); } return $retorno; }
public function uploadAction() { $request = $this->getRequest(); if (!$request->isPost()) { return; } $name = $this->_getParam('name', false); $upload = new Zend_File_Transfer(); $upload->addValidator('Count', false, 1); if (!$upload->isValid()) { return; } $upload->receive(); $file = $upload->getFileName(); $fp = fopen($file, "r"); if (!$fp) { return; } $mime = $upload->getMimeType(); if (!$name) { // get short name $name = $upload->getFileName(null, false); } $this->_storage->storeItem($name, $fp, array(Zend_Cloud_StorageService_Adapter_S3::METADATA => array("type" => $mime))); try { $this->_storage->storeMetadata($name, array("type" => $mime)); } catch (Zend_Cloud_OperationNotAvailableException $e) { // ignore it } return $this->_helper->redirector('index'); }
public function direct($exts = array('xml', 'csv', 'txt')) { $front = Zend_Controller_Front::getInstance(); $front->registerPlugin(new \Tid_Zend_Controller_Plugin_UploadMax()); // Frontend HACK if ($this->getRequest()->getParam('iframeHack', false)) { $h = Zend_Controller_Action_HelperBroker::getStaticHelper('Output'); $h->direct('json')->setContentType('text/html'); } // Preprocess mime types $mimes = array(); foreach ($exts as $ext) { if (!isset($this->_mimeTypes[$ext])) { throw new \Application\Exceptions\InvalidArgumentException("Unsupported extension {$ext}"); } if (!in_array($this->_mimeTypes[$ext], $mimes)) { $mimes[] = $this->_mimeTypes[$ext]; } } // Upload file $upload = new Zend_File_Transfer(); $mimes['headerCheck'] = true; $upload->addValidator('Count', true, array('min' => 1, 'max' => 1))->addValidator('Extension', true, $exts)->addValidator('MimeType', true, $mimes)->addValidator('Size', true, array('max' => '20MB')); // Validate file if (!$upload->isValid()) { throw new \Application\Exceptions\ValidateException('Invalid file', array('validationErrors' => $upload->getMessages(), 'entity' => 'file', 'code' => ValidationCodes::FILE_UPLOAD_ERR)); } if (!$upload->receive()) { throw new \Application\Exceptions\InvalidArgumentException('Could not receive file', ValidationCodes::FILE_UPLOAD_ERR); } return $upload; }
public function uploadAction() { $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $json = new ZendT_Json_Result(); try { $options = $this->getRequest()->getParam('options'); if ($options && !is_array($options)) { $options = unserialize($options); } /** * @var Zend_File_Transfer_Adapter_Http */ $uploads = new Zend_File_Transfer('Http', false, array('detectInfos' => false)); if ($options['extension'] == ZendT_Type_Blob::FILTER_EXECUTABLE) { $options['extension'] = array('text/php', 'text/x-php', 'text/asp', 'text/x-asp'); } if ($options['maxSize'] || $options['minSize']) { $uploads->addValidator('FilesSize', false, array('max' => $options['maxSize'], 'min' => $options['minSize'])); } if (is_array($options['validators'])) { array_merge($options['extension'], $options['validators']); } //$uploads->addValidator('ExcludeMimeType', false, $options['extension']); $uploads->receive(); if ($uploads->hasErrors()) { $message = $uploads->getMessages(); throw new ZendT_Exception_Information(current($message)); } else { } $infoFiles = $uploads->getFileInfo(); @($content = file_get_contents($infoFiles['file']['tmp_name'])); if ($content === false) { throw new ZendT_Exception_Error('Não foi possível armazenar o arquivo informado!'); } $_file = new ZendT_File($infoFiles['file']['name'], $content, $infoFiles['file']['type']); @unlink($infoFiles['file']['tmp_name']); $infoFile = $_file->toArrayJson(); $infoFile['size'] = $infoFiles['file']['size']; $json->setResult($infoFile); } catch (Exception $Ex) { $json->setException($Ex); } echo $json->render(); }
/** * 上传用户文件的action */ public function uploadUserDocAction() { $this->_helper->layout->disableLayout(); $doctype = $this->request->getParam('doctype'); $this->view->doctype = $doctype; $result = 0; if ($this->request->isPost()) { $upload = new Zend_File_Transfer(); $upload->addValidator('Size', false, 10240000); //10M $utilService = $this->_container->get('util'); $fileService = $this->_container->get('file'); $filename = $utilService->getFilename($upload->getFileName()); $extension = $fileService->getExtensionByFilename($filename); $destination = $utilService->getTmpDirectory() . DIRECTORY_SEPARATOR . uniqid(); $upload->addFilter('Rename', $destination); if ($upload->isValid()) { if ($upload->receive()) { $userModel = $this->getModel('user'); $mimetype = $upload->getMimeType(); if ($fileService->isAcceptedDocument($mimetype, $extension)) { $user = $userModel->getUserById($this->me->getId()); if ($user) { $doc = null; if ($doctype == \Angel_Model_User::FILETYPE_IDENTITY_FRONT || $doctype == \Angel_Model_User::FILETYPE_IDENTITY_BACK) { $doc = $userModel->addUserDoc($user, $doctype, $destination, $filename, $mimetype); } if ($doc) { $result = 1; $this->view->filename = $doc->filename; $this->view->path = $this->view->url(array('doctype' => $doctype, 'user_id' => $user->id, 'doc_id' => $doc->id), 'user-doc'); } } } else { // 上传的文件格式不接受 $result = 2; } } } } $this->view->result = $result; }
public function importSeasons() { $option = JRequest::getCmd('option'); $controller = JRequest::getCmd('controller'); // Check for request forgeries JRequest::checkToken() or die('Invalid Token'); $path = JPATH_ROOT . "/tmp"; $upload = new Zend_File_Transfer(); $upload->setDestination($path); $upload->addValidator('Extension', false, array("csv")); $errors = array(); $file = "products_seasons"; $info = $upload->getFileInfo($file); if ($upload->isUploaded($file)) { if (!$upload->isValid($file)) { foreach ($upload->getMessages() as $k => $v) { $errors[$k] = true; } } } if ($upload->receive()) { $mProduct = new EcwidgatewayModelProducts(); $mProduct->processSeasonsCsv($path . "/" . $info[$file]["name"]); $msg = "Данные импортированы"; } else { $errorMessages = array("Ошибка при загрузке файла"); foreach ($errors as $k => $v) { if (isset($errors[Zend_Validate_File_Extension::FALSE_EXTENSION])) { $errorMessages[] = JText::_("Недопустимое расширение файла"); } } $msg = implode("<p>", $errorMessages); } $link = 'index.php?option=' . $option . '&controller=' . $controller; $this->setRedirect($link, $msg); }
function addproductsAction() { $muser = new Admin_Model_Page(); $paginator = Zend_Paginator::factory($muser->option_page()); $paginator->setItemCountPerPage(10); $paginator->setPageRange(10); $currentPage = $this->_request->getParam('page', 1); $paginator->setCurrentPageNumber($currentPage); $this->view->books = $paginator; $system = new Admin_Model_Category(); $menu = $system->option_menu(); $this->view->bookss = $menu; $district = $system->option_dictrict(); $this->view->bokk = $district; if ($this->_request->isPost()) { $this->view->purifier = Zend_Registry::get('purifier'); $conf = HTMLPurifier_Config::createDefault(); $purifier = new HTMLPurifier($conf); $menu_id = $purifier->purify($this->_request->getParam('parent_id')); $title = $purifier->purify($this->_request->getParam('title')); $dis = $purifier->purify($this->_request->getParam('dis')); $key = $purifier->purify($this->_request->getParam('key')); $description = $purifier->purify($this->_request->getParam('description')); $home = $purifier->purify($this->_request->getParam('home')); $upload = new Zend_File_Transfer(); // $images=$upload->addValidator('IsImage', false, array('application/gif')); $images = $upload->addValidator('Extension', false, 'jpg,png,gif'); // if($images==true){ thongbao('Không đúng định dạng hình ảnh'); return;} $images = $upload->getFilename(); $images = basename($images); $url = khongdau($title); $random_digit = rand(00, 99999); $img = $url . "-" . $random_digit . $images; $filterRename = new Zend_Filter_File_Rename(array('target' => 'Upload/' . $img, 'overwrite' => false)); $upload->addFilter($filterRename); $upload->receive(); $position = $purifier->purify($this->_request->getParam('position')); $active = $purifier->purify($this->_request->getParam('active')); $content = $purifier->purify($this->_request->getParam('content')); $price = $purifier->purify($this->_request->getParam('price')); $state = $purifier->purify($this->_request->getParam('state')); $sales = $purifier->purify($this->_request->getParam('sales')); $code = $purifier->purify($this->_request->getParam('code')); $members = $purifier->purify($this->_request->getParam('members')); $dictrict_id = $purifier->purify($this->_request->getParam('dictrict_id')); $type = $purifier->purify($this->_request->getParam('type')); $category_id = $purifier->purify($this->_request->getParam('category_id')); $add = new Admin_Model_Products(); $add->insert_products($title, $description, $img, $content, $menu_id, $price, $state, $sales, $dis, $key, $position, $active, $home, $code, $members, $dictrict_id, $type, $category_id); } $this->view->idmenu = $this->_request->getParam('idmenu'); }
function postingAction() { $captcha = new Zend_Captcha_Image(); $vi = new Zend_View(); $base = $vi->baseurl(); $muser = new Admin_Model_Page(); $paginator = Zend_Paginator::factory($muser->option_page()); $paginator->setItemCountPerPage(10); $paginator->setPageRange(10); $currentPage = $this->_request->getParam('page', 1); $paginator->setCurrentPageNumber($currentPage); $this->view->books = $paginator; $system = new Admin_Model_Category(); $menu = $system->option_menu(); $this->view->bookss = $menu; $district = $system->option_dictrict(); $this->view->bokk = $district; if (!$this->_request->isPost()) { $captcha->setTimeout('300')->setWordLen('4')->setHeight('60')->setWidth('320')->setImgDir(APPLICATION_PATH . '/../public_html/captcha/images/')->setImgUrl($base . '/captcha/images/')->setFont(APPLICATION_PATH . '/../public_html/font/AHGBold.ttf')->setFontSize(24); $captcha->generate(); $this->view->captcha = $captcha->render($this->view); $this->view->captchaID = $captcha->getId(); // Dua chuoi Captcha vao session $captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_' . $captcha->getId()); $captchaSession->word = $captcha->getWord(); } else { $captchaID = $this->_request->captcha_id; $captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_' . $captchaID); $captchaIterator = $captchaSession->getIterator(); $captchaWord = $captchaIterator['word']; if ($this->_request->captcha == $captchaWord) { $this->view->purifier = Zend_Registry::get('purifier'); $conf = HTMLPurifier_Config::createDefault(); $purifier = new HTMLPurifier($conf); $content = $purifier->purify($this->_request->getParam('content')); $menu_id = $purifier->purify($this->_request->getParam('parent_id')); $title = $purifier->purify($this->_request->getParam('title')); $dis = $purifier->purify($this->_request->getParam('dis')); $key = $purifier->purify($this->_request->getParam('key')); $description = $purifier->purify($this->_request->getParam('description')); // $home = $purifier->purify($this->_request->getParam('home')); $upload = new Zend_File_Transfer(); $images = $upload->addValidator('Extension', false, 'jpg,png,gif'); //print_r($images, FALSE) ; $images = $upload->getFilename(); $images = basename($images); $url = khongdau($title); $random_digit = rand(00, 99999); if (basename($images)) { $img = $url . "-" . $random_digit . $images; $filterRename = new Zend_Filter_File_Rename(array('target' => 'Upload/' . $img, 'overwrite' => false)); $upload->addFilter($filterRename); if (!$upload->receive()) { thongbao("Vui lòng nhập đúng định dạng hình ảnh"); trang_truoc(); return; } $upload->receive(); } else { $img == "no-img.png"; } // $position = $purifier->purify($this->_request->getParam('position')); // $active = $purifier->purify($this->_request->getParam('active')); $price = $purifier->purify($this->_request->getParam('price')); $state = $purifier->purify($this->_request->getParam('state')); $sales = $purifier->purify($this->_request->getParam('sales')); $made_in = $purifier->purify($this->_request->getParam('made_in')); //$members = $purifier->purify($this->_request->getParam('members')); $session = new Zend_Session_Namespace('identity'); $members = $session->username; $dictrict_id = $purifier->purify($this->_request->getParam('dictrict_id')); // $type = $purifier->purify($this->_request->getParam('type')); $add = new Admin_Model_Products(); $add->insert_products($title, $description, $img, $content, $menu_id, $price, $state, $sales, $dis, $key, "", 1, 2, $made_in, $members, $dictrict_id, 1); thongbao("Chúc mừng {$members}, bạn đã đăng tin thành công"); chuyen_trang($base . "/thanh-vien.html"); } else { thongbao('Ban nhap sai chuoi Captcha'); trang_truoc(); } $this->_helper->viewRenderer->setNoRender(); $mask = APPLICATION_PATH . "/../public_html/captcha/images/*.png"; array_map("unlink", glob($mask)); } }
public function filesAction() { if (!$this->getRequest()->isPost()) { throw new AppEx\ForbiddenException("Files action must be a post request."); } $front = Zend_Controller_Front::getInstance(); $front->registerPlugin(new \Tid_Zend_Controller_Plugin_UploadMax()); try { $upload = new Zend_File_Transfer('App_File_Transfer_Adapter_HttpMultipartMixed', false, array('ignoreNoFile' => true)); } catch (Zend_File_Transfer_Exception $e) { throw new AppEx\InvalidArgumentException($e->getMessage()); } $upload->addValidator('Count', true, array('min' => 1, 'max' => 1))->addValidator('Extension', true, array('xml', 'csv', 'txt'))->addValidator('MimeType', true, array('application/xml', 'text/plain', 'headerCheck' => true)); if ($upload->isValid()) { if ($upload->receive()) { try { $fileinfo = current($upload->getFileInfo()); $filename = $fileinfo['tmp_name']; // Attempt to parse data from file $parseResult = $this->_stockSrv->getData($filename, $upload->getMimeType()); $data = $parseResult['data']; $errors = $parseResult['errors']; if (!empty($errors) && is_array($errors)) { foreach ($errors as $errMess) { require_once APPLICATION_PATH . '/modules/default/controllers/ErrorController.php'; $errMess->code = ErrorController::finishErrorCode($errMess->code); } } $method = 'create' . ucfirst($data['_type']); if (!empty($data['_type']) && is_callable(array($this->_stockSrv, $method))) { // Check permissions according to the data type $dumbSim = new Application\Model\SimModel(); $this->_helper->allowed($data['_perm'], $dumbSim); try { $watcher = $this->_stockSrv->{$method}($parseResult); } catch (AppEx\GlobalServiceException $ex) { $ex->addErrorMessages($errors); throw $ex; } $txId = uniqid('parser'); WatcherService::getInstance()->pushEntityId($watcher, $txId); $event = new EventModel(); $event->entityId = $txId; $event->entityType = 'transaction'; $event->namespace = 'connectivity'; $event->eventData = $errors; $event->created = time(); $event->forceFinish = true; WatcherService::getInstance()->publishEvent($event); // WatcherService::getInstance()->setStatus($watcher->id, WatcherModel::STATUS_FINISHED); $errors_ex = $this->_loadErrorsFromWatcher($watcher); if (!empty($errors_ex)) { $errors = Zend_Json::encode($errors_ex); App::log()->warn("Error on file upload in stock:\n" . $errors); throw new AppEx\StockParserException("Some errors uploading file to stock.", array('errorMessages' => $errors_ex)); } } else { throw new AppEx\UnexpectedException('Unknown data type (' . $data['_type'] . ')'); } } catch (PermissionException $e) { throw $e; } catch (StockParserException $e) { throw $e; } catch (GlobalServiceException $e) { $txId = uniqid('parser'); if (!isset($watcher)) { $watcher = $this->_stockSrv->createFileWatcher(); $watcher->entityIds = array($txId); $watcher->params->type = 'sim'; $watcher->params->action = 'stockUpload'; $watcher->save(); } else { WatcherService::getInstance()->pushEntityId($watcher, $txId); } $event = new EventModel(); $event->entityId = $txId; $event->entityType = 'transaction'; $event->namespace = 'connectivity'; $event->created = time(); $event->modified = time(); $event->pushEventData = true; $eventData = array(); $errors = $e->getErrorMessages(); $eventData['hasFailures'] = true; if (!empty($errors) && is_array($errors)) { require_once APPLICATION_PATH . '/modules/default/controllers/ErrorController.php'; foreach ($errors as $errMess) { if ($errMess instanceof ErrorModel) { $errMess->code = ErrorController::finishErrorCode($errMess->code); } } $eventData['message'] = array('failed' => $errors); } $event->eventData = $eventData; $event->forceFinish = true; $compressor = new ErrorModelCompressEvent(); $compressor->compress($event); WatcherService::getInstance()->publishEvent($event); // WatcherService::getInstance()->setStatus($watcher->id, WatcherModel::STATUS_FINISHED); $errors = $this->_loadErrorsFromWatcher($watcher); if (!empty($errors)) { App::log()->warn("Error on file upload in stock:\n" . Zend_Json::encode($errors)); throw new AppEx\StockParserException("Some errors uploading file to stock.", array('errorMessages' => $errors)); } } } else { throw new AppEx\InvalidArgumentException('Could not receive file'); } } else { throw new AppEx\InvalidArgumentException('Invalid file: ' . implode(', ', $upload->getMessages())); } }
/** * Upload a new file for this user if one is present in the form data, or if * not, check if one has been uploaded previously. If there's one known * about, return its name. Uses session to persist an uploaded file's * details between form submission attempts, in the case the overall form * doesn't validate. * * @todo Move somewhere else. * * @return array Array indicating boolean true for success plus and an * associative array with uploaded file information (or empty array if no * file), or boolean false for failure and an array of error messages. */ private function _uploadPersistentCompanyApplicationFile() { // For storing original filename intact $session = new Zend_Session_Namespace('homelet_connect_referencing'); $tempFile = "{$this->_params->connect->tempPrivatePath}companyApp_{$this->_agentSchemeNumber}_{$this->_agentId}"; // Is a new file being sent? $upload = new Zend_File_Transfer('http'); if ($upload->isUploaded()) { $upload->getValidator('Upload')->setMessages(array(Zend_Validate_File_Upload::INI_SIZE => 'The uploaded file size exceeds system maximum (' . ini_get('upload_max_filesize') . ')', Zend_Validate_File_Upload::FORM_SIZE => 'The uploaded file size exceeds the HTML form maximum', Zend_Validate_File_Upload::PARTIAL => 'The uploaded file was only partially uploaded', Zend_Validate_File_Upload::NO_FILE => 'No file was uploaded', Zend_Validate_File_Upload::NO_TMP_DIR => 'Missing a temporary folder', Zend_Validate_File_Upload::CANT_WRITE => 'Failed to write file to disk', Zend_Validate_File_Upload::EXTENSION => 'File upload stopped by extension', Zend_Validate_File_Upload::UNKNOWN => 'Unknown upload error')); $upload->addValidator('Count', true, 1); $upload->addValidator('Size', false, $this->_params->connect->companyapps->fileUpload->maxSize->file); $upload->getValidator('Size')->setMessages(array(Zend_Validate_File_Size::TOO_SMALL => 'File \'%value%\' below minimum size', Zend_Validate_File_Size::TOO_BIG => 'File \'%value%\' above maximum size')); $upload->addValidator('MimeType', false, $this->_params->connect->companyapps->fileUpload->mimeTypes); $upload->getValidator('MimeType')->setMessages(array(Zend_Validate_File_MimeType::FALSE_TYPE => 'File \'%value%\' of incorrect MIME type')); $upload->addValidator('Extension', true, $this->_params->connect->companyapps->fileUpload->extensions); $upload->getValidator('Extension')->setMessages(array(Zend_Validate_File_Extension::FALSE_EXTENSION => 'File \'%value%\' of incorrect extension')); if ($upload->isValid()) { // First delete any old file that may have been previously // uploaded $this->_deleteCompanyApplicationFile(); // Upload new one $session->companyAppFile->originalFilename = $upload->getFileName(null, false); $upload->addFilter('Rename', $tempFile); if ($upload->receive()) { $session->companyAppFile->uploadedFile = $tempFile; } else { unset($session->companyAppFile); } } else { // Send back validation messages return array(false, $upload->getMessages()); } } // Is there one stored, perhaps already? If yes, return original // filename $returnVal = array(); if (isset($session->companyAppFile->originalFilename)) { $returnVal = array('originalName' => $session->companyAppFile->originalFilename, 'pathToFile' => $tempFile); } return array(true, $returnVal); }
public function processpictureAction() { // disable rendering of the view and layout so that we can just echo the AJAX output $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(TRUE); $session = SessionWrapper::getInstance(); $config = Zend_Registry::get("config"); $this->_translate = Zend_Registry::get("translate"); $formvalues = $this->_getAllParams(); //debugMessage($this->_getAllParams()); $user = new UserAccount(); $user->populate(decode($this->_getParam('id'))); // only upload a file if the attachment field is specified $upload = new Zend_File_Transfer(); // set the file size in bytes $upload->setOptions(array('useByteString' => false)); // Limit the extensions to the specified file extensions $upload->addValidator('Extension', false, $config->uploads->photoallowedformats); $upload->addValidator('Size', false, $config->uploads->photomaximumfilesize); // base path for profile pictures $destination_path = BASE_PATH . DIRECTORY_SEPARATOR . "uploads" . DIRECTORY_SEPARATOR . "users" . DIRECTORY_SEPARATOR . "user_"; // determine if user has destination avatar folder. Else user is editing there picture if (!is_dir($destination_path . $user->getID())) { // no folder exits. Create the folder mkdir($destination_path . $user->getID(), 0777); } // set the destination path for the image $profilefolder = $user->getID(); $destination_path = $destination_path . $profilefolder . DIRECTORY_SEPARATOR . "avatar"; if (!is_dir($destination_path)) { mkdir($destination_path, 0777); } // create archive folder for each user $archivefolder = $destination_path . DIRECTORY_SEPARATOR . "archive"; if (!is_dir($archivefolder)) { mkdir($archivefolder, 0777); } $oldfilename = $user->getProfilePhoto(); //debugMessage($destination_path); $upload->setDestination($destination_path); // the profile image info before upload $file = $upload->getFileInfo('profileimage'); $uploadedext = findExtension($file['profileimage']['name']); $currenttime = time(); $currenttime_file = $currenttime . '.' . $uploadedext; $thefilename = $destination_path . DIRECTORY_SEPARATOR . 'base_' . $currenttime_file; $thelargefilename = $destination_path . DIRECTORY_SEPARATOR . 'large_' . $currenttime_file; $updateablefile = $destination_path . DIRECTORY_SEPARATOR . 'base_' . $currenttime; $updateablelarge = $destination_path . DIRECTORY_SEPARATOR . 'large_' . $currenttime; //debugMessage($thefilename); // rename the base image file $upload->addFilter('Rename', array('target' => $thefilename, 'overwrite' => true)); // exit(); // process the file upload if ($upload->receive()) { // debugMessage('Completed'); $file = $upload->getFileInfo('profileimage'); // debugMessage($file); $basefile = $thefilename; // convert png to jpg if (in_array(strtolower($uploadedext), array('png', 'PNG', 'gif', 'GIF'))) { ak_img_convert_to_jpg($thefilename, $updateablefile . '.jpg', $uploadedext); unlink($thefilename); } $basefile = $updateablefile . '.jpg'; // new profilenames $newlargefilename = "large_" . $currenttime_file; // generate and save thumbnails for sizes 250, 125 and 50 pixels resizeImage($basefile, $destination_path . DIRECTORY_SEPARATOR . 'large_' . $currenttime . '.jpg', 400); resizeImage($basefile, $destination_path . DIRECTORY_SEPARATOR . 'medium_' . $currenttime . '.jpg', 165); // unlink($thefilename); unlink($destination_path . DIRECTORY_SEPARATOR . 'base_' . $currenttime . '.jpg'); // exit(); // update the user with the new profile images try { $user->setProfilePhoto($currenttime . '.jpg'); $user->save(); // check if user already has profile picture and archive it $ftimestamp = current(explode('.', $user->getProfilePhoto())); $allfiles = glob($destination_path . DIRECTORY_SEPARATOR . '*.*'); $currentfiles = glob($destination_path . DIRECTORY_SEPARATOR . '*' . $ftimestamp . '*.*'); // debugMessage($currentfiles); $deletearray = array(); foreach ($allfiles as $value) { if (!in_array($value, $currentfiles)) { $deletearray[] = $value; } } // debugMessage($deletearray); if (count($deletearray) > 0) { foreach ($deletearray as $afile) { $afile_filename = basename($afile); rename($afile, $archivefolder . DIRECTORY_SEPARATOR . $afile_filename); } } $session->setVar(SUCCESS_MESSAGE, $this->_translate->translate("global_update_success")); $this->_helper->redirector->gotoUrl($this->view->baseUrl("profile/picture/id/" . encode($user->getID()) . '/crop/1')); } catch (Exception $e) { $session->setVar(ERROR_MESSAGE, $e->getMessage()); $session->setVar(FORM_VALUES, $this->_getAllParams()); $this->_helper->redirector->gotoUrl($this->view->baseUrl('profile/picture/id/' . encode($user->getID()))); } } else { // debugMessage($upload->getMessages()); $uploaderrors = $upload->getMessages(); $customerrors = array(); if (!isArrayKeyAnEmptyString('fileUploadErrorNoFile', $uploaderrors)) { $customerrors['fileUploadErrorNoFile'] = "Please browse for image on computer"; } if (!isArrayKeyAnEmptyString('fileExtensionFalse', $uploaderrors)) { $custom_exterr = sprintf($this->_translate->translate('global_invalid_ext_error'), $config->uploads->photoallowedformats); $customerrors['fileExtensionFalse'] = $custom_exterr; } if (!isArrayKeyAnEmptyString('fileUploadErrorIniSize', $uploaderrors)) { $custom_exterr = sprintf($this->_translate->translate('global_invalid_size_error'), formatBytes($config->uploads->photomaximumfilesize, 0)); $customerrors['fileUploadErrorIniSize'] = $custom_exterr; } if (!isArrayKeyAnEmptyString('fileSizeTooBig', $uploaderrors)) { $custom_exterr = sprintf($this->_translate->translate('global_invalid_size_error'), formatBytes($config->uploads->photomaximumfilesize, 0)); $customerrors['fileSizeTooBig'] = $custom_exterr; } $session->setVar(ERROR_MESSAGE, 'The following errors occured <ul><li>' . implode('</li><li>', $customerrors) . '</li></ul>'); $session->setVar(FORM_VALUES, $this->_getAllParams()); $this->_helper->redirector->gotoUrl($this->view->baseUrl('profile/picture/id/' . encode($user->getID()))); } // exit(); }
function regAction() { if ($this->_request->isPost('reg-form')) { Zend_Loader::loadClass('Zend_Filter_StripTags'); Zend_Loader::loadClass('Zend_File_Transfer'); Zend_Loader::loadClass('Zend_Date'); Zend_Loader::loadClass('Zend_Mail'); Zend_Loader::loadClass('Zend_Validate_EmailAddress'); Zend_Loader::loadClass('Zend_Validate_StringLength'); Zend_Loader::loadClass('Zend_Validate_Alnum'); $filter = new Zend_Filter_StripTags(); $email = trim($filter->filter($this->_request->getPost('reg-email'))); $username = trim($filter->filter($this->_request->getPost('reg-name'))); $password = trim($filter->filter($this->_request->getPost('reg-pswd'))); $password_confirm = trim($filter->filter($this->_request->getPost('reg-pswd-verification'))); $real_name = trim($filter->filter($this->_request->getPost('reg-real-name'))); $file_name = ''; $warnings = new Zend_Session_Namespace(); $warnings->username = $username; $warnings->email = $email; $warnings->real_name = $real_name; $warnings->error = ''; $error_msg = ''; $mail_val = new Zend_Validate_EmailAddress(); $name_lenght_val = new Zend_Validate_StringLength(6, 12); $name_an_val = new Zend_Validate_Alnum(); $pass_lenght_val = new Zend_Validate_StringLength(6, 16); $real_name_lenght_val = new Zend_Validate_StringLength(0, 60); if ($email == '') { $error_msg .= '<p>Enter your email.</p>'; } else { if (!$mail_val->isValid($email)) { foreach ($mail_val->getMessages() as $message) { $error_msg .= '<p>' . $message . '</p>'; } } else { $data = new Users(); $query = 'email = "' . $email . '"'; $data_row = $data->fetchRow($query); if ($data_row['email'] != '') { $error_msg .= '<p>User with such an email is already registered.</p>'; } } } if ($username == '') { $error_msg .= '<p>Enter your username.</p>'; } else { if (!$name_lenght_val->isValid($username) || !$name_an_val->isValid($username)) { foreach ($name_lenght_val->getMessages() as $message) { $error_msg .= '<p>' . $message . '</p>'; } foreach ($name_an_val->getMessages() as $message) { $error_msg .= '<p>' . $message . '</p>'; } } else { $data = new Users(); $query = 'login = "******"'; $data_row = $data->fetchRow($query); if ($data_row['login'] != '') { $error_msg .= '<p>User with such an username is already registered.</p>'; } } } if ($password == '' || !$pass_lenght_val->isValid($password)) { $error_msg .= '<p>Enter password (must consist 6 to 16 characters).</p>'; } else { if ($password_confirm == '') { $error_msg .= '<p>Empty verification password.</p>'; } else { if ($password != $password_confirm) { $error_msg .= '<p>The entered passwords do not match.</p>'; } else { $salt = substr(sha1(microtime(true) . rand(1, 99999)), 0, 3); $password = sha1($password . $salt); } } } if ($real_name != '') { if (!$real_name_lenght_val->isValid($real_name)) { foreach ($real_name_lenght_val->getMessages() as $message) { $error_msg .= '<p>' . $message . '</p>'; } } } $upload = new Zend_File_Transfer(); if ($upload->isUploaded()) { $upload->setDestination('public/upload/avatars/'); $upload->addValidator('IsImage', false); $upload->addValidator('Size', false, 1024 * 1024); if (!$upload->isValid()) { foreach ($upload->getMessages() as $message) { $error_msg .= '<p>' . $message . '</p>'; } } else { $upload_info = $upload->getFileName(); $file_ext = mb_substr($upload_info, strrpos($upload_info, '.') + 1); $file_name = $username . '.' . $file_ext; $upload->addFilter('Rename', array('target' => 'public/upload/avatars/' . $file_name, 'overwrite' => true)); } } if ($error_msg != '') { $warnings->error = $error_msg; $warnings->status = ''; $this->_redirect('/register/'); return; } else { $date = new Zend_Date(); $current_date = $date->toString('YYYY-MM-dd'); $upload->receive(); $data = array('login' => $username, 'email' => $email, 'password' => $password, 'salt' => $salt, 'real_name' => $real_name, 'reg_date' => $current_date, 'avatar' => $file_name, 'last_login' => '-'); $user = new Users(); $user->insert($data); $warnings->error = '<p>Registration complete.</p><p>Now check your E-Mail to activate your profile.</p>'; $warnings->username = ''; $warnings->email = ''; $warnings->real_name = ''; $warnings->status = ' reg_ok'; $mail = new Zend_Mail(); $hash = sha1($email . $salt); $url = $this->getRequest()->getServer('HTTP_HOST'); $mail->setBodyHtml('<p>To activate your profile follow the link below:</p> <p>Link: <a href="http://' . $url . '/register/activate/' . $hash . '">http://' . $url . '/register/activate/' . $hash . '</a></p> <p>Thanks for your registration.</p> '); $mail->setFrom('*****@*****.**', 'Administrator'); $mail->addTo($email, $username); $mail->setSubject('Test activation link'); $mail->send(); $this->_redirect('/register/'); return; } } }
public function photoUploadAction() { if ($this->request->isPost()) { // POST METHOD $result = 0; $upload = new Zend_File_Transfer(); $upload->addValidator('Size', false, 5120000); //5M $uid = uniqid(); $destination = $this->getTmpFile($uid); $upload->addFilter('Rename', $destination); if ($upload->isValid()) { if ($upload->receive()) { $result = $uid; } } echo $result; exit; } else { // GET METHOD $this->view->title = "上传图片"; } }
/** * Controller to handle file upload form * @throws Exception */ public function indexAction() { $response = new stdClass(); try { $upload = new Zend_File_Transfer(); } catch (Exception $e) { $response->error = $e->getMessage(); $this->_helper->json->sendJson($response); } $upload->addValidator('Count', false, array('min' => 1, 'max' => 100)); $upload->addValidator('IsImage', false); $upload->addValidator('Size', false, array('max' => '10MB', 'bytestring' => false)); $translate = Zend_Registry::get('Zend_Translate'); $updating = false; try { if (!$upload->receive()) { throw new Exception($translate->translate('error_uploading')); } else { $files = $upload->getFileInfo(); // Updating hash with new images if (!empty($_POST['hash']) && Unsee_Hash::isValid($_POST['hash'])) { $hashDoc = new Unsee_Hash($_POST['hash']); $updating = true; $response = array(); if (!Unsee_Session::isOwner($hashDoc) && !$hashDoc->allow_anonymous_images) { die('[]'); } } else { // Creating a new hash $hashDoc = new Unsee_Hash(); $this->setExpiration($hashDoc); $response->hash = $hashDoc->key; } $imageAdded = false; foreach ($files as $file => $info) { if ($upload->isUploaded($file)) { $imgDoc = new Unsee_Image($hashDoc); $res = $imgDoc->setFile($info['tmp_name']); $imgDoc->setSecureParams(); //hack to populate correct secureTtd if ($updating) { $ticket = new Unsee_Ticket(); $ticket->issue($imgDoc); $newImg = new stdClass(); $newImg->hashKey = $hashDoc->key; $newImg->key = $imgDoc->key; $newImg->src = '/image/' . $imgDoc->key . '/' . $imgDoc->secureMd5 . '/' . $imgDoc->secureTtd . '/'; $newImg->width = $imgDoc->width; $newImg->ticket = md5(Unsee_Session::getCurrent() . $hashDoc->key); $response[] = $newImg; } if ($res) { $imageAdded = true; } // Remove uploaded file from temporary dir if it wasn't removed if (file_exists($info['tmp_name'])) { @unlink($info['tmp_name']); } } } if (!$imageAdded) { throw new Exception('No images were added'); } } } catch (Exception $e) { $response->error = $e->getMessage(); } $this->_helper->json->sendJson($response); }
public function imageuploadAction() { $ArticleMapper = new Application_Model_ImageinfoMapper(); $method = $this->_request->getParam("method"); if ($method == "post") { $deptid = $this->_request->getParam("deptid"); //实例化文件上传类 $upload = new Zend_File_Transfer(); $upload->addValidator('Size', false, 5 * 1024 * 1024); $upload->addValidator('Extension', false, 'jpg,gif,png'); if (!$upload->isValid()) { echo "<script>alert('格式不符或文件过大,请重新尝试');location.href = '/admin/imageupload';</script>"; exit; } //获取上传的文件表单,可以有多项 $fileInfo = $upload->getFileInfo(); $parseImg = new Application_Model_Admin_Admin(); $filetmp = $parseImg->resize_image($fileInfo['imageFile']['name'], $fileInfo['imageFile']['tmp_name'], '480', '280'); imagedestroy($fileInfo['imageFile']['tmp_name']); //获取后缀名,这里imageFile为上传表单file控件的name $ext = explode(".", $fileInfo['imageFile']['name']); $ext = $ext[1]; //定义生成目录 $dir = './upload' . date('/Y/m/'); //文件重新命名 do { $filename = date('His') . rand(100000, 999999) . '.' . $ext; } while (file_exists($dir . $filename)); //如果目录不存在则创建目录 if (!file_exists($dir)) { mkdir($dir, 0777, true); } //将图片正式写入 $pass = imagejpeg($filetmp, $dir . '/' . $filename, 100); if (!$pass) { imagedestroy($filetmp); echo "<script>alert('图片资源上传失败,请重新尝试');location.href = '/admin/imageupload';</script>"; exit; } imagedestroy($filetmp); //将图片信息插入数据库 $i = $ArticleMapper->uploadImageInfo($filename, $_SESSION['user']['RealName'], $deptid); if (!isset($i)) { echo "<script>alert('图片信息上传失败,请重新尝试');location.href = '/admin/imageupload';</script>"; exit; } echo "<script>alert('上传成功!');location.href = '/admin/imageupload';</script>"; } else { //加载列表 $DeptMapper = new Application_Model_DepartmentMapper(); $arr = $DeptMapper->findAllDept(); $this->view->arrDept = $arr; $this->view->imageArr = $ArticleMapper->selectImageInfo($_SESSION['user']['RealName']); } }