public function index() { $db = MySQL::getInstance(); if (isset($this->data[0]) && $this->data[0] == 'save') { foreach ($this->post as $name => $value) { $db->query('UPDATE `config` SET `FieldValue` = ' . $db->escape($value) . ' WHERE `FieldName` = ' . $db->escape($name)); } foreach ($_FILES as $field => $file) { if ($fileName = File::upload('var/upload/', $field, true, true)) { $db->query("SELECT `FieldValue` FROM `config` WHERE `FieldName` = " . $db->escape($field)); if ($oldFile = $db->fetchField()) { File::delete($oldFile, 'var/upload/'); } $db->query('UPDATE `config` SET `FieldValue` = ' . $db->escape($fileName) . ' WHERE `FieldName` = ' . $db->escape($field)); if ($field == "Banner") { File::imageCrop($fileName, 'var/upload/', 699, 122); } } } redirect(BASE_PATH . 'admin/cp'); } $this->show->configData = array(); $db->query('SELECT FieldName, FieldValue, FieldDescription, FieldType FROM `config` ORDER BY SortOrder'); while (list($key, $value, $description, $type) = $db->fetchRow()) { $this->show->configData[] = array('Key' => $key, 'Value' => $value, 'Description' => $description, 'Type' => $type); } }
public function execute() { $this->params = $this->extractRequestParams(); // Extract the file and archiveName from the request parameters $this->validateParameters(); // Check whether we're allowed to revert this file $this->checkPermissions($this->getUser()); $sourceUrl = $this->file->getArchiveVirtualUrl($this->archiveName); $status = $this->file->upload($sourceUrl, $this->params['comment'], $this->params['comment']); if ($status->isGood()) { $result = array('result' => 'Success'); } else { $result = array('result' => 'Failure', 'errors' => $this->getResult()->convertStatusToArray($status)); } $this->getResult()->addValue(null, $this->getModuleName(), $result); }
public function updateMe($inputs) { $this->name = $inputs['name']; $this->lastName = $inputs['lastName']; $this->city_id = $inputs['city_id']; $this->country_id = $inputs['country_id']; $this->province_id = $inputs['province_id']; $this->village = $inputs['village']; $this->hive_count = $inputs['hive_count']; $this->cooperative_member = isset($inputs['cooperative_member']) ? $inputs['cooperative_member'] : 0; $this->union_beekeeper_member = isset($inputs['union_beekeeper_member']) ? $inputs['union_beekeeper_member'] : 0; $this->phone = $inputs['phone']; $this->email = $inputs['email']; // $this->month_record = $inputs['']; $this->year_record = $inputs['year_record']; $this->beekeeping_book_code = $inputs['beekeeping_book_code']; $this->post_code = $inputs['post_code']; $this->beekeeping_as_main_job = isset($inputs['beekeeping_as_main_job']) ? $inputs['beekeeping_as_main_job'] : 0; $this->amount_of_honey_extraction_per_year = $inputs['']; $this->education_id = $inputs['education_id']; // $this->picture = $inputs['']; $this->description = $inputs['description']; $this->cellphone = $inputs['cellphone']; $this->union_name = $inputs['union_name']; $this->job_id = $inputs['job_id']; $this->location = $inputs['location']; $this->practice = serialize($inputs['practice']); $this->picture = isset($_FILES['picture']) ? \File::upload($_FILES['picture'])->url : null; $this->save(); }
/** * The resume application handler. * * @access public * @return string The JSON response. */ public function app() { $response = array('result' => 0, 'posted' => 0); if (Request::get('Name') && Request::get('Email') && Request::get('Phone') && !Request::get('Message')) { $response['posted'] = 1; $Resume = new Resume(); $Resume->setPost($_POST); $fields = Error::test($Resume); if (count($fields)) { $response['msg'] = 'Неверно заполнены поля: ' . implode(', ', $fields); } else { $Resume->Id = rand(1, 1000000); if (!empty($_FILES['file']['tmp_name'])) { File::upload($Resume, $_FILES['file']); } $Email = new Email_Resume($Resume); if ($Email->send()) { $response['result'] = 1; } else { $response['msg'] = 'Ошибка отправки e-mail'; } File::detach($Resume); } } return $this->outputJSON($response); }
/** * The function uploads Benefit examples. * * @access public * @param int $id The Benefit id. * @return string The JSON response. */ public function upload($id = null) { $response = array('result' => 0); if (isset($_POST['upload'])) { $Benefit = new Benefit(); $Benefit = $Benefit->findItem(array('Id = ' . $id)); if ($Benefit->Id) { if (empty($_FILES['example']['tmp_name'])) { $response['msg'] = 'Выберите файл'; } else { $Example = new Benefit_Example(); $Example->BenefitId = $Benefit->Id; if ($Example->save()) { if (File::upload($Example, $_FILES['example'])) { $Example->save(); $response['result'] = 1; $response['html'] = $this->getView()->htmlExamples($Benefit); } else { $response['msg'] = 'Не удалось загрузить файл'; } } else { $response['msg'] = 'Ошибка записи данных'; } } } else { $response['msg'] = 'Продукция не найдена'; } } return $this->outputJSON($response); }
function upload() { $file = new File(); //we check access in the upload function if ($file->upload()) { Response($file); } else { Response()->error($file->errors()); } }
function user_update_0() { //this should be replaced with a user save but that requires a full bootstrap :( $sql = "REPLACE INTO `user` (`uid`, `email`, `username`, `password`, `created`, `updated`, `deleted`, `status`, `firstname`, `lastname`, `profile`, `location`, `age`, `picture`, `gender`)\nVALUES\n (2, '*****@*****.**', 'nodefortytwo', '5133b5ed586f3107c016ab3440d1f251', 1346599169, 1346599169, 0, 1, 'Rick', 'Burgess', '', '4c03d3af187ec9287322b67b', 25, '', 'Male');\n "; db()->query($sql); file_init(); $file = array('name' => 'default-profile.gif', 'tmp_name' => cwd() . '/' . PATH_TO_MODULES . '/user/img/default-profile.gif', 'type' => 'image/gif'); $f = new File(); $f->upload($file); var_set('DEFAULT_PROFILE_PIC', $f->id); }
public function process() { if ($this->field_data['tmp_name'] !== '') { $destination = BASE_PATH . '/' . $this->settings['destination']; $filename = File::cleanFilename($this->field_data['name']); if (File::upload($this->field_data['tmp_name'], $destination, $filename)) { return Path::tidy('/' . $this->settings['destination'] . '/' . $filename); } else { Log::fatal($this->field_data['tmp_name'] . ' could up not be uploaded to ' . $destination, 'core'); return ''; } } }
/** * Uploading a file should not fail. */ public function testSaveNew() { $at = getenv("BB_ACCESS_TOKEN"); $tmpDirName = sys_get_temp_dir(); $tmpFileName = md5(rand()) . '.gif'; $tmpFilePath = $tmpDirName . DIRECTORY_SEPARATOR . $tmpFileName; $tmpFile = fopen($tmpFilePath, 'w'); fwrite($tmpFile, 'Test file created by ' . __METHOD__); fclose($tmpFile); $object = File::upload($at, $tmpFilePath); unlink($tmpFilePath); $this->assertInstanceOf('\\ClausConrad\\BillysBilling\\File', $object, 'Uploading a file returns a File instance.'); return $object; }
function insertProcess() { $send = Request::get('send'); $valid = Validator::make(array('send.title' => 'required|min:1|slashes', 'send.parentid' => 'slashes')); if (!$valid) { throw new Exception("Error Processing Request: " . Validator::getMessage()); } if (Request::hasFile('image')) { if (Request::isImage('image')) { $send['image'] = File::upload('image'); } } if (!($id = Categories::insert($send))) { throw new Exception("Error. " . Database::$error); } }
/** * Upload the attachment * * @param array $input * @return bool */ public static function upload($input) { $path = \Config::get('application.upload_path'); if (!file_exists($path = $path . $input['project_id'])) { mkdir($path); } if (!file_exists($path = $path . '/' . $input['upload_token'])) { mkdir($path); } $file = \Input::file('Filedata'); \File::upload('Filedata', $file_path = $path . '/' . $file['name']); $fill = array('uploaded_by' => \Auth::user()->id, 'filename' => $file['name'], 'fileextension' => \File::extension($file_path), 'filesize' => $file['size'], 'upload_token' => $input['upload_token']); $attachment = new static(); $attachment->fill($fill); $attachment->save(); return true; }
public function control() { $this->redirectToSternIndiaEndPoint(); $config = Config::getInstance(); if (isset($_POST['upload']) && $_POST['upload'] == 'Upload') { $target_dir = new FileSystem('upload/'); $file = new File('foo', $target_dir); $name = date('D_d_m_Y_H_m_s_'); $name = $name . $file->getName(); $file->setName($name); $config = Config::getInstance(); $file->addValidations(array(new Mimetype($config->getMimeTypes()), new Size('5M'))); $data = array('name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5()); try { // /Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__,$data); $file->upload(); //Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__,$data); } catch (Exception $e) { $errors = $file->getErrors(); } $csvReader = new CSVReader(); $destinationFile = $target_dir->directory . $file->getNameWithExtension(); $data = $csvReader->parse_file($destinationFile); //$country= DAOFactory::getDAO('LocationDAO'); foreach ($data as $loc_arr) { Utils::processLocation($loc_arr); } //Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__); $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if (isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if ($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } } return $this->generateView(); }
public function update($data, $brandID) { if ((int) $brandID == 0) { return $this->insert($data); } if (empty($data['Title'])) { throw new Exception(lang('data_empty', __CLASS__)); } $db = MySQL::getInstance(); $queryStr = ""; if ($imageName = File::upload('var/brand/')) { $this->deleteFile($brandID); File::imageCrop($imageName, 'var/brand/', 120, 120); $queryStr .= ', `Image` = ' . $db->escape($imageName); } $db->query("UPDATE `catalog_brand` SET\n\t\t\t\t`Title` = " . $db->escape($data['Title'], 255) . ",\n\t\t\t\t`Description` = " . $db->escape($data['Description'], 255) . ",\n\t\t\t\t`Content` = " . $db->escape($data['Content']) . "\n\t\t\t\t" . $queryStr . "\n\t\t\tWHERE `BrandID` = " . $db->escape((int) $brandID)); return true; }
function execute() { $files = Request::files('photo'); if (!$files || sizeof($files) == 0) { return; } $user = ConnectionHelper::userLogin(); $uploadDir = ConnectionHelper::getPhotoDir($user['id']); $model = new connectionUserPhotoModel(); File::mkdir($uploadDir); foreach ($files as $file) { $file_info = pathinfo($file['name']); if (!in_array(strtolower($file_info['extension']), array('png', 'jpeg', 'jpg', 'gif'))) { continue; } $file_name = uniqid() . strtotime('now') . md5(rand()) . '.' . $file_info['extension']; File::upload($file, $uploadDir, $file_name); $model->addPhoto($user['id'], $file_name); } }
function execute() { $status = 'success'; $model = connectionSliderModel::create(); $locale = new Locales('connection'); $list = $locale->getList(); $data = Request::post('slide'); if (!isset($data['link']) || empty($data['link'])) { $status = 'error'; } else { if (isset($data['id'])) { $slide = $model->where(array('id' => (int) $data['id']))->fetchOne(); } $dir = UPLOAD_DIR . DS . 'slider' . DS; File::mkdir($dir); foreach ($list as $lang) { $file = Request::files('slide_' . $lang['iso']); if (!$file || empty($file[0]['name'])) { if (isset($data['id'])) { $data[$lang['iso']]['image'] = isset($slide[$lang['iso']]['image']) ? $slide[$lang['iso']]['image'] : ''; } continue; } $file = $file[0]; $info = pathinfo($file['name']); $name = strtotime('now') . md5($file['name']) . uniqid() . '.' . $info['extension']; File::upload($file, $dir, $name); $data[$lang['iso']]['image'] = $name; } if (isset($data['id'])) { $id = $data['id']; unset($data['id']); $model->where(array('id' => (int) $id))->update($data); } else { $data['sort'] = 0; $model->insert($data); } } return array('status' => $status); }
/** * The upload form handler. * * @access public * @return string The HTML code. */ public function upload() { $error = array(); if (isset($_POST['submit'])) { if (isset($_FILES['file'])) { foreach ($_FILES['file']['name'] as $id => $value) { $file = array('name' => $_FILES['file']['name'][$id], 'type' => $_FILES['file']['type'][$id], 'tmp_name' => $_FILES['file']['tmp_name'][$id], 'error' => $_FILES['file']['error'][$id], 'size' => $_FILES['file']['size'][$id]); if ($file['tmp_name']) { $Award = new Award(); $Award->Type = intval(Request::get('t')); if ($Award->save()) { if (File::upload($Award, $file)) { $Award->save(); } } } } } return $this->halt('', true); } $this->getView()->set('Error', $error); return $this->getView()->render(); }
public function test_8() { $fail = 0; $files = array('tmp_name' => getcwd() . '/uploads/rob1.jpg', 'name' => 'test.jpg'); if (!file_exists(getcwd() . '/uploads/rob1.jpg')) { $fail = 1; $this->errors[8] .= 'Essential rob imagery is missing (uploads/rob.jpg). '; } $result = File::upload($files, true); if ($result === false || !preg_match("!uploads/test!", $result)) { $fail = 1; $this->errors[8] .= 'Unable to upload file using the upload function. '; } if (file_exists(getcwd() . '/uploads/test.jpg')) { unlink(getcwd() . '/uploads/test.jpg'); } return !$fail; }
Shield::abort(); } if (!$folder) { $folder = $config->shield; } if (!File::exist(SHIELD . DS . $folder)) { Shield::abort(); // Folder not found! } if (isset($_FILES) && !empty($_FILES)) { Guardian::checkToken(Request::post('token')); $task_connect_path = SHIELD; include DECK . DS . 'workers' . DS . 'task.package.1.php'; if (!Notify::errors()) { File::upload($_FILES['file'], SHIELD, function () use($speak) { Notify::clear(); Notify::success(Config::speak('notify_success_uploaded', $speak->shield)); }); $P = array('data' => $_FILES); Weapon::fire('on_shield_update', array($P, $P)); Weapon::fire('on_shield_construct', array($P, $P)); $task_connect_kick = 'shield'; include DECK . DS . 'workers' . DS . 'task.package.2.php'; } else { Weapon::add('SHIPMENT_REGION_BOTTOM', function () { echo '<script> (function($) { $(\'.tab-area .tab[href$="#tab-content-2"]\').trigger("click"); })(window.Zepto || window.jQuery); </script>'; }, 11); }
} Guardian::kick($config->manager->slug . '/asset/' . $offset); } else { Weapon::add('SHIPMENT_REGION_BOTTOM', function () { echo '<script> (function($) { $(\'.tab-area .tab[href$="#tab-content-2"]\').trigger("click"); })(window.Zepto || window.jQuery); </script>'; }, 11); } // New file } else { if (isset($_FILES) && !empty($_FILES)) { File::upload($_FILES['file'], $d, function ($name, $type, $size, $link) { Session::set('recent_file_update', $name); }); $P = array('data' => $_FILES); Weapon::fire('on_asset_update', array($P, $P)); Weapon::fire('on_asset_construct', array($P, $P)); } if (!Notify::errors()) { Guardian::kick($config->manager->slug . '/asset/' . $offset . ($p ? '?path=' . urlencode($p) : "")); } else { Weapon::add('SHIPMENT_REGION_BOTTOM', function () { echo '<script> (function($) { $(\'.tab-area .tab[href$="#tab-content-3"]\').trigger("click"); })(window.Zepto || window.jQuery); </script>'; }, 11);
/** * Add a post */ public function iframe_add() { $this->setView('iframe_add.php'); @set_time_limit(0); $uploaded_files = array(); try { if (!isset(User_Model::$auth_data)) { throw new Exception(__('POST_ADD_ERROR_SESSION_EXPIRED')); } $is_student = isset(User_Model::$auth_data['student_number']); // Message $message = isset($_POST['message']) ? trim($_POST['message']) : ''; if ($message == '' || $message == __('PUBLISH_DEFAULT_MESSAGE')) { throw new Exception(__('POST_ADD_ERROR_NO_MESSAGE')); } $message = preg_replace('#\\n{2,}#', "\n\n", $message); // Category if (!isset($_POST['category']) || !ctype_digit($_POST['category'])) { throw new Exception(__('POST_ADD_ERROR_NO_CATEGORY')); } $category = (int) $_POST['category']; // Official post (in a group) $official = isset($_POST['official']); // Group $group = isset($_POST['group']) && ctype_digit($_POST['group']) ? (int) $_POST['group'] : 0; if ($group == 0) { $group = null; $official = false; } else { $groups_auth = Group_Model::getAuth(); if (isset($groups_auth[$group])) { if ($official && !$groups_auth[$group]['admin']) { throw new Exception(__('POST_ADD_ERROR_OFFICIAL')); } } else { throw new Exception(__('POST_ADD_ERROR_GROUP_NOT_FOUND')); } } // Private message $private = isset($_POST['private']); if ($private && !$is_student) { throw new Exception(__('POST_ADD_ERROR_PRIVATE')); } $attachments = array(); // Photos if (isset($_FILES['attachment_photo']) && is_array($_FILES['attachment_photo']['name'])) { foreach ($_FILES['attachment_photo']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_PHOTO) { throw new Exception(__('POST_ADD_ERROR_PHOTO_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_PHOTO)))); } } if ($filepaths = File::upload('attachment_photo')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { $name = isset($_FILES['attachment_photo']['name'][$i]) ? $_FILES['attachment_photo']['name'][$i] : ''; try { $img = new Image(); $img->load($filepath); $type = $img->getType(); if ($type == IMAGETYPE_JPEG) { $ext = 'jpg'; } else { if ($type == IMAGETYPE_GIF) { $ext = 'gif'; } else { if ($type == IMAGETYPE_PNG) { $ext = 'png'; } else { throw new Exception(); } } } if ($img->getWidth() > 800) { $img->setWidth(800, true); } $img->save($filepath); // Thumb $thumbpath = $filepath . '.thumb'; $img->thumb(Config::$THUMBS_SIZES[0], Config::$THUMBS_SIZES[1]); $img->setType(IMAGETYPE_JPEG); $img->save($thumbpath); unset($img); $attachments[] = array($filepath, $name, $thumbpath); $uploaded_files[] = $thumbpath; } catch (Exception $e) { throw new Exception(__('POST_ADD_ERROR_PHOTO_FORMAT')); } } } } // Vidéos /* @uses PHPVideoToolkit : http://code.google.com/p/phpvideotoolkit/ * @requires ffmpeg, php5-ffmpeg */ if (isset($_FILES['attachment_video']) && is_array($_FILES['attachment_video']['name'])) { foreach ($_FILES['attachment_video']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_VIDEO) { throw new Exception(__('POST_ADD_ERROR_VIDEO_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_VIDEO)))); } } if ($filepaths = File::upload('attachment_video')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { $name = isset($_FILES['attachment_video']['name'][$i]) ? $_FILES['attachment_video']['name'][$i] : ''; try { $video = new ffmpeg_movie($filepath, false); if (!$video->hasVideo()) { throw new Exception('No video stream found in the file'); } if (!$video->hasAudio()) { throw new Exception('No audio stream found in the file'); } } catch (Exception $e) { throw new Exception(__('POST_ADD_ERROR_VIDEO_FORMAT')); } // Video conversion try { $video_current_width = $video->getFrameWidth(); $video_width = min($video_current_width, Config::VIDEO_MAX_WIDTH); if ($video_width % 2 == 1) { // Even number required $video_width--; } $video_height = $video_width * $video->getFrameHeight() / $video_current_width; if ($video_height % 2 == 1) { // Even number required $video_height--; } // Extract thumb $video_thumb = $video->getFrame(round($video->getFrameCount() * 0.2)); unset($video); $video_thumb = $video_thumb->toGDImage(); $thumbpath = DATA_DIR . Config::DIR_DATA_TMP . File::getName($filepath) . '.thumb'; imagejpeg($video_thumb, $thumbpath, 95); unset($video_thumb); $img = new Image(); $img->load($thumbpath); $img->setWidth($video_width, true); $img->setType(IMAGETYPE_JPEG); $img->save($thumbpath); $uploaded_files[] = $thumbpath; unset($img); // Convert to FLV if (!preg_match('#\\.flv$#i', $filepath)) { $toolkit = new PHPVideoToolkit(); $toolkit->on_error_die = true; // Will throw exception on error $toolkit->setInputFile($filepath); $toolkit->setVideoOutputDimensions($video_width, $video_height); $toolkit->setFormatToFLV(Config::VIDEO_SAMPLING_RATE, Config::VIDEO_AUDIO_BIT_RATE); $toolkit->setOutput(DATA_DIR . Config::DIR_DATA_TMP, File::getName($filepath) . '.flv', PHPVideoToolkit::OVERWRITE_EXISTING); $toolkit->execute(false, false); // Multipass: false, Log: false File::delete($filepath); $filepath = $toolkit->getLastOutput(); $filepath = $filepath[0]; unset($toolkit); } $attachments[] = array($filepath, $name, $thumbpath); $uploaded_files[] = $filepath; } catch (Exception $e) { throw new Exception(__('POST_ADD_ERROR_VIDEO_CONVERT') . $e->getMessage()); } } } } // Audios if (isset($_FILES['attachment_audio']) && is_array($_FILES['attachment_audio']['name'])) { foreach ($_FILES['attachment_audio']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_AUDIO) { throw new Exception(__('POST_ADD_ERROR_AUDIO_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_AUDIO)))); } } if ($filepaths = File::upload('attachment_audio')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { if (!preg_match('#\\.mp3$#', $filepath)) { throw new Exception(__('POST_ADD_ERROR_AUDIO_FORMAT')); } $name = isset($_FILES['attachment_audio']['name'][$i]) ? $_FILES['attachment_audio']['name'][$i] : ''; $attachments[] = array($filepath, $name); } } } // Files if (isset($_FILES['attachment_file']) && is_array($_FILES['attachment_file']['name'])) { foreach ($_FILES['attachment_file']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_FILE) { throw new Exception(__('POST_ADD_ERROR_FILE_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_FILE)))); } } if ($filepaths = File::upload('attachment_file')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { if (!preg_match('#\\.[a-z0-9]{2,4}$#i', $filepath)) { throw new Exception(__('POST_ADD_ERROR_FILE_FORMAT')); } if (preg_match('#\\.(jpg|png|gif|mp3|flv)$#i', $filepath)) { throw new Exception(__('POST_ADD_ERROR_FILE_FORMAT2')); } $name = isset($_FILES['attachment_file']['name'][$i]) ? $_FILES['attachment_file']['name'][$i] : ''; $attachments[] = array($filepath, $name); } } } // Event if (isset($_POST['event_title']) && isset($_POST['event_start']) && isset($_POST['event_end'])) { // Title $event_title = trim($_POST['event_title']); if ($event_title == '') { throw new Exception(__('POST_ADD_ERROR_EVENT_NO_TITLE')); } // Dates if (!($event_start = strptime($_POST['event_start'], __('PUBLISH_EVENT_DATE_FORMAT')))) { throw new Exception(__('POST_ADD_ERROR_EVENT_DATE')); } if (!($event_end = strptime($_POST['event_end'], __('PUBLISH_EVENT_DATE_FORMAT')))) { throw new Exception(__('POST_ADD_ERROR_EVENT_DATE')); } $event_start = mktime($event_start['tm_hour'], $event_start['tm_min'], 0, $event_start['tm_mon'] + 1, $event_start['tm_mday'], $event_start['tm_year'] + 1900); $event_end = mktime($event_end['tm_hour'], $event_end['tm_min'], 0, $event_end['tm_mon'] + 1, $event_end['tm_mday'], $event_end['tm_year'] + 1900); if ($event_start > $event_end) { throw new Exception(__('POST_ADD_ERROR_EVENT_DATE_ORDER')); } $event = array($event_title, $event_start, $event_end); } else { $event = null; } // Survey if (isset($_POST['survey_question']) && isset($_POST['survey_end']) && isset($_POST['survey_answer']) && is_array($_POST['survey_answer'])) { // Question $survey_question = trim($_POST['survey_question']); if ($survey_question == '') { throw new Exception(__('POST_ADD_ERROR_SURVEY_NO_QUESTION')); } // Date if (!($survey_end = strptime($_POST['survey_end'], __('PUBLISH_EVENT_DATE_FORMAT')))) { throw new Exception(__('POST_ADD_ERROR_SURVEY_DATE')); } $survey_end = mktime($survey_end['tm_hour'], $survey_end['tm_min'], 0, $survey_end['tm_mon'] + 1, $survey_end['tm_mday'], $survey_end['tm_year'] + 1900); // Multiple answers $survey_multiple = isset($_POST['survey_multiple']); // Answers $survey_answers = array(); foreach ($_POST['survey_answer'] as $survey_answer) { $survey_answer = trim($survey_answer); if ($survey_answer != '') { $survey_answers[] = $survey_answer; } } if (count($survey_answers) < 2) { throw new Exception(__('POST_ADD_ERROR_SURVEY_ANSWERS')); } $survey = array($survey_question, $survey_end, $survey_multiple, $survey_answers); } else { $survey = null; } // Creation of the post $id = $this->model->addPost((int) User_Model::$auth_data['id'], $message, $category, $group, $official, $private); // Attach files foreach ($attachments as $attachment) { $this->model->attachFile($id, $attachment[0], $attachment[1], isset($attachment[2]) ? $attachment[2] : null); } // Event if (isset($event)) { $this->model->attachEvent($id, $event[0], $event[1], $event[2]); } // Survey if (isset($survey)) { $this->model->attachSurvey($id, $survey[0], $survey[1], $survey[2], $survey[3]); } $this->addJSCode(' parent.location = "' . Config::URL_ROOT . Routes::getPage('home') . '"; '); } catch (Exception $e) { // Delete all uploading files in tmp foreach ($uploaded_files as $uploaded_file) { File::delete($uploaded_file); } $this->addJSCode(' with(parent){ Post.errorForm(' . json_encode($e->getMessage()) . '); } '); } }
$page = 'testimonios'; $page2 = 'nav-testimonios'; require "template/header.php"; ?> <div class="container"> <div class="row"> <?php require "template/nav_testimonios.php"; ?> <?php if (Utils::checkPost("add")) { if (Config::exist("bgtestimonios")) { $edit = array("value" => File::upload("background")); $confirm = Config::edit($edit, array("name", "=", "bgtestimonios")); } else { $new = array("name" => "bgtestimonios", "value" => File::upload("background")); $confirm = Config::add($new); } } ?> <div class="grid col-9"> <div class="row"> <form action="" method="post" enctype="multipart/form-data" > <p><?php if (isset($confirm) && $confirm > 0) { echo "Modificación exitosa"; } ?> </p>
/** * Upload file(s) * * @param string $destination Where the file is going * @param string $id The field took look at in the files array * @return array */ public static function uploadBatch($destination = null, $id = null) { $destination = $destination ?: Request::get('destination'); $id = $id ?: Request::get('id'); $files = self::standardizeFileUploads($_FILES); $results = array(); // Resizing configuration if ($resize = Request::get('resize')) { $width = Request::get('width', null); $height = Request::get('height', null); $ratio = Request::get('ratio', true); $upsize = Request::get('upsize', false); $quality = Request::get('quality', '75'); } // If $files[$id][0] exists, it means there's an array of images. // If there's not, there's just one. We want to change this to an array. if ( ! isset($files[$id][0])) { $tmp = $files[$id]; unset($files[$id]); $files[$id][] = $tmp; } // Process each image foreach ($files[$id] as $file) { // Image data $path = File::upload($file, $destination); $name = basename($path); // Resize if ($resize) { $image = \Intervention\Image\Image::make(Path::assemble(BASE_PATH, $path)); $resize_folder = Path::assemble($image->dirname, 'resized'); if ( ! Folder::exists($resize_folder)) { Folder::make($resize_folder); } $resize_path = Path::assemble($resize_folder, $image->basename); $path = Path::toAsset($resize_path); $name = basename($path); $image->resize($width, $height, $ratio, $upsize)->save($resize_path, $quality); } $results[] = compact('path', 'name'); } return $results; }
public function saveImage($image) { $file = new File($image); if ($file->upload()) { $this->setImage($file->getFileName()); } return $this; }
/** * The function shows edit form and saves data on submit. * * @access protected * @param object $Object The object. * @return string The HTML code. */ protected function initForm(Object $Object, $method = 'edit') { $error = array(); if (isset($_POST['submit'])) { $Object->setPost($_POST); //$fields = Locale::translate( Error::test( $Object ) ); if (count($fields)) { $error[] = 'Неверно заполнены поля: ' . implode(', ', Locale::translate($fields)); } else { if ($Object->save()) { if (!empty($_FILES['file']['tmp_name'])) { if (File::upload($Object, $_FILES['file'])) { $Object->save(); } else { if ($this->dropOnFailedUpload($Object)) { $Object->drop(); } } } if (!empty($_POST['detach'])) { if (File::detach($Object)) { $Object->save(); } } return $this->haltForm($Object, $method); } else { $error[] = 'Ошибка базы данных: ' . $Object->getError(); } } } $name = $this->getAliasName($method) ? $this->getAliasName($method) : $this->getModelName($method); $this->getView()->set($name, $Object); $this->getView()->set('Error', $error); return $this->getView()->render(); }
/** * Process a form submission * * @return void */ private function process() { /* |-------------------------------------------------------------------------- | Prep form and handler variables |-------------------------------------------------------------------------- | | We're going to assume success = true here to simplify code readability. | Checks already exist for require and validation so we simply flip the | switch there. | */ $success = true; $errors = array(); /* |-------------------------------------------------------------------------- | Hidden fields and $_POST hand off |-------------------------------------------------------------------------- | | We slide the hidden key out of the POST data and assign the rest to a | cleaner $submission variable. | */ $hidden = $_POST['hidden']; unset($_POST['hidden']); $submission = $_POST; /* |-------------------------------------------------------------------------- | Grab formset and collapse settings |-------------------------------------------------------------------------- | | Formset settings are merged on top of the default raven.yaml config file | to allow per-form overrides. | */ $formset_name = array_get($hidden, 'formset'); $formset = $formset_name . '.yaml'; if (File::exists('_config/add-ons/raven/formsets/' . $formset)) { $formset = Yaml::parse('_config/add-ons/raven/formsets/' . $formset); } elseif (File::exists('_config/formsets/' . $formset)) { $formset = Yaml::parse('_config/formsets/' . $formset); } else { $formset = array(); } if (!is_array($this->config)) { $this->log->warn('Could not find the config file.'); $this->config = array(); } $config = array_merge($this->config, $formset, array('formset' => $hidden['formset'])); /* |-------------------------------------------------------------------------- | Prep filters |-------------------------------------------------------------------------- | | We jump through some PHP hoops here to filter, sanitize and validate | our form inputs. | */ $allowed_fields = array_flip(array_get($formset, 'allowed', array())); $required_fields = array_flip(array_get($formset, 'required', array())); $validation_rules = isset($formset['validate']) ? $formset['validate'] : array(); $messages = isset($formset['messages']) ? $formset['messages'] : array(); $referrer = Request::getReferrer(); $return = array_get($hidden, 'return', $referrer); $error_return = array_get($hidden, 'error_return', $referrer); /* |-------------------------------------------------------------------------- | Allowed fields |-------------------------------------------------------------------------- | | It's best to only allow a set of predetermined fields to cut down on | spam and misuse. | */ if (count($allowed_fields) > 0) { $submission = array_intersect_key($submission, $allowed_fields); } /* |-------------------------------------------------------------------------- | Required fields |-------------------------------------------------------------------------- | | Requiring fields isn't required (ironic-five!), but if any are specified | and missing from the POST, we'll be squashing this submission right here | and sending back an array of missing fields. | */ if (count($required_fields) > 0) { $missing = array_flip(array_diff_key($required_fields, array_filter($submission))); if (count($missing) > 0) { foreach ($missing as $key => $field) { $errors['missing'][] = array('field' => $field); } $success = false; } } /* |-------------------------------------------------------------------------- | Validation |-------------------------------------------------------------------------- | | Run optional per-field validation. Any data failing the specified | validation rule will squash the submission and send back error messages | as specified in the formset. | */ $invalid = $this->validate($submission, $validation_rules); // Prepare a data array of fields and error messages use for template display if (count($invalid) > 0) { $errors['invalid'] = array(); foreach ($invalid as $field) { $errors['invalid'][] = array('field' => $field, 'message' => isset($messages[$field]) ? $messages[$field] : null); } $success = false; } /* |-------------------------------------------------------------------------- | Upload Files |-------------------------------------------------------------------------- | | Upload any files to their specified destination. | */ if (count($_FILES) > 0) { $files = array_intersect_key($_FILES, $allowed_fields); $upload_destination = array_get($config, 'upload_destination'); foreach ($files as $name => $file) { $submission[$name] = File::upload($file, $upload_destination); } } /* |-------------------------------------------------------------------------- | Hook: Pre Process |-------------------------------------------------------------------------- | | Allow pre-processing by other add-ons with the ability to kill the | success of the submission. Has access to the submission and config. | */ $success = Hook::run('raven', 'pre_process', 'replace', $success, compact('submission', 'config', 'success')); /* |-------------------------------------------------------------------------- | Form Identifier |-------------------------------------------------------------------------- | | In the event of multiple forms on a page, we'll be able to determine | which one was the one that had been triggered. | */ $this->flash->set('form_id', $hidden['raven']); /* |-------------------------------------------------------------------------- | Finalize & determine action |-------------------------------------------------------------------------- | | Send back the errors if validation or require fields are missing. | If successful, save to file (if enabled) and send notification | emails (if enabled). | */ if ($success) { // Akismet? $is_spam = false; if ($akismet = array_get($config, 'akismet') && array_get($config, 'akismet_api_key')) { $is_spam = $this->tasks->akismetCheck(array('permalink' => URL::makeFull(URL::getCurrent()), 'comment_type' => $formset_name, 'comment_author' => array_get($submission, array_get($akismet, 'author')), 'comment_author_email' => array_get($submission, array_get($akismet, 'email')), 'comment_author_url' => array_get($submission, array_get($akismet, 'url')), 'comment_content' => array_get($submission, array_get($akismet, 'content')))); } // Shall we save? if (array_get($config, 'submission_save_to_file', false) === true) { $file_prefix = Parse::template(array_get($config, 'file_prefix', ''), $submission); $file_suffix = Parse::template(array_get($config, 'file_suffix', ''), $submission); $file_prefix = $is_spam ? '_' . $file_prefix : $file_prefix; $this->save($submission, $config, $config['submission_save_path'], $is_spam); } // Shall we send? if (!$is_spam && array_get($config, 'send_notification_email', false) === true) { $this->send($submission, $config); } /* |-------------------------------------------------------------------------- | Hook: On Success |-------------------------------------------------------------------------- | | Allow events after the form as been processed. Has access to the | submission and config. | */ Hook::run('raven', 'on_success', null, null, array('submission' => $submission, 'config' => $config)); $this->flash->set('success', true); URL::redirect(URL::format($return)); } else { $this->flash->set('success', false); $this->flash->set('errors', $errors); $this->flash->set('old_values', $_POST); URL::redirect(URL::format($error_return)); } }
/** * The upload handler. * * @param int $id The Proud id. * @return string The HTML code. */ public function upload($id = null) { $Proud = new Proud(); $Proud = $Proud->findItem(array('Id = ' . $id)); if (isset($_POST['upload'])) { $files = array('image' => new Proud_Image(), 'example' => new Proud_Example()); foreach ($files as $id => $class) { if (isset($_FILES[$id])) { foreach ($_FILES[$id]['name'] as $i => $value) { $file = File::convertMultiple($_FILES[$id], $i); if (empty($file['tmp_name'])) { continue; } $class->Id = null; $class->ProudId = $Proud->Id; if ($class->save()) { if (File::upload($class, $file)) { $class->save(); } else { if ($this->dropOnFailedUpload($class)) { $class->drop(); } } } } } } } return $this->getView()->htmlUpload($Proud); }
/** * Add a group */ public function add($params) { $this->setView('add.php'); $this->setTitle(__('GROUP_ADD_TITLE')); $is_logged = isset(User_Model::$auth_data); $is_admin = $is_logged && User_Model::$auth_data['admin'] == '1'; // Authorization if (!$is_admin) { throw new ActionException('Page', 'error404'); } $group = array(); // Saving data if (isset($_POST['name']) && isset($_POST['creation_date']) && isset($_POST['mail']) && isset($_POST['description'])) { $uploaded_files = array(); try { // Members $members = array(); if (isset($_POST['members_ids']) && is_array($_POST['members_ids'])) { foreach ($_POST['members_ids'] as $id) { if (ctype_digit($id)) { $id = (int) $id; $members[$id] = array('title' => isset($_POST['member_title_' . $id]) ? $_POST['member_title_' . $id] : '', 'admin' => isset($_POST['member_admin_' . $id])); } } } // Other info $data = array('name' => $_POST['name'], 'creation_date' => $_POST['creation_date'], 'mail' => $_POST['mail'], 'description' => $_POST['description'], 'members' => $members); // Avatar if (isset($_FILES['avatar']) && !is_array($_FILES['avatar']['name'])) { if ($_FILES['avatar']['size'] > Config::UPLOAD_MAX_SIZE_PHOTO) { throw new FormException('avatar'); } if ($avatarpath = File::upload('avatar')) { $uploaded_files[] = $avatarpath; try { $img = new Image(); $img->load($avatarpath); $type = $img->getType(); if ($type == IMAGETYPE_JPEG) { $ext = 'jpg'; } else { if ($type == IMAGETYPE_GIF) { $ext = 'gif'; } else { if ($type == IMAGETYPE_PNG) { $ext = 'png'; } else { throw new Exception(); } } } if ($img->getWidth() > 800) { $img->setWidth(800, true); } $img->setType(IMAGETYPE_JPEG); $img->save($avatarpath); // Thumb $avatarthumbpath = $avatarpath . '.thumb'; $img->thumb(Config::$AVATARS_THUMBS_SIZES[0], Config::$AVATARS_THUMBS_SIZES[1]); $img->setType(IMAGETYPE_JPEG); $img->save($avatarthumbpath); unset($img); $uploaded_files[] = $avatarthumbpath; $data['avatar_path'] = $avatarthumbpath; $data['avatar_big_path'] = $avatarpath; } catch (Exception $e) { throw new FormException('avatar'); } } } $url_name = $this->model->create($data); Routes::redirect('group', array('group' => $url_name)); } catch (FormException $e) { foreach ($uploaded_files as $uploaded_file) { File::delete($uploaded_file); } foreach ($data as $key => $value) { $group[$key] = $value; } $group['members'] = Student_Model::getInfoByUsersIds(array_keys($members)); foreach ($group['members'] as &$member) { if (isset($members[(int) $member['user_id']])) { $member['title'] = $members[(int) $member['user_id']]['title']; $member['admin'] = $members[(int) $member['user_id']]['admin'] ? '1' : '0'; } } $this->set('form_error', $e->getError()); } } $this->set('group', $group); $this->addJSCode('Group.initEdit();'); }
function insertProcess() { $send = Request::get('send'); $valid = Validator::make(array('send.title' => 'min:1|slashes', 'send.keywords' => 'slashes', 'tags' => 'slashes', 'send.catid' => 'slashes', 'send.type' => 'slashes', 'send.allowcomment' => 'slashes')); if (!$valid) { throw new Exception("Error Processing Request: " . Validator::getMessage()); } $friendlyUrl = trim(String::makeFriendlyUrl($send['title'])); $getData = Post::get(array('where' => "where friendly_url='{$friendlyUrl}'")); if (isset($getData[0]['postid'])) { throw new Exception("This post exists in database."); } $uploadMethod = Request::get('uploadMethod'); switch ($uploadMethod) { case 'frompc': if (Request::hasFile('imageFromPC')) { if (Request::isImage('imageFromPC')) { $send['image'] = File::upload('imageFromPC'); } } break; case 'fromurl': if (Request::isImage('imageFromUrl')) { $url = Request::get('imageFromUrl'); $send['image'] = File::upload('uploadFromUrl'); } break; } $send['userid'] = Users::getCookieUserId(); if (!Request::has('send.catid')) { $loadCat = Categories::get(array('limitShow' => 1)); if (isset($loadCat[0]['catid'])) { $send['catid'] = $loadCat[0]['catid']; } } if (!($id = Post::insert($send))) { throw new Exception("Error. " . Database::$error); } $tags = trim(Request::get('tags')); $parse = explode(',', $tags); $total = count($parse); $insertData = array(); for ($i = 0; $i < $total; $i++) { $insertData[$i]['title'] = trim($parse[$i]); $insertData[$i]['postid'] = $id; } PostTags::insert($insertData); }
//make url friendly if (Input::get('pageid')) { $page = Page::find(Input::get('pageid')); } else { $page = new Page(); } $page->slug = $slug; $page->title = Input::get('title'); $page->summary = Input::get('summary'); $page->content = Input::get('content'); $page->publish = Input::get('publish'); $page->save(); return Redirect::to('admin/pages'); }), 'POST /admin/newmedia' => array('before' => 'auth', function () { $imagename = time() . Input::file('image.name'); File::upload('image', PUBLIC_PATH . 'img/' . $imagename); $newimage = PUBLIC_PATH . 'img/' . $imagename; $image = new Imagick($newimage); $image->scaleImage(400, 0); $image->writeImage(PUBLIC_PATH . 'img/medium_' . $imagename); $image->resizeImage(80, 80, Imagick::FILTER_LANCZOS, 1, TRUE); $image->writeImage(PUBLIC_PATH . 'img/thumb_' . $imagename); $image->destroy(); $media = new Media(); $media->filename = $imagename; $media->caption = Input::get('caption'); $media->meta = Input::get('meta'); $media->save(); return Redirect::to('admin/media'); }), 'POST /admin/newuser' => array('before' => 'auth', function () { $rules = array('firstname' => 'required|max:140', 'lastname' => 'required|max:140', 'email' => 'required|max:50|unique:users', 'role' => 'required', 'password' => 'required|max:50|between:6,16|confirmed');
public function process() { if ($this->field_data['tmp_name'] !== '') { return File::upload($this->field_data, $this->settings['destination'], true); } }