Вроде заработало так, как надо

This commit is contained in:
Krivchikov Dmitry 2014-08-03 20:49:26 +04:00
parent f653347ba8
commit 1dc15df6eb
17 changed files with 386 additions and 183 deletions

20
.gitignore vendored
View File

@ -1 +1,21 @@
ground/config.php ground/config.php
public/photos/*.jpg
public/photos/*.jpeg
public/photos/*.png
public/photos/*.gif
public/photos/small/*.jpg
public/photos/small/*.jpeg
public/photos/small/*.png
public/photos/small/*.gif
public/photos/middle/*.jpg
public/photos/middle/*.jpeg
public/photos/middle/*.png
public/photos/middle/*.gif
public/photos/big/*.jpg
public/photos/big/*.jpeg
public/photos/big/*.png
public/photos/big/*.gif

View File

@ -31,6 +31,7 @@ class App
private static $urlParams = array(); private static $urlParams = array();
private static $DB = null; private static $DB = null;
public static $user = null; public static $user = null;
public static $request = array();
/** /**
* Разбивает урл на контроллер, метод и выбирает параметры. * Разбивает урл на контроллер, метод и выбирает параметры.
@ -70,6 +71,8 @@ class App
$controller = self::$controller; $controller = self::$controller;
$action = self::$action; $action = self::$action;
self::fillRequest();
if (method_exists($controller, $action)) if (method_exists($controller, $action))
{ {
$controller::$action(); $controller::$action();
@ -139,6 +142,7 @@ class App
public static function redirect($url, $httpCode = 307) public static function redirect($url, $httpCode = 307)
{ {
header('Location: ' . $url, true, $httpCode); header('Location: ' . $url, true, $httpCode);
die;
} }
/** /**
@ -194,4 +198,13 @@ class App
return self::$urlParams; return self::$urlParams;
} }
private static function fillRequest()
{
self::$request = array(
'method' => isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : '',
'ajax' => isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest',
'refferer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
);
}
} }

View File

@ -28,26 +28,27 @@ class Image
} }
/** /**
* Ресайзит изображение. На входе запрос вида sizeX_sizeY_imgName.ext * Создаёт все требуемые размеры изображения и раскладывает их по папкам.
* @param type $name * @param type $imgName
*/ */
public static function resize($imgName, $sizeX, $sizeY = false, $quality = 85) public static function createAllSizes($imgName)
{ {
$dir = 'photos/'; $sizes = App::getConfig('images');
$newDir = 'photos/resize/'; $pathInfo = pathinfo($_SERVER['SCRIPT_FILENAME']);
$uploaddir = $pathInfo['dirname'] . '/photos/';
$sizeY = $sizeY ? $sizeY : $sizeX; foreach ($sizes as $dir => $size)
$oldImgName = $dir . $imgName;
$newImgName = $newDir . $sizeX . '_' . $sizeY . '_' . $imgName;
if (file_exists($newImgName) || self::imgResize($oldImgName, $newImgName, $sizeX, $sizeY, $quality))
{ {
return '/' . $newImgName; self::imgResize(
$uploaddir . $imgName, // Source - original image
$uploaddir . $dir . '/' . $imgName, // Destination
$size[0], // X
$size[1], // Y
$size[2] // Quelity
);
} }
return '/' . $oldImgName; return TRUE; // o_O
} }
/** /**

View File

@ -9,11 +9,12 @@ class JsonController extends Controller
static function actionPoints() static function actionPoints()
{ {
$points = Point::model()->getAll(); $points = Point::model()->getAll();
$categories = Category::model()->getAll(array('asArray'=>true)); $categories = Category::model()->getAll(array('asArray' => true));
$result = array(); $result = array();
foreach ($points as $point) { foreach ($points as $point)
{
$id = $point->id; $id = $point->id;
$result[$id]['id'] = $point->id; $result[$id]['id'] = $point->id;
$result[$id]['name'] = $point->name; $result[$id]['name'] = $point->name;
@ -40,8 +41,26 @@ class JsonController extends Controller
$point->descriptionHtml = nl2br($point->description); $point->descriptionHtml = nl2br($point->description);
$point->name = htmlspecialchars($point->name); $point->name = htmlspecialchars($point->name);
$imgs = $point->photos;
$categories = Category::model()->getAll(array('asArray'=>true)); if ($point->img == '' && !empty($imgs))
{
$img = array_shift($imgs);
$point->img = '/photos/small/' . $img->name;
}
$imgs = $point->photos;
if (!empty($imgs))
{
$tmp = array();
foreach ($imgs as $img)
{
$tmp[] = $img->name;
}
$point->images = $tmp;
}
$categories = Category::model()->getAll(array('asArray' => true));
$point->categoryIcon = $categories[$point->categoryId]['icon']; $point->categoryIcon = $categories[$point->categoryId]['icon'];
$point->categoryName = $categories[$point->categoryId]['name']; $point->categoryName = $categories[$point->categoryId]['name'];
@ -58,7 +77,7 @@ class JsonController extends Controller
*/ */
static function actionCategories() static function actionCategories()
{ {
$categories = Category::model()->getAll(array('asArray'=>true)); $categories = Category::model()->getAll(array('asArray' => true));
self::renderPartial('json.php', array( self::renderPartial('json.php', array(
'data' => $categories, 'data' => $categories,
@ -70,95 +89,148 @@ class JsonController extends Controller
*/ */
static function actionAddPoint() static function actionAddPoint()
{ {
$photos = array(); $errors = array();
$temp = pathinfo($_SERVER['SCRIPT_FILENAME']);
$uploaddir = $temp['dirname'] . '/photos/'; if (!App::$user)
// print_r($_FILES); $errors[8] = 'Вы не авторизованы! Пожалуйста, войдите.';
// print_r($_REQUEST); if (isset($_POST['id']) && $_POST['id'] && App::$user->isAdmin == 0)
// die; $errors[9] = 'Редактирование точек достурно только администратору!';
$photos = $images = array();
$ordering = $_POST['ordering'];
if (empty($errors) && !App::$request['ajax'] && isset($_POST['id']) && (int) $_POST['id'])
{
$id = (int) $_POST['id'];
$pathInfo = pathinfo($_SERVER['SCRIPT_FILENAME']);
$uploaddir = $pathInfo['dirname'] . '/photos/';
if (isset($_FILES) && !empty($_FILES)) if (isset($_FILES) && !empty($_FILES))
{ {
foreach ($_FILES['photos']['name'] as $key => $fileName) foreach ($_FILES['photos']['name'] as $key => $fileName)
{ {
$temp = pathinfo($_FILES['photos']['name'][$key]); $temp = pathinfo($_FILES['photos']['name'][$key]);
$extension = strtolower($temp['extension']) ? strtolower($temp['extension']) : 'jpg';
$foto = strtolower('_' . substr(md5($fileName . time()), 0, 5) . '.' . $temp['extension']); $photo = $id . strtolower('_' . substr(md5($fileName . time()), 0, 5) . '.' . $extension);
if (move_uploaded_file($_FILES['photos']['tmp_name'][$key], $uploaddir . $foto)) if (move_uploaded_file($_FILES['photos']['tmp_name'][$key], $uploaddir . $photo))
{ {
$photos[] = $foto; $photos[] = $photo;
} }
} }
} }
print_r($photos);
die;
$errors = array(); if (isset($_POST['imgs']) && !empty($_POST['imgs']))
{
foreach ($_POST['imgs'] as $key => $img)
{
if (mb_strpos($img, '://') !== false)
{
$temp = pathinfo($img);
$extension = strtolower($temp['extension']) ? strtolower($temp['extension']) : 'jpg';
$photo = $id . strtolower('_' . substr(md5($img . time()), 0, 5) . '.' . $extension);
if(!( isset($_POST['name']) && $_POST['name'] && strlen($_POST['name']) > 1 )) $errors[1]='Неверное название точки'; if (file_put_contents($uploaddir . $photo, file_get_contents($img)))
if(!( isset($_POST['img']) && $_POST['img'] && strlen($_POST['img']) > 13 )) $errors[2]='Плохая ссылка на изображение'; {
if(!( isset($_POST['description']) && $_POST['description'] && strlen($_POST['description']) > 25 )) $errors[3]='Слишком короткое описание'; $images[] = $photo;
if(!( isset($_POST['categoryId']) && $_POST['categoryId'] )) $errors[4]='Не задана категория точки'; }
if(!( isset($_POST['source']) )) $errors[5]='Не передано поле источкика информации. Допускается пустое значение.'; } else
if(!( isset($_POST['lat']) && $_POST['lat'] )) $errors[6]='Ошибочное значение широты'; {
if(!( isset($_POST['lng']) && $_POST['lng'] )) $errors[7]='Ошибочное значение долготы'; $images[] = $img;
if(!App::$user ) $errors[8]='Вы не авторизованы! Пожалуйста, войдите.'; }
if(isset($_POST['id']) && $_POST['id'] && App::$user->isAdmin == 0 ) $errors[9]='Редактирование точек достурно только администратору!'; }
}
$resPhotos = array();
foreach ($ordering as $order)
{
$resPhotos[] = $order == 'FILE' ? array_shift($photos) : array_shift($images);
}
if (empty($errors)) if (!empty($resPhotos))
{
App::DB()->query('DELETE FROM `poi`.`photos` WHERE `pointId` = ' . $id . ';');
$P = new Photo();
foreach ($resPhotos as $key => $photo)
{
$P->add(array(
'pointId' => $id,
'name' => $photo,
'ord' => $key,
));
Image::createAllSizes($photo);
}
}
App::redirect('/?point=' . $id);
}
if (!( isset($_POST['name']) && $_POST['name'] && strlen($_POST['name']) > 1 ))
$errors[1] = 'Неверное название точки';
if (!( isset($_POST['img']) && (int) $_POST['img']))
$errors[2] = 'Плохая ссылка на изображение';
if (!( isset($_POST['description']) && $_POST['description'] && strlen($_POST['description']) > 25 ))
$errors[3] = 'Слишком короткое описание';
if (!( isset($_POST['categoryId']) && $_POST['categoryId'] ))
$errors[4] = 'Не задана категория точки';
if (!( isset($_POST['source']) ))
$errors[5] = 'Не передано поле источкика информации. Допускается пустое значение.';
if (!( isset($_POST['lat']) && $_POST['lat'] ))
$errors[6] = 'Ошибочное значение широты';
if (!( isset($_POST['lng']) && $_POST['lng'] ))
$errors[7] = 'Ошибочное значение долготы';
if (!empty($errors))
{
header("HTTP/1.0 400 Bad Request");
header('Content-Type: application/json');
print json_encode($errors);
return false;
}
if (App::$request['ajax'])
{ {
$point = new Point(); $point = new Point();
unset($_POST['img']);
// Редактирование существующей точки
if (isset($_POST['id']) && $_POST['id']) if (isset($_POST['id']) && $_POST['id'])
{ {
// Редактирование существующей точки
$id = $_POST['id']; $id = (int) $_POST['id'];
$point = $point->getByPK($id); $point = $point->getByPK($id);
$point->setValues($_POST); $point->setValues($_POST);
$point->save(); $point->save();
} else
self::renderPartial('json.php', array( {
'data' => $point->id
));
die;
}
$_POST['author'] = App::$user->id; $_POST['author'] = App::$user->id;
$_POST['date'] = time(); $_POST['date'] = time();
$point->add($_POST); $point->add($_POST);
if ( $point->id ) if (!$point->id)
{
self::renderPartial('json.php', array(
'data' => $point->id
));
$ch = curl_init("http://sms.ru/sms/send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"api_id" => "2c2af6a7-a935-0e84-5952-599f5cd61905",
"to" => "79046106141, 79046106144",
"text" => "#".$point->id.": ".$point->name,
));
curl_exec($ch);
curl_close($ch);
}
else
{ {
header("HTTP/1.0 500 Internal Server Error"); header("HTTP/1.0 500 Internal Server Error");
die('Error 500 - Internal Server Error'); die('Error 500 - Internal Server Error');
} }
} if (!App::getConfig('disableSMS'))
else
{ {
header("HTTP/1.0 400 Bad Request"); $ch = curl_init("http://sms.ru/sms/send");
header('Content-Type: application/json'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
print json_encode($errors); curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"api_id" => "2c2af6a7-a935-0e84-5952-599f5cd61905",
"to" => "79046106141, 79046106144",
"text" => "#" . $point->id . ": " . $point->name,
));
curl_exec($ch);
curl_close($ch);
}
}
self::renderPartial('json.php', array(
'data' => $point->id
));
} }
} }
@ -215,11 +287,11 @@ class JsonController extends Controller
{ {
$address = isset($_GET['search']) ? $_GET['search'] : ''; $address = isset($_GET['search']) ? $_GET['search'] : '';
$res = @file_get_contents('http://geocode-maps.yandex.ru/1.x/?format=json&geocode='.urlencode($address)); $res = @file_get_contents('http://geocode-maps.yandex.ru/1.x/?format=json&geocode=' . urlencode($address));
$res = json_decode($res, true); $res = json_decode($res, true);
if (isset ($res['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['Point']['pos'])) if (isset($res['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['Point']['pos']))
$point = explode (' ', $res['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['Point']['pos']); $point = explode(' ', $res['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['Point']['pos']);
else else
$point = array(0, 0); $point = array(0, 0);
@ -229,4 +301,5 @@ class JsonController extends Controller
self::renderPartial('json.php', $coords); self::renderPartial('json.php', $coords);
} }
} }

View File

@ -65,14 +65,14 @@ class PageController extends Controller
$categories = new Category(); $categories = new Category();
$categories = $categories->getAll(); $categories = $categories->getAll();
$point->categoryIcon = $categories[$point->categoryId]['icon']; $point->categoryIcon = $categories[$point->categoryId]->icon;
$point->categoryName = $categories[$point->categoryId]['name']; $point->categoryName = $categories[$point->categoryId]->name;
self::render('point.php', array( self::render('point.php', array(
'point' => $point, 'point' => $point,
'categories' => $categories, 'categories' => $categories,
) 'photos' => $point->photos,
); ));
} else } else
{ {
App::error404(); App::error404();

17
ground/models/Photo.php Normal file
View File

@ -0,0 +1,17 @@
<?php
class Photo extends Model
{
function __construct($fromArray = array())
{
$this->_tableName_ = 'photos';
parent::__construct($fromArray);
$this->setRelation('point', 'pointId', 'Point', 'id', self::TO_ONE);
}
static function model()
{
return new self();
}
}

View File

@ -8,6 +8,7 @@ class Point extends Model
parent::__construct($fromArray); parent::__construct($fromArray);
$this->setRelation('category', 'categoryId', 'Category', 'id', self::TO_ONE); $this->setRelation('category', 'categoryId', 'Category', 'id', self::TO_ONE);
$this->setRelation('authorUser', 'author', 'User', 'id', self::TO_ONE); $this->setRelation('authorUser', 'author', 'User', 'id', self::TO_ONE);
$this->setRelation('photos', 'id', 'Photo', 'pointId', self::TO_MANY);
} }
static function model() static function model()

View File

@ -20,14 +20,11 @@
</div> </div>
<div class="form-group extraImage asLink"> <div class="form-group extraImage asLink">
<label class="control-label" for="img">Файлы и ссылки (URL) на изображения</label> <label class="control-label" for="imgs">Файлы и ссылки на изображения</label>
<label class="control-label error" for="img">(Что-то не так с сылкой на изображение)</label> <label class="control-label error" for="imgs">(Что-то не так с изображениями!)</label>
<div class="input-group"> <span class="btn btn-sm add button" onclick="addNewImage()" title="Добавить ещё одно изображение"><span class="glyphicon glyphicon-plus"></span></span>
<div class="input-group-addon type ico" title="Укажите ссылку на изображение"><span class="glyphicon glyphicon-link"></span></div>
<input type="text" id="" name="imgs[]" class="form-control" placeholder="http://" />
<div class="input-group-addon type button" onclick="switchType($(this))" title="Загрузить файл"><span class="glyphicon glyphicon-transfer"></span></div>
<div class="input-group-addon add button" onclick="addNewImage()" title="Добавить ещё одно изображение"><span class="glyphicon glyphicon-plus"></span></div>
</div> </div>
<div id="imgsContainer">
</div> </div>
<div class="form-group"> <div class="form-group">
@ -46,23 +43,22 @@
<div class="form-group"> <div class="form-group">
Координаты: Координаты:
<input type="text" id="addPointLat" name="lat" class="form-control input-sm" style="width: 145px; display: inline-block;" readonly="readonly" disabled="disabled"/> <input type="text" id="addPointLat" name="lat" class="form-control input-sm" style="width: 145px; display: inline-block;" readonly="readonly" />
<input type="text" id="addPointLng" name="lng" class="form-control input-sm" style="width: 145px; display: inline-block;" readonly="readonly" disabled="disabled"/> <input type="text" id="addPointLng" name="lng" class="form-control input-sm" style="width: 145px; display: inline-block;" readonly="readonly" />
<button type="button" class="btn btn-sm btn-default" onclick="editSetNewCoords();"><span class="glyphicon glyphicon-screenshot"></span> изменить координаты</button> <button type="button" class="btn btn-sm btn-default" onclick="editSetNewCoords();"><span class="glyphicon glyphicon-screenshot"></span> изменить координаты</button>
</div> </div>
</form> </form>
</div> </div>
<div class="modal-footer"> <div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button> <button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-primary" onclick="$('#addPointForm').submit();">Сохранить</button> <button type="button" class="btn btn-primary" onclick="addPoint();">Сохранить</button>
</div> </div>
<div id="newIm"> <div id="newIm">
<div class="form-group extraImage asLink" style="display: none;"> <div class="form-group extraImage asLink" style="display: none;">
<label class="control-label error" for="img">(Что-то не так с сылкой на изображение)</label>
<div class="input-group"> <div class="input-group">
<div class="input-group-addon type ico" title="Укажите ссылку на изображение"><span class="glyphicon glyphicon-link"></span></div> <div class="input-group-addon type ico" title="Укажите ссылку на изображение"><input type="hidden" class="ordering" name="ordering[]" value="LINK" /><span class="glyphicon glyphicon-link"></span></div>
<input type="text" name="imgs[]" class="form-control" /> <input type="text" name="imgs[]" class="form-control images" placeholder="http://" />
<div class="input-group-addon type button" onclick="switchType($(this))" title="Изменить поле на загрузку файла"><span class="glyphicon glyphicon-transfer"></span></div> <div class="input-group-addon type button" onclick="switchType($(this))" title="Изменить поле на загрузку файла"><span class="glyphicon glyphicon-transfer"></span></div>
<div class="input-group-addon remove button" onclick="removeInput($(this))" title="Удалить это поле"><span class="glyphicon glyphicon-trash"></span></div> <div class="input-group-addon remove button" onclick="removeInput($(this))" title="Удалить это поле"><span class="glyphicon glyphicon-trash"></span></div>
</div> </div>
@ -72,15 +68,23 @@
</div> </div>
</div> </div>
<script> <script>
function addNewImage() function addNewImage(link)
{ {
if ($('.extraImage', '#addPointForm').length < 10) if ($('.extraImage', '#addPointForm').length < 10)
$('.extraImage', '#newIm').clone().insertAfter($('.extraImage', '#addPointForm').last()).show(200); {
$('.extraImage', '#newIm').clone().appendTo('#imgsContainer').show(200);
if (link != undefined)
{
$('.form-control.images', '#addPointForm').last().attr('readonly', 'readonly').val(link);
$('.input-group-addon.type.button', '#addPointForm').remove();
}
}
} }
function removeInput(el) function removeInput(el)
{ {
$(el).parent().parent().hide(300, function(){$(el).remove()}); container = $(el).parent().parent();
container.hide(300, function(){container.remove()});
} }
function switchType(el) function switchType(el)
@ -88,6 +92,7 @@
container = $(el).parent().parent(); container = $(el).parent().parent();
if (container.hasClass('asLink')) if (container.hasClass('asLink'))
{ {
$('.ordering', container).val('FILE');
$('.ico span', container).removeClass('glyphicon-link').addClass('glyphicon-paperclip'); $('.ico span', container).removeClass('glyphicon-link').addClass('glyphicon-paperclip');
$('.form-control', container).attr('type', 'file').attr('name', 'photos[]'); $('.form-control', container).attr('type', 'file').attr('name', 'photos[]');
container.removeClass('asLink'); container.removeClass('asLink');
@ -96,6 +101,7 @@
} }
else else
{ {
$('.ordering', container).val('LINK');
$('.ico span', container).removeClass('glyphicon-paperclip').addClass('glyphicon-link'); $('.ico span', container).removeClass('glyphicon-paperclip').addClass('glyphicon-link');
$('.form-control', container).attr('type', 'text').attr('name', 'imgs[]'); $('.form-control', container).attr('type', 'text').attr('name', 'imgs[]');
container.addClass('asLink'); container.addClass('asLink');

View File

@ -18,6 +18,16 @@
<?= $point->descriptionHtml ?> <?= $point->descriptionHtml ?>
<br/> <br/>
<div style="text-align: center"> <?php if ($point->img): ?>
<div style="text-align: center">
<img src="<?= $point->img ?>" style="max-width: 800px;"> <img src="<?= $point->img ?>" style="max-width: 800px;">
</div> </div>
<?php endif; ?>
<?php if ($photos): ?>
<div style="text-align: center">
<?php foreach ($photos as $photo): ?>
<img src="/photos/<?= $photo->name ?>" style="max-width: 800px;">
<?php endforeach; ?>
</div>
<?php endif; ?>

51
public/apitest.php Normal file

File diff suppressed because one or more lines are too long

View File

@ -20,10 +20,11 @@ div.header a:hover {text-decoration: none;}
div.header a:hover h1 {cursor: pointer;} div.header a:hover h1 {cursor: pointer;}
div.add {cursor: pointer;} div.add {cursor: pointer;}
#addPointModal .extraImage .button {cursor: pointer;} #addPointModal .extraImage .button {cursor: pointer; background-color: #eeeeee;}
#addPointModal .extraImage .remove:hover {background-color: #d44950; color: #fff;} #addPointModal .extraImage .remove:hover {background-color: #f4bfbf;}
#addPointModal .extraImage .add:hover {background-color: #49d450; color: #fff;} #addPointModal .extraImage .add:hover {background-color: #bff4c8;}
#addPointModal .extraImage .type.button:hover {background-color: #ddd;} #addPointModal .extraImage .type.button:hover {background-color: #ddd;}
#addPointModal .extraImage .input-group-addon.type.button {border-left: 0px;}
.form-group .error {display: none;} .form-group .error {display: none;}
.form-group.has-error .error {display: inline-block;} .form-group.has-error .error {display: inline-block;}

View File

@ -1,22 +0,0 @@
### Основные точки ###
* Парки, заповедники и сады (forest)
* Усадьбы и замки (castle)
* Памятники и монументы (statue)
* Церкви и монастыри (cathedral)
* Архитектурные ансамбли (arch)
* Видовые площадки (photo)
* Реки, озёра и пляжи (lake)
* Водопады (waterfall)
* Пещеры (spelunking)
* Горы (mountaint)
* Сталкеры (radiation)
* Места для пикника и привала (picnic)
* Прочие интересные точки (other)
* Музеи (museum)
### Вспомогательные точки ###
* Место старта (man)
* Конечная точка (home)
* Информация (information)
Основной цвет: #22bb22

View File

@ -57,7 +57,7 @@ function init(lat, lng) {
if (status == statusHunting) if (status == statusHunting)
{ {
$('#addPointId').remove(); $('#addPointId').remove();
$('#addPointForm input').val(''); $('#addPointForm input:text').val('');
$("#addPointCategoryId option" ).attr('selected', null); $("#addPointCategoryId option" ).attr('selected', null);
$('#addPointLat').val(e.latlng.lat); $('#addPointLat').val(e.latlng.lat);
$('#addPointLng').val(e.latlng.lng); $('#addPointLng').val(e.latlng.lng);
@ -82,6 +82,7 @@ function init(lat, lng) {
$("#wayPoints").sortable(); $("#wayPoints").sortable();
$("#wayPoints").disableSelection(); $("#wayPoints").disableSelection();
$("#imgsContainer").sortable();
myMap.on('moveend', function(e) { myMap.on('moveend', function(e) {
if (!myMap._popup && $('#boxRoute').css('display') == 'none') if (!myMap._popup && $('#boxRoute').css('display') == 'none')
@ -188,11 +189,11 @@ function showInfo(id)
} }
description = description + data.descriptionHtml; description = description + data.descriptionHtml;
description = description + ' <a href="/page/point/id/' + id + '" target="blank">Подробнее...</a>';
if (data.source.length > 11) if (data.source.length > 11)
{ {
//description = description + ' <a href="/page/point/id/' + id + '" target="blank">Подробнее...</a>'; //description = description + ' <a href="' + data.source + '" target="blank">Подробнее...</a>';
description = description + ' <a href="' + data.source + '" target="blank">Подробнее...</a>';
} }
description = description + '</div><div class="clear"></div>'; description = description + '</div><div class="clear"></div>';
@ -294,6 +295,8 @@ function activateAddPoint()
$('#addPointButton').toggleClass('active'); $('#addPointButton').toggleClass('active');
if ($('#addPointButton').hasClass('active')) if ($('#addPointButton').hasClass('active'))
{ {
$('.extraImage','#imgsContainer').remove();
addNewImage();
$('#map').css('cursor', 'crosshair'); $('#map').css('cursor', 'crosshair');
setStatus(statusHunting) setStatus(statusHunting)
} }
@ -317,12 +320,21 @@ function addPoint()
{ {
setStatus(statusSendingToServer) setStatus(statusSendingToServer)
id = $('#addPointId').length ? $('#addPointId').val() : 0; id = $('#addPointId').length ? $('#addPointId').val() : 0;
hasImages = false;
$("input[name='imgs[]']", '#addPointForm').each(function(){
if ( $(this).val().length > 10)
hasImages = true;
});
$("input[name='photos[]']", '#addPointForm').each(function(){
if ( $(this).val().length > 5)
hasImages = true;
})
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "/json/addpoint/", url: "/json/addpoint/",
data: { data: {
name: $('#addPointName').val(), name: $('#addPointName').val(),
img: $('#addPointImg').val(), img: hasImages ? 1 : 0,
description: $('#addPointDescription').val(), description: $('#addPointDescription').val(),
categoryId: $('#addPointCategoryId').val(), categoryId: $('#addPointCategoryId').val(),
source: $('#addPointSource').val(), source: $('#addPointSource').val(),
@ -331,6 +343,12 @@ function addPoint()
id: id id: id
}, },
success: function(data) { success: function(data) {
if ($("input[name='photos[]']").length > 0 || $("input[name='imgs[]']").length > 0)
{
$('<input type="hidden" id="addPointId" name="id"/>').appendTo('#addPointForm').val(data);
$('#addPointForm').submit();
}
text = id ? 'Точка успешно отредактирована!' : 'Точка успешно добавлена!'; text = id ? 'Точка успешно отредактирована!' : 'Точка успешно добавлена!';
if ( id ) if ( id )
{ {
@ -380,7 +398,9 @@ function addPoint()
$('#addPointName').parent().addClass('has-error'); $('#addPointName').parent().addClass('has-error');
else else
if (k == 2) if (k == 2)
$('#addPointImg').parent().addClass('has-error'); {
$('.extraImage', '#addPointForm').addClass('has-error');
}
else else
if (k == 3) if (k == 3)
$('#addPointDescription').parent().addClass('has-error'); $('#addPointDescription').parent().addClass('has-error');
@ -413,7 +433,6 @@ function editPoint(id)
$('#addPointId').remove(); $('#addPointId').remove();
$('<input type="hidden" id="addPointId" name="id"/>').appendTo('#addPointForm').val(id); $('<input type="hidden" id="addPointId" name="id"/>').appendTo('#addPointForm').val(id);
$('#addPointName').val(pointsSources[id].name); $('#addPointName').val(pointsSources[id].name);
$('#addPointImg').val(pointsSources[id].img);
$('#addPointDescription').val(pointsSources[id].description); $('#addPointDescription').val(pointsSources[id].description);
$("#addPointCategoryId option" ).attr('selected', null); $("#addPointCategoryId option" ).attr('selected', null);
$("#addPointCategoryId option[value='"+pointsSources[id].categoryId+"']" ).attr('selected', 'selected'); $("#addPointCategoryId option[value='"+pointsSources[id].categoryId+"']" ).attr('selected', 'selected');
@ -421,6 +440,19 @@ function editPoint(id)
$('#addPointLat').val(pointsSources[id].lat); $('#addPointLat').val(pointsSources[id].lat);
$('#addPointLng').val(pointsSources[id].lng); $('#addPointLng').val(pointsSources[id].lng);
$('.extraImage','#imgsContainer').remove();
if (pointsSources[id].images != undefined && pointsSources[id].images.length > 0)
{
for(var i=0; i < pointsSources[id].images.length; i++)
{
addNewImage(pointsSources[id].images[i]);
}
}
else
{
addNewImage(pointsSources[id].img);
}
closePopup(); closePopup();
$('#addPointModal').modal('show'); $('#addPointModal').modal('show');
setStatus(statusEdit); setStatus(statusEdit);

0
public/photos/.gitkeep Normal file
View File

View File

View File

View File