register(new Silex\Provider\HttpCacheServiceProvider(), array( 'http_cache.cache_dir' => __DIR__.'/inc/http_cache/', 'http_cache.esi' => null, )); $app->register(new Silex\Provider\MonologServiceProvider(), array( 'monolog.logfile' => __DIR__.'/inc/logs/block.log', 'monolog.level' => "WARNING", // "DEBUG", "INFO", "WARNING", "ERROR". )); //$app['monolog']->addDebug('Testing the Monolog logging.'); ############################################################################### // проверка SERVER_PROTOCOL, REQUEST_METHOD, наличие IP в бан-листе $app->before(function (Request $request, Silex\Application $app) { $app['block_format'] = $request->getClientIp() . ' :: %s' . ' :: '; $app['block_format'].= $request->server->get('REQUEST_URI') . ' :: '; $app['block_format'].= $request->server->get('HTTP_USER_AGENT') . ' :: '; /* // ради тебя, мэйлрушечка if ( '/robots.txt' != $request->server->get('REQUEST_URI') ) { // это неподходящий протокол if ( 'HTTP/1.0' == $request->server->get('SERVER_PROTOCOL') ) { $app['block'].= ' Bad SERVER_PROTOCOL : ' . $request->server->get('SERVER_PROTOCOL'); } }*/ // это НЕподходящий метод if ( ! in_array( $request->server->get('REQUEST_METHOD'), array('GET', 'POST', 'HEAD') ) ) { $app['block'].= ' Bad REQUEST_METHOD : ' . $request->server->get('REQUEST_METHOD'); } // это забаненный IP-шник if ( in_array( $request->getClientIp(), $app['ban_ip'] ) ) { $app['block'].= ' Bad REMOTE_ADDR'; } // это IP-шник из torlist // https://www.dan.me.uk/torlist/ if ( in_array( $request->getClientIp(), $app['ban_ip_torlist'] ) ) { $app['block'].= ' Bad REMOTE_ADDR (torlist)'; } // это забаненная подсеть if ( ip_search_net( $app['ban_net'], $request->getClientIp() ) ) { $app['block'].= ' Bad SUB_NET'; } if ( $app['block'] ) { $app['monolog']->addWarning( sprintf( $app['block_format'], $app['block'] ) ); return new Response(null, 503); die(); } }, Silex\Application::EARLY_EVENT ); ############################################################################### // проверка HTTP_USER_AGENT на пустой или наличие в бан-листе $app->before(function (Request $request, Silex\Application $app){ $ua = $request->server->get('HTTP_USER_AGENT'); $check = FALSE; if ( '' == $ua ) { $check = TRUE; $app['block'] = 'Bad USER_AGENT'; } else { foreach ( $app['ban_ua'] as $v ) { if ( FALSE !== stripos( $ua, trim($v) ) ) { $check = TRUE; $app['block'] = 'Bad USER_AGENT'; break; } } } if ( TRUE === $check ) { $app['block_format'] = $request->getClientIp() . ' :: %s' . ' :: '; $app['block_format'].= $request->server->get('REQUEST_URI') . ' :: '; $app['block_format'].= $request->server->get('HTTP_USER_AGENT') . ' :: '; $app['monolog']->addWarning( sprintf( $app['block_format'], $app['block'] ) ); return new Response(null, 503); die(); } }, Silex\Application::EARLY_EVENT ); ############################################################################### // проверка REQUEST_URI на наличие в бан-листе $app->before(function (Request $request, Silex\Application $app){ $uri = $request->server->get('REQUEST_URI'); $check = FALSE; foreach ( $app['ban_uri'] as $v ) { if ( FALSE !== stripos( $uri, trim($v) ) ) { $check = TRUE; $app['block'] = 'Bad REQUEST_URI'; break; } } if ( TRUE === $check ) { $app['block_format'] = $request->getClientIp() . ' :: %s' . ' :: '; $app['block_format'].= $request->server->get('REQUEST_URI') . ' :: '; $app['block_format'].= $request->server->get('HTTP_USER_AGENT') . ' :: '; $app['monolog']->addWarning( sprintf( $app['block_format'], $app['block'] ) ); return new Response(null, 503); die(); } }, Silex\Application::EARLY_EVENT ); ############################################################################### // static files ( inc/static/* ) $app->before(function (Request $request, Silex\Application $app){ $uri = $request->server->get('REQUEST_URI'); $check = FALSE; foreach ( $app['static'] as $k => $v ) { if ( $k == $uri ) { $check = TRUE; $include_file = $k; $include_content_type = $v; break; } } if ( TRUE === $check ) { $response = new Response( file_get_contents('inc/static/' . $include_file), 200 ); $response->headers->set('Content-Type', $include_content_type ); return $response; die(); } }, Silex\Application::EARLY_EVENT ); ############################################################################### // redirect $app->before(function (Request $request, Silex\Application $app){ $uri = $request->server->get('REQUEST_URI'); $check = FALSE; foreach ( $app['redirect'] as $k => $v ) { if ( $k == $uri ) { $check = TRUE; $goto = $v; break; } } if ( TRUE === $check ) { return $app->redirect( $goto ); ; die(); } }, Silex\Application::EARLY_EVENT ); ############################################################################### // index $app->get('/', function () use ($app,$db) { //$db->setDebug('mydebug'); $houses = $db->query('SELECT * FROM eip WHERE `what`=? AND `oper`=2 AND `price` > 0 AND `image` IS NOT NULL ORDER BY RAND() LIMIT 6', ['дом'], 'assoc'); $acres = $db->query('SELECT * FROM eip WHERE `what`=? AND `oper`=2 AND `price` > 0 AND `image` IS NOT NULL ORDER BY RAND() LIMIT 6', ['з/у'], 'assoc'); $num_rec_csv = ''; foreach( array_merge($houses, $acres) as $v ) { $num_rec_csv.= $v['num_rec'] . ','; } $images = $db->query('SELECT * FROM image WHERE `num_rec` IN (?q)', array( substr($num_rec_csv,0,-1) ), 'assoc:num_rec'); $response = new Response( $app['twig']->render('index.twig', array( 'app' => $app, 'houses' => $houses, 'acres' => $acres, 'images' => $images, ) ), 200 ); $response->setTtl(3600*24); return $response; })->bind('home_page'); ############################################################################### // /error $app->get('/error', function ($message) use ($app) { return new Response( $app['twig']->render('error.twig', array('code'=> 'xxx', 'message'=> $message ) ), 404); }) ->value('message','Ошибка! Начните с главной страницы! ') ->bind('error') ; ############################################################################### // logout $app->get('/logout', function () use ($app) { if( isset($_SESSION['is_login']) ) { unset( $_SESSION['is_login'] ); } $message = 'Вы вышли вон!'; return new Response( $app['twig']->render('error.twig', array('code' => 'чао!', 'message'=>$message ) ), 404 ); })->bind('logout'); ############################################################################### // район $app->get('/area/{alias}', function ($alias) use ($app,$db) { //$db->setDebug('mydebug'); //$area = $db->query('SELECT * FROM area WHERE `eip_name`=?', [$alias], 'assoc'); $house['id'] = $db->query('SELECT `num_rec` FROM eip WHERE `what`=? AND `region`=? AND `oper`=2 AND `image` IS NOT NULL ORDER BY RAND() LIMIT 1;', [ 'дом', $app['regions'][$alias]['eip_name'] ], 'el'); $house['path'] = $db->query('SELECT `path` FROM `image` WHERE `num_rec`=?i ORDER BY RAND() LIMIT 1;', [ $house['id'] ], 'el'); $acre['id'] = $db->query('SELECT `num_rec` FROM eip WHERE `what`=? AND `region`=? AND `oper`=2 AND `image` IS NOT NULL ORDER BY RAND() LIMIT 1;', [ 'з/у', $app['regions'][$alias]['eip_name'] ], 'el'); $acre['path'] = $db->query('SELECT `path` FROM `image` WHERE `num_rec`=?i ORDER BY RAND() LIMIT 1;', [ $acre['id'] ], 'el'); $arenda['id'] = $db->query('SELECT `num_rec` FROM eip WHERE `what`=? AND `region`=? AND `oper`=5 AND `image` IS NOT NULL ORDER BY RAND() LIMIT 1;', [ 'дом', $app['regions'][$alias]['eip_name'] ], 'el'); $arenda['path'] = $db->query('SELECT `path` FROM `image` WHERE `num_rec`=?i ORDER BY RAND() LIMIT 1;', [ $arenda['id'] ], 'el'); $response = new Response( $app['twig']->render('area.twig', array( 'app' => $app, 'area' => $app['regions'][$alias], 'title' => $app['regions'][$alias]['title'], 'house' => $house, 'acre' => $acre, 'arenda' => $arenda, ) ), 200 ); $response->setTtl(3600*24*30); return $response; }) ->convert('alias', function($alias) use ($app) { if( $app['regions'][$alias] ) { return $alias; }else{ return 'default';} } ) ; ############################################################################### // питер $app->get('/spb/', function () use ($app,$db) { // $db->setDebug('mydebug'); // $db->query('SET NAMES utf8'); $count['all'] = $db->query('SELECT COUNT(`num_rec`) FROM eip WHERE `what` IN(\'з/у\',\'дом\')', array(), 'el' ); $count['oblast'] = $db->query('SELECT COUNT(`num_rec`) FROM eip WHERE `what` IN(\'з/у\',\'дом\') AND `district`=\'Ленинградская обл.\'', array(), 'el' ); $count['gorod'] = $db->query('SELECT COUNT(`num_rec`) FROM eip WHERE `what` IN(\'з/у\',\'дом\') AND `district`=\'С-Петербург\'', array(), 'el' ); $count['oblast_dom'] = $db->query('SELECT COUNT(`num_rec`) FROM eip WHERE `what`=\'дом\' AND `district`=\'Ленинградская обл.\'', array(), 'el' ); $count['oblast_uch'] = $db->query('SELECT COUNT(`num_rec`) FROM eip WHERE `what`=\'з/у\' AND `district`=\'Ленинградская обл.\'', array(), 'el' ); $count['gorod_dom'] = $db->query('SELECT COUNT(`num_rec`) FROM eip WHERE `what`=\'дом\' AND `district`=\'С-Петербург\'', array(), 'el' ); $count['gorod_uch'] = $db->query('SELECT COUNT(`num_rec`) FROM eip WHERE `what`=\'з/у\' AND `district`=\'С-Петербург\'', array(), 'el' ); return $app['twig']->render('index_spb.twig', array( 'app' => $app, 'count' => $count, 'name' => 'Петербург' ) ); })->bind('spb_page'); ############################################################################### $app->get( '/detail/{id}', function($id) use ($app, $db){ // $db->setDebug('mydebug'); if( $id > 0 ) { if( $object = $db->query('SELECT * FROM eip WHERE `num_rec`=?i', array($id), 'row') ) { if( ! $region = $db->query('SELECT * FROM area WHERE `eip_name`=?', array($object['region']), 'row' ) ) { return new Response( $app['twig']->render('error.twig', array('code' => 'xxx', 'message'=>'No region!' ) ), 404 ); } if( ! $meta = $db->query('SELECT * FROM meta WHERE `num_rec`=?i', array( $id ), 'row') ) { return new Response( $app['twig']->render('error.twig', array('code' => 'xxx', 'message'=>'No meta!' ) ), 404 ); } if( $object['image'] ) { $images = $db->query('SELECT * FROM image WHERE `num_rec`=?i AND `path` IS NOT NULL AND `image_width` > 0 AND `image_height` > 0', array( $id ), 'assoc'); }else{ $images = ''; } // удаление URL http://habrahabr.ru/post/66931/ // Паттерн: /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/ // лучше так — /^(https?:\/\/)?([\w\.]+)\.([a-z]{2,6}\.?)(\/[\w\.]*)*\/?$/ // $pattern2 = "#^(https?://)?([\w\.]+)\.([a-z]{2,6}\.?)(/[\w\.]*)*/?$#"; // $object['note'] = preg_replace( $pattern2, '***', $object['note'] ); $object['full_description'] = str_replace( 'Подробное описание объекта на сайте - ', '', $object['full_description'] ); $object['full_description'] = str_replace( 'http://rfn.spb.ru/catalog/zagorod', '', $object['full_description'] ); $object['full_description'] = str_replace( 'Номер объекта на портале EstateOnline - ', '', $object['full_description'] ); if( $app['is_login'] == 0 ) { // удаление номеров телефона в описании $pattern = "/((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}/"; $object['full_description'] = preg_replace( $pattern, '+7(***) *** **** ', $object['full_description'] ); } // сложный title $title = mb_ucfirst($meta['title']) . ', цена: '; if( $object['price'] > 0 ) { $title.= $object['price'] . ' руб.'; }else{ $title.= 'договорная'; } $title.= ', ' . mb_ucfirst($region['name']) . ' район'; return $app['twig']->render('detail.twig', array( 'app' => $app, 'object' => $object, 'region' => $region, 'meta' => $meta, 'images' => $images, 'title' => $title, 'description' => mb_ucfirst( $meta['description'] ), 'keywords' => $meta['keywords'], )); } } if( ! $object ) { // return $app->redirect( $app['url_generator']->generate('error') ); return new Response( $app['twig']->render('error.twig', array('code' => '404', 'message'=>'Объект не найден' ) ), 404); } }) ->value('id', 0) //->assert('id', '\d+') ->convert('id', function($id){return (int)($id/797);}) ; ############################################################################### // дома /* $app->get('/doma/{page_id}', function ($page_id) use ($app,$db) { $count['all'] = $db->query('SELECT COUNT(`num_rec`) FROM eip WHERE `what`=\'дом\'', array(), 'el' ); // максимальное значение {page_id} if ( (int) $page_id > ceil($count['all'] / $app['per_page']) ) { return $app->redirect( $app['url_generator']->generate('error') ); } $app->register( new PaginationServiceProvider, array( 'pagination.per_page' => $app['per_page'], 'pagination.neighbours' => $app['neighbours'] )); $pagination = $app['pagination']( $count['all'], $page_id); $pages = $pagination->build(); $offset = $pagination->offset(); // Сдвиг $limit = $pagination->limit(); // Лимит $objects = $db->query('SELECT * FROM eip WHERE `what`=\'дом\' LIMIT ?i, ?i;', array($offset, $limit), 'assoc' ); return $app['twig']->render('doma.twig', array( 'app' => $app, 'count' => $count, 'objects' => $objects, 'current' => $pagination->currentPage(), 'pages' => $pages, 'name' => 'Дома', 'page_id' => $page_id, ) ); }) ->bind('doma_page') ->value('page_id', '' ) ->assert('page_id', '\d+') ->convert('page_id', function ($page_id) { if ( !isset($page_id) || 0 == (int)$page_id ){ return 1; }else{ return (int)$page_id; } } ) ; */ ############################################################################### // дома / район / страница $app->get('/{type}/{region_alias}/{page_id}', function ( $type, $region_alias, $page_id) use ($app,$db) { // $db->setDebug('mydebug'); foreach( $app['regions'] as $v ) { if ( $region_alias == $v['alias'] ) { $region = $v; break; } } /* if( false === in_array( $type, array('doma','uchastki') ) ) { return $app->redirect( $app['url_generator']->generate('error', array('message'=>'13') ) ); }*/ if( $region['eip_name'] === false ) { return $app->redirect( $app['url_generator']->generate('error') ); } switch( $type ) { case 'doma' : $type_name = 'дом'; $oper_name = 'продажа'; $sql = 'SELECT COUNT(`num_rec`) FROM eip WHERE `what`=\'дом\' AND oper=2 AND `region`=?'; $sql2 = 'SELECT * FROM eip WHERE `what`=\'дом\' AND oper=2 AND `region`=? ORDER BY `price` DESC LIMIT ?i, ?i;'; $titles = file('./inc/lists/pagename_house_sale.txt'); $title = str_replace( array('%name%','%name_v%'), array($region['name'],$region['name_v']), trim( $titles[$page_id] ) ); $description = 'Продажа: '; break; case 'uchastki' : $type_name = 'з/у'; $oper_name = 'продажа'; $sql = 'SELECT COUNT(`num_rec`) FROM eip WHERE `what`=\'з/у\' AND oper=2 AND `region`=?'; $sql2 = 'SELECT * FROM eip WHERE `what`=\'з/у\' AND oper=2 AND `region`=? ORDER BY `price` DESC LIMIT ?i, ?i;'; $titles = file('./inc/lists/pagename_acre_sale.txt'); $title = str_replace( array('%name%','%name_v%'), array($region['name'],$region['name_v']), trim( $titles[$page_id] ) ); $description = 'Продажа: '; break; case 'arenda' : $type_name = 'дом'; $oper_name = 'аренда'; $sql = 'SELECT COUNT(`num_rec`) FROM eip WHERE `what` IN(\'дом\',\'з/у\') AND oper=5 AND `region`=?'; $sql2 = 'SELECT * FROM eip WHERE `what` IN(\'дом\',\'з/у\') AND oper=5 AND `region`=? ORDER BY `price` DESC LIMIT ?i, ?i;'; $titles = file('./inc/lists/pagename_house_rent.txt'); $title = str_replace( array('%name%','%name_v%'), array($region['name'],$region['name_v']), trim( $titles[$page_id] ) ); $description = 'Сдается в аренду: '; break; default: return $app->redirect( $app['url_generator']->generate('error') ); break; } $count['all'] = $db->query( $sql, array( $region['eip_name'] ), 'el' ); // максимальное значение {page_id} if ( (int) $page_id > ceil($count['all'] / $app['per_page']) ) { //return $app->redirect( $app['url_generator']->generate('error') ); $message = 'Страница ' . (int) $page_id . ' не найдена.'; return new Response( $app['twig']->render('error.twig', array('code' => '404', 'message'=>$message ) ), 404 ); } $app->register( new PaginationServiceProvider, array( 'pagination.per_page' => $app['per_page'], 'pagination.neighbours' => $app['neighbours'] )); $pagination = $app['pagination']( $count['all'], $page_id); $pages = $pagination->build(); $offset = $pagination->offset(); // Сдвиг $limit = $pagination->limit(); // Лимит $objects = $db->query( $sql2, array( $region['eip_name'], $offset, $limit), 'assoc' ); $c=0; $image_csv = ''; foreach( $objects as $v ) { // для meta descritionобъединяются адреса объектов $description.= $v['straddr'] . ': ' . substr($v['price'], 0, -3 ) . ' тыс.руб., '; // список первых картинок if( $v['image'] ) { $images = explode('|', $v['image'] ); $image_csv.= '"' . trim( $images[0] ) . '"' . ','; } $c++; } //echo $image_csv; if( $image_csv ) { $images = $db->query('SELECT `num_rec`,`path` FROM image WHERE `url` IN (?q) AND `path` IS NOT NULL AND `image_width` > 0 AND `image_height` > 0', array( substr($image_csv,0,-1) ), 'assoc:num_rec' ); } // var_dump( $images ); $response = new Response( $app['twig']->render('doma_region.twig', array( 'app' => $app, 'count' => $count, 'objects' => $objects, 'current' => $pagination->currentPage(), 'pages' => $pages, 'type_name' => $type_name, 'oper_name' => $oper_name, 'page_id' => $page_id, 'region' => $region, 'type' => $type, 'title' => mb_ucfirst( $title ), 'description' => mb_ucfirst( $description ), 'images' => $images, ) ), 200 ); $response->setTtl(3600*24*7); return $response; }) ->bind('doma_region_page') ->value('type', '' ) ->value('region_alias', '' ) ->value('page_id', 1 ) ->assert('page_id', '\d+') ->convert('page_id', function ($page_id) { if ( !isset($page_id) || 0 == (int)$page_id ){ return 1; }else{ return (int)$page_id; } } ) ; ############################################################################### // errors handling $app->error(function (\Exception $e, $code) use ($app) { switch ($code) { case 404: $message = 'Страница не найдена.'; return new Response( $app['twig']->render('error.twig', array('code' => '404', 'message'=>$message ) ), 404 ); break; default: $message = 'Что-то пошло не так(
' . ( ($app['debug'] ) ? $e : ''); return new Response( $app['twig']->render('error.twig', array('code' => '404', 'message'=>$message ) ), 404 ); break; } return new Response($message); }); ############################################################################### // take fun $app->run(); //$app['http_cache']->run();