· 5 years ago · Aug 19, 2020, 04:46 AM
1<?php
2
3/* (C) Websplosion LTD., 2001-2014
4
5IMPORTANT: This is a commercial software product
6and any kind of using it must agree to the Websplosion's license agreement.
7It can be found at http://www.chameleonsocial.com/license.doc
8
9This notice may not be removed from the source code. */
10
11Class Common {
12
13 const ALLOWTAGS = '<b><i><u><s><strike><strong><em>';
14
15 static $menuItemUrl = array(
16 'gallery' => 'gallery_index.php',
17 'users' => 'users_online.php',
18 'profile' => 'profile_view.php',
19 'rating' => 'users_hon.php',
20 'my' => 'my_friends.php',
21 'partner' => 'partner/',
22 );
23
24 static $urlHomePage = false;
25
26 static $menuItemAuthOnly = array(
27 'home',
28 'wall',
29 'games',
30 'city',
31 'flashchat',
32 'mail',
33 'chat',
34 'profile',
35 'my',
36 'upgrade',
37 );
38
39 static $urlAutoMail = array(
40 'join' => 'profile_view.php',
41 'profile_approved' => 'profile_view.php',
42 'confirm_email' => 'confirm_email.php?hash={hash}',
43 'change_email' => 'confirm_email.php?hash={hash}',
44 'forget' => 'join.php?cmd=forgot',
45 'forget_link' => '{code_link}',
46 'mail_message' => 'mail.php?display=text&mid={mid}',
47 'interest' => 'mail_whos_interest.php?display=profile&uid={uid}',
48 'interest_urban' => 'search_results.php?display=profile&uid={uid}',
49 'invite' => 'invite_confirm.php?id={id}&key={key}',
50 'invite_group' => 'groups_invite.php?cmd=join&group_id={group_id}&key={key}',
51 'invite_group_site' => 'groups_invite.php?cmd=join&group_id={group_id}&key={key}',
52 'friend_added' => 'search_results.php?display=profile&uid={uid}',
53 'wall_alert_message' => 'wall.php?uid={uid}&item={item}',
54 'wall_alert_message_urban' => 'search_results.php?display=profile&uid={uid}&show=wall&wall_item={item}',
55 'wall_alert_like' => 'wall.php?uid={uid}&item={item}',
56 'wall_alert_like_urban' => 'wall.php?wall_item={item}',
57 'wall_alert_comment' => 'wall.php?uid={uid}&item={item}',
58 'match_mail' => 'join.php',
59 'end_paid' => 'upgrade.php',
60 'admin_delete' => 'index.php',
61 'partner_join' => 'index.php',
62 'join_admin' => 'search_results.php?display=profile&uid={uid}',
63 'partner_forget' => 'index.php',
64 'partner_delete' => 'partner/index.php',
65 'friend_request' => 'my_friends.php?show=requests&from={uid}',
66 'contact' => 'administration/contact.php',
67 'partner_contact' => 'administration/contact_partner.php',
68 'profile_visitors' => 'search_results.php?display=profile&uid={uid}',
69 'want_to_meet_you' => 'search_results.php?display=encounters&uid={uid_sender}',
70 'mutual_attraction' => 'mutual_attractions.php',
71 'private_date' => 'search_results.php?display=privatedate&uid={uid_sender}',
72 'private_mutual_attraction' => 'private_mutual_attractions.php',
73 'gift' => 'profile_view.php',
74 'voted_photo' => 'profile_view.php?show=gallery&photo_id={photo_id}',
75 'new_message' => 'search_results.php?display=profile&uid={uid_sender}&show=messages',
76 'new_comment_photo' => 'profile_view.php?show=gallery&photo_id={id}',
77 'new_comment_video' => 'profile_view.php?show=video_gallery&video_id={id}',
78 'welcoming_message' => 'search_results.php?display=profile&uid={user_id}',
79 'approve_image_admin' => 'administration/users_photo.php',
80 'approve_video_admin' => 'administration/users_video.php',
81 'approve_text_admin' => 'administration/users_text.php',
82 'partner_join_admin' => 'administration/partner_edit.php?id={user_id}',
83
84 'photo_approved' => 'profile_view.php',
85 'photo_declined' => 'profile_view.php',
86
87 'video_approved' => 'profile_view.php',
88 'video_declined' => 'profile_view.php',
89 'account_reactive_mail' => 'profile_view.php',
90
91 'text_approved' => 'profile_view.php',
92 'text_declined' => 'profile.php',
93 'like_comment_photo' => 'photos_list.php?uid={uid_gallery}&show=gallery&photo_id={id}&cid={cid}',
94 'like_comment_video' => 'vids_list.php?uid={uid_gallery}&show=gallery&video_id={id}&cid={cid}'
95 );
96
97 static $urlAutoMailTemplate = array(
98 'impact' => array(
99 'new_message' => 'messages.php?display=one_chat&user_id={uid_sender}'
100 ),
101 'impact_mobile' => array(
102 'new_message' => 'messages.php?display=one_chat&user_id={uid_sender}'
103 )
104 );
105
106 static $urlAutoMailByCurrentLocation = array(
107 'join',
108 'confirm_email',
109 'change_email',
110 'forget',
111 'forget_link',
112 'partner_join',
113 'partner_forget',
114 );
115
116 static $urlAutoMailAutologinOff = array(
117 'confirm_email',
118 'change_email',
119 'forget',
120 'forget_link',
121 'admin_delete',
122 'partner_join',
123 'join_admin',
124 'partner_forget',
125 'partner_delete',
126 'contact',
127 'partner_contact',
128 'approve_image_admin',
129 'approve_video_admin',
130 'approve_text_admin',
131 'partner_join_admin',
132 );
133
134 static $uaHttpHeaders = array(
135 // The default User-Agent string.
136 'HTTP_USER_AGENT',
137 // Header can occur on devices using Opera Mini.
138 'HTTP_X_OPERAMINI_PHONE_UA',
139 // Vodafone specific header: http://www.seoprinciple.com/mobile-web-community-still-angry-at-vodafone/24/
140 'HTTP_X_DEVICE_USER_AGENT',
141 'HTTP_X_ORIGINAL_USER_AGENT',
142 'HTTP_X_SKYFIRE_PHONE',
143 'HTTP_X_BOLT_PHONE_UA',
144 'HTTP_DEVICE_STOCK_UA',
145 'HTTP_X_UCBROWSER_DEVICE_UA'
146 );
147
148 static private $classLinks = '';
149 static private $targetLinks = '_blank';
150 static private $prepareLinks = array();
151 static private $setTarget = false;
152 static private $iterationLinks = 1;
153 static public $pagerUrl = '';
154 static public $lPleaseChoose = '';
155
156
157 static function getUrlHomePage()
158 {
159 return self::$urlHomePage;
160 }
161
162 static function setUrlHomePage($urlHomePage)
163 {
164 self::$urlHomePage = $urlHomePage;
165 }
166
167 static function getMenuItemUrl($menu)
168 {
169 return isset(self::$menuItemUrl[$menu]) ? self::$menuItemUrl[$menu] : $menu . '.php';
170 }
171
172 static function getLocationTitle($type, $id, $index = 0)
173 {
174 $types = array(
175 'city',
176 'state',
177 'country',
178 );
179 $title = '';
180 $type = to_sql($type, 'Plain');
181
182 if (in_array($type, $types)) {
183 $sql = 'SELECT ' . $type . '_title
184 FROM geo_' . $type . '
185 WHERE ' . $type . '_id = ' . to_sql($id, 'Number');
186 $result = DB::result($sql, 0, $index);
187 if($result !== 0) {
188 $title = $result;
189 }
190 }
191
192 return $title;
193 }
194
195 static function filterProfileText($text, $isTags = false, $removeTags = true)
196 {
197 global $g;
198
199 if($removeTags) {
200 $text = strip_tags($text);
201 }
202
203 if ($g['options']['filter'] == 'Y') {
204 $text = to_profile($text, '', '', $isTags);
205 }
206
207 return $text;
208 }
209
210 static function replaceByVars($text, $vars, $delimiters = array('{', '}'), $case = false)
211 {
212
213 if (is_array($vars) && count($vars)) {
214
215 $search = array();
216 $replace = array();
217
218 if (is_array($delimiters) && count($delimiters) > 0) {
219 if (!isset($delimiters[1])) {
220 $delimiters[1] = $delimiters[0];
221 }
222 } else {
223 $delimiters = array('', '');
224 }
225
226 foreach ($vars as $key => $value) {
227 $search[] = $delimiters[0] . $key . $delimiters[1];
228 $replace[] = $value;
229 }
230
231 if($case) {
232 $text = str_replace($search, $replace, $text);
233 } else {
234 $text = str_ireplace($search, $replace, $text);
235 }
236 }
237
238 return $text;
239 }
240
241 static function automailInfo($type, $lang, $dbIndex = DB_MAX_INDEX)
242 {
243 $emailAuto = false;
244
245 $sql = 'SELECT * FROM email_auto
246 WHERE note = ' . to_sql($type, 'Text')
247 . 'AND lang = ' . to_sql($lang);
248 $emailAuto = DB::row($sql, $dbIndex);
249 if(!$emailAuto) {
250 $sql = 'SELECT * FROM email_auto
251 WHERE note = ' . to_sql($type, 'Text')
252 . 'AND lang = "default"';
253 $emailAuto = DB::row($sql, $dbIndex);
254 }
255
256 $sql = 'SELECT `value` FROM `email_auto_settings`
257 WHERE `option` = "template"';
258 $emailAuto['template'] = DB::result($sql, 0, $dbIndex);
259
260 $sql = 'SELECT `value` FROM `email_auto_settings`
261 WHERE `option` = ' . to_sql($lang);
262 $emailAuto['thanks'] = DB::result($sql, 0, $dbIndex);
263 if(!$emailAuto['thanks']) {
264 $sql = 'SELECT `value` FROM `email_auto_settings`
265 WHERE `option` = "default"';
266 $emailAuto['thanks'] = DB::result($sql, 0, $dbIndex);
267 }
268
269 return $emailAuto;
270 }
271
272 static function prepareUrlAutoMail($type, $vars)
273 {
274 $optionTmplName = Common::getOption('name', 'template_options');
275 if (Common::isOptionActiveTemplate('is_prepare_url_auto_mail')) {
276 if (!isset(self::$urlAutoMailTemplate[$optionTmplName])) {
277 self::$urlAutoMailTemplate[$optionTmplName] = array();
278 }
279 if ($optionTmplName == 'edge') {
280 if ($type == 'new_message') {
281 self::$urlAutoMailTemplate[$optionTmplName]['new_message'] = User::url($vars['uid'], null, array('show' => 'message', 'uid_sender' => $vars['uid_sender'], 'group_id_sender' => $vars['group_id_sender']));
282 } elseif ($type == 'friend_request') {
283 self::$urlAutoMailTemplate[$optionTmplName]['friend_request'] = User::url($vars['uid_send'], null, array('show' => 'friend_request'));
284 } elseif ($type == 'friend_added') {
285 self::$urlAutoMailTemplate[$optionTmplName]['friend_added'] = User::url($vars['uid']);
286 } elseif ($type == 'new_comment_photo') {
287 self::$urlAutoMailTemplate[$optionTmplName]['new_comment_photo'] = self::pageUrl('user_photos_list', $vars['to_user_id'], null, array('show' => 'gallery', 'photo_id' => $vars['id'], 'cid' => $vars['cid']));
288 } elseif ($type == 'new_comment_video') {
289 self::$urlAutoMailTemplate[$optionTmplName]['new_comment_video'] = self::pageUrl('user_vids_list', $vars['to_user_id'], null, array('show' => 'video_gallery', 'video_id' => $vars['id'], 'cid' => $vars['cid']));
290 } elseif ($type == 'wall_alert_like' || $type == 'wall_alert_message') {
291 self::$urlAutoMailTemplate[$optionTmplName][$type] = self::pageUrl('wall') . '?uid={uid}&item={item}';
292 } elseif ($type == 'wall_alert_comment') {
293 self::$urlAutoMailTemplate[$optionTmplName]['wall_alert_comment'] = self::pageUrl('wall') . '?uid={uid}&item={item}';
294 if (isset($vars['cid']) && $vars['cid']) {
295 self::$urlAutoMailTemplate[$optionTmplName]['wall_alert_comment'] .= '&ncid={cid}';
296 }
297 } elseif ($type == 'group_subscribe_new') {
298 self::$urlAutoMailTemplate[$optionTmplName]['group_subscribe_new'] = User::url($vars['uid']);
299 } elseif ($type == 'group_subscribe_request') {
300 self::$urlAutoMailTemplate[$optionTmplName]['group_subscribe_request'] = User::url($vars['uid'], null, array('show' => 'friend_request'));
301 }
302
303 }
304 }
305 }
306
307 static function sendAutomail($lang, $email, $type, $vars = array(), $emailAuto = false, $dbIndex = DB_MAX_INDEX, $isGetData = false)
308 {
309 global $g;
310 global $sitePart;
311
312 $sent = false;
313
314 if(!Common::isOptionActive('mail') && $type == 'mail_message') {
315 return false;
316 }
317 //Common::getOption('info_mail', 'main') 'partner_delete' 'partner_forget' 'partner_join' 'invite_group' 'invite'
318 if(mb_strpos($type, 'partner', 0, 'UTF-8') === false
319 && !in_array($type, array('invite_group', 'invite'))
320 && $email != Common::getOption('info_mail', 'main')
321 && User::getInfoBasicByEmail($email, 'use_as_online', $dbIndex)){
322 return false;
323 }
324
325 if(Common::isOptionActive('send_emails_only_to_confirmed_emails')
326 && $type != 'confirm_email'
327 && $type != 'change_email'
328 && $type != 'forget'
329 && $type != 'forget_link'
330 && User::getInfoBasicByEmail($email, 'active_code', $dbIndex)) {
331 return false;
332 }
333
334 if(!$emailAuto) {
335 $emailAuto = self::automailInfo($type, $lang, $dbIndex);
336 }
337 $data = array('subject' => '', 'text' => '');
338 if ($emailAuto) {
339 $subject = $emailAuto['subject'];
340 $text = $emailAuto['text'];
341 $data['subject'] = $subject;
342 $data['text'] = $text;
343
344 $vars['to_user_name'] = User::getInfoBasicByEmail($email, 'name', $dbIndex);
345 $vars['to_user_id'] = User::getInfoBasicByEmail($email, 'user_id', $dbIndex);
346 $vars['from_user_name'] = guser('name');
347 $vars['from_user_id'] = guser('user_id');
348
349 if(Common::isValidArray($vars)) {
350 $subject = self::replaceByVars($subject, $vars);
351 $data['subject'] = $subject;
352
353 if (strip_tags($text) == $text) {
354 $text = nl2br($text);
355 }
356 if (isset($vars['text']) &&
357 (strip_tags($vars['text']) == $vars['text'])) {
358 $vars['text'] = nl2br($vars['text']);
359 }
360 $text = self::replaceByVars($text, $vars);
361 /*if (strip_tags($text) == $text) {
362 $text = nl2br($text);
363 }*/
364 $data['text'] = $text;
365 //$data['header'] = $emailAuto['header'];
366 $data['header'] = self::replaceByVars($emailAuto['header'], $vars);
367 $data['button'] = $emailAuto['button'];
368
369
370 self::prepareUrlAutoMail($type, $vars);
371
372 $autoMailTmpl = $type . '_' . Common::getOption('set', 'template_options');
373 $optionTmplName = Common::getOption('name', 'template_options');
374 if (isset(self::$urlAutoMailTemplate[$optionTmplName])
375 && isset(self::$urlAutoMailTemplate[$optionTmplName][$type])) {
376 $urlAutoMail = self::$urlAutoMailTemplate[$optionTmplName][$type];
377 } else {
378 $urlAutoMail = isset(self::$urlAutoMail[$autoMailTmpl]) ? self::$urlAutoMail[$autoMailTmpl] : self::$urlAutoMail[$type];
379 }
380
381 if($type == 'forget' && $sitePart == 'administration') {
382 $urlAutoMail = 'index.php';
383 }
384
385 if(in_array($type, self::$urlAutoMailByCurrentLocation)) {
386 $data['url'] = Common::urlSite() . self::replaceByVars($urlAutoMail, $vars);
387 } else {
388 $data['url'] = Common::urlSiteSubfolders() . self::replaceByVars($urlAutoMail, $vars);
389 }
390
391 if(!in_array($type, self::$urlAutoMailAutologinOff)) {
392 $receiverBasicInfo = User::getInfoBasicByEmail($email, false, $dbIndex);
393 if($receiverBasicInfo) {
394 $data['url'] = User::urlAddAutologin($data['url'], $receiverBasicInfo);
395 }
396 }
397
398 //$urlTmpl = str_replace($g['path']['url_main'], '', $g['tmpl']['url_tmpl_administration']);
399 //$data['url_admin'] = Common::urlSiteSubfolders() . $urlTmpl;
400 $data['url_logo_auto_mail'] = Common::getUrlLogoAutoMail();
401 $data['thanks'] = self::replaceByVars($emailAuto['thanks'], array('title' => Common::getOption('title', 'main')));
402 $text = self::replaceByVars($emailAuto['template'], $data);
403 }
404 if (!$isGetData) {
405 send_mail($email, Common::getOption('info_mail', 'main'), $subject, $text);
406 $sent = true;
407 }
408 }
409
410 return $isGetData ? $data : $sent;
411 }
412
413 static function isEnabledAutoMail($type){
414 global $g;
415
416 $enabled = true;
417 if (isset($g['automail'][$type])) {
418 $enabled = false;
419 if ($g['automail'][$type] == 'Y') {
420 $enabled = true;
421 }
422 }
423 return $enabled;
424 }
425
426
427 static function dirCopy($src, $dst, $chmod = 0777) {
428 $dir = opendir($src);
429 @mkdir($dst);
430 @chmod($dst, $chmod);
431 while(false !== ( $file = readdir($dir)) ) {
432 if (( $file != '.' ) && ( $file != '..' )) {
433 if ( is_dir($src . '/' . $file) ) {
434 self::dirCopy($src . '/' . $file,$dst . '/' . $file);
435 } else {
436 $filePath = $dst . '/' . $file;
437 copy($src . '/' . $file, $filePath);
438 @chmod($filePath, $chmod);
439 }
440 }
441 }
442 closedir($dir);
443 }
444
445 static function dirRemove($dir) {
446 if(file_exists($dir)) {
447 $files = array_diff(scandir($dir), array('.', '..'));
448 foreach ($files as $file) {
449 $path = $dir . DIRECTORY_SEPARATOR . $file;
450 (is_dir($path)) ? self::dirRemove($path) : unlink($path);
451 }
452 return rmdir($dir);
453 }
454 }
455
456 static function getHomePage()
457 {
458 return Menu::getUrlHomePage();
459 }
460
461 static function toHomePage()
462 {
463 $link = get_session('ref_login_link');
464 $link_mobile = get_session('ref_login_link_mobile');
465 $link_admin = get_session('ref_login_link_admin');
466 $link_partner = get_session('ref_login_link_partner');
467 $ref_link = self::getHomePage();
468
469 if (Common::getOption('site_part', 'main') == 'mobile') {
470 if ($link_mobile != '') {
471 delses('ref_login_link_mobile');
472 $ref_link = $link_mobile;
473 }
474 } elseif (Common::getOption('site_part', 'main') == 'administration') {
475 if ($link_admin != '') {
476 delses('ref_login_link_admin');
477 $ref_link = $link_admin;
478 }
479 } elseif (Common::getOption('site_part', 'main') == 'partner') {
480 if ($link_partner != '') {
481 delses('ref_login_link_partner');
482 $ref_link = $link_partner;
483 }
484 } else {
485 if ($link != '') {
486 delses('ref_login_link');
487 $ref_link = $link;
488 }
489 }
490
491 if (mb_strpos($ref_link, '_ajax.php') != false || strpos($ref_link, 'ajax.php') || strpos($ref_link, '&ajax=1') || strpos($ref_link, '?ajax=1')) {
492 $ref_link = self::getHomePage();
493 }
494
495 redirect($ref_link);
496 }
497
498 static function getLoginPage()
499 {
500 if (Common::getOption('site_part', 'main') == 'mobile'
501 || Common::getOption('site_part', 'main') == 'administration'
502 || Common::getOption('site_part', 'main') == 'partner') {
503 $page = 'index.php';
504 } else {
505 $page = Common::pageUrl('login');
506 }
507
508 global $g;
509 return $g['to_root'] . $page;
510 }
511
512 static function toLoginPage()
513 {
514 global $p;
515
516 if($p != 'ajax.php' && $p != 'js.php' && $p != 'css.php' && !strpos($p, '_ajax.php') && !get_param('ajax') && $p != 'manifest.php') {
517 $link = get_session('ref_login_link');
518 $link_mobile = get_session('ref_login_link_mobile');
519 $link_admin = get_session('ref_login_link_admin');
520 $link_partner = get_session('ref_login_link_partner');
521
522 if (Common::getOption('site_part', 'main') == 'mobile') {
523 if ($link != '') {
524 delses('ref_login_link');
525 }
526 set_session('ref_login_link_mobile', self::urlPage(true));
527 } elseif (Common::getOption('site_part', 'main') == 'administration') {
528 if ($link_admin != '') {
529 delses('ref_login_link_admin');
530 }
531 set_session('ref_login_link_admin', self::urlPage(true));
532 } elseif (Common::getOption('site_part', 'main') == 'partner') {
533 if ($link_partner != '') {
534 delses('ref_login_link_partner');
535 }
536 set_session('ref_login_link_partner', self::urlPage(true));
537 } else {
538 if ($link_mobile != '') {
539 delses('ref_login_link_mobile');
540 }
541 set_session('ref_login_link', self::urlPage(true));
542 }
543 }
544
545 redirect(self::getLoginPage());
546 }
547
548 static function listMonths($prefix = '')
549 {
550 return array(
551 1 => l($prefix . 'january'),
552 2 => l($prefix . 'february'),
553 3 => l($prefix . 'march'),
554 4 => l($prefix . 'april'),
555 5 => l($prefix . 'may'),
556 6 => l($prefix . 'june'),
557 7 => l($prefix . 'july'),
558 8 => l($prefix . 'august'),
559 9 => l($prefix . 'september'),
560 10 => l($prefix . 'october'),
561 11 => l($prefix . 'november'),
562 12 => l($prefix . 'december'),
563 );
564 }
565
566 static function plListMonths($format = 'F', $isFirstValueEmpty = false)
567 {
568 $list = array();
569 if ($isFirstValueEmpty) {
570 $list[0] = l('please_choose_empty');
571 }
572 for ($i = 1; $i < 13; $i++) {
573 $m = $i;
574 if ($m < 10) {
575 $m = "0{$m}";
576 }
577 $list[$i] = pl_date($format, "2000{$m}01", true, false, true);
578 }
579 return $list;
580 }
581
582 static function listCountries($selected, $firstDefault = false, $list = false, $isFirstValueEmpty = false, $setCountryDefault = true)
583 {
584 $countries = '';
585
586 if ($setCountryDefault && guid() && $selected == '') {
587 $sql = "SELECT `country_id`
588 FROM `geo_country`
589 WHERE hidden = 0
590 ORDER BY `first` DESC, `country_title` ASC LIMIT 1";
591 $selected = DB::result($sql);
592 }
593
594 $where = '`first` != 0 AND hidden = 0';
595
596 $sql = 'SELECT `country_id`, `country_title`
597 FROM `geo_country`
598 WHERE ' . $where . '
599 ORDER BY `first` DESC, `country_title` ASC';
600
601 $countries .= ($list) ? DB::db_options_ul($sql, $selected) : DB::db_options($sql, $selected, 0, false, $isFirstValueEmpty, 'country');
602
603 $where .= ' AND `country_id` = ' . to_sql($selected, 'Number');
604 if (DB::count('geo_country', $where)) {
605 $selected = '';
606 }
607
608 $sql = 'SELECT `country_id`, `country_title`
609 FROM `geo_country`
610 WHERE (hidden = 0 OR country_id = ' . to_sql($selected, 'Number') . ')';
611
612 $countries .= ($list) ? DB::db_options_ul($sql, $selected, 0, true) : DB::db_options($sql, $selected, 0, true, false, 'country');
613
614 return $countries;
615 }
616
617 static function listStates($country, $selected = '', $list = false, $isFirstValueEmpty = false)
618 {
619 $sql = 'SELECT state_id, state_title FROM geo_state
620 WHERE country_id = ' . to_sql($country, 'Number') . '
621 AND (hidden = 0 OR state_id = ' . to_sql($selected, 'Number') . ')';
622 $states = ($list) ? DB::db_options_ul($sql, $selected, 0, true) : DB::db_options($sql, $selected, 0, true, $isFirstValueEmpty);
623 return $states;
624 }
625
626 static function listCities($state, $selected = '', $list = false, $isFirstValueEmpty = false)
627 {
628 $sql = 'SELECT city_id, city_title FROM geo_city
629 WHERE state_id = ' . to_sql($state, 'Number') . '
630 AND (hidden = 0 OR city_id = ' . to_sql($selected, 'Number') . ')';
631 $cities = ($list) ? DB::db_options_ul($sql, $selected, 0, true) : DB::db_options($sql, $selected, 0, true, $isFirstValueEmpty);
632 return $cities;
633 }
634
635 static function setSiteOptions()
636 {
637 global $g;
638 global $p;
639 global $l;
640
641 if (get_param('bg') != ''
642 && ($p != 'send.php' && $p != 'postcard_preview.php')) {
643 $g['options']['website_background_oryx'] = get_param('bg') . '.jpg';
644 $g['options']['background_only_not_logged_oryx'] = 'N';
645 set_session('set_bg', 'Y');
646 }
647 if (get_param('color_scheme') != '') {
648 $g['options']['allow_users_color_scheme'] = 'Y';
649 set_session('set_color', 'Y');
650 }
651 if (get_param('maintenance_off') == 'Y') {
652 set_session('maintenance_off', 'Y');
653 }
654 if (get_param('maintenance_on') == 'Y') {
655 set_session('maintenance_off', 'N');
656 }
657
658 if (get_session('maintenance_off') == 'Y') {
659 $g['options']['maintenance'] = "N";
660 }
661
662
663 $homePageModeParam = 'home_page_mode';
664 $homePageMode = get_param($homePageModeParam, '');
665 if($homePageMode != '') {
666 set_session($homePageModeParam, $homePageMode);
667 set_session('demo_widgets', false);
668 $sql = 'DELETE FROM widgets
669 WHERE user_id = ' . to_sql(get_session('user_id'), 'Number') . '
670 AND session = ' . to_sql(session_id(), 'Text');
671 DB::execute($sql);
672 }
673 $homePageModeSession = get_session($homePageModeParam);
674 if($homePageModeSession != '') {
675 $g['options'][$homePageModeParam] = $homePageModeSession;
676 }
677
678 $mainPageModeParam = 'main_page_mode';
679 $mainPageMode = get_param($mainPageModeParam, '');
680 if($mainPageMode != '') {
681 set_session($mainPageModeParam, $mainPageMode);
682 }
683 $mainPageModeSession = get_session($mainPageModeParam);
684 if($mainPageModeSession != '') {
685 $g['options'][$mainPageModeParam] = $mainPageModeSession;
686 }
687
688 $mainSectionModeParam = 'main_section';
689 $mainSectionMode = get_param($mainSectionModeParam, '');
690 if($mainSectionMode != '') {
691 set_session($mainSectionModeParam, $mainSectionMode);
692 }
693
694 $partner = intval(get_param('p', ''));
695 if ($partner != 0) {
696 set_session('partner', $partner);
697 }
698
699 $webrtcOnOff = get_param('webrtc','');
700 if($webrtcOnOff=='on'){
701 $typeChat = 'webrtc';
702 Config::update('options','type_media_chat',$typeChat,true);
703 } elseif($webrtcOnOff=='off'){
704 $typeChat = 'flash';
705 Config::update('options','type_media_chat',$typeChat,true);
706 }
707
708 $widgetsModeParam = 'widgets';
709 $widgetsMode = get_param($widgetsModeParam, '');
710 if($widgetsMode == 'on') {
711 $sql = 'DELETE FROM widgets
712 WHERE user_id = ' . to_sql(get_session('user_id'), 'Number') . '
713 AND session = ' . to_sql(session_id(), 'Text');
714 DB::execute($sql);
715 set_session('demo_widgets', false);
716 }
717 if($widgetsMode == 'off') {
718 $sql = 'DELETE FROM widgets
719 WHERE user_id = ' . to_sql(get_session('user_id'), 'Number') . '
720 AND session = ' . to_sql(session_id(), 'Text');
721 DB::execute($sql);
722 set_session('demo_widgets', true);
723 }
724
725 // demo widgets
726 // clean all old
727 // disable demo widgets
728 // reset widgets status
729 // home page and social widgets are different things
730
731 $demoPagesDisable = self::paramFromSession('demo_pages_disable');
732 if($demoPagesDisable != '' && $demoPagesDisable != 'off') {
733 $pages = explode(',', $demoPagesDisable);
734 foreach($pages as $page) {
735 if(isset($g['menu'][$page])) {
736 unset($g['menu'][$page]);
737 }
738 }
739 }
740
741 $demoPages = self::paramFromSession('demo_pages');
742 if($demoPages != '' && $demoPages != 'off') {
743 $pages = array_flip(explode(',', $demoPages));
744
745 foreach($g['menu'] as $key => $value) {
746 if(!isset($pages[$key])) {
747 unset($g['menu'][$key]);
748 } else {
749 $g['menu'][$key] = $pages[$key];
750 }
751 }
752 }
753
754 $demoOptionsOff = self::paramFromSession('demo_options_off');
755 if($demoOptionsOff != '' && $demoOptionsOff != 'off') {
756 $optionsOff = explode(',', $demoOptionsOff);
757 foreach($optionsOff as $optionOff) {
758 Common::optionDeactivate($optionOff);
759 }
760 }
761
762 $demoColorScheme = self::getDemoParamValueFromSession('demo_color_scheme');
763
764 $currentTemplateName = $g['tmpl']['tmpl_loaded'];
765
766 if($demoColorScheme && ($currentTemplateName == 'impact' || $currentTemplateName == 'impact_mobile')) {
767 $templateOptions = loadTemplateSettings('main', 'impact');
768 if(isset($templateOptions['color_scheme'][$demoColorScheme])) {
769 foreach($templateOptions['color_scheme'][$demoColorScheme] as $key => $value) {
770 if(is_array($value)) {
771 $value = $value['value'];
772 }
773 $g['options'][$key] = $value;
774 }
775 }
776 }
777
778 if(IS_DEMO) {
779
780 if(isset($_SERVER['QUERY_STRING']) && get_param('demo_site')) {
781 set_session('demo_version', md5($_SERVER['QUERY_STRING']));
782 }
783
784 $demoOptions = self::paramFromSession('demo_options', true);
785 if($demoOptions) {
786 foreach($demoOptions as $demoOptionKey => $demoOptionValue) {
787 $g['options'][$demoOptionKey] = $demoOptionValue;
788 }
789 }
790 }
791
792 $setCityModule = 'set_city_module';
793 $setCityModuleValue = get_param($setCityModule);
794 if($setCityModuleValue == 'on' || $setCityModuleValue == 'off') {
795 set_session($setCityModule, $setCityModuleValue);
796 }
797 /*$setWallModule = 'set_wall_module';
798 $setWallModuleValue = get_param($setWallModule);
799 if($setWallModuleValue == 'on' || $setWallModuleValue == 'off') {
800 set_session($setWallModule, $setWallModuleValue);
801 }*/
802
803 $devColorSchemeModeParam = 'dev_color_scheme_mode';
804 $devColorSchemeMode = get_param($devColorSchemeModeParam, '');
805 if($devColorSchemeMode != '') {
806 set_session($devColorSchemeModeParam, $devColorSchemeMode);
807 }
808 $devColorSchemeModeSession = get_session($devColorSchemeModeParam);
809 if($devColorSchemeModeSession == 'on') {
810 $templateOptions = loadTemplateSettings('main', 'impact');
811 $siteColorScheme = Common::getOption('color_scheme_impact');
812 if(isset($templateOptions['color_scheme'][$siteColorScheme])) {
813 foreach($templateOptions['color_scheme'][$siteColorScheme] as $key => $value) {
814 if(is_array($value)) {
815 $value = $value['value'];
816 }
817 $g['options'][$key] = $value;
818 }
819 }
820 }
821
822 $edgeMainPageTitle = self::paramFromSession('edge_main_page_title');
823 if($edgeMainPageTitle != '' && $edgeMainPageTitle != 'off') {
824 $l['index.php']['are_you_social_enough'] = $edgeMainPageTitle;
825 }
826
827 $edgeMainPageText = self::paramFromSession('edge_main_page_text');
828 if($edgeMainPageText != '' && $edgeMainPageText != 'off') {
829 $l['index.php']['the_social_network_you_were_dreaming_about_all_your_life'] = $edgeMainPageText;
830 }
831
832 $edgeSetHomePage = self::paramFromSession('edge_set_home_page');
833 if($edgeSetHomePage != '' && $edgeSetHomePage != 'off') {
834 $g['edge']['set_home_page'] = $edgeSetHomePage;
835 }
836
837 $edgeColorSchemeVisitorOptions = array(
838 'main_page_image',
839 'main_page_header_background_color',
840 );
841
842 foreach($edgeColorSchemeVisitorOptions as $edgeColorSchemeVisitorOption) {
843 $edgeColorSchemeVisitorOptionValue = self::paramFromSession($edgeColorSchemeVisitorOption);
844 if($edgeColorSchemeVisitorOptionValue != '' && $edgeColorSchemeVisitorOptionValue != 'off') {
845 $g['edge_color_scheme_visitor'][$edgeColorSchemeVisitorOption] = $edgeColorSchemeVisitorOptionValue;
846 }
847 }
848
849 $edgeDisablePages = Common::paramFromSession('edge_disable_pages');
850
851 if(IS_DEMO) {
852 Demo::setSiteOptions();
853 }
854
855 self::paramFromSession('demo_logo');
856 }
857
858 static public function getDemoParamValueFromSession($param)
859 {
860 $paramValue = get_param($param, '');
861 if($paramValue != '') {
862 set_session($param, $paramValue);
863 }
864 $paramValueFromSession = get_session($param);
865
866 return $paramValueFromSession;
867 }
868
869 static function paramFromSession($param, $array = false)
870 {
871 if($array) {
872 $value = get_param_array($param);
873 } else {
874 $value = get_param($param, '');
875 }
876
877 if($value || get_param('demo_init')) {
878 set_session($param, $value);
879 }
880 return get_session($param);
881 }
882
883 static function itemTitleOrBlank($location, $blank = 'Blank')
884 {
885 return ($location == '' || $location == '0') ? l($blank) : l($location);
886 }
887
888 static function newLinesLimit($text, $limit = 2, $endTrim = true)
889 {
890 $text = str_replace("\r\n", "\n", $text);
891 $pattern = '#(\n){' . ($limit + 1) . ',}#';
892 $text = preg_replace($pattern, str_repeat("\n", $limit), $text);
893 // delete from the end of string
894
895 if($endTrim) {
896 #$pattern = '#[\n]$#';
897 #$text = preg_replace($pattern, '', $text);
898 $text = trim($text);
899 }
900
901 return $text;
902 }
903
904 static function parseLinks($text, $target = '_blank', $class = '', $method = 'getHref', $setTarget = false)
905 {
906 if (trim($class)) {
907 self::$classLinks = " class='$class'";
908 }
909
910 if (trim($target)) {
911 self::$targetLinks = " target='$target'";
912 }
913 self::$setTarget = $setTarget;
914 #"/(https?:\/\/|ftp:\/\/)?([\da-z\.-]+\.?[a-z\.]{2,6})[\/\w\#,>)\];'\"!?=\&\.-]*\/?/i";
915 $patterns = array("#(https?|ftp)://(\S+[^\s.,>)\];'\"!?])#i",
916 "#([[:space:]()[{}]|^)(www\.(\S+[^\s.,>)\];'\"!?]))#i");
917
918 foreach ($patterns as $pattern) {
919 $text = preg_replace_callback($pattern, 'Common::' . $method, $text);
920 }
921 return $text;
922 }
923
924 static function getHref($matches)
925 {
926 $domain = explode('/', str_replace('www.', '', $matches[2]));
927 if (self::$setTarget) {
928 $target = self::$targetLinks;
929 } else {
930 $target = ('.' . $domain[0] == domain()) ? '' : self::$targetLinks;
931 }
932 $isHttp = trim($matches[1]);
933 $http = (empty($isHttp)) ? 'http://' : '';
934 $url = trim($matches[0]);
935 $url = str_replace('"', '%22', $url);
936 return ' <a href="'. $http . $url . '"'. $target . self::$classLinks . '>' . $matches[0] . '</a>';
937
938 }
939
940 static function parseLinksSmile($text, $target = '_blank', $class = '', $cutTag = true, $setTarget = false)
941 {
942 self::$prepareLinks = array();
943 self::$iterationLinks = 1;
944 $text = self::parseLinks($text, $target, $class, 'getHrefSmile', $setTarget);
945 if ($cutTag) {
946 $text = self::cutTag($text);
947 }
948 $text = replaceSmile($text);
949 return self::replaceByVars($text, self::$prepareLinks);
950 }
951
952 static function getHrefSmile($matches)
953 {
954 $domain = explode('/', str_replace('www.', '', $matches[2]));
955 if (self::$setTarget) {
956 $target = self::$targetLinks;
957 } else {
958 $target = ('.' . $domain[0] == domain()) ? '' : self::$targetLinks;
959 }
960 $isHttp = trim($matches[1]);
961 $http = (empty($isHttp)) ? 'http://' : '';
962 $url = trim($matches[0]);
963 $url = str_replace('"', '%22', $url);
964 self::$prepareLinks['parse_links_' . self::$iterationLinks] = ' <a href="'. $http . $url . '"'. $target . self::$classLinks . '>' . $matches[0] . '</a>';
965 $result = '{parse_links_' . self::$iterationLinks . '}';
966 self::$iterationLinks++;
967 return $result;
968 }
969
970 static function cutTag($text)
971 {
972 $vids = array('youtube', 'vimeo', 'metacafe', 'site', 'img');
973 foreach ($vids as $type) {
974 $objs = grabs($text, "{{$type}:", '}');
975 foreach ($objs as $obj) {
976 $num = 'parse_links_' . self::$iterationLinks;
977 $tag = "{{$type}:{$obj}}";
978 self::$prepareLinks[$num] = $tag;
979 $text = str_replace($tag, "{{$num}}", $text);
980 self::$iterationLinks++;
981 }
982 }
983 return $text;
984 }
985
986 static function parseLinksTag($text, $tag = 'a', $attr = '<', $method = 'parseLinks', $target = '_blank', $class = '', $setTarget = false)
987 {
988 preg_match_all('{'.$attr.$tag.'[^>]*>(.*?)'.$attr.'/'.$tag.'>}', $text, $matches, PREG_PATTERN_ORDER);
989 $i = 1;
990 $prepare = array();
991 foreach ($matches[0] as $tag) {
992 $prepare['parse_tag_' . $i] = $tag;
993 $text = str_replace($tag, '{parse_tag_' . $i . '}',$text);
994 $i++;
995 }
996 $text = self::$method($text, $target, $class, 'getHref', $setTarget);
997 return self::replaceByVars($text, $prepare);
998 }
999
1000
1001
1002 static function getImgTagToDb($matches)
1003 {
1004 $exts = array('.png', '.jpg', '.jpeg', '.gif');
1005 $replase = $matches[0];
1006
1007 foreach ($exts as $ext) {
1008 $startExts = stripos($matches[0], $ext);
1009 if ($startExts !== false) {
1010 $endExts = $startExts + mb_strlen($ext, 'UTF-8');
1011 if (mb_substr($matches[0], $endExts, 1, 'UTF-8') == '?'
1012 || mb_strlen($matches[0], 'UTF-8') == $endExts){
1013 $image = OutsideImages::do_upload_image($matches[0]);
1014 if ($image) {
1015 $replase = '{img:' . $image['image_id'] . '}';
1016 }
1017 }
1018 }
1019 }
1020
1021 return $replase;
1022 }
1023
1024 static function linksToVideo($text)
1025 {
1026 // youtube
1027 // http or www or youtube.com start of link
1028 $pattern = "#((https?)://(www.)?youtube\.com/\S+[^\s.,>)\];'\"!?])#i";
1029 $template = "[ID=$1]";
1030 #$pattern = "#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#";
1031 #preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $link, $matches);
1032 $text = preg_replace($pattern, $template, $text);
1033
1034 // vimeo
1035
1036
1037 return $text;
1038 }
1039
1040 static function textToMedia($text, $target = '_blank', $class = '', $width = null)
1041 {
1042 require_once(dirname(__FILE__) . '/video_hosts.php');
1043 $text = VideoHosts::textUrlToVideoCode($text);
1044 $text = self::linksToVideo($text);
1045 $text = self::parseLinksSmile($text, $target, $class);
1046 $text = VideoHosts::filterFromDb($text, '', '', $width);
1047 $text = nl2br($text);
1048
1049 return $text;
1050 }
1051
1052 static function urlPage($domain = false)
1053 {
1054 $url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
1055 if($domain) {
1056 $protocol = self::urlProtocol();
1057 $domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
1058 $url = "{$protocol}://{$domain}{$url}";
1059 }
1060 return $url;
1061 }
1062
1063 static function urlSite()
1064 {
1065 $urlToPage = isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : '';
1066 $urlToPage = isset($_SERVER['ORIG_PATH_INFO']) ? $_SERVER['ORIG_PATH_INFO'] : $urlToPage;
1067 $urlToPageParts = explode('/', $urlToPage);
1068 array_pop($urlToPageParts);
1069 $urlToPage = implode('/', $urlToPageParts);
1070
1071 $protocol = self::urlProtocol();
1072 $domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
1073 $url = "{$protocol}://{$domain}{$urlToPage}/";
1074 return $url;
1075 }
1076
1077 static function urlSiteSubfolders()
1078 {
1079 global $g;
1080
1081 $urlSubfolders = '';
1082 $baseDir = str_replace(array('\\', '//'), '/', $g['path']['dir_main']);
1083
1084 if(isset($_SERVER['CONTEXT_PREFIX']) && $_SERVER['CONTEXT_PREFIX'] !== '' && isset($_SERVER['CONTEXT_DOCUMENT_ROOT']) && strpos($_SERVER['REQUEST_URI'], $_SERVER['CONTEXT_PREFIX']) !== false) {
1085 $urlSubfolders = str_replace(rtrim($_SERVER['CONTEXT_DOCUMENT_ROOT'], '/'), rtrim($_SERVER['CONTEXT_PREFIX'], '/'), $baseDir);
1086 } else {
1087
1088 $serverDocumentRoot = $_SERVER['DOCUMENT_ROOT'];
1089
1090 if(strpos($serverDocumentRoot, '\\') !== false) {
1091 $serverDocumentRoot = str_replace('\\', '/', $serverDocumentRoot);
1092 }
1093
1094 // $serverDocumentRoot - /home/site/www
1095 // $baseDir - /usr/home/site/www/
1096 // use only left side of path
1097 if(strpos($baseDir, $serverDocumentRoot) > 0) {
1098 $baseDirParts = explode($serverDocumentRoot, $baseDir);
1099 if(count($baseDirParts > 1)) {
1100 unset($baseDirParts[0]);
1101 $baseDir = $serverDocumentRoot . implode('', $baseDirParts);
1102 }
1103 }
1104
1105 $urlSubfolders = str_replace(rtrim($serverDocumentRoot, '/'), '', $baseDir);
1106
1107 $serverDocumentRootParts = explode('/', $serverDocumentRoot);
1108 $baseDirParts = explode('/', $baseDir);
1109
1110 $commonFolders = array_intersect($serverDocumentRootParts, $baseDirParts);
1111
1112 if($commonFolders) {
1113 $commonPath = implode('/', $commonFolders);
1114
1115 if(strlen($serverDocumentRoot) === strpos($serverDocumentRoot, $commonPath) + strlen($commonPath) && strpos($baseDir, $commonPath) === 0) {
1116 $urlSubfolders = str_replace(rtrim($commonPath, '/'), '', $baseDir);
1117 }
1118 }
1119
1120 if($urlSubfolders != '/' && isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI']) {
1121 $requestUriParts = explode('/', $_SERVER['REQUEST_URI']);
1122
1123 $countRequestUriParts = count($requestUriParts);
1124
1125 if($countRequestUriParts > 1) {
1126
1127 $urlSubfoldersParts = explode('/', $urlSubfolders);
1128 $isUrlSubfoldersChanged = false;
1129 $i = 0;
1130 while($i < $countRequestUriParts) {
1131 if(isset($urlSubfoldersParts[$i])) {
1132 if($urlSubfoldersParts[$i] != '') {
1133 if($requestUriParts[$i] != $urlSubfoldersParts[$i]) {
1134 $urlSubfoldersParts[$i] = $requestUriParts[$i];
1135 $isUrlSubfoldersChanged = true;
1136 }
1137 }
1138 } else {
1139 break;
1140 }
1141 $i++;
1142 }
1143
1144 if($isUrlSubfoldersChanged) {
1145 $urlSubfolders = implode('/', $urlSubfoldersParts);
1146 }
1147 }
1148
1149 }
1150
1151 }
1152
1153 // Fix for incorrect path detection
1154 if(strpos($_SERVER['REQUEST_URI'], $urlSubfolders) === false) {
1155 $urlSubfolders = '';
1156 }
1157
1158 $protocol = self::urlProtocol();
1159 $domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
1160 $url = rtrim("{$protocol}://{$domain}{$urlSubfolders}", '/') . '/';
1161 return $url;
1162 }
1163
1164 static function urlProtocol()
1165 {
1166 $protocol = ( (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
1167 || (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443)
1168 || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
1169 || (isset($_SERVER['HTTP_SSL']) && $_SERVER['HTTP_SSL'] == 'TRUE')
1170 ) ? 'https' : 'http';
1171 return $protocol;
1172 }
1173
1174 static function page()
1175 {
1176 global $p;
1177
1178 return $p;
1179 }
1180
1181 static function pageBaseName()
1182 {
1183 global $p;
1184
1185 $pageParts = explode('.', $p);
1186 array_pop($pageParts);
1187 $page = implode('.', $pageParts);
1188
1189 return $page;
1190 }
1191
1192 static function isOptionActive($option, $key = 'options')
1193 {
1194 global $g;
1195
1196 $active = false;
1197 if(isset($g[$key][$option]) && $g[$key][$option] == 'Y') {
1198 $active = true;
1199 }
1200
1201 return $active;
1202 }
1203
1204 static function isOptionActiveTemplate($option)
1205 {
1206 return self::isOptionActive($option, 'template_options');
1207 }
1208
1209 static function optionDeactivate($option)
1210 {
1211 global $g;
1212 $g['options'][$option] = 'N';
1213 }
1214
1215 static function getOption($option, $key = 'options')
1216 {
1217 global $g;
1218
1219 return isset($g[$key][$option]) ? $g[$key][$option] : null;
1220 }
1221
1222 static function getOptionTemplate($option)
1223 {
1224 return self::getOption($option, 'template_options');
1225 }
1226
1227 static function getOptionInt($option, $key = 'options')
1228 {
1229 return intval(self::getOption($option, $key));
1230 }
1231
1232 static function getOptionTemplateInt($option)
1233 {
1234 return intval(self::getOption($option, 'template_options'));
1235 }
1236
1237 static function setOptionRuntime($value, $option, $key = 'options')
1238 {
1239 global $g;
1240 $g[$key][$option] = $value;
1241 }
1242
1243 static function tmplPath($type, $path)
1244 {
1245 if($type == 'mobile') {
1246 $path = str_replace('/_frameworks/main', '/_frameworks/mobile', $path);
1247 }
1248
1249 return $path;
1250 }
1251
1252 static function langPath($type, $path)
1253 {
1254 if($type == 'mobile') {
1255
1256 }
1257
1258 return $path;
1259 }
1260
1261 static function sanitizeFilename($name)
1262 {
1263 return basename($name);
1264 }
1265
1266 static function mobileRedirect()
1267 {
1268 global $g;
1269 if(isset($g['mobile_redirect_off'])) {
1270 return;
1271 }
1272 if(Common::isOptionActive('frameworks_version') && get_cookie('frameworks_version') == '1') {
1273 return;
1274 }
1275 if(self::isMobile()) {
1276 return;
1277 }
1278 $mobile = countFrameworks('mobile');
1279 if(!$mobile) {
1280 return;
1281 }
1282 global $p;
1283 if($p == 'confirm_email.php' || $p == 'invite_confirm.php' || $p == 'before.php' || $p == 'after.php') {
1284 return;
1285 }
1286 if(!self::isOptionActive('mobile_redirect') and (!self::isOptionActive('mobile_site_on_tablet'))) {
1287 return;
1288 }
1289 if (self::isMobile(false)){
1290 if(IS_DEMO && get_param('demo_redirect')) {
1291 if(get_param('demo_redirect') == '_server/city_js/index.php') {
1292 $_GET['demo_redirect'] = urlencode('_server/city_js/index.php?view=mobile');
1293 }
1294 return;
1295 }
1296
1297 $optionTemplateSet = Common::getOption('set', 'template_options');
1298 $optionTemplateName = Common::getOption('name', 'template_options');
1299 $url = self::urlSite() . MOBILE_VERSION_DIR . '/';
1300
1301 $pagesAllowed = array(
1302 'search_results.php',
1303 'mutual_attractions.php',
1304 'my_friends.php'
1305 );
1306
1307 $urlRedirect = '';
1308 if ($optionTemplateSet == 'urban') {
1309 /* Messages template urban */
1310 //Sent to the desktop Urban http://l/r/search_results.php?display=profile&uid=451&show=&email_auth_key=12_1
1311 $uid = get_param('uid');
1312 $show = get_param('show');
1313 $nameSeoParams = get_param('name_seo');
1314 $display = get_param('display');
1315
1316 if ($uid && $show == 'messages') {
1317 $urlRedirect = '/messages.php?display=one_chat&user_id=' . $uid;
1318 }
1319
1320 //http://l/trunk/profile_view.php?show=gallery&photo_id=413859&email_auth_key=451_1
1321 $pid = get_param('photo_id');
1322 if($pid && $show == 'gallery'){
1323 $urlRedirect = '/profile_view.php?show=albums&photo_id=' . $pid;
1324 }
1325 /* Messages template urban */
1326
1327 $page = get_param('page');
1328 if ($p == 'info.php' && ($page == 'term_cond' || $page == 'priv_policy')) {
1329 $alias = 'terms';
1330 if ($page == 'priv_policy') {
1331 $alias = 'privacy_policy';
1332 }
1333 $urlRedirect = '/' . Common::pageUrl($alias);
1334 }
1335
1336 //http://l/r/york_hunt?email_auth_key=12_1
1337 if ($optionTemplateName != 'edge' && $p == 'search_results.php'
1338 && $display == 'profile'
1339 && ($uid || $nameSeoParams)) {
1340 if ($nameSeoParams) {
1341 $uid = User::getUidFromNameSeo($nameSeoParams);
1342 }
1343 if ($uid) {
1344 $urlRedirect = '/profile_view.php?user_id=' . $uid;
1345 }
1346 }
1347
1348 if ($urlRedirect) {
1349 redirect(self::urlSiteSubfolders() . MOBILE_VERSION_DIR . $urlRedirect);
1350 }
1351
1352 $pagesAllowed[] = 'messages.php';//mobile urban - mobile impact
1353 }
1354 if (!in_array($p, $pagesAllowed)) {
1355 $urlRedirect = $url . 'index.php';
1356 $place = get_param('place');
1357 if ($place && mb_strpos($url, '_server/city_js', 0, 'UTF-8') !== false ) {
1358 if(Common::isOptionActive('seo_friendly_urls')) {
1359 $urlRedirect = self::urlSiteSubfolders() . MOBILE_VERSION_DIR . '/3d' . '/' . $place;
1360 } else {
1361 $urlRedirect = self::urlSiteSubfolders() . '_server/city_js/index.php?view=mobile&place=' .$place ;
1362 }
1363 }
1364
1365 if(IS_DEMO) {
1366 // redirect to compatible mobile template
1367 $mobileTemplatesCompatibility = array(
1368 'new_age' => 'black',
1369 'mixer' => 'black',
1370 'oryx' => 'white',
1371 'urban' => 'urban_mobile',
1372 'impact' => 'impact_mobile',
1373 );
1374
1375 $tmplLoaded = Common::getOptionTemplate('name');
1376
1377 $mobileTemplateCompatible = isset($mobileTemplatesCompatibility[$tmplLoaded]) ? $mobileTemplatesCompatibility[$tmplLoaded] : false;
1378
1379 if($mobileTemplateCompatible) {
1380 $delimiter = (strpos($urlRedirect, '?') !== false) ? '&' : '?';
1381 $urlRedirect .= $delimiter . 'set_template_mobile=' . $mobileTemplateCompatible;
1382 }
1383 }
1384
1385 redirect($urlRedirect);
1386 }
1387 $mobileRedirectUrl = array(
1388 'search_results.php_profile' => 'profile_view.php?user_id={uid}',//profile_visitors
1389 );
1390 $display = get_param('display');
1391 $type = "{$p}_{$display}";
1392 if (isset($mobileRedirectUrl[$type])) {
1393 $uid = get_param('uid');
1394 $vars = array('uid' => $uid);
1395 $url .= Common::replaceByVars($mobileRedirectUrl[$type], $vars);
1396 } else {
1397 $params = get_params_string();
1398 if ($params) {
1399 $params = del_param("ref", $params);
1400 $params = '?' . $params;
1401 }
1402 $url .= $p . $params;
1403 }
1404
1405 redirect($url);
1406 }
1407 }
1408
1409 static function getCacheHeadersUserAgent()
1410 {
1411 $userAgent = null;
1412 foreach(self::$uaHttpHeaders as $altHeader){
1413 if (isset($_SERVER[$altHeader])){
1414 $userAgent .= $_SERVER[$altHeader] . " ";
1415 }
1416 }
1417
1418 $userAgent = (!empty($userAgent) ? trim($userAgent) : null);
1419 return md5($userAgent);
1420 }
1421
1422 static function isAppIos()
1423 {
1424 $isIos = get_session('is_ios', null);
1425 //$isIos = true;
1426 if ($isIos === null) {
1427 $isIos = isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'IOSWebview');
1428 set_session('is_ios', $isIos);
1429 }
1430 return $isIos;
1431 }
1432
1433 static function isIosDevice()
1434 {
1435 $isIosDevice = get_session('is_ios_device', null);
1436 if ($isIosDevice === null) {
1437 $detect = new mobile_detect;
1438 $isIosDevice = $detect->isiOS();
1439 set_session('is_ios_device', $isIosDevice);
1440 }
1441 return $isIosDevice;
1442 }
1443
1444 static function isSafari()
1445 {
1446 $isSafari = get_session('is_safari', null);
1447 if ($isSafari === null) {
1448 $detect = new mobile_detect;
1449 $isSafari = $detect->isSafari();
1450 set_session('is_safari', $isSafari);
1451 }
1452 return $isSafari;
1453 }
1454
1455
1456 static function isAppAndroid()
1457 {
1458 $sessionName = 'is_app_android';
1459 $isApp = get_session($sessionName, null);
1460 if ($isApp === null) {
1461 $isApp = isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'AppWebview');
1462 set_session($sessionName, $isApp);
1463 }
1464 return $isApp;
1465 }
1466
1467 static function isApp()
1468 {
1469 return self::isAppIos() || self::isAppAndroid();
1470 }
1471
1472 static function isInAppPurchaseEnabled()
1473 {
1474 $isInAppPurchaseEnabled = true;
1475 if (Common::isApp()) {
1476 $isInAppPurchaseEnabled = Common::isOptionActive('in_app_purchase_enabled');
1477 }
1478 //return Common::isOptionActive('in_app_purchase_enabled');
1479 return $isInAppPurchaseEnabled;
1480 }
1481
1482 static function getMobileOs()
1483 {
1484 $os = get_session('mobile_os', null);
1485 if ($os === null) {
1486 $os = '';
1487 $detect = new mobile_detect;
1488 if ($detect->isAndroidOS()) {
1489 $os = 'android';
1490 } elseif ($detect->isiOS()) {
1491 $os = 'ios';
1492 }
1493 set_session('mobile_os', $os);
1494 }
1495 return $os;
1496 }
1497
1498 static public function getIosVersion()
1499 {
1500 $version = '';
1501
1502 if(isset($_SERVER['HTTP_USER_AGENT'])) {
1503 $regex = '/OS (.*) like/Uis';
1504 if(preg_match($regex, $_SERVER['HTTP_USER_AGENT'], $matches)) {
1505 $version = str_replace('_', '.', $matches[1]);
1506 }
1507 }
1508
1509 return $version;
1510 }
1511
1512 static function isMobile($version = true, $isMobileRedirect = null, $isMobileSiteOnTablet = null)
1513 {
1514 global $g;
1515 if ($version){
1516 return isset($g['mobile']);
1517 } else {
1518 $result = '';
1519 $browserVersionCache = get_session('browser_version_cache');
1520 $isMobileNoTablet = get_session('is_mobile_no_tablet_browser', null);
1521 $isTablet = get_session('is_tablet_browser', null);
1522 if ($isMobileRedirect === null) {
1523 $isMobileRedirect = Common::isOptionActive('mobile_redirect');
1524 }
1525 if ($isMobileSiteOnTablet === null) {
1526 $isMobileSiteOnTablet = Common::isOptionActive('mobile_site_on_tablet');
1527 }
1528 if (($isTablet !== null or $isMobileNoTablet !== null) && $browserVersionCache == self::getCacheHeadersUserAgent())
1529 {
1530 if ($isMobileRedirect){
1531 $result = $isMobileNoTablet;
1532 }
1533 if ($isMobileSiteOnTablet){
1534 if (!$result){
1535 $result = $isTablet;
1536 }
1537 }
1538 } else {
1539 $detect = new mobile_detect;
1540 $isTablet = $detect->isTablet();
1541 $isMobileNoTablet = $detect->isMobileNoTablet();
1542 if (($isMobileSiteOnTablet && $isTablet) or ($isMobileRedirect && $isMobileNoTablet)){
1543 $result = true;
1544 } else {
1545 $result = false;
1546 }
1547 }
1548 $count = countFrameworks('main');
1549 if ($count) {
1550 return $result;
1551 } else {
1552 return true;
1553 }
1554 }
1555
1556 }
1557
1558 static function dirFiles($dir)
1559 {
1560 $files = false;
1561
1562 if (is_dir($dir)) {
1563 if ($dh = opendir($dir)) {
1564 $files = array();
1565 while (($file = readdir($dh)) !== false) {
1566 if (is_file($dir . $file) and $file != "." and $file != "..") {
1567 $files[] = $file;
1568 }
1569 }
1570 closedir($dh);
1571 }
1572 }
1573
1574 return $files;
1575 }
1576
1577 static function dirDirs($dir)
1578 {
1579 $files = false;
1580
1581 if(substr($dir, -1) != DIRECTORY_SEPARATOR) {
1582 $dir .= DIRECTORY_SEPARATOR;
1583 }
1584
1585 if (is_dir($dir)) {
1586 if ($dh = opendir($dir)) {
1587 $files = array();
1588 while (($file = readdir($dh)) !== false) {
1589 if ($file != "." and $file != ".." and is_dir($dir . $file)) {
1590 $files[] = $file;
1591 }
1592 }
1593 closedir($dh);
1594 }
1595 }
1596
1597 return $files;
1598 }
1599
1600 static function parsePagesList(&$html, $block, $count, $start = 0, $limit = 10, $pagesLimit = 5, $pageUrlDefault = '')
1601 {
1602 $eu = $start;
1603 $this_page = $eu + $limit;
1604 $back = $eu - $limit;
1605 $next = $eu + $limit;
1606
1607 $nextCount = $next;
1608 if($nextCount > $count) {
1609 $nextCount = $count;
1610 }
1611
1612 $html->setvar('this_count', $eu + 1);
1613 $html->setvar('next_count', $nextCount);
1614 $html->setvar('all_count', $count);
1615
1616 $pageUrlDelimiter = '';
1617 $isPagerSeo = $html->varExists('pager_url_seo');
1618 if ($isPagerSeo) {
1619 $pageUrlDelimiter = self::getPagesListDelimiter($pageUrlDefault, 'offset');
1620 $html->setvar('pager_url_seo', $pageUrlDefault);
1621 }
1622
1623 if ($count / $limit > $pagesLimit) {
1624 $tostart = $eu;
1625 $tonume = (1 + round($eu / $limit)) * $limit;
1626 } else {
1627 $tostart = 0;
1628 $tonume = $count;
1629 }
1630
1631 if ($tostart > 0) {
1632 $html->setvar('toleft', $tostart - $limit);
1633 $html->parse($block . '_left_2', true);
1634 }
1635 $n = $tostart / $limit + 1;
1636
1637 $n_pages = ceil($count / $limit);
1638 $page = max(1, min($n_pages, round($eu / $limit)));
1639 $links = pager_get_pages_links($n_pages, $page, $pagesLimit);
1640 foreach($links as $link) {
1641 $i = ($link - 1) * $limit;
1642 $n = $link;
1643 if ($i == $eu) {
1644 $html->setvar('l', $n);
1645 $html->setblockvar($block . '_page', '');
1646 $html->parse($block . '_page_1', false);
1647 $html->parse($block . '_pages_1', true);
1648 } else {
1649 if ($isPagerSeo) {
1650 $html->setvar('page_i', self::getPagesListParam($i, $pageUrlDelimiter));
1651 }
1652 $html->setvar('i', $i);
1653 $html->setvar('l', $n);
1654 $html->parse($block . '_page', false);
1655 $html->setblockvar($block . '_page_1', '');
1656 $html->parse($block . '_pages_1', true);
1657 }
1658 }
1659
1660 /*for ($i = $tostart; $i < $tonume; $i = $i + $limit) {
1661 if ($i <> $eu) {
1662 $html->setvar('i', $i);
1663 $html->setvar('l', $n);
1664 $html->parse($block . '_page', false);
1665 $html->setblockvar($block . '_page_1', '');
1666 $html->parse($block . '_pages_1', true);
1667 } else {
1668 $html->setvar('l', $n);
1669 $html->setblockvar($block . '_page', '');
1670 $html->parse($block . '_page_1', false);
1671 $html->parse($block . '_pages_1', true);
1672 }
1673 $n = $n + 1;
1674 }*/
1675 if ($count > $tonume) {
1676 $html->setvar('toright', $tonume);
1677 $html->parse($block . '_right_2', true);
1678 }
1679 if ($back >= 0) {
1680 if ($isPagerSeo) {
1681 $html->setvar('page_back', self::getPagesListParam($back, $pageUrlDelimiter));
1682 }
1683 $html->setvar('back', $back);
1684 $html->parse($block . '_prev', true);
1685 } else {
1686 $html->parse($block . '_prev_disabled', true);
1687 }
1688 if ($back >= 0 && $this_page < $count) {
1689 $html->parse($block . '_separator', true);
1690 }
1691 if ($this_page < $count) {
1692 if ($isPagerSeo) {
1693 $html->setvar('page_next', self::getPagesListParam($next, $pageUrlDelimiter));
1694 }
1695 $html->setvar('next', $next);
1696 $html->parse($block . '_next', true);
1697 } else {
1698 $html->parse($block . '_next_disabled', true);
1699 }
1700 if($count > $limit) {
1701 $html->parse($block . '_pages', true);
1702 }
1703 }
1704
1705 static function getPagesListParam($page, $delimiter = '')
1706 {
1707 if ($page > 1) {
1708 return $delimiter . $page;
1709 }
1710 return '';
1711 }
1712
1713 static function getPagesListDelimiter($pageUrl, $pageUrlParam = 'page')
1714 {
1715 if (Common::isOptionActive('seo_friendly_urls')) {
1716 $pageUrlDelimiter = '/';
1717 } else {
1718 $pageUrlDelimiter = '&';
1719 if (mb_strpos($pageUrl, '?', 0, 'UTF-8') === false) {
1720 $pageUrlDelimiter = '?';
1721 }
1722 $pageUrlDelimiter .= "{$pageUrlParam}=";
1723 }
1724
1725 return $pageUrlDelimiter;
1726
1727 }
1728
1729 static function parsePagesListUrban(&$html, $page, $n_results, $n_results_per_page, $n_links = 5, $pageUrlDefault = '', $pageUrlParam = 'page')
1730 {
1731 global $p;
1732
1733 if ($html->varExists('pager_url')) {
1734 $pagerUrlDelimiter = '?';
1735 if (self::$pagerUrl) {
1736 $pageUrl = self::$pagerUrl;
1737 if (mb_strpos($pageUrl, '?', 0, 'UTF-8') !== false) {
1738 $pagerUrlDelimiter = '&';
1739 }
1740 } else {
1741 $pageUrl = substr($p, 0, -4);
1742 $pageUrl = Common::pageUrl($pageUrl);
1743 }
1744 $html->setvar('pager_url_delimiter', $pagerUrlDelimiter);
1745 $html->setvar('pager_url', $pageUrl);
1746
1747 }
1748
1749 $pageUrlDelimiter = '';
1750 $isPagerSeo = $html->varExists('pager_url_seo');
1751 if ($isPagerSeo) {
1752 $pageUrlDelimiter = self::getPagesListDelimiter($pageUrlDefault, $pageUrlParam);
1753 $html->setvar('pager_url_seo', $pageUrlDefault);
1754 }
1755
1756 $page = intval($page);
1757 if($page < 1) {
1758 $page = 1;
1759 }
1760 $n_pages = ceil($n_results / $n_results_per_page);
1761 $page = max(1, min($n_pages, $page));
1762
1763 if($n_pages > 1) {
1764 if($page > 1) {
1765 if ($isPagerSeo) {
1766 $html->setvar('page_n_seo', self::getPagesListParam($page - 1, $pageUrlDelimiter));
1767 }
1768 $html->setvar('offset', ($page - 1) * $n_results_per_page + 1 - $n_results_per_page);
1769 $html->setvar('page_n', $page-1);
1770 $html->parse('pager_prev');
1771 } else {
1772 $html->parse('pager_prev_disabled');
1773 }
1774
1775 $links = pager_get_pages_links($n_pages, $page, $n_links);
1776 $total = count($links);
1777 $i = 0;
1778 $j = 0;
1779 $offsetNext = 0;
1780 foreach($links as $link) {
1781 $i++;
1782 if ($isPagerSeo) {
1783 $html->setvar('page_n_seo', self::getPagesListParam($link, $pageUrlDelimiter));
1784 }
1785 $html->setvar('page_n', $link);
1786 $offset = ($link - 1) * $n_results_per_page + 1;
1787 $html->setvar('offset', $offset);
1788 if($page == $link) {
1789 $class = 'sel_c';
1790 if ($i == 1) {
1791 $class = 'sel_f';
1792 } else if ($i == $total) {
1793 $class = 'sel_l';
1794 }
1795 $html->setvar('class_link_active', $class);
1796 $html->parse('pager_link_active', false);
1797 $html->setblockvar('pager_link_not_active', '');
1798 $j = 1;
1799 } else {
1800 if ($j) {
1801 $j = 0;
1802 $offsetNext = $offset;
1803 }
1804 $html->parse('pager_link_not_active', false);
1805 $html->setblockvar('pager_link_active', '');
1806 }
1807 $html->parse('pager_link');
1808 }
1809
1810 if($page < $n_pages) {
1811 if ($isPagerSeo) {
1812 $html->setvar('page_n_seo', self::getPagesListParam($page + 1, $pageUrlDelimiter));
1813 }
1814 $html->setvar('offset', $offsetNext);
1815 $html->setvar('page_n', $page+1);
1816 $html->parse('pager_next');
1817 } else {
1818 $html->parse('pager_next_disabled');
1819 }
1820 $html->parse('pager');
1821 }
1822 }
1823
1824 static function isModuleCityExists()
1825 {
1826 static $exists = 0;
1827 if($exists === 0) {
1828 $exists = file_exists(dirname(__FILE__) . '/../../_server/city_js');
1829 }
1830 return (Common::isMultisite()) ? 0 : $exists;
1831 }
1832
1833 static function isModuleCityActive()
1834 {
1835 return self::isOptionActive('city') && self::isModuleCityExists();
1836 }
1837
1838 static function isValidArray($array)
1839 {
1840 return (is_array($array) && count($array));
1841 }
1842
1843 static function mainPageRedirect()
1844 {
1845 if(Common::isOptionActive('main_page_by_first_menu_item', 'template_options')) {
1846 $url = Menu::getUrlHomePage();
1847 // prevent infinite redirect
1848 if($url != Common::page()) {
1849 redirect($url);
1850 }
1851 }
1852 }
1853
1854 static function demoSetMainSection($menuItems)
1855 {
1856 $mainSectionModeSession = get_session('main_section');
1857 if($mainSectionModeSession) {
1858 if(isset($menuItems[$mainSectionModeSession])) {
1859 $menuItems[$mainSectionModeSession] = '-1';
1860 }
1861 }
1862 return $menuItems;
1863 }
1864
1865 static function authRequiredExit()
1866 {
1867 if(!guid()) {
1868 die('please_login');
1869 }
1870 }
1871
1872 static function tmplName($tmplPath = NULL)
1873 {
1874 if ($tmplPath == NULL) {
1875 $tmplPath = self::getOption('dir_tmpl_main', 'tmpl');
1876 }
1877 $tmplPathParts = explode('/', $tmplPath);
1878 array_pop($tmplPathParts);
1879 return end($tmplPathParts);
1880 }
1881
1882 static function refererFromSite()
1883 {
1884 $url = Common::getHomePage();
1885 $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
1886 if($referer) {
1887 // check if from our domain
1888 $urlSite = self::urlSite();
1889 if(substr($referer, 0, strlen($urlSite)) == $urlSite) {
1890 $url = $referer;
1891 }
1892 }
1893
1894 return $url;
1895 }
1896
1897 static function refererPageFromSite()
1898 {
1899 $refererPage = '';
1900 $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
1901 if($referer) {
1902 $urlSite = self::urlSite();
1903 $lenUrlSite = mb_strlen($urlSite, 'UTF-8');
1904 if(mb_substr($referer, 0, $lenUrlSite, 'UTF-8') == $urlSite) {
1905 $refererPage = mb_substr($referer, $lenUrlSite, mb_strlen($referer, 'UTF-8'), 'UTF-8');
1906 }
1907 }
1908
1909 return $refererPage;
1910 }
1911
1912 static function getIdsByNear($cityInfo, $howNear=0, $onlyWithPublicPhoto = true)
1913 {
1914 $eq=array('=','=','=');
1915 if($howNear>0){
1916 $eq[0]='!=';
1917 }
1918 if($howNear>1){
1919 $eq[1]='!=';
1920 }
1921 if($howNear>2){
1922 $eq[2]='!=';
1923 }
1924
1925 $where = '';
1926 if ($onlyWithPublicPhoto) {
1927 $where = ' AND is_photo_public = "Y" ';
1928 }
1929 $sql='SELECT user_id
1930 FROM `user`
1931 WHERE `is_photo` = "Y"
1932 AND `hide_time` = 0
1933 AND `set_who_view_profile` = "anyone"
1934 AND city_id '.$eq[0] . $cityInfo['city_id'] . '
1935 AND state_id '.$eq[1] . $cityInfo['state_id'] . '
1936 AND country_id '.$eq[2] . $cityInfo['country_id']
1937 . $where . '
1938 ORDER BY user_id DESC
1939 LIMIT 100';
1940
1941 $idsNear=DB::column($sql);
1942
1943 return $idsNear;
1944 }
1945
1946
1947 static function sqlUsersNearCity($cityInfo, $limit = 5, $onlyWithPublicPhoto = true)
1948 {
1949
1950 $sessCacheKeyIds='users_near_ids_'.$cityInfo['city_id'];
1951
1952 $idsCache=get_session($sessCacheKeyIds,array('time'=>0, 'values'=>array()));
1953
1954 $updateCache=false;
1955 if( $idsCache['time']+3600>time()){
1956 $cacheArr=$idsCache['values'];
1957 }else {
1958 $updateCache=true;
1959 }
1960
1961 $idsArr=array();
1962 $countUsersNear=0;
1963 $nNear=0;
1964 while($countUsersNear<$limit && $nNear<=3){
1965 if(!isset($cacheArr[$nNear])){
1966 $cacheArr[$nNear]=self::getIdsByNear($cityInfo, $nNear, $onlyWithPublicPhoto);
1967 $updateCache=true;
1968 }
1969 $idsNear=$cacheArr[$nNear];
1970 shuffle($idsNear);
1971 foreach($idsNear as $v){
1972 $idsArr[]=$v;
1973 $countUsersNear++;
1974 if($countUsersNear>=$limit){
1975 break;
1976 }
1977 }
1978 $nNear++;
1979 }
1980
1981 if($updateCache){
1982 set_session($sessCacheKeyIds,array('time'=>time(),'values'=>$cacheArr));
1983 }
1984
1985 if(count($idsArr)==0){
1986 $idsArr[]=0;
1987 }
1988
1989 $where = '';
1990 if ($onlyWithPublicPhoto) {
1991 $where = ' AND is_photo_public = "Y" ';
1992 }
1993 $sqlHide = User::isHiddenSql('');
1994 $sql = 'SELECT *, IF(city_id = ' . $cityInfo['city_id'] . ', 1, 0) +
1995 IF(state_id = ' . $cityInfo['state_id'] . ', 1, 0) +
1996 IF(country_id = ' . $cityInfo['country_id'] . ', 1, 0) AS near,
1997 DATE_FORMAT(NOW(), "%Y") - DATE_FORMAT(birth, "%Y") - (DATE_FORMAT(NOW(), "00-%m-%d") < DATE_FORMAT(birth, "00-%m-%d")) AS age
1998 FROM `user`
1999 WHERE `is_photo` = "Y"
2000 AND ' . $sqlHide
2001 . $where . '
2002 AND `set_who_view_profile` = "anyone"
2003 AND user_id IN ('.implode(',',$idsArr).')';
2004
2005 return $sql;
2006 }
2007
2008 static function isNotAllowedLanguage($lang)
2009 {
2010 return false;
2011
2012 $optionSet = Common::getOption('set', 'template_options');
2013 $defaultLang = array('chinese','default','dutch','french','german','italian','lithuanian','portuguese','russian','spanish','turkish');
2014 $allowedUrbanLang = array('default', 'russian', 'spanish', 'polish', 'portuguese', 'german', 'french', 'italian', 'turkish', 'polish', 'bulgarian', 'czech', 'hungarian', 'norwegian', 'swedish', 'italian', 'greek', 'persian', 'thai', 'vietnamese');
2015
2016 return IS_DEMO && $optionSet == 'urban' && in_array($lang, $defaultLang) && !in_array($lang, $allowedUrbanLang);
2017 }
2018
2019 static function listLangs($dir = 'main', $hide = true)
2020 {
2021 $dirPath = self::getOption('dir_lang', 'path') . $dir . '/';
2022 $langs = Common::dirDirs($dirPath);
2023 $langsList = false;
2024 if (is_array($langs) && count($langs)) {
2025 $langsList = array();
2026 foreach ($langs as $file) {
2027// if (self::isNotAllowedLanguage($file)) {
2028// continue;
2029// }
2030 if ($hide && Common::getOption($file, 'hide_language_' . $dir)) {
2031 continue;
2032 }
2033 $langKey = $file;
2034 if($file == 'default') {
2035 $langKey = 'language_default';
2036 }
2037 $langsList[$file] = l(ucfirst($langKey));
2038 }
2039 if ($langsList) {
2040 natcasesort($langs);
2041 //$langsList = array_flip($langsList);
2042 $langsList = Common::sortingLangsList($langsList, $dir);
2043 }
2044 }
2045 return $langsList;
2046 }
2047
2048 static function setFirstCurrentLanguage($langs, $part = null) {
2049 if ($part === null) {
2050 $part = 'main';
2051 }
2052 $languageCurrent = Common::getOption($part, 'lang_value');
2053 if(isset($langs[$languageCurrent])) {
2054 $firstLanguage = array($languageCurrent => $langs[$languageCurrent]);
2055 unset($langs[$languageCurrent]);
2056 $langs = array_merge($firstLanguage, $langs);
2057 }
2058 return $langs;
2059 }
2060
2061 static function sortingLangsList($langs, $part = 'main')
2062 {
2063 global $g;
2064 if (!isset($g['lang_order'][$part])) {
2065 $languageCurrent = Common::getOption($part, 'lang_value');
2066 if(isset($langs[$languageCurrent])) {
2067 $g['lang_order'][$part] = serialize(array($languageCurrent => '0'));
2068 } else {
2069 $g['lang_order'][$part] = serialize(array('default' => '0'));
2070 }
2071 }
2072 natcasesort($langs);
2073 $languagesOrder = unserialize($g['lang_order'][$part]);
2074 if(count($languagesOrder) > 0){
2075 $langsTmp = $langs;
2076 $langs = array();
2077 foreach($languagesOrder as $k => $v){
2078 $key = isset($langsTmp[$k]);
2079 if(isset($langsTmp[$k])){
2080 $langs[$k] = $langsTmp[$k];
2081 unset($langsTmp[$k]);
2082 }
2083 }
2084 $langs = array_merge($langs, $langsTmp);
2085 }
2086
2087 return $langs;
2088 }
2089
2090 static function listTmpls($part)
2091 {
2092 $parts = array('main', 'mobile', 'partner', 'administration');
2093 if(!in_array($part, $parts)) {
2094 return;
2095 }
2096
2097 $dir = self::getOption('dir_tmpl', 'path') . $part . '/';
2098 $tmpls = Common::dirDirs($dir);
2099 $tmplsList = false;
2100 if (is_array($tmpls) && count($tmpls)) {
2101 $tmplsList = array();
2102 foreach ($tmpls as $file) {
2103 $tmplsList[$file] = ucfirst(str_replace('_', ' ', $file));
2104 }
2105 natcasesort($tmplsList);
2106 $tmplsList = array_flip($tmplsList);
2107 }
2108
2109 return $tmplsList;
2110 }
2111
2112 static function isLanguageFileExists($language,$part = 'main')
2113 {
2114 $file = self::getOption('dir_lang', 'path') . $part . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . 'language.php';
2115
2116 return file_exists($file);
2117 }
2118
2119 static function devCustomJs(&$html)
2120 {
2121 global $g;
2122 global $p;
2123 global $sitePart;
2124 global $sitePartParam;
2125
2126 if (FOOTER_CUSTOM_JS && $html->varExists('footer_custom_js')) {
2127 $dir = Common::getOption('dir_tmpl', 'path') . $sitePart;
2128
2129 $tmplsAvailable = array(
2130 'main' => array('new_age', 'oryx', 'mixer'),
2131 'mobile' => array('edge_mobile', 'black', 'white', 'urban_mobile', 'impact_mobile'),
2132 );
2133
2134 if($sitePart == 'main') {
2135 $urbanIsActive = true;
2136 $pagesUrban = array(
2137 'index.php',
2138 'join.php',
2139 'forget_password.php',
2140 'profile_view.php',
2141 'search_results.php',
2142 'mail_whos_interest.php',
2143 );
2144
2145 if($p == 'search_results.php') {
2146 if(get_param('display') == 'photo') {
2147 $urbanIsActive = false;
2148 }
2149 }
2150
2151 if($urbanIsActive && in_array($p, $pagesUrban)) {
2152 $tmplsAvailable['main'][] = 'urban';
2153 $tmplsAvailable['main'][] = 'impact';
2154 $tmplsAvailable['main'][] = 'edge';
2155 }
2156
2157 }
2158
2159 if(isset($tmplsAvailable[$sitePart])) {
2160 $tmpls = $tmplsAvailable[$sitePart];
2161 } else {
2162 $tmpls = Common::dirDirs($dir);
2163 }
2164
2165 $tmplsToJs = "var tmplsList = [];\n";
2166 $index = 0;
2167 foreach($tmpls as $tmpl) {
2168 $tmplsToJs .= "tmplsList[$index] = '$tmpl';\n";
2169 $index++;
2170 }
2171
2172 $tmplLoaded = Common::getOption('tmpl_loaded', 'tmpl');
2173 $languageOfUser = get_session('language_of_user');
2174 $languageLoaded = Common::getOption('lang_loaded', 'main');
2175 $analyticsCode = '';
2176 if ($g['main']['site_part'] != 'administration') {
2177 $analyticsCode = '</script>' . Common::getOption('analytics_code', 'main') . '<script>';
2178 }
2179
2180 if(IS_DEMO && $sitePart != 'mobile' && !file_exists(__DIR__ . '/../config/jivosite_off')) {
2181 $analyticsCode .= "
2182 <!-- BEGIN JIVOSITE CODE {literal} -->
2183
2184 function jivo_onOpen() {
2185 jivo_api.setCustomData([
2186 {
2187 content: '$tmplLoaded',
2188 }
2189 ]);
2190 }
2191
2192 (function(){ var widget_id = 'MTgzMTIw';
2193 if(parent.window.frames['iframe_demo']) {
2194 return;
2195 }
2196 var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = '//code2.jivosite.com/script/widget/'+widget_id; var ss = document.getElementsByTagName('script')[0]; ss.parentNode.insertBefore(s, ss);})();
2197 <!-- {/literal} END JIVOSITE CODE -->
2198 ";
2199 }
2200
2201 $guid = guid();
2202 if (DEV === true) {
2203 // disable it on real site
2204 $initDevFunctions = Common::getOption('version', 'db_info') ? 'false' : 'true';
2205
2206 $footerCustomJs = <<<JS
2207$tmplsToJs
2208
2209var tmplCurrent = '$tmplLoaded';
2210
2211if($initDevFunctions) {
2212 initDevFunctions();
2213}
2214
2215var sitePart = '$sitePart';
2216var sitePartParam = '$sitePartParam';
2217var languageOfUser = '$languageOfUser';
2218var siteLanguage = '$languageLoaded';
2219var siteGuid = '$guid'*1;
2220$analyticsCode
2221JS;
2222
2223} else {
2224 $footerCustomJs = <<<JS
2225$analyticsCode
2226JS;
2227}
2228 $footerCustomJsGroup = '';
2229 $groupId = Groups::getParamId();
2230 if ($groupId) {
2231 $footerCustomJsGroup = ", group_vids_list_{$groupId} : '" . self::pageUrl('group_vids_list', $groupId) . "'
2232 , group_photos_list_{$groupId} : '" . self::pageUrl('group_photos_list', $groupId) . "'";
2233 }
2234
2235 $footerCustomJs .= "
2236 var IS_DEMO = " . intval(IS_DEMO) . ";
2237 var urlPageJoin = '" . Common::pageUrl('join') . "';
2238 var urlPageLogin = '" . Common::pageUrl('login') . "';
2239 var urlPageUpgrade = '" . Common::pageUrl('upgrade') . "';
2240 var urlPagesSite = {
2241 index : '" . self::pageUrl('index') . "',
2242 login : '" . self::pageUrl('login') . "',
2243 join : '" . self::pageUrl('join') . "',
2244 home : '" . self::getHomePage() . "',
2245 upgrade : '" . self::pageUrl('upgrade') . "',
2246 search_results : '" . self::pageUrl('search_results') . "',
2247 profile_view : '" . self::pageUrl('profile_view') . "',
2248 messages : '" . self::pageUrl('messages') . "',
2249 refill_credits : '" . self::pageUrl('refill_credits') . "',
2250 my_vids_list : '" . self::pageUrl('user_vids_list', guid()) . "',
2251 my_photos_list : '" . self::pageUrl('user_photos_list', guid()) . "',
2252 photos_list : '" . Common::pageUrl('photos_list') . "',
2253 blogs_add : '" . Common::pageUrl('blogs_add') . "',
2254 profile_settings : '" . Common::pageUrl('profile_settings') . "',
2255 wall : '" . Common::pageUrl('wall') . "'"
2256 . $footerCustomJsGroup ."
2257 };
2258 var cacheVersionParam = '" . (isset($g['site_cache']['cache_version_param']) ? $g['site_cache']['cache_version_param'] : '') . "';
2259
2260 setAjaxPrefilter();
2261 ";
2262
2263 $html->setvar('footer_custom_js', $footerCustomJs);
2264 }
2265 }
2266
2267 static function langParamValue($param = 'lang', $part = 'main')
2268 {
2269 $value = get_param($param, self::getOption($part, 'lang_value'));
2270 return $value;
2271 }
2272
2273 static function swf($src, $params = NULL, $flashVars = NULL)
2274 {
2275 global $g;
2276
2277 $attributes = '';
2278 $paramsFlashVars = '';
2279 $paramsObject = self::swfPrepareParam('movie', $src);
2280 $paramsEmbed = self::swfPrepareParam('src', $src, false);
2281
2282 if (Common::isValidArray($params)) {
2283 foreach ($params as $keys => $param) {
2284 $type = $keys;
2285 foreach ($param as $key => $value) {
2286 if ($type == 'main') {
2287 $paramsObject .= self::swfPrepareParam($key, $value);
2288 $paramsEmbed .= self::swfPrepareParam($key, $value, false);
2289 } else {
2290 $attributes .= self::swfPrepareParam($key, $value, false);
2291 }
2292 }
2293 }
2294 }
2295
2296 if (Common::isValidArray($flashVars)) {
2297
2298 if(isset($flashVars['lang'])) {
2299 $flashVars['lang'] = str_replace('{lang}', Common::getOption('lang_loaded', 'main'), $flashVars['lang']);
2300 }
2301
2302 foreach ($flashVars as $key => $value) {
2303 if ($key == 'dateFormat'){
2304 $paramsFlashVars .= self::swfPrepareParam($key, $g['date_formats']['flashchat_message_datetime'], false, '&', '');
2305 } else {
2306 $paramsFlashVars .= self::swfPrepareParam($key, $value, false, '&', '');
2307 }
2308 }
2309 $paramsFlashVars = substr($paramsFlashVars, 0, -1);
2310 }
2311
2312 $object = "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\"
2313 codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0\" "
2314 . $attributes . ">\r"
2315 . $paramsObject
2316 . "<param name = \"FlashVars\" value=\"" . $paramsFlashVars . "\"/>\r";
2317 $embed = "<embed type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" "
2318 . $paramsEmbed . ' ' . $attributes . "\r flashvars=\"" . $paramsFlashVars . "\"/>\r";
2319
2320 return $object . $embed . "</object>";
2321 }
2322
2323 static function swfPrepareParam($name, $value, $object = true, $separator = ' ', $quote = '"')
2324 {
2325 return ($object) ? "<param name=\"" . $name . "\" value=\"" . $value . "\"/>\r" : $name . '=' . $quote . $value . $quote . $separator;
2326 }
2327
2328 static function getUrlAbsolute()
2329 {
2330 return self::urlSite();
2331 }
2332
2333 static function colorLuminance($hex, $lum = 0, $darker = true, $percent = true)
2334 {
2335 if ($percent === true) {
2336 $lum = $lum/100;
2337 }
2338 if ($darker === true) {
2339 $lum = -1*$lum;
2340 }
2341 // validate $hex string
2342 $hex = preg_replace('/[^0-9a-f]/i', '', $hex);
2343 if (mb_strlen($hex) < 6) {
2344 $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
2345 }
2346 // convert to decimal and change luminosity
2347 $rgb = "#";
2348 for ($i = 0; $i < 3; $i++) {
2349 $color = intval(mb_substr($hex, $i*2, 2), 16);
2350 $color = $color + ($color * $lum);
2351 $color = ($color > 0) ? $color : 0;
2352 $color = ($color < 255) ? round($color) : 255;
2353 $color = dechex($color);
2354 $rgb .= mb_substr('00' . $color, mb_strlen($color));
2355 }
2356 return $rgb;
2357 }
2358
2359 static function grabsTags($text, $tags = NULL)
2360 {
2361 if ($tags === NULL)
2362 $tags = array('{youtube:', '{img:', '{site:', '{vimeo:', '{metacafe:');
2363
2364 $grabs = array();
2365 foreach ($tags as $start) {
2366 $grabs = array_merge($grabs, grabs($text, $start, '}', true));
2367 }
2368 return $grabs;
2369 }
2370
2371 static function getTextTagsToBr($text, $tag, $tagHtml)
2372 {
2373 $lengthText = mb_strlen($text, 'UTF-8');
2374 $lengthTag = mb_strlen($tag, 'UTF-8');
2375 $lengthTagHtml = mb_strlen($tagHtml, 'UTF-8');
2376 $parseBr = !Common::isOptionActiveTemplate('get_text_tags_to_br_no_parse_br');
2377 while (($offset = mb_strpos($text, $tag, 0, 'UTF-8'))!== FALSE){
2378 $offsetTag = $offset + $lengthTag;
2379 $transferOne = preg_match('/\\n/', mb_substr($text, $offsetTag, 1, 'UTF-8'));
2380 $transferTwo = preg_match('/\\r\\n/', mb_substr($text, $offsetTag, 2, 'UTF-8'));
2381 if ($parseBr) {
2382 $br = ($offsetTag == $lengthText || !empty($transferOne) || !empty($transferTwo)) ? '' : '<br>';
2383 } else {
2384 $br = '';
2385 }
2386 $text = mb_substr($text, 0, $offset, 'UTF-8') . $tagHtml . $br . mb_substr($text, $offsetTag, $lengthText, 'UTF-8');
2387 $offset = $offset + $lengthTagHtml;
2388 $lengthText = mb_strlen($text, 'UTF-8');
2389 if ($offset > $lengthText) break;
2390 }
2391
2392 return $text;
2393 }
2394
2395 static function findExistsTmpl($part, $path = true)
2396 {
2397 $tmpl = false;
2398 $tmplDir = Common::getOption('dir_tmpl', 'path') . $part . '/';
2399
2400 $openDir = opendir($tmplDir);
2401
2402 while(false !== ( $dir = readdir($openDir)) ) {
2403 if ($dir != '.' && $dir != '..' && is_dir($tmplDir . '/' . $dir)) {
2404 if($path) {
2405 $tmpl = $tmplDir. $dir;
2406 } else {
2407 $tmpl = $dir;
2408 }
2409 break;
2410 }
2411 }
2412 closedir($openDir);
2413
2414 return $tmpl;
2415 }
2416
2417 static function getFolderTitle($name, $count = 0, $tmplBox, $tmplCounter, $nameItemBox)
2418 {
2419 $countTitle = ($count > 0) ? lSetVars($tmplCounter, array('count' => $count)) : '';
2420 $vars = array($nameItemBox => strip_tags($name), 'counter' => $countTitle);
2421 $title = lSetVars($tmplBox, $vars);
2422
2423 return $title;
2424 }
2425
2426 static function getDateTemplate($date, $template = 'im_msg_date')
2427 {
2428 $vars = array('number' => date('j', $date),
2429 'month' => l('m_' . date('n', $date)),
2430 'year' => date('Y', $date)
2431 );
2432
2433 return lSetVars('im_msg_date', $vars);
2434 }
2435
2436 static function faviconName()
2437 {
2438 $name = 'favicon';
2439 if(Common::isMultisite()) {
2440 $name = 'f';
2441 }
2442
2443 return $name;
2444 }
2445
2446 static function getFaviconSiteHtml()
2447 {
2448 global $g;
2449
2450 $html = Common::getOption('meta_tags', 'main');
2451 $faviconFileName = self::getFaviconFilename();
2452
2453 if($faviconFileName) {
2454 $html .= '<link rel="shortcut icon" href="' . $g['path']['url_files'] . $faviconFileName . '?v=' . filemtime($g['path']['dir_files'] . $faviconFileName) . '" type="image/x-icon">';
2455 }
2456
2457 return $html;
2458 }
2459
2460 static function getFaviconFilename()
2461 {
2462 global $g;
2463 global $sitePart;
2464
2465 $faviconName = self::faviconName();
2466
2467 $faviconTypes = array(
2468 '',
2469 '_' . (IS_DEMO && ($sitePart == 'main' || $sitePart == 'mobile') ? str_replace('_mobile', '', $g['tmpl']['tmpl_loaded']) : Common::getOption('main', 'tmpl')),
2470 '_all',
2471 );
2472
2473 $faviconFileNameResult = false;
2474
2475 foreach($faviconTypes as $faviconType) {
2476 $faviconFileName = $faviconName . $faviconType . '.ico';
2477 $faviconFile = $g['path']['dir_files'] . $faviconFileName;
2478 if (file_exists($faviconFile)) {
2479 $faviconFileNameResult = $faviconFileName;
2480 break;
2481 }
2482 }
2483
2484 return $faviconFileNameResult;
2485 }
2486
2487 static function getUrlLogo($name = 'logo', $part = 'main', $particle = '')
2488 {
2489 global $g;
2490
2491 $url = '';
2492 if ($particle != '') {
2493 $particle = '_' . $particle;
2494 }
2495 $typeAllowed = array('png', 'svg');
2496 foreach ($typeAllowed as $ext) {
2497 $fileName = 'logo/' . $g['main']['site_part'] . '_' . $g['tmpl']['tmpl_loaded'] . "{$particle}.{$ext}";
2498 if (file_exists($g['path']['dir_files'] . $fileName)) {
2499 $url = $g['path']['url_files'] . $fileName;
2500 }
2501 }
2502 if (!$url) {
2503 $patchDir = array('images', 'img');
2504 $typeImage = array('png', 'gif', 'svg');
2505
2506 $logoDemoPrefixes = array('');
2507
2508 if(IS_DEMO) {
2509 Demo::setLogoData($logoDemoPrefixes, $patchDir);
2510 }
2511
2512 foreach($logoDemoPrefixes as $logoDemoPrefix) {
2513
2514 foreach ($patchDir as $patchV) {
2515 foreach ($typeImage as $ext) {
2516 if($g['multisite']) {
2517 $name = $name . '_joomph';
2518 }
2519 $fileName = $patchV . '/' . $logoDemoPrefix . $name . '.' . $ext;
2520 if (file_exists($g['tmpl']['dir_tmpl_' . $part] . $fileName)) {
2521 $url = $g['tmpl']['url_tmpl_' . $part] . $fileName;
2522 break(2);
2523 }
2524 }
2525 }
2526
2527 }
2528 }
2529 if ($url != '') {
2530 $url .= self::getVersionFile($url);
2531 }
2532
2533 return $url;
2534 }
2535
2536 static function parseSizeParamLogo(&$html, $block, $url)
2537 {
2538 if ($html->blockExists("{$block}_params")) {
2539 $url = explode('/', $url);
2540 $fileLogo = end($url);
2541 $fileLogo = explode('?', $fileLogo);
2542 if (!isset($fileLogo[0])) {
2543 return;
2544 }
2545 $fileLogo = $fileLogo[0];
2546 $isSetParams = false;
2547 $logosSizeparams = Common::getOption('logos_size_params', 'image');
2548 if ($logosSizeparams !== null) {
2549 $logosSizeparams = json_decode($logosSizeparams, true);
2550 if (is_array($logosSizeparams)) {
2551 if (isset($logosSizeparams[$fileLogo])) {
2552 $isSetParams = true;
2553 $widthLogo = $logosSizeparams[$fileLogo]['w'];
2554 $heightLogo = $logosSizeparams[$fileLogo]['h'];
2555 }
2556 }
2557 }
2558 if (!$isSetParams) {
2559 $widthLogo = Common::getOption("{$block}_w", 'template_options');
2560 $heightLogo = Common::getOption("{$block}_h", 'template_options');
2561 }
2562 if ($widthLogo && $heightLogo) {
2563 $html->setvar("{$block}_width", $widthLogo);
2564 $html->setvar("{$block}_height", $heightLogo);
2565 $html->parse("{$block}_params", false);
2566 }
2567 }
2568 }
2569
2570 static function getUrlLogoAutoMail()
2571 {
2572 global $g;
2573
2574 $url = '';
2575 $fileName = 'logo/administration_' . $g['tmpl']['administration'] . '_auto_mail.png';
2576 $fileNameSvg = 'logo/administration_' . $g['tmpl']['administration'] . '_auto_mail.svg';
2577 $patchFile = $g['path']['dir_files'] . $fileName;
2578 $patchFileSvg = $g['path']['dir_files'] . $fileNameSvg;
2579 if (file_exists($patchFile)) {
2580 $url = str_replace($g['path']['dir_main'], '', $patchFile);
2581 } elseif (file_exists($patchFileSvg)) {
2582 $url = str_replace($g['path']['dir_main'], '', $patchFileSvg);
2583 } else {
2584
2585 $name = 'logo_auto_mail';
2586
2587 if(Common::isMultisite()) {
2588 $name = $name . '_joomph';
2589 }
2590
2591 $patchFile = $g['tmpl']['dir_tmpl_administration'] . 'images/' . $name . '.png';
2592 if (file_exists($patchFile)) {
2593 $url = str_replace($g['path']['url_main'], '', $g['tmpl']['url_tmpl_administration'] . 'images/' . $name . '.png');
2594 }
2595 }
2596 if ($url != '') {
2597 $url = Common::urlSiteSubfolders() . $url . self::getVersionFile($patchFile);
2598 }
2599
2600 return $url;
2601 }
2602
2603 static function getVersionFile($path)
2604 {
2605 $result = '';
2606 if ($path != '' && file_exists($path) && is_readable($path)) {
2607 $result = '?v=' . filemtime($path);
2608 }
2609 return $result;
2610 }
2611
2612 static function saveFileSize($path = null, $add = true, $update = true)
2613 {
2614 $fileSize = 0;
2615 if ($path !== null) {
2616 if (is_array($path) && count($path) > 0) {
2617 foreach ($path as $file) {
2618 $fileSize += self::getFileSize($file);
2619 }
2620 } else {
2621 $fileSize = self::getFileSize($path);
2622 }
2623 }
2624 if ($fileSize > 0) {
2625 $fileSizeConfig = self::getOption('files_size', 'main');
2626 if ($add) {
2627 $fileSize = $fileSizeConfig + $fileSize;
2628 } else {
2629 $fileSize = $fileSizeConfig - $fileSize;
2630 }
2631 if ($fileSize < 0) {
2632 $fileSize = 0;
2633 }
2634 Config::update('main', 'files_size', $fileSize, $update);
2635 }
2636
2637 }
2638
2639 static function getFileSize($file = '')
2640 {
2641 if ($file != '' && file_exists($file)) {
2642 return filesize($file);
2643 } else {
2644 return 0;
2645 }
2646 }
2647
2648 static function existsFilesUserDelete($path = null)
2649 {
2650 if ($path !== null) {
2651 if (is_array($path) && count($path) > 0) {
2652 foreach ($path as $file) {
2653 self::existsOneFileUserDelete($file);
2654 }
2655 } else {
2656 self::existsOneFileUserDelete($file);
2657 }
2658 }
2659 }
2660
2661 static function existsOneFileUserDelete($file)
2662 {
2663 if (file_exists($file)) {
2664 self::saveFileSize($file, false);
2665 unlink($file);
2666 }
2667 }
2668
2669 static function isLoadTemplate()
2670 {
2671 global $g;
2672
2673 $sitePart = $g['main']['site_part'];
2674 $dirTmpl = $g['tmpl']['dir_tmpl_' . $sitePart];
2675 if (is_dir($dirTmpl)) {
2676 return true;
2677 }
2678 return false;
2679 }
2680
2681 static function setTemplateNotIs($sitePart)
2682 {
2683 global $g;
2684
2685 check_template_settings_status();
2686
2687 if (!self::isLoadTemplate()) {
2688 $dirTmpl = $g['path']['dir_tmpl'] . $sitePart;
2689 $tmpl = array();
2690 $tmpl = scandir($dirTmpl);
2691
2692 unset($tmpl[0]);
2693 unset($tmpl[1]);
2694
2695 foreach ($tmpl as $item) {
2696 $patch = $dirTmpl . '/' . $item;
2697 if (is_dir($patch)) {
2698 Config::update('tmpl', $sitePart, $item);
2699 break;
2700 }
2701 }
2702 }
2703 }
2704
2705 static function isMultisite()
2706 {
2707 global $g;
2708 return $g['multisite'] != '';
2709 }
2710
2711 static function itemDateFormat($date, $format = 'common_item_date_format', $formatCurrentYear = 'common_item_date_format_year')
2712 {
2713 global $g;
2714 $format = $g['date_formats'][$format];
2715 $formatCurrentYear = $g['date_formats'][$formatCurrentYear];
2716 if ($formatCurrentYear && date('Y') == pl_date('Y', $date)) {
2717 $format = $formatCurrentYear;
2718 }
2719
2720 return pl_date($format, $date);
2721 }
2722
2723 static function isWallActive()
2724 {
2725 global $p;
2726 $isActive = Common::getOption('home_page_mode') != 'dating';
2727 if (Common::getOption('set', 'template_options') == 'urban') {
2728 $isActive = Common::isOptionActive('wall_enabled');
2729 }
2730 return $isActive;
2731 }
2732
2733 static function validateEmail($email)
2734 {
2735 $maxLength = Common::getOption('mail_length_max');
2736 $pattern = "/^[a-zA-Z\-_\.\+0-9]{1," . $maxLength . "}@[a-zA-Z\-_\.0-9]{1," . $maxLength . "}\.[a-zA-Z\-_\.0-9]{1," . $maxLength . "}$/";
2737
2738 if ($email == ''
2739 || mb_strlen($email, 'UTF-8') > $maxLength
2740 || !preg_match($pattern, $email)) {
2741 return false;
2742 } else {
2743 return true;
2744 }
2745 }
2746
2747 static function sendWink($to, $from = null)
2748 {
2749 global $g_user;
2750
2751 if($from === null) {
2752 $from = $g_user;
2753 }
2754
2755 $response = false;
2756 $table = 'users_interest';
2757 if ($from && isset($from['user_id']) && isset($from['name']) && $to) {
2758
2759 $where = 'user_from = ' . to_sql($from['user_id'], 'Number') . '
2760 AND user_to = ' . to_sql($to, 'Number');
2761 DB::delete($table, $where);
2762
2763 DB::insert($table, array('user_from' => $from['user_id'], 'user_to' => $to, 'date' => date('Y-m-d H:i:s')));
2764 CStatsTools::count('winks_sent');
2765
2766 $sql = 'UPDATE user SET new_interests = (
2767 SELECT COUNT(*) FROM ' . $table . '
2768 WHERE new = "Y"
2769 AND user_to = ' . to_sql($to, 'Number') . '
2770 )
2771 WHERE user_id = ' . to_sql($to, 'Number');
2772 DB::execute($sql);
2773 $response = true;
2774
2775 if (Common::isEnabledAutoMail('interest')) {
2776 $row = DB::row('SELECT * FROM user WHERE user_id = ' . to_sql($to, 'Number'));
2777 if ($row) {
2778 if ($row['set_email_interest'] != '2') {
2779 $vars = array(
2780 'title' => Common::getOption('title', 'main'),
2781 'name' => $from['name'],
2782 'uid' => $from['user_id']
2783 );
2784 Common::sendAutomail($row['lang'], $row['mail'], 'interest', $vars);
2785 }
2786 }
2787 }
2788 }
2789 return $response;
2790 }
2791
2792 static function sendMailByAdmin($uid, $toName, $type, $admin = false)
2793 {
2794 if (Common::isEnabledAutoMail($type)) {
2795 $uidAdmin = DB::result('SELECT `user_id` FROM `user` WHERE `admin` = 1');
2796 if (!$uidAdmin) {
2797 return;
2798 }
2799 if (Common::getOption('set', 'template_options') == 'urban') {
2800 global $g_user;
2801 $g_user['welcoming_message_sender'] = 1;
2802 $g_user['user_id'] = $uidAdmin;
2803 $g_user['name'] = DB::result('SELECT `name` FROM `user` WHERE `user_id` = ' . to_sql($uidAdmin));
2804 $sendId = CIm::addMessageToDb($uid, 'welcoming_message', null, 1, 0, true, false, 1);
2805 if ($sendId) {
2806 User::update(array('welcoming_message_notify' => 1), $uid);
2807 if (Common::isEnabledAutoMail('new_message')
2808 && (User::isOptionSettings('set_notif_new_msg') || $admin)) {
2809 $vars = array('title' => Common::getOption('title', 'main'),
2810 'name' => $toName,
2811 'name_sender' => $g_user['name'],
2812 'uid_sender' => $g_user['user_id'],
2813 'uid' => $uid,
2814 'group_id_sender' => 0,
2815 'url_site' => Common::urlSite());
2816 $userInfo = User::getInfoBasic($uid);
2817 Common::sendAutomail($userInfo['lang'], $userInfo['mail'], 'new_message', $vars);
2818 }
2819 }
2820 } else {
2821 $_GET['user_from'] = $uidAdmin;
2822 $_GET['user_to'] = $uid;
2823 $_GET['save'] = 1;
2824 $vars = array('name' => $toName);
2825 $emailAuto = Common::sendAutomail(Common::getOption('lang_loaded', 'main'), '', $type, $vars, false, DB_MAX_INDEX, true);
2826 $_GET['subject'] = $emailAuto['subject'];
2827 $_GET['text'] = $emailAuto['text'];
2828 self::sendMail(true, $type);
2829 }
2830 }
2831 }
2832
2833 static function sendMail($admin = false, $typeAutoMail = 'mail_message')
2834 {
2835 global $g, $g_user;
2836
2837 $message = '';
2838
2839 $type = get_param('type');// Для админа 'plain'
2840 $subject = get_param('subject');
2841 $text = get_param('text');
2842 $isSave = get_param('save');
2843 $userTo = get_param('user_to');
2844 $userFrom = get_param('user_from');
2845
2846 $subject = trim(Common::filterProfileText(strip_tags($subject)));
2847 if (!$subject) {
2848 $subject = l('no_subject');
2849 }
2850
2851 $text = Common::filterProfileText($text);
2852 if ($type == 'postcard') {
2853 $text = urldecode($text);
2854 }
2855 $text = trim(strip_tags($text));
2856
2857 if ($userTo && $userFrom && $subject && $text)
2858 {
2859 $id = $userTo;
2860
2861 if ($admin) {
2862 $g_user['user_id'] = $userFrom;
2863 $g_user['name'] = DB::result('SELECT `name` FROM `user` WHERE `user_id` = ' . to_sql($id, 'Number'));
2864 $textHash = md5(time());
2865 } else {
2866 $textHash = md5(mb_strtolower($text, 'UTF-8'));
2867 if (User::isBanMails($textHash) || User::isBanMailsIp()) {
2868 redirect('ban_mails.php');
2869 }
2870 }
2871
2872 $block = 0;
2873 if (!$admin) {
2874 $block = User::isBlocked('mail', $id, $g_user['user_id']);
2875 }
2876
2877 $to_myself = (guid() == to_sql($id, "Number"));
2878 $empty_text = (trim(get_param('text')) == '');
2879
2880 if ($id && !$block && !$to_myself && !$empty_text)
2881 {
2882 $idMailFrom = 0;
2883 $sqlInto = '';
2884 $sqlValue = '';
2885 if ($type != 'postcard') {
2886 $sqlInto = ', text_hash';
2887 $sqlValue = ', ' . to_sql($textHash);
2888 }
2889 if ($isSave == '1') {
2890 $sql = "INSERT INTO
2891 mail_msg (user_id, user_from, user_to, folder, subject, text, date_sent, new, type, receiver_read" . $sqlInto . ")
2892 VALUES(
2893 " . $g_user['user_id'] . ",
2894 " . $g_user['user_id'] . ",
2895 " . to_sql($id, 'Number') . ",
2896 " . 3 . ",
2897 " . to_sql($subject) . ",
2898 " . to_sql($text) . ",
2899 " . time() . ",
2900 'N',
2901 " . to_sql($type) . ",
2902 'N'" . $sqlValue . ")";
2903 DB::execute($sql);
2904 $idMailFrom = DB::insert_id();
2905 }
2906
2907 $sql = "INSERT INTO
2908 mail_msg (user_id, user_from, user_to, folder, subject, text, date_sent, type, receiver_read, sent_id" . $sqlInto . ")
2909 VALUES(
2910 " . to_sql($id, "Number") . ",
2911 " . $g_user['user_id'] . ",
2912 " . to_sql($id, "Number") . ",
2913 " . 1 . ",
2914 " . to_sql($subject) . ",
2915 " . to_sql($text) . ",
2916 " . time() . ",
2917 " . to_sql($type) . ",
2918 'N',
2919 " . to_sql($idMailFrom, 'Number') . $sqlValue . ")";
2920
2921 DB::execute($sql);
2922 $idMailTo = DB::insert_id();
2923
2924 $sql = "UPDATE user
2925 SET new_mails = new_mails+1
2926 WHERE user_id = " . to_sql($id, 'Number');
2927 DB::execute($sql);
2928 CStatsTools::count('mail_messages_sent');
2929 User::updateActivity($id);
2930
2931 if (Common::isEnabledAutoMail($typeAutoMail)) {
2932 $sql = 'SELECT * FROM `user` WHERE `user_id` = ' . to_sql($id, 'Number');
2933 DB::query($sql);
2934 if ($row = DB::fetch_row()) {
2935 if ($row['set_email_mail'] != '2'){
2936 $textMail = Common::isOptionActive('mail_message_alert') ? $text : '';
2937 $vars = array('title' => $g['main']['title'],
2938 'name' => $g_user['name'],
2939 'text' => $textMail,
2940 'mid' => $idMailTo,
2941 'user_id' => $id);
2942 Common::sendAutomail($row['lang'], $row['mail'], $typeAutoMail, $vars);
2943 }
2944 }
2945 }
2946
2947 if (!$admin) {
2948 $message_sent = true;
2949 if ($message_sent) {
2950 $to = get_param('page_from', '');
2951 set_session('send_message', true);
2952 redirect($to);
2953 }
2954 }
2955
2956 } elseif ($block) {
2957 $message = l('You are in Block List') . '<br>';
2958 } elseif ($to_myself) {
2959 $message = l('You can not do this with yourself!') . '<br>';
2960 } elseif ($empty_text) {
2961 $message = l('Message text is empty!') . '<br>';
2962 } else {
2963 $message = l('Incorrect Username') . '<br>';
2964 }
2965 } else {
2966 $message = l('Incorrect Username, subject or message' . '<br>');
2967 }
2968
2969 return $message;
2970 }
2971
2972 static function isParseModule($name)
2973 {
2974 $notDisplay = Common::getOption('not_display_module', 'template_options');
2975 if (is_array($notDisplay)) {
2976 return !in_array($name, $notDisplay);
2977 } else {
2978 return true;
2979 }
2980 }
2981
2982 static function isAllowedModuleTemplate($name)
2983 {
2984 $modules = Common::getOption('display_module', 'template_options');
2985 if (is_array($modules)) {
2986 return in_array($name, $modules);
2987 } else {
2988 return false;
2989 }
2990 }
2991
2992 static function parseDropDownListLanguage(&$html, $block = 'view', $blockLang = 'language', $part = 'main')
2993 {
2994 global $g;
2995
2996 $langs = Common::listLangs($part);
2997 $isParse = false;
2998 if ($langs && count($langs) > 1) {
2999 $languageCurrent = Common::getOption('main','lang_value');
3000 if (!isset($langs[$g['lang_loaded']])) {
3001 redirect('index.php?set_language=' . Common::getOption('main', 'lang_value'));
3002 return;
3003 }
3004 $html->setvar("{$blockLang}_current", $langs[$g['lang_loaded']]);
3005 if ($html->varExists("{$blockLang}_bright")) {
3006 $uid = User::getRequestUserId();
3007 if (!$uid) {
3008 $uid = guid();
3009 }
3010 $bg = User::getInfoBasic($uid, 'profile_bg');
3011 if (!empty($bg)) {
3012 $linkColor = cache("profile_bg_link_color_bright_{$bg}", 7 * 24 * 60);
3013 if ($linkColor === false) {
3014 $image = $g['tmpl']['dir_tmpl_main'] . '/images/patterns_sm/' . $bg;
3015 $linkColor = changeLinkColorOfBackgroundBright($image);
3016 cache_update("profile_bg_link_color_bright_{$bg}", $linkColor);
3017 }
3018 if (!intval($linkColor)) {
3019 $html->setvar("{$blockLang}_bright", 'white');
3020 }
3021 }
3022 }
3023 $urlPageParams = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
3024 if($urlPageParams != '') {
3025 $html->setvar('url_page_params', del_param('set_language', $urlPageParams, true, true));
3026 }
3027
3028 //$langs = self::setFirstCurrentLanguage($langs);
3029 //$langs = Common::sortingLangsList($langs, 'main');
3030
3031 foreach ($langs as $file => $title) {
3032 $html->setvar("{$blockLang}_value", $file);
3033 $html->setvar("{$blockLang}_title", $title);
3034 if ($g['lang_loaded'] == $file)
3035 $html->setvar("{$blockLang}_class", 'selected');
3036 else
3037 $html->setvar("{$blockLang}_class", '');
3038 $html->parse($blockLang, true);
3039 }
3040 $html->parse($block, true);
3041 $isParse = true;
3042 }
3043 return $isParse;
3044 }
3045
3046 static function filter_text_to_db($v, $parse_media = true, $old_text = null, $validTags = false)
3047 {
3048 if ($parse_media) {
3049 $v = VideoHosts::filterToDb($v);
3050 $v = OutsideImages::filter_to_db($v, $old_text);
3051 }
3052 $v = str_replace("\r\n", "\n", $v);
3053 $v = str_replace("\r", "\n", $v);
3054
3055 $validTags = ($validTags) ? self::ALLOWTAGS : null;
3056 $v = strip_tags_attributes($v, $validTags);
3057 $v = trim($v);
3058
3059 return $v;
3060 }
3061
3062 static function getLinkHtml($url, $isTarget = false, $attr = array())
3063 {
3064 global $g;
3065
3066 $target = '';
3067 if ($isTarget) {
3068 $target = 'target="_blank"';
3069 }
3070 $attrLink = '';
3071 if (!empty($attr) && is_array($attr)) {
3072 foreach ($attr as $key => $value) {
3073 $attrLink .= $key . '="' . $value . '" ';
3074 }
3075 }
3076 $url = '<a ' . $attrLink . $target . ' href="' . $g['path']['url_main'] . $url . '">';
3077 return $url;
3078 }
3079
3080 /*
3081 * @param string $fn the name of a language functions(l, toAttrL, toJsL).
3082 */
3083 static function lSetLink($s, $vars, $isTarget = false, $indx = '', $attr = array(), $fn = 'l', $isCascade = true)
3084 {
3085 if (isset($vars['url'])) {
3086 $vars['link_start' . $indx] = self::replaceByVars(self::getLinkHtml($vars['url'], $isTarget, $attr), $vars);
3087 }
3088 $vars['link_end' . $indx] = '</a>';
3089 if ($isCascade) {
3090 $result = lSetVarsCascade($s, $vars);
3091 } else {
3092 $result = Common::replaceByVars($fn($s), $vars);
3093 }
3094 return $result;
3095 }
3096
3097 static function parseCaptcha(&$html)
3098 {
3099 global $g;
3100 if (Common::isOptionActive('recaptcha_enabled')) {
3101 $block = 're_captcha';
3102 $html->setvar($block . '_lang', self::getLocaleCode());
3103 $theme = Common::getOption('recaptcha_theme');
3104 $html->setvar($block . '_theme', $theme);
3105 $siteKey = Common::getOption('recaptcha_site_key');
3106 $html->setvar($block . '_class', 'recaptcha_bl');
3107 $html->setvar($block . '_sitekey', $siteKey);
3108 $html->parse($block . '_js', false);
3109 $html->parse($block . '_script', false);
3110 $html->parse($block, false);
3111 } else {
3112 if ($html->varExists('tmpl_set_captcha')) {
3113 $html->setvar('tmpl_set_captcha', Common::getOption('set', 'template_options'));
3114 }
3115 if(!function_exists('parseParam')) {
3116 function parseParam(&$html, $name){
3117 $param = Common::getOption($name, 'template_options');
3118 if ($param && $html->varExists($name)) {
3119 $html->setvar($name, "&{$name}={$param}");
3120 }
3121 }
3122 }
3123 $params = array('width_captcha', 'height_captcha');
3124 foreach ($params as $name) {
3125 parseParam($html, $name);
3126 }
3127 $html->setvar('sid', time());
3128 $html->parse('default_captcha_js', true);
3129 $html->parse('default_captcha', false);
3130 }
3131
3132 }
3133
3134 static function getWhereSearchLocation($user, $tableUser = 'u')
3135 {
3136 $where = '';
3137 if ($user['country'] != 0){
3138 $where .= " AND {$tableUser}.country_id=" . $user['country'];
3139 }
3140 if ($user['state'] != 0){
3141 $where .= " AND {$tableUser}.state_id=" . $user['state'];
3142 }
3143 if ($user['city'] != 0){
3144 $where .= " AND {$tableUser}.city_id=" . $user['city'];
3145 }
3146
3147 return $where;
3148 }
3149
3150 static function getLanguageCode($langName)
3151 {
3152 $lang=loadLanguageSite($langName);
3153 return l('language_code',$lang);
3154 }
3155
3156 static function getLocaleCode($lCode='')
3157 {
3158 if($lCode==''){
3159 $lCode = l('language_code');
3160 }
3161
3162 $lCodeParts = explode('-', $lCode);
3163 if(isset($lCodeParts[1])) {
3164 $lCodeParts[1] = strtoupper($lCodeParts[1]);
3165 }
3166
3167 $lCodeValue = implode('_', $lCodeParts);
3168
3169 return $lCodeValue;
3170 }
3171
3172 static function getLocaleShortCode($lCode='')
3173 {
3174 if($lCode==''){
3175 $lCode = l('language_code');
3176 }
3177
3178 $lCodeParts = explode('-', $lCode);
3179
3180 return $lCodeParts[0];
3181 }
3182
3183 static function sortArrayByLocale($array)
3184 {
3185 if(class_exists('Collator', false)) {
3186 $collator = new Collator(Common::getLocaleCode());
3187 $collator->asort($array);
3188 } else {
3189
3190 static $mbEncodings = false;
3191
3192 if($mbEncodings === false) {
3193 $mbEncodings = mb_list_encodings();
3194 }
3195
3196 $localeCurrent = setlocale(LC_COLLATE, 0);
3197
3198 $localeWindows = l('locale_windows');
3199 if($localeWindows == 'locale_windows') {
3200 $localeWindows = false;
3201 }
3202
3203 $isLinux = false;
3204 if(DIRECTORY_SEPARATOR === '/') {
3205 $isLinux = true;
3206 }
3207
3208 $arraySrc = $array;
3209
3210 $lcCollate = Common::getLocaleCode();
3211
3212 if($isLinux) {
3213 $lcCollate .= '.UTF-8';
3214 } else {
3215 if($localeWindows && is_array($mbEncodings) && in_array($localeWindows, $mbEncodings)) {
3216 foreach($array as $key => $value) {
3217 $array[$key] = mb_convert_encoding($value, $localeWindows, 'utf-8');
3218 }
3219 }
3220 }
3221
3222 setlocale(LC_COLLATE, $lcCollate);
3223 if($isLinux || !DEV_PROFILING) {
3224 global $g;
3225
3226 $compareFunction = 'strcoll';
3227 if($g['php'] >= 7) {
3228 $compareFunction = 'strcmp';
3229 }
3230
3231 uasort($array, $compareFunction);
3232 }
3233 setlocale(LC_COLLATE, $localeCurrent);
3234
3235 if(!$isLinux && $localeWindows) {
3236 //$array = array_merge($array, $arraySrc);
3237 foreach($array as $key => $item) {
3238 if(!$isLinux && $localeWindows) {
3239 $array[$key] = $arraySrc[$key];
3240 }
3241 }
3242 }
3243
3244 }
3245 return $array;
3246 }
3247
3248 static function isAvailableFeaturesSuperPowers()
3249 {
3250 $typePaymentFeatures = Common::getOption('type_payment_features', 'template_options');
3251 $typePaymentFeatures = '%' . $typePaymentFeatures . '%';
3252 $where = '`status` = 1 AND `type` LIKE ' . to_sql($typePaymentFeatures);
3253 return DB::count('payment_features', $where, '', 1);
3254 }
3255
3256 static function isAvailableFeaturesSuperPowersMobile()
3257 {
3258 $typePaymentFeatures = Common::getOption('type_payment_features', 'template_options');
3259 $typePaymentFeatures = '%' . $typePaymentFeatures . '%';
3260 $where = "`status` = 1 AND `alias` != 'extended_search' AND `type` LIKE " . to_sql($typePaymentFeatures);
3261 return DB::count('payment_features', $where, '', 1);
3262 }
3263
3264 static function isActiveFeatureSuperPowers($feature)
3265 {
3266 $typePaymentFeatures = Common::getOption('type_payment_features', 'template_options');
3267 $typePaymentFeatures = '%' . $typePaymentFeatures . '%';
3268 $sql = 'SELECT `status`
3269 FROM `payment_features`
3270 WHERE `alias` = ' . to_sql($feature) .
3271 ' AND `type` LIKE ' . to_sql($typePaymentFeatures);
3272 return intval(DB::result($sql, 0, DB_MAX_INDEX, true));
3273 }
3274
3275 static function parseBlockBtnDownloadApp(&$html, $app, $block, $class = array())
3276 {
3277 $isParse = false;
3278 if ($html->blockExists($block) && Common::isOptionActive("app_{$app}_active")){
3279 $cl = $app;
3280 if (isset($class[$app])) {
3281 $cl = $class[$app];
3282 }
3283 $html->setvar("{$block}_class", $cl);
3284 $html->setvar("{$block}_url", Common::getOption("app_{$app}_url"));
3285 $html->setvar("{$block}_icon", $app);
3286 $html->setvar("{$block}_title", l("btn_title_{$app}"));
3287 $html->parse($block, true);
3288 $isParse = true;
3289 }
3290 return $isParse;
3291 }
3292
3293 static function parseBtnDownloadApp(&$html, $position = null, $class = array())
3294 {
3295 global $p;
3296
3297 if ($position === null) {
3298 $position = Common::getOption('app_btn_position');
3299 $optionTmplSet = Common::getOption('set', 'template_options');
3300 $optionTmplPosition = Common::getOption('app_btn_position', 'template_options');
3301 if ($optionTmplPosition) {
3302 $position = $optionTmplPosition;
3303 } elseif ($optionTmplSet == 'urban') {
3304 if (guid()) {
3305 $position = 'bottom';
3306 } elseif ($p == 'index.php' && $position == 'bottom') {
3307 $position = 'bottom_login_form';
3308 } else {
3309 $position = 'top';
3310 }
3311 }
3312 }
3313 $blockBtn = "btn_download_app_{$position}";
3314 $isParseBlock = false;
3315 if ($html->blockExists($blockBtn)) {
3316 $blockBtnItem = "{$blockBtn}_item";
3317 $appList = array('ios', 'android');
3318 foreach ($appList as $app) {
3319 $isParse = self::parseBlockBtnDownloadApp($html, $app, $blockBtnItem, $class);
3320 $isParseBlock = $isParseBlock || $isParse;
3321 }
3322 if ($isParseBlock) {
3323 $html->parse($blockBtn, false);
3324 }
3325 }
3326 return $isParseBlock;
3327 }
3328
3329 static function parseMobileBtnDownloadApp(&$html, $block = 'btn_download_app')
3330 {
3331 $os = self::getMobileOs();
3332 $method = "isApp{$os}";
3333 $isParse = false;
3334 if ($os && !self::$method()) {
3335 self::parseBlockBtnDownloadApp($html, $os, $block);
3336 $isParse = true;
3337 }
3338 return $isParse;
3339 }
3340
3341 static function getSeoSite($url, $uid, $userInfo = null, $noPlaceCity = false, $groupId = false)
3342 {
3343 global $g, $p;
3344
3345 $vars = array('site_title' => $g['main']['title']);
3346 //"SELECT * FROM `seo` WHERE `lang` = 'russian' AND `default` = 1 AND `url` = 'profile_group'"
3347 if ($groupId) {
3348 $groupInfo = Groups::getInfoBasic($groupId);
3349 if ($groupInfo) {
3350 $uid = 0;
3351 $vars = array('title' => $groupInfo['title'],
3352 'description' => $groupInfo['description']
3353 );
3354 } else {
3355 $url = 'profile';
3356 }
3357 }
3358
3359 if ($uid) {
3360 if ($userInfo === null) {
3361 $userInfo = User::getInfoBasic($uid);
3362 }
3363 $vars = array('site_title' => $g['main']['title'],
3364 'name' => $userInfo['name'],
3365 'age' => $userInfo['age'],
3366 'location' => $userInfo['city'] ? l($userInfo['city']) : l($userInfo['country'])
3367 );
3368 }
3369 if ($url == '3dcity' && !$noPlaceCity) {
3370 $vars['place'] = City::getSeoTitlePlace(get_param('place'));
3371 }
3372
3373 $langLoad = Common::getOption('lang_loaded', 'main');
3374 $sql = 'SELECT * FROM `seo`
3375 WHERE `url` = ' . to_sql($url, 'Text') . '
3376 AND `lang` = ' . to_sql($langLoad);
3377 $seo = DB::row($sql, 0, true);
3378
3379 if (!$seo) {
3380 // get default for this language
3381 if ($url == '3dcity') {
3382 $title = $g['main']['title'] . '.' . l('3dcity');
3383 $seo = array('title' => $title,
3384 'description' => $title,
3385 'keywords' => $title);
3386 } else {
3387 $where = '`lang` = ' . to_sql($langLoad) . ' AND `default` = 1';
3388 if ($url == 'profile' || $url == 'profile_group') {
3389 $where .= ' AND `url` = ' . to_sql($url);
3390 } else {
3391 $where .= ' AND `url` = ""';
3392 }
3393 $sql = 'SELECT * FROM `seo` WHERE ' . $where;
3394 $seo = DB::row($sql, 0, true);
3395 }
3396 if (!$seo) {
3397 // get default config
3398 $option = 'seo';
3399 if ($url == 'profile' || $url == 'profile_group') {
3400 $option = "seo_{$url}";
3401 }
3402 $seo = $g[$option];
3403 }
3404 if (isset($l[$p]['header_title']) && $l[$p]['header_title'] != '') {
3405 $seo['title'] = $l[$p]['header_title'];
3406 }
3407 }
3408 if ($seo['title']) {
3409 $seo['title'] = Common::replaceByVars($seo['title'], $vars);
3410 }
3411 if ($seo['description']) {
3412 $seo['description'] = Common::replaceByVars($seo['description'], $vars);
3413 $seo['description'] = htmlspecialchars($seo['description'], ENT_QUOTES, 'UTF-8');
3414 }
3415 if ($seo['keywords']) {
3416 $seo['keywords'] = Common::replaceByVars($seo['keywords'], $vars);
3417 $seo['keywords'] = htmlspecialchars($seo['keywords'], ENT_QUOTES, 'UTF-8');
3418 }
3419 return $seo;
3420 }
3421
3422 static function parseSeoSite(&$html)
3423 {
3424 global $g, $p;
3425
3426 if (isset($g['main']['description'])) {
3427 $seo['title'] = $g['main']['title'];
3428 $seo['description'] = $g['main']['description'];
3429 $seo['keywords'] = '';
3430 if (isset($g['main']['keywords'])) {
3431 $seo['keywords'] = $g['main']['keywords'];
3432 }
3433 $seo['description'] = htmlspecialchars($seo['description'], ENT_QUOTES, 'UTF-8');
3434 $seo['keywords'] = htmlspecialchars($seo['keywords'], ENT_QUOTES, 'UTF-8');
3435 } else {
3436 $queryString = isset($_SERVER['QUERY_STRING']) ? trim($_SERVER['QUERY_STRING']) : '';
3437 $mobile = '';
3438 if (Common::isMobile()) {
3439 if ($queryString) {
3440 $queryString = del_param('set_template_mobile_runtime', $queryString, true, false);
3441 }
3442 $mobile = MOBILE_VERSION_DIR . '/';
3443 }
3444
3445 $url = $mobile . $p . ( $queryString != '' ? '?' . $queryString : '' );
3446
3447 $uid = guid();
3448 $groupId = false;
3449 $groupId = Groups::getParamId();
3450
3451 if ($groupId) {
3452 $uid = User::getRequestUserId();
3453 $url = 'profile_group';
3454 } elseif (($p == 'search_results.php' && get_param('display') == 'profile')
3455 || $p == 'profile_view.php') {
3456 $url = 'profile';
3457 if ($mobile) {
3458 $uid = get_param('user_id', guid());
3459 } elseif ($p == 'search_results.php') {
3460 $uid = User::getRequestUserId();
3461 }
3462 } elseif ($p == 'city.php' || City::isCityInTab()) {
3463 $url = '3dcity';
3464 }
3465
3466 $seo = self::getSeoSite($url, $uid, null, false, $groupId);
3467 }
3468 $html->setvar('title', $seo['title']);
3469 $html->setvar('description', $seo['description']);
3470 $html->setvar('keywords', $seo['keywords']);
3471
3472 if ($html->varExists('js_title')) {
3473 $html->setvar('js_title', toJs($seo['title']));
3474 }
3475 if ($html->varExists('js_description')) {
3476 $html->setvar('js_description', toJs($seo['description']));
3477 }
3478 if ($html->varExists('js_keywords')) {
3479 $html->setvar('js_keywords', toJs($seo['keywords']));
3480 }
3481 }
3482
3483 static function getOptionSetTmpl()
3484 {
3485 $tmplOptionSet = Common::getOption('set', 'template_options');
3486 if (!$tmplOptionSet) {
3487 $tmplOptionSet = 'old';
3488 }
3489 return $tmplOptionSet;
3490 }
3491
3492 static function getTmplSet()
3493 {
3494 return self::getOptionSetTmpl();
3495 }
3496
3497 static function getTmplName()
3498 {
3499 return Common::getOption('name', 'template_options');
3500 }
3501
3502 static function isCreditsEnabled()
3503 {
3504 return !Common::isOptionActive('free_site') && Common::isOptionActive('credits_enabled');
3505 }
3506
3507 static function isTransferCreditsEnabled()
3508 {
3509 return Common::isCreditsEnabled() && Common::isOptionActive('credit_transfer_to_another_user');
3510 }
3511
3512 static function dateFormat($timestamp, $formatName, $strtotime = true, $isObjDateTime = false, $isTimeStamp = false, $siteTime = false, $isFormat = false) {
3513 global $g;
3514
3515 if ($strtotime){
3516 $timestamp = strtotime($timestamp);
3517 }
3518 //echo $formatName.' - '.$timestamp.' <br>';
3519 if ($isFormat) {
3520 $format = $formatName;
3521 } else {
3522 $format = $g['date_formats'][$formatName];
3523 }
3524 return pl_date($format, $timestamp, $isObjDateTime, $isTimeStamp, $siteTime);
3525 }
3526
3527 static function getMapImageUrl($x, $y, $sizeX, $sizeY, $scale, $needMarker) {
3528 $service = Common::getOption('maps_service');
3529 if ($service == 'Google'){
3530 if ($needMarker){
3531 $url = '//maps.googleapis.com/maps/api/staticmap?markers=color:red%7Clabel:%7C' . $x . ',' . $y . '¢er=' . $x . ',' . $y . '&zoom=10&size=' . $sizeX . 'x' . $sizeY .'&sensor=false&scale='.$scale;
3532 } else {
3533 $url = '//maps.googleapis.com/maps/api/staticmap?center=' . $x . ',' . $y . '&zoom=10&size=' . $sizeX . 'x' . $sizeY .'&sensor=false&scale='.$scale;
3534 }
3535
3536 $apiKey = trim(Common::getOption('google_apikey'));
3537 if($apiKey) {
3538 $url .= '&key=' . $apiKey;
3539 }
3540 } else {
3541 $apiKey = Common::getOption('bing_apikey');
3542 if ($needMarker){
3543 $url = '//dev.virtualearth.net/REST/V1/Imagery/Map/Road/'. $x . ',' . $y . '/' . $scale . '?mapSize=' . $sizeX . ',' . $sizeY .'&pp=' . $x . ',' . $y . ';66;&c='.Common::getLocaleShortCode().'&format=png&key='.$apiKey;
3544 } else {
3545 $url = '//dev.virtualearth.net/REST/V1/Imagery/Map/Road/'. $x . ',' . $y . '/' . $scale . '?mapSize=' . $sizeX . ',' . $sizeY .'&c='.Common::getLocaleShortCode().'&format=png&key='.$apiKey;
3546 }
3547 }
3548
3549 return $url;
3550 }
3551
3552 static function isOptionTemplateSet($template = 'urban')
3553 {
3554 return Common::getOption('set', 'template_options') == $template;
3555 }
3556
3557 static function getDefaultBirthday($param = null, $value = 0)
3558 {
3559 $defaultBirthday = array('day' => 1, 'month' => date('n'), 'year' => Common::getOption('default_birth_year'));
3560 if ($param === null) {
3561 return $defaultBirthday;
3562 }
3563 if (!$value) {
3564 $value = $defaultBirthday[$param];
3565 }
3566 return $value;
3567 }
3568
3569 static function searchWhere($typeSearch, $tableUser = 'u', $isAlwaysInterestMy = false)
3570 {
3571 global $g;
3572
3573 $guid = guid();
3574 $guidSql = to_sql($guid, 'Number');
3575 $optionSet = Common::getOption('set', 'template_options');
3576 $isFreeSite = Common::isOptionActive('free_site');
3577 $optionTemplateSet = Common::getOption('set', 'template_options');
3578 $display = get_param('display');
3579
3580 $where = '';
3581 $whereCore = '1=1 ';
3582 $user = array();
3583
3584 $user['horoscope'] = intval(get_checks_param('p_star_sign'));
3585 if ($user['horoscope']){
3586 $where .= " AND {$user['horoscope']} & (1 << (cast({$tableUser}.horoscope AS signed) - 1))";
3587 }
3588
3589 $user['p_orientation'] = intval(get_checks_param('p_orientation'));
3590 if ($user['p_orientation'] > 0){
3591 $where .= " AND {$user['p_orientation']} & (1 << (cast({$tableUser}.orientation AS signed) - 1))";
3592 }
3593
3594 $user['p_relation'] = intval(get_checks_param('p_relation'));
3595 if ($user['p_relation'] != '0'){
3596 $where .= " AND {$user['p_relation']} & (1 << (cast({$tableUser}.relation AS signed) - 1))";
3597 }
3598
3599 $user['name'] = trim(get_param('name_key'));
3600 if ($user['name']) {
3601 $where .= " AND {$tableUser}.name LIKE '%" . to_sql($user['name'], 'Plain') . "%'";
3602 }
3603
3604 $user['name'] = trim(get_param('name'));
3605 if ($user['name']) {
3606 $where .= ' AND {$tableUser}.name=' . to_sql($user['name']);
3607 }
3608
3609 $user['p_age_from'] = intval(get_param('p_age_from'));
3610 if ($user['p_age_from'] == $g['options']['users_age']) {
3611 $user['p_age_from'] = 0;
3612 }
3613
3614 $user['p_age_to'] = intval(get_param('p_age_to'));
3615 if ($user['p_age_to'] == $g['options']['users_age_max']) {
3616 $user['p_age_to'] = 10000;
3617 }
3618
3619 if ($user['p_age_from']) {
3620 $where .= " AND (DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT({$tableUser}.birth, '%Y')
3621 - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT({$tableUser}.birth, '00-%m-%d'))) >= " . $user['p_age_from'];
3622 }
3623
3624 if ($user['p_age_to']) {
3625 $where .= " AND (DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT({$tableUser}.birth, '%Y')
3626 - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT({$tableUser}.birth, '00-%m-%d')) <= " . $user['p_age_to'] . ') ';
3627 }
3628
3629 $addWhereInterests = '';
3630
3631 foreach ($g['user_var'] as $k => $v){
3632 $user[$k] = intval(get_param($k));
3633 }
3634 $typeFields = array('from', 'checks', 'checkbox');
3635 $numCheckbox = 0;
3636 $from_add = '';
3637 $from_group = '';
3638 foreach ($g['user_var'] as $k => $v) {
3639 if (in_array($v['type'], $typeFields) && $v['status'] == 'active') {
3640 if ($v['type'] == 'from'){
3641 $key = $k;
3642 if (substr($key, 0, 2) == "p_") $key = substr($key, 2);
3643 if (substr($key, -5) == "_from") $key = substr($key, 0, strlen($key) - 5);
3644
3645 $valFieldFrom = $user[$k];
3646
3647 $fieldTo = substr($k, 0, strlen($k) - 4) . 'to';
3648 $valFieldTo = intval($user[$fieldTo]);
3649
3650 if ($valFieldTo) {
3651 $where .= ' AND i.' . $key . '<=' . $valFieldTo;
3652
3653 if(!$valFieldFrom) {
3654 $valFieldFrom = 1;
3655 }
3656 }
3657
3658 if($valFieldFrom) {
3659 $where .= " AND i." . $key . ">=" . intval($valFieldFrom);
3660 }
3661
3662 if($valFieldFrom || $valFieldTo) {
3663 // save real value for defaul select value
3664 $valFieldFrom = $user[$k];
3665
3666 $keyFilter = $k;
3667
3668 if(!$valFieldFrom) {
3669 $keyFilter = $fieldTo;
3670 }
3671
3672 $userSearchFilters[$keyFilter] = array(
3673 'field' => $key,
3674 'values' => array($k => $valFieldFrom, $fieldTo => $valFieldTo),
3675 );
3676 }
3677 } elseif ($v['type'] == 'checks' && $user[$k] != 0) {
3678 $user[$k] = intval(get_checks_param($k));
3679 if ($user[$k] != 0) {
3680 $key = $k;
3681 if (substr($key, 0, 2) == "p_") $key = substr($key, 2);
3682
3683 $userSearchFilters[$k] = array(
3684 'field' => $key,
3685 'value' => get_param_array($k),
3686 );
3687
3688 if ($k != 'p_star_sign') {
3689 $where .= " AND " . to_sql($user[$k], 'Number') . " & (1 << (cast(i." . $key . " AS signed) - 1))";
3690 }
3691 }
3692 } elseif ($v['type'] == 'checkbox' && $user[$k] != 0) {
3693 $params = get_param_array($k);
3694 foreach ($params as $key => $value) {
3695 if ($value == 0) {
3696 unset($params[$key]);
3697 }
3698 }
3699 if (!empty($params)){
3700 $userSearchFilters[$k] = array(
3701 'field' => $k,
3702 'value' => $params,
3703 );
3704 $nameTable = 'uck' . $numCheckbox;
3705 $from_add .= " LEFT JOIN users_checkbox AS " . $nameTable . " ON " . $nameTable . ".user_id = {$tableUser}.user_id AND " . $nameTable . ".field = " . to_sql($v['id'], 'Number') . " AND " . $nameTable . ".value IN (" . implode(',', $params) . ")";
3706 $where .= " AND " . $nameTable . ".user_id IS NOT NULL";
3707 $numCheckbox++;
3708 }
3709 }
3710 }
3711 }
3712
3713 if ($numCheckbox) {
3714 $from_group = "{$tableUser}.user_id";
3715 }
3716 if (intval(get_param('photo'))){
3717 $where .= " AND {$tableUser}.is_photo='Y'";
3718 }
3719 if (intval(get_param('couple'))){
3720 $where .= " AND {$tableUser}.couple='Y'";
3721 }
3722
3723 if (get_param('status') == 'online'){
3724 $time = date('Y-m-d H:i:s', time() - $g['options']['online_time'] * 60);
3725 if ($optionSet == 'urban') {
3726 $where .= " AND ({$tableUser}.last_visit> " . to_sql($time, 'Text') . ' AND ' . User::isHiddenSql($tableUser . '.') . ')';
3727 //$where .= " AND ({$tableUser}.last_visit> " . to_sql($time, 'Text') . " AND {$tableUser}.set_hide_my_presence = 2)";
3728 } else {
3729 $where .= " AND {$tableUser}.last_visit> " . to_sql($time, 'Text');
3730 }
3731 } elseif (get_param('status') == 'new'){
3732 $where .= " AND {$tableUser}.register > " . to_sql(date('Y-m-d H:i:s', (time() - $g['options']['new_time'] * 3600 * 24)), 'Text');
3733 } elseif (get_param('status') == 'birthday'){
3734 $where .= " AND (DAYOFMONTH({$tableUser}.birth)=DAYOFMONTH('" . date('Y-m-d H:i:s') . "') AND MONTH({$tableUser}.birth)=MONTH('" . date('Y-m-d H:i:s') . "'))";
3735 }
3736
3737 $day = to_sql(get_param('day', 0), 'Number');
3738 $month = to_sql(get_param('month', 0), 'Number');
3739 $year = to_sql(get_param('year', 0), 'Number');
3740
3741 if($day && $month && $year) {
3742 $month = sprintf('%02d', $month);
3743 $day = sprintf('%02d', $day);
3744 $where .= " AND {$tableUser}.register >= '{$year}-{$month}-{$day} 00:00:00' ";
3745 }
3746
3747 $day = to_sql(get_param('day_to', 0), 'Number');
3748 $month = to_sql(get_param('month_to', 0), 'Number');
3749 $year = to_sql(get_param('year_to', 0), 'Number');
3750
3751 if ($day && $month && $year) {
3752 $month = sprintf('%02d', $month);
3753 $day = sprintf('%02d', $day);
3754 $where .= " AND {$tableUser}.register <= '{$year}-{$month}-{$day} 23:59:59' ";
3755 }
3756
3757 // IF active distance search, then exclude others
3758 // DISTANCE
3759 $distance = intval(get_param('radius', 0));
3760 $user['city'] = intval(get_param('city', 0));
3761 $user['state'] = intval(get_param('state', 0));
3762 $user['country'] = intval(get_param('country', 0));
3763
3764 $maxDistance = 200;
3765 if ($optionTemplateSet == 'urban') {
3766 $maxDistance = Common::getOption('max_search_distance');
3767 }
3768 if($distance > $maxDistance) {
3769 $user['city'] = 0;
3770 $user['state'] = 0;
3771 }
3772 // search only by distance from selected city
3773 $whereLocation = '';
3774 if ($distance && $user['city']) {
3775 // find MAX geo values
3776 $whereLocation = inradius($user['city'], $distance);
3777 } else {
3778 $whereLocation = Common::getWhereSearchLocation($user);
3779 }
3780
3781 $from_add .= " LEFT JOIN userinfo AS i ON {$tableUser}.user_id=i.user_id LEFT JOIN geo_city AS gc ON gc.city_id = {$tableUser}.city_id";
3782
3783 $keyword = trim(get_param('keyword'));
3784 $search_header = get_param('search_header');
3785 $where_search = '';
3786 if ($keyword ) {
3787 if ($search_header == 1) {
3788 $where_search = " OR {$tableUser}.mail =" . to_sql($keyword);
3789 }
3790 $keyword_search_sql = '';
3791 $keyword = to_sql(strip_tags($keyword), 'Plain');
3792 foreach ($g['user_var'] as $k => $v){
3793 if ($v['type'] == 'text' or $v['type'] == 'textarea') {
3794 $keyword_search_sql .= " OR i.{$k} LIKE '%{$keyword}%'";
3795 }
3796 }
3797 $where .= " AND ({$tableUser}.name LIKE '%{$keyword}%'{$keyword_search_sql}{$where_search}) ";
3798 }
3799
3800 $ht = '';
3801 if ($typeSearch != 'wall_urban') {
3802 //Для урбана u.hide_time = 0 убрать вообще
3803 $ht = $user['name'] ? '1 ' : "{$tableUser}.hide_time = 0";
3804 $wallItemId = get_param('wall_item_id');
3805 if($wallItemId) {
3806 $where .= ' AND wl.wall_item_id = ' . to_sql($wallItemId, 'Number');
3807 $from_add .= " LEFT JOIN wall_likes AS wl ON wl.user_id = {$tableUser}.user_id ";
3808 // show hidden profiles in likes
3809 $ht = ' 1 ';
3810 }
3811 }
3812
3813 $whereCore .=" AND {$ht}";
3814
3815 $uidsExclude = get_param('uids_exclude', '');
3816 if($uidsExclude) {
3817 $where .= " AND {$tableUser}.user_id NOT IN (" . to_sql($uidsExclude, 'Plain') . ') ';
3818 }
3819
3820 $paramUid = intval(get_param('uid'));
3821 if (!$paramUid) {
3822 $interest = get_param('interest');
3823 if($interest) {
3824 $addWhere = '';
3825 if ($isAlwaysInterestMy) {
3826 $addWhereInterests=" AND {$tableUser}.user_id IN (SELECT uint.user_id as uint_user FROM user_interests uint WHERE uint.interest = " . to_sql($interest) ." UNION SELECT " . to_sql($guid) ." AS uint_user )";
3827 } else {
3828 $from_add .= " JOIN user_interests AS uint ON ({$tableUser}.user_id = uint.user_id AND uint.interest = " . to_sql($interest) .') ' ;
3829 }
3830 }
3831 $where = "{$ht} {$where}";
3832 }
3833
3834 $order = '';
3835 if (intval(get_param('with_photo')) && $display != 'encounters'
3836 && $display != 'rate_people' && $typeSearch != 'wall_urban') {
3837 $order = "is_photo = 'Y' DESC, ";
3838 }
3839
3840 $user['i_am_here_to'] = intval(get_param('i_am_here_to'));
3841 if ($user['i_am_here_to'] && $typeSearch != 'wall_urban'){
3842 //$where .= " AND u.i_am_here_to = " . to_sql($user['i_am_here_to']);
3843 $order .= 'i_am_here_to = ' . to_sql($user['i_am_here_to']) . ' DESC, ';
3844 }
3845
3846 if ($optionTemplateSet == 'urban') {
3847 if ($display == '') {
3848 $order .= ($isFreeSite) ? 'near DESC, user_id DESC' : 'date_search DESC, near DESC, user_id DESC';
3849 }
3850 } else {
3851 $order .= 'near DESC, user_id DESC';
3852 }
3853
3854 if (Common::getOption('do_not_show_me_in_search', 'template_options')
3855 && $typeSearch != 'wall_urban'
3856 && $guid != User::getRequestUserId()) {
3857 $where .= " AND {$tableUser}.user_id != {$guidSql}";
3858 $whereCore .= " AND {$tableUser}.user_id != {$guidSql}";
3859 }
3860
3861 if ($guid) {
3862 if ($optionTemplateSet == 'urban' && Common::isOptionActive('contact_blocking')) {
3863 //$order = ' date_search DESC, near DESC, user_id DESC';
3864 $from_add .= " LEFT JOIN user_block_list AS ubl1 ON (ubl1.user_to = {$tableUser}.user_id AND ubl1.user_from = {$guidSql})
3865 LEFT JOIN user_block_list AS ubl2 ON (ubl2.user_from = {$tableUser}.user_id AND ubl2.user_to = {$guidSql})";
3866 $where .=' AND ubl1.id IS NULL AND ubl2.id IS NULL';
3867 $whereCore .= ' AND ubl1.id IS NULL AND ubl2.id IS NULL';
3868
3869 }
3870 if ($display == 'encounters') {
3871 $where .= " AND {$tableUser}.is_photo_public = 'Y' AND {$tableUser}.user_id != {$guidSql}";
3872 if (!$paramUid) {
3873 $where .= ' AND enc1.user_from IS NULL AND enc2.user_from IS NULL ';
3874 $from_add .= " LEFT JOIN encounters AS enc1 ON ({$tableUser}.user_id = enc1.user_to AND enc1.user_from = {$guidSql})
3875 LEFT JOIN encounters AS enc2 ON ({$tableUser}.user_id = enc2.user_from AND enc2.user_to = {$guidSql}
3876 AND ((enc2.from_reply != 'N' AND enc2.to_reply != 'P')OR(enc2.from_reply = 'N')))";
3877
3878 }
3879 $order .= ($isFreeSite) ? 'near DESC, user_id DESC' : 'date_encounters DESC, near DESC, user_id DESC';
3880 } elseif ($display == 'rate_people') {
3881 $where .= " AND {$tableUser}.is_photo_public = 'Y' AND {$tableUser}.user_id != {$guidSql} AND upr.photo_id IS NULL ";
3882 $from_add .= " LEFT JOIN photo AS up ON {$tableUser}.user_id = up.user_id AND up.private = 'N'
3883 LEFT JOIN photo_rate AS upr ON up.photo_id = upr.photo_id AND upr.user_id = {$guidSql}";
3884 $order .= 'votes ASC, RAND()';
3885 $from_group = "{$tableUser}.user_id";
3886 if (!$paramUid) {
3887 if(Users_List::isBigBase()){
3888 //Внимание!!! Все поля, которые могут попасть в $order необходимо добавить в SELECT
3889 $sql="
3890 SELECT {$tableUser}.user_id, SUM(votes) AS votes, {$tableUser}.i_am_here_to
3891 FROM (SELECT DISTINCT {$tableUser}.user_id, {$tableUser}.i_am_here_to
3892 FROM user AS u ".$from_add. ' WHERE '.$where.' '.$whereLocation.') u
3893 LEFT JOIN photo AS up ON {$tableUser}.user_id = up.user_id AND up.private = "N"
3894 GROUP BY '.$from_group.'
3895 ORDER BY '.$order.' LIMIT 0,1';
3896 $user = DB::row($sql);
3897 if (!$user['user_id']) {
3898 $user['user_id']=0;
3899 }
3900 $where = " {$tableUser}.user_id = " . $user['user_id'];
3901 $order = '';
3902 }
3903 }
3904 }
3905 }
3906
3907 $addWhereLocation = true;
3908 if ($display == 'encounters' && $paramUid && $typeSearch != 'wall_urban') {
3909 $addWhereLocation = false;
3910 }
3911 if ($addWhereLocation) {
3912 $where .= $whereLocation;
3913 }
3914
3915 $where .= $addWhereInterests;
3916
3917 $globalUsernameSearch = trim(get_param('global_search_by_username'));
3918 if($globalUsernameSearch){
3919 $where = "{$whereCore} AND {$tableUser}.name LIKE '%" . to_sql($global_username_search,'Plain') . "%'";
3920 }
3921 return array('from_add' => $from_add, 'where' => $where, 'order' => $order, 'from_group' => $from_group);
3922 }
3923
3924 static function parseErrorAccessingUser(&$html)
3925 {
3926 $blockErrorAccessing = 'error_accessing_user';
3927 $errorAccessing = get_session($blockErrorAccessing);
3928 if ($html->blockexists($blockErrorAccessing) && $errorAccessing) {
3929 delses($blockErrorAccessing);
3930 $errorParam = get_session("{$blockErrorAccessing}_param");
3931 delses("{$blockErrorAccessing}_param");
3932 $html->setvar($blockErrorAccessing, lSetVars($errorAccessing, array('param' => $errorParam)));
3933 $html->parse($blockErrorAccessing, false);
3934
3935 if ($html->varExists('is_mode_viewing_moderator')) {//EDGE
3936 $html->setvar('is_mode_viewing_moderator', intval(Moderator::isAllowedViewingUsers($errorAccessing)));
3937 }
3938 }
3939 }
3940
3941 static function parseErrorForNotLoginUserNotExist(&$html)
3942 {
3943 if (!guid()) {
3944 $uid = User::getRequestUserId();
3945 if ($uid && !User::isExistsByUid($uid)) {
3946 $urlRedirect = Common::refererPageFromSite();
3947 if (!$urlRedirect) {
3948 $urlRedirect = Common::getHomePage();
3949 }
3950 $html->setvar('url_redirect', $urlRedirect);
3951 $html->parse('for_not_login_user_not_exist');
3952 }
3953 }
3954 }
3955
3956 static function autoTranslate($msg, $fromLang, $toLang)
3957 {
3958 $translatorEngine = 'google';
3959
3960 $trMsg='';
3961 if($translatorEngine == 'google'){
3962 $APIkey=trim(Common::getOption('autotranslator_key'));
3963 if($APIkey!=''){
3964 $fromLocale=Common::getLocaleShortCode(Common::getLanguageCode($fromLang));
3965 $toLocale=Common::getLocaleShortCode(Common::getLanguageCode($toLang));
3966
3967 if (function_exists('curl_init')) {
3968
3969 $query = "https://www.googleapis.com/language/translate/v2?key=".$APIkey.
3970 "&q=".urlencode($msg)."&source=".$fromLocale."&target=".$toLocale;
3971
3972 $curl = curl_init(); // Create Curl Object
3973 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0); // Allow self-signed certs
3974 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0); // Allow certs that do not match the hostname
3975 curl_setopt($curl, CURLOPT_HEADER,0); // Do not include header in output
3976 curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); // Return contents of transfer on curl_exec
3977 curl_setopt($curl, CURLOPT_URL, $query); // execute the query
3978 $result = curl_exec($curl);
3979 if ($result == false) {
3980
3981 $result='ERROR';
3982 }
3983 curl_close($curl);
3984
3985 $result=json_decode($result);
3986
3987 if(isset($result->data->translations)){
3988 $texts=$result->data->translations;
3989 foreach($texts as $k=>$v){
3990 $trMsg.=$v->translatedText;
3991 }
3992 }
3993 if($msg==$trMsg){
3994 $trMsg='';
3995 }
3996 }
3997 }
3998 }
3999
4000 return $trMsg;
4001
4002 }
4003
4004 static public function getColOrder($section='main')
4005 {
4006 $sql="SELECT * FROM `col_order` WHERE `section`=".to_sql($section)." ORDER BY `position`";
4007 $rows=DB::rows($sql);
4008 $result=array();
4009 foreach($rows as $k=>$row){
4010 $result[$row['name']]=$row;
4011 }
4012 return $result;
4013 }
4014
4015 static public function redirectFromWithBaseUrl($page, $uid = null, $id = null, $params = null)
4016 {
4017 redirect(self::pageUrlWithBaseUrl($page, $uid = null, $id = null, $params = null));
4018 }
4019
4020 static public function pageUrlWithBaseUrl($page, $uid = null, $id = null, $params = null)
4021 {
4022 global $g;
4023
4024 return $g['path']['base_url_main'] . Common::pageUrl($page, $uid = null, $id = null, $params = null);
4025 }
4026
4027 static public function pageUrl($page, $uid = null, $id = null, $params = null)
4028 {
4029 global $g, $g_user;
4030
4031 $pageType = $page;
4032 if ($uid === null) {
4033 $uid = User::getParamUid();
4034 }
4035
4036 if(Common::isOptionActive('seo_friendly_urls')) {
4037 $paramsAddSymbol = '?';
4038 $optionTmplName = Common::getTmplName();
4039 if ($optionTmplName == 'edge') {
4040 $customUrls = array(
4041 'user_photos_list' => 'photos',
4042 'user_vids_list' => 'vids',
4043 'user_friends_list' => 'friends',
4044 'my_friends_online' => 'friends_online',
4045
4046 'blogs_list' => 'blogs',
4047 'user_blogs_list' => 'blogs',
4048
4049 'photos_list' => 'photos',
4050 'pages_photos_list' => 'photos_pages',
4051 'groups_photos_list' => 'photos_groups',
4052 'pages_vids_list' => 'vids_pages',
4053 'groups_vids_list' => 'vids_groups',
4054
4055 'vids_list' => 'vids',
4056 'wall_liked' => 'wall_liked/' . get_param_int('wall_item_id', $id),
4057 'wall_shared' => 'wall_shared/' . get_param_int('wall_shared_item_id', $id),
4058 'wall_liked_comment' => 'wall_liked_comment/' . get_param_int('comment_id', $id),
4059
4060 'photo_liked' => 'photo_liked/' . get_param_int('photo_id', $id),
4061 'photo_liked_comment' => 'photo_liked_comment/' . get_param_int('comment_id', $id),
4062
4063 'video_liked' => 'video_liked/' . get_param_int('video_id', $id),
4064 'video_liked_comment' => 'video_liked_comment/' . get_param_int('comment_id', $id),
4065
4066 'group_photos_list' => 'photos',
4067 'group_page_liked' => 'liked',
4068 'group_subscribers' => 'subscribers',
4069 'group_vids_list' => 'vids',
4070 'group_block_list' => 'block_list',
4071 'pages_list' => 'pages',
4072 'user_pages_list' => 'pages',
4073 'groups_list' => 'groups',
4074 'user_groups_list' => 'groups',
4075 'user_my_pages_photos_list' => 'photos_my_pages',
4076 'user_my_groups_photos_list' => 'photos_my_groups',
4077 'user_my_pages_vids_list' => 'vids_my_pages',
4078 'user_my_groups_vids_list' => 'vids_my_groups',
4079
4080 'user_calendar' => 'calendar',
4081 'user_my_calendar' => 'calendar',
4082 'task_create' => 'task_create',
4083 'task_my_create' => 'task_create',
4084
4085 'blogs_post_liked' => 'blogs_post_liked/' . get_param_int('blog_id', $id),
4086 'blogs_post_liked_comment' => 'blogs_post_liked_comment/' . get_param_int('comment_id', $id),
4087
4088 );
4089 if (isset($customUrls[$page])) {
4090 if ($page == 'my_friends_online') {
4091 $urlSeo = User::url(guid(), null, null, true, true);
4092 } else {
4093 if (in_array($page, array('group_photos_list', 'group_vids_list', 'group_page_liked', 'group_subscribers', 'group_block_list'))) {
4094 $urlSeo = Groups::url($uid, null, null, true, true);
4095 } else {
4096 $urlSeo = User::url($uid, null, null, true, true);
4097 }
4098 }
4099 $assignProfilePage = array('user_photos_list',
4100 'user_vids_list',
4101 'user_blogs_list',
4102 'user_pages_list',
4103 'user_friends_list',
4104 'my_friends_online',
4105
4106 'user_groups_list',
4107 'group_photos_list',
4108 'group_vids_list',
4109 'group_page_liked',
4110 'group_subscribers',
4111 'group_block_list',
4112 'photos_my_pages',
4113 'user_my_pages_photos_list',
4114 'user_my_groups_photos_list',
4115 'user_my_pages_vids_list',
4116 'user_my_groups_vids_list',
4117 'user_calendar',
4118 'user_my_calendar',
4119 'task_create',
4120 'task_my_create'
4121 );
4122 if (in_array($page, $assignProfilePage)) {
4123 $page = $urlSeo . '/' . $customUrls[$page];
4124 } else {
4125 $page = $customUrls[$page];
4126 }
4127 }
4128
4129 if ($page == 'page_edit' || $page == 'group_edit' || $page == 'blog_edit') {
4130 $page .= '/' . $uid;
4131 }
4132
4133 if (in_array($pageType, array('task_create', 'task_my_create', 'task_edit', 'calendar', 'user_calendar', 'user_my_calendar')) && $id) {
4134 $page .= '/' . $id;
4135 }
4136 }
4137
4138 $result = $page;
4139 } else {
4140 $paramsAddSymbol = '';
4141 $urls = array(
4142 'encounters' => 'search_results.php?display=encounters',
4143 'hot_or_not' => 'search_results.php?display=encounters',
4144 'rate_people' => 'search_results.php?display=rate_people',
4145 'login' => 'join.php?cmd=please_login',
4146 'private_mutual_attractions' => 'private_mutual_attractions.php',
4147 'mutual_likes' => 'mutual_attractions.php',
4148 'whom_you_like' => 'mutual_attractions.php?cmd=whom_you_like',
4149 'who_likes_you' => 'mutual_attractions.php?cmd=who_likes_you',
4150 'private_photo_access' => 'my_friends.php',
4151 'terms' => 'info.php?page=term_cond',
4152 'privacy_policy' => 'info.php?page=priv_policy',
4153 'profile_boost' => 'upgrade.php?action=refill_credits',
4154 'refill_credits' => 'upgrade.php?action=refill_credits',
4155 /* Edge */
4156 'social_network_info' => 'info.php?page=social_network_info',
4157 'my_friends_online' => 'friends_list_online.php',
4158 'user_photos_list' => 'photos_list.php?uid=' . $uid,
4159 'user_vids_list' => 'vids_list.php?uid=' . $uid,
4160 'user_blogs_list' => 'blogs_list.php?uid=' . $uid,
4161 'user_friends_list' => 'friends_list.php?uid=' . $uid,
4162 'wall_liked' => 'search_results.php?show=wall_liked&wall_item_id=' . get_param_int('wall_item_id', $id),
4163 'wall_shared' => 'search_results.php?show=wall_shared&wall_shared_item_id=' . get_param_int('wall_shared_item_id', $id),
4164 'wall_liked_comment' => 'search_results.php?show=wall_liked_comment&comment_id=' . get_param_int('comment_id', $id),
4165
4166 'photo_liked' => 'search_results.php?show=photo_liked&photo_id=' . get_param_int('photo_id', $id),
4167 'photo_liked_comment' => 'search_results.php?show=photo_liked_comment&comment_id=' . get_param_int('comment_id', $id),
4168
4169 'video_liked' => 'search_results.php?show=video_liked&video_id=' . get_param_int('video_id', $id),
4170 'video_liked_comment' => 'search_results.php?show=video_liked_comment&comment_id=' . get_param_int('comment_id', $id),
4171
4172 'page_add' => 'group_add.php?view=group_page',
4173 'pages_list' => 'groups_list.php?view=group_page',
4174 'user_pages_list' => 'groups_list.php?view=group_page&uid=' . $uid,
4175 'groups_list' => 'groups_list.php',
4176 'user_groups_list' => 'groups_list.php?uid=' . $uid,
4177 'page_edit' => 'group_add.php?cmd=edit&view=group_page&group_id=' . $uid,
4178 'group_edit' => 'group_add.php?cmd=edit&group_id=' . $uid,
4179 /* Edge */
4180 'calendar' => 'calendar.php',
4181 'user_calendar' => 'calendar.php?uid=' . $uid,
4182 'user_my_calendar' => 'calendar.php?uid=' . $uid,
4183 'task_create' => 'calendar_task_create.php?uid=' . $uid,
4184 'task_my_create' => 'calendar_task_create.php?uid=' . $uid,
4185 'task_edit' => 'calendar_task_edit.php?event_id=' . $id,
4186
4187 'pages_photos_list' => 'photos_list.php?view_list=group_page',
4188 'groups_photos_list' => 'photos_list.php?view_list=group',
4189 'user_my_pages_photos_list' => 'photos_list.php?view_list=group_page&uid=' . $uid,
4190 'user_my_groups_photos_list' => 'photos_list.php?view_list=group&uid=' . $uid,
4191 'user_my_pages_vids_list' => 'vids_list.php?view_list=group_page&uid=' . $uid,
4192 'user_my_groups_vids_list' => 'vids_list.php?view_list=group&uid=' . $uid,
4193
4194 'pages_vids_list' => 'vids_list.php?view_list=group_page',
4195 'groups_vids_list' => 'vids_list.php?view_list=group',
4196
4197 'user_blogs_list' => 'blogs_list.php?uid=' . $uid,
4198
4199 'blog_edit' => 'blog_add.php?blog_id=' . $uid,
4200
4201 'blogs_post_liked' => 'search_results.php?show=blogs_post_liked&blog_id=' . get_param_int('blog_id', $id),
4202 'blogs_post_liked_comment' => 'search_results.php?show=blogs_post_liked_comment&comment_id=' . get_param_int('comment_id', $id),
4203
4204 'street_chat' => 'city.php?place=street_chat',
4205 );
4206 if ($id && in_array($page, array('calendar', 'task_create', 'task_my_create', 'user_calendar', 'user_my_calendar'))) {
4207 $delimiter = '&';
4208 if ($page == 'calendar') {
4209 $delimiter = '?';
4210 }
4211 $urls[$page] .= $delimiter . 'date=' . $id;
4212 } elseif (in_array($page, array('group_photos_list', 'group_vids_list', 'group_page_liked', 'group_subscribers'))) {
4213 $typeGroupParam = Groups::getTypeParam($uid);
4214 if ($typeGroupParam) {
4215 $pagesGroupUrl = array('group_photos_list' => 'photos_list.php',
4216 'group_vids_list' => 'vids_list.php',
4217 'group_page_liked' => 'groups_social_subscribers.php',
4218 'group_subscribers' => 'groups_social_subscribers.php',
4219 'group_block_list' => 'groups_social_block_list.php');
4220 if (isset($pagesGroupUrl[$page])) {
4221 $urlGroupParam = '?group_id=' . $uid . '&' . $typeGroupParam;
4222 $urls[$page] = $pagesGroupUrl[$page] . $urlGroupParam;
4223 }
4224 }
4225 }
4226
4227 if (Common::isMobile()) {
4228 $urls['profile_boost'] = 'upgrade.php?action=refill_credits&service=search';
4229 $urls['whom_you_like'] = 'mutual_attractions.php?display=whom_you_like';
4230 $urls['who_likes_you'] = 'mutual_attractions.php?display=who_likes_you';
4231 }
4232
4233 $result = isset($urls[$page]) ? $urls[$page] : $page . '.php';
4234 }
4235
4236 if ($params !== null && !$paramsAddSymbol) {
4237 $paramsAddSymbol = mb_strpos($result, '?', 0, 'UTF-8') === false ? '?' : '&';
4238 }
4239
4240 $result .= $params ? $paramsAddSymbol . http_build_query($params) : '';
4241
4242 return $result;
4243 }
4244
4245 static public function ageToDate($age, $maxDate = false)
4246 {
4247 //$baseDate = strtotime('2016-12-31');
4248 //$baseDate = strtotime('2016-01-01');
4249 //$baseDate = strtotime('2016-03-29');
4250 //$baseDate = strtotime('2016-03-31');
4251 //$baseDate = strtotime('2016-02-29');
4252 //$baseDate = strtotime('2016-02-28');
4253 $baseDate = time();
4254 $today = date('m-d', $baseDate);
4255 $date = new DateTime(date('Y-m-d', $baseDate));
4256
4257 $age = intval($age);
4258 if($age < 0) {
4259 $age = 0;
4260 }
4261
4262 if($maxDate) {
4263 $age++;
4264 }
4265
4266 $date->sub(new DateInterval('P' . $age . 'Y'));
4267
4268 if($maxDate) {
4269 if($today != '02-29' || $date->format('m-d') == '02-29') {
4270 $date->add(new DateInterval('P1D'));
4271 }
4272 } else {
4273 if($today == '02-29' && $date->format('m-d') != '02-29') {
4274 $date->sub(new DateInterval('P1D'));
4275 }
4276 }
4277
4278 return $date->format('Y-m-d');
4279 }
4280
4281 static public function getSearchOrderNear()
4282 {
4283 if(Users_List::isBigBase()) {
4284 $orderNear = '';
4285 } else {
4286 $orderNear = ' near DESC, ';
4287 }
4288
4289 return $orderNear;
4290 }
4291
4292 static public function prepareSearchWhereOrderByPhoto(&$where, &$order)
4293 {
4294 if(Users_List::isBigBase()) {
4295 $where .= " AND is_photo = 'Y' ";
4296 } else {
4297 $order = "is_photo = 'Y' DESC, ";
4298 }
4299 }
4300
4301 static public function prepareSearchWhereOrderByIAmHereTo(&$where, &$order, $value)
4302 {
4303 if(Users_List::isBigBase()) {
4304 $where .= ' AND u.i_am_here_to = ' . to_sql($value) . ' ';
4305 } else {
4306 $order .= 'i_am_here_to = ' . to_sql($value) . ' DESC, ';
4307 }
4308 }
4309
4310 static public function checkAreaLogin($toLogin = true)
4311 {
4312 global $p;
4313 $result = true;
4314 if (!guid()) {
4315 $area = Common::getOption('area_login', 'template_options');
4316 if ($area) {
4317 $result = !in_array($p, $area);
4318 }
4319 }
4320 if ($toLogin && !$result) {
4321 Common::toLoginPage();
4322 }
4323 return $result;
4324 }
4325
4326 static function getBlockIntoWhichAddPart($namePart)
4327 {
4328 $blockAdd = 'page';
4329 $blockAddTmpl = Common::getOption("block_add_{$namePart}", 'template_options');
4330 if ($blockAddTmpl) {
4331 $blockAdd = $blockAddTmpl;
4332 }
4333 return $blockAdd;
4334 }
4335
4336 static function allowedFeatureSuperPowersFromTemplate($feature)
4337 {
4338 $allowedFeatures = Common::getOption('feature_super_powers_allowed', 'template_options');
4339 if (is_array($allowedFeatures)) {
4340 return in_array($feature, $allowedFeatures);
4341 } else {
4342 return false;
4343 }
4344 }
4345
4346 static function mainPageSetRandomImage()
4347 {
4348 global $g;
4349
4350 $isRandomImageActive = false;
4351
4352 $tmplName = Common::getTmplName();
4353
4354 if(Common::getTmplSet() == 'urban') {
4355 if( (($tmplName != 'edge') && Common::isOptionActive('map_on_main_page_urban', 'template_options') && ('random_image' == Common::getOption('map_on_main_page_urban'))) || ($tmplName == 'edge' && ('random_image' == Common::getOption('main_page_background_type', 'edge_color_scheme_visitor'))) ) {
4356 $isRandomImageActive = true;
4357 }
4358 }
4359
4360 if ($isRandomImageActive) {
4361 $dir = Common::getOption('dir_tmpl_main', 'tmpl') . 'images/main_page_image';
4362 if (file_exists($dir)){
4363 $optionsArray = readAllFileArrayOfDir($dir, '');
4364 $dir = Common::getOption('url_files', 'path') . 'tmpl';
4365 $templateFile = Common::getOption('tmpl_loaded', 'tmpl') . '_main_page_image_';
4366 $optionsArray += readAllFileArrayOfDir($dir,'', '', $templateFile);
4367 if (!empty($optionsArray)){
4368 $rand_file = array_rand($optionsArray);
4369 $image = getFileUrl('main_page_image', $rand_file, '_main_page_image_', 'image_main_page_urban', 'main_page_image_default_urban');
4370 if (file_exists($image)){
4371 $g['options']['image_main_page_urban'] = $rand_file;
4372 $g['options']['image_main_page_impact'] = $rand_file;
4373 $g['edge_color_scheme_visitor']['main_page_image'] = $rand_file;
4374 if($tmplName == 'urban') {
4375 $infoImage = getimagesize($image);
4376 $g['options']['image_main_page_height_urban'] = $infoImage[1];
4377 }
4378 }
4379 }
4380 }
4381 }
4382 }
4383
4384 static function impactGetMapOnMainPageUrbanValue($value)
4385 {
4386 $allowValues = array('image', 'random_image', 'video');
4387
4388 if(!in_array($value, $allowValues)) {
4389 $value = 'image';
4390 }
4391
4392 return $value;
4393 }
4394
4395 static public function isCountryHidden($countryId, $dbIndex = DB_MAX_INDEX)
4396 {
4397 $sql = 'SELECT hidden FROM geo_country
4398 WHERE country_id = ' . to_sql($countryId);
4399 return DB::result($sql, 0, $dbIndex);
4400 }
4401
4402 static public function isStateHidden($stateId, $dbIndex = DB_MAX_INDEX)
4403 {
4404 $sql = 'SELECT hidden FROM geo_state
4405 WHERE state_id = ' . to_sql($stateId);
4406 return DB::result($sql, 0, $dbIndex);
4407 }
4408
4409 static public function isCityHidden($cityId, $dbIndex = DB_MAX_INDEX)
4410 {
4411 $sql = 'SELECT hidden FROM geo_city
4412 WHERE city_id = ' . to_sql($cityId);
4413 return DB::result($sql, 0, $dbIndex);
4414 }
4415
4416 static public function getFirstStateInCountry($countryId, $dbIndex = DB_MAX_INDEX)
4417 {
4418 $sql = 'SELECT * FROM geo_state
4419 WHERE country_id = ' . to_sql($countryId) . '
4420 AND hidden = 0
4421 ORDER BY state_id ASC
4422 LIMIT 1';
4423 return DB::row($sql, $dbIndex);
4424 }
4425
4426 static public function getFirstCityInState($stateId, $dbIndex = DB_MAX_INDEX)
4427 {
4428 $sql = 'SELECT * FROM geo_city
4429 WHERE state_id = ' . to_sql($stateId) . '
4430 AND hidden = 0
4431 ORDER BY city_id ASC
4432 LIMIT 1';
4433 return DB::row($sql, $dbIndex);
4434 }
4435
4436 static public function getBackgroundColorSheme($option, $prf = 'impact', $module = 'options')
4437 {
4438 if ($prf) {
4439 $prf = '_' . $prf;
4440 }
4441 $type = Common::getOption("{$option}_type{$prf}", $module);
4442 if ($type == 'color') {
4443 return Common::getOption("{$option}_color{$prf}", $module);
4444 } else {
4445 $colorDirection = Common::getOption("{$option}_color_direction{$prf}", $module);
4446 $colorUpper = Common::getOption("{$option}_color_upper{$prf}", $module);
4447 $colorUpperStop = intval(Common::getOption("{$option}_color_upper_stop{$prf}", $module));
4448 $colorLower = Common::getOption("{$option}_color_lower{$prf}", $module);
4449 $colorLowerStop = intval(Common::getOption("{$option}_color_lower_stop{$prf}", $module));
4450 return "linear-gradient(to {$colorDirection}, {$colorUpper} $colorUpperStop%, {$colorLower} $colorLowerStop%)";
4451 }
4452 }
4453
4454 static public function getAllowedOptionsJs()
4455 {
4456 $optionTemplateName = Common::getTmplName();
4457 $allowedOptions = array(
4458 'options' => array(
4459 'hide_im_on_page_city',
4460 'number_of_columns_in_language_selector',
4461 'message_notifications_not_show_when_3d_city',
4462 'forced_open_chat_with_new_message',
4463 'photo_approval'
4464 )
4465 );
4466
4467 if ($optionTemplateName == 'edge') {
4468 $allowedOptions = array(
4469 'edge_member_settings' => array(
4470 'show_your_photo_browse_photos',
4471 'show_your_video_browse_videos'
4472 ),
4473 'options' => array(
4474 'seo_friendly_urls'
4475 ),
4476 'edge_gallery_settings' => array(
4477 'gallery_show_download_original'
4478 ),
4479 'edge_events_settings' => array(
4480 'first_day_week'
4481 ),
4482 );
4483 }
4484 $result = array();
4485 foreach ($allowedOptions as $key => $options) {
4486 $result[$key] = array();
4487 foreach ($options as $option) {
4488 $value = Common::getOption($option, $key);
4489 if ($option == 'forced_open_chat_with_new_message') {
4490 $value = IS_DEMO ? 'Y' : 'N';
4491 }
4492 if ($value && !is_array($value)) {
4493 $result[$key][$option] = is_string($value) ? toJs($value) : intval($value);
4494 }
4495 }
4496 }
4497 return json_encode($result);
4498 }
4499
4500 static function isPage($page, $isMyProfile = false)
4501 {
4502 global $p;
4503
4504 $isPage = false;
4505
4506 $display = get_param('display');
4507 $show = get_param('show');
4508 $paramUid = User::getParamUid(0);//get_param('uid');
4509 $paramTypeGroup = get_param('view');
4510 $paramIsGroupPage = $paramTypeGroup == 'group_page';
4511
4512 $uid = User::getParamUid();
4513 $cmd = get_param('cmd');
4514 $guid = guid();
4515 $viewList = get_param('view_list');
4516 if ($page == 'profile_view') {
4517 $isPage = $p == 'profile_view.php'
4518 || ($p == 'search_results.php' && ($display == 'profile' && $guid == $uid));
4519 } elseif ($page == 'profile') {
4520 $isPage = $p == 'profile_view.php'
4521 || ($p == 'search_results.php' && $display == 'profile');
4522 } elseif ($page == 'search_results') {
4523 $isPage = $p == 'search_results.php' && !$display && !$show;
4524 } elseif ($page == 'user_vids_list' || $page == 'group_vids_list') {
4525 $isPage = $p == 'vids_list.php' && $paramUid && !$viewList;
4526 } elseif ($page == 'user_my_vids_list') {
4527 $isPage = $p == 'vids_list.php' && $guid == $paramUid && !$viewList;
4528
4529 } elseif ($page == 'vids_list') {
4530 $isPage = $p == 'vids_list.php' && !$paramUid && !$viewList;
4531 } elseif ($page == 'pages_vids_list') {
4532 $isPage = $p == 'vids_list.php' && $viewList == 'group_page' && !$paramUid;
4533 } elseif ($page == 'groups_vids_list') {
4534 $isPage = $p == 'vids_list.php' && $viewList == 'group' && !$paramUid;
4535 } elseif ($page == 'user_my_pages_vids_list') {
4536 $isPage = $p == 'vids_list.php' && $viewList == 'group_page' && $paramUid == $guid;
4537 } elseif ($page == 'user_my_groups_vids_list') {
4538 $isPage = $p == 'vids_list.php' && $viewList == 'group' && $paramUid == $guid;
4539 } elseif ($page == 'user_photos_list' || $page == 'group_photos_list') {
4540 $isPage = $p == 'photos_list.php' && $paramUid && !$viewList;
4541 } elseif ($page == 'user_my_photos_list') {
4542 $isPage = $p == 'photos_list.php' && $guid == $paramUid && !$viewList;
4543 } elseif ($page == 'photos_list') {
4544 $isPage = $p == 'photos_list.php' && !$paramUid && !$viewList;
4545 } elseif ($page == 'pages_photos_list') {
4546 $isPage = $p == 'photos_list.php' && $viewList == 'group_page' && !$paramUid;
4547 } elseif ($page == 'groups_photos_list') {
4548 $isPage = $p == 'photos_list.php' && $viewList == 'group' && !$paramUid;
4549 } elseif ($page == 'user_my_pages_photos_list') {
4550 $isPage = $p == 'photos_list.php' && $viewList == 'group_page' && $paramUid == $guid;
4551 } elseif ($page == 'user_my_groups_photos_list') {
4552 $isPage = $p == 'photos_list.php' && $viewList == 'group' && $paramUid == $guid;
4553
4554 } elseif ($page == 'user_friends_list') {
4555 $isPage = $p == 'friends_list.php' && get_param('show', 'all') == 'all';
4556 //} elseif ($page == 'friends_list') {
4557 // $isPage = $p == 'my_friends.php' && $guid == $uid && get_param('show', 'all') == 'all';
4558 } elseif ($page == 'my_friends_online') {
4559 $isPage = $p == 'friends_list_online.php';
4560 } elseif ($page == 'wall') {
4561 $isPage = $p == 'wall.php' && !get_param_int('item');
4562 /* Groups */
4563 } elseif ($page == 'group_add') {
4564 $isPage = $p == 'group_add.php' && !$paramTypeGroup;
4565 } elseif ($page == 'groups_list') {
4566 $isPage = $p == 'groups_list.php' && !$paramIsGroupPage && !$paramUid;
4567 } elseif ($page == 'user_my_groups_list') {
4568 $isPage = $p == 'groups_list.php' && !$paramIsGroupPage && $guid == $paramUid;
4569 } elseif ($page == 'user_groups_list') {
4570 $isPage = $p == 'groups_list.php' && !$paramIsGroupPage && $paramUid;
4571 /* Groups */
4572 /* Pages */
4573 } elseif ($page == 'page_add') {
4574 $isPage = $p == 'group_add.php' && $paramIsGroupPage && !$cmd;
4575 } elseif ($page == 'pages_list') {
4576 $isPage = $p == 'groups_list.php' && $paramIsGroupPage && !$paramUid;
4577 } elseif ($page == 'user_my_pages_list') {
4578 $isPage = $p == 'groups_list.php' && $paramIsGroupPage && $guid == $paramUid;
4579 } elseif ($page == 'user_pages_list') {
4580 $isPage = $p == 'groups_list.php' && $paramIsGroupPage && $paramUid;
4581 } elseif ($page == 'group_page_liked') {
4582 $isPage = $p == 'groups_social_subscribers.php';
4583 } elseif ($page == 'group_subscribers') {
4584 $isPage = $p == 'groups_social_subscribers.php';
4585 /* Pages */
4586 /* Blogs */
4587 } elseif ($page == 'blogs_list') {
4588 $isPage = $p == 'blogs_list.php' && !$paramUid;
4589 } elseif ($page == 'user_my_blogs_list') {
4590 $isPage = $p == 'blogs_list.php' && $guid == $paramUid;
4591 } elseif ($page == 'user_blogs_list') {
4592 $isPage = $p == 'blogs_list.php' && $paramUid;
4593 } elseif ($page == 'blogs_add') {
4594 $isPage = $p == 'blogs_add.php' && !get_param_int('blog_id');
4595 /* Blogs */
4596 } elseif ($page == 'user_my_calendar') {
4597 $isPage = $p == 'events_calendar.php' && $guid == $paramUid;
4598 } elseif ($page == 'user_calendar') {
4599 $isPage = $p == 'events_calendar.php' && $paramUid;
4600 } elseif ($page == 'task_my_create') {
4601 $isPage = $p == 'events_event_edit.php' && $uid == $guid && !get_param_int('event_id');
4602 } elseif ($page == 'task_create') {
4603 $isPage = $p == 'events_event_edit.php' && $paramUid && !get_param_int('event_id');
4604 } else {
4605 $isPage = $p == ($page . '.php');
4606 }
4607 if ($isMyProfile) {
4608 $isPage = $isPage && $guid == $uid;
4609 }
4610
4611 return $isPage;
4612 }
4613
4614 static function parseBackgroundImage(&$html, $module, $prf = '')
4615 {
4616 $option = 'main_page_image';
4617 $blockImage = "{$option}_pic{$prf}";
4618 if ($html->blockExists($blockImage)) {
4619 $bgImage = Common::getOption($option, $module);
4620 if($bgImage != 'no_image') {
4621 $image = getFileUrl($option, $bgImage, "_{$option}_", $option, "{$option}_default", 'main', $module);
4622 if ($image) {
4623 $html->setvar($blockImage, $image);
4624 $html->parse("{$blockImage}_head_js", false);
4625 $html->parse("{$blockImage}_js", false);
4626 if (Common::isOptionActive('main_page_image_darken', $module)) {
4627 $html->parse("{$blockImage}_darken", false);
4628 }
4629 $html->parse($blockImage, false);
4630 }
4631 }
4632 }
4633 }
4634
4635 static public function sendAutoMailApproveImageToAdmin()
4636 {
4637 if(Common::isOptionActive('photo_approval') && Common::isEnabledAutoMail('approve_image_admin')){
4638 $vars = array('name' => guser('name'));
4639 Common::sendAutomail(Common::getOption('administration', 'lang_value'), Common::getOption('info_mail', 'main'), 'approve_image_admin', $vars);
4640 }
4641 }
4642
4643 static public function getOptionUsersInfoPerPage()
4644 {
4645 $mOnPage = Common::getOptionTemplate('usersinfo_per_page');
4646 if ($mOnPage === 'number_of_profiles_in_the_search_results') {
4647 $mOnPage = Common::getOptionInt('number_of_profiles_in_the_search_results');
4648 }
4649 if (!intval($mOnPage)) {
4650 $mOnPage = 20;
4651 }
4652 return $mOnPage;
4653 }
4654
4655 static public function parseGdprCookie(&$html)
4656 {
4657 if ($html->blockExists('gdpr_cookie_popup')) {
4658 if (Common::isApp()) {
4659 $isParseCookiePopup = Common::isOptionActive('gdpr_cookie_consent_popup_app');
4660 } else {
4661 $isParseCookiePopup = Common::isOptionActive('gdpr_cookie_consent_popup');
4662 }
4663 if ($isParseCookiePopup) {
4664 $varsLink = array(
4665 'link_start' => '<a class="more_link" href="' . Common::pageUrl('privacy_policy') . '">',
4666 'link_end' => '</a>'
4667 );
4668 $html->setvar('cookies_accept_text', lSetVars('cookies_accept_text', $varsLink, 'toJsL'));
4669 $html->parse('gdpr_cookie_popup', false);
4670 }
4671 }
4672 }
4673
4674 static public function getFileFromStringParam($param)
4675 {
4676 $fileString = str_replace(' ', '+', get_param($param));
4677
4678 if($fileString) {
4679 $fileString = base64_decode($fileString);
4680 }
4681
4682 return $fileString;
4683 }
4684
4685 static public function isAdminSitePart()
4686 {
4687 global $sitePart;
4688 return isset($sitePart) && $sitePart === 'administration';
4689 }
4690
4691 static public function getGUserJs()
4692 {
4693 if (!guid()) {
4694 return json_encode(array());
4695 }
4696
4697 global $g_user;
4698
4699 $allowedOptions = array(
4700 'sound' => array('type' => 'check', 'value' => 1)
4701 );
4702
4703
4704 $result = array();
4705 foreach ($allowedOptions as $key => $option) {
4706 if ($option['type'] == 'check') {
4707 if (isset($g_user[$key])) {
4708 $result[$key] = $g_user[$key] == $option['value'];
4709 } else {
4710 $result[$key] = false;
4711 }
4712 }
4713 }
4714 return json_encode($result);
4715 }
4716
4717 static public function getAppIosApiVersion()
4718 {
4719 return intval(Common::getOption('api_version', 'app_ios'));
4720 }
4721
4722 static public function setPleaseChoose($value)
4723 {
4724 self::$lPleaseChoose = $value;
4725 }
4726
4727 static public function getPleaseChoose($clear = true)
4728 {
4729 $lPleaseChoose = l('please_choose');
4730 if (self::$lPleaseChoose) {
4731 $lPleaseChoose = self::$lPleaseChoose;
4732 }
4733 if ($clear) {
4734 self::clearPleaseChoose();
4735 }
4736 return $lPleaseChoose;
4737 }
4738
4739 static public function clearPleaseChoose()
4740 {
4741 self::$lPleaseChoose = '';
4742 }
4743
4744 static public function deleteTags($id, $type = '')
4745 {
4746 $tableTags = '';
4747 if ($type == 'video') {
4748 $tableTags = 'vids_tags';
4749 $tableTagsRelations = 'vids_tags_relations';
4750 $fieldRelationsId = 'video_id';
4751 } elseif ($type == 'photo') {
4752 $tableTags = 'photo_tags';
4753 $tableTagsRelations = 'photo_tags_relations';
4754 $fieldRelationsId = 'photo_id';
4755 } elseif ($type == 'blogs') {
4756 $tableTags = 'blogs_post_tags';
4757 $tableTagsRelations = 'blogs_post_tags_relations';
4758 $fieldRelationsId = 'blog_id';
4759 }
4760
4761 if (!$tableTags) {
4762 return;
4763 }
4764
4765 $sql = "SELECT TR.id, TR.tag_id, T.counter
4766 FROM `{$tableTagsRelations}` as TR
4767 LEFT JOIN `{$tableTags}` as T ON TR.tag_id = T.id
4768 WHERE TR.{$fieldRelationsId} = " . to_sql($id);
4769 $tags = DB::all($sql);
4770 if ($tags) {
4771 foreach ($tags as $key => $tag) {
4772 $count = $tag['counter'] - 1;
4773 if ($count) {
4774 DB::update($tableTags, array('counter' => $count), '`id` = ' . to_sql($tag['tag_id']));
4775 } else {
4776 DB::delete($tableTags, '`id` = ' . to_sql($tag['tag_id']));
4777 }
4778 DB::delete($tableTagsRelations, '`id` = ' . to_sql($tag['id']));
4779 }
4780 }
4781 }
4782}