· 6 years ago · Oct 11, 2019, 11:26 AM
1<?php namespace App\Http\Controllers;
2
3use App;
4use DB;
5use Auth;
6use Input;
7use Intervention\Image\Facades\Image as Image;
8use Lang;
9use JsonSchema\Constraints\Type;
10use PhpParser\Node\Scalar\String_;
11use Psy\Util\String;
12use Validator;
13use Redirect;
14use Request;
15use Carbon\Carbon;
16use Storage;
17use Response;
18use File;
19use Session;
20use Cookie;
21use Log;
22use DomDocument;
23use Hash;
24use Mail;
25use ReflectionClass;
26
27/***********************************************************************************
28Функция img_resize(): генерация JPG thumbnails
29Параметры:
30$src - имя исходного файла
31$dest - имя генерируемого файла
32$width, $height - ширина и высота генерируемого изображения, в пикселях
33Необязательные параметры:
34$vcenter - центровка по вертикали, по умолчанию - false
35$rgb - цвет фона, по умолчанию - белый
36$quality - качество генерируемого JPEG, по умолчанию - максимальное (100)
37
38
39function bulletinsSearch($value)
40{
41$Sphinx = new SphinxClient();
42return;
43
44// Создадим объект - клиент сфинкса и подключимся к нашей службе
45$cl = new SphinxClient();
46$cl->SetServer( "127.0.0.1", 9312 );
47
48// Собственно поиск
49$cl->SetMatchMode( SPH_MATCH_ANY ); // ищем хотя бы 1 слово из поисковой фразы
50$result = $cl->Query($value); // поисковый запрос
51
52// обработка результатов запроса
53if ( $result === false ) {
54echo "Query failed: " . $cl->GetLastError() . ".\n"; // выводим ошибку если произошла
55}
56else {
57if ( $cl->GetLastWarning() ) {
58echo "WARNING: " . $cl->GetLastWarning() . " // выводим предупреждение если оно было
59";
60}
61
62if ( ! empty($result["matches"]) ) { // если есть результаты поиска - обрабатываем их
63foreach ( $result["matches"] as $product => $info ) {
64echo $product . "<br />"; // просто выводим id найденных товаров
65}
66}
67}
68}
69
70
71 ***********************************************************************************/
72
73function str2arr ($strArrayToParse) {
74 $strArrayToParse = mb_strcut($strArrayToParse, 1, strlen($strArrayToParse)-2);
75 return (explode(',' , $strArrayToParse));
76}
77
78function arr2str ($arrayToBeString) {
79
80 if (is_null($arrayToBeString))
81 $arrayToBeString = array();
82
83 $sectionsArrText = "{";
84
85 $i = 0;
86 foreach ($arrayToBeString as $arrayElement) {
87 $sectionsArrText .= $arrayElement;
88 $sectionsArrText .= ($i++ == (count($arrayToBeString)-1) ? "" : ",");
89 }
90 $sectionsArrText .= "}";
91
92 return $sectionsArrText;
93}
94function searchElement($array)
95{
96
97}
98
99function _getSectionsFullBranch ($sidToCheck) {
100 if ($sidToCheck == 0)
101 return;
102
103 $finalSidsBranch = array();
104
105 $sidsResult = DB::table('sections')
106 ->select('psids')
107 ->where('sid', '=', $sidToCheck)
108 ->get();
109
110 $sids = str2arr($sidsResult[0]->psids);
111
112 foreach ($sids as $currSid) {
113 if ($currSid != "0") {
114 array_push($finalSidsBranch, $currSid);
115 }
116
117 $ololosids = _getSectionsFullBranch($currSid);
118 if ($ololosids != NULL)
119 $finalSidsBranch = array_merge($finalSidsBranch, $ololosids);
120 }
121
122
123 array_push($finalSidsBranch, Input::get("section"));
124 $finalSidsBranch = array_unique($finalSidsBranch);
125 return($finalSidsBranch);
126}
127
128function _getSectionsFullLeaves ($sidToCheck) {
129 if ($sidToCheck == 0)
130 return;
131
132 $finalSidsBranch = array();
133
134 $sidsResult = DB::table('sections')
135 ->select('sid')
136 ->whereRaw($sidToCheck.' = any(psids)')
137 ->get();
138
139 foreach ($sidsResult as $currSid) {
140 array_push($finalSidsBranch, $currSid->sid);
141
142 $ololosids = _getSectionsFullLeaves($currSid->sid);
143 if ($ololosids != NULL)
144 $finalSidsBranch = array_merge($finalSidsBranch, $ololosids);
145 }
146
147
148 array_push($finalSidsBranch, $sidToCheck);
149 $finalSidsBranch = array_unique($finalSidsBranch);
150 return($finalSidsBranch);
151}
152
153function _getCitiesFullBranch($currCid) {
154 $currItemParent = -1;
155 $finalCitiesBranch = array();
156 array_push($finalCitiesBranch, $currCid);
157
158 $currItemParent = $currCid;
159
160 while ($currItemParent != 0) {
161 $currCid = DB::table('cities_russia')
162 ->select('pcid')
163 ->where('cid', '=', $currItemParent)
164 ->get();
165
166 $currItemParent = $currCid[0]->pcid;
167 array_push($finalCitiesBranch, $currCid[0]->pcid);
168 }
169
170 return $finalCitiesBranch;
171}
172
173//Оплата за услуги
174//$cash = Сумма оплаты
175//$orderType = Тип операции
176//$bulletinID = Номер объявления необязательное
177function payment_for_services($cash, $orderType = "payment", $bulletinID = 0)
178{
179
180 $Users_payID = DB::table('users_pay')->insertGetId([
181 'cash' => $cash,
182 'uid' => Auth::user()->id,
183 'success' => '0'
184 ]);
185
186 $mrh_login = "SellPay.ru";
187
188 //$mrh_pass1 = "akbzt6WRjZkb87H0dzH7"; // TEST PASSWORD
189 $mrh_pass1 = "ytwT5gPxe07m5w7yGPvx";
190
191 // язык
192 $culture = "ru";
193
194 // Номер заказа
195 $inv_id = $Users_payID;
196
197 // Тип операции
198 $Shp_orderType = $orderType;
199
200 // ID объявления
201 $Shp_bulletinID = $bulletinID;
202
203 // ID Пользователся
204 $UserID = Auth::user()->id;
205
206 // Получения имени денежной операции
207 $inv_desc = getOrderType($orderType, $bulletinID)['orderName'];
208
209 // Формирование подписи
210 $crc = md5("$mrh_login:$cash:$inv_id:$mrh_pass1:Shp_bulletinID=$bulletinID:Shp_orderType=$Shp_orderType:Shp_userID=$UserID");
211
212 //Тестовый режим
213 //$IsTest = 0;//1;
214
215 $url = "https://auth.robokassa.ru/Merchant/Index.aspx?".
216 "MerchantLogin=$mrh_login&".
217 "OutSum=$cash&".
218 "InvId=$inv_id&".
219 "Desc=$inv_desc&".
220 "SignatureValue=$crc&".
221 "Shp_bulletinID=$bulletinID&".
222 "Shp_orderType=$Shp_orderType&".
223 "Shp_userID=$UserID&"; //.
224 //"IsTest=$IsTest";
225
226 return $url;
227}
228// Получения информации о денежной операции
229// input > $Type - тип операции
230// input > $bulletinID - номер объявления
231// output < orderName - имя операции
232// output < orderText - опесание операции
233// output < orderPrice - стоимосто
234function getOrderType($Type, $bulletinID = 0)
235{
236 $orderType = $Type;
237 $orderName = NULL;
238 $orderText = NULL;
239 $orderPrice = NULL;
240 $addCash = false;
241
242 switch ($orderType) {
243 case 1 :
244 $orderName = "Поднятие объявления";
245 $orderPrice = 5;
246 $orderText = "Обявление будет показано сразу после прикрепленных.";
247 break;
248 case 2 :
249 $orderName = "Прикрепление объявления";
250 $orderPrice = 30;
251 $orderText = "Услуга предоставляется сроком на 5 дней. Объявление будет размещено выше остальных публикаций, на момент его прикрепления.";
252 break;
253 case 3 :
254 $orderName = "Восстановление объявления";
255 $orderText = "Объявление будет показано сразу после прикрепленных.";
256 $orderPrice = 10;
257 break;
258 case 4 :
259 $orderName = "Сделать объявление анонимным";
260 $orderText = "В объявлении будет скрыт телефонный номер, а так же профиль пользователя.";
261 $orderPrice = 5;
262 break;
263 case 5 :
264 $orderName = "Размещение объявления";
265 $bulletinSid = DB::table('bulletins')
266 ->select('sid')
267 ->where('id', '=', $bulletinID)
268 ->first()->sid;
269 $bulletinSidArray = str2arr($bulletinSid);
270 $bulletinSid = end($bulletinSidArray);
271 $orderPrice = getPriceSections($bulletinSid);
272 break;
273 case 6 :
274 $orderName = "Размещение объявления";
275 break;
276 default :
277 $addCash = true;
278 $orderName = "Пополнение счета";
279 $orderPrice = 50;
280 break;
281 }
282 return array(
283 "orderName" => $orderName,
284 "orderText" => $orderText,
285 "orderPrice" => $orderPrice,
286 "addCash" => $addCash
287 );
288}
289
290// Выбо типа оплаты
291// input > $orderType - информация о денежной операции
292// input > bulletinID - идентификатор объявления
293function getServicesOnline($orderType , $bulletinID)
294{
295
296 switch ($orderType) {
297 case 1 : //Поднятие объявления
298 DB::table('bulletins')
299 ->where('id', '=', $bulletinID)
300 ->where('uid', '=', Auth::user()->id)
301 ->update(['actual_at' => Carbon::now()]);
302 break;
303 case 2 : //Прикрепление объявления
304 DB::table('bulletins')
305 ->where('id', '=', $bulletinID)
306 ->where('uid', '=', Auth::user()->id)
307 ->update(['fixed_to' => Carbon::now()->addDays(5), 'actual_at' => Carbon::now()]);
308 break;
309 case 3 : // Восстановление объявления
310 DB::table('bulletins')
311 ->where('id', '=', $bulletinID)
312 ->where('uid', '=', Auth::user()->id)
313 ->update(['moderated' => '0']);
314 break;
315 case 4 : // Сделать объявление анонимным
316 DB::statement('UPDATE "bulletins" SET "is_anonymous" = NOT "is_anonymous" WHERE "id" = '.$bulletinID);
317 break;
318 case 5 :
319 DB::table('bulletins')
320 ->where('id', '=', $bulletinID)
321 ->where('uid', '=', Auth::user()->id)
322 ->update(['moderated' => '0']);
323 break;
324 case 6 :
325 $rejected = DB::table('bulletins')
326 ->select('moderated')
327 ->where('id', '=', $bulletinID)
328 ->where('uid', '=', Auth::user()->id)
329 ->first()->moderated;
330 if ($rejected == 2)
331 {
332 DB::table('bulletins')
333 ->where('id', '=', $bulletinID)
334 ->where('uid', '=', Auth::user()->id)
335 ->update(['moderated' => '0']);
336 }
337 else
338 return Redirect::to('error404');
339
340 break;
341 default :
342 $errorOrder = true;
343 break;
344 }
345}
346
347function getPriceSections($sid)
348{
349 $section = $sid;
350 $bulletinPrice = null;
351
352 while ($bulletinPrice == null)
353 {
354 $bulletinPrice = DB::table('bulletins_price')
355 ->select('price')
356 ->where('id', '=', $section)
357 ->first();
358
359 if ($bulletinPrice != null)
360 break;
361
362 $logSection = $section;
363
364 $section = DB::table('sections')
365 ->select('mpsid')
366 ->where('sid', '=', $section)
367 ->first()->mpsid;
368
369 if ($section == 0)
370 {
371 Log::info('Погляди в секции', array('секция:' => $logSection));
372 return Redirect::to('error404');
373 }
374 }
375
376 if ($bulletinPrice->price == 0)
377 return null;
378
379 return $bulletinPrice->price;
380
381}
382
383function random_seq_gen () {
384 $str = '0123456789ABCDEFGHJIKLMNOPQRSTUVWXYZabcdefghjiklmnopqrstuvwxyz';
385 $seq_length = 24;
386 $str_length = strlen($str)-1;
387 $seq='';
388 for ($i=0; $i<$seq_length; $i++) {
389 $seq .= substr($str, mt_rand(0, $str_length), 1);
390 }
391
392 return ($seq);
393}
394
395function br2nl($str) {
396 $str = preg_replace("/(rn|n|r)/", "", $str);
397 return preg_replace("=<br */?>=i", "n", $str);
398}
399
400function GetCursFromXML($XMLlink = '') {
401 $Xml = new DomDocument();
402 $Xml->load($XMLlink);
403 return $Xml->documentElement->firstChild->nextSibling->firstChild->nextSibling->firstChild->data;
404}
405
406function GetCBRcurrency () {
407 $cache_file = "/cache/currency.cache";
408 $scripturl = 'http://www.cbr.ru/scripts/XML_dynamic.asp';
409 $string = '';
410
411 # Начальная дата для запроса (сегодня - 2 дня(-172800) или 3 дня (-259200) или 9 дней(-777600))
412 $date_1 = date('d/m/Y', time()-259200);
413
414 # Конечная дата (чтобы учитывать завтра добавьте параметр time()+86400)
415 $date_2 = date('d/m/Y', time());
416
417 # Таким образом, мы получим данные либо за 2, либо за 3 последних дня.
418 # За 2 - если на "сегодня" курс еще не выставили, иначе - за 3
419
420 # Код валюты в архиве данных cbr.ru
421 $currency_code = array('R01235', 'R01239', 'R01820', 'R01375');
422
423 $resultCurses = array();
424
425 for ($j = 0; $j < count($currency_code); $j++) {
426 $requrl = "{$scripturl}?date_req1={$date_1}&date_req2={$date_2}&VAL_NM_RQ={$currency_code[$j]}";
427
428 $doc = "";
429
430 try {
431 file_get_contents($requrl);
432 //return dd($requrl);
433 } catch (Exception $e) {
434 return dd($e);
435 }
436 //$doc = implode($doc, '');
437
438 $r = array();
439
440 # ищем <ValCurs>...</ValCurs>
441 if (preg_match("/<ValCurs.*?>(.*?)<\/ValCurs>/is", $doc, $m)) {
442 # а потом ищем все вхождения <Record>...</Record>
443 preg_match_all("/<Record(.*?)>(.*?)<\/Record>/is", $m[1], $r, PREG_SET_ORDER);
444 dd($m);
445 }
446
447 $m = array(); # его уже использовали, реинициализируем
448 $d = array(); # этот тоже проинициализируем
449
450 # Сканируем на предмет самых нужных цифр
451 for ($i = 1; $i < count($r); $i+=2) {
452 if (preg_match("/Date=\"(\d{2})\.(\d{2})\.(\d{4})\"/is", $r[$i][1], $m)) {
453 if (preg_match("/<Value>(.*?)<\/Value>/is", $r[$i][2], $m)) {
454 $m[1] = preg_replace("/,/", ".", $m[1]);
455 array_push($resultCurses, $m[1]);
456 }
457 }
458 }
459 }
460 return $resultCurses;
461}
462
463
464function CheckEmptiness($InputPhotoNamber)
465{
466 /*
467 / $InputPhotoNamber - Кол-во файлов загружаемых
468 */
469 $filelist = array(); //Файлы в папке
470 $EmptyElements = array(); //Свободные элементы в папке
471 $NumberItemsFree = 0; //Кол-во свободных
472 $imgID = 0;
473 $indexOffset = 0; //Смещение
474 $lastImageElement = 0; //Последнее фото
475
476 $dir = "tmp/".Auth::user()->id . '/';
477 if (!(is_dir($dir))) {
478 $EmptyElements['lastImageElement'] = 0;
479 $EmptyElements['NumberItemsFree'] = 0;
480 return $EmptyElements;
481 }
482
483 if ($handle = opendir($dir))
484 {
485 while ($entry = readdir($handle))
486 {
487 if (preg_match ("/\.\w+/" , $entry))
488 {
489 $filelist[] = $entry;
490 }
491 }
492 closedir($handle);
493 }
494
495 foreach ($filelist as &$value)
496 {
497 $value = (int)(basename($value, ".".pathinfo($value, PATHINFO_EXTENSION)));
498 }
499
500 sort($filelist);
501 $lastImageElement = (string)(end($filelist));
502
503 for ($i=0; $i < count($filelist); $i++)
504 {
505 if (!($filelist[$i] == $imgID))
506 {
507 $indexOffset = (int)$filelist[$i] - $imgID;
508 for ($j = 1; $j <= $indexOffset; $j++)
509 {
510 $EmptyElements[$NumberItemsFree] = ($imgID - 1) + $j;
511 $NumberItemsFree++;
512 if ($NumberItemsFree == $InputPhotoNamber)
513 break 2;
514 }
515 $imgID = $imgID + $indexOffset + 1;
516 $indexOffset = 0;
517 }
518 else
519 $imgID++;
520 }
521
522 $EmptyElements['lastImageElement'] = ($lastImageElement + 1);
523
524 if ($NumberItemsFree == 0) {
525 $EmptyElements['NumberItemsFree'] = 0;
526 return $EmptyElements;
527 }
528 else
529 {
530 $EmptyElements['NumberItemsFree'] = $NumberItemsFree;
531 return $EmptyElements;
532 }
533}
534
535class PageController extends Controller
536{
537
538 public function __construct()
539 {
540 if (Auth::check()) {
541 $confirmed = DB::table('users')
542 ->select('confirmed')
543 ->where('email', '=', Auth::user()->email)
544 ->first();
545
546 if ($confirmed->confirmed == false) {
547 Session::flash('message', 'Пожалуйста, проверьте вашу почту и подтвердите регистрацию на сайте!');
548 Auth::logout();
549 }
550 }
551
552 self::setLocale(self::getMainLng());
553 //$this->middleware('auth'); //Открывает доступ к странице только для авторизованных юзеров
554 }
555
556 public function getMainLng() {
557 return isset(Auth::user()->lng) ? Auth::user()->lng : Lang::getLocale();
558 }
559
560 public function setLocale ($locale) {
561 if (in_array($locale, \Config::get('app.locales'))) { # Проверяем, что у пользователя выбран доступный язык
562 Session::put('locale', $locale); # И устанавливаем его в сессии под именем locale
563 }
564
565 return Redirect::to('/');
566 }
567
568 public function getMainPage()
569 {
570 if (isset($_GET['adid'])) {
571 DB::update('update ad_stats set views = views+1 where adid = '.$_GET['adid']);
572 return Redirect::to('/');
573 }
574 date_default_timezone_set('Asia/Vladivostok');
575 return view('pages.main');
576 }
577
578 public function getSectionPage($sid)
579 {
580 $main_lang = self::getMainLng(); //Lang::getLocale();
581
582 $articles_per_page = 20; // количество статей на странице
583
584 $from = Input::get("from");
585
586 DB::table('sections')
587 ->where('sid', '=', $sid)
588 ->increment('views');
589
590 $sections = DB::table('sections')
591 ->select('sid', 'mpsid', Lang::getLocale()=='cn'?'name_cn as name':'name')
592 ->whereRaw($sid . ' = any(psids)')
593 ->orderBy(Lang::getLocale()=='cn'?'name_cn':'name', 'asc')
594 ->get();
595
596 foreach ($sections as $key => $value) {
597 if ((mb_stripos($value->name,"проч") !== false) || (mb_stripos($value->name,"друг") !== false)) {
598 $sections[] = $value;
599 unset($sections[$key]);
600 }
601 }
602
603 array_values($sections);
604
605 $bulletinsCount = array();
606 $targetCity = isset(Auth::user()->city) ? Auth::user()->city : 1;
607
608 if (!Auth::user())
609 {
610
611 if (Cookie::get('cityID') == null) {
612 $targetCity = 1;
613 }
614 else
615 $targetCity = Cookie::get('cityID');
616 }
617
618 foreach ($sections as $section) {
619 if ($main_lang == 'ru' && Session::get('is_chinesse_bulletins') == 'true') {
620 $bulletinsCount[$section->sid] = DB::table('bulletins')
621 ->whereRaw("$section->sid = any(sid) AND (moderated = 0 OR moderated = 1) AND language = 'cn' AND loc_id IS NOT NULL")
622 ->count();
623 } else {
624 $bulletinsCount[$section->sid] = DB::table('bulletins')
625 ->whereRaw("$section->sid = any(sid) AND ".(Lang::getLocale()=='ru'?$targetCity." = any(city) AND":"")." (moderated = 0 OR moderated = 1) AND language = '".$main_lang."'")
626 ->count();
627 }
628 }
629
630 if ($main_lang == 'ru' && Session::get('is_chinesse_bulletins') == 'true') {
631 $total_articles_number = DB::table('bulletins')
632 ->whereRaw('(moderated = 1 or moderated = 0) AND language = \'cn\' AND loc_id IS NOT NULL')
633 ->count();
634 } else {
635 $total_articles_number = DB::table('bulletins')
636 ->whereRaw('(moderated = 1 or moderated = 0) AND ' .$sid." = any(bulletins.sid) AND ".(Lang::getLocale()=='ru'?$targetCity." = any(city) AND":"")." language = '".$main_lang."'")
637 ->count();
638 }
639
640 if (!($from > 0))
641 $from = 1;
642
643 if ($main_lang == 'ru' && Session::get('is_chinesse_bulletins') == 'true') {
644 $bulletins = DB::table('bulletins') // was "fixedBulletins"
645 ->selectRaw('(bulletins.fixed_to > \''.Carbon::now().'\'), users.name as username, bulletins.id, bulletins.main_photo, bulletins.actual_at, bulletins_locs.name as name, bulletins_locs.data as data, bulletins_locs.description as description, bulletins.views, bulletins.currency')
646 ->join('users','bulletins.uid','=','users.id')
647 ->join('bulletins_locs','bulletins.loc_id','=','bulletins_locs.id')
648 ->whereRaw('(moderated = 1 or moderated = 0) AND ' .$sid.' = any(bulletins.sid) AND bulletins.language = \'cn\' AND bulletins.loc_id IS NOT NULL')
649 ->orderBy('priority', 'desc')
650 ->orderByRaw('1 DESC')
651 ->orderBy('bulletins.actual_at', 'desc')
652 ->limit(20)
653 ->offset(($from-1)*20)
654 ->get();
655 } else {
656 $bulletins = DB::table('bulletins') // was "fixedBulletins"
657 ->selectRaw('(bulletins.fixed_to > \''.Carbon::now().'\'), users.name as username, bulletins.id, bulletins.main_photo, bulletins.actual_at, bulletins.name, bulletins.data, bulletins.description, bulletins.views, bulletins.currency')
658 ->join('users','bulletins.uid','=','users.id')
659 ->whereRaw('(moderated = 1 or moderated = 0) AND ' .$sid.' = any(bulletins.sid) AND '.(Lang::getLocale()=='ru'?$targetCity." = any(bulletins.city) AND":"").' language = \''.$main_lang.'\'')
660 ->orderBy('priority', 'desc')
661 ->orderByRaw('1 DESC')
662 ->orderBy('bulletins.actual_at', 'desc')
663 ->limit(20)
664 ->offset(($from-1)*20)
665 ->get();
666 }
667
668 $ControlArray = array() ;
669
670 //получаем количество страниц
671 if ($total_articles_number > $articles_per_page)
672 {
673 $total_pages = ceil($total_articles_number/$articles_per_page);
674
675 $url = Request::url();
676
677 if ($from == null)
678 $from = 1;
679
680 // запускаем цикл - количество итераций равно количеству страниц
681 $i = max(0, $from-4);
682 $last_shown_page_number = min($from+4, $total_pages);
683
684 if ($i >= 1)
685 $ControlArray[0] = "<div class=\"controll\"><a href='".$url."?from=1'> 1 </a>".($i==1?"":" ... ")."</div> ";
686
687
688 for ($i; $i<$last_shown_page_number; $i++)
689 {
690 // получаем значение $from (как $page_number) для использования в формировании ссылки
691 $page_number=$i+1;
692
693 if ($page_number != $from)
694 $ControlArray[$i] = "<div class=\"controll\"><a href='".$url."?from=".$page_number."'> ".($i+1)." </a></div>";
695 else $ControlArray[$i] = "<div class=\"controllTarget\" ><a href='".$url."?from=".$page_number."'> ".($i+1)." </a></div>";
696 }
697
698
699 if ($total_pages - $last_shown_page_number >= 1)
700 $ControlArray[$total_pages] = "<div class=\"controll\">".($total_pages - $last_shown_page_number == 1?"":" ... ")."<a href='".$url."?from=".$total_pages."'> ".$total_pages." </a></div>";
701
702
703 if ($articles_per_page*$from > $total_articles_number)
704 $article_number_on_the_page = ($total_articles_number - $articles_per_page*($from-1));
705 else
706 $article_number_on_the_page = $articles_per_page;
707
708 //$bulletins = array_slice($bulletins,(($articles_per_page*($from-1))), ($article_number_on_the_page));
709 }
710 $curSection = DB::table('sections')->select($main_lang=='cn'?'name_cn as name':'name')->where('sid', '=', $sid)->get();
711
712 return view('pages.section', [
713 'curSection' => $curSection[0]->name,
714 'sections' => $sections,
715 'bulletinsCount' => $bulletinsCount,
716 'bulletins' => $bulletins,
717 'sid' => $sid,
718 'ControlArray' => $ControlArray
719 ]);
720 }
721
722 public function getBulletinPage($id)
723 {
724 $UserID = null;
725 if (Auth::User() != null) {
726 $UserID = Auth::User()->id;
727 }
728
729 if (!is_numeric($id))
730 return view('errors.404');
731
732 $isTableContainsId = DB::table('bulletins')
733 ->select('name')
734 ->where('id', '=', $id)
735 ->first();
736
737 if (!isset($isTableContainsId))
738 return view('errors.404');
739
740 $today_code = floor(((Carbon::now()->startOfDay()->timestamp - 50400)/86400)-16630)."";
741
742
743 if (self::getMainLng() == 'ru' && Session::get('is_chinesse_bulletins') == 'true') {
744 $bulletinInfo = DB::table('bulletins')
745 ->selectRaw('sid[array_upper(sid, 1)], bulletins_locs.name as name, uid, bulletins_locs.data as data, bulletins_locs.description as description, main_photo, add_timestamp, is_anonymous, statistic, moderated')
746 ->join('bulletins_locs','bulletins.loc_id','=','bulletins_locs.id')
747 ->where('bulletins.id', '=', $id)
748 ->get();
749
750 if (!$bulletinInfo) {
751 $bulletinInfo = DB::table('bulletins')
752 ->selectRaw('sid[array_upper(sid, 1)], name, uid, data, description, main_photo, add_timestamp, is_anonymous, statistic, moderated')
753 ->where('id', '=', $id)
754 ->get();
755 }
756 } else {
757 $bulletinInfo = DB::table('bulletins')
758 ->selectRaw('sid[array_upper(sid, 1)], name, uid, data, description, main_photo, add_timestamp, is_anonymous, statistic, moderated')
759 ->where('id', '=', $id)
760 ->get();
761 }
762
763 if (Auth::user() == null)
764 {
765 DB::table('bulletins')
766 ->where('id', '=', $id)
767 ->increment('views');
768 }
769 elseif (Auth::user()->id != $bulletinInfo[0]->uid)
770 {
771 DB::table('bulletins')
772 ->where('id', '=', $id)
773 ->increment('views');
774 }
775
776 Session::put('mainPhoto', $bulletinInfo[0]->main_photo);
777
778 $bulletinStatistic = array();
779 if ($bulletinInfo[0]->statistic != "") {
780 $bulletinStatistic = json_decode($bulletinInfo[0]->statistic, true);
781 if (!array_key_exists("$today_code", $bulletinStatistic))
782 $bulletinStatistic = array_add($bulletinStatistic, "$today_code", 1);
783 else
784 $bulletinStatistic["$today_code"]++;
785 } else {
786 $bulletinStatistic = array();
787 $bulletinStatistic["statistic_starts"] = $today_code;
788 $bulletinStatistic["$today_code"] = "1";
789 }
790
791 $bulletinStatistic = json_encode($bulletinStatistic);
792 DB::table('bulletins')
793 ->where('id', '=', $id)
794 ->update(['statistic' => $bulletinStatistic]);
795
796 $ffsid = DB::table('sections')
797 ->select('ffsid')
798 ->where('sid', '=', $bulletinInfo[0]->sid)
799 ->get();
800
801 $userName = DB::table('users')
802 ->select('name')
803 ->where('id', '=', $bulletinInfo[0]->uid)
804 ->get();
805
806 if (Auth::check()) {
807 $currentFavorites = DB::table('users')
808 ->select('favorites')
809 ->where('id', '=', Auth::user()->id)
810 ->first();
811
812 $currentFavorites = str2arr($currentFavorites->favorites);
813 }
814 else $currentFavorites = array();
815
816 $isFavorite = '2';
817 if (in_array($id, $currentFavorites)) {
818 $isFavorite = '1';
819 } else {
820 $isFavorite = '';
821 }
822
823 $dirContent = array();
824 if (is_dir("images/bulletinsPics/$id"))
825 $dirContent = File::files("images/bulletinsPics/$id");
826
827 $thumbsDir = "images/bulletinsPics/$id/thumbs";
828 if (!is_dir($thumbsDir)) {
829 File::makeDirectory($thumbsDir, 0755, true);
830 }
831
832 $index = 0;
833 $images = array();
834 foreach ($dirContent as $e) {
835 $path = explode('/',$e);
836 $filename = $path[count($path)-1];
837 array_push($images,$filename);
838 if (!File::exists("$thumbsDir/$filename"))
839
840 $img = new Image();
841 $img = Image::make($e);
842 $img->save($thumbsDir.'/'.$filename);
843
844 $index++;
845 }
846 $images = array_values($images);
847
848 $isOwner = false;
849 if (Auth::check()) {
850 $isOwner = $bulletinInfo[0]->uid == Auth::user()->id ? true : false;
851 }
852
853 $comments = DB::table('bulletins_comments')
854 ->select('comment_text', 'user_name', 'is_owner')
855 ->where('bid', '=', $id)
856 ->orderBy('creation_timestamp', 'asc')
857 ->get();
858
859 return view('pages.bulletin', [
860 'UserID' => $UserID,
861 'isOwner' => $isOwner,
862 'sid' => $bulletinInfo[0]->sid,
863 'ffsid' => $ffsid[0]->ffsid,
864 'bulletinName' => htmlentities($bulletinInfo[0]->name),
865 'description' => $bulletinInfo[0]->description,
866 'isBulletinAnonymous' => $bulletinInfo[0]->is_anonymous,
867 'isFavorite' => $isFavorite,
868 'bulletinUserName' => $userName[0]->name,
869 'bulletinUserId' => $bulletinInfo[0]->uid,
870 'bulletinId' => $id,
871 'bulletinDate' => date_format(date_create($bulletinInfo[0]->add_timestamp), 'd-m-Y \в H:i'),
872 'photosLinks' => $images,
873 'comments' => $comments,
874 'moderated' => $bulletinInfo[0]->moderated
875 ]);
876 }
877
878 public function getBulletinStatistic($id) {
879 $bulletinStats = DB::table('bulletins')
880 ->select('statistic')
881 ->where('id', '=', $id)
882 ->first();
883
884 $bulletinStats = json_decode($bulletinStats->statistic, true);
885
886 $resultData = array();
887 $statistic_starts = $bulletinStats["statistic_starts"];
888 $today_code = (((Carbon::now()->startOfDay()->timestamp - 50400)/86400)-16630)."";
889
890 for ($i = $statistic_starts; $i <= $today_code; $i++) {
891 if (array_key_exists($i.'', $bulletinStats))
892 $resultData[date_format(Carbon::createFromTimestamp(($i + 16630) * 86400 + 50401), 'd-M-y')] = $bulletinStats[$i];
893 else
894 $resultData[date_format(Carbon::createFromTimestamp(($i + 16630) * 86400 + 50401), 'd-M-y')] = 0;
895 }
896
897 return view('pages.bulletinStatistic', [
898 'bulletinId' => $id,
899 'viewsChartPoints' => $resultData
900 ]);
901 }
902
903 public function addBulletinPage()
904 {
905 if (Auth::check()) {
906 File::deleteDirectory('./tmp/' . Auth::user()->id . '/');
907 return view('pages.bulletinAddEdit', ['id' => 0, 'sid' => 0, 'name' => "", 'editMode' => false]);
908 } else
909 return ('Добавление объявлений на сайт разрешено только зарегистрированным пользователям.');
910 }
911
912 function getSectionsFullLeaves($sidToCheck)
913 {
914 return (
915 array_unique(
916 _GetSectionsFullLeaves(
917 $sidToCheck
918 )
919 )
920 );
921 }
922
923 public function postBulletinPage() {
924 if (!Auth::check()) // Если юзер залогинен
925 return ('You have not permission too see this page');
926
927 $images = array(); // Все фотки объявы
928 if (isset($_FILES["image"]))
929 $images = $_FILES["image"];
930
931 global $currId; // ???
932
933 DB::transaction( function () {
934
935 $bulletinData = Input::all(); // Все данные объявы
936
937 $city = _getCitiesFullBranch($bulletinData["city_id"]); // Полный путь к городу
938
939 /* Ансетим излишества */
940 unset($bulletinData["_token"]);
941 unset($bulletinData["section"]);
942 unset($bulletinData["description"]);
943 unset($bulletinData["imageDownloaderKey"]);
944
945 if (isset($bulletinData["image"]))
946 unset($bulletinData["image"]);
947
948 unset($bulletinData["name"]);
949 unset($bulletinData["isDraft"]);
950 unset($bulletinData["city_id"]);
951
952 if (isset($bulletinData["currency"])) {
953 $currency = $bulletinData["currency"];
954 unset($bulletinData["currency"]);
955 } else $currency = '';
956
957 if (isset($bulletinData["contacts"])) {
958 $bulletinData["contacts"] = strip_tags($bulletinData["contacts"]);
959 }
960
961 if (isset($bulletinData["youtubeLink"])) {
962 $link = parse_url($bulletinData["youtubeLink"]);
963 if (isset($link['query'])) {
964 // парсинг по полной ссылке http://www.youtube.com/watch?v=XXXXX
965 parse_str($link['query'], $output);
966 $bulletinData["youtubeLink"] = $output['v'];
967 } else {
968 // парсинг по короткой ссылке https://youtu.be/XXXXX
969 $output = pathinfo($bulletinData["youtubeLink"]);
970 $bulletinData["youtubeLink"] = $output['basename'];
971 }
972 }
973 else
974 $bulletinData["youtubeLink"] = '';
975
976 /* Разборки с автомобилями */
977 if (isset($bulletinData["autoVendor"])) {
978 $name = DB::table('auto_models')
979 ->select('name')
980 ->where('id', '=', $bulletinData["autoVendor"])
981 ->first();
982 $bulletinData["autoVendor"] = $name->name; // Заменяем айдишник производителя на его имя
983 }
984 if (isset($bulletinData["autoModel"])) {
985 $name = DB::table('auto_models')
986 ->select('name')
987 ->where('id', '=', $bulletinData["autoModel"])
988 ->first();
989 $bulletinData["autoModel"] = $name->name; // Заменяем айдишник модели на ее имя
990 }
991 if (isset($bulletinData["autoCarcass"])) {
992 $name = DB::table('auto_models')
993 ->select('name')
994 ->where('id', '=', $bulletinData["autoCarcass"])
995 ->first();
996 $bulletinData["autoCarcass"] = $name->name; // Заменяем айдишник корпуса на его имя
997 }
998 if (isset($bulletinData["autoEngine"])) {
999 $name = DB::table('auto_models')
1000 ->select('name')
1001 ->where('id', '=', $bulletinData["autoEngine"])
1002 ->first();
1003 $bulletinData["autoEngine"] = $name->name; // Заменяем айдишник движка на его имя
1004 }
1005
1006 $nowTimestamp = date('Y-m-d H:i:s',(time()-3600*1)); // Текущий таймштамп
1007 $nowTimestampPlus = date('Y-m-d H:i:s', (time()+3600*24*30)); // Текущий таймштамп + 30 дней
1008
1009 $sections = _getSectionsFullBranch(Input::get("section")); // Берем полную ветку секции размещения объявления
1010
1011 $GLOBALS["currId"] = DB::table('bulletins')->insertGetId([
1012 'name' => Input::get('name'),
1013 'sid' => arr2str($sections),
1014 'city' => arr2str($city),
1015 'uid' => Auth::user()->id,
1016 'data' => json_encode($bulletinData),
1017 'description' => Input::get('description'),
1018 'currency' => $currency,
1019 'add_timestamp' => $nowTimestamp,
1020 'expire_timestamp' => $nowTimestampPlus,
1021 'fixed_to' => $nowTimestamp,
1022 'actual_at' => $nowTimestamp,
1023 'moderated' => self::getMainLng() == 'cn' ? '1' : '4',
1024 'language' => self::getMainLng()
1025 ]);
1026
1027 });
1028
1029 // Moving attached images
1030 $loadedImages = File::files('./tmp/'.Auth::user()->id);
1031
1032 if (count($loadedImages) > 0) {
1033 $movingTo_dir = "images/bulletinsPics/".$GLOBALS["currId"];
1034
1035 if (!File::isDirectory($movingTo_dir))
1036 File::makeDirectory($movingTo_dir, 0755, true);
1037
1038 foreach ($loadedImages as $loadedImage) {
1039 $explodedPath = explode('/', $loadedImage);
1040 $name = random_seq_gen() . $explodedPath[count($explodedPath)-1];
1041
1042 $img = Image::make($loadedImage);
1043 $img->save($movingTo_dir.'/'.$name);
1044
1045 //img_resize($loadedImage, "$movingTo_dir/$name", 1280, 768);
1046 }
1047 }
1048
1049 if (count(File::files('images/bulletinsPics/'.$GLOBALS["currId"])) > 0) {
1050 $explodedPath = explode('/', File::files('images/bulletinsPics/' . $GLOBALS["currId"])[0]);
1051 DB::table('bulletins')
1052 ->where('id', '=', $GLOBALS["currId"])
1053 ->update(['main_photo' => $explodedPath[3]]);
1054 }
1055
1056 if (isset($_POST['saveDraft']))
1057 return Redirect::to('/bulletin/' . $GLOBALS["currId"]);
1058 if (self::getMainLng() == 'ru')
1059 return Redirect::to('/payment?orderType=5&bulletinID=' . $GLOBALS["currId"] . '');
1060 else
1061 return Redirect::to('/bulletin/' . $GLOBALS["currId"]);
1062 }
1063
1064
1065 public function getBulletinFieldNames ($id) {
1066 $bulletinInfo = DB::table('bulletins')
1067 ->select('data')
1068 ->where('id', '=', $id)
1069 ->first();
1070
1071 return json_decode($bulletinInfo->data, true);
1072 }
1073
1074 public function getBulletinFields ($sid) {
1075 $bulletinFieldsSet = DB::table('sections')
1076 ->select('ffsid', 'mpsid')
1077 ->where('sid', '=', $sid)
1078 ->first();
1079 $ffsid =& $bulletinFieldsSet->ffsid;
1080
1081 while (is_null($ffsid)) {
1082 $bulletinFieldsSet = DB::table('sections')
1083 ->select('ffsid', 'mpsid')
1084 ->where('sid', '=', $bulletinFieldsSet->mpsid)
1085 ->first();
1086 $ffsid =& $bulletinFieldsSet->ffsid;
1087 }
1088
1089 $bulletinFieldsIds = DB::table('forms_fields_sets')
1090 ->select('fields')
1091 ->where('ffsid', '=', $ffsid)
1092 ->first();
1093
1094 $bulletinFieldsIds = str2arr($bulletinFieldsIds->fields);
1095
1096 $fieldNames = array();
1097 foreach($bulletinFieldsIds as $fieldId) {
1098 $fieldName = DB::table('forms_fields')
1099 ->select('field_name','name')
1100 ->where('ffid', '=', $fieldId)
1101 ->first();
1102
1103 $fieldNames[$fieldName->field_name] = $fieldName->name;
1104 }
1105
1106 $embedCode = '';
1107 foreach($fieldNames as $key => $fieldName) {
1108 if ($key != 'spaceSelector') {
1109 $style = '';
1110 if (in_array($key, ['experience', 'skills', 'conditionHouse', 'achievements', 'conditionsWork', 'contacts', 'description'])) {
1111 $style = 'margin-top: 10px;';
1112 }
1113 $embedCode .= '<div data-name="'.$key.'" data-required="0" class="Bltn_field" style="display:none;'.$style.'"><div class="Bltn_field_label"><label name="'.$key.'"></label></div><div class="Bltn_field_Control full_width"><div name="'.$key.'"></div></div><div class="Bltn_field_Note"></div></div>';
1114 }
1115 }
1116
1117 array_unshift($fieldNames, $embedCode);
1118
1119 return ($fieldNames);
1120 }
1121
1122 public function getSectionBulletinFields ($sid) {
1123
1124 $lng = Lang::getLocale();
1125
1126 $parentSection = Input::get('parentSection');
1127
1128 $bulletinPrice = getPriceSections($sid);
1129
1130 $bulletinFieldsSet = DB::table('sections')
1131 ->select('sid', 'ffsid', 'mpsid')
1132 ->where('sid', '=', $sid)
1133 ->first();
1134 $ffsid =& $bulletinFieldsSet->ffsid;
1135
1136 while (is_null($ffsid)) {
1137 $bulletinFieldsSet = DB::table('sections')
1138 ->select('sid', 'ffsid', 'mpsid')
1139 ->where('sid', '=', $bulletinFieldsSet->mpsid)
1140 ->first();
1141 $ffsid =& $bulletinFieldsSet->ffsid;
1142 }
1143
1144 $bulletinFieldsIds = DB::table('forms_fields_sets')
1145 ->select('fields')
1146 ->where('ffsid', '=', $ffsid)
1147 ->first();
1148
1149 $summedStr = '';
1150
1151 $fields = DB::table('forms_fields')
1152 ->select('ffid', 'field_name', $lng=='cn'?'name_cn as name':'name', 'field_type', $lng=='cn'?'field_options_cn as field_options':'field_options', $lng=='cn'?'field_note_cn as field_note':'field_note', 'field_addons')
1153 ->whereRaw('ffid = any(\''.$bulletinFieldsIds->fields.'\')')
1154 ->get();
1155
1156 foreach(str2arr($bulletinFieldsIds->fields) as $ffid) {
1157 foreach($fields as $field) {
1158 if ($field->ffid == $ffid) {
1159 echo('<div data-name="' . $field->field_name . '" data-required="0" class="addBltn_field">
1160 <div class="addBltn_field_label"><label>' . $field->name . '</label></div>
1161 <div class="addBltn_field_Control full_width">');
1162 switch ($field->field_type) {
1163 case 'text' :
1164 if ($field->field_name == 'bulletinVideo') {
1165 echo('<input class="form-control" type="' . $field->field_type . '" name="youtubeLink" autocomplete="off" form="addBltn_form" ' . $field->field_addons . '>');
1166 } elseif ($field->field_name == 'price') {
1167 echo('<input class="form-control" name="' . $field->field_name . '" type="' . $field->field_type . '" autocomplete= "off" form="addBltn_form" '.$field->field_addons.'>');
1168 echo('<div class="radio"><label><input type="radio" name="currency" autocomplete="off" form="addBltn_form" value="RUR" checked style="margin-right:25px;"><div>RUR</div></label></div>');
1169 echo('<div class="radio"><label><input type="radio" name="currency" autocomplete="off" form="addBltn_form" value="CNY" style="margin-right:25px;"><div>CNY</div></label></div>');
1170 echo('<div class="radio"><label><input type="radio" name="currency" autocomplete="off" form="addBltn_form" value="USD" style="margin-right:25px;"><div>USD</div></label></div>');
1171 echo('<div class="radio"><label><input type="radio" name="currency" autocomplete="off" form="addBltn_form" value="EUR" style="margin-right:25px;"><div>EUR</div></label></div>');
1172 echo('<div class="radio"><label><input type="radio" name="currency" autocomplete="off" form="addBltn_form" value="JPY" style="margin-right:25px;"><div>JPY</div></label></div>');
1173 } else {
1174 echo('<input class="form-control" name="' . $field->field_name . '" type="' . $field->field_type . '" autocomplete= "off" form="addBltn_form" '.$field->field_addons.'>');
1175 }
1176 break;
1177 case 'radio' :
1178 $options = str2arr($field->field_options);
1179 $i = 0;
1180 foreach ($options as $option) {
1181 $i++;
1182 echo('<div class="' . $field->field_type . '"><label>');
1183 echo('<input id="'.$field->field_name.'" type="' . $field->field_type . '" name="' . $field->field_name . '" autocomplete= "off" form="addBltn_form" value="' . $option . '" '.(($i == 1)?'checked':'').' '.$field->field_addons.'>');
1184 echo('<div>'.$option.'</div>');
1185 echo('</label></div>');
1186 }
1187 break;
1188 case 'select' :
1189 $i = 0;
1190 echo('<select class="form-control" name="' . $field->field_name . '" autocomplete="off" form="addBltn_form" style="max-width:50%;width:auto;" ' . $field->field_addons . ' onchange="loadModels(this);">');
1191 if ($field->field_name == 'autoVendor') {
1192 $foptions = DB::table('auto_models')
1193 ->select('id', 'name')
1194 ->where('pid', '=', 0)
1195 ->orderBy('name', 'asc')
1196 ->get();
1197 foreach($foptions as $foption) {
1198 $i++;
1199 echo('<option value="' . $foption->id . '" ' . (($i == 1) ? 'selected' : '') . '>' . $foption->name . '</option>');
1200 }
1201 } else {
1202 $options = str2arr($field->field_options);
1203 foreach ($options as $option) {
1204 $i++;
1205 echo('<option value="' . $option . '" ' . (($i == 1) ? 'selected' : '') . '>' . $option . '</option>');
1206 }
1207 unset($options);
1208 }
1209 echo('</select>');
1210 break;
1211 case 'checkbox' :
1212 echo('<label class="checkbox-inline">');
1213 echo('<input type="'.$field->field_type.'" name="'.$field->field_name.'" autocomplete="off" form="addBltn_form" value="'.$field->field_options.'" '.$field->field_addons.'>');
1214 echo($field->field_options.'</label>');
1215 break;
1216 case 'textarea' :
1217 echo('<textarea name="' . $field->field_name . '" maxlength="4000" rows="5" cols="130" form="addBltn_form" '.$field->field_addons.'></textarea>');
1218 break;
1219 case 'email' :
1220 echo('<input class="form-control" name="' . $field->field_name . '" type="' . $field->field_type . '" maxlength="128" size="130" autocomplete= "off" form="addBltn_form" '.$field->field_addons.'>');
1221 break;
1222 case 'file' :
1223
1224 if ($field->field_name == 'bulletinPhotos') {
1225 echo " <div id=\"attachImagesProgressBar\" style=\"display: none;float: left;\"><img id=\"Stop\" style=\"margin-right: 20px; margin-top: -4px;\" src=\"../../images/icons/looping.gif\" tyle=\"ext-align:center;\"></div>";
1226 echo('<input type="' . $field->field_type . '" name="image[]" value="Добавить фото" id="inputPhotos" multiple form="addBltn_form" size="10" '.$field->field_addons.'><br><div id="photos_miniatures"></div><script type="text/javascript">InitPhotosInput();</script>');
1227 }
1228 break;
1229 }
1230 echo('</div>');
1231 if (!is_null($field->field_note))
1232 echo('<div class="addBltn_field_Note">'.$field->field_note.'</div>');
1233 echo('</div>');
1234 }
1235 }
1236 }
1237
1238 if (is_null($bulletinPrice) == null)
1239 echo('<div id="bulletinPrice" data-name="Payment_amount" data-required="0" class="addBltn_field">
1240 <div class="addBltn_field_label"><label>Размещение объявления: '.$bulletinPrice.' ₽</label></div>');
1241
1242// foreach($fieldNames as $fieldName) {
1243// $embedCode = File::get('./docs/static/fields2add/' . $fieldName . '.php');
1244// $summedStr .= $embedCode;
1245// }
1246
1247 unset($fieldNames);
1248
1249 return ($summedStr);
1250 }
1251
1252 public function getPaymentPage() {
1253
1254 $bulletinID = 0;
1255 $bulletinName = "";
1256 $bulletinMainPhoto = "";
1257 $UserCash = 0;
1258 $bulletinID = Input::get('bulletinID');
1259
1260 if (isset(Auth::user()->id))
1261 {
1262 $UserID = Auth::user()->id;
1263 $UserCash = Auth::user()->cash;
1264 }
1265 else
1266 return response()->view('errors.404', [], 404);
1267
1268 $noMoney = Session::get('noMoney');
1269
1270 $orderType = Input::get('orderType');
1271 $aboutOrder = getOrderType($orderType, $bulletinID);
1272
1273 $orderName = $aboutOrder['orderName'];
1274 $orderPrice = $aboutOrder['orderPrice'];
1275 $orderText = $aboutOrder['orderText'];
1276 $addCash = $aboutOrder['addCash'];
1277
1278
1279
1280 if ($orderPrice == null)
1281 return Redirect::to('/paymentServicesOnline?orderType=' . $orderType . '&bulletinID=' . $bulletinID . '');
1282
1283 if ($addCash == true)
1284 {
1285 return view('pages.payment', [
1286 'addCash' => ($addCash = true),
1287 'noMoney' => $noMoney,
1288 'orderType' => $orderType,
1289 'orderName' => $orderName,
1290 'orderText' => $orderText,
1291 'orderPrice' => $orderPrice,
1292 'bulletinID' => $bulletinID,
1293 'UserCash' => $UserCash
1294 ]);
1295 }
1296
1297 if (!$bulletinID)
1298 return response()->view('errors.404', [], 404);
1299
1300 $bulletinUID = DB::table('bulletins')
1301 ->select('uid')
1302 ->where('id', '=', $bulletinID)
1303 ->first()->uid;
1304
1305 if (!$bulletinUID)
1306 return response()->view('errors.404', [], 404);
1307
1308 if ($bulletinUID != $UserID)
1309 return response()->view('errors.404', [], 404);
1310
1311 $bulletinInfo = DB::table('bulletins')
1312 ->select('name', 'main_photo')
1313 ->where('id', '=', $bulletinID)
1314 ->first();
1315 if ($bulletinInfo)
1316 {
1317 $bulletinName = $bulletinInfo->name;
1318 $bulletinMainPhoto = $bulletinInfo->main_photo;
1319 }
1320
1321 if ($noMoney == true)
1322 {
1323 $orderPrice = $orderPrice - $UserCash;
1324 return view('pages.payment', [
1325 'addCash' => ($addCash = true),
1326 'noMoney' => $noMoney,
1327 'orderType' => $orderType,
1328 'orderName' => $orderName,
1329 'orderText' => $orderText,
1330 'orderPrice' => $orderPrice,
1331 'bulletinID' => $bulletinID,
1332 'UserCash' => $UserCash
1333 ]);
1334 }
1335
1336 return view('pages.payment', [
1337 'addCash' => false,
1338 'orderType' => $orderType,
1339 'orderName' => $orderName,
1340 'orderText' => $orderText,
1341 'noMoney' => $noMoney,
1342 'orderPrice' => $orderPrice,
1343 'bulletinID' => $bulletinID,
1344 'bulletinName' => $bulletinName,
1345 'bulletinMainPhoto' => $bulletinMainPhoto,
1346 'UserCash' => $UserCash
1347 ]);
1348 }
1349
1350 //Отчет
1351 public function getPaymentResultPage() {
1352
1353 }
1354
1355 //Успешная оплата
1356 public function getPaymentSuccessPage() {
1357
1358 $mrh_pass2 = "6frh3DKKFd";
1359
1360 $inv_id = 0;
1361
1362 $UserID = Input::get('Shp_userID');
1363 $orderType = Input::get('Shp_orderType');
1364 $bulletinID = Input::get('Shp_bulletinID');
1365
1366 $aboutOrder = getOrderType($orderType, $bulletinID);
1367
1368 $orderText = $aboutOrder['orderText'];
1369 $orderName = $aboutOrder['orderName'];
1370 $orderPrice = $aboutOrder['orderPrice'];
1371
1372 // Shp_userID
1373 $Shp_item = Input::get('Shp_item');
1374 $out_summ = Input::get('out_summ');
1375 $crc = Input::get('crc');
1376 $inv_id = Input::get('inv_id');
1377
1378 $orderPrice = $out_summ;
1379 $UserCash = Auth::user()->cash;
1380
1381 if ((!$orderType) and ($bulletinID == 0))
1382 {
1383 $UserCash = $UserCash + $out_summ;
1384 DB::table('users')
1385 ->where('id', Auth::user()->id)
1386 ->update(array('cash' => $UserCash));
1387 return Redirect::to('/personal/start');
1388 }
1389
1390 $UserCash = $UserCash + $out_summ;
1391 DB::table('users')
1392 ->where('id', Auth::user()->id)
1393 ->update(array('cash' => $UserCash));
1394
1395 return Redirect::to('/bulletin/'.$bulletinID);
1396 // if ($UserCash > $orderPrice)
1397 // {
1398 // $UserCash = $UserCash - $orderPrice;
1399 // DB::table('users')
1400 // ->where('id', Auth::user()->id)
1401 // ->update(array('cash' => $UserCash));
1402 // getServicesOnline($orderType,$bulletinID);
1403 // return Redirect::to('/bulletin/'.$bulletinID);
1404 // }
1405 }
1406
1407 //Неуспешная оплата
1408 public function getPaymentFailPage()
1409 {
1410 return view('app');
1411 }
1412
1413 //Пополнить счет
1414 public function paymentAddCash()
1415 {
1416 $noMoney = Input::get('noMoney');
1417 $orderType = Input::get('orderType');
1418 $bulletinID = Input::get('bulletinID');
1419 $cash = Input::get('cash');
1420
1421 if ($noMoney == 1)
1422 return Redirect::to(payment_for_services($cash,$orderType,$bulletinID));
1423
1424 return Redirect::to(payment_for_services($cash));
1425 }
1426
1427
1428 public function paymentServicesOnline()
1429 {
1430 $UserCash = Auth::user()->cash;
1431 $userID = Auth::user()->id;
1432
1433 $bulletinID = 0;
1434 $orderType = 0;
1435
1436 $bulletinID = Input::get('bulletinID');
1437 $orderType = Input::get('orderType');
1438 $aboutOrder = getOrderType($orderType, $bulletinID);
1439
1440 $orderPrice = $aboutOrder['orderPrice'];
1441 $orderName = $aboutOrder['orderName'];
1442 $orderText = $aboutOrder['orderText'];
1443 $addCash = $aboutOrder['addCash'];
1444
1445 if ($UserCash >= $orderPrice)
1446 {
1447 $UserCash = $UserCash - $orderPrice;
1448 DB::table('users')
1449 ->where('id', Auth::user()->id)
1450 ->update(array('cash' => $UserCash));
1451 getServicesOnline($orderType,$bulletinID);
1452 return Redirect::to('/bulletin/'.$bulletinID);
1453 }
1454 else
1455 {
1456 return Redirect::to('/payment?orderType=' . $orderType . '&bulletinID=' . $bulletinID . '')->with('noMoney' , true);
1457 }
1458 }
1459
1460
1461 public function getActionsPanel($id) {
1462
1463 $SetActionsPanel = null;
1464 $arraySetActionsPanel = array();
1465
1466 $bulletinInfo = DB::table('bulletins')
1467 ->select('moderated', 'is_anonymous', 'uid')
1468 ->where('id', '=', $id)
1469 ->first();
1470
1471 $isFavorite = Input::get('isFavorite');
1472 $bulletinId = $id;
1473 $isBulletinAnonymous = $bulletinInfo->is_anonymous;
1474 $moderated = $bulletinInfo->moderated;
1475
1476 if ($moderated == 1 || $moderated == 0) {
1477 $arraySetActionsPanel[0] = 1;
1478 $arraySetActionsPanel[1] = 2;
1479
1480 if (self::getMainLng() == 'ru') {
1481 $arraySetActionsPanel[2] = 3;
1482 $arraySetActionsPanel[3] = 4;
1483 $arraySetActionsPanel[4] = 5;
1484 $arraySetActionsPanel[5] = 6;
1485 $arraySetActionsPanel[6] = 7;
1486 $arraySetActionsPanel[7] = 8;
1487 } else {
1488 $arraySetActionsPanel[2] = 5;
1489 $arraySetActionsPanel[3] = 7;
1490 }
1491 }
1492 if ($moderated == 4) {
1493 $arraySetActionsPanel[0] = 1;
1494 $arraySetActionsPanel[1] = 2;
1495 $arraySetActionsPanel[2] = 10;
1496 }
1497
1498 if ($moderated == 2) {
1499 $arraySetActionsPanel[0] = 1;
1500 $arraySetActionsPanel[1] = 2;
1501 $arraySetActionsPanel[2] = 11;
1502 }
1503
1504 if ($moderated == 3) {
1505 $arraySetActionsPanel[0] = 9;
1506 }
1507 if (Auth::user() == null)
1508 {
1509 $arraySetActionsPanel = null;
1510 }
1511 if (Auth::user()->id != $bulletinInfo->uid)
1512 {
1513 $arraySetActionsPanel = null;
1514 $arraySetActionsPanel[0] = 8;
1515 }
1516
1517 foreach ( $arraySetActionsPanel as $Value ) {
1518 switch ($Value) {
1519 case 1:
1520 $SetActionsPanel .= "<div class=\"action\" title=\"Редактировать объявление\" onclick=\"location = '../systems/bulletinEdit/" . $bulletinId . "'\">";
1521 $SetActionsPanel .= "<img src=\"/images/icons/bulletin/pencil-2.png\" style=\" margin-top: -2px;margin-right: -1px;\">";
1522 $SetActionsPanel .= "</div>";
1523 break;
1524 case 2:
1525 $SetActionsPanel .= "<div class=\"action\" title=\"Редактировать изображения\" onclick=\"location = '../systems/bulletinImagesEdit/" . $bulletinId . "'\">";
1526 $SetActionsPanel .= "<img src=\"/images/icons/bulletin/pic_edit.png\">";
1527 $SetActionsPanel .= "</div>";
1528 break;
1529 case 3:
1530 $SetActionsPanel .= "<div class=\"action\" title=\"Прикрепить\" onclick=\"location = '../payment?orderType=2&bulletinID=" . $bulletinId . "'\">";
1531 $SetActionsPanel .= "<img src=\"/images/icons/post-clip-1.png\" style=\"width: 34px;\">";
1532 $SetActionsPanel .= "</div>";
1533 break;
1534 case 4:
1535 $SetActionsPanel .= "<div class=\"action fa fa-angle-up\" title=\"Поднять\" onclick=\"location = '../payment?orderType=1&bulletinID=" . $bulletinId . "'\" style=\"font-size:250%;line-height:42px;\">";
1536 $SetActionsPanel .= "</div>";
1537 break;
1538 case 5:
1539 $SetActionsPanel .= "<div class=\"action\" title=\"Статистика\" onclick=\"location = '../stats/" . $bulletinId . "'\">";
1540 $SetActionsPanel .= "<img src=\"/images/icons/bulletin/stat.png\">";
1541 $SetActionsPanel .= "</div>";
1542 break;
1543 case 6:
1544 if ($isBulletinAnonymous == "1")
1545 {
1546 $SetActionsPanel .= "<div class=\"action\" onclick=\"MakeNotAnonymous();\" title=\"Сделать не анонимным\">";
1547 $SetActionsPanel .= "<img src=\"/images/icons/bulletin/anonym.png\" style=\"width: 44px;margin-top: 4px;\">";
1548 $SetActionsPanel .= "</div>";
1549 }
1550 else
1551 {
1552 $SetActionsPanel .= "<div class=\"action\" title=\"Сделать анонимным\" onclick=\"location = '../payment?orderType=4&bulletinID=" . $bulletinId . "'\">";
1553 $SetActionsPanel .= "<img src=\"/images/icons/bulletin/anonym.png\" style=\"width: 44px;margin-top: 4px;\">";
1554 $SetActionsPanel .= "</div>";
1555 }
1556 break;
1557 case 7:
1558 $SetActionsPanel .= "<div class=\"action\" id=\"dellBulletin\" onclick=\"dellBulletin();\" title=\"Удалить\">";
1559 $SetActionsPanel .= "<img src=\"/images/icons/bulletin/delete.png\" style=\"width:20px;\">";
1560 $SetActionsPanel .= "</div>";
1561 break;
1562 case 8:
1563 if ($isFavorite != 1)
1564 {
1565 $SetActionsPanel .= "<div class=\"action\" title=\"В избранное\" onclick=\"AddToFavorites();\" id=\"favoriteButtonContainer\">";
1566 $SetActionsPanel .= "<img src=\"/images/icons/bulletin/favorites.png\">";
1567 $SetActionsPanel .= "</div>";
1568 }
1569 else
1570 {
1571 $SetActionsPanel .= "<div class=\"action\" title=\"Удалить из избранного\" onclick=\"AddToFavorites();\" id=\"favoriteButtonContainer\">";
1572 $SetActionsPanel .= "<span style=\"font-size: 40px;\">—</span>";
1573 $SetActionsPanel .= "</div>";
1574 }
1575 break;
1576 case 9:
1577 $SetActionsPanel .= "<div class=\"action\" title=\"Восстановить\" onclick=\"location = '../payment?orderType=3&bulletinID=" . $bulletinId . "'\">";
1578 $SetActionsPanel .= "<img src=\"/images/icons/bulletin/repair.png\" style=\"width:30px;margin-left: -2px;\">";
1579 $SetActionsPanel .= "</div>";
1580 break;
1581 case 10:
1582 $SetActionsPanel .= "<div class=\"action\" title=\"Разместить объявление\" onclick=\"location = '../payment?orderType=5&bulletinID=" . $bulletinId . "'\">";
1583 $SetActionsPanel .= "<img src=\"/images/icons/bulletin/PlaceAds.png\" style=\"width:36px;\">";
1584 $SetActionsPanel .= "</div>";
1585 break;
1586 case 11:
1587 $SetActionsPanel .= "<div class=\"action\" title=\"Разместить объявление\" onclick=\"location = '../payment?orderType=6&bulletinID=" . $bulletinId . "'\">";
1588 $SetActionsPanel .= "<img src=\"/images/icons/bulletin/PlaceAds.png\" style=\"width:36px;\">";
1589 $SetActionsPanel .= "</div>";
1590 break;
1591 default:
1592 # code...
1593 break;
1594 }
1595 }
1596 return $SetActionsPanel;
1597 }
1598
1599 public function deleteBulletin($id) {
1600 DB::table('bulletins')
1601 ->where('id', '=', $id)
1602 ->where('uid', '=', Auth::user()->id)
1603 ->update(['moderated' => '3']);
1604
1605 return Redirect::to('/bulletin/'.$id);
1606 }
1607
1608 public function setBulletinNotAnonymous($id)
1609 {
1610
1611 $bulletinUID = DB::table('bulletins')
1612 ->select('uid')
1613 ->where('id', '=', $id)
1614 ->first()->uid;
1615 $UserID = Auth::user()->id;
1616
1617 if ((DB::table('bulletins')->where('id', $id)->first()->is_anonymous == true) and ($bulletinUID == $UserID))
1618 {
1619
1620 DB::table('bulletins')
1621 ->where('id', '=', $id)
1622 ->where('uid', '=', Auth::user()->id)
1623 ->update(['is_anonymous' => false ]);
1624 return Redirect::to('/bulletin/'.$id);
1625 }
1626 }
1627
1628 public function editBulletinPage($id){
1629 $bulletinInfo = DB::table('bulletins')
1630 ->select('uid', 'sid', 'name', 'data')
1631 ->where('id', '=', $id)
1632 ->first();
1633
1634 if ($bulletinInfo->uid != Auth::user()->id)
1635 return ('У вас нет на это прав');
1636
1637 $sid = str2arr($bulletinInfo->sid);
1638 $sid = $sid[count($sid)-1];
1639
1640 $data = json_decode($bulletinInfo->data, true);
1641
1642 $autoData = array();
1643 foreach ($data as $key => $value) {
1644 if (in_array($key, ['autoVendor','autoModel','autoCarcass','autoEngine'])) {
1645 $pid = 0;
1646 switch ($key) {
1647 case "autoModel":
1648 $pid = $autoData["autoVendor"];
1649 break;
1650 case "autoCarcass":
1651 $pid = $autoData["autoModel"];
1652 break;
1653 case "autoEngine":
1654 $pid = $autoData["autoCarcass"];
1655 break;
1656 }
1657 $autoId = DB::table('auto_models')
1658 ->select('id')
1659 ->where('name', '=', $value)
1660 ->where('pid', '=', $pid)
1661 ->get();
1662
1663 $autoData[$key] = $autoId[0]->id;
1664 }
1665 }
1666 return view('pages.bulletinAddEdit', ['id' => $id, 'sid' => $sid, 'name' => $bulletinInfo->name, 'editMode' => true, 'autoIDs' => $autoData]);
1667
1668 }
1669
1670 public function addBulletinAsFavorite($bid) {
1671
1672 $currentFavorites = DB::table('users')
1673 ->select('favorites')
1674 ->where('id', '=', Auth::user()->id)
1675 ->first();
1676
1677 if ($currentFavorites->favorites == "" || $currentFavorites->favorites == "{}")
1678 $currentFavorites = array();
1679 else
1680 $currentFavorites = str2arr($currentFavorites->favorites);
1681
1682 if (in_array($bid, $currentFavorites)) {
1683 $currentFavorites = array_diff($currentFavorites, array($bid));
1684 DB::table("users")
1685 ->where('id', '=', Auth::user()->id)
1686 ->update(['favorites' => arr2str($currentFavorites)]);
1687 return "";
1688 }
1689
1690 array_push($currentFavorites, $bid);
1691 DB::table("users")
1692 ->where('id', '=', Auth::user()->id)
1693 ->update(['favorites' => arr2str($currentFavorites)]);
1694
1695 return "1";
1696 }
1697
1698 public function editBulletinImages($id){
1699
1700 if (Auth::check())
1701 File::deleteDirectory('./tmp/' . Auth::user()->id . '/');
1702
1703 $bulletinInfo = DB::table('bulletins')
1704 ->select('uid')
1705 ->where('id', '=', $id)
1706 ->first();
1707
1708 if ($bulletinInfo->uid != Auth::user()->id)
1709 return ('You have not permission too see this page');
1710
1711 $dirContent = array();
1712 if (is_dir('images/bulletinsPics/'.$id))
1713 $dirContent = File::files('images/bulletinsPics/'.$id);
1714
1715// $index = 0;
1716// foreach($dirContent as $e) {
1717// if (is_dir($e) || $e == 'originalImages')
1718// unset($dirContent[$index]);
1719// if (is_dir($e) || $e == 'deletedImages')
1720// unset($dirContent[$index]);
1721// $index++;
1722// }
1723 $dirContent = array_values($dirContent);
1724
1725 return view('pages.bulletinImages',[
1726 'bulletinId' => $id,
1727 'photosLinks' => $dirContent,
1728 'mainPhoto' => Session::get('mainPhoto', '')
1729 ]);
1730 }
1731
1732 public function imageFilter($id, $photoLink){
1733 $bulletinInfo = DB::table('bulletins')
1734 ->select('uid')
1735 ->where('id', '=', $id)
1736 ->first();
1737
1738 if ($bulletinInfo->uid != Auth::user()->id)
1739 return ('You have not permission too see this page');
1740
1741 return view('pages.imageFilter', [
1742 'imageName' => $photoLink,
1743 'bulletinId' => $id
1744 ]);
1745 }
1746
1747 public function saveImageFilter($id, $photoLink) {
1748
1749 $dirContent = array();
1750 if (is_dir('images/bulletinsPics/'.$id))
1751 $dirContent = File::files('images/bulletinsPics/'.$id);
1752
1753 $index = 0;
1754 foreach($dirContent as $e) {
1755 if (is_dir($e) || $e == 'originalImages')
1756 unset($dirContent[$index]);
1757 if (is_dir($e) || $e == 'deletedImages')
1758 unset($dirContent[$index]);
1759 $index++;
1760 }
1761 $dirContent = array_values($dirContent);
1762
1763 return view('pages.bulletinImages',[
1764 'bulletinId' => $id,
1765 'photosLinks' => $dirContent,
1766 'mainPhoto' => Session::get('mainPhoto', '')
1767 ]);
1768 }
1769
1770 public function saveBulletinImage($id, $imageName) {
1771
1772 File::delete('images/bulletinsPics/' . $id . '/thumbs/' . explode('.', $imageName)[0] . '.png');
1773
1774 $bulletinData = Input::all();
1775
1776 if ($bulletinData['photoBase'] == 1) {
1777 if (File::isFile('images/bulletinsPics/' . $id . '/originalImages/o_' . $imageName)) {
1778 File::delete('images/bulletinsPics/' . $id . '/' . explode('.', $imageName)[0] . '.png');
1779 File::delete('images/bulletinsPics/' . $id . '/thumbs/' . explode('.', $imageName)[0] . '.png');
1780 File::move('images/bulletinsPics/' . $id . '/originalImages/o_'. $imageName, 'images/bulletinsPics/' . $id . '/' . $imageName);
1781 return ('Success!');
1782 }
1783 else return ('It is original photo!');
1784 }
1785
1786 if ($bulletinData['photoBase'] == 2) {
1787 if (!File::isDirectory('images/bulletinsPics_removed/' . $id))
1788 File::makeDirectory('images/bulletinsPics_removed/' . $id, 0755, true);
1789
1790 if (File::isFile('images/bulletinsPics/' . $id . '/originalImages/o_' . $imageName)) {
1791 File::delete('images/bulletinsPics/' . $id . '/' . explode('.', $imageName)[0] . '.png');
1792 File::delete('images/bulletinsPics/' . $id . '/thumbs/' . explode('.', $imageName)[0] . '.png');
1793 File::move('images/bulletinsPics/' . $id . '/originalImages/o_'. $imageName, 'images/bulletinsPics_removed/' . $id. '/' . $imageName);
1794 }
1795 else File::move('images/bulletinsPics/' . $id . '/'. $imageName, 'images/bulletinsPics_removed/' . $id. '/' . $imageName);
1796 return ('Success!');
1797 }
1798
1799 if ($photoBase = base64_decode(explode(',', $bulletinData['photoBase'])[1])) {
1800 if (!File::isDirectory('images/bulletinsPics/' . $id . '/originalImages'))
1801 File::makeDirectory('images/bulletinsPics/' . $id . '/originalImages', 0755, true);
1802
1803 if (!File::isFile('images/bulletinsPics/' . $id . '/originalImages/o_' . $imageName))
1804 File::move('images/bulletinsPics/' . $id . '/' . $imageName, 'images/bulletinsPics/' . $id . '/originalImages/o_' . explode('.', $imageName)[0] . '.png');
1805 else
1806 File::delete('images/bulletinsPics/' . $id . '/' . $imageName);
1807
1808 fopen('images/bulletinsPics/' . $id . '/' . explode('.', $imageName)[0] . '.png', 'w');
1809 file_put_contents('images/bulletinsPics/' . $id . '/' . explode('.', $imageName)[0] . '.png', $photoBase);
1810
1811 return ('The filter was applied!');
1812 }
1813 }
1814
1815 public function makeMainPhoto($id, $imageName) {
1816
1817 DB::table('bulletins')
1818 ->where('id', '=', $id)
1819 ->update(['main_photo' => $imageName]);
1820 Session::put('mainPhoto', $imageName);
1821
1822 $dirContent = array();
1823 if (is_dir('images/bulletinsPics/'.$id))
1824 $dirContent = File::files('images/bulletinsPics/'.$id);
1825
1826 return view('pages.bulletinImages',[
1827 'bulletinId' => $id,
1828 'photosLinks' => $dirContent,
1829 'mainPhoto' => $imageName
1830 ]);
1831 }
1832
1833 public function getBulletinData ($id,$editMode) {
1834
1835 if (self::getMainLng() == 'ru' && Session::get('is_chinesse_bulletins') == 'true') {
1836 $bulletinInfo = DB::table('bulletins')
1837 ->select('bulletins_locs.data as data','currency', 'bulletins_locs.description as description')
1838 ->join('bulletins_locs','bulletins.loc_id','=','bulletins_locs.id')
1839 ->where('bulletins.id', '=', $id)
1840 ->first();
1841 } else {
1842 $bulletinInfo = DB::table('bulletins')
1843 ->select('data','currency', 'description')
1844 ->where('id', '=', $id)
1845 ->first();
1846 }
1847
1848 //256789//
1849 // $bulletinInfoDataArray = str2arr($bulletinInfo->data);
1850 // dd($bulletinInfoDataArray);
1851 // $key = array_search('contacts', $bulletinInfoDataArray);
1852
1853 // $bulletinInfoDataArray[1] = null;
1854 // $bulletinInfo->data = arr2str($bulletinInfoDataArray);
1855
1856 // dd($bulletinInfo->data);
1857 $data = json_decode($bulletinInfo->data, true);
1858 $data["currency"] = $bulletinInfo->currency;
1859 $data["description"] = $bulletinInfo->description;
1860 if ($editMode !== "0") {$data["editMode"] = true;} else {$data["editMode"] = false;}
1861 foreach ($data as $key => $value) {
1862 if ($editMode == "0") {
1863 $data[$key] = nl2br(htmlentities($value));
1864 }
1865 else {
1866 $data[$key] = $value;
1867// if (in_array($key, ['autoVendor','autoModel','autoCarcass','autoEngine'])) {
1868// $pid = 0;
1869// switch ($key) {
1870// case "autoModel":
1871// $pid = $data["autoVendor"][0];
1872// break;
1873// case "autoCarcass":
1874// $pid = $data["autoModel"][0];
1875// break;
1876// case "autoEngine":
1877// $pid = $data["autoCarcass"][0];
1878// break;
1879// }
1880// $autoId = DB::table('auto_models')
1881// ->select('id')
1882// ->where('name', '=', $value)
1883// ->where('pid', '=', $pid)
1884// ->get();
1885//
1886// $data[$key] = array($autoId[0]->id, $value);
1887// }
1888 }
1889 }
1890
1891 return ($data);
1892 }
1893
1894 public function postEditedBulletinPage($id){
1895 $bulletinInfo = DB::table('bulletins')
1896 ->select('uid' , 'moderated')
1897 ->where('id', '=', $id)
1898 ->first();
1899
1900 $Moderated = $bulletinInfo->moderated;
1901
1902 if (!($bulletinInfo->moderated == 4 || $bulletinInfo->moderated == 3)) {
1903 $Moderated = 0;
1904 }
1905
1906 else
1907
1908 if ($bulletinInfo->uid != Auth::user()->id)
1909 return ('You have not permission too see this page');
1910
1911 $bulletinData = Input::all();
1912
1913 $sections = _getSectionsFullBranch(Input::get("section"));
1914 $sections = arr2str($sections);
1915
1916 $name = $bulletinData["name"];
1917 if (isset($bulletinData["currency"])) {
1918 $currency = $bulletinData["currency"];
1919 unset($bulletinData["currency"]);
1920 } else $currency = '';
1921
1922 unset($bulletinData["_token"]);
1923 unset($bulletinData["section"]);
1924 unset($bulletinData["imageDownloaderKey"]);
1925 unset($bulletinData["image"]);
1926 unset($bulletinData["name"]);
1927 unset($bulletinData["description"]);
1928
1929 /* Разборки с автомобилями */
1930 if (isset($bulletinData["autoVendor"])) {
1931 $vendorName = DB::table('auto_models')
1932 ->select('name')
1933 ->where('id', '=', $bulletinData["autoVendor"])
1934 ->first();
1935 $bulletinData["autoVendor"] = $vendorName->name; // Заменяем айдишник производителя на его имя
1936 }
1937 if (isset($bulletinData["autoModel"])) {
1938 $modelName = DB::table('auto_models')
1939 ->select('name')
1940 ->where('id', '=', $bulletinData["autoModel"])
1941 ->first();
1942 $bulletinData["autoModel"] = $modelName->name; // Заменяем айдишник модели на ее имя
1943 }
1944 if (isset($bulletinData["autoCarcass"])) {
1945 $carcassName = DB::table('auto_models')
1946 ->select('name')
1947 ->where('id', '=', $bulletinData["autoCarcass"])
1948 ->first();
1949 $bulletinData["autoCarcass"] = $carcassName->name; // Заменяем айдишник корпуса на его имя
1950 }
1951 if (isset($bulletinData["autoEngine"])) {
1952 $engineName = DB::table('auto_models')
1953 ->select('name')
1954 ->where('id', '=', $bulletinData["autoEngine"])
1955 ->first();
1956 $bulletinData["autoEngine"] = $engineName->name; // Заменяем айдишник движка на его имя
1957 }
1958
1959 if (isset($bulletinData["contacts"])) {
1960 $bulletinData["contacts"] = strip_tags($bulletinData["contacts"]);
1961 }
1962
1963 $parsBuff = DB::table('bulletins')
1964 ->select('data')
1965 ->where('id', '=', $id)
1966 ->first();
1967 $parsBuff = json_decode($parsBuff->data, true);
1968
1969 if(isset($parsBuff['youtubeLink']))
1970 {
1971 $bulletinData['youtubeLink'] = $parsBuff['youtubeLink'];
1972 }
1973 else $bulletinData['youtubeLink'] = '';
1974
1975 DB::table('bulletins')
1976 ->where('id', '=', $id)
1977 ->update(['data' => json_encode($bulletinData), 'description' => Input::get("description"), 'currency' => $currency, 'sid' => $sections, 'name' => $name, 'moderated' => $Moderated]);
1978
1979 return Redirect::to('/bulletin/'.$id);
1980 }
1981
1982 public function postTmpBulletinImage() {
1983
1984 $uploadedImages = array();
1985
1986 $filesCount = count(File::files('tmp/'.Auth::user()->id.'/'));
1987
1988 if ($filesCount >= 10) {
1989 return ("MaximumCount");
1990 }
1991
1992 $EmptySeats = NULL;
1993 $EmptySeats = array();
1994 $EmptySeats = CheckEmptiness(count(Input::file('image'))); //Нахождения пустых мест.
1995
1996 if (!($EmptySeats['NumberItemsFree'] == 0))
1997 {
1998 for ($i = 0; $i < (int)$EmptySeats['NumberItemsFree']; $i++)
1999 {
2000 $imageName = ($EmptySeats[$i]) . '.' . Input::file('image')[$i]->getClientOriginalExtension();
2001 $uploadFlag = Input::file('image')[$i]->move('tmp/' . Auth::user()->id . '/', $imageName);
2002 if ($uploadFlag) {
2003 $uploadedImages[] = $imageName;
2004 }
2005 }
2006 }
2007
2008
2009 $UploadImagesShift = 0;
2010
2011 for ($i = (int)$EmptySeats['NumberItemsFree']; $i < (count(Input::file('image')) - (int)$EmptySeats['NumberItemsFree']); $i++)
2012 {
2013 if (($UploadImagesShift + (int)$EmptySeats['lastImageElement']) < 10)
2014 {
2015 $imageName = ((int)$EmptySeats['lastImageElement'] + $UploadImagesShift) . '.' . Input::file('image')[$i]->getClientOriginalExtension();
2016 $uploadFlag = Input::file('image')[$i]->move('tmp/' . Auth::user()->id . '/', $imageName);
2017 if ($uploadFlag) {
2018 $uploadedImages[] = $imageName;
2019 }
2020 }
2021 else
2022 {
2023 return Response::json(['success' => true, 'message' => 'MaximumGot', 'images' => $uploadedImages]);
2024 }
2025 $UploadImagesShift++;
2026 }
2027 return Response::json(['success' => true, 'message' => 'Alright', 'images' => $uploadedImages]);
2028 }
2029
2030 public function deleteTmpBulletinImage () {
2031 File::delete('./tmp/'.Auth::user()->id.'/'.Input::get('imageId'));
2032 }
2033
2034 public function saveEditImage ($id) {
2035 $collect = count(File::files('tmp/'.Auth::user()->id.'/'));
2036 $filesCount = count(File::files('images/bulletinsPics/'.$id.'/'));
2037
2038 if ($collect + $filesCount > 10)
2039 return ("max");
2040 else {
2041 $loadedImages = File::files('./tmp/'.Auth::user()->id);
2042
2043 if (count($loadedImages) > 0) {
2044 $movingTo_dir = "images/bulletinsPics/".$id;
2045
2046 foreach ($loadedImages as $loadedImage) {
2047 $explodedPath = explode('/', $loadedImage);
2048 $name = random_seq_gen() . $explodedPath[count($explodedPath)-1];
2049
2050 //dd($name);
2051 $img = Image::make($loadedImage);
2052 $img->save($movingTo_dir.'/'.$name);
2053 }
2054 }
2055 return ("success");
2056 }
2057 }
2058
2059 public function editYoutubeVideo () {
2060 $youtubeVideoId = Input::get('link');
2061
2062 if (isset($youtubeVideoId)) {
2063 $link = parse_url($youtubeVideoId);
2064 if (isset($link['query'])) {
2065 // парсинг по полной ссылке http://www.youtube.com/watch?v=XXXXX
2066 parse_str($link['query'], $output);
2067 $youtubeVideoId = $output['v'];
2068 } else {
2069 // парсинг по короткой ссылке https://youtu.be/XXXXX
2070 $output = pathinfo($youtubeVideoId);
2071 $youtubeVideoId= $output['basename'];
2072 }
2073 }
2074 else
2075 $youtubeVideoId = '';
2076
2077 $parsBuff = DB::table('bulletins')
2078 ->select('data')
2079 ->where('id', '=', Input::get('bulletinId'))
2080 ->first();
2081
2082 $parsBuff = json_decode($parsBuff->data, true);
2083 $parsBuff['youtubeLink'] = $youtubeVideoId;
2084 $parsBuff = json_encode($parsBuff);
2085
2086 DB::table('bulletins')
2087 ->where('id', Input::get('bulletinId'))
2088 ->update(['data' => $parsBuff]);
2089
2090 return ($youtubeVideoId);
2091 }
2092
2093 public function deleteYoutubeVideo () {
2094 $parsBuff = DB::table('bulletins')
2095 ->select('data')
2096 ->where('id', '=', Input::get('bulletinId'))
2097 ->first();
2098 $parsBuff = json_decode($parsBuff->data, true);
2099 $parsBuff['youtubeLink'] = '';
2100 $parsBuff = json_encode($parsBuff);
2101
2102 DB::table('bulletins')
2103 ->where('id', Input::get('bulletinId'))
2104 ->update(['data' => $parsBuff]);
2105 }
2106 public function getSectionsList ($sid)
2107 {
2108 if (Request::ajax()) {
2109 $sections = DB::table('sections')
2110 ->select('sid', Lang::getLocale()=='cn'?'name_cn as name':'name', 'canbeSelected')
2111 ->whereRaw($sid . ' = any(psids)')
2112 ->orderBy(Lang::getLocale()=='cn'?'name_cn':'name', 'asc')
2113 ->get();
2114 return $sections;
2115 }
2116 }
2117
2118 public function getCitiesList ($cid)
2119 {
2120 if ( Request::ajax() ) {
2121 $cities = DB::table('cities_russia')
2122 ->select('cid', 'name')
2123 ->where('pcid', '=', $cid)
2124 ->orderBy('name', 'asc')
2125 ->get();
2126
2127 return $cities;
2128 }
2129 }
2130
2131 public function cityIdToName ($cid)
2132 {
2133 $name = DB::table('cities_russia')
2134 ->select('name')
2135 ->where('cid', '=', $cid)
2136 ->get();
2137
2138 $name = $name[0]->name;
2139
2140 return $name;
2141 }
2142
2143 public function setUserCity ($cid) {
2144
2145
2146 if (Auth::user())
2147 {
2148 DB::table('users')
2149 ->where('id', '=', Auth::user()->id)
2150 ->update(['city' => $cid]);
2151 }
2152
2153 $name = DB::table('cities_russia')
2154 ->select('name' , 'cid')
2155 ->where('cid', '=', $cid)
2156 ->get();
2157
2158 $name = $name[0]->name;
2159 $response = Response::make($name);
2160
2161 $response->withCookie(Cookie::make('city', $name, 0));
2162 $response->withCookie(Cookie::make('cityID', $cid, 0));
2163
2164
2165 return $response;
2166 }
2167
2168 function getSectionsFullBranch ($sidToCheck)
2169 {
2170 return(
2171 array_unique(
2172 _GetSectionsFullBranch(
2173 $sidToCheck
2174 )
2175 )
2176 );
2177 }
2178
2179 public function likeUser() {
2180 if (Request::ajax()) {
2181 $data = Input::all();
2182
2183 if ($data['liker']) {
2184 DB::table('likes')
2185 ->where('to_id', $data['id'])
2186 ->where('from_id', Auth::user()->id)
2187 ->delete();
2188 } else {
2189 DB::table('likes')
2190 ->insert([
2191 'to_id' => $data['id'],
2192 'from_id' => Auth::user()->id
2193 ]);
2194 }
2195
2196 return DB::table('likes')->where('to_id', $data['id'])->count();
2197 }
2198
2199 return false;
2200 }
2201
2202 public function getUserPublicPage ($id)
2203 {
2204 if ( Auth::check() ) {
2205 $userInfo = DB::table('users')
2206 ->where('id', '=', $id)
2207 ->get();
2208
2209 $userBulletins = DB::table('bulletins')
2210 ->select('id', 'main_photo', 'actual_at', 'name', 'data', 'views', 'moderated', 'currency', 'description')
2211 ->whereRaw('((moderated = 1) or (moderated = 0)) and uid = '.$id)
2212 ->get();
2213
2214 $likes = DB::table('likes')
2215 ->where('to_id', $id)
2216 ->count();
2217
2218 $liker = DB::table('likes')
2219 ->where('to_id', $id)
2220 ->where('from_id', Auth::user()->id)
2221 ->count();
2222 $liker = ($liker > 0);
2223
2224 $isOwner = ($id == Auth::user()->id);
2225
2226 return view('pages.userPublicPage', [
2227 'id' => $userInfo[0]->id,
2228 'userName' => $userInfo[0]->name,
2229 'userFirstName' => $userInfo[0]->first_name,
2230 'userLastName' => $userInfo[0]->last_name,
2231 'userEmail' => $userInfo[0]->email,
2232 'userBulletins' => $userBulletins,
2233 'isOwner' => $isOwner,
2234 'userLikes' => $likes,
2235 'liker' => $liker
2236 ]);
2237 }
2238 else
2239 return ('You have not permission too see this page');
2240 }
2241
2242 public function getUserPersonalPage ($type) {
2243 if ((Auth::check())&&(isset($type))&&(in_array($type,['start','0','1','2','3','4','5']))) {
2244 $userInfo = DB::table('users')
2245 ->where('id', '=', Auth::user()->id)
2246 ->get();
2247
2248 $userFavorites = DB::table('users')
2249 ->select('favorites')
2250 ->where('id', '=', Auth::user()->id)
2251 ->first();
2252
2253 if ($userFavorites->favorites == "{}")
2254 $favorites = array();
2255 else
2256 $favorites = str2arr($userFavorites->favorites);
2257
2258 $userBulletins = DB::table('bulletins')
2259 ->select('id', 'main_photo', 'actual_at', 'name', 'data', 'views', 'moderated', 'currency')
2260 ->where('uid', '=', Auth::user()->id)
2261 ->get();
2262
2263 $actualCount = 0;
2264 $bannedCount = 0;
2265 $waitingCount = 0;
2266 $deletedCount = 0;
2267 $draftsCount = 0;
2268 $favoritesCount = count($favorites);
2269
2270 $totalAmount = count($userBulletins);
2271
2272 foreach ($userBulletins as $bulletin) {
2273 switch ($bulletin->moderated) {
2274 case '0' :
2275 $waitingCount++;
2276 break;
2277 case '1' :
2278 $actualCount++;
2279 break;
2280 case '2' :
2281 $bannedCount++;
2282 break;
2283 case '3' :
2284 $deletedCount++;
2285 break;
2286 case '4' :
2287 $draftsCount++;
2288 break;
2289 }
2290 }
2291
2292 $today_day = Carbon::now()->day;
2293 $today_month = Carbon::now()->month;
2294 $today_year = Carbon::now()->year;
2295
2296 if (strlen($today_day) == 1)
2297 $today_day = "0" . $today_day;
2298 if (strlen($today_month) == 1)
2299 $today_month = "0" . $today_month;
2300
2301 $today_date = $today_day . "/" . $today_month . "/" . $today_year;
2302
2303
2304 $currentCurses = [];//GetCBRcurrency();
2305
2306 if (isset($currentCurses[0])) {
2307 if (!isset($currentCurses[5]))
2308 Session(['usd' => $currentCurses[0], 'eur' => $currentCurses[1], 'jpy' => $currentCurses[2], 'cny' => $currentCurses[3]]);
2309 else
2310 Session(['usd' => $currentCurses[1], 'eur' => $currentCurses[3], 'jpy' => $currentCurses[5], 'cny' => $currentCurses[7]]);
2311 }
2312
2313 if (($type)&&($type == '5')) {
2314 $userBulletins = DB::table('bulletins')
2315 ->select('id', 'main_photo', 'actual_at', 'name', 'data', 'views', 'moderated', 'currency')
2316 ->whereIn('id', $favorites)
2317 ->get();
2318 } elseif ($type != 'start') {
2319 $userBulletins = DB::table('bulletins')
2320 ->select('id', 'main_photo', 'actual_at', 'name', 'data', 'views', 'moderated', 'currency')
2321 ->where('uid', '=', Auth::user()->id)
2322 ->where('moderated', '=', $type)
2323 ->get();
2324 } else {
2325 // Раскомментить, если не нужно выводить удаленные в общем списке
2326 // foreach ($userBulletins as $key => $bulletin)
2327 // if ($bulletin->moderated == '3')
2328 // unset ($userBulletins[$key]);
2329 }
2330
2331 return view('pages.userPersonalPage', [
2332 'userName' => $userInfo[0]->name,
2333 'userFirstName' => $userInfo[0]->first_name,
2334 'userLastName' => $userInfo[0]->last_name,
2335 'userEmail' => $userInfo[0]->email,
2336 'uID' => Auth::user()->id,
2337 'userBulletins' => $userBulletins,
2338 'unreadMessagesCount' => DB::table('messenger')
2339 ->where('to_uid', '=', Auth::user()->id)
2340 ->where('isRead', '=', 'false')
2341 ->count(),
2342 'totalAmount' => $totalAmount,
2343 'actualCount' => $actualCount,
2344 'bannedCount' => $bannedCount,
2345 'waitingCount' => $waitingCount,
2346 'deletedCount' => $deletedCount,
2347 'draftsCount' => $draftsCount,
2348 'favoritesCount' => $favoritesCount
2349 ]);
2350 }
2351 else
2352 return redirect()->back();
2353 }
2354
2355 public function getUserProfile() {
2356 if ( Auth::check() ) {
2357 $userInfo = DB::table('users')
2358 ->where('id', '=', Auth::user()->id)
2359 ->get();
2360
2361 unset($userInfo[0]->password);
2362 unset($userInfo[0]->remember_token);
2363 unset($userInfo[0]->created_at);
2364 unset($userInfo[0]->updated_at);
2365 unset($userInfo[0]->utype);
2366
2367 $userProfile = $userInfo[0];
2368
2369 if ($userProfile->city != 0)
2370 $userProfile->city = array('id' => $userProfile->city, 'name' => DB::table('cities_russia')
2371 ->select('name')
2372 ->where('cid', $userProfile->city)
2373 ->get()[0]->name);
2374
2375 return view('pages.userProfile', [
2376 'userInfo' => $userProfile
2377 ]);
2378 }
2379 else
2380 return ('You have not permission too see this page');
2381 }
2382
2383 public function postUserProfile(){
2384 $data = Input::all();
2385
2386 if (isset($data['btn_last_name'])) {
2387 $valid = Validator::make($data, ['last_name' => 'max:255']);
2388 if($valid->fails())
2389 return redirect()->back()->withErrors($valid);
2390 else
2391 DB::table('users')
2392 ->where('id', Auth::user()->id)
2393 ->update(['last_name' => $data['last_name']]);
2394 }
2395 if (isset($data['btn_first_name'])) {
2396 $valid = Validator::make($data, ['first_name' => 'max:255']);
2397 if($valid->fails())
2398 return redirect()->back()->withErrors($valid);
2399 else
2400 DB::table('users')
2401 ->where('id', Auth::user()->id)
2402 ->update(['first_name' => $data['first_name']]);
2403 }
2404 if (isset($data['btn_email'])) {
2405 $valid = Validator::make($data,
2406 ['email' => 'required|unique:users,email,'.Auth::user()->id.'|different:user_email|max:255'],
2407 [
2408 'different' => 'Вы указали Ваш текущий E-mail. Изменения не были произведены.',
2409 'unique' => 'Пользователь с электронной почтой '.$data['email'].' уже зарегистрирован'
2410 ]
2411 );
2412 if($valid->fails()) {
2413 return redirect()->back()->withErrors($valid);
2414 } else
2415 DB::table('users')
2416 ->where('id', Auth::user()->id)
2417 ->update(['email' => $data['email']]);
2418 }
2419 if (isset($data['btn_pwd'])) {
2420 $rules = ['password' => 'required|confirmed|min:6|max:60'];
2421 $messages = [
2422 'required' => 'Вы не указали новый пароль',
2423 'confirmed' => 'Введенные пароли не совпадают'
2424 ];
2425 $valid = Validator::make($data, $rules, $messages);
2426 if($valid->fails())
2427 return redirect()->back()->withErrors($valid);
2428 else
2429 DB::table('users')
2430 ->where('id', Auth::user()->id)
2431 ->update(['password' => Hash::make($data['password'])]);
2432 }
2433
2434 return redirect()->route('profile');
2435 }
2436
2437 public function getUserBulletinsOfType($type) {
2438 return DB::table('bulletins')
2439 ->select('name', 'id', 'moderated')
2440 ->where('uid', '=', Auth::user()->id)
2441 ->where('moderated', '=', $type)
2442 ->get();
2443 }
2444
2445 public function getSearchBulletinsList () {
2446 $searchText = mb_strtolower(Input::get('searchQuery'));
2447
2448 // $bulletins = DB::select("select id, name from bulletins where lower(name) like '%".$searchText."%' order by add_timestamp desc");
2449 // Подключим файл с api
2450
2451 return view('pages.searchResults', ['searchQuery' => Input::get('searchQuery')]);
2452 }
2453
2454 public function TestSearchFilters($parentId){
2455 $cars = DB::table("search_filters")
2456 ->select('name', 'item_id')
2457 ->where('parent_id', "=", $parentId)
2458 ->get();
2459
2460 $summedString = "";
2461
2462 for ($i = 0; $i < count($cars); $i++)
2463 $summedString .= "<a class='parameter' onclick='Load(\"/testSearchFilters/".$cars[$i]->item_id."\")'>" . $cars[$i]->name . "</a> <br>";
2464
2465 $summedString .= '<script type="text/javascript">function Load(href){$.get(href,function(data){$("#main_container").html(data);});}</script>';
2466
2467 return $summedString;
2468 }
2469
2470
2471 public function TestFormsFieldsGet () {
2472 return '<form method="POST"><textarea name="source"></textarea><input type="hidden" name="_token" id="csrf-token" value="'.Session::token().'" /><input type="submit"></form>';
2473 }
2474
2475 public function TestFormsFieldsPost () {
2476 $JSONStr = Input::get("source");
2477
2478 $JSONStr = json_decode($JSONStr, true);
2479 $result = "";
2480
2481 $globalID = DB::table("search_filters")
2482 ->selectRaw("max(item_id)")
2483 ->get();// видеорегистраторы: 21976;//телефоны: 16970;
2484
2485 $globalID = $globalID[0]->max+2;
2486 $mainParent = $globalID-1;
2487
2488 echo ($mainParent)."<BR><font color=red>ЗАПИШИ ЭТО ЧИСЛО В ДОКУМЕНТ!!!<BR>НЕ ПЕРЕЗАГРУЖАЙ СТРАНИЧКУ, ВСЕ ДОБАВИТСЯ СНОВА!!!</font><br>";
2489
2490 for ($i = 0; $i < count(array_keys($JSONStr)); $i++) {
2491 DB::table("search_filters")->insert(['item_id'=>$globalID, 'parent_id'=>$mainParent, 'name'=>array_keys($JSONStr)[$i]]);
2492 $result .= $globalID.";".$mainParent.";".array_keys($JSONStr)[$i]."<br>";
2493 $parentID = $globalID;
2494 $childs = $JSONStr[array_keys($JSONStr)[$i]];
2495 $globalID++;
2496 for ($j = 0; $j < count(array_keys($childs)); $j++){
2497 DB::table("search_filters")->insert(['item_id'=>$globalID, 'parent_id'=>$parentID, 'name'=>array_keys($childs)[$j]]);
2498 $result .= $globalID.";".$parentID.";".array_keys($childs)[$j]."<br>";
2499 $parentID2 = $globalID;
2500 $childs2 = $childs[array_keys($childs)[$j]];
2501 $globalID++;
2502 for ($k = 0; $k < count(array_keys($childs2)); $k++){
2503 DB::table("search_filters")->insert(['item_id'=>$globalID, 'parent_id'=>$parentID2, 'name'=>array_keys($childs2)[$k]]);
2504 $result .= $globalID.";".$parentID2.";".array_keys($childs2)[$k]."<br>";
2505 $globalID++;
2506 }
2507 }
2508 }
2509
2510 return $result;
2511 }
2512
2513 public function addCash($cash) {
2514 if (Auth::user()->utype < 100)
2515 Die ("Go away, motherfucker!");
2516
2517 DB::table('users')
2518 ->where('id', '=', Auth::user()->id)
2519 ->update(['cash' => Auth::user()->cash+$cash]);
2520 }
2521
2522 public function commentBulletin ($id) {
2523 $owner_id = DB::table('bulletins')
2524 ->select('uid')
2525 ->where('id', '=', $id)
2526 ->first();
2527 $owner_id = $owner_id->uid;
2528 $userName = (Auth::user()->id == $owner_id) ? 'Продавец' : Input::get('userName');
2529
2530 DB::table('bulletins_comments')
2531 ->insert([
2532 'comment_text' => Input::get('messageText'),
2533 'user_name' => $userName,
2534 'is_owner' => Auth::user()->id == $owner_id,
2535 'bid' => $id,
2536 'creation_timestamp' => Carbon::now()
2537 ]);
2538
2539 return Redirect::to('/bulletin/'.$id);
2540 }
2541
2542 public function modelsParse($pid) {
2543 if (Request::ajax()) {
2544 $foptions = DB::table('auto_models')
2545 ->select('id', 'name')
2546 ->where('pid', '=', $pid)
2547 ->orderBy('name', 'asc')
2548 ->get();
2549
2550 return $foptions;
2551 }
2552
2553 return (false);
2554 }
2555
2556 public function categorySelected($sid) {
2557 if (Request::ajax()) {
2558 $i = 0;
2559 $category = array();
2560 while (($i < 3)&&($sid != 0)) {
2561 $section = DB::table('sections')
2562 ->select(Lang::getLocale()=='cn'?'name_cn as name':'name', 'mpsid')
2563 ->where('sid', '=', $sid)
2564 ->first();
2565 $category[$i] = $section->name;
2566 $sid = $section->mpsid;
2567 $i++;
2568 }
2569
2570 $cats = '';
2571 for ($i = 0; $i <= count($category)-1; $i++) {
2572 $cats = (($i != count($category)-1)?' > ':'').$category[$i].$cats;
2573 }
2574 return $cats;
2575 }
2576
2577 return (false);
2578 }
2579
2580 public function canbeSelected($sid) {
2581 $canbeSelected = DB::table('sections')
2582 ->select('views')
2583 ->where('sid', '=', $sid)
2584 ->first();
2585 if (isset($canbeSelected)) {
2586 if ($canbeSelected->views == 0)
2587 return 'true';
2588 else
2589 return 'false';
2590 }
2591 }
2592 public function getRules()
2593 {
2594 return view('pages.rules');
2595 }
2596 public function getContacts()
2597 {
2598 return view('pages.contacts');
2599 }
2600
2601 public function registerConfirmCode($confirmCode) {
2602 $trueConfirmCode = DB::table('users')
2603 ->select('confirmation_code')
2604 ->where('id', '=', explode('_' , $confirmCode)[0])
2605 ->first();
2606
2607 if (!isset($trueConfirmCode))
2608 return ('Неверный адрес ссылки!');
2609
2610 if ($trueConfirmCode->confirmation_code == explode('_' , $confirmCode)[1]) {
2611 DB::table('users')
2612 ->where('id', '=', explode('_', $confirmCode)[0])
2613 ->update(['confirmed' => 'true']);
2614 return Redirect::to('/auth/login');
2615 }
2616 else return ('Неверный адрес ссылки!');
2617 }
2618
2619//Restore User Pasword
2620 public function restorePassword() {
2621 return view("auth.restorePassword");
2622 }
2623
2624 public function sendRestoreCode() {
2625 $restore_password_code = md5(rand(0,1000).'passwCode');
2626 $userEmail = Input::all()['email'];
2627 $userId = DB::table('users')
2628 ->select('id')
2629 ->where('email', '=', $userEmail)
2630 ->first();
2631
2632 DB::table('users')
2633 ->where('email', '=', $userEmail)
2634 ->update(['restore_password_code' => $restore_password_code]);
2635
2636 $to = $userEmail;
2637 $MayMessage = 'Для смены пароля нажмите на ссылку ниже, вы будете перенаправлены на страницу изменения пароля.<br><a href="http://sellpay.ru/restorePassword/'.$userId->id.'_'.$restore_password_code.'">http://sellpay.ru/restorePassword/'.$userId->id.'_'.$restore_password_code.'</a>';
2638 $subject = 'Смена пароля на сайте SellPay';
2639 Mail::send('emails.restore-code', array('MayMessage' => $MayMessage), function($message) use ($userEmail, $subject)
2640 {
2641 $message->to($userEmail, 'Джон Смит')->subject($subject);
2642 });
2643 //$headers = "From:admin@sellpay.ru" . "\r\n";
2644 //$headers .= 'MIME-Version: 1.0' . "\r\n";
2645 //$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
2646
2647 // echo (mail($to, $subject, $message, $headers));
2648 return view('auth.successRestorePsw');
2649 }
2650
2651 public function checkRestoreCode($restorePswCode) {
2652 return view('auth.changePassword');
2653 }
2654
2655 public function changePassword($restorePswCode) {
2656 $data = Input::All();
2657 $trueRestorePswCode = DB::table('users')
2658 ->select('restore_password_code')
2659 ->where('id', '=', explode('_' , $restorePswCode)[0])
2660 ->first();
2661
2662 if (!isset($trueRestorePswCode))
2663 return ('Неверный адрес ссылки!');
2664
2665 $rules = ['password_New' => 'required|min:6|max:60'];
2666 $messages = [
2667 'required' => 'Вы не указали новый пароль',
2668 'confirmed' => 'Введенные пароли не совпадают'
2669 ];
2670 $valid = Validator::make($data, $rules, $messages);
2671
2672 if ($valid->fails() || ($data["password_New"] != $data["password_confirmation_New"])) {
2673 Session::flash('message', 'Введенные пароли не сповпадают/длина пароля меньше 6 символов!');
2674 return Redirect::to('restorePassword/'.$restorePswCode);
2675 }
2676 else
2677 {
2678 if ($trueRestorePswCode->restore_password_code == explode('_' , $restorePswCode)[1]) {
2679 DB::table('users')
2680 ->where('id', '=', explode('_', $restorePswCode)[0])
2681 ->update(['password' => bcrypt(Input::all()["password_New"]), 'restore_password_code' => md5(rand(0,1000).'passwCode')]);
2682
2683 Session::flash('message', 'Пароль успешно изменен!');
2684 return Redirect::to('/auth/login');
2685 }
2686 else return ('Неверный адрес ссылки!');
2687 }
2688 }
2689 public function getCnBulletins() {
2690 if (Session::get('is_chinesse_bulletins') == 'true')
2691 Session::put('is_chinesse_bulletins', 'false');
2692 else
2693 Session::put('is_chinesse_bulletins', 'true');
2694
2695 echo('<script>window.location = "/";</script>');
2696 }
2697 public function cn()
2698 {
2699 if (!Auth::check()) {
2700 Lang::setLocale('cn');
2701 Session::put('locale', 'cn');
2702 }
2703 return redirect('/');
2704 }
2705 public function ru()
2706 {
2707 if (!Auth::check()) {
2708 Lang::setLocale('ru');
2709 Session::put('locale', 'ru');
2710 }
2711 return redirect('/');
2712 }
2713}