/** * 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 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(); }
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); }
public function saveAction() { $request = $this->getRequest(); $id = $this->getParam('id'); $auth = Zend_Auth::getInstance(); if ($auth->hasIdentity()) { $user_id = $auth->getIdentity()->id; } $form = $this->getSaveProductForm($id); if ($this->getRequest()->isPost()) { if ($form->isValid($request->getPost())) { $data = $this->getRequest()->getParams(); $upload = new Zend_File_Transfer(); $files = $upload->getFileInfo(); $isValid = true; foreach ($files as $field => $file) { if (!strlen($file["name"])) { continue; } $extension = pathinfo($file['name'], PATHINFO_EXTENSION); $filename = pathinfo($file['name'], PATHINFO_FILENAME); if (!file_exists(UPLOADS_IMAGES)) { mkdir(UPLOADS_IMAGES, 0774, true); } if (!file_exists(UPLOADS_DATA)) { mkdir(UPLOADS_DATA, 0774, true); } // upload instructions for image if ($field == 'image') { $upload->addFilter('Rename', array('target' => UPLOADS_IMAGES . '/' . $filename . "_" . $user_id . "_" . time() . "." . $extension, 'overwrite' => TRUE), $field)->addValidator('Extension', false, array('jpg', 'jpeg', 'png'), $field); $data['image'] = $filename . "_" . $user_id . "_" . time() . "." . $extension; } // upload instructions for file if ($field == 'file') { $upload->addFilter('Rename', array('target' => UPLOADS_DATA . '/' . $filename . "_" . $user_id . "_" . time() . "." . $extension, 'overwrite' => TRUE), $field)->addValidator('Extension', false, array('doc', 'docx', 'txt', 'pdf'), $field); $data['file'] = $filename . "_" . $user_id . "_" . time() . "." . $extension; } if ($upload->isValid($field)) { if (!$upload->receive($field)) { $isValid = false; foreach ($upload->getMessages() as $key => $val) { $this->_helper->getHelper('FlashMessenger')->addMessage($val, 'error'); } } } else { $isValid = false; $this->_helper->getHelper('FlashMessenger')->addMessage($file['name'] . " is not valid {$field}", 'error'); //return $this->_helper->redirector('save'); } } if ($upload->hasErrors()) { $errors = $upload->getMessages(); foreach ($errors as $error) { $this->_helper->getHelper('FlashMessenger')->addMessage("{$error}", 'error'); } return $this->_helper->redirector('save'); } if ($isValid) { $product = new Application_Model_Product(); $productMapper = new Application_Model_ProductMapper(); if ($id) { $product = $productMapper->getProductById($id); } if (isset($data['file']) && $product->file && $product->file != $data['file'] || !isset($data['file']) && $product->file) { $productMapper->delete_file($product->file); } if (isset($data['image']) && $product->image && $product->image != $data['image'] || !isset($data['image']) && $product->image) { $productMapper->delete_image($product->image); } $product = new Application_Model_Product($data); $productMapper->save($product); return $this->_helper->redirector('dashboard', 'users'); } } } $this->view->headScript()->appendFile(JS_DIR . '/' . self::DELETE_FIELD . '.js'); $this->view->form = $form; }
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; } } }