AUTOFORMAT

This commit is contained in:
Krivchikov Dmitry 2015-08-09 00:03:11 +03:00
parent c70d82c57d
commit 29fba9e036
32 changed files with 411 additions and 507 deletions

View File

@ -2,27 +2,28 @@
function __autoload($className) function __autoload($className)
{ {
$dirs = array('classes','models','controllers'); $dirs = array('classes', 'models', 'controllers');
$loaded = false; $loaded = false;
foreach ($dirs as $dir) { foreach ($dirs as $dir) {
$fileName = dirname(__FILE__) . '/../ground/' . $dir. '/' . $className . '.php'; $fileName = dirname(__FILE__) . '/../ground/' . $dir . '/' . $className . '.php';
if (file_exists($fileName)){ if (file_exists($fileName)) {
$loaded = (bool) include $fileName; $loaded = (bool) include $fileName;
} }
} }
if (!$loaded){ if (!$loaded) {
App::error404('Class '.$className.' was not loaded!'); App::error404('Class ' . $className . ' was not loaded!');
return false; return false;
} }
return true; return true;
} }
class App class App
{ {
private static $url = array(); private static $url = array();
private static $controller = 'IndexController'; private static $controller = 'IndexController';
private static $action = 'actionIndex'; private static $action = 'actionIndex';
@ -38,16 +39,14 @@ class App
*/ */
private static function parseUrl() private static function parseUrl()
{ {
$url = explode('?', $_SERVER['REQUEST_URI']); $url = explode('?', $_SERVER['REQUEST_URI']);
self::$url = explode('/', $url[0]); self::$url = explode('/', $url[0]);
self::$controller = isset(self::$url[1]) && self::$url[1] ? ucfirst(self::$url[1]) . 'Controller' : self::$controller; self::$controller = isset(self::$url[1]) && self::$url[1] ? ucfirst(self::$url[1]) . 'Controller' : self::$controller;
self::$action = isset(self::$url[2]) && self::$url[2] ? 'action' . ucfirst(self::$url[2]) : self::$action; self::$action = isset(self::$url[2]) && self::$url[2] ? 'action' . ucfirst(self::$url[2]) : self::$action;
// Разбираем параметры из урла // Разбираем параметры из урла
if ((count(self::$url) > 3) && (self::$url[3])) if ((count(self::$url) > 3) && (self::$url[3])) {
{ for ($index = 3; $index < count(self::$url); $index = $index + 2) {
for ($index = 3; $index < count(self::$url); $index = $index + 2)
{
$paramName = self::$url[$index]; $paramName = self::$url[$index];
$paramValue = isset(self::$url[$index + 1]) && self::$url[$index + 1] ? self::$url[$index + 1] : NULL; $paramValue = isset(self::$url[$index + 1]) && self::$url[$index + 1] ? self::$url[$index + 1] : NULL;
self::$urlParams[$paramName] = $paramValue; self::$urlParams[$paramName] = $paramValue;
@ -73,8 +72,7 @@ class App
self::fillRequest(); self::fillRequest();
if (method_exists($controller, $action)) if (method_exists($controller, $action)) {
{
$controller::$action(); $controller::$action();
// if (method_exists($controller, '__construct')) { // if (method_exists($controller, '__construct')) {
// $class = new $controller(); // $class = new $controller();
@ -82,23 +80,18 @@ class App
// } else { // } else {
// $controller::$action(); // $controller::$action();
// } // }
} else } else {
{
self::error404(); self::error404();
} }
} }
public static function DB() public static function DB()
{ {
if (self::$DB === NULL && self::getConfig('DB')) if (self::$DB === NULL && self::getConfig('DB')) {
{ try {
try
{
$confDB = self::getConfig('DB'); $confDB = self::getConfig('DB');
self::$DB = new PDO('mysql:host=' . $confDB['host'] . ';dbname=' . $confDB['dbname'].';charset=utf8;', $confDB['user'], $confDB['password']); self::$DB = new PDO('mysql:host=' . $confDB['host'] . ';dbname=' . $confDB['dbname'] . ';charset=utf8;', $confDB['user'], $confDB['password']);
} } catch (PDOException $e) {
catch (PDOException $e)
{
echo $e->getMessage(); echo $e->getMessage();
} }
} }
@ -116,12 +109,10 @@ class App
// Пытаемся восстановить пользователя из сессии // Пытаемся восстановить пользователя из сессии
public static function userInit() public static function userInit()
{ {
if (isset($_SESSION['user_id']) && isset($_SESSION['user_key']) && $_SESSION['user_id'] && $_SESSION['user_key'] ) if (isset($_SESSION['user_id']) && isset($_SESSION['user_key']) && $_SESSION['user_id'] && $_SESSION['user_key']) {
{ $user = User::model()->getByPK((int) $_SESSION['user_id']);
$user = User::model()->getByPK((int)$_SESSION['user_id']);
if ( $user && md5($user->uid) == $_SESSION['user_key'] ) if ($user && md5($user->uid) == $_SESSION['user_key']) {
{
App::$user = $user; App::$user = $user;
} }
} }
@ -142,10 +133,10 @@ class App
} }
/** /**
* Перенаправление на другой URL * Перенаправление на другой URL
* @param type $url * @param type $url
* @param type $httpCode - по умолчанию 307, временный редирект * @param type $httpCode - по умолчанию 307, временный редирект
*/ */
public static function redirect($url, $httpCode = 307) public static function redirect($url, $httpCode = 307)
{ {
header('Location: ' . $url, true, $httpCode); header('Location: ' . $url, true, $httpCode);

View File

@ -4,95 +4,87 @@ abstract class Controller
{ {
static $layout = 'layout.php'; static $layout = 'layout.php';
static private $styles = array(); static private $styles = array();
static private $scripts = array(); static private $scripts = array();
static private $og = array(); static private $og = array();
static private $vars = array(); static private $vars = array();
static function addStyle($name)
{
if (array_search($name, self::$styles) === FALSE) {
self::$styles[] = $name;
}
}
static function addStyle($name) static function addScript($name)
{ {
if (array_search($name, self::$styles) === FALSE ) if (array_search($name, self::$scripts) === FALSE) {
{ self::$scripts[] = $name;
self::$styles[] = $name; }
} }
}
static function addScript($name)
{
if (array_search($name, self::$scripts) === FALSE )
{
self::$scripts[] = $name;
}
}
static function addVar($name, $value) static function addVar($name, $value)
{ {
self::$vars[$name] = $value; self::$vars[$name] = $value;
} }
/** /**
* Рендерит шаблон без лейаута. * Рендерит шаблон без лейаута.
* @param string $template - имя шаблона * @param string $template - имя шаблона
* @param array $data - передаваемые параметры * @param array $data - передаваемые параметры
* @param bool $return - вернуть результат в виде строки * @param bool $return - вернуть результат в виде строки
* @return string * @return string
*/ */
static function renderPartial($template, $data, $return = false) static function renderPartial($template, $data, $return = false)
{ {
if (!file_exists(App::getBasedir() . 'views/' . $template)) if (!file_exists(App::getBasedir() . 'views/' . $template))
return 'Template not found'; return 'Template not found';
if ($return) if ($return) {
{
$oldContentFormBuffer_temp = ob_get_clean(); $oldContentFormBuffer_temp = ob_get_clean();
ob_start(); ob_start();
} }
if ( $data && is_array($data) ) if ($data && is_array($data)) {
{
extract($data); extract($data);
} }
include App::getBasedir() . 'views/' . $template; include App::getBasedir() . 'views/' . $template;
if ($return) if ($return) {
{
$newContentFormBuffer_temp = ob_get_clean(); $newContentFormBuffer_temp = ob_get_clean();
ob_start(); ob_start();
echo $oldContentFormBuffer_temp; echo $oldContentFormBuffer_temp;
return $newContentFormBuffer_temp; return $newContentFormBuffer_temp;
} }
return true; return true;
} }
/** /**
* Рендерит шаблон и вписывает его в лейаут. * Рендерит шаблон и вписывает его в лейаут.
* @param string $template - имя шаблона * @param string $template - имя шаблона
* @param array $data - передаваемые параметры * @param array $data - передаваемые параметры
* @param bool $return - вернуть результат в виде строки * @param bool $return - вернуть результат в виде строки
* @return string * @return string
*/ */
static function render($template, $data, $return = false) static function render($template, $data, $return = false)
{ {
$content = self::renderPartial($template, $data, true); $content = self::renderPartial($template, $data, true);
$result = self::renderPartial(self::$layout, array( $result = self::renderPartial(self::$layout, array(
'content' => $content, 'content' => $content,
'styles' => self::$styles, 'styles' => self::$styles,
'scripts' => self::$scripts, 'scripts' => self::$scripts,
'vars' => self::$vars, 'vars' => self::$vars,
'data' => $data, 'data' => $data,
), true); ), true);
if ($return) if ($return) {
{
return $result; return $result;
} else } else {
{
echo $result; echo $result;
return true; return true;
} }
} }

View File

@ -2,6 +2,7 @@
class Coord class Coord
{ {
static function dergeeToMinute($input) static function dergeeToMinute($input)
{ {
$input = abs($input); $input = abs($input);
@ -9,6 +10,7 @@ class Coord
$degree = floor($input); $degree = floor($input);
$minute = 60 * ($input - $degree); $minute = 60 * ($input - $degree);
return $degree.'°'.substr($minute,0,6).'\''; return $degree . '°' . substr($minute, 0, 6) . '\'';
} }
} }

View File

@ -2,6 +2,7 @@
class Helper class Helper
{ {
public static function boolval($var) public static function boolval($var)
{ {
return (bool) $var; return (bool) $var;
@ -11,23 +12,19 @@ class Helper
{ {
preg_match_all("(\[#(\d+)>?(.*?)\])", $string, $links); preg_match_all("(\[#(\d+)>?(.*?)\])", $string, $links);
$links = isset($links[0]) ? $links[0] : FALSE; $links = isset($links[0]) ? $links[0] : FALSE;
if ($links) if ($links) {
{ foreach ($links as $link) {
foreach ($links as $link) $idAndLink = mb_substr($link, 2, -1);
{
$idAndLink = mb_substr($link, 2, -1);
$idAndLink = explode('>', $idAndLink); $idAndLink = explode('>', $idAndLink);
$linkId = $idAndLink[0]; $linkId = $idAndLink[0];
$linkName = isset($idAndLink[1])?$idAndLink[1]:'<span class="glyphicon glyphicon-link"></span>'; $linkName = isset($idAndLink[1]) ? $idAndLink[1] : '<span class="glyphicon glyphicon-link"></span>';
if ($linkId) if ($linkId) {
{
$linkPoint = Point::model()->getByPK($linkId); $linkPoint = Point::model()->getByPK($linkId);
if ($linkPoint->id) if ($linkPoint->id) {
{
$linkPoint->name = str_replace('"', 'ʺ', $linkPoint->name); $linkPoint->name = str_replace('"', 'ʺ', $linkPoint->name);
$string = str_replace($link, '<a href="'.$linkTemplate.$linkId.'" title="'.$linkPoint->name.'">'.$linkName.'</a>', $string); $string = str_replace($link, '<a href="' . $linkTemplate . $linkId . '" title="' . $linkPoint->name . '">' . $linkName . '</a>', $string);
} }
} }
} }
@ -41,7 +38,7 @@ class Helper
$og = array(); $og = array();
$og['title'] = str_replace('"', 'ʺ', $point->name) . ' [wikipoints.ru]'; $og['title'] = str_replace('"', 'ʺ', $point->name) . ' [wikipoints.ru]';
$point->description = str_replace('"', 'ʺ', $point->description); $point->description = str_replace('"', 'ʺ', $point->description);
$og['description'] = mb_substr($point->description, 0, 97, 'UTF-8').'...'; $og['description'] = mb_substr($point->description, 0, 97, 'UTF-8') . '...';
$og['site_name'] = 'WikiPoints: Лучшие выходные - это выходные в путешествии!'; $og['site_name'] = 'WikiPoints: Лучшие выходные - это выходные в путешествии!';
$og['type'] = 'website'; $og['type'] = 'website';
$og['url'] = 'http://wikipoints.ru/?point=' . $point->id; $og['url'] = 'http://wikipoints.ru/?point=' . $point->id;
@ -49,4 +46,5 @@ class Helper
return $og; return $og;
} }
} }

View File

@ -10,12 +10,10 @@ class Image
*/ */
public static function toBase64($path) public static function toBase64($path)
{ {
if ($path) if ($path) {
{
$type = pathinfo($path, PATHINFO_EXTENSION); $type = pathinfo($path, PATHINFO_EXTENSION);
if (!$type) if (!$type) {
{
return FALSE; return FALSE;
} }
@ -36,11 +34,10 @@ class Image
$sizes = App::getConfig('images'); $sizes = App::getConfig('images');
$pathInfo = pathinfo($_SERVER['SCRIPT_FILENAME']); $pathInfo = pathinfo($_SERVER['SCRIPT_FILENAME']);
$uploaddir = $pathInfo['dirname'] . '/photos/'; $uploaddir = $pathInfo['dirname'] . '/photos/';
$watermarkDir = App::getBasedir().'watermarks/'; $watermarkDir = App::getBasedir() . 'watermarks/';
foreach ($sizes as $dir => $size) foreach ($sizes as $dir => $size) {
{ $watermark = isset($size[3]) ? $watermarkDir . $size[3] : '';
$watermark = isset($size[3])?$watermarkDir.$size[3]:'';
self::imgResize( self::imgResize(
$uploaddir . $imgName, // Source - original image $uploaddir . $imgName, // Source - original image
$uploaddir . $dir . '/' . $imgName, // Destination $uploaddir . $dir . '/' . $imgName, // Destination
@ -57,10 +54,7 @@ class Image
public static function createCustomSize($imgFullName, $x, $y) public static function createCustomSize($imgFullName, $x, $y)
{ {
self::imgResize( self::imgResize(
$imgFullName, $imgFullName, null, $x, $y
null,
$x,
$y
); );
} }
@ -108,8 +102,7 @@ class Image
imagefill($idest, 0, 0, 0xFFFFFF); imagefill($idest, 0, 0, 0xFFFFFF);
imagecopyresampled($idest, $isrc, $new_left, $new_top, 0, 0, $new_width, $new_height, $size[0], $size[1]); imagecopyresampled($idest, $isrc, $new_left, $new_top, 0, 0, $new_width, $new_height, $size[0], $size[1]);
if ($watermark) if ($watermark) {
{
$stamp = imagecreatefrompng($watermark); $stamp = imagecreatefrompng($watermark);
$marge_right = 10; $marge_right = 10;

View File

@ -6,16 +6,16 @@
class User extends Model class User extends Model
{ {
function __construct($fromArray = array()) function __construct($fromArray = array())
{ {
$this->_tableName_ = 'Users'; $this->_tableName_ = 'Users';
parent::__construct($fromArray); parent::__construct($fromArray);
} }
static function model() static function model()
{ {
return new self(); return new self();
} }
} }
Просто новый пользователь: Просто новый пользователь:
@ -52,8 +52,7 @@ abstract class Model
{ {
$this->_primaryKey_ = $this->getPk(); $this->_primaryKey_ = $this->getPk();
if ($fromArray) if ($fromArray) {
{
$this->setValues($fromArray); $this->setValues($fromArray);
} }
} }
@ -67,26 +66,21 @@ abstract class Model
{ {
$this->_vals_[$name] = $value; $this->_vals_[$name] = $value;
if ($name == $this->_primaryKey_) if ($name == $this->_primaryKey_) {
{
$this->_id_ = $value; $this->_id_ = $value;
} }
} }
function __get($name) function __get($name)
{ {
if (isset($this->_vals_[$name])) if (isset($this->_vals_[$name])) {
{
return $this->_vals_[$name]; return $this->_vals_[$name];
} else } else {
{ if (isset($this->_relations_[$name])) {
if (isset($this->_relations_[$name]))
{
extract($this->_relations_[$name]); extract($this->_relations_[$name]);
$model = new $targetModel; $model = new $targetModel;
switch ($relationType) switch ($relationType) {
{
case self::TO_ONE: case self::TO_ONE:
return $model::model()->getOne($targetField, $this->$localField); return $model::model()->getOne($targetField, $this->$localField);
break; break;
@ -151,20 +145,19 @@ abstract class Model
function getAll($params = array()) function getAll($params = array())
{ {
$sql = 'SELECT * FROM `' . $this->_tableName_ . '`'; $sql = 'SELECT * FROM `' . $this->_tableName_ . '`';
$sql .= isset($params['where'])&&$params['where'] ? ' WHERE ' . $params['where'] : ''; $sql .= isset($params['where']) && $params['where'] ? ' WHERE ' . $params['where'] : '';
$sql .= isset($params['order'])&&$params['order'] ? ' ORDER BY ' . $params['order'] : ''; $sql .= isset($params['order']) && $params['order'] ? ' ORDER BY ' . $params['order'] : '';
$sql .= isset($params['limit'])&&$params['limit'] ? ' LIMIT ' . $params['limit'] : ''; $sql .= isset($params['limit']) && $params['limit'] ? ' LIMIT ' . $params['limit'] : '';
$res = App::DB()->query($sql); $res = App::DB()->query($sql);
$ready = array(); $ready = array();
$calledClass = get_called_class(); $calledClass = get_called_class();
while ($res && $row = $res->fetch(PDO::FETCH_ASSOC)) while ($res && $row = $res->fetch(PDO::FETCH_ASSOC)) {
{ $ready[$row[$this->_primaryKey_]] = isset($params['asArray']) && $params['asArray'] ? $row : new $calledClass($row);
$ready[$row[$this->_primaryKey_]] = isset($params['asArray'])&&$params['asArray'] ? $row : new $calledClass($row);
} }
return (isset($params['limit'])&&$params['limit']==1) ? array_shift($ready) : $ready; return (isset($params['limit']) && $params['limit'] == 1) ? array_shift($ready) : $ready;
} }
/** /**
@ -178,7 +171,7 @@ abstract class Model
return $this->getAll(array( return $this->getAll(array(
'where' => '`' . $whereField . '` = "' . $whereValue . '"', 'where' => '`' . $whereField . '` = "' . $whereValue . '"',
'limit' => 1 'limit' => 1
)); ));
} }
/** /**
@ -202,34 +195,29 @@ abstract class Model
unset($values[$this->_primaryKey_]); unset($values[$this->_primaryKey_]);
$q = array(); $q = array();
foreach ($values as $val) foreach ($values as $val) {
{
$q[] = '?'; $q[] = '?';
} }
var_dump('INSERT INTO `' . $this->_tableName_ . '` (`' . implode('`, `', array_keys($values)) . '`) VALUES (' . implode(', ', array_values($q)) . ') ');die; var_dump('INSERT INTO `' . $this->_tableName_ . '` (`' . implode('`, `', array_keys($values)) . '`) VALUES (' . implode(', ', array_values($q)) . ') ');
die;
$res = App::DB()->prepare_query('INSERT INTO `' . $this->_tableName_ . '` (`' . implode('`, `', array_keys($values)) . '`) VALUES (' . implode(', ', array_values($q)) . ') ', self::arrayWithTypes($values)); $res = App::DB()->prepare_query('INSERT INTO `' . $this->_tableName_ . '` (`' . implode('`, `', array_keys($values)) . '`) VALUES (' . implode(', ', array_values($q)) . ') ', self::arrayWithTypes($values));
if ($res) if ($res) {
{
throw new Exception('MySQL error #' . $res->errno . ' - ' . $res->error); throw new Exception('MySQL error #' . $res->errno . ' - ' . $res->error);
} }
return $this->getByPK(App::DB()->insert_id); return $this->getByPK(App::DB()->insert_id);
} }
function add($values) function add($values)
{ {
$request = App::DB()->prepare('INSERT INTO ' . $this->_tableName_ . ' (' . implode(',', array_keys($values)) . ') values (:' . implode(', :', array_keys($values)) . ')'); $request = App::DB()->prepare('INSERT INTO ' . $this->_tableName_ . ' (' . implode(',', array_keys($values)) . ') values (:' . implode(', :', array_keys($values)) . ')');
if ( $request->execute((array) $values) ) if ($request->execute((array) $values)) {
{ return $this->getByPK(App::DB()->lastInsertId());
return $this->getByPK(App::DB()->lastInsertId()); } else {
} return false;
else }
{
return false;
}
} }
/** /**
@ -238,8 +226,7 @@ abstract class Model
*/ */
function setValues($values) function setValues($values)
{ {
if (isset($values[$this->_primaryKey_])) if (isset($values[$this->_primaryKey_])) {
{
$this->_id_ = $values[$this->_primaryKey_]; $this->_id_ = $values[$this->_primaryKey_];
} }
@ -252,14 +239,10 @@ abstract class Model
*/ */
function save2() function save2()
{ {
if (!$this->_id_ || !$this->_vals_) if (!$this->_id_ || !$this->_vals_) {
{ if ($this->_vals_) {
if ($this->_vals_)
{
return $this->add($this->_vals_); return $this->add($this->_vals_);
} } else {
else
{
return FALSE; return FALSE;
} }
} }
@ -275,27 +258,23 @@ abstract class Model
} }
function save() function save()
{ {
if (!$this->_id_ || !$this->_vals_) if (!$this->_id_ || !$this->_vals_) {
{ if ($this->_vals_) {
if ($this->_vals_)
{
return $this->add($this->_vals_); return $this->add($this->_vals_);
} } else {
else
{
return FALSE; return FALSE;
} }
} }
$values = $this->_vals_; $values = $this->_vals_;
unset($values[$this->_primaryKey_]); unset($values[$this->_primaryKey_]);
$request = App::DB()->prepare('UPDATE ' . $this->_tableName_ . ' SET ' . implode('=?, ', array_keys($values)) . '=? WHERE '.$this->_primaryKey_.'='.$this->_id_); $request = App::DB()->prepare('UPDATE ' . $this->_tableName_ . ' SET ' . implode('=?, ', array_keys($values)) . '=? WHERE ' . $this->_primaryKey_ . '=' . $this->_id_);
$res = $request->execute(array_values($values)); $res = $request->execute(array_values($values));
return $res ? $this : FALSE; return $res ? $this : FALSE;
} }
/** /**
* Возвращает значения полей объекта в виде ассоциативного массива. * Возвращает значения полей объекта в виде ассоциативного массива.

View File

@ -14,7 +14,7 @@ return array(
'middle' => array(555, 450, 90, 'middle.png'), 'middle' => array(555, 450, 90, 'middle.png'),
'big' => array(1110, 900, 90, 'big.png'), 'big' => array(1110, 900, 90, 'big.png'),
), ),
//'version' => trim(file_get_contents(dirname(__FILE__).'/version')), //'version' => trim(file_get_contents(dirname(__FILE__).'/version')),
'metrika' => true, 'metrika' => true,
'ganalytics' => true, 'ganalytics' => true,
'disableSMS' => false, 'disableSMS' => false,

View File

@ -3,9 +3,9 @@
class ImagesController extends Controller class ImagesController extends Controller
{ {
static function actionGet() static function actionGet()
{ {
$pointId = (int) App::getParam('id'); $pointId = (int) App::getParam('id');
$width = (int) App::getParam('width'); $width = (int) App::getParam('width');
$height = (int) App::getParam('height'); $height = (int) App::getParam('height');
@ -17,32 +17,32 @@ class ImagesController extends Controller
$height = 200; $height = 200;
} }
if (!$pointId) { if (!$pointId) {
App::error404(); App::error404();
}
$point = Point::model()->getByPK($pointId);
if (!$point) {
App::error404();
}
$photos = $point->photos;
$img = array_shift($photos);
if ($img) {
$photo = $photo = App::getBasedir().'../public/'.'photos/'.$img->name;
} else {
$photo = $photo = App::getBasedir().'../public/'.'img/noPhoto.png';
}
if (!file_exists($photo)) {
$photo = $photo = App::getBasedir().'../public/'.'img/noPhoto.png';
} }
Image::createCustomSize($photo, $width, $height); $point = Point::model()->getByPK($pointId);
if (!$point) {
App::error404();
}
$photos = $point->photos;
$img = array_shift($photos);
if ($img) {
$photo = $photo = App::getBasedir() . '../public/' . 'photos/' . $img->name;
} else {
$photo = $photo = App::getBasedir() . '../public/' . 'img/noPhoto.png';
}
if (!file_exists($photo)) {
$photo = $photo = App::getBasedir() . '../public/' . 'img/noPhoto.png';
}
Image::createCustomSize($photo, $width, $height);
// print $photo; // print $photo;
} }
} }

View File

@ -44,18 +44,15 @@ class IndexController extends Controller
$category = Category::model()->getAll(array('order' => 'ord ASC')); $category = Category::model()->getAll(array('order' => 'ord ASC'));
$routes = array(); $routes = array();
if (App::$user && App::$user->id) if (App::$user && App::$user->id) {
{
$routes = Route::model()->getByAuthor(App::$user->id); $routes = Route::model()->getByAuthor(App::$user->id);
self::addVar('user', App::$user->id); self::addVar('user', App::$user->id);
} else } else {
{
self::addVar('user', '0'); self::addVar('user', '0');
} }
$favorites = array(); $favorites = array();
if (App::$user && App::$user->id) if (App::$user && App::$user->id) {
{
$favorites = Favorite::model()->getAllMy(); $favorites = Favorite::model()->getAllMy();
} }
@ -74,8 +71,7 @@ class IndexController extends Controller
} }
$og = array(); $og = array();
if (isset($_GET['point']) && $_GET['point'] && is_numeric($_GET['point'])) if (isset($_GET['point']) && $_GET['point'] && is_numeric($_GET['point'])) {
{
$id = (int) $_GET['point']; $id = (int) $_GET['point'];
$point = Point::model()->getByPK($id); $point = Point::model()->getByPK($id);
@ -88,8 +84,7 @@ class IndexController extends Controller
self::addVar('pointLat', $point->lat); self::addVar('pointLat', $point->lat);
self::addVar('pointLng', $point->lng); self::addVar('pointLng', $point->lng);
} else if (isset($_GET['point']) && $_GET['point'] && strtolower($_GET['point']) == 'random') } else if (isset($_GET['point']) && $_GET['point'] && strtolower($_GET['point']) == 'random') {
{
$og['title'] = 'Случайная точка на wikipoints.ru'; $og['title'] = 'Случайная точка на wikipoints.ru';
$og['description'] = 'Загляните сюда: http://vk.com/wikipoints Случайная точка на карте - лучший способ узнать что-то новое!'; $og['description'] = 'Загляните сюда: http://vk.com/wikipoints Случайная точка на карте - лучший способ узнать что-то новое!';
$og['site_name'] = 'WikiPoints - ' . $res['pointsCount'] . ' или даже больше поводов не сидеть дома'; $og['site_name'] = 'WikiPoints - ' . $res['pointsCount'] . ' или даже больше поводов не сидеть дома';
@ -130,8 +125,7 @@ class IndexController extends Controller
$user = User::model()->getByUID($uLoginUser['identity']); $user = User::model()->getByUID($uLoginUser['identity']);
if (!$user->id) if (!$user->id) {
{
$user = $user->add(array( $user = $user->add(array(
'uid' => $uLoginUser['identity'], 'uid' => $uLoginUser['identity'],
'nick' => $uLoginUser['nickname'], 'nick' => $uLoginUser['nickname'],
@ -141,14 +135,13 @@ class IndexController extends Controller
'photo' => $uLoginUser['photo_big'], 'photo' => $uLoginUser['photo_big'],
)); ));
if (!$user) if (!$user) {
{
return false; return false;
} }
} }
App::userLogin($user); App::userLogin($user);
App::redirect(isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:'/'); App::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '/');
} }
static function actionSitemap() static function actionSitemap()
@ -156,8 +149,7 @@ class IndexController extends Controller
$xml = new SimpleXMLElement('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>'); $xml = new SimpleXMLElement('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>');
$articles = Article::model()->getAll(array('order' => 'ID DESC', 'asArray' => true)); $articles = Article::model()->getAll(array('order' => 'ID DESC', 'asArray' => true));
foreach ($articles as $article) foreach ($articles as $article) {
{
$url = $xml->addChild('url'); $url = $xml->addChild('url');
$url->addChild('loc', 'http://wikipoints.ru/page/article/id/' . $article['id']); $url->addChild('loc', 'http://wikipoints.ru/page/article/id/' . $article['id']);
$url->addChild('lastmod', date("Y-m-d", strtotime('- 5 days'))); $url->addChild('lastmod', date("Y-m-d", strtotime('- 5 days')));
@ -166,8 +158,7 @@ class IndexController extends Controller
} }
$points = Point::model()->getAll(array('order' => 'ID DESC', 'asArray' => true)); $points = Point::model()->getAll(array('order' => 'ID DESC', 'asArray' => true));
foreach ($points as $point) foreach ($points as $point) {
{
$url = $xml->addChild('url'); $url = $xml->addChild('url');
$url->addChild('loc', 'http://wikipoints.ru/page/point/id/' . $point['id']); $url->addChild('loc', 'http://wikipoints.ru/page/point/id/' . $point['id']);
$url->addChild('lastmod', date("Y-m-d", $point['date'])); $url->addChild('lastmod', date("Y-m-d", $point['date']));
@ -195,7 +186,7 @@ class IndexController extends Controller
} }
$points = array(); $points = array();
foreach ($route as $pointId){ foreach ($route as $pointId) {
if ((int) $pointId) { if ((int) $pointId) {
$points[] = Point::model()->getByPK($pointId); $points[] = Point::model()->getByPK($pointId);
} }

View File

@ -11,7 +11,7 @@ class JsonController extends Controller
if (App::$user && App::$user->isAdmin == 1) { if (App::$user && App::$user->isAdmin == 1) {
$points = Point::model()->getAll(); $points = Point::model()->getAll();
} else { } else {
$minEditDate = isset($_GET['time']) ? (int)$_GET['time'] : 0; $minEditDate = isset($_GET['time']) ? (int) $_GET['time'] : 0;
if (!isset($_GET['bounds']) || !isset($_GET['bounds'][0]) || !isset($_GET['bounds'][1]) || !isset($_GET['bounds'][2]) || !isset($_GET['bounds'][3])) { if (!isset($_GET['bounds']) || !isset($_GET['bounds'][0]) || !isset($_GET['bounds'][1]) || !isset($_GET['bounds'][2]) || !isset($_GET['bounds'][3])) {
$points = Point::model()->getAllPublished(false, $minEditDate); $points = Point::model()->getAllPublished(false, $minEditDate);
} else { } else {
@ -28,8 +28,7 @@ class JsonController extends Controller
$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;
@ -50,8 +49,7 @@ class JsonController extends Controller
static function actionPoint() static function actionPoint()
{ {
$id = (int) App::getParam('id'); $id = (int) App::getParam('id');
if ($id) if ($id) {
{
$point = Point::model()->getByPK($id); $point = Point::model()->getByPK($id);
$point->descriptionHtml = nl2br($point->description); $point->descriptionHtml = nl2br($point->description);
@ -61,19 +59,16 @@ class JsonController extends Controller
$imgs = $point->photos; $imgs = $point->photos;
$photosCount = 1; $photosCount = 1;
if ($point->img == '' && !empty($imgs)) if ($point->img == '' && !empty($imgs)) {
{
$img = array_shift($imgs); $img = array_shift($imgs);
$point->img = $img->name; $point->img = $img->name;
} }
$imgs = $point->photos; $imgs = $point->photos;
if (!empty($imgs)) if (!empty($imgs)) {
{
$tmp = array(); $tmp = array();
$photosCount = count($imgs); $photosCount = count($imgs);
foreach ($imgs as $img) foreach ($imgs as $img) {
{
$tmp[] = $img->name; $tmp[] = $img->name;
} }
$point->images = $tmp; $point->images = $tmp;
@ -88,8 +83,7 @@ class JsonController extends Controller
$point->iLike = Like::model()->checkIsMy($id); $point->iLike = Like::model()->checkIsMy($id);
self::renderPartial('json.php', $point->getValues()); self::renderPartial('json.php', $point->getValues());
} else } else {
{
App::error404(); App::error404();
} }
} }
@ -113,61 +107,49 @@ class JsonController extends Controller
{ {
$errors = array(); $errors = array();
if (!App::$user) if (!App::$user) {
{
$errors[8] = 'Вы не авторизованы! Пожалуйста, войдите.'; $errors[8] = 'Вы не авторизованы! Пожалуйста, войдите.';
} }
if (isset($_POST['id']) && $_POST['id'] && App::$user->isAdmin == 0) if (isset($_POST['id']) && $_POST['id'] && App::$user->isAdmin == 0) {
{
$point = new Point(); $point = new Point();
$id = (int) $_POST['id']; $id = (int) $_POST['id'];
$point = $point->getByPK($id); $point = $point->getByPK($id);
if ($point->author != App::$user->id || $point->moderate == 1) if ($point->author != App::$user->id || $point->moderate == 1) {
{
$errors[9] = 'Редактирование точек достурно только администратору или автору!'; $errors[9] = 'Редактирование точек достурно только администратору или автору!';
} }
} }
$photos = $images = array(); $photos = $images = array();
if (empty($errors) && !App::$request['ajax'] && isset($_POST['id']) && (int) $_POST['id']) if (empty($errors) && !App::$request['ajax'] && isset($_POST['id']) && (int) $_POST['id']) {
{
$id = (int) $_POST['id']; $id = (int) $_POST['id'];
$pathInfo = pathinfo($_SERVER['SCRIPT_FILENAME']); $pathInfo = pathinfo($_SERVER['SCRIPT_FILENAME']);
$uploaddir = $pathInfo['dirname'] . '/photos/'; $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'; $extension = strtolower($temp['extension']) ? strtolower($temp['extension']) : 'jpg';
$photo = $id . strtolower('_' . substr(md5($fileName . time()), 0, 5) . '.' . $extension); $photo = $id . strtolower('_' . substr(md5($fileName . time()), 0, 5) . '.' . $extension);
if (move_uploaded_file($_FILES['photos']['tmp_name'][$key], $uploaddir . $photo)) if (move_uploaded_file($_FILES['photos']['tmp_name'][$key], $uploaddir . $photo)) {
{
$photos[] = $photo; $photos[] = $photo;
} }
} }
} }
if (isset($_POST['imgs']) && !empty($_POST['imgs'])) if (isset($_POST['imgs']) && !empty($_POST['imgs'])) {
{ foreach ($_POST['imgs'] as $key => $img) {
foreach ($_POST['imgs'] as $key => $img) if (mb_strpos($img, '://') !== false) {
{
if (mb_strpos($img, '://') !== false)
{
$temp = pathinfo($img); $temp = pathinfo($img);
$extension = strtolower($temp['extension']) ? strtolower($temp['extension']) : 'jpg'; $extension = strtolower($temp['extension']) ? strtolower($temp['extension']) : 'jpg';
$photo = $id . strtolower('_' . substr(md5($img . time()), 0, 5) . '.' . $extension); $photo = $id . strtolower('_' . substr(md5($img . time()), 0, 5) . '.' . $extension);
if (file_put_contents($uploaddir . $photo, file_get_contents($img))) if (file_put_contents($uploaddir . $photo, file_get_contents($img))) {
{
PhotoLinks::addLink($photo, $img); PhotoLinks::addLink($photo, $img);
$images[] = $photo; $images[] = $photo;
} }
} else } else {
{
$images[] = $img; $images[] = $img;
} }
} }
@ -175,18 +157,15 @@ class JsonController extends Controller
$resPhotos = array(); $resPhotos = array();
$ordering = $_POST['ordering']; $ordering = $_POST['ordering'];
foreach ($ordering as $order) foreach ($ordering as $order) {
{
$resPhotos[] = $order == 'FILE' ? array_shift($photos) : array_shift($images); $resPhotos[] = $order == 'FILE' ? array_shift($photos) : array_shift($images);
} }
if (!empty($resPhotos)) if (!empty($resPhotos)) {
{
App::DB()->query('DELETE FROM `poi`.`photos` WHERE `pointId` = ' . $id . ';'); App::DB()->query('DELETE FROM `poi`.`photos` WHERE `pointId` = ' . $id . ';');
$P = new Photo(); $P = new Photo();
foreach ($resPhotos as $key => $photo) foreach ($resPhotos as $key => $photo) {
{
$P->add(array( $P->add(array(
'pointId' => $id, 'pointId' => $id,
'name' => $photo, 'name' => $photo,
@ -221,21 +200,18 @@ class JsonController extends Controller
if (!( isset($_POST['lng']) && $_POST['lng'] )) if (!( isset($_POST['lng']) && $_POST['lng'] ))
$errors[7] = 'Ошибочное значение долготы'; $errors[7] = 'Ошибочное значение долготы';
if (!empty($errors)) if (!empty($errors)) {
{
header("HTTP/1.0 400 Bad Request"); header("HTTP/1.0 400 Bad Request");
header('Content-Type: application/json'); header('Content-Type: application/json');
print json_encode($errors); print json_encode($errors);
return false; return false;
} }
if (App::$request['ajax']) if (App::$request['ajax']) {
{
$point = new Point(); $point = new Point();
unset($_POST['img']); unset($_POST['img']);
if (isset($_POST['id']) && $_POST['id']) if (isset($_POST['id']) && $_POST['id']) {
{
// Редактирование существующей точки // Редактирование существующей точки
$id = (int) $_POST['id']; $id = (int) $_POST['id'];
$_POST['dateEdit'] = time(); $_POST['dateEdit'] = time();
@ -243,22 +219,19 @@ class JsonController extends Controller
$point = $point->getByPK($id); $point = $point->getByPK($id);
$point->setValues($_POST); $point->setValues($_POST);
$point->save(); $point->save();
} else } else {
{
$_POST['author'] = App::$user->id; $_POST['author'] = App::$user->id;
$_POST['date'] = time(); $_POST['date'] = time();
$_POST['dateEdit'] = time(); $_POST['dateEdit'] = time();
$_POST['moderate'] = (App::$user && App::$user->isAdmin == 1) ? $_POST['moderate'] : 0; $_POST['moderate'] = (App::$user && App::$user->isAdmin == 1) ? $_POST['moderate'] : 0;
$point->add($_POST); $point->add($_POST);
if (!$point->id) if (!$point->id) {
{
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')) if (!App::getConfig('disableSMS')) {
{
$ch = curl_init("http://sms.ru/sms/send"); $ch = curl_init("http://sms.ru/sms/send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 10);
@ -296,12 +269,10 @@ class JsonController extends Controller
static function actionRoute() static function actionRoute()
{ {
$id = (int) App::getParam('id'); $id = (int) App::getParam('id');
if ($id) if ($id) {
{
$route = Route::model()->getByPK($id); $route = Route::model()->getByPK($id);
self::renderPartial('json.php', $route->points); self::renderPartial('json.php', $route->points);
} else } else {
{
App::error404(); App::error404();
} }
} }
@ -309,18 +280,15 @@ class JsonController extends Controller
static function actionDeleteRoute() static function actionDeleteRoute()
{ {
$id = (int) App::getParam('id'); $id = (int) App::getParam('id');
if ($id && App::$user) if ($id && App::$user) {
{
$route = Route::model()->getByPK($id); $route = Route::model()->getByPK($id);
if ($route->author == App::$user->id) if ($route->author == App::$user->id) {
{
$route->delete($id); $route->delete($id);
} }
self::renderPartial('json.php', true); self::renderPartial('json.php', true);
} else } else {
{
App::error404(); App::error404();
} }
} }
@ -347,8 +315,7 @@ class JsonController extends Controller
static function actionAddRemoveFavorites() static function actionAddRemoveFavorites()
{ {
$id = (int) App::getParam('id'); $id = (int) App::getParam('id');
if (!$id || !App::$user) if (!$id || !App::$user) {
{
App::error404(); App::error404();
} }
self::renderPartial('json.php', Helper::boolval(Favorite::addRemove($id))); self::renderPartial('json.php', Helper::boolval(Favorite::addRemove($id)));
@ -357,8 +324,7 @@ class JsonController extends Controller
static function actionAddRemoveLike() static function actionAddRemoveLike()
{ {
$id = (int) App::getParam('id'); $id = (int) App::getParam('id');
if (!$id || !App::$user) if (!$id || !App::$user) {
{
App::error404(); App::error404();
} }
self::renderPartial('json.php', Helper::boolval(Like::addRemove($id))); self::renderPartial('json.php', Helper::boolval(Like::addRemove($id)));
@ -369,20 +335,16 @@ class JsonController extends Controller
$search = isset($_GET['query']) ? $_GET['query'] : ''; $search = isset($_GET['query']) ? $_GET['query'] : '';
$results = array(); $results = array();
if ($search) if ($search) {
{
// ====== POINTS ============ // ====== POINTS ============
$points = Point::model()->searchByString($search); $points = Point::model()->searchByString($search);
if (!empty($points)) if (!empty($points)) {
{ foreach ($points as $point) {
foreach ($points as $point) $results[] = array('value' => $point->name, 'data' => '/?point=' . $point->id);
{
$results[] = array('value' => $point->name, 'data' => '/?point='.$point->id);
} }
} }
if (count($results) < 10) if (count($results) < 10) {
{
// ====== YANDEX ============ // ====== YANDEX ============
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://geocode-maps.yandex.ru/1.x/?geocode=' . urlencode($search)); curl_setopt($ch, CURLOPT_URL, 'http://geocode-maps.yandex.ru/1.x/?geocode=' . urlencode($search));
@ -391,17 +353,13 @@ class JsonController extends Controller
$out = null; $out = null;
$out = curl_exec($ch); // выполняем запрос curl - обращаемся к сервера php.su $out = curl_exec($ch); // выполняем запрос curl - обращаемся к сервера php.su
if (!empty($out)) if (!empty($out)) {
{
$obj = simplexml_load_string($out); $obj = simplexml_load_string($out);
if (isset($obj->GeoObjectCollection->metaDataProperty->GeocoderResponseMetaData->found)) if (isset($obj->GeoObjectCollection->metaDataProperty->GeocoderResponseMetaData->found)) {
{
$count = (int) $obj->GeoObjectCollection->metaDataProperty->GeocoderResponseMetaData->found; $count = (int) $obj->GeoObjectCollection->metaDataProperty->GeocoderResponseMetaData->found;
if ($count > 0) if ($count > 0) {
{ for ($index = 0; $index < $count && $index < 5 && count($results) < 25; $index++) {
for ($index = 0; $index < $count && $index < 5 && count($results) < 25; $index++)
{
$name = (string) $obj->GeoObjectCollection->featureMember[$index]->GeoObject->name; $name = (string) $obj->GeoObjectCollection->featureMember[$index]->GeoObject->name;
$coords = explode(' ', (string) $obj->GeoObjectCollection->featureMember[$index]->GeoObject->Point->pos); $coords = explode(' ', (string) $obj->GeoObjectCollection->featureMember[$index]->GeoObject->Point->pos);
$lat = $coords[1]; $lat = $coords[1];
@ -424,18 +382,16 @@ class JsonController extends Controller
static function actionArticle() static function actionArticle()
{ {
$id = (int) App::getParam('id'); $id = (int) App::getParam('id');
if ($id) if ($id) {
{
$article = Article::model()->getByPK($id); $article = Article::model()->getByPK($id);
if (!$article) { if (!$article) {
die; die;
} }
self::renderPartial('modals/article.php', self::renderPartial('modals/article.php', array(
array( 'title' => $article->title,
'title' => $article->title, 'text' => $article->text,
'text' => $article->text, ));
));
} }
} }
@ -446,11 +402,10 @@ class JsonController extends Controller
if (!$article) { if (!$article) {
die; die;
} }
self::renderPartial('modals/pointAgreement.php', self::renderPartial('modals/pointAgreement.php', array(
array( 'title' => $article->title,
'title' => $article->title, 'text' => $article->text,
'text' => $article->text, ));
));
} }
} }

View File

@ -2,6 +2,7 @@
class Article extends Model class Article extends Model
{ {
function __construct($fromArray = array()) function __construct($fromArray = array())
{ {
$this->_tableName_ = 'articles'; $this->_tableName_ = 'articles';
@ -15,4 +16,3 @@ class Article extends Model
} }
} }

View File

@ -2,6 +2,7 @@
class Category extends Model class Category extends Model
{ {
function __construct($fromArray = array()) function __construct($fromArray = array())
{ {
$this->_tableName_ = 'categories'; $this->_tableName_ = 'categories';
@ -13,5 +14,5 @@ class Category extends Model
{ {
return new self(); return new self();
} }
}
}

View File

@ -28,11 +28,9 @@ class Favorite extends Model
$res = self::model()->getAll(array('where' => '`userId` = ' . (int) App::$user->id . ' AND `pointId` = ' . (int) $pointId, 'limit' => 1)); $res = self::model()->getAll(array('where' => '`userId` = ' . (int) App::$user->id . ' AND `pointId` = ' . (int) $pointId, 'limit' => 1));
if ($res) if ($res) {
{
return Helper::boolval(Favorite::model()->delete($res->id)); return Helper::boolval(Favorite::model()->delete($res->id));
} else } else {
{
return Favorite::model()->add(array('userId' => App::$user->id, 'pointId' => $pointId)); return Favorite::model()->add(array('userId' => App::$user->id, 'pointId' => $pointId));
} }
} }

View File

@ -28,11 +28,9 @@ class Like extends Model
$res = self::model()->getAll(array('where' => '`userId` = ' . (int) App::$user->id . ' AND `pointId` = ' . (int) $pointId, 'limit' => 1)); $res = self::model()->getAll(array('where' => '`userId` = ' . (int) App::$user->id . ' AND `pointId` = ' . (int) $pointId, 'limit' => 1));
if ($res) if ($res) {
{
return Helper::boolval(Like::model()->delete($res->id)); return Helper::boolval(Like::model()->delete($res->id));
} else } else {
{
return Like::model()->add(array('userId' => App::$user->id, 'pointId' => $pointId)); return Like::model()->add(array('userId' => App::$user->id, 'pointId' => $pointId));
} }
} }

View File

@ -2,6 +2,7 @@
class Photo extends Model class Photo extends Model
{ {
function __construct($fromArray = array()) function __construct($fromArray = array())
{ {
$this->_tableName_ = 'photos'; $this->_tableName_ = 'photos';
@ -14,5 +15,5 @@ class Photo extends Model
{ {
return new self(); return new self();
} }
}
}

View File

@ -2,6 +2,7 @@
class PhotoLinks extends Model class PhotoLinks extends Model
{ {
function __construct($fromArray = array()) function __construct($fromArray = array())
{ {
$this->_tableName_ = 'photoLinks'; $this->_tableName_ = 'photoLinks';
@ -17,8 +18,8 @@ class PhotoLinks extends Model
{ {
$parsedUrl = parse_url($url); $parsedUrl = parse_url($url);
$photoDetails = explode('_', $photo); $photoDetails = explode('_', $photo);
$pointId = (int)$photoDetails[0]; $pointId = (int) $photoDetails[0];
App::DB()->query('INSERT INTO photoLinks VALUES ("'.$photo.'", "'.$pointId.'","'.$url.'","'.$parsedUrl['host'].'") ON DUPLICATE KEY UPDATE url=url;'); App::DB()->query('INSERT INTO photoLinks VALUES ("' . $photo . '", "' . $pointId . '","' . $url . '","' . $parsedUrl['host'] . '") ON DUPLICATE KEY UPDATE url=url;');
} }
static function getCaption($photo) static function getCaption($photo)
@ -31,5 +32,5 @@ class PhotoLinks extends Model
return $photolink->host ? $photolink->host : $photolink->url; return $photolink->host ? $photolink->host : $photolink->url;
} }
}
}

View File

@ -2,6 +2,7 @@
class Point extends Model class Point extends Model
{ {
function __construct($fromArray = array()) function __construct($fromArray = array())
{ {
$this->_tableName_ = 'points'; $this->_tableName_ = 'points';
@ -19,15 +20,14 @@ class Point extends Model
public function getImg($size = 'small') public function getImg($size = 'small')
{ {
$img = $this->img; $img = $this->img;
if ($img == '') if ($img == '') {
{
$photos = $this->photos; $photos = $this->photos;
$img = array_shift($photos); $img = array_shift($photos);
if (!$img) if (!$img)
return null; return null;
$img = '/photos/'.$size.'/'.$img->name; $img = '/photos/' . $size . '/' . $img->name;
} }
return $img; return $img;
@ -68,12 +68,11 @@ class Point extends Model
LIMIT 6;'; LIMIT 6;';
$res = App::DB()->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)); $res = App::DB()->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$res->execute(array(':lat' => $lat, ':lng' => $lng, ':minLat' => $lat-1, ':minLng' => $lng-1, ':maxLat' => $lat+1, ':maxLng' => $lng+1)); $res->execute(array(':lat' => $lat, ':lng' => $lng, ':minLat' => $lat - 1, ':minLng' => $lng - 1, ':maxLat' => $lat + 1, ':maxLng' => $lng + 1));
$ready = array(); $ready = array();
$calledClass = get_called_class(); $calledClass = get_called_class();
while ($res && $row = $res->fetch(PDO::FETCH_ASSOC)) while ($res && $row = $res->fetch(PDO::FETCH_ASSOC)) {
{
$ready[] = new $calledClass($row); $ready[] = new $calledClass($row);
} }
@ -96,16 +95,15 @@ class Point extends Model
$userId = App::$user ? App::$user->id : 0; $userId = App::$user ? App::$user->id : 0;
$minEditDate = intval($minEditDate); $minEditDate = intval($minEditDate);
if ($bounds) { if ($bounds) {
$b0 = $bounds[0]<$bounds[2]?$bounds[0]:$bounds[2]; $b0 = $bounds[0] < $bounds[2] ? $bounds[0] : $bounds[2];
$b2 = $bounds[0]<$bounds[2]?$bounds[2]:$bounds[0]; $b2 = $bounds[0] < $bounds[2] ? $bounds[2] : $bounds[0];
$b1 = $bounds[1]<$bounds[3]?$bounds[1]:$bounds[3]; $b1 = $bounds[1] < $bounds[3] ? $bounds[1] : $bounds[3];
$b3 = $bounds[1]<$bounds[3]?$bounds[3]:$bounds[1]; $b3 = $bounds[1] < $bounds[3] ? $bounds[3] : $bounds[1];
return $this->getAll(array('where' => "(`moderate` = 1 OR `author` = $userId) AND (`dateEdit` >= $minEditDate) AND (`lat` BETWEEN '$b0' AND '$b2') AND(`lng` BETWEEN '$b1' AND '$b3')")); return $this->getAll(array('where' => "(`moderate` = 1 OR `author` = $userId) AND (`dateEdit` >= $minEditDate) AND (`lat` BETWEEN '$b0' AND '$b2') AND(`lng` BETWEEN '$b1' AND '$b3')"));
} else { } else {
return $this->getAll(array('where' => "(`moderate` = 1 OR `author` = ".$userId.") AND (`dateEdit` >= $minEditDate)")); return $this->getAll(array('where' => "(`moderate` = 1 OR `author` = " . $userId . ") AND (`dateEdit` >= $minEditDate)"));
} }
} }
} }

View File

@ -2,6 +2,7 @@
class Route extends Model class Route extends Model
{ {
function __construct($fromArray = array()) function __construct($fromArray = array())
{ {
$this->_tableName_ = 'routes'; $this->_tableName_ = 'routes';
@ -15,7 +16,7 @@ class Route extends Model
function getByAuthor($authorId) function getByAuthor($authorId)
{ {
return $this->getAll(array('where'=>'`author` = '.$authorId)); return $this->getAll(array('where' => '`author` = ' . $authorId));
} }
}
}

View File

@ -2,6 +2,7 @@
class User extends Model class User extends Model
{ {
function __construct($fromArray = array()) function __construct($fromArray = array())
{ {
$this->_tableName_ = 'users'; $this->_tableName_ = 'users';
@ -17,15 +18,12 @@ class User extends Model
function getByUID($uid) function getByUID($uid)
{ {
$res = App::DB()->query('SELECT `id` FROM `' . $this->_tableName_ . '` WHERE `uid` = "' . $uid . '"'); $res = App::DB()->query('SELECT `id` FROM `' . $this->_tableName_ . '` WHERE `uid` = "' . $uid . '"');
if ($res) if ($res) {
{
$res = $res->fetch(PDO::FETCH_ASSOC); $res = $res->fetch(PDO::FETCH_ASSOC);
$user = $this->getByPK((int)$res['id']); $user = $this->getByPK((int) $res['id']);
return $user; return $user;
} } else {
else
{
return false; return false;
} }
} }
@ -34,5 +32,5 @@ class User extends Model
{ {
return Point::model()->getCountByUser($this->id); return Point::model()->getCountByUser($this->id);
} }
}
}

View File

@ -9,7 +9,7 @@
<div style="text-align: justify;"> <div style="text-align: justify;">
<?php <?php
print $article->text; print $article->text;
?> ?>
</div> </div>

View File

@ -7,13 +7,13 @@
<h1>Ошибка 404 - страница не найдена!</h1> <h1>Ошибка 404 - страница не найдена!</h1>
<hr/> <hr/>
<br/> <br/>
<noindex> <noindex>
<div style="text-align: center;"> <div style="text-align: center;">
<h2>Не беда! Возможно вас заинтересует точка «<?= $point->name ?>»?</h2> <h2>Не беда! Возможно вас заинтересует точка «<?= $point->name ?>»?</h2>
<a href="/page/point/id/<?= $point->id ?>"> <a href="/page/point/id/<?= $point->id ?>">
<img src="<?= $point->getImg() ?>" style="max-width: 400px; margin: 0 20px 10px 0;" /> <img src="<?= $point->getImg() ?>" style="max-width: 400px; margin: 0 20px 10px 0;" />
</a> </a>
</div> </div>
</noindex> </noindex>
</body> </body>
</html> </html>

View File

@ -1,14 +1,21 @@
<?php if (App::getConfig('ganalytics')): ?> <?php if (App::getConfig('ganalytics')): ?>
<script> <script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (function (i, s, o, g, r, a, m) {
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), i['GoogleAnalyticsObject'] = r;
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) i[r] = i[r] || function () {
})(window,document,'script','//www.google-analytics.com/analytics.js','ga'); (i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-56791930-1', 'auto'); ga('create', 'UA-56791930-1', 'auto');
ga('send', 'pageview'); ga('send', 'pageview');
</script> </script>
<?php endif; ?> <?php endif; ?>

View File

@ -1,8 +1,8 @@
<?php <?php
$addWithoutConfirm = false; $addWithoutConfirm = false;
if (App::$user) { if (App::$user) {
$addWithoutConfirm = Point::model()->getCountByUser(App::$user->id) > 0; $addWithoutConfirm = Point::model()->getCountByUser(App::$user->id) > 0;
} }
?> ?>
<div id="map"></div> <div id="map"></div>
<div id="control"> <div id="control">
@ -18,7 +18,7 @@
<?php if ($user): ?> <?php if ($user): ?>
<div class="glyphicon glyphicon-map-marker _t" id="addPointButton" title="Добавить точку" onclick="<?= $addWithoutConfirm ? 'activateAddPoint()' : 'showPointagreement()'; ?>"></div> <div class="glyphicon glyphicon-map-marker _t" id="addPointButton" title="Добавить точку" onclick="<?= $addWithoutConfirm ? 'activateAddPoint()' : 'showPointagreement()'; ?>"></div>
<div class="glyphicon glyphicon-star _c boxButtonFavorites" onclick="openBox('Favorites')" title="Хочу посетить"></div> <div class="glyphicon glyphicon-star _c boxButtonFavorites" onclick="openBox('Favorites')" title="Хочу посетить"></div>
<div class="glyphicon glyphicon-cloud-download _c boxButtonRoutes" onclick="openBox('Routes')" title="Мои маршруты"></div> <div class="glyphicon glyphicon-cloud-download _c boxButtonRoutes" onclick="openBox('Routes')" title="Мои маршруты"></div>
<div class="glyphicon glyphicon-user _b boxButtonUser" onclick="openBox('User')" title="Профиль"></div> <div class="glyphicon glyphicon-user _b boxButtonUser" onclick="openBox('User')" title="Профиль"></div>
@ -85,7 +85,7 @@
<?php endforeach; ?> <?php endforeach; ?>
<?php else: ?> <?php else: ?>
Ваши закладки пока пусты. Ваши закладки пока пусты.
<?php endif; ?> <?php endif; ?>
</div> </div>
</div> </div>
<div id="boxRoutes"> <div id="boxRoutes">
@ -96,8 +96,8 @@
<div class="route" onclick="loadRoute(<?= $route->id ?>)"><span onclick="deleteRoute(<?= $route->id ?>); <div class="route" onclick="loadRoute(<?= $route->id ?>)"><span onclick="deleteRoute(<?= $route->id ?>);
$(this).parent().remove(); $(this).parent().remove();
event.stopPropagation();">&times;</span> <?= $route->name ?></div> event.stopPropagation();">&times;</span> <?= $route->name ?></div>
<?php endforeach; ?> <?php endforeach; ?>
<?php else: ?> <?php else: ?>
У вас пока нет сохраненных маршрутов. У вас пока нет сохраненных маршрутов.
<?php endif; ?> <?php endif; ?>
</div> </div>
@ -118,7 +118,7 @@
</map> </map>
<?php if (isset($categoryArray)): ?> <?php if (isset($categoryArray)): ?>
<script type="text/javascript"> <script type="text/javascript">
var categoryArray = '<?= json_encode($categoryArray)?>'; var categoryArray = '<?= json_encode($categoryArray) ?>';
</script> </script>
<?php endif; ?> <?php endif; ?>
<script> <script>
@ -127,13 +127,13 @@
$('#vkBigLogo').remove(); $('#vkBigLogo').remove();
} else { } else {
setTimeout(function () { setTimeout(function () {
$('#vkBigLogo').css({'display':'block'}).animate({'margin-left': "-225px"}, 1500); $('#vkBigLogo').css({'display': 'block'}).animate({'margin-left': "-225px"}, 1500);
}, 10000); }, 10000);
} }
}) })
function hideBigLogo() { function hideBigLogo() {
$.cookie('doNotShowVKgroup', true, { expires: 100, path: '/' }); $.cookie('doNotShowVKgroup', true, {expires: 100, path: '/'});
$('#vkBigLogo').animate({'margin-left': "285px"}, 1500, function () { $('#vkBigLogo').animate({'margin-left': "285px"}, 1500, function () {
$('#vkBigLogo').remove(); $('#vkBigLogo').remove();
}); });

View File

@ -1,5 +1,5 @@
<?php <?php
header('Content-Type: application/json'); header('Content-Type: application/json');
echo json_encode($data); echo json_encode($data);

File diff suppressed because one or more lines are too long

View File

@ -21,9 +21,9 @@
<?php if ($vars): ?> <?php if ($vars): ?>
<script type="text/javascript"> <script type="text/javascript">
<?php foreach ($vars as $varName => $var): ?> <?php foreach ($vars as $varName => $var): ?>
var <?= $varName ?> = '<?= $var ?>'; var <?= $varName ?> = '<?= $var ?>';
<?php endforeach; ?> <?php endforeach; ?>
</script> </script>
<?php endif; ?> <?php endif; ?>
@ -39,38 +39,37 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Ubuntu:400&subset=Cyrillic"> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Ubuntu:400&subset=Cyrillic">
<link rel="apple-touch-icon" href="/img/touch-icon-iphone.png"> <link rel="apple-touch-icon" href="/img/touch-icon-iphone.png">
<link rel="apple-touch-icon" sizes="76x76" href="/img/touch-icon-ipad.png"> <link rel="apple-touch-icon" sizes="76x76" href="/img/touch-icon-ipad.png">
<link rel="apple-touch-icon" sizes="120x120" href="/img/touch-icon-iphone-retina.png"> <link rel="apple-touch-icon" sizes="120x120" href="/img/touch-icon-iphone-retina.png">
<link rel="apple-touch-icon" sizes="152x152" href="/img/touch-icon-ipad-retina.png"> <link rel="apple-touch-icon" sizes="152x152" href="/img/touch-icon-ipad-retina.png">
</head> </head>
<body style="padding: 10px 25px; overflow-y: scroll;"> <body style="padding: 10px 25px; overflow-y: scroll;">
<div class="header"> <div class="header">
<a href="/"><img src="/img/logo.png" title="WIKIPOINTS.RU" /></a> <a href="/"><img src="/img/logo.png" title="WIKIPOINTS.RU" /></a>
</div> </div>
<?= isset($content) && !empty($content) ? $content : 'No content =(' ?> <?= isset($content) && !empty($content) ? $content : 'No content =(' ?>
<?= self::renderPartial('metrika.php', array(), true) ?> <?= self::renderPartial('metrika.php', array(), true) ?>
<?= self::renderPartial('ganalytics.php', array(), true) ?> <?= self::renderPartial('ganalytics.php', array(), true) ?>
</body> </body>
<script lang="javascript"> <script lang="javascript">
function setSizeForAdditional(){ function setSizeForAdditional() {
width = $('.col-md-12').width()/6-4; width = $('.col-md-12').width() / 6 - 4;
if(width < 100) if (width < 100)
width = $('.col-md-12').width()/3-4; width = $('.col-md-12').width() / 3 - 4;
height = width/4*3; height = width / 4 * 3;
$('.pagePoinsNearCards').width(width);
$('.pagePoinsNearCardsImg').width(width);
$('.pagePoinsNearCards').height(height);
$('.pagePoinsNearCardsImg').height(height);
}
$('.pagePoinsNearCards').width(width); setSizeForAdditional();
$('.pagePoinsNearCardsImg').width(width);
$('.pagePoinsNearCards').height(height);
$('.pagePoinsNearCardsImg').height(height);
}
setSizeForAdditional(); $(window).resize(function () {
setSizeForAdditional();
$( window ).resize(function() { });
setSizeForAdditional(); </script>
}); </html>
</script>
</html>

View File

@ -17,9 +17,9 @@
<?php if ($vars): ?> <?php if ($vars): ?>
<script type="text/javascript"> <script type="text/javascript">
<?php foreach ($vars as $varName => $var): ?> <?php foreach ($vars as $varName => $var): ?>
var <?= $varName ?> = '<?= $var ?>'; var <?= $varName ?> = '<?= $var ?>';
<?php endforeach; ?> <?php endforeach; ?>
</script> </script>
<?php endif; ?> <?php endif; ?>
@ -31,7 +31,7 @@
<hr/> <hr/>
<?= isset($content) && !empty($content) ? $content : 'No content =(' ?> <?= isset($content) && !empty($content) ? $content : 'No content =(' ?>
<script> <script>
window.onload=window.print(); window.onload = window.print();
</script> </script>
<?= self::renderPartial('metrika.php', array(), true) ?> <?= self::renderPartial('metrika.php', array(), true) ?>
<?= self::renderPartial('ganalytics.php', array(), true) ?> <?= self::renderPartial('ganalytics.php', array(), true) ?>

View File

@ -31,8 +31,8 @@
<div class="form-group"> <div class="form-group">
<label class="control-label" for="categoryId">Тип</label> <label class="control-label" for="categoryId">Тип</label>
<select id="addPointCategoryId" name="categoryId" class="form-control"> <select id="addPointCategoryId" name="categoryId" class="form-control">
<?php foreach ($categories as $category): ?> <?php foreach ($categories as $category): ?>
<option value="<?= $category->id ?>"><?= $category->name ?></option> <option value="<?= $category->id ?>"><?= $category->name ?></option>
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
</div> </div>
@ -51,7 +51,7 @@
</form> </form>
</div> </div>
<div class="modal-footer"> <div class="modal-footer">
<select id="moderate" name="moderate" class="form-control" style="width: 40%; display: <?= (App::$user && App::$user->isAdmin == 1)?'inline-block':'none'?>; padding-top: 5px; float: left;"> <select id="moderate" name="moderate" class="form-control" style="width: 40%; display: <?= (App::$user && App::$user->isAdmin == 1) ? 'inline-block' : 'none' ?>; padding-top: 5px; float: left;">
<option value="hide">Скрыта - на модераци</option> <option value="hide">Скрыта - на модераци</option>
<option value="show">Опубликована</option> <option value="show">Опубликована</option>
</select> </select>
@ -91,7 +91,9 @@
function removeInput(el) function removeInput(el)
{ {
container = $(el).parent().parent(); container = $(el).parent().parent();
container.hide(300, function(){container.remove()}); container.hide(300, function () {
container.remove()
});
} }
function switchType(el) function switchType(el)
@ -122,13 +124,13 @@
} }
function showPreview(el) { function showPreview(el) {
img = $('input.images',el.parent()).val(); img = $('input.images', el.parent()).val();
if ($('input.ordering',el.parent()).val() == 'FILE' || img.length < 12) { if ($('input.ordering', el.parent()).val() == 'FILE' || img.length < 12) {
return true; return true;
} }
if (img.toLowerCase().indexOf('http') == -1 ) { if (img.toLowerCase().indexOf('http') == -1) {
img = '/photos/small/' + img; img = '/photos/small/' + img;
} }

View File

@ -6,9 +6,9 @@
<h4 class="modal-title" id="myModalLabel">Список доступных категорий</h4> <h4 class="modal-title" id="myModalLabel">Список доступных категорий</h4>
</div> </div>
<div class="modal-body"> <div class="modal-body">
<?php foreach ($categories as $category): ?> <?php foreach ($categories as $category): ?>
<img src="<?=$category->icon?>"> - <a href="/page/points/category/<?=$category->id?>"><?=$category->name?></a><br/> <img src="<?= $category->icon ?>"> - <a href="/page/points/category/<?= $category->id ?>"><?= $category->name ?></a><br/>
<?php endforeach; ?> <?php endforeach; ?>
</div> </div>
<div class="modal-footer"> <div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">OK</button> <button type="button" class="btn btn-default" data-dismiss="modal">OK</button>

View File

@ -1,5 +1,5 @@
<?php <?php
$index = 0; $index = 0;
?> ?>
<div id="pageSmoothBackground" style="background-image: url(<?= $point->getImg('middle') ?>);"></div> <div id="pageSmoothBackground" style="background-image: url(<?= $point->getImg('middle') ?>);"></div>
<div class="container" style="background-color: rgba(255,255,255, 0.8);margin-top: -10px;padding-bottom: 30px;"> <div class="container" style="background-color: rgba(255,255,255, 0.8);margin-top: -10px;padding-bottom: 30px;">
@ -19,10 +19,10 @@
</nobr> </nobr>
&nbsp;&nbsp;/&nbsp;&nbsp; &nbsp;&nbsp;/&nbsp;&nbsp;
<a href="/?point=<?= $point->id ?>">На карте</a> <a href="/?point=<?= $point->id ?>">На карте</a>
<?php if($user && $user->isAdmin):?> <?php if ($user && $user->isAdmin): ?>
&nbsp;&nbsp;/&nbsp;&nbsp; &nbsp;&nbsp;/&nbsp;&nbsp;
<a href="/?point=<?= $point->id ?>&edit=true">Редактировать</a> <a href="/?point=<?= $point->id ?>&edit=true">Редактировать</a>
<?php endif;?> <?php endif; ?>
</div> </div>
<div style="text-align: justify;"> <div style="text-align: justify;">
@ -39,19 +39,19 @@
<?php if ($photos || $point->img): ?> <?php if ($photos || $point->img): ?>
<br/><br/> <br/><br/>
<div style="text-align: center;"> <div style="text-align: center;">
<div class="dfotorama" data-loop="true" data-nav="thumbs" data-thumbwidth="100" data-keyboard="true"> <div class="dfotorama" data-loop="true" data-nav="thumbs" data-thumbwidth="100" data-keyboard="true">
<?php if ($point->img): ?> <?php if ($point->img): ?>
<img data-thumb="<?= $point->img ?>" src="<?= $point->img ?>"> <img data-thumb="<?= $point->img ?>" src="<?= $point->img ?>">
<?php endif; ?> <?php endif; ?>
<?php if ($photos): ?> <?php if ($photos): ?>
<?php foreach ($photos as $photo): ?> <?php foreach ($photos as $photo): ?>
<img data-thumb="/photos/small/<?= $photo->name ?>" src="/photos/middle/<?= $photo->name ?>"> <img data-thumb="/photos/small/<?= $photo->name ?>" src="/photos/middle/<?= $photo->name ?>">
<?php endforeach; ?> <?php endforeach; ?>
<?php endif; ?> <?php endif; ?>
<span data-thumb="/img/mapThumb.png"> <span data-thumb="/img/mapThumb.png">
<div id="map" style="width: 100%; height: 100%; position: static; display: block;"></div> <div id="map" style="width: 100%; height: 100%; position: static; display: block;"></div>
</span> </span>
</div> </div>
</div> </div>
<br/><br/> <br/><br/>
<?php endif; ?> <?php endif; ?>
@ -66,8 +66,8 @@
} }
?> ?>
<?php if ($photoLinks):?> <?php if ($photoLinks): ?>
Использованы фотоматериалы с сайтов: <?= $photoLinks?> Использованы фотоматериалы с сайтов: <?= $photoLinks ?>
<?php endif; ?> <?php endif; ?>
</div> </div>
@ -79,7 +79,7 @@
[ <span class="glyphicon glyphicon-star"></span> <?= $countInFavs ?> - в закладках ] [ <span class="glyphicon glyphicon-star"></span> <?= $countInFavs ?> - в закладках ]
[ <span class="glyphicon glyphicon-thumbs-up"></span> <?= $countLikes ?> - нравится ] [ <span class="glyphicon glyphicon-thumbs-up"></span> <?= $countLikes ?> - нравится ]
<?php endif; ?> <?php endif; ?>
[ <span class="glyphicon glyphicon-user"></span> <?= $point->authorUser->nick ?> - <span class="glyphicon glyphicon-pencil" title="<?= date('d-m-Y H:i', $point->date) ?>"></span> <?= $point->authorUser->getPointsCount() ?> ] [ <span class="glyphicon glyphicon-user"></span> <?= $point->authorUser->nick ?> - <span class="glyphicon glyphicon-pencil" title="<?= date('d-m-Y H:i', $point->date) ?>"></span> <?= $point->authorUser->getPointsCount() ?> ]
<?php if (App::$user && App::$user->isAdmin == 1): ?> <?php if (App::$user && App::$user->isAdmin == 1): ?>
[ <span class="glyphicon glyphicon-new-window"></span> <a href="<?= $point->source ?>" target="_blank">источник: <?= $point->source ?></a> ] [ <span class="glyphicon glyphicon-new-window"></span> <a href="<?= $point->source ?>" target="_blank">источник: <?= $point->source ?></a> ]
<?php endif; ?> <?php endif; ?>

View File

@ -1,6 +1,5 @@
<?php <?php
foreach ($points as $point) foreach ($points as $point) {
{
?> ?>
<h2><?= $point->name ?></h2> <h2><?= $point->name ?></h2>

View File

@ -1,6 +1,6 @@
<?php <?php
foreach ($photos as $photo) { foreach ($photos as $photo) {
print 'http://wikipoints.ru/photos/big/'.$photo->name.'</br>'; print 'http://wikipoints.ru/photos/big/' . $photo->name . '</br>';
} }
?> ?>
<?= $point->name ?> (, )<br/> <?= $point->name ?> (, )<br/>