'; print "

"; echo $cfg['GLOBAL']['lock_message']; print "

"; } exit; } } $num2letter=array(1=>'A',2=>'B',3=>'C',4=>'D',5=>'E',6=>'F',7=>'G',8=>'H',9=>'I',10=>'J',11=>'K',12=>'L',13=>'M',14=>'N',15=>'O',16=>'P',17=>'Q',18=>'R',19=>'S',20=>'T',21=>'U',22=>'V',23=>'W',24=>'X',25=>'Y',26=>'Z',27=>'AA',28=>'AB',29=>'AC',30=>'AD',31=>'AE',32=>'AF',33=>'AG',34=>'AH',35=>'AI',36=>'AJ',37=>'AK',38=>'AL',39=>'AM',40=>'AN',41=>'AO',42=>'AP',43=>'AQ',44=>'AR',45=>'AS',46=>'AT',47=>'AU',48=>'AV',49=>'AW',50=>'AX',51=>'AY',52=>'AZ',53=>'BA',54=>'BB',55=>'BC',56=>'BD',57=>'BE',58=>'BF',59=>'BG',60=>'BH',61=>'BI',62=>'BJ',63=>'BK',64=>'BL',65=>'BM',66=>'BN',67=>'BO',68=>'BP',69=>'BQ',70=>'BR',71=>'BS',72=>'BT',73=>'BU',74=>'BV',75=>'BW',76=>'BX',77=>'BY',78=>'BZ',79=>'CA',80=>'CB',81=>'CC',82=>'CD',83=>'CE',84=>'CF',85=>'CG',86=>'CH',87=>'CI',88=>'CJ',89=>'CK',90=>'CL',91=>'CM',92=>'CN',93=>'CO',94=>'CP',95=>'CQ',96=>'CR',97=>'CS',98=>'CT',99=>'CU',100=>'CV'); $officialTournamentModes=array(1,2,6,7,8,9,13,14,15,17,18); function getCookieDomain() { global $cfg; return ".".$cfg['GLOBAL']['domain']; } function strsize($string) { return mb_strlen($string,'latin1'); } $REMORE_ADDR=$_SERVER['REMOTE_ADDR']; $PHP_SELF=$_SERVER['PHP_SELF']; $QUERY_STRING=$_SERVER['QUERY_STRING']; Lock::$namespace = $project_name; $exp_user=array(1=>20,2=>60,3=>170,4=>350,5=>600,6=>1000,7=>2000,8=>4000,9=>8000,10=>16000,11=>32000,12=>64000,13=>128000,14=>256000,15=>512000,16=>1024000,17=>2048000,18=>4096000); $exp_player = Array( 1 => 5, 2 => 15, 3 => 30, 4 => 60, 5 => 100, 6 => 150, 7 => 200, 8 => 300, 9 => 400, 10 => 550, 11 => 750, 12 => 1000, 13 => 1500, 14 => 2000, 15 => 3000, 16 => 4000, 17 => 5500, 18 => 7500, 19 => 10000, 20 => 15000, 21 => 20000, 22 => 35000, 23 => 50000, 24 => 75000, 25 => 100000, 26 => 150000, 27 => 200000, 28 => 350000, 29 => 500000, 30 => 750000, 31 => 1000000, 32 => 1250000, 33 => 1500000, 34 => 1800000, 35 => 2100000, 36 => 2400000, 37 => 2700000, 38 => 3000000, 39 => 3500000, 40 => 4000000, 41 => 4800000, 42 => 5600000, 43 => 6400000, 44 => 7200000, 45 => 8000000, 46 => 8800000, 47 => 9600000, 48 => 10400000, 49 => 11200000, 50 => 12000000, 51 => 13500000, 52 => 15000000, 53 => 16500000, 54 => 18000000, 55 => 20000000, 56 => 22000000, 57 => 25000000, 58 => 28000000, 59 => 32000000, 60 => 37000000 ); $exp_gk = Array( 1 => 5, 2 => 10, 3 => 15, 4 => 20, 5 => 25, 6 => 30, 7 => 35, 8 => 40, 9 => 45, 10 => 50, 11 => 55, 12 => 60, 13 => 65, 14 => 70, 15 => 75, 16 => 80, 17 => 85, 18 => 90, 19 => 95, 20 => 100, 21 => 105, 22 => 110, 23 => 115, 24 => 120, 25 => 130, 26 => 140, 27 => 150, 28 => 160, 29 => 170, 30 => 180, 31 => 190, 32 => 200, 33 => 215, 34 => 230, 35 => 245, 36 => 260, 37 => 275, 38 => 290, 39 => 305, 40 => 320, 41 => 340, 42 => 360, 43 => 380, 44 => 400, 45 => 420, 46 => 440, 47 => 460, 48 => 480, 49 => 500, 50 => 520, 51 => 540, 52 => 560, 53 => 580, 54 => 600, 55 => 620, 56 => 640, 57 => 665, 58 => 690, 59 => 715, 60 => 740, 61 => 765, 62 => 790, 63 => 815, 64 => 840, 65 => 870, 66 => 900, 67 => 930, 68 => 960, 69 => 990, 70 => 1020, 71 => 1050, 72 => 1080, 73 => 1120, 74 => 1160, 75 => 1200, 76 => 1240, 77 => 1280, 78 => 1320, 79 => 1360, 80 => 1400, 81 => 1450, 82 => 1500, 83 => 1550, 84 => 1600, 85 => 1650, 86 => 1700, 87 => 1750, 88 => 1800, 89 => 1850, 90 => 1900, 91 => 1950, 92 => 2000, 93 => 2050, 94 => 2100, 95 => 2150, 96 => 2200, 97 => 2250, 98 => 2300, 99 => 2350, 100 => 2400, 101 => 2450, 102 => 2500, 103 => 2550, 104 => 2600, 105 => 2650, 106 => 2700, 107 => 2750, 108 => 2800, 109 => 2850, 110 => 2900, 111 => 2950, 112 => 3000, 113 => 3075, 114 => 3150, 115 => 3225, 116 => 3300, 117 => 3375, 118 => 3450, 119 => 3525, 120 => 3600, 121 => 3700, 122 => 3800, 123 => 3900, 124 => 4000, 125 => 4100, 126 => 4200, 127 => 4300, 128 => 4400, 129 => 4600, 130 => 4800, 131 => 5000, 132 => 5200, 133 => 5400, 134 => 5600, 135 => 5800, 136 => 6000, 137 => 6250, 138 => 6500, 139 => 6750, 140 => 7000, 141 => 7250, 142 => 7500, 143 => 7750, 144 => 8000, 145 => 8250, 146 => 8500, 147 => 8750, 148 => 9000, 149 => 9250, 150 => 9500, 151 => 9750, 152 => 10000, 153 => 10250, 154 => 10500, 155 => 10750, 156 => 11000, 157 => 11250, 158 => 11500, 159 => 12000, 160 => 12000, 161 => 12375, 162 => 12750, 163 => 13125, 164 => 13500, 165 => 13875, 166 => 14250, 167 => 14625, 168 => 15000, 169 => 15375, 170 => 15750, 171 => 16125, 172 => 16500, 173 => 16875, 174 => 17250, 175 => 17625, 176 => 18000, 177 => 18750, 178 => 19500, 179 => 20250, 180 => 21000, 181 => 21750, 182 => 22500, 183 => 23250, 184 => 24000, 185 => 24750, 186 => 25500, 187 => 26250, 188 => 27000, 189 => 27750, 190 => 28500, 191 => 29250, 192 => 30000, 193 => 30750, 194 => 31500, 195 => 32250, 196 => 33000, 197 => 33750, 198 => 34500, 199 => 35250, 200 => 36000, 201 => 37000, 202 => 38000, 203 => 39000, 204 => 40000, 205 => 41000, 206 => 42000, 207 => 43000, 208 => 44000, 209 => 45000, 210 => 46000, 211 => 47000, 212 => 48000, 213 => 49000, 214 => 50000, 215 => 51000, 216 => 52000, 217 => 53500, 218 => 55000, 219 => 56500, 220 => 58000, 221 => 59500, 222 => 61000, 223 => 62500, 224 => 64000, 225 => 65500, 226 => 67000, 227 => 68500, 228 => 70000, 229 => 71500, 230 => 73000, 231 => 74500, 232 => 76000, 233 => 77750, 234 => 79500, 235 => 81250, 236 => 83000, 237 => 84750, 238 => 86500, 239 => 88250, 240 => 90000, 241 => 91750, 242 => 93500, 243 => 95250, 244 => 97000, 245 => 98750, 246 => 100500, 247 => 102250, 248 => 104000, 249 => 106000, 250 => 108000, 251 => 110000, 252 => 112000, 253 => 114000, 254 => 116000, 255 => 118000, 256 => 120000, 257 => 122500, 258 => 125000, 259 => 127500, 260 => 130000, 261 => 132500, 262 => 135000, 263 => 137500, 264 => 140000, 265 => 143750, 266 => 147500, 267 => 151250, 268 => 155000, 269 => 158750, 270 => 162500, 271 => 166250, 272 => 170000, 273 => 175000, 274 => 180000, 275 => 185000, 276 => 190000, 277 => 195000, 278 => 200000, 279 => 205000, 280 => 210000, 281 => 216250, 282 => 222500, 283 => 228750, 284 => 235000, 285 => 241250, 286 => 247500, 287 => 253750, 288 => 260000, 289 => 267500, 290 => 275000, 291 => 282500, 292 => 290000, 293 => 297500, 294 => 305000, 295 => 312500, 296 => 320000, 297 => 330000, 298 => 340000, 299 => 350000, 300 => 360000, 301 => 370000, 302 => 380000, 303 => 390000, 304 => 400000, 305 => 412500, 306 => 425000, 307 => 437500, 308 => 450000, 309 => 462500, 310 => 475000, 311 => 487500, 312 => 500000, 313 => 518750, 314 => 537500, 315 => 556250, 316 => 575000, 317 => 593750, 318 => 612500, 319 => 631250, 320 => 650000, 321 => 675000, 322 => 700000, 323 => 725000, 324 => 750000, 325 => 775000, 326 => 800000, 327 => 825000, 328 => 850000, 329 => 881250, 330 => 912500, 331 => 943750, 332 => 975000, 333 => 1006250, 334 => 1037500, 335 => 1068750, 336 => 1100000, 337 => 1150000, 338 => 1200000, 339 => 1250000, 340 => 1300000, 341 => 1350000, 342 => 1400000, 343 => 1450000, 344 => 1500000, 345 => 1562500, 346 => 1625000, 347 => 1687500, 348 => 1750000, 349 => 1812500, 350 => 1875000, 351 => 1937500, 352 => 2000000, 353 => 2075000, 354 => 2150000, 355 => 2225000, 356 => 2300000, 357 => 2375000, 358 => 2450000, 359 => 2525000, 360 => 2600000, 361 => 2687500, 362 => 2775000, 363 => 2862500, 364 => 2950000, 365 => 3037500, 366 => 3125000, 367 => 3212500, 368 => 3300000, 369 => 3400000, 370 => 3500000, 371 => 3600000, 372 => 3700000, 373 => 3800000, 374 => 3900000, 375 => 4000000, 376 => 4100000, 377 => 4212500, 378 => 4325000, 379 => 4437500, 380 => 4550000, 381 => 4662500, 382 => 4775000, 383 => 4887500, 384 => 5000000, 385 => 5125000, 386 => 5250000, 387 => 5375000, 388 => 5500000, 389 => 5625000, 390 => 5750000, 391 => 5875000, 392 => 6000000, 393 => 6250000, 394 => 6500000, 395 => 6750000, 396 => 7000000, 397 => 7250000, 398 => 7500000, 399 => 7750000, 400 => 8000000, 401 => 8500000, 402 => 9000000, 403 => 9500000, 404 => 10000000, 405 => 10500000, 406 => 11000000, 407 => 11500000, 408 => 12000000, 409 => 12500000, 410 => 13000000, 411 => 14000000, 412 => 15000000, 413 => 16000000, 414 => 17000000, 415 => 18000000, 416 => 19000000, 417 => 20000000, 418 => 21000000, 419 => 22000000, 420 => 23000000, 421 => 25000000, 422 => 27000000, 423 => 29000000, 424 => 31000000, 425 => 33000000, 426 => 35000000, 427 => 37000000, 428 => 39000000, 429 => 41000000, 430 => 43000000, 431 => 46000000, 432 => 49000000, 433 => 52000000, 434 => 55000000, 435 => 58000000, 436 => 61000000, 437 => 64000000, 438 => 67000000, 439 => 70000000, 440 => 73000000, 441 => 77000000, 442 => 81000000, 443 => 85000000, 444 => 89000000, 445 => 93000000, 446 => 97000000, 447 => 101000000, 448 => 105000000, 449 => 109000000, 450 => 113000000, 451 => 118000000, 452 => 123000000, 453 => 128000000, 454 => 133000000, 455 => 138000000, 456 => 143000000, 457 => 148000000, 458 => 153000000, 459 => 158000000, 460 => 163000000, 461 => 169000000, 462 => 175000000, 463 => 181000000, 464 => 187000000, 465 => 193000000, 466 => 199000000, 467 => 205000000, 468 => 211000000, 469 => 217000000, 470 => 223000000, 471 => 230000000, 472 => 237000000, 473 => 244000000, 474 => 251000000, 475 => 258000000, 476 => 265000000, 477 => 272000000, 478 => 279000000, 479 => 286000000, 480 => 293000000 ); $ab_array=array('Tck','Mrk','Drb','Rcv','Edu','Pas','Shp','Sha'); function get_practice_name() { $practice_name = Array( 1 => message("egypt", "Египет", "Egypt"), 2 => message("cyprus", "Кипр", "Cyprus"), 3 => message("israel", "Израиль", "Israel"), 4 => message("spain", "Испания", "Spain"), 5 => message("emirates", "ОАЭ", "UAE") ); return $practice_name; } function drawBlitzGroup($groupID, $divisionID, $full_nick) { global $auth; $practice_name = get_practice_name(); $width = $full_nick ? '' : '162' ; $padding = $full_nick ? '5' : '2' ; $rewards = Consts::$BLITZ_REWARDS[$divisionID]; if ($full_nick) $group = runsql("select u.Login FullNick, r.UserID, r.Points from top_rating r left outer join rt_users u on r.UserID = u.UserID where GroupID=$groupID and DivisionID=$divisionID order by Points desc"); else $group = runsql("select concat('',Login,'') FullNick, r.UserID, r.Points from top_rating r where GroupID=$groupID and DivisionID=$divisionID order by Points desc"); $place = 1; echo ""; echo $full_nick ? '' : ""; while ($user = mysql_fetch_array($group)) { $bgcolor = ($place%2) ? "f3f3f3" : "ffffff" ; $style = ($user['UserID']==$auth->user) ? " style='font-weight: bold;' " : "" ; echo ""; $place++; } echo "
№'.message('user','Пользователь').''.message('points','Очки').'
"; echo $rewards[$place] ? "" : $place ; echo "$user[FullNick]$user[Points]
"; } function sessionStartEx() { global $cfg; if ($cfg['MC']['enabled']) { //TODO: Добавить проверку extension_loaded if ($cfg['MC']['memcached']) { ini_set('session.save_handler', 'memcached'); ini_set('session.save_path', $cfg['MC']['host'] . ":" . $cfg['MC']['port']); ini_set('session.cookie_domain', getCookieDomain()); } else { ini_set('session.save_handler', 'memcache'); ini_set('session.save_path', "tcp://" . $cfg['MC']['host'] . ":" . $cfg['MC']['port']); ini_set('session.cookie_domain', getCookieDomain()); } } session_start(); } function userGetPlayerTrainer($userID,$playerID,$rst = null) { $rst = ($rst === null) ? read_rst($userID) : $rst; if ($rst['Players'][$playerID]['Position']=='Gk') $result = in_array($playerID,$rst['PersonalCoach']) ? 4 : $rst['Staff'][5] ; else $result = in_array($playerID,$rst['PersonalCoach']) ? 4 : $rst['Staff'][1] ; $result = $result ? $result : 0 ; return $result; } /* function playerGetSkillMax($player,$trainer) { $a = Array(120,144,184,200,240); $result = $a[$trainer]; $data = GET_STAR_DATA(); $result = playerIsStar($player) ? $data[playerGetStarLevel($player)]['MaxSkl'] : $result; return $result; } function playerGetAbilityMax($player,$trainer) { $a = Array(15,18,23,25,30); $result = $a[$trainer]; $data = GET_STAR_DATA(); $result = playerIsStar($player) ? $data[playerGetStarLevel($player)]['Skl'] : $result; return $result; } */ function playerGetSkillMax($player, $trainer, $abilityID = -1) { $a = Array(120, 144, 184, 200, 240); $result = $a[$trainer]; if (playerIsStar($player)) { $data = GET_STAR_DATA(); $result = $data[playerGetStarLevel($player)]['MaxSkl']; $userID = $player['UserID']; $playerID = $player['ID']; if (($abilityID != -1) && select("select * from ut_arts where ArtID=13 and UserID=$userID and OperationObject=$playerID and Value=$abilityID and ActivationDate+Time>unix_timestamp()")) { $result = max(480, $result); } } return $result; } function playerGetAbilityMax($player, $trainer, $abilityID = -1) { $a = Array(15, 18, 23, 25, 30); $result = $a[$trainer]; if (playerIsStar($player)) { $data = GET_STAR_DATA(); $result = $data[playerGetStarLevel($player)]['Skl']; $userID = $player['UserID']; $playerID = $player['ID']; if (($abilityID != -1) && select("select * from ut_arts where ArtID=13 and UserID=$userID and OperationObject=$playerID and Value=$abilityID and ActivationDate+Time>unix_timestamp()")) { $result = max(60, $result); } } return $result; } function playerGetName($player) { global $lang; return ($lang=='rus') ? $player['Name_rus'] : $player['Name_eng'] ; } function playerGetSkill($player) { return ($player['Position']=='Gk') ? $player['Skl'] : $player['Tck']+$player['Mrk']+$player['Drb']+$player['Rcv']+$player['Edu']+$player['Pas']+$player['Shp']+$player['Sha'] ; } function userGetPower($userID, $rst = null) { $rst = ($rst === null) ? read_rst($userID) : $rst; $goalkeepers = Array(); $players = Array(); foreach ($rst['Players'] as $playerID => $player) { if ($player['Position'] == 'Gk') $goalkeepers[$playerID] = playerGetSkill($player); else $players[$playerID] = playerGetSkill($player); } arsort($goalkeepers); $goalkeepers = array_slice($goalkeepers, 0, 1); arsort($players); $players = array_slice($players, 0, 10); return array_sum($goalkeepers)+array_sum($players); } /* function playerGetPrice($player,$trainer = 0) { return ($player['Date']>1379361600) ? playerGetPriceNew($player,$trainer) : playerGetPriceOld($player,$trainer); } */ function playerGetPrice($player, $trainer = 0) { $price = ($player['Date'] > 1377108000) ? playerGetPriceNew($player, $trainer) : playerGetPriceOld($player, $trainer); $price = min(2600000000,$price); return $price; } function playerGetPriceOld($player,$trainer = 0) { global $exp_gk,$exp_player; if ($player['Position']=='Gk') { $sum = 0; $sum_exp_gk = Array(); foreach ($exp_gk as $key => $value) { $sum += $value; $sum_exp_gk[$key] = $sum; } $exp = $player['Exp'] + $sum_exp_gk[$player['Skl']]; foreach ($sum_exp_gk as $key => $value) if ($value>$exp) break; $max = max($sum_exp_gk); $exp = min($exp,$max); $player['Skl'] = ($exp-$sum_exp_gk[$key-1])/($sum_exp_gk[$key]-$sum_exp_gk[$key-1])+($key-1); $player['Skl'] = min(240,$player['Skl']); } else { $sum = 0; $sum_exp_player = Array(); foreach ($exp_player as $key => $value) { $sum += $value; $sum_exp_player[$key] = $sum; } $exp = $player['Exp']+$sum_exp_player[$player['Tck']]+$sum_exp_player[$player['Mrk']]+$sum_exp_player[$player['Drb']]+$sum_exp_player[$player['Rcv']]+$sum_exp_player[$player['Edu']]+$sum_exp_player[$player['Pas']]+$sum_exp_player[$player['Shp']]+$sum_exp_player[$player['Sha']]; $exp /= 8; foreach ($sum_exp_player as $key => $value) if ($value>$exp) break; $max = max($sum_exp_player); $exp = min($exp,$max); $player['Skl'] = ($exp-$sum_exp_player[$key-1])/($sum_exp_player[$key]-$sum_exp_player[$key-1])+($key-1); $player['Skl'] = min(30,$player['Skl']); $player['Skl'] *= 8; } $price = round(3*(pow(1.18,($player['Skl']-8)/5)*(12/(10-$player['Talent'])-1)*1.5*exp(($player['Age']-23)*($player['Age']-23)/-200)*100)); return $price; } function playerGetPriceNew($player,$trainer = 0) { global $exp_gk,$exp_player; if ($player['Position']=='Gk') { $sum = 0; $sum_exp_gk = Array(); foreach ($exp_gk as $key => $value) { $sum += $value; $sum_exp_gk[$key] = $sum; } $exp = $player['Exp'] + $sum_exp_gk[$player['Skl']]; foreach ($sum_exp_gk as $key => $value) if ($value>$exp) break; $max = max($sum_exp_gk); $exp = min($exp,$max); //$max = max(playerGetSkillMax($player,$trainer),$player['Skl']); $max = playerIsStar($player) ? playerGetSkillMax($player, $trainer) : max(playerGetSkillMax($player, $trainer), $player['Skl']); $skill = ($exp-$sum_exp_gk[$key-1])/($sum_exp_gk[$key]-$sum_exp_gk[$key-1])+($key-1); $skill = min($max,$skill); } else { $player['Skl'] = $player['Tck']+$player['Mrk']+$player['Drb']+$player['Rcv']+$player['Edu']+$player['Pas']+$player['Shp']+$player['Sha']; $sum = 0; $sum_exp_player = Array(); foreach ($exp_player as $key => $value) { $sum += $value; $sum_exp_player[$key] = $sum; } $exp = $player['Exp']+$sum_exp_player[$player['Tck']]+$sum_exp_player[$player['Mrk']]+$sum_exp_player[$player['Drb']]+$sum_exp_player[$player['Rcv']]+$sum_exp_player[$player['Edu']]+$sum_exp_player[$player['Pas']]+$sum_exp_player[$player['Shp']]+$sum_exp_player[$player['Sha']]; $exp /= 8; foreach ($sum_exp_player as $key => $value) if ($value>$exp) break; $max = max($sum_exp_player); $exp = min($exp,$max); //$max = max(8*playerGetAbilityMax($player,$trainer),$player['Skl']); $max = playerIsStar($player) ? 8 * playerGetAbilityMax($player, $trainer) : max(8 * playerGetAbilityMax($player, $trainer), $player['Skl']); $skill = ($exp-$sum_exp_player[$key-1])/($sum_exp_player[$key]-$sum_exp_player[$key-1])+($key-1); $skill = min($max,8*$skill); } $price = round(3*(pow(1.18,($skill-8)/5)*(12/(10-$player['Talent'])-1)*1.5*exp(($player['Age']-23)*($player['Age']-23)/-200)*100)); return $price; } function form_footer() { global $img_path; print " "; } function form_header($width = false, $padding = 20) { global $img_path; print "
"; } $PHP_SELF=$_SERVER['PHP_SELF']; $QUERY_STRING=$_SERVER['QUERY_STRING']; $project_name="11x11"; function pages() { global $form; print ""; $form->pages(''); print "
"; } function guildlogo($guild,$link) { global $img_path; $str=""; if($link) $str="$str"; return $str; } function guildGetMembersMaxCount($guildID) { //[!!!] MAX_INT return 16384; } function username($r,$link) { global $rang_types,$img_path; if($link) $login="".$r['Login'].""; else $login=$r['Login']; if($r['GuildID']&&$r['GuildStatusID']==1) $login=" ".$login; if($r['Rang']>0) { //if ($r[Rang]==1) $title="управляющий"; //elseif($r[Rang]==2) $title="директор"; //elseif($r[Rang]==3) $title="президент"; //elseif($r[Rang]==4) $title="олигарх"; $title="VIP-".$r['Rang']; $login=" ".$login; } if(!$r['Level']) $r['Level']=0; $login=$login." [".$r['Level']."]"; $wc=select("select w.TeamID from wc_teams w join wc_seasons s on s.SeasonID=w.SeasonID where w.TeamID='$r[UserID]' and s.StatusID<=2"); if($wc[0]) $w=" "; else $w=""; $login=$w.$login; $ec = select("select w.TeamID from ec_teams w join ec_seasons s on s.SeasonID=w.SeasonID where w.TeamID='$r[UserID]' and s.StatusID<=2"); $login = ($ec) ? " $login" : $login; return $login; } function deleteimage($image,$act) { global $site_path; if($act&&strstr($image,".jpg")) unlink($site_path."images/".$image); } // 0 - платные // 1 - бесплатные // 2 - все function userGetBonusCount($userID,$mode = 2) { list($bonusCount) = select("select Bonus from vp_bonus where UserID=$userID"); list($freeBonusCount) = select("select Bonus from vp_bonus2 where UserID=$userID"); switch ($mode) { case 0: return (float)$bonusCount - (float)$freeBonusCount; case 1: return (float)$freeBonusCount; case 2: return (float)$bonusCount; } } function getfile($filename) { global $site_path,$secpass,$PHP_SELF,$QUERY_STRING,$auth; define('FILE_READ_TIMEOUT',100000); if(!file_exists($filename)) return pack("l",strsize('')); $full_str=file_get_contents($filename); $md5=substr($full_str,7,32); $str=substr($full_str,39); for($i=0;$i<10;$i++) { if((!$str) || ($md5!=md5($str.$secpass)) ) { log_rst("[error] File incorrect md5 $filename ($id)"); usleep(FILE_READ_TIMEOUT); $full_str=file_get_contents($filename); $md5=substr($full_str,7,32); $str=substr($full_str,39); } } if($md5!=md5($str.$secpass)) return pack("l",strsize('')); return pack("l",strsize($full_str)).$full_str; } function make_stage_reward($tournamentID, $stageID, $userID) { if (!$stageID) { return; } list($tournamentTypeID, $number) = select("select TournamentTypeID,Number from ft_stages where StageID=$stageID"); $data = runsql("select sum(sr.Value) Value,sr.TypeID TypeID from ft_stage_rewards sr join ft_stages s on sr.StageID=s.StageID where TournamentTypeID=$tournamentTypeID and Number<=$number group by sr.TypeID"); while ($row = mysql_fetch_array($data)) { switch ($row['TypeID']) { case 1: list($guildID) = select("select if(GuildStatusID=1,GuildID,0) GuildID from ut_users where UserID=$userID"); if ($guildID) { } $cityID = userGetCityID($userID); runsql("insert into ft_glory(CityID,UserID,Points,Date,TournamentID,GuildID) values($cityID,'$userID','$row[Value]',unix_timestamp(),$tournamentID,coalesce((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$userID'),0))"); runsql("insert into ft_points(UserID,Points) values('$userID','$row[Value]') on duplicate key update Points=Points+'$row[Value]'"); if ($guildID) { runsql("insert into ft_guild_points(GuildID,Points) values('$guildID','$row[Value]') on duplicate key update Points=Points+'$row[Value]'"); } break; case 2: transfer_money($row['Value'], 1, $userID, OperationType::TOURNAMENT_MONEY, 0); break; case 3: transfer_bonus(1, $userID, $row['Value'], BonusType::TOURNAMENT_BONUS, false, 0); break; case 4: for ($i = 1; $i <= $row['Value']; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),2,86400,unix_timestamp()+10*86400)"); } break; case 5: for ($i = 1; $i <= $row['Value']; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date) values(2,$userID,unix_timestamp())"); } break; case 6: runsql("insert into free_combinations(UserID,Combinations) values($userID,$row[Value]) on duplicate key update Combinations=Combinations+$row[Value]"); break; case 7: runsql("insert into free_bonus(UserID,Bonus) values($userID,$row[Value]) on duplicate key update Bonus=Bonus+$row[Value]"); break; case 8: for ($i = 1; $i <= $row['Value']; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),3,86400,unix_timestamp()+10*86400)"); } break; case 9: for ($i = 1; $i <= $row['Value']; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value) values(3,$userID,unix_timestamp(),25000)"); } break; case 10: for ($i = 1; $i <= $row['Value']; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),4,12*3600,unix_timestamp()+10*86400)"); } break; case 11: for ($i = 1; $i <= $row['Value']; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),4,86400,unix_timestamp()+10*86400)"); } break; case 12: for ($i = 1; $i <= $row['Value']; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),5,6*3600,unix_timestamp()+10*86400)"); } break; case 13: for ($i = 1; $i <= $row['Value']; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),5,86400,unix_timestamp()+10*86400)"); } break; case 14: for ($i = 1; $i <= $number; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),6,6*3600,unix_timestamp()+10*86400)"); } break; case 15: for ($i = 1; $i <= $row['Value']; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),6,86400,unix_timestamp()+10*86400)"); } break; case 16: for ($i = 1; $i <= $row['Value']; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),5,3*3600,unix_timestamp()+10*86400)"); } break; case 17: for ($i = 1; $i <= $row['Value']; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),6,6*3600,unix_timestamp()+10*86400)"); } break; case 18: for ($i = 1; $i <= $row['Value']; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value) values(6,$userID,unix_timestamp(),30000)"); } break; case 19: lock_rst($userID); $rst = read_rst($userID); $rst['StarPoints'] += $row['Value']; write_rst($userID,$rst); unlock_rst($userID); runsql("insert into ut_arts(Date,ArtID,UserID,Value) values(unix_timestamp(),20,$userID,$row[Value])"); break; case 20: for ($i = 1; $i <= $row['Value']; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),8,6*3600,unix_timestamp()+10*86400)"); } break; case 21: for ($i = 1; $i <= $row['Value']; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),10,3*3600,unix_timestamp()+10*86400)"); } break; } } } function make_schedule($tournament) { global $stage,$id,$fights,$num; $id = $tournament; $q = select("select * from ft_tournaments where TournamentID='$id'"); if ($q['StatusID']!=0) return 0; if (!$q[0]) return 0; $numplayers = $q['NumPlayers']; $res = runsql("select * from ft_stages where TournamentTypeID='$q[TournamentTypeID]' order by Tour1"); if (!mysql_num_rows($res)) return false; $stage = 0; while ($r = mysql_fetch_array($res)) { $stage++; $res1 = runsql("select * from ft_reglaments where StageID='$r[StageID]' order by Num"); $numfights = mysql_num_rows($res1); $j = 1; while ($r1 = mysql_fetch_array($res1)) { $reg[$j] = $r1; $j++; } //выборка пользователей 1 //начальная выборка пользователей if ($r['Tour1']==1) { $res2 = runsql("select * from ft_tournament_members where TournamentID='$id' order by rand()"); for ($k = 1;$k<=$numplayers;$k++) { $r2 = mysql_fetch_array($res2); $users[$k] = $r2['UserID']; } } for ($i = $r['Tour1'];$i<=$r['Tour2'];$i++) { if ($r['TypeID']==0 && ($prevtype==$r['TypeID'] || !$prevtype)) { $p = 1; for ($k = 1;$k<=$numplayers;$k = $k+2) addfights(0,$p++,$i,$numfights,$reg,$k,$k+1,'',''); } elseif ($r['TypeID']==0 && $prevtype!=$r['TypeID']) { $p = 1; for ($k = 1;$k<=$numplayers;$k = $k+2) { $g1 = $k; $g2 = $k+1; if ($g1>$numplayers/2) $g1 = $numplayers-$g1+1; if ($g2>$numplayers/2) $g2 = $numplayers-$g2+1; addfights(0,$p++,$i,$numfights,$reg,$g1,$g2,1,2); } } elseif ($i==$r['Tour1'] && $r['TypeID']==1 && (!$prevtype)) { $numgroups = $numplayers/4; for ($g = 1;$g<=$numgroups;$g++) { $k = ($g-1)*4; runsql("insert into ft_groups(Stage,TournamentID,Name,Pair,Place) values('$stage','$id','$g','".($k+1)."','')"); runsql("insert into ft_groups(Stage,TournamentID,Name,Pair,Place) values('$stage','$id','$g','".($k+2)."','')"); runsql("insert into ft_groups(Stage,TournamentID,Name,Pair,Place) values('$stage','$id','$g','".($k+3)."','')"); runsql("insert into ft_groups(Stage,TournamentID,Name,Pair,Place) values('$stage','$id','$g','".($k+4)."','')"); addfights(1,$g,$i,$numfights,$reg,$k+2,$k+1,'',''); addfights(1,$g,$i,$numfights,$reg,$k+3,$k+4,'',''); addfights(1,$g,$i+1,$numfights,$reg,$k+1,$k+4,'',''); addfights(1,$g,$i+1,$numfights,$reg,$k+3,$k+2,'',''); addfights(1,$g,$i+2,$numfights,$reg,$k+4,$k+2,'',''); addfights(1,$g,$i+2,$numfights,$reg,$k+1,$k+3,'',''); } } elseif ($i==$r['Tour1'] && $r['TypeID']==1 && ($prevtype==$r['TypeID'])) { $numgroups = $numplayers/4; for ($g = 1;$g<=$numgroups;$g++) { $k = 1+($g-1)*2; $k2 = 1+($numgroups-$g)*2; runsql("insert into ft_groups(Stage,TournamentID,Name,Pair,Place) values('$stage','$id','$g','".($k)."',1)"); runsql("insert into ft_groups(Stage,TournamentID,Name,Pair,Place) values('$stage','$id','$g','".($k+1)."',1)"); runsql("insert into ft_groups(Stage,TournamentID,Name,Pair,Place) values('$stage','$id','$g','".($k2)."',2)"); runsql("insert into ft_groups(Stage,TournamentID,Name,Pair,Place) values('$stage','$id','$g','".($k2+1)."',2)"); addfights(1,$g,$i,$numfights,$reg,$k2+1,$k,'2','1'); addfights(1,$g,$i,$numfights,$reg,$k2,$k+1,'2','1'); addfights(1,$g,$i+1,$numfights,$reg,$k,$k2,'1','2'); addfights(1,$g,$i+1,$numfights,$reg,$k+1,$k2+1,'1','2'); addfights(1,$g,$i+2,$numfights,$reg,$k2,$k2+1,'2','2'); addfights(1,$g,$i+2,$numfights,$reg,$k,$k+1,'1','1'); } } elseif ($i==$r['Tour1'] && $r['TypeID']==1 && $prevtype!=$r['TypeID']) { $numgroups = $numplayers/4; for ($g = 1;$g<=$numgroups;$g++) { $k = ($g-1)*4; runsql("insert into ft_groups(Stage,TournamentID,Name,Pair) values('$stage','$id','$g','$k+1')"); runsql("insert into ft_groups(Stage,TournamentID,Name,Pair) values('$stage','$id','$g','$k+2')"); runsql("insert into ft_groups(Stage,TournamentID,Name,Pair) values('$stage','$id','$g','$k+3')"); runsql("insert into ft_groups(Stage,TournamentID,Name,Pair) values('$stage','$id','$g','$k+4')"); addfights(1,$g,$i,$numfights,$reg,$k+1,$k+2,'',''); addfights(1,$g,$i,$numfights,$reg,$k+3,$k+4,'',''); addfights(1,$g,$i+1,$numfights,$reg,$k+4,$k+1,'',''); addfights(1,$g,$i+1,$numfights,$reg,$k+2,$k+3,'',''); addfights(1,$g,$i+2,$numfights,$reg,$k+2,$k+4,'',''); addfights(1,$g,$i+2,$numfights,$reg,$k+1,$k+3,'',''); } } if ($r['TypeID']==0) $numplayers = $numplayers/2; $prevtype = $r['TypeID']; } if ($r['TypeID']==1) $numplayers = $numplayers/2; } } function addfights($typeid,$k,$i,$numfights,$reg,$p1,$p2,$place1,$place2) { global $id,$stage,$fights,$num; for ($j = 1; $j<=$numfights; $j++) { $r1 = $reg[$j]; $timeout = 5; runsql("insert into ft_tmp_agreements(TournamentID,Stage,Tour,Fight,Pair,UserID1,UserID2,TypeID,LimitSkl,Timeout,Approved,Date,StatusID,Pair1,Pair2,Place1,Place2,NumFights,StageTypeID) values ('$id','$stage','$i','$j','$k','$user1','$user2','$r1[TypeID]','$r1[SklLimit]','$timeout',0,unix_timestamp(),0,'$p1','$p2','$place1','$place2','$numfights','$typeid')"); $fights[$i][$j][$k] = $num++; } } function path($id) { $n1=floor($id/1000000); $n2=$id % 1000000; $n2=floor($n2/10000); $n3=$id % 10000; $n3=floor($n3/100); return "$n1/$n2/$n3"; } function gampath($id) { global $site_path; return $site_path."files/gam/".path($id); } function ordpath($id) { global $site_path; return $site_path."files/testord/".path($id); } function ord2path($id) { global $site_path; $ord2_path = $site_path."files/ord2/".path($id); System::forceDirectory($ord2_path); return $ord2_path; } function rstpath($id) { global $site_path; return $site_path."files/rst/".path($id); } function rstname($id) { global $site_path; return rstpath($id)."/".$id.".rst"; } function mirror_rstpath($id) { global $site_path; return $site_path."mirror/rst/".path($id); } function mirror_rstname($id) { global $site_path; return mirror_rstpath($id)."/".$id.".rst"; } function userSetExperienceLite(&$rst,$exp) { global $auth; $level = $rst['Level']; $levelExp = Consts::$LEVEL_EXPERIENCE[$level+1]; $exp = ( $levelExp || Consts::LEVEL_EXPERIENCE_OVERLOAD ) ? $exp : 0; $exp = floor($exp); $rst['LevelScores'] += $exp; if ($auth->user == $rst['UserID']) { $auth->rst['LevelScores'] = $rst['LevelScores']; $auth->exp = $rst['LevelScores']; } if ($levelExp && ($rst['LevelScores']>=$levelExp)) userSetLevelLite($rst,$level+1); } function userProcessReferal2($userID,$bonus) { list($referalUserID) = select("select ReferalID from ut_users where UserID=$userID"); if (!$referalUserID) return false; list($count,$bonus) = select("select count(*),sum(Bonus) from ut_referals where ReferalID=$referalUserID"); if ($count>=10 || $bonus>=50) return false; list($count,$bonus) = select("select count(*),sum(Bonus) from ut_referals where ReferalID=$referalUserID and UserID=$userID"); if ($count>=1 || $bonus>=5) return false; if (checkReferalOnMults($userID)) { lock_rst($referalUserID); $rst = read_rst($referalUserID); $rst['Messages'] .= PopupMessageType::REFERAL_MULT."|$userID,"; write_rst($referalUserID,$rst); unlock_rst($referalUserID); runsql("update ut_users set ReferalID=0 where UserID=$userID"); } else { transfer_bonus(1,$referalUserID,Consts::REFERAL_BONUS,BonusType::REFERAL_BONUS,true,$userID); runsql("insert into ut_referals(UserID,ReferalID,Date,Bonus) values($userID,$referalUserID,unix_timestamp(),".Consts::REFERAL_BONUS.")"); } } function userProcessReferalPayment($userID,$bonus) { if (time()<1411380000) return false; list($referalUserID) = select("select ReferalID from ut_users where UserID=$userID and Date>1411380000"); if (!$referalUserID) return false; if (checkReferalOnMults($userID)) { lock_rst($referalUserID); $rst = read_rst($referalUserID); $rst['Messages'] .= PopupMessageType::REFERAL_MULT."|$userID,"; write_rst($referalUserID,$rst); unlock_rst($referalUserID); runsql("update ut_users set ReferalID=0 where UserID=$userID"); } else { if ($bonus>0 && $bonus<=5) { switch (rand(0,1)) { case 0: runsql("insert into free_combinations(UserID,Combinations) values($referalUserID,1) on duplicate key update Combinations=Combinations+1"); break; case 1: runsql("insert into free_bonus(UserID,Bonus) values($referalUserID,1) on duplicate key update Bonus=Bonus+1"); break; } } elseif ($bonus>5 && $bonus<10) runsql("insert into ut_arts(UserID,ArtID,Date,Value,Time) values($referalUserID,1,unix_timestamp(),2,1800)"); else { $bonus = floor($bonus*0.1); transfer_bonus(1,$referalUserID,$bonus,BonusType::REFERAL_BONUS,false,$userID); } } } /* function userSetLevelLite(&$rst,$level) { global $auth,$cfg; $userID = $rst['UserID']; $rst['Level'] = $level; runsql("update ut_users set Level=$level where UserID=$userID"); runsql("insert into marketing_levels(UserID,Level,Date,Money) values ('$userID','$level',unix_timestamp(),(select coalesce(sum(Money),0) from vp_payments where UserID='$userID' and StatusID=1));"); $rst['Messages'] .= PopupMessageType::LEVEL_UP."|$level,"; if($cfg['GLOBAL']['domain_suffix']=="ru") { if (!select("select * from vp_payments where UserID=$userID and StatusID=1 limit 1")) { $_POST['From'] = 15; send_pm($userID,MailID::PERSONAL_CONSULTANT_LEVEL_UP); } } if ($level==1) { transfer_bonus(1,$userID,1,17,1); $rst['MoneyDate'] = time(); runsql("insert ignore into rg_start_money (UserID,MoneyDate) values ($userID,unix_timestamp())"); } if ($level == 1 || $level == 2 || $level == 3) { update_health($rst); foreach ($rst['Players'] as $k => $v) { $rst['Players'][$k]['Stamina'] = 100; } $rst['Date'] = time(); } if ($level == 2) { transfer_bonus(1, $userID, 5, 17, 1); $_POST['From'] = 15; send_pm($userID, MailID::PERSONAL_CONSULTANT_LEVEL_UP); } if ($level==3) userProcessReferal2($userID,5); if ($level==4 || $level==5) runsql("insert into ut_arts set Date=unix_timestamp(), ArtID=1, UserID='$userID', Value=3, Time=60*60*24"); if ($level == 13) { $rst['StarPoints'] += 5; runsql("insert into ut_arts(Date,ArtID,UserID,Value) values(unix_timestamp(),20,$userID,5)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),10,3*3600,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),10,3*3600,unix_timestamp()+30*86400)"); } if ($auth->user == $userID) { $auth->rst['Level'] = $level; $auth->updateLevel(); $auth->rst['Messages'] = $rst['Messages']; } System::dispatchEvent(new SystemEvent(SystemEvent::LEVEL_UP,Array($userID,$level))); } */ function userSetLevelLite(&$rst, $level) { global $auth, $cfg; $userID = $rst['UserID']; $rst['Level'] = $level; runsql("update ut_users set Level=$level where UserID=$userID"); runsql("insert into marketing_levels(UserID,Level,Date,Money) values ('$userID','$level',unix_timestamp(),(select coalesce(sum(Money),0) from vp_payments where UserID='$userID' and StatusID=1));"); $rst['Messages'] .= PopupMessageType::LEVEL_UP . "|$level,"; if ($level == Consts::REFERAL_LEVEL) { //userProcessReferal($userID); } if ($level == 1 || $level == 2 || $level == 3) { update_health($rst); foreach ($rst['Players'] as $k => $v) { $rst['Players'][$k]['Stamina'] = 100; } $rst['Date'] = time(); } if ($level == 1) { transfer_bonus(1, $userID, 1, 17, 1); $rst['MoneyDate'] = time(); runsql("insert ignore into rg_start_money (UserID,MoneyDate) values ($userID,unix_timestamp())"); } if ($level == 2) { transfer_bonus(1, $userID, 5, 17, 1); $_POST['From'] = 15; send_pm($userID, MailID::PERSONAL_CONSULTANT_LEVEL_UP); } if ($level == 3) { $rst = short_transfer_money($rst, 10000, 1, $userID, 24); } if ($level == 4) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),3,86400,unix_timestamp()+30*86400)"); runsql("insert into ut_free_practice(UserID,PracticeID,Date) values($userID,5,unix_timestamp())"); } if ($level == 5) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),3,86400,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(17,$userID,unix_timestamp(),0,0,unix_timestamp()+14*86400)"); } if ($level == 6) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),3,86400,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); } if ($level == 7) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),4,12*3600,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); } if ($level == 8) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),4,86400,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); } if ($level == 9) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),5,12*3600,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); } if ($level == 10) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),6,12*3600,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); } if ($level == 11) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),8,6*3600,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); } if ($level == 12) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),10,3*3600,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); } if ($level == 13) { $rst['StarPoints'] += 5; runsql("insert into ut_arts(Date,ArtID,UserID,Value) values(unix_timestamp(),20,$userID,5)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),10,3*3600,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),10,3*3600,unix_timestamp()+30*86400)"); } if ($level == 14) { $rst['StarPoints'] += 20; runsql("insert into ut_arts(Date,ArtID,UserID,Value) values(unix_timestamp(),20,$userID,20)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time) values(unix_timestamp(),3,$userID,25000,0)"); runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),10,3*3600,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),10,3*3600,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),10,3*3600,unix_timestamp()+30*86400)"); } if ($auth->user == $userID) { $auth->rst['Level'] = $level; $auth->updateLevel(); $auth->rst['Messages'] = $rst['Messages']; } System::dispatchEvent(new SystemEvent(SystemEvent::LEVEL_UP, Array($userID, $level))); } function userGetPracticeID($userID,$rst = null) { $rst = ($rst === null) ? read_rst($userID) : $rst; if ($rst['Practice']['ExpiresDate']>time()) return $rst['Practice']['PracticeID']; return false; } function userGetDegradation1($userID,$rst = null) { $rst = ($rst === null) ? read_rst($userID) : $rst; $count = $rst['QuestsHelpers']['DailyMatchesCount'][0]; $result = ($count<50) ? 1 : (10000 + 500*$count - 5*$count*$count)/22500 ; $result = max(0,$result); return $result; } function read_rst_bot($c,$skl) { $rst = read_rst(2); $l1 = Array(); $l2 = Array(); foreach ($rst['Players'] as $playerID => $player) { $player['Stamina'] = 100; $player['Morale'] = -5; $player['Injury'] = 0; $player['Tck'] = floor($skl/8); $player['Mrk'] = floor($skl/8); $player['Drb'] = floor($skl/8); $player['Rcv'] = floor($skl/8); $player['Edu'] = floor($skl/8); $player['Pas'] = floor($skl/8); $player['Shp'] = floor($skl/8); $player['Sha'] = floor($skl/8); $player['Skl'] = $player['Tck'] + $player['Mrk'] + $player['Drb'] + $player['Rcv'] + $player['Edu'] + $player['Pas'] + $player['Shp'] + $player['Sha']; if ($player['CountryID']==$c) $l1[$playerID] = $player; if ($player['CountryID']==23) $l2[$playerID] = $player; } $rst['Players'] = count($l1) ? $l1 : $l2 ; $rst['TrainDate'] = time(); $rst['Date'] = time(); $rst['StaffDate'] = time(); return $rst; } function userNormalizePlayers(&$rst) { global $ab_array; $userID = $rst['UserID']; $list = Array(); $arts_ = Array(); foreach ($rst['Players'] as $playerID => $player) { $list[] = $playerID; $arts_[$playerID] = array(); } $list = count($list) ? implode(',', $list) : 'null'; $data = runsql("select * from ut_arts where ArtID=13 and UserID=$userID and OperationObject in ($list) and ActivationDate+Time>unix_timestamp()"); while ($row = mysql_fetch_array($data)) { $playerID = $row['OperationObject']; $abilityID = $row['Value']; $arts_[$playerID][$abilityID] = true; } foreach ($rst['Players'] as $playerID => $player) { if (!playerIsStar($player)) { continue; } if (!$player['Boost']) { continue; } $player['UserID'] = $userID; $player['ID'] = $playerID; //[!!!] Мы не режем за увольнение тренера - мы режем только звезд - тренер не важен по сути $trainer = userGetPlayerTrainer($userID, $playerID, $rst); if ($player['Position'] == 'Gk') { $ability = 'Skl'; $abilityID = 0; $max_gk_skill = playerGetSkillMax($player, $trainer, $abilityID, array_key_exists($abilityID, $arts_[$playerID])); $player[$ability] = min($max_gk_skill, $player[$ability]); } else { foreach ($ab_array as $key2 => $ability) { $abilityID = $key2 + 1; $max_player_ability = playerGetAbilityMax($player, $trainer, $abilityID, array_key_exists($abilityID, $arts_[$playerID])); $player[$ability] = min($max_player_ability, $player[$ability]); } } $player['Skl'] = playerGetSkill($player); $rst['Players'][$playerID] = $player; } } function userFlush($userID) { //if ($userID!=12619733) //return; //return; lock_rst($userID); $roster = read_rst($userID); userNormalizePlayers($roster); //$roster = update_exp($roster); //$roster = update_health($roster); // $roster['Units'] = userGetUnits($userID,$roster['Date']); // $roster['Date'] = time(); write_rst($userID, $roster); unlock_rst($userID); } function generategame($id) { global $gladexplevels,$site_path,$secpass,$k,$serialized, $cfg; $path=gampath($id); System::forceDirectory($path); $fname=$path."/".$id.".gam"; $q=runsql("select a.Date+60*a.Timeout Date,a.UserID1,a.UserID2,a.TypeID MatchTypeID,a.LimitSkl,a.TournamentID,t.GuildID TournamentGuildID, if(m.TypeID=4,(select if(Place<=5,6, if(Place<=15,5, if(Place<=30,4,3))) Exp from rt_guildpoints where GuildID=t.GuildID),coalesce(m.Coefficient,1)) TournamentFactor,tt.TypeID ModeID,tt.BotSkl,a.Tour, if(a.TournamentID >0 and a.StageTypeID=0 and a.NumFights=2 and (a.Tour-s.Tour1)%2=1,2,if(a.TournamentID >0 and a.StageTypeID=0,1,0)) TypeID, s.Number from ft_agreements a left outer join ft_tournaments t using(TournamentID) left outer join ft_tournament_types tt on t.TournamentTypeID=tt.TournamentTypeID left outer join ft_tournament_modes m on tt.TypeID=m.TypeID left outer join ft_stages s on s.TournamentTypeID=tt.TournamentTypeID and (a.Tour>=s.Tour1 and a.Tour<=s.Tour2) where a.RecordID='$id';"); $q=mysql_fetch_array($q,1); if($q['ModeID']==TournamentTypeID::INTERNAL) { list($guild_exp)=select("select Exp from rt_guildpoints where GuildID='$q[TournamentGuildID]'"); if(!$guild_exp) $guild_exp=1.5; $q['TournamentFactor']=$guild_exp; } $gam=$q; $t1=select("select coalesce(Win/Lose,1) from stat_win where UserID='$gam[UserID1]';"); $t2=select("select coalesce(Win/Lose,1) from stat_win where UserID='$gam[UserID2]';"); $k=select("select sum(i.Slots) from tm_buildings b join fn_buildings_info i on b.BuildingID=i.BuildingID and b.Level=i.Level where b.UserID='$gam[UserID1]'"); if(!$t1[0]) $t1[0]=1; if(!$t2[0]) $t2[0]=1; if(!$gam['Number']) $gam['Number']=1; $k=0.4+0.01*$k[0]; $v1=select("select Visitors from ft_visitors where UserID='$gam[UserID1]'"); $v2=select("select Visitors from ft_visitors where UserID='$gam[UserID2]'"); if(!$v1[0]) $v1[0]=100; if(!$v2[0]) $v2[0]=100; $gam['Visitors']=round($k*$gam['Number']*($t1[0]*$v1[0]+$t2[0]*$v2[0]*0.3)); $_rst[0] = read_rst($gam['UserID1']); $_rst[1] = read_rst($gam['UserID2']); $_rst[0]['Captcha'] = true; $_rst[1]['Captcha'] = true; $rst = $_rst[0]; $capacity=$rst['Capacity']; if($capacity<$gam['Visitors']) $gam['Visitors']=$capacity; $gam['Visitors'] = (int)$gam['Visitors']; if(!$q['UserID1'] || !$q['UserID2']) return false; unset($gam['ModeID']); unset($gam['Number']); $expfactor=array(1,1.25,1.5,2,3); for ($i = 0; $i < 2; $i++) { $index = $i + 1; $userID = $q["UserID$index"]; $kit = Array(); list($kit['ID1'],$kit['Color1'],$kit['Color2']) = userGetKitOld($userID); $gam["Kit$index"] = $kit; $a1 = select("select * from ut_arts where ArtID=1 and UserID=$userID and ActivationDate>0 and ActivationDate+Time>unix_timestamp() limit 1"); $q1 = select("select coalesce(Rang,0),BanTime from ut_users where UserID=$userID"); $gam["Rang$index"] = $q1[0]; //$gam['Technical'][$i] = !$q1 || ($q1['BanTime'] > time()); //$gam['Technical'][$i] = $gam['Technical'][$i] || ($_rst[$i]['Captcha'] && !file_exists($site_path."files/ord/$id-$userID.ord") && $gam['MatchTypeID']!=2); //$gam['Technical'][$i] = ($userID==Consts::BOT_ID) ? false : $gam['Technical'][$i] ; $gam["ExpFactor$index"] = $expfactor[$q1[0]]; if($a1[0]) $gam["ExpFactor$index"] *= $a1['Value']; $practice1 = userGetPracticeID($userID); if ($practice1) $gam["ExpFactor$index"] *= Practice::$PRACTICES[$practice1]['Exp']; //если межсоюзный, то в 3 раза больше опыта if($gam['MatchTypeID']==2) $gam["ExpFactor$index"] *=3; $gam['Degradation'][$i] = userGetDegradation1($userID,$_rst[$i]); $technical = false; $technical = ( ! $q1 || ( $q1['BanTime'] > time() ) ) ? true : $technical; $technical = ( ! file_exists($site_path . "files/ord/$id-$userID.ord") ) ? true : $technical; $technical = ( $userID == Consts::BOT_ID ) ? false : $technical; $gam['Technical'][$i] = $technical; } $gam['id']=$id; // I need it for rating system $typeid=$q['TypeID']; if($q['Date']) { userFlush($q['UserID1']); userFlush($q['UserID2']); $c = 23; if ($q['UserID1']!=2) list($c) = select("select TeamCountryID from ut_users where UserID=$q[UserID1]"); if ($q['UserID2']!=2) list($c) = select("select TeamCountryID from ut_users where UserID=$q[UserID2]"); $skl = 80 ; $skl = $q['BotSkl'] ? $q['BotSkl'] : $skl ; $skl = ($q['MatchTypeID'] == 2) ? 290 : $skl; $skl = ($q['MatchTypeID'] == 3) ? 290 : $skl; $rstbot = read_rst_bot($c,$skl); $r1 = ($q['UserID1']==2) ? get_rst_file_rst($rstbot) : get_rst_file($q['UserID1']) ; $r2 = ($q['UserID2']==2) ? get_rst_file_rst($rstbot) : get_rst_file($q['UserID2']) ; $str = $r1.getfile($site_path."files/ord/$id-".$q['UserID1'].".ord").$r2.getfile($site_path."files/ord/$id-".$q['UserID2'].".ord"); //$str = get_rst_file($q[UserID1]).getfile($site_path."files/ord/$id-".$q[UserID1].".ord").get_rst_file($q[UserID2]).getfile($site_path."files/ord/$id-".$q[UserID2].".ord"); $gam['Date'] = time(); if(file_exists($fname)) return false; if ($q['TournamentID']) { @clearstatcache(); if(file_exists($site_path."files/matches/".$id)) return false; touch($site_path."files/matches/".$id); //$res2=runsql("select d.* from ut_disqualify d join ut_players p on d.PlayerID=p.PlayerID and (UserID='$q[UserID1]' or UserID='$q[UserID2]') where TournamentID='$q[TournamentID]'"); $res2 = runsql("select d.* from ut_disqualify d join ut_players p on d.PlayerID=p.PlayerID and (UserID='$q[UserID1]' or UserID='$q[UserID2]') and UserID<>".Consts::BOT_ID." where TournamentID='$q[TournamentID]'"); while($r2=mysql_fetch_array($res2)) { $d=1+$r2['Length']+$r2['Tour']-$q['Tour']; if($d>0) $gam['Disqualify'][$r2['PlayerID']]=$d; } } @clearstatcache(); if(file_exists($fname)) return false; $str = serialize($gam).$str; file_put_contents($fname,"GAM".pack("N",0x01000000).md5($str.$secpass).$str); $fp = fsockopen($cfg['GEN']['host'], $cfg['GEN']['port'], $errno, $errstr, 30); fwrite($fp, $cfg['GEN']['string']."$fname:$id\r\n"); stream_set_timeout($fp, 5); $answer=fread($fp,2); if ($answer!='ok') { $f=fopen($site_path."tmp/answerbug.txt","a"); fputs($f,System::date("d.m.Y H:i:s")." $id answer ".$answer." ".$_SERVER['PHP_SELF']." ".$_SERVER['QUERY_STRING']." ".$_SERVER['REMOTE_ADDR']."\r\n"); fclose($f); touch($site_path."files/demon/".$id); } fclose($fp); } return true; } function habala($userID, $tournament, $stage) { if (!$userID) { return; } if ($userID == Consts::BOT_ID) { return; } $tournamentID = $tournament['TournamentID']; $tournament_= select("select GuildID,TypeID,Name,Number,TournamentTypeID from ft_tournaments where TournamentID='$tournament[TournamentID]'"); list($number) = select("select Number from ft_stages where TournamentTypeID='$tournament_[TournamentTypeID]' and StageID='$stage[StageID]'"); list($factor) = select("select Reputation from ft_tournament_modes where TypeID='$tournament_[TypeID]'"); list($usersCount) = select("select count(*) from ft_tournament_members where TournamentID='$tournamentID' and UserID<>2"); list($stagesMax) = select("select max(Number) from ft_stages where TournamentTypeID='$tournament_[TournamentTypeID]'"); $pr = 0; $data = runsql("select * from ft_stages where TournamentTypeID='$tournament_[TournamentTypeID]' and Number<='$number'"); while ($row = mysql_fetch_array($data)) { $gamesCount = $row['Tour2'] - $row['Tour1'] + 1; $pr += $usersCount * $factor * $gamesCount / pow(2, $stagesMax - $row['Number']); } $points = floor(10 * $pr); runsql("insert into ft_reputation(UserID,Points,Date,TournamentID,GuildID) values('$userID','$points',unix_timestamp(),$tournamentID,coalesce((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$userID'),0))"); } function userGetCityID($userID, $rst = null) { $rst = $rst ? $rst : read_rst($userID); $result = ($rst['CityID'] && $rst['CityDate'] < time()) ? $rst['CityID'] : 0; if (time() >= 1516654800 && time() < 1516914000) { $result = 11; } return $result; } function getPointsFactor($typeID) { $result = 0; if ($typeID == 17) { $result = 3 * (1 * 4 / 100); } elseif ($typeID == 26) { $result = 25 * 20 * (1 * 4 / 100); } elseif ($typeID != 4 && $typeID != 5) { $result = (1 * 4 / 100); } return $result; } function userSetTournamentPoints($userID, $tournament, $stage, $points, $money) { if ( ! $userID) { return; } if ($userID == Consts::BOT_ID) { return; } $tournamentID = $tournament['TournamentID']; list( $guildID ) = select("select if(GuildStatusID=1,GuildID,0) GuildID from ut_users where UserID=$userID"); if ($guildID) { } if ($points) { $cityID = userGetCityID($userID); runsql("insert into ft_glory(CityID,UserID,Points,Date,TournamentID,GuildID) values($cityID,'$userID','$points',unix_timestamp(),$tournamentID,coalesce((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$userID'),0))"); runsql("insert into ft_points(UserID,Points) values('$userID','$points') on duplicate key update Points=Points+'$points'"); if ($guildID) { runsql("insert into ft_guild_points(GuildID,Points) values('$guildID','$points') on duplicate key update Points=Points+'$points'"); } } $stageID = $stage['StageID']; make_stage_reward($tournamentID, $stageID, $userID); habala($userID, $tournament, $stage); } function next_schedule($id) { global $site_path,$img_path; //выбираем описание текущего боя------------------ $q=select("select * from ft_matches where RecordID='$id'"); $tournament=select("select GuildID,TypeID,Name,Number,TournamentTypeID from ft_tournaments where TournamentID='$q[TournamentID]'"); $tournament['Name']=addslashes($tournament['Name']."-".dec2roman($tournament['Number'])); //if($q[NumFights]==2 && $q[StageTypeID]==1) //есть ли победитель в этой паре--------------- if($q['WinnerID']==$q['UserID1']) {$winner=$q['UserID1'];$loser=$q['UserID2'];} elseif($q['WinnerID']==$q['UserID2']) {$winner=$q['UserID2'];$loser=$q['UserID1'];} else $tie=1; if(($winner || $tie) && $tournament['TypeID']!=19) { $p=3*$q['Stage']; $p2=2*$q['Stage']; $p3=$q['Stage']; if($winner) { $rst=read_rst($winner); if($rst['Staff'][8]>=1 && $rst['Staff'][8]<=3) $p+=$rst['Staff'][8]; runsql("insert into ft_visitors(UserID,Visitors) values($winner,100+$p) on duplicate key update Visitors=Visitors+$p"); runsql("insert into ft_visitors(UserID,Visitors) values($loser,100-$p2) on duplicate key update Visitors=if(Visitors>$p2,Visitors-$p2,0)"); } else { runsql("insert into ft_visitors(UserID,Visitors) values($q[UserID1],100+$p3) on duplicate key update Visitors=Visitors+$p3"); runsql("insert into ft_visitors(UserID,Visitors) values($q[UserID2],100+$p3) on duplicate key update Visitors=Visitors+$p3"); } //print "Победитель определен
"; if($q['StageTypeID']==0) { //в плейофф------------------- runsql("update ft_tournament_members set StatusID=1 where TournamentID='$q[TournamentID]' and UserID='$loser'"); $p=select("select Prize,StageID from ft_stages where TournamentTypeID='$tournament[TournamentTypeID]' and Number='$q[Stage]'-1"); $points = round($p['Prize']*getPointsFactor($tournament['TypeID'])); //if($tournament[TypeID]==17 ) $points=3*round($p[Prize]*4/100); //elseif($tournament[TypeID]!=4 && $tournament[TypeID]!=5) $points=round($p[Prize]*4/100); //if($tournament[TypeID]==26) $points=25*20*round($p[Prize]*4/100); //if($p[0]&&$tournament[TypeID]==1) userSetTournamentPoints($loser, $q, $p, $points, 0); //if($loser && $points) //{ // runsql("insert into ft_points(UserID,Points) values('$loser','$points') on duplicate key update Points=Points+'$points'"); // runsql("insert into ft_glory(UserID,Points,Date,TournamentID,GuildID) values('$loser','$points',unix_timestamp(),'$q[TournamentID]',coalesce((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$loser'),0))"); //} if($p[0]&&$tournament['GuildID']) transfer_guild2user($p[0],$tournament['GuildID'],$loser,27,$q['TournamentID']); elseif($p[0]) transfer_money($p[0],1,$loser,27,$q['TournamentID']); //следующая стадия--------------- $u=select("select * from ft_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and (Pair1='$q[Pair]' or Pair2='$q[Pair]')"); //проверка на окончание турнира--------------- if(!$u[0]) { runsql("insert ignore into ft_winners(UserGuildID, GuildID,TournamentID,UserID,Date,Login,Tournament,Place,TypeID,TournamentTypeID) values((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$winner'),'$tournament[GuildID]','$q[TournamentID]','$winner',unix_timestamp(),(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$winner'),'$tournament[Name]',1,'$tournament[TypeID]','$tournament[TournamentTypeID]')"); runsql("insert ignore into ft_winners(UserGuildID, GuildID,TournamentID,UserID,Date,Login,Tournament,Place,TypeID,TournamentTypeID) values((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$loser'),'$tournament[GuildID]','$q[TournamentID]','$loser',unix_timestamp(),(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$loser'),'$tournament[Name]',2,'$tournament[TypeID]','$tournament[TournamentTypeID]')"); runsql("update ft_tournaments set StatusID=2 where TournamentID='$q[TournamentID]';"); $p=select("select Prize,StageID from ft_stages where TournamentTypeID='$tournament[TournamentTypeID]' and Number='$q[Stage]'"); $points = round($p['Prize']*getPointsFactor($tournament['TypeID'])); //if($tournament[TypeID]==17 ) $points=3*round($p[Prize]*4/100); //elseif($tournament[TypeID]!=4 && $tournament[TypeID]!=5) $points=round($p[Prize]*4/100); //if($tournament[TypeID]==26) $points=25*20*round($p[Prize]*4/100); //if($p[0]&&$tournament[TypeID]==1) userSetTournamentPoints($winner, $q, $p, $points, 0); //if($points) //{ // runsql("insert into ft_glory(UserID,Points,Date,TournamentID,GuildID) values('$winner','$points',unix_timestamp(),'$q[TournamentID]',coalesce((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$winner'),0))"); // runsql("insert into ft_points(UserID,Points) values('$winner','$points') on duplicate key update Points=Points+'$points'"); //} if($p[0]&&$tournament['GuildID']) transfer_guild2user($p[0],$tournament['GuildID'],$winner,27,$q['TournamentID']); elseif($p[0]) transfer_money($p[0],1,$winner,27,$q['TournamentID']); /* if($cfg['GLOBAL']['domain_suffix']=="ru") { рассылаем код ХЦ РБК победителям кубковых турниров if (in_array($tournament[TypeID], array(1,2,6,7,8,9))) send_rbc_mail($winner); Турнир на призы Doctor Web $DWEB = 6484; if ($DWEB == $tournament["TournamentTypeID"]){ if ($q["WinnerID"]==$q["UserID1"]) { send_dweb_mail($q["UserID1"],$q["UserID2"]); } else { send_dweb_mail($q["UserID2"],$q["UserID1"]); } } } */ } else { if($u['StageTypeID']==0) { //обновляем следующий этап------------------------ runsql("update ft_tmp_agreements set UserID1='$winner', Login1=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$winner') where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Pair1='$q[Pair]'"); runsql("update ft_tmp_agreements set UserID2='$winner', Login2=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$winner') where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Pair2='$q[Pair]'"); //подстраховка $u=select("select * from ft_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and (Pair1='$q[Pair]' or Pair2='$q[Pair]')"); } //если оба соперника - добавляем бой ------------------------------- if($u['StageTypeID']==0&&($u['UserID1']>0||$u['Pair1']==$q['Pair'])&&($u['UserID2']>0||$u['Pair2']==$q['Pair'])) { runsql("insert ignore into ft_agreements (UserID1,UserID2,TypeID,LimitSkl,Timeout,TournamentID,Stage,Tour,Fight,Pair,Pair1,Pair2,Place1,Place2,NumFights,StageTypeID,Approved,StatusID,Date,Login1,Login2) (select UserID1,UserID2,TypeID,LimitSkl,Timeout,TournamentID ,Stage,Tour,Fight,Pair,Pair1,Pair2,Place1,Place2,NumFights,StageTypeID, 1,2,unix_timestamp(),Login1,Login2 from ft_tmp_agreements where RecordID='$u[RecordID]' and StatusID=0)"); runsql("update ft_tmp_agreements set StatusID=1 where RecordID='$u[RecordID]' and StatusID=0"); } elseif($u['StageTypeID']==1) { //обновляем следующий этап------------------------ runsql("update ft_tmp_agreements set UserID1='$winner', Login1=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$winner') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair1='$q[Pair]'"); runsql("update ft_tmp_agreements set UserID2='$winner', Login2=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$winner') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair2='$q[Pair]'"); //обновляем группу, куда выходит победитель-------------------- runsql("update ft_groups set UserID='$winner',Login=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$winner') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair='$q[Pair]'"); runsql("insert ignore into ft_agreements (UserID1,UserID2,TypeID,LimitSkl,Timeout,TournamentID,Stage,Tour,Fight,Pair,Pair1,Pair2,Place1,Place2,NumFights,StageTypeID,Approved,StatusID,Date,Login1,Login2) (select UserID1,UserID2,TypeID,LimitSkl,Timeout,TournamentID ,Stage,Tour,Fight,Pair,Pair1,Pair2,Place1,Place2,NumFights,StageTypeID, 1,2,unix_timestamp(),Login1,Login2 from ft_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and ((UserID1='$winner' and UserID2>0) or (UserID2='$winner' and UserID1>0)) and StatusID=0)"); runsql("update ft_tmp_agreements set StatusID=1 where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and ((UserID1='$winner' and UserID2>0) or (UserID2='$winner' and UserID1>0)) and StatusID=0"); } } } elseif($q['StageTypeID']==1) { //в группе------------------- $finished=1; $i=1; $p1=0; $p2=0; $w1=0; $w2=0; $t1=0; $t2=0; $l1=0; $l2=0; if($winner==$q['UserID1']) {$p1=3;$w1=1;$l2=1;} elseif($winner==$q['UserID2']) {$p2=3;$w2=1;$l1=1;} if($tie) {$p1=1;$p2=1;$t1=1;$t2=1;} runsql("update ft_groups set Games=Games+1,Tour='$q[Tour]',Points=Points+'$p1',Win=Win+'$w1',Tie=Tie+'$t1',Lose=Lose+'$l1',Score1=Score1+'".$q['Score1']."',Score2=Score2+'".$q['Score2']."' where TournamentID='$q[TournamentID]' and Stage='$q[Stage]' and UserID='$q[UserID1]' and Pair='$q[Pair1]' and (Tour='0' or '$q[Tour]'>Tour) and Name='$q[Pair]' and (Place=0 or Place='$q[Place1]')"); runsql("update ft_groups set Games=Games+1,Tour='$q[Tour]',Points=Points+'$p2',Win=Win+'$w2',Tie=Tie+'$t2',Lose=Lose+'$l2',Score1=Score1+'".$q['Score2']."',Score2=Score2+'".$q['Score1']."' where TournamentID='$q[TournamentID]' and Stage='$q[Stage]' and UserID='$q[UserID2]' and Pair='$q[Pair2]' and (Tour='0' or '$q[Tour]'>Tour) and Name='$q[Pair]' and (Place=0 or Place='$q[Place2]')"); $res=runsql("select * from ft_groups where TournamentID='$q[TournamentID]' and Stage='$q[Stage]' and Name='$q[Pair]' order by Points desc, Win desc, Score1-Score2 desc, Score1 desc, rand($q[TournamentID]*$q[Stage]*$q[Pair])"); while($r=mysql_fetch_array($res)) { if($r['Games']!=3) $finished=0; $place[$i]=$r['UserID']; $i++; } //если группа завершена----------------- if($finished) { //print "Группа завершена
"; //следующая стадия runsql("update ft_tournament_members set StatusID=1 where TournamentID='$q[TournamentID]' and UserID='$place[3]'"); runsql("update ft_tournament_members set StatusID=1 where TournamentID='$q[TournamentID]' and UserID='$place[4]'"); $p=select("select Prize,StageID from ft_stages where TournamentTypeID='$tournament[TournamentTypeID]' and Number='$q[Stage]'-1"); $points = round($p['Prize']*getPointsFactor($tournament['TypeID'])); //if($tournament[TypeID]==17 ) $points=3*round($p[Prize]*4/100); //elseif($tournament[TypeID]!=4 && $tournament[TypeID]!=5) $points=round($p[Prize]*4/100); //if($tournament[TypeID]==26) $points=25*20*round($p[Prize]*4/100); userSetTournamentPoints($place[3], $q, $p, $points, 0); userSetTournamentPoints($place[4], $q, $p, $points, 0); //if($points) runsql("insert into ft_glory(UserID,Points,Date,TournamentID,GuildID) values('$place[3]','$points',unix_timestamp(),$q[TournamentID],coalesce((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$place[3]'),0))"); //if($points) runsql("insert into ft_glory(UserID,Points,Date,TournamentID,GuildID) values('$place[4]','$points',unix_timestamp(),$q[TournamentID],coalesce((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$place[4]'),0))"); //if($points) runsql("insert into ft_points(UserID,Points) values('$place[3]','$points') on duplicate key update Points=Points+'$points'"); //if($points) runsql("insert into ft_points(UserID,Points) values('$place[4]','$points') on duplicate key update Points=Points+'$points'"); if($p[0]&&$tournament['GuildID']) transfer_guild2user($p[0],$tournament['GuildID'],$place[3],27,$q['TournamentID']); elseif($p[0]) transfer_money($p[0],1,$place[3],27,$q['TournamentID']); if($p[0]&&$tournament['GuildID']) transfer_guild2user($p[0],$tournament['GuildID'],$place[4],27,$q['TournamentID']); elseif($p[0]) transfer_money($p[0],1,$place[4],27,$q['TournamentID']); $u=select("select * from ft_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and (Pair1='$q[Pair]' or Pair2='$q[Pair]')"); if(!$u[0]) { userSetTournamentPoints($place[2], $q, $p, $points, 0); //if($points) runsql("insert into ft_glory(UserID,Points,Date,TournamentID,GuildID) values('$place[2]',$points,unix_timestamp(),$q[TournamentID],coalesce((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$place[2]'),0))"); //if($points) runsql("insert into ft_points(UserID,Points) values('$place[2]','$points') on duplicate key update Points=Points+'$points'"); if($p[0]&&$tournament['GuildID']) transfer_guild2user($p[0],$tournament['GuildID'],$place[2],27,$q['TournamentID']); elseif($p[0]) transfer_money($p[0],1,$place[2],27,$q['TournamentID']); runsql("insert ignore into ft_winners(UserGuildID, GuildID,TournamentID,UserID,Date,Login,Tournament,Place,TypeID,TournamentTypeID) values((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$place[1]'),'$tournament[GuildID]','$q[TournamentID]','$place[1]',unix_timestamp(),(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[1]'),'$tournament[Name]',1,'$tournament[TypeID]','$tournament[TournamentTypeID]')"); runsql("insert ignore into ft_winners(UserGuildID, GuildID,TournamentID,UserID,Date,Login,Tournament,Place,TypeID,TournamentTypeID) values((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$place[2]'),'$tournament[GuildID]','$q[TournamentID]','$place[2]',unix_timestamp(),(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[2]'),'$tournament[Name]',2,'$tournament[TypeID]','$tournament[TournamentTypeID]')"); $p=select("select Prize,StageID from ft_stages where TournamentTypeID='$tournament[TournamentTypeID]' and Number='$q[Stage]'"); //$points=round($p[Prize]*4/100); $points = round($p['Prize']*getPointsFactor($tournament['TypeID'])); //if($tournament[TypeID]==17 ) $points=3*round($p[Prize]*4/100); //elseif($tournament[TypeID]!=4 && $tournament[TypeID]!=5) $points=round($p[Prize]*4/100); //if($tournament[TypeID]==26) $points=25*20*round($p[Prize]*4/100); userSetTournamentPoints($place[1], $q, $p, $points, 0); //if($points) //{ // runsql("insert into ft_glory(UserID,Points,Date,TournamentID,GuildID) values('$place[1]',$points,unix_timestamp(),$q[TournamentID],coalesce((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$place[1]'),0))"); // runsql("insert into ft_points(UserID,Points) values('$place[1]','$points') on duplicate key update Points=Points+'$points'"); //} if($p[0]&&$tournament['GuildID']) transfer_guild2user($p[0],$tournament['GuildID'],$place[1],27,$q['TournamentID']); elseif($p[0]) transfer_money($p[0],1,$place[1],27,$q['TournamentID']); runsql("update ft_tournaments set StatusID=2 where TournamentID='$q[TournamentID]';"); } else { if($u['StageTypeID']==0) { runsql("update ft_tmp_agreements set UserID1='$place[1]', Login1=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[1]') where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and ((Pair1='$q[Pair]' and Place1='1') or (Pair2='$q[Pair]' and Place2='1'))"); runsql("update ft_tmp_agreements set UserID2='$place[2]', Login2=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[2]') where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and ((Pair2='$q[Pair]' and Place2='2') or (Pair1='$q[Pair]' and Place1='2'))"); //бой за 3 место //runsql("update ft_tmp_agreements set UserID1='$place[3]',Login1=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[1]') where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and ((Pair1='$q[Pair]' and Place1='3') or (Pair2='$q[Pair]' and Place2='3'))"); //runsql("update ft_tmp_agreements set UserID2='$place[4]',Login2=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[2]') where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and ((Pair2='$q[Pair]' and Place2='4') or (Pair1='$q[Pair]' and Place1='4'))"); } elseif($u['StageTypeID']==1) { runsql("update ft_groups set UserID='$place[1]',Login=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[1]') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair='$q[Pair]' and Place='1'"); runsql("update ft_groups set UserID='$place[2]',Login=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[2]') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair='$q[Pair]' and Place='2'"); runsql("update ft_tmp_agreements set UserID1='$place[1]', Login1=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[1]') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair1='$q[Pair]' and Place1='1'"); runsql("update ft_tmp_agreements set UserID2='$place[1]', Login2=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[1]') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair2='$q[Pair]' and Place2='1'"); runsql("update ft_tmp_agreements set UserID2='$place[2]', Login2=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[2]') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair2='$q[Pair]' and Place2='2'"); runsql("update ft_tmp_agreements set UserID1='$place[2]', Login1=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[2]') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair1='$q[Pair]' and Place1='2'"); } //группа соперника---------------------- if($u['Pair1']==$q['Pair']) $opgroup=$u['Pair2']; else $opgroup=$u['Pair1']; $g=select("select Finished from ft_groups where TournamentID='$q[TournamentID]' and Stage='$q[Stage]' and Name='$opgroup'"); if($g[0]==1 || $opgroup==$q['Pair']) { if($u['StageTypeID']==0) { runsql("insert ignore into ft_agreements (UserID1,UserID2,TypeID,LimitSkl,Timeout,TournamentID,Stage,Tour,Fight,Pair,Pair1,Pair2,Place1,Place2,NumFights,StageTypeID,Approved,StatusID,Date,Login1,Login2) (select UserID1,UserID2,TypeID,LimitSkl,Timeout,TournamentID ,Stage,Tour,Fight,Pair,Pair1,Pair2,Place1,Place2,NumFights,StageTypeID, 1,2,unix_timestamp(),Login1,Login2 from ft_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and (Pair1='$q[Pair]' or Pair2='$q[Pair]') and StatusID=0)"); runsql("update ft_tmp_agreements set StatusID=1 where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and (Pair1='$q[Pair]' or Pair2='$q[Pair]') and StatusID=0"); } elseif($u['StageTypeID']==1) { runsql("insert ignore into ft_agreements (UserID1,UserID2,TypeID,LimitSkl,Timeout,TournamentID,Stage,Tour,Fight,Pair,Pair1,Pair2,Place1,Place2,NumFights,StageTypeID,Approved,StatusID,Date,Login1,Login2) (select UserID1,UserID2,TypeID,LimitSkl,Timeout,TournamentID ,Stage,Tour,Fight,Pair,Pair1,Pair2,Place1,Place2,NumFights,StageTypeID, 1,2,unix_timestamp(),Login1,Login2 from ft_tmp_agreements where TournamentID='$q[TournamentID]' and ( (Tour='$q[Tour]'+1 and (Pair1='$q[Pair]' or Pair2='$q[Pair]') and Stage<>'$q[Stage]') or (Tour='$q[Tour]'+1 and (Pair='$q[Pair]') and Stage='$q[Stage]') ) and Fight=1 and StatusID=0)"); runsql("update ft_tmp_agreements set StatusID=1 where TournamentID='$q[TournamentID]' and ( (Tour='$q[Tour]'+1 and (Pair1='$q[Pair]' or Pair2='$q[Pair]') and Stage<>'$q[Stage]') or (Tour='$q[Tour]'+1 and (Pair='$q[Pair]') and Stage='$q[Stage]') ) and Fight=1 and StatusID=0"); } } } runsql("update ft_groups set Finished=1 where TournamentID='$q[TournamentID]' and Stage='$q[Stage]' and Name='$q[Pair]'"); } else { //print "Группа не завершена
"; // $u=select("select * from ft_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and (UserID1='$q[UserID1]' or UserID2='$q[UserID1]')"); //$u=select("select * from ft_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Pair='$q[Pair]' and Fight=1 and ((UserID1='$q[UserID1]' and Pair1='$q[Pair1]') or (UserID2='$q[UserID1]' and Pair2='$q[Pair1]'))"); $u = select("select * from ft_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Pair='$q[Pair]' and Fight=1 and ((UserID1='$q[UserID1]' and Pair1='$q[Pair1]' and Place1='$q[Place1]') or (UserID2='$q[UserID1]' and Pair2='$q[Pair1]' and Place2='$q[Place1]'))"); //доиграл ли соперник?--------- // if($u[UserID1]==$q[UserID1]) $op=$u[UserID2]; // elseif($u[UserID2]==$q[UserID1]) $op=$u[UserID1]; /* if($u[UserID1]==$q[UserID1] && $u[Pair1]==$q[Pair1]) { $op=$u[UserID2]; $opp=$u[Pair2]; } elseif($u[UserID2]==$q[UserID1] && $u[Pair2]==$q[Pair1]) { $op=$u[UserID1]; $opp=$u[Pair1]; } */ if ($u['UserID1'] == $q['UserID1'] && $u['Pair1'] == $q['Pair1'] && $u['Place1'] == $q['Place1']) { $op = $u['UserID2']; $opp= $u['Pair2']; $oppl = $u['Place2']; } elseif ($u['UserID2'] == $q['UserID1'] && $u['Pair2'] == $q['Pair1'] && $u['Place2'] == $q['Place1']) { $op = $u['UserID1']; $opp= $u['Pair1']; $oppl = $u['Place1']; } // $q2=select("select RecordID from ft_matches where TournamentID='$q[TournamentID]' and Tour='$q[Tour]' and (UserID1='$op' or UserID2='$op')"); //$q2=select("select RecordID from ft_matches where TournamentID='$q[TournamentID]' and Tour='$q[Tour]' and Pair='$q[Pair]' and ((UserID1='$op' and Pair1='$opp') or (UserID2='$op' and Pair2='$opp'))"); $q2 = select("select RecordID from ft_matches where TournamentID='$q[TournamentID]' and Tour='$q[Tour]' and Pair='$q[Pair]' and ((UserID1='$op' and Pair1='$opp' and Place1='$oppl') or (UserID2='$op' and Pair2='$opp' and Place2='$oppl'))"); if($q2[0]) { //print "Бой соперника завершен
"; runsql("insert ignore into ft_agreements (UserID1,UserID2,TypeID,LimitSkl,Timeout,TournamentID,Stage,Tour,Fight,Pair,Pair1,Pair2,Place1,Place2,NumFights,StageTypeID,Approved,StatusID,Date,Login1,Login2) (select UserID1,UserID2,TypeID,LimitSkl,Timeout,TournamentID ,Stage,Tour,Fight,Pair,Pair1,Pair2,Place1,Place2,NumFights,StageTypeID, 1,2,unix_timestamp(),Login1,Login2 from ft_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and Pair='$q[Pair]' and StatusID=0)"); runsql("update ft_tmp_agreements set StatusID=1 where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and Pair='$q[Pair]' and StatusID=0"); } /* $u=select("select * from ft_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and (UserID1='$q[UserID2]' or UserID2='$q[UserID2]')"); //доиграл ли соперник?--------- if($u[UserID1]==$q[UserID2]) $op=$u[UserID2]; elseif($u[UserID2]==$q[UserID2]) $op=$u[UserID1]; $q2=select("select RecordID from ft_matches where TournamentID='$q[TournamentID]' and Tour='$q[Tour]' and (UserID1='$op' or UserID2='$op')"); if($q2[0]) { //print "Бой соперника завершен
"; runsql("insert into ft_agreements (UserID1,UserID2,TypeID,LimitSkl,Timeout,TournamentID,Stage,Tour,Fight,Pair,NumFights,StageTypeID,Approved,StatusID,Date,Login1,Login2) (select UserID1,UserID2,TypeID,LimitSkl,Timeout,TournamentID ,Stage,Tour,Fight,Pair,NumFights,StageTypeID, 1,2,unix_timestamp(),Login1,Login2 from ft_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and Pair='$q[Pair]' and StatusID=0)"); runsql("update ft_tmp_agreements set StatusID=1 where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and Pair='$q[Pair]' and StatusID=0"); } */ } } } else { //print "Победитель ещё не определен
"; //добавить следующий бой в серии runsql("insert ignore into ft_agreements (UserID1,UserID2,TypeID,LimitSkl,Timeout,TournamentID,Stage,Tour,Fight,Pair,Pair1,Pair2,Place1,Place2,NumFights,StageTypeID,Approved,StatusID,Date,Login1,Login2) (select UserID1,UserID2,TypeID,LimitSkl,Timeout,TournamentID ,Stage,Tour,Fight,Pair,Pair1,Pair2,Place1,Place2,NumFights,StageTypeID, 1,2,unix_timestamp(),Login1,Login2 from ft_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]' and Fight=1+'$q[Fight]' and (UserID1='$q[UserID1]' or UserID1='$q[UserID2]') and StatusID=0)"); runsql("update ft_tmp_agreements set StatusID=1 where TournamentID='$q[TournamentID]' and Tour='$q[Tour]' and Fight=1+'$q[Fight]' and (UserID1='$q[UserID1]' or UserID1='$q[UserID2]') and StatusID=0"); } //TODO: На этой строке происходит зависание при записи warning в журнал ошибок php (причину пока найти не удалось) @unlink($site_path."files/matches/".$id); tournamentProcessBotResults($q); //TODO: Убираем не участвующих в турнире пользователей (временное решение) if (select("select m.* from ft_tournament_members m where m.TournamentID='$q[TournamentID]' and m.UserID not in (select UserID1 from ft_tmp_agreements where TournamentID='$q[TournamentID]' and Stage=1 and Tour=1 union select UserID2 from ft_tmp_agreements where TournamentID='$q[TournamentID]' and Stage=1 and Tour=1) limit 1")) { Log::debug("next_schedule($id) extra member in tournament $q[TournamentID]"); runsql("delete from ft_tournament_members where TournamentID='$q[TournamentID]' and UserID not in (select UserID1 from ft_tmp_agreements where TournamentID='$q[TournamentID]' and Stage=1 and Tour=1 union select UserID2 from ft_tmp_agreements where TournamentID='$q[TournamentID]' and Stage=1 and Tour=1)"); } } function tournamentProcessBotResults($tournament) { static $recursive = false; if ($recursive) return; $recursive = true; $repeat = true; while ($repeat) { $repeat = false; $data = runsql("select * from ft_agreements where TournamentID='$tournament[TournamentID]' and UserID1=".Consts::BOT_ID." and UserID2=".Consts::BOT_ID." order by Tour"); while ($row = mysql_fetch_array($data)) { gameProcessBotResults($tournament,$row['RecordID']); $repeat = true; } } $recursive = false; } function short_transfer_money($rst,$money,$sender,$receiver,$type,$info = '') { global $REMOTE_ADDR,$PHP_SELF,$QUERY_STRING,$auth; $money=round($money); if(!is_array($rst)) return 0; $user=$rst['UserID']; if($money>0) { $userMarketingStats=getMarketingStats($user); if($sender==1) { $balance=$rst['Money']+$money; $userMarketingStats['sessionMoneyIncome']+=$money; } else { $balance=$rst['Money']-$money; $userMarketingStats['sessionMoneyOutcome']+=$money; } setMarketingStats($user,$userMarketingStats); $rst['Money']=round($balance); if($sender==1) runsql("insert into fn_operations(Money,SenderID,ReceiverID,SenderBalance,ReceiverBalance,TypeID,OperationDate,OperationObject) values('$money','1','$user','','$balance','$type' ,unix_timestamp(),'$info')"); else runsql("insert into fn_operations(Money,SenderID,ReceiverID,SenderBalance,ReceiverBalance,TypeID,OperationDate,OperationObject) values('$money','$user','1','$balance','','$type' ,unix_timestamp(),'$info')"); } if ($auth->user == $rst['UserID']) { $auth->money = $rst['Money']; $auth->rst['Money'] = $rst['Money']; } return $rst; } function get_health($rst) { global $stamina,$morale,$injury; if($rst['Staff'][2]==1) $hours=9; elseif($rst['Staff'][2]==2) $hours=6; elseif($rst['Staff'][2]==3) $hours=4; if($rst['Staff'][2]>=1 && $rst['Staff'][2]<=3) {$stamina=round($rst['Status'][2]+100*(time() - $rst['StaffDate'])/3600/($hours));if($stamina>100) $stamina=100;} else $stamina=0; if($rst['Staff'][4]==1) $hours=9; elseif($rst['Staff'][4]==2) $hours=6; elseif($rst['Staff'][4]==3) $hours=4; if($rst['Staff'][4]>=1 && $rst['Staff'][4]<=3) {$morale=round($rst['Status'][4]+100*(time() - $rst['StaffDate'])/3600/($hours));if($morale>100) $morale=100;} else $morale=0; if($rst['Staff'][3]==1) $hours=9; elseif($rst['Staff'][3]==2) $hours=6; elseif($rst['Staff'][3]==3) $hours=4; if($rst['Staff'][3]>=1 && $rst['Staff'][8]<=3) {$injury=round($rst['Status'][3]+100*(time() - $rst['StaffDate'])/3600/($hours));if($injury>100) $injury=100;} else $injury=0; } function lock_rst_file($id) { global $site_path,$PHP_SELF,$QUERY_STRING; $f=rstname($id); $f.=".locked"; @clearstatcache(); while (@file_exists($f)) { sleep(1); @clearstatcache(); $t=time(); $t2=@filectime($f); if (!($t2>0)) $t2=time(); if (($t-$t2)>30) { $debug=file_get_contents($f); @unlink($f); @clearstatcache(); log_rst("[error] lock_rst timeout $id - $debug"); } } $fp=@fopen($f,"w"); fputs($fp,'FILE: '.__FILE__.' func '.__FUNCTION__.' at line'.__LINE__); @fclose($fp); @chmod($f,0666); } function unlock_rst_file($id) { global $site_path; $f=rstname($id); @unlink($f.".locked"); } function lock_gld_file($id) { global $site_path,$PHP_SELF,$QUERY_STRING; $f=$site_path."files/gld/$id.gld"; $f.=".locked"; @clearstatcache(); while (@file_exists($f)) { sleep(1); @clearstatcache(); $t=time(); $t2=@filectime($f); if (!($t2>0)) $t2=time(); if (($t-$t2)>10) { $debug=file_get_contents($f); @unlink($f); @clearstatcache(); log_rst("[error] lock_gld timeout $id - $debug"); } } $fp=@fopen($f,"w"); fputs($fp,'FILE: '.__FILE__.' func '.__FUNCTION__.' at line'.__LINE__); @fclose($fp); @chmod($f,0666); } function unlock_gld_file($id) { global $site_path; $f=$site_path."files/gld/$id.gld"; @unlink($f.".locked"); } function lock_gld($id) { global $cfg; if ($cfg['MC']['enabled']) { $lock = new Memcache_Lock(); $lock->lock("gld_$id"); } else lock_gld_file($id); } function unlock_gld($id) { global $cfg; if ($cfg['MC']['enabled']) { $lock = new Memcache_Lock(); $lock->unlock("gld_$id"); } else unlock_gld_file($id); } function lock_rst($id) { global $cfg; if ($cfg['GLOBAL']['rst_lock_profiler_enabled']) { $self=$_SERVER['PHP_SELF']; $query=$_SERVER['QUERY_STRING']; $lockInfo['locked']=true; $lockInfo['hostname']=$cfg['GLOBAL']['hostname']; $lockInfo['timestamp']=time(); $lockInfo['filename']=__FILE__; $lockInfo['function']=__FUNCTION__; $lockInfo['backtrace']=debug_backtrace(); $lockInfo['line']=__LINE__; $lockInfo['url']="$self ? $query"; Cache_Memcache::setValue("dr_$id",$lockInfo,3600); } if ($cfg['MC']['enabled']) { $lock = new Memcache_Lock(); $lock->lock("rst_$id"); } else lock_rst_file($id); } function unlock_rst($id) { global $cfg; if ($cfg['MC']['enabled']) { $lock = new Memcache_Lock(); $lock->unlock("rst_$id"); } else unlock_rst_file($id); } function lock_rst_old($id) { global $engine_path; include_once($engine_path.'/cls/common/Memcache_Lock.php'); $lock = new Memcache_Lock(); $lock->lock("rst_$id"); } function unlock_rst_old($id) { $lock = new Memcache_Lock(); $lock->unlock("rst_$id"); } function myeval($code) { Log::debug("myeval [$code]"); ob_start(); myevalx($code); $output = ob_get_contents(); ob_end_clean(); return $output; } function build($id) { global $auth; $user=$auth->user; lock_rst($user); $q=select("select Price,BuildingID,Level from fn_buildings_info where InfoID='$id'"); $price=$q[0]; $building=$q[1]; $level=$q[2]; if($level&&$building&&$price>0&&$user>0&&$id>0) { $rst=read_rst($user); if($rst['Buildings'][$building]==$level) { unlock_rst($user); return 0; } $rst['Buildings'][$building]=$level; if($price>0) $rst=short_transfer_money($rst,$price,$user,1,6,$id); write_rst($user,$rst); runsql("insert into tm_buildings(BuildingID,Level,Date,UserID,Slots) values ('$building','$level',unix_timestamp(),'$user',(select Slots from fn_buildings_info where BuildingID='$building' and Level='$level'))"); } unlock_rst($user); } function update_exp($rst) { global $k,$serialized; $serialized=$rst['Players']; foreach($serialized as $k=>$v) { $exp=expgained($rst); if($exp) { $rst['Players'][$k]['Exp']=strval(round($rst['Players'][$k]['Exp']+$exp,2)); $rst['Players'][$k]['NextTrain']=strval(round($exp+$rst['Players'][$k]['NextTrain'],2)); } } $rst['TrainDate']=time(); return $rst; } function update_health($rst) { global $k,$serialized; $serialized = $rst['Players']; $practice = userGetPracticeID($rst['UserID'],$rst); if ($practice) { $staminaPractice=Practice::$PRACTICES[$practice]['Stamina']; $moralePractice=Practice::$PRACTICES[$practice]['Morale']; $injuryPractice=Practice::$PRACTICES[$practice]['Injury']; } else { $staminaPractice=1; $moralePractice=1; $injuryPractice=1; } foreach($serialized as $k=>$v) { $rst['Players'][$k]['Stamina']=get_stamina($rst['Players'][$k]['Stamina'],$rst['Players'][$k]['PercentTrain'],$rst['Date'],$staminaPractice); $rst['Players'][$k]['Morale']=get_morale($rst['Players'][$k]['Morale'],$rst['Date'],$moralePractice); $rst['Players'][$k]['Injury']=get_injury($rst['Players'][$k]['Stamina'],$rst['Date'],$injuryPractice); } $rst['TrainDate']=time(); $rst['Date']=time(); return $rst; } function sell_building($user,$id,$level,$price) { global $REMOTE_ADDR,$auth; $user=$auth->user; $q=select("select BuildingID, max(LeveL) from tm_buildings where BuildingID='$id' and UserID='$user' group by BuildingID"); if($q[1]!=$level) return 0; $q=select("select round(Price/2) from fn_buildings_info where BuildingID='$id' and Level='$level'"); $price=$q[0]; if(!$id||!$level||!$user||!$price) return 0; lock_rst($user); $rst=read_rst($user); $rst=short_transfer_money($rst,$price,1,$user,22,$id); if($rst['Buildings'][$id]>1) $rst['Buildings'][$id]=$rst['Buildings'][$id]-1; elseif($rst['Buildings'][$id]) unset($rst['Buildings'][$id]); runsql("delete from tm_buildings where BuildingID='$id' and Level='$level' and UserID='$user'"); write_rst($user,$rst); unlock_rst($user); } function transfer_money($money,$sender,$receiver,$type,$info) { global $REMOTE_ADDR,$PHP_SELF,$QUERY_STRING,$auth; $money=round($money); @clearstatcache(); if($sender!=1) lock_rst($sender); if($receiver!=1) lock_rst($receiver); if(!$money) {unlock_rst($sender);unlock_rst($receiver);return false;} if($money>0&&$sender>0&&$receiver>0) { if($sender==1) $senderbalance=''; else { $sender_rst=read_rst($sender); $user1MarketingStats=getMarketingStats($sender); $senderbalance=$sender_rst['Money']-$money; $sender_rst['Money']=round($senderbalance); $user1MarketingStats['sessionMoneyOutcome']+=$money; } if($receiver==1) $receiverbalance=''; else { $receiver_rst=read_rst($receiver); $user2MarketingStats=getMarketingStats($receiver); $receiverbalance=$receiver_rst['Money']+$money; $receiver_rst['Money']=round($receiverbalance); $user2MarketingStats['sessionMoneyIncome']+=$money; } runsql("insert into fn_operations(Money,SenderID,ReceiverID,SenderBalance,ReceiverBalance,TypeID,OperationDate,OperationObject) values('$money','$sender','$receiver','$senderbalance','$receiverbalance','$type' ,unix_timestamp(),'$info')"); if($receiver!=1) { if ($auth->user == $receiver_rst['UserID']) { $auth->money = $receiver_rst['Money']; $auth->rst['Money'] = $receiver_rst['Money']; } write_rst($receiver,$receiver_rst); setMarketingStats($receiver,$user2MarketingStats); } if($sender!=1) { if ($auth->user == $sender_rst['UserID']) { $auth->money = $sender_rst['Money']; $auth->rst['Money'] = $sender_rst['Money']; } write_rst($sender,$sender_rst); setMarketingStats($sender,$user1MarketingStats); } } if($sender!=1) unlock_rst($sender); if($receiver!=1) unlock_rst($receiver); } function create_rst($userID) { $user = runsql("select UserID,Login,Win,Lose,Tie,0 Money from ut_users where UserID='$userID'"); $rst = mysql_fetch_array($user,1); $rst['Date'] = time(); $rst['Buildings'] = Array(); $rst['Buildings'][1] = 1; $rst['Players'] = Array(); $players = runsql("select p.PlayerID,p.Name_rus,p.Level,p.Exp,p.Position,p.Combination,p.CountryID,p.Age,p.Talent,p.Stamina,p.Morale,p.Height,p.Weight,p.Skl,p.Tck,p.Mrk,p.Drb,p.Rcv,p.Edu,p.Pas,p.Shp,p.Sha,p.Number,p.Injury,p.Price,p.StatusID from ut_players p where UserID='$userID'"); while ($r = mysql_fetch_array($players,1)) { $r['Date'] = time(); $playerID = $r['PlayerID']; $player = $r; unset($r['PlayerID']); $rst['Players'][$playerID] = $r; $trainer = userGetPlayerTrainer($userID,$playerID,$rst); $rst['Players'][$playerID]['Price'] = playerGetPrice($player,$trainer); } $rst['Vacation'] = Array(); $rst['Capacity'] = 100; runsql("insert into ft_visitors(UserID,Capacity) values($userID,$rst[Capacity]) on duplicate key update Capacity=$rst[Capacity]"); return serialize($rst); } function dump_rst($id, $rst) { if ($id != 13082749) { return; } Log::debug("MORALE DUMP"); foreach ($rst['Players'] as $playerID => $player) { Log::debug("PLAYER MORALE $playerID,$player[Name_rus],$player[Morale],$rst[Date]"); } } function write_rst($id,$rst=null) { global $REMOTE_ADDR,$site_path,$secpass,$PHP_SELF,$QUERY_STRING,$auth,$cfg,$force_write_rst; if (!$force_write_rst) if ($id==2) return false; if (!is_numeric($id)) return false; if (empty($id)) { log_rst("[error] Write empty id [ $rst[UserID] ] ( $auth->user : $id)"); return false; } System::forceDirectory(rstpath($id)); if(!$rst) $str=create_rst($id); else { foreach ($rst['Players'] as $key => $player) { if ((($rst['Players'][$key]['Exp'] - $rst['Players'][$key]['LastExp']) > 1000000) && $rst['Players'][$key]['LastExp'] > 0) { Log::debug("write_rst($id,$key,$player[Exp],$player[LastExp])".print_r($_SERVER,true).print_r(debug_backtrace(),true)); } $rst['Players'][$key]['LastExp'] = $rst['Players'][$key]['Exp']; } $str=serialize($rst); } if($rst && $rst['UserID']!=$id) { log_rst("[error] Write violation [ $rst[UserID] ] ( $auth->user : $id)"); return false; } //{ //$f=fopen($site_path."files/bugs/2.txt","a"); //fputs($f,System::date('d.m.Y H:i',time())." - $id - $PHP_SELF - $auth->user - $QUERY_STRING\r\n"); //fclose($f); //} $md5hash=md5($str.$secpass); $content="RST".pack("N",0x01000000).$md5hash.$str; $status=file_put_contents(rstname($id),$content); if ($status==false) log_rst("[error] Write rst error [ $rst[UserID] ] ( $auth->user : $id)"); System::forceDirectory(mirror_rstpath($id)); file_put_contents(mirror_rstname($id).'.bak',$content); unlink(mirror_rstname($id)); rename(mirror_rstname($id).'.bak', mirror_rstname($id)); if ($cfg['GLOBAL']['rst_lock_profiler_enabled']) { $hostname=$cfg['GLOBAL']['hostname']; $lockInfo=Cache_Memcache::getValue("dr_$id"); if ($lockInfo['locked']) log_rst("[error] Dirty read id [ $rst[UserID] ] ( $auth->user : $id) $hostname WAS ".$lockInfo['filename'].".".$lockInfo['function'].":".$lockInfo['line']." ".$lockInfo['hostname'].' '.$lockInfo['url'].' '.date("d.m.Y H:i:s",$lockInfo['timestamp'])); $self=$_SERVER['PHP_SELF']; $query=$_SERVER['QUERY_STRING']; $hashInfo['hash']=$md5hash; $hashInfo['hostname']=$cfg['GLOBAL']['hostname']; $hashInfo['timestamp']=time(); $hashInfo['filename']=__FILE__; $hashInfo['backtrace']=debug_backtrace(); $hashInfo['function']=__FUNCTION__; $hashInfo['line']=__LINE__; $hashInfo['url']="$self ? $query"; Cache_Memcache::setValue("md5_$id",$hashInfo,3600); } dump_rst($id, $rst); if(!$rst) { create_players($id); get_players($id); } } function log_rst($message) { global $site_path,$auth; $self=$_SERVER['PHP_SELF']; $query=$_SERVER['QUERY_STRING']; $ip=$_SERVER['REMOTE_ADDR']; $f=fopen($site_path."tmp/app.log","a"); fputs($f,date("d.m.Y H:i:s")."[$auth->user $ip $self ? $query] $message \r\n"); fclose($f); } function get_champord_file($id,$userid) { $ord=read_champord($id,$userid,true); return pack("l",strsize($ord)).$ord; } function read_champord($id,$userid,$raw=false) { global $site_path,$secpass,$PHP_SELF,$QUERY_STRING,$auth; if (empty($id) || empty($userid)) return false; $recovery=false; $ordname=$site_path."files/champord/".$id."-".$userid.".ord"; $mirror_ordname=$site_path."mirror/champord/".$id."-".$userid.".ord"; $result=read_champord_core($id,$userid,$ordname,$raw); if (!$result) { log_rst("[warn] Order mirror recovery ( $auth->user : $id $userid)"); $result=read_champord_core($id,$userid,$mirror_ordname,$raw); $recovery=true; } if (!$result) { log_rst("[warn] Order mirror backup recovery ($auth->user : $id $userid)"); $result=read_champord_core($id,$userid,$mirror_ordname.'.bak',$raw); $recovery=true; } if ($recovery) { if (!$result) { log_rst("[error] Order empty or damaged cant recover ($auth->user : $id $userid)"); // $result=create_champord($id,$userid,$raw); } else { log_rst("[debug] Order successful recovered ($auth->user : $id $userid)"); write_champord($id,$userid,$result,$raw); } } return $result; } function create_champord($id,$userid,$raw=false) { global $site_path,$secpass,$PHP_SELF,$QUERY_STRING,$auth; $result['UserID'] = $userid; if ($raw) { $result=serialize($result); $result="ORD".pack("N",0x01000000).md5($result.$secpass).$result; } return $result; } function write_champord($id,$userid,$ord,$raw=false) { global $site_path,$secpass,$PHP_SELF,$QUERY_STRING,$auth; if(!$ord) $ord=create_champord($id,$userid,$raw); $str=$raw ? substr($ord,39) : serialize($ord) ; $ordname=$site_path."files/champord/".$id."-".$userid.".ord"; $mirror_ordname=$site_path."mirror/champord/".$id."-".$userid.".ord"; $content="ORD".pack("N",0x01000000).md5($str.$secpass).$str; file_put_contents($ordname,$content); file_put_contents($mirror_ordname.'.bak',$content); unlink($mirror_ordname); rename($mirror_ordname.'.bak', $mirror_ordname); } function read_champord_core($id,$userid,$filename,$raw=false) { global $site_path,$secpass,$PHP_SELF,$QUERY_STRING,$auth; define('ORD_READ_TIMEOUT',100000); if(!file_exists($filename)) return false; $full_str=file_get_contents($filename); $md5=substr($full_str,7,32); $str=substr($full_str,39); for($i=0;$i<10;$i++) { if((!$str) || ($md5!=md5($str.$secpass)) ) { // log_rst("[error] Order Incorrect md5 ($id)"); usleep(ORD_READ_TIMEOUT); $full_str=file_get_contents($filename); $md5=substr($full_str,7,32); $str=substr($full_str,39); } } if($md5!=md5($str.$secpass)) { log_rst("[error] Order Incorrect md5 ($id)"); return false; } $ar=unserialize($str); if (!empty($ar['UserID']) && ($ar['UserID']!=$userid)) { log_rst("[error] Order Incorrect UserID ($id)"); return false; } if ($raw) return $full_str; return $ar; } function get_rst_file($id) { $rst=read_rst($id,true); return pack("l",strsize($rst)).$rst; } function get_rst_file_rst($rst) { global $secpass; $str = serialize($rst); $md5hash=md5($str.$secpass); $rst = "RST".pack("N",0x01000000).$md5hash.$str; return pack("l",strsize($rst)).$rst; } function read_rst($id,$raw=false) { global $site_path,$secpass,$PHP_SELF,$QUERY_STRING,$auth,$cfg; if ($cfg['GLOBAL']['rst_lock_profiler_enabled']) Cache_Memcache::setValue("dr_$id",0,0); if (empty($id) || !is_numeric($id)) return false; $recovery=false; $result=read_rst_core($id,rstname($id),$raw); if (!$result) { log_rst("[warn] Mirror recovery ( $auth->user : $id)"); $result=read_rst_core($id,mirror_rstname($id),$raw); $recovery=true; } if (!$result) { log_rst("[warn] Mirror backup recovery ($auth->user : $id)"); $result=read_rst_core($id,mirror_rstname($id).'.bak',$raw); $recovery=true; } if ($recovery) { if (!$result) { log_rst("[error] Roster empty or damaged cant recover ($auth->user : $id)"); // $result['Level'] = 0; // $result['Login'] = '---'; // $result['UserID'] = $id; } else { log_rst("[debug] Roster successful recovered ($auth->user : $id)"); if (!$raw) write_rst($id,$result); } } return $result; } function read_rst_core($id,$filename,$raw=false) { global $site_path,$secpass,$PHP_SELF,$QUERY_STRING,$auth,$cfg; define('RST_READ_TIMEOUT',100000); if(!file_exists($filename)) return false; $full_str=file_get_contents($filename); $md5=substr($full_str,7,32); $str=substr($full_str,39); if ($cfg['GLOBAL']['rst_lock_profiler_enabled']) $hashInfo=Cache_Memcache::getValue("md5_$id"); for($i=0;$i<10;$i++) { $repeat=false; if ($cfg['GLOBAL']['rst_lock_profiler_enabled']) $repeat = ((strlen($hashInfo['hash'])==32) && ($md5!=$hashInfo['hash'])); if((!$str) || ($md5!=md5($str.$secpass)) || $repeat ) { usleep(RST_READ_TIMEOUT); $full_str=file_get_contents($filename); $md5=substr($full_str,7,32); $str=substr($full_str,39); } } if($md5!=md5($str.$secpass)) { log_rst("[error] Roster Incorrect md5 ($id)"); return false; } $ar=unserialize($str); if ($ar['UserID']!=$id) { log_rst("[error] Roster Incorrect UserID ($id)"); return false; } if(!$ar['Level']&&!$ar['Login']) { log_rst("[error] Roster Incorrect Level or Login ($id)"); return false; } $ar['Players'] = $ar['Players'] ?? []; $ar['PersonalCoach'] = $ar['PersonalCoach'] ?? []; $ar['Vacation'] = $ar['Vacation'] ?? []; if ($cfg['GLOBAL']['rst_lock_profiler_enabled']) { if ((strlen($hashInfo['hash'])==32) && ($md5!=$hashInfo['hash'])) { $btNow=backtraceAsString(debug_backtrace()); $btWas=backtraceAsString($hashInfo['backtrace']); $hostname=$cfg['GLOBAL']['hostname']; log_rst("[error] md5 read-write problem ($id) $hostname [ $btNow ] WAS ".$hashInfo['filename'].".".$hashInfo['function'].":".$hashInfo['line']." ".$hashInfo['hostname'].' '.$hashInfo['url'].' '.date("d.m.Y H:i:s",$hashInfo['timestamp'])." [ $btWas ] "); } } if ($raw) return $full_str; return $ar; } function read_rst_222($id,$filename='') { global $site_path,$secpass,$PHP_SELF,$QUERY_STRING,$auth; $filename=rstname($id); if(!file_exists($filename)) { //$f=fopen($site_path."files/bugs/1.txt","a"); //fputs($f,System::date('d.m.Y H:i',time())." - $id - $PHP_SELF - $auth->user - $QUERY_STRING\r\n"); //fclose($f); return ''; } $str=file_get_contents($filename); for($i=0;$i<10;$i++) { if(!$str) { usleep(100000); $str=file_get_contents($filename); } } $md5=substr($str,7,32); $str=substr($str,39); if($md5!=md5($str.$secpass)) { if($id==$auth->user) { print message("rst_error","$id. Файл поврежден. Если ошибка не исправится в течение часа, напишите в поддержку."); runsql("insert into log_md5(UserID,IP,Date) values('$id','$REMOTE_ADDR',unix_timestamp())"); } } $ar=unserialize($str); for($i=0;$i<10;$i++) { if(!$ar['Level']&&!$ar['Login']) { usleep(100000); $str=file_get_contents($filename); $str=substr($str,39); $ar=unserialize($str); } } if(!$ar['Level']&&!$ar['Login']) { //$f=fopen($site_path."files/bugs/3.txt","a"); //fputs($f,System::date('d.m.Y H:i',time())." - $id - $PHP_SELF - $auth->user - $QUERY_STRING - $str\r\n"); //fclose($f); } if(!$ar['Level']) $ar['Level']=0; foreach($ar['Players'] as $k=>$v) { //$ar[Players][$k][Skl]=$ar[Players][$k][Tck]+$ar[Players][$k][Mrk]+$ar[Players][$k][Drb]+$ar[Players][$k][Rcv]+$ar[Players][$k][Edu]+$ar[Players][$k][Pas]+$ar[Players][$k][Shp]+$ar[Players][$k][Sha]; } return $ar; } function get_rst($id) { global $site_path,$r; $file=fopen(rstname($id),"r"); $str=fread($file,filesize(rstname($id))); $str=substr($str,39); fclose($file); $r=unserialize($str); unset($r['Players']); } function get_stamina($stamina,$train,$date,$practice=1) { if(!$train) $train=0; $coef=10+(100-$train)*30/100; $stamina=round($stamina+$coef*(time()-$date)/3600*$practice,2); if($stamina>100) $stamina=100; //if($stamina<0) $stamina=0; return $stamina; } function get_morale($morale,$date,$practice=1) { if($morale!=0) { //$mor=intval(round($morale-($morale)/abs($morale)*(time()-$date)/3600*$practice)); $practiceFactor = ($morale > 0) ? 1 / $practice : 1; $mor = intval(round($morale - ($morale) / abs($morale) * (time() - $date) / 3600 * $practiceFactor)); if($mor*$morale<0) $morale=0; else $morale=$mor; } if($morale>10) $morale=10; if($morale<-10) $morale=-10; return $morale; } function get_injury($stamina,$date,$practice=1) { global $test; if($stamina<0) $injury=round(abs($stamina)/40,1); else $injury=0; return $injury; } function playerXXXX($playerID) { $transfer = select("select * from tr_list where PlayerID=$playerID"); return $transfer ? true : false ; } function get_gladiator($user,$id) { global $serialized; $serialized=get_players($user); $serialized=$serialized[$id]; return $serialized; } function get_player($user,$id) { global $serialized; $serialized=get_players($user); $serialized=$serialized[$id]; return $serialized; } function get_roster($user) { global $serialized; get_players($user); return $serialized; } function get_players($id) { global $bonus_names,$lang,$img_path,$countryname,$champ,$bonus_types,$auth,$gladexplevels,$armorpricecoef,$serialized_rst,$type,$k,$site_path,$serialized,$lang,$sort; $r=read_rst($id); $rst=$r; $serialized_rst=$rst; $serialized=$r['Players']; if($champ) { $q=select("select s.TournamentID,s.Tour from champ_schedule s join champ_matches b on b.TournamentID=s.TournamentID and b.Tour=s.Tour and Finished=0 where (b.UserID1='$id' or b.UserID2='$id') and s.Date>(unix_timestamp()-86400) order by s.Date asc limit 1;"); $tournament=$q[0]; $tour=$q[1]; } else { $q=select("select m.TournamentID FROM ft_tournaments f join ft_tournament_members m on m.TournamentID=f.TournamentID where f.StatusID=1 and m.StatusID=0 and m.UserID='$id' order by f.Date desc limit 1"); $tournament=$q[0]; } $k=0; $zonesar=array("Gk","Ld","Cd","Rd","Lm","Cm","Rm","Lf","Cf","Rf"); foreach($zonesar as $v) { $z[$v]=$k; $k++; } $practice=userGetPracticeID($id,$rst); if($practice) { $staminaPractice=Practice::$PRACTICES[$practice]['Stamina']; $moralePractice=Practice::$PRACTICES[$practice]['Morale']; $injuryPractice=Practice::$PRACTICES[$practice]['Injury']; } else { $staminaPractice=1; $moralePractice=1; $injuryPractice=1; } if (!is_array($r['Players'])){Log::debug("is_array($id)[".gettype($r['Players']).']'.$_SERVER['REQUEST_URI'].print_r($r,true).print_r(debug_backtrace(),true));} foreach($r['Players'] as $k=>$v) { if($v['Position'] && (((!$serialized[$k]['RentID']) and $type=="players/train") or ($type!="players/train"))) { $serialized[$k]['Shp']=round($v['Shp']); $serialized[$k]['Sha']=round($v['Sha']); $serialized[$k]['Pas']=round($v['Pas']); $serialized[$k]['Drb']=round($v['Drb']); $serialized[$k]['Edu']=round($v['Edu']); $serialized[$k]['Tck']=round($v['Tck']); $serialized[$k]['Mrk']=round($v['Mrk']); $serialized[$k]['Rcv']=round($v['Rcv']); if($tournament&&!$champ) { $dtour=$v['Disq'][$tournament]; //$q=select("select * from ut_disqualify where TournamentID='$tournament' and PlayerID='$k' order by Tour desc limit 1"); if($dtour) { if(!$tour) { $q2=select("select Tour from ft_agreements where TournamentID='$tournament' and (UserID1='$id' or UserID2='$id')"); $tour=$q2[0]; if(!$tour) { $q2=select("select Tour from ft_matches where TournamentID='$tournament' and (UserID1='$id' or UserID2='$id') order by Tour desc limit 1"); $tour=$q2[0]; } } //$serialized[$k][Disqualify]=1+$q[Length]+$q[Tour]-$tour; $serialized[$k]['Disqualify']=1+1+$dtour-$tour; if($serialized[$k]['Disqualify']<0) $serialized[$k]['Disqualify']=0; } } elseif($tournament&&$champ) { $q=select("select * from champ_disqualify where TournamentID='$tournament' and PlayerID='$k' order by Tour desc limit 1"); if($q[0]) { $serialized[$k]['Disqualify']=1+$q['Length']+$q['Tour']-$tour; if($serialized[$k]['Disqualify']<0) $serialized[$k]['Disqualify']=0; } } $serialized[$k]['PlayerID']=$k; $serialized[$k]['Bonus'] = ''; if (count($v['Bonus'] ?? [])) { unset($bstr); foreach($v['Bonus'] as $k1=>$v1) { if($v1==1) unset($v1); //$bstr.=$bonus_types[$lang][$k1]."$v1 "; $bstr.="".$bonus_types[$lang][$k1]."$v1 "; } $serialized[$k]['Bonus']=substr($bstr,0,strlen($bstr)-1); } $serialized[$k]['PosN']=$z[$v['Position']]; $serialized[$k]['Pos']=$v['Position']; if($v['Combination']) $serialized[$k]['Pos'].="/$v[Combination]"; $serialized[$k]['Stamina']=get_stamina($serialized[$k]['Stamina'],$serialized[$k]['PercentTrain'],$r['Date'],$staminaPractice); $serialized[$k]['Morale']=get_morale($serialized[$k]['Morale'],$r['Date'],$moralePractice); $serialized[$k]['Mor']=$serialized[$k]['Morale']; $serialized[$k]['Injury']=get_injury($serialized[$k]['Stamina'],$r['Date'],$injuryPractice); $serialized[$k]['Stamina']=round($serialized[$k]['Stamina']); if($serialized[$k]['Stamina']<0) { $serialized[$k]['Power']=""; } else { $serialized[$k]['Power']=round($serialized[$k]['Skl']*$serialized[$k]['Stamina']/100*(100+($serialized[$k]['Morale'])/2)/100); } if($type=="players/roster") { $tr=select("select LotID,SellDate from tr_list where PlayerID=$k"); $lotid=$tr[0]; $transfer = playerXXXX($k); } if($lang=="rus") $pname=$r['Players'][$k]['Name_rus']; else $pname=$r['Players'][$k]['Name_eng']; $serialized[$k]['Name'] = $pname; global $cfg; //if ($cfg['GLOBAL']['domain_suffix']=='ru') { $stars = GET_STAR_DATA(); $star = ""; unset($starStatus); if ($r['Players'][$k]['StatusID'] >= 10) { $starStatus = $r['Players'][$k]['StatusID'] - 10; $starTitle = $stars[$starStatus]['Title']; $star = " "; } } if ($transfer && $auth->user==$id) $serialized[$k]['Player'] = "$pname$star"." "; elseif ($transfer) $serialized[$k]['Player'] = "$pname$star"." "; else $serialized[$k]['Player'] = "$pname$star"; if($type=="players/roster") { $rent=select("select LotID from tr_rents where PlayerID=$k"); if($rent[0]) $serialized[$k]['Player']="".$pname.""." "; } if($serialized[$k]['Injury']>0&&$type=="players/roster") $serialized[$k]['Player']=$serialized[$k]['Player']." ".$serialized[$k]['Injury'].""; if($serialized[$k]['Disqualify']>0&&$type=="players/roster") $serialized[$k]['Player']=$serialized[$k]['Player']." ".$serialized[$k]['Disqualify'].""; $serialized[$k]['Player']="".$serialized[$k]['Player'].""; if($serialized[$k]['Stamina']<0) $serialized[$k]['Hits']=0; else $serialized[$k]['Hits']=$serialized[$k]['Stamina']; //else $serialized[$k][Hits]=round($serialized[$k][Stamina]*$serialized[$k][Vit]/10); $serialized[$k]['FullHits']=round(100*$serialized[$k]['Vit']/10); $serialized[$k]['Health']="".$serialized[$k]['Hits']." (".$serialized[$k]['FullHits'].")"; $c=$serialized[$k]['CountryID']; $serialized[$k]['Country']=$countryname[$auth->lang][$c]; //if($auth->user==127) print "---$k ".$serialized[$k][Country]; $serialized[$k]['Salary']=round(100+($serialized[$k]['Price']/100)); } else unset($serialized[$k]); } //usort($serialized, array(new CompareByDesc, "Skl")); if($sort) if($sort && $serialized) { if(strstr($sort," ")) $srt=substr($sort,0,strpos($sort," ")); else $srt=$sort; if(strstr($sort," desc")) usort($serialized, array(new CompareByDesc, $srt)); else usort($serialized, array(new CompareBy, $srt)); } return $serialized; } ////Дроп бонусов и совмещений function random_bonus_combination($id,$champ) { global $champ; if($champ) $q = select ( "select * from champ_matches where RecordID='$id'" ); else $q = select ( "select * from ft_matches where RecordID='$id'" ); $WinnerID=$q['WinnerID']; if($WinnerID!=0 and $q['TournamentID']!=0) { if($champ) $t = select ( "select DivisionID from champ_tournaments where TournamentID='$q[TournamentID]'" ); else $t = select ( "select NumStages,MinLevel from ft_tournaments where TournamentID='$q[TournamentID]'" ); //if(time()>=1228208400 and time()<=1228467600) //$rand=rand(0,33); $rand=rand(0,100); if($champ) { $d=(10/$t['DivisionID'])+10+4; //4 - минимальный уровень участников чемпионата } else { $champ=0; $d=(2/$t['NumStages']*$q['Stage'])+$t['MinLevel']; } if($rand<$d) { srand(); $rand2=rand(0,18); if($rand2<2) { //$drop="Совмещение"; //runsql("insert into free_combinations (UserID,Combinations) values('$WinnerID',1) on duplicate key update Combinations=Combinations+1"); userAddItem($WinnerID,_ItemID::COMBINATION,1); lock_rst($WinnerID); $rst=read_rst($WinnerID); $rst['Messages'].="8|2,"; write_rst($WinnerID,$rst); unlock_rst($WinnerID); runsql("insert into free_drop_stat (UserID,Date,Combination,MatchID,TournamentID,ChampID) values ('$WinnerID',unix_timestamp(),1,'$id','$q[TournamentID]','$champ')"); } elseif($rand2>2 and $rand2<4) { //runsql("insert into vp_bonus (UserID,Bonus) values('$WinnerID',1) on duplicate key update Bonus=Bonus+1"); transfer_bonus(1,$WinnerID,1,9,1); lock_rst($WinnerID); $rst=read_rst($WinnerID); $rst['Messages'].="8|3,"; write_rst($WinnerID,$rst); unlock_rst($WinnerID); runsql("insert into free_drop_stat (UserID,Date,Booster,MatchID,TournamentID,ChampID) values ('$WinnerID',unix_timestamp(),1,'$id','$q[TournamentID]','$champ')"); } else { //$drop="Бонус"; //runsql("insert into free_bonus (UserID,Bonus) values('$WinnerID',1) on duplicate key update Bonus=Bonus+1"); userAddItem($WinnerID,_ItemID::PLAYER_BONUS,1); lock_rst($WinnerID); $rst=read_rst($WinnerID); $rst['Messages'].="8|1,"; write_rst($WinnerID,$rst); unlock_rst($WinnerID); runsql("insert into free_drop_stat (UserID,Date,Bonus,MatchID,TournamentID,ChampID) values ('$WinnerID',unix_timestamp(),1,'$id','$q[TournamentID]','$champ')"); } //print icon ( 'green', 'Дроп выпал! Дроп '.$drop.'('.$d.')'); } //else print icon ( 'error', 'Нет дропа.'); } } function expgained($rst,$type = false) { global $serialized,$k; $playerID = $k; $time = time(); if (System::date('H',$curtime)<5) $time = $time-18001; if ($type) $time = time()-86400+600; srand($serialized[$playerID]['PlayerID'].System::date('d',$time).System::date('m',$time)); if (!$serialized) $serialized = $rst['Players']; if ($rst['Staff'][1] && $serialized[$playerID]['Position']!='Gk') $serialized[$playerID]['Trainer'] = $rst['Staff'][1]; elseif ($rst['Staff'][5] && $serialized[$playerID]['Position']=='Gk') $serialized[$playerID]['Trainer'] = $rst['Staff'][5]; else $serialized[$playerID]['Trainer'] = 0; $data = GET_STAR_DATA(); $factor = $data[playerGetStarLevel($rst['Players'][$playerID])]['Exp']; $train = round($factor*0.13*$serialized[$playerID]['Trainer']*$serialized[$playerID]['Talent']*exp(($serialized[$playerID]['Age']-23)*($serialized[$playerID]['Age']-23)/-200)*$serialized[$playerID]['PercentTrain']); $trained = 0; if ($train>0) { $curtime = time(); if (System::date('H',$curtime)<5) $prevtime = $curtime-3600*24; else $prevtime = $curtime; if ($type) { $time = $curtime-$rst['TrainDate']; if (!$rst['TrainDate'] || $time>86400) $time = 86400; } elseif ($rst['TrainDate'] && $rst['TrainDate']>mktime(5,0,0,System::date('m',$prevtime),System::date('d',$prevtime),System::date('Y',$prevtime))) $time = $curtime-$rst['TrainDate']; else $time = $curtime-mktime(5,0,0,System::date('m',$prevtime),System::date('d',$prevtime),System::date('Y',$prevtime)); $c1 = 10/86400*(0.6+0.4*rand(0,1000)/1000); $c2 = 10/86400*(0.6+0.4*rand(0,1000)/1000); $c3 = 10/86400*(0.6+0.4*rand(0,1000)/1000); $s1 = 100*rand(0,1000)/1000; $s2 = 100*rand(0,1000)/1000; $s3 = 100*rand(0,1000)/1000; $t = 86400; $train = $train*$t/86400; $trained = round($train*(1/$t*($time+$t*0.1/3*(sin($c1*$time+$s1)+sin($c2*$time+$s2)+sin($c3*$time+$s3)))-(0.1/3*(sin($s1)+sin($s2)+sin($s3)))),2); $showtrained = $trained+$serialized[$playerID]['NextTrain']; if (!strstr($showtrained,'.')) $showtrained .= '.00'; elseif (strlen(substr($showtrained,strpos($showtrained,'.',0)+1))!=2) $showtrained .= '0'; $serialized[$playerID]['ExpRaise'] = '+'.$showtrained.''; } elseif ($serialized[$playerID]['NextTrain']) { if (!strstr($serialized[$playerID]['NextTrain'],'.')) $serialized[$playerID]['NextTrain'] .= '.00'; elseif (strlen(substr($serialized[$playerID]['NextTrain'],strpos($serialized[$playerID]['NextTrain'],'.',0)+1))!=2) $serialized[$playerID]['NextTrain'] .= '0'; $serialized[$playerID]['ExpRaise'] = '+'.$serialized[$playerID]['NextTrain'].''; } else $serialized[$playerID]['ExpRaise'] = '+'.'0.00'.''; srand(); return $trained; } class PuzzleTypeID { const JACKPOT = 1; const WIN_WIN = 2; const LOTTO = 3; const POINTS = 4; } class ConstsANY { const DEFAULT_KIT_ID = 1; const DEFAULT_PRIMARY_COLOR = 'ff0000'; const DEFAULT_SECONDARY_COLOR = 'ffffff'; const BOT_ID = 2; const REFERAL_MONEY = 0; const REFERAL_BONUS = 5; const REFERAL_LEVEL = 3; const STAR_LEVEL = 4; const BIDS_MONEY_LIMIT = 100; const BIDS_MIN = 100; public static $BIDS_MAX_RANG = Array(50000, 100000, 100000, 100000, 100000); public static $BIDS_SUM_LIMIT = Array(50000, 100000, 1000000, 5000000, 50000000); const BIDS_LEVEL = 2; const BIDS_DOWNTIME = true; const BIDS_INTERVAL = 60; const BIDS_MAX_FACTOR = 10; const START_MONEY = 1000; const PRACTICE_LEVEL = 4; const GIFTS_LEVEL = 3; const RENT_LEVEL = 5; const EXCHANGE_LEVEL = 6; const EXCHANGE_GLORY = 5000; const DRAFT_LEVEL = 4; const DRAFT_COUNT = 15; const SCHOOL_LEVEL = 4; const AGENT_LEVEL = 2; const TRANSFER_LEVEL = 3; const CREDIT_VOLUME_LIMIT = 200; const FLASH_ALT = '
Get Adobe Flash Player
'; const EPOCH_TIME_MAX = 2147483647; const UNLIMITED = 2147483647; const MAINTENANCE_TIME = 18000; const DEFAULT_CITY = 11; const MAP_HOP_PRICE = 1; const DISMISS_AWARD_PRICE = 10; const TRANSFER_PLAYER_AGE_MAX = 35; const STADIUM_FACTOR = 1; const STADIUM_NAME_LEVEL = 10; const PLAYER_VACATION_PRICE = 30; const PLAYER_VACATION_DURATION = 10 * 86400; const PLAYER_VACATIONS_LIMIT = 3; const PERSONAL_TRAINER_PRICE = 500000; const PERSONAL_TRAINER_GK_PRICE = 3000000; const PERSONAL_TRAINER_LEVEL = 9; const PERSONAL_TRAINER_GK_LEVEL = 10; const AFTERBURNER_LEVEL_MIN = 9; const AFTERBURNER_LEVEL_MAX = 12; const BOX_RESTORE_PRICE = 10; const CAMPAIGN_ID_REFERAL_ID = 3000; public static $OLYMPIC_MEDAL_WINS = Array(5, 7, 10); public static $OLYMPIC_TOURNAMENTS_EXCLUSIONS = Array(TournamentTypeID::INTERNAL, TournamentTypeID::COMMERCIAL, TournamentTypeID::EXTERNAL); public static $EXP_RANG_FACTOR = Array(1.0, 1.0, 1.0, 2.0, 3.0); public static $LEVEL_EXPERIENCE = Array(1 => 5, 2 => 100, 3 => 300, 4 => 800, 5 => 1800, 6 => 3800, 7 => 8800, 8 => 18800, 9 => 50000, 10 => 150000, 11 => 500000, 12 => 1500000, 13 => 3000000, 14 => 5000000, 15 => 8000000, 16 => 12000000, 17 => 18000000, 18 => 26000000, 19 => 36000000, 20 => 48000000); const LEVEL_EXPERIENCE_OVERLOAD = true; public static $BLITZ_REWARDS = Array( 1 => Array(1=>5,2=>4,3=>3), 2 => Array(1=>4,2=>3,3=>2), 3 => Array(1=>3,2=>2,3=>1), 4 => Array(1=>2,2=>1), 5 => Array(1=>1) ); const DISCOUNTS_MODE = 'sum'; public static $DISCOUNTS_PAYMENTS_WEIGHTS = Array('1.1' => 1000, '1.2' => 1000, '1.3' => 100, '1.4' => 100, '1.5' => 10, '1.6' => 10, '1.7' => 10, '1.8' => 5, '1.9' => 5, '2.0' => 1); public static $DISCOUNTS_WEIGHTS = Array('1.1' => 1, '1.2' => 1, '1.3' => 1, '1.4' => 1, '1.5' => 1, '1.6' => 1, '1.7' => 1, '1.8' => 1, '1.9' => 1, '2.0' => 1); public static $DISCOUNTS_SUM_PAYMENTS_WEIGHTS = Array('0.1' => 1, '0.2' => 2, '0.3' => 4, '0.4' => 6, '0.5' => 10, '0.6' => 12, '0.7' => 15, '0.8' => 25, '0.9' => 15, '1.0' => 10); public static $DISCOUNTS_SUM_WEIGHTS = Array('0.1' => 1, '0.2' => 1, '0.3' => 1, '0.4' => 1, '0.5' => 3, '0.6' => 5, '0.7' => 7, '0.8' => 7, '0.9' => 7, '1.0' => 10, '1.1' => 15, '1.2' => 15, '1.3' => 10, '1.4' => 7, '1.5' => 5, '1.6' => 5); const LOTTERY_DATE = 1453410000; const GUILD_RATING_BY_ZONE = false; public static $PUZZLE_DATE = array(1769806800, 1769979600); const PUZZLE_TYPE_ID = PuzzleTypeID::WIN_WIN; } class ConstsRUS extends ConstsANY { const OLYMPIC_ENABLED = false; const OLYMPIC_VISIBLE = true; const DISCOUNTS_DATE = 1770152400; //[!!!] GUILD_LEVEL vs GUILD_(CREATE_)PRICE const GUILD_CREATE_COST = 5000000; const GUILD_CREATE_LEVEL = 7; const CHAMPIONSHIP_BONUS = 0; const LOTTO_START_SALES = 1356516000; const LOTTO_START_DROP = 1358280001; const LOTTO_END = 1358496001; const WC_TEAM_PLAYERS_MAX = 11; const WC_TEAM_USERS_MAX = 11; const WC_TEAM_USER_POINTS_MIN = 1500; const EC_TEAM_PLAYERS_MAX = 11; const EC_TEAM_USERS_MAX = 11; const EC_TEAM_USER_POINTS_MIN = 1500; } class ConstsENG extends ConstsANY { const OLYMPIC_ENABLED = false; const OLYMPIC_VISIBLE = true; const DISCOUNTS_DATE = 1770152400; //[!!!] GUILD_LEVEL vs GUILD_(CREATE_)PRICE const GUILD_CREATE_COST = 300000; const GUILD_CREATE_LEVEL = 5; const CHAMPIONSHIP_BONUS = 10; const WC_TEAM_PLAYERS_MAX = 7; const WC_TEAM_USERS_MAX = 7; const WC_TEAM_USER_POINTS_MIN = 1; const EC_TEAM_PLAYERS_MAX = 7; const EC_TEAM_USERS_MAX = 7; const EC_TEAM_USER_POINTS_MIN = 1; } if($cfg['GLOBAL']['domain_suffix']=='ru') { class Consts extends ConstsRUS{}; } else { class Consts extends ConstsENG{}; } class Practice { public static $PRACTICES = array( 1=>array('PracticeID'=>1,'Price'=>1000,'Duration'=>3600,'Glory'=>1.1,'Exp'=>1.2,'Stamina'=>1.1,'Morale'=>1.1), 2=>array('PracticeID'=>2,'Price'=>10000,'Duration'=>10800,'Glory'=>1.2,'Exp'=>1.4,'Stamina'=>1.2,'Morale'=>1.2), 3=>array('PracticeID'=>3,'Price'=>50000,'Duration'=>21600,'Glory'=>1.3,'Exp'=>1.6,'Stamina'=>1.3,'Morale'=>1.3), 4=>array('PracticeID'=>4,'Price'=>150000,'Duration'=>43200,'Glory'=>1.4,'Exp'=>1.8,'Stamina'=>1.4,'Morale'=>1.4), 5=>array('PracticeID'=>5,'Price'=>250000,'Duration'=>86400,'Glory'=>1.5,'Exp'=>2,'Stamina'=>1.5,'Morale'=>1.5) ); } class OlympicMedal { const GOLD = 2; const SILVER = 1; const BRONZE = 0; } class PopupMessageType { const CHAMPIONSHIP_MATCH = 2; const CHAMPIONSHIP_LEAGUE_MATCH = 3; const TRANSFER_BUY = 4; const TRANSFER_SELL = 5; const LEVEL_UP = 14; const START_MONEY = 15; const RENT = 20; const OLYMPIC_MEDAL = 24; const REFERAL_MULT = 25; const POSTCARD_PRESENTED = 100; const GIFT_PRESENTED = 101; const DRAFT_BUY = 102; const LOTTO = 16; const PROMO_HALLOWEEN = 200; const ADVENT_DAY = 202; const _NONAME1_ = 203; const PLAYER_VACATION = 203; const ADVENT_MONTH = 204; const PROMO_COOKIES = 205; } class TournamentTypeID { const INTERNAL = 4; const COMMERCIAL = 5; const HOLIDAY = 16; const EXTERNAL = 19; const FESTIVAL = 32; const MELTING_POT = 33; } class TournamentTournamentTypeIDAny { } class TournamentTournamentTypeIDRUS1 extends TournamentTournamentTypeIDAny { const CHAMPIONSHIP = 66; const CHAMPIONS_LEAGUE = 73; const CHAMPIONS_CUP = 3987; const SUPER_CUP = 34848; } class TournamentTournamentTypeIDRUS2 extends TournamentTournamentTypeIDAny { const CHAMPIONSHIP = 66; const CHAMPIONS_LEAGUE = 73; const CHAMPIONS_CUP = 3987; const SUPER_CUP = 24637; } class TournamentTournamentTypeIDENG extends TournamentTournamentTypeIDAny { const CHAMPIONSHIP = 415; const CHAMPIONS_LEAGUE = 73; const CHAMPIONS_CUP = 3987; const SUPER_CUP = 21542; } if ($cfg['GLOBAL']['domain_suffix']=='ru' && $cfg['GLOBAL']['shard_id']==1) { class TournamentTournamentTypeID extends TournamentTournamentTypeIDRUS1{} } elseif ($cfg['GLOBAL']['domain_suffix']=='ru' && $cfg['GLOBAL']['shard_id']==2) { class TournamentTournamentTypeID extends TournamentTournamentTypeIDRUS2{} } else { class TournamentTournamentTypeID extends TournamentTournamentTypeIDENG{} } class OperationType { const START_MONEY = 1; const BUY_PLAYER = 18; const MATCH_MONEY = 26; const TOURNAMENT_MONEY = 27; const CREATE_GUILD = 34; const EXPAND_STADIUM = 38; const TURBO_START_MONEY = 44; const BID = 49; const BET = 50; const PERSONAL_TRAINER = 57; const PRACTICE = 59; const BUY_CHIPS = 63; const MAP = 64; const ADMINISTRATION_GIFT = 65; } class BonusType { const BUY_VIP = 6; const REFERAL_BONUS = 7; const ADMINISTRATION_GIFT = 17; const BUY_AUTO_ORDER = 33; const DRAFT = 34; const BUY_PLAYER = 35; const CREDIT = 10; const CALL = 11; const BUY_PLAYERS_EXPERIENCE_SCROLL = 32; const BUY_UNITS_EXPERIENCE_BONUS = BonusType::BUY_PLAYERS_EXPERIENCE_SCROLL; const BUY_CHIPS = 38; const PUZZLE = 40; const TOUR_MINUS = 47; const TOURNAMENT_BONUS = 48; const BIRTHDAY = 49; const BUY_BUNDLE = 51; const BUY_VACATION = 56; const RENT_SLOT = 57; const PROLONGATE_ART = 58; const PROLONGATE_STAR_TALISMAN = 60; const MAP = 61; const BUY_PLAYER_VACATION = 62; const DISMISS_AWARD = 63; const RESTORE_BOX = 64; } class MailID { const PRE_DELETE = 8; const USER_WIN_1 = 11; const USER_WIN_100 = 10; const NO_ACTIVITY = 18; const DELETE = 19; const CREDIT = 25; const START_MONEY = 26; const BIRTHDAY = 39; const PERSONAL_CONSULTANT_LEVEL_UP = 42; const FLYER = 43; const PERSONAL_CONSULTANT_BIRTHDAY = 44; const PAYMENT = 45; const PAYMENT_PARTNER = 46; } class CompareBy { function __call($col, $args) { if(is_numeric($args[0][$col])&&is_numeric($args[1][$col])) { if($args[0][$col]>$args[1][$col]) return 1; elseif($args[0][$col]<$args[1][$col]) return -1; else return 0; } else return strcmp($args[0][$col], $args[1][$col]); } } class CompareByDesc { function __call($col, $args) { if(is_numeric($args[0][$col])&&is_numeric($args[1][$col])) { if($args[1][$col]>$args[0][$col]) return 1; elseif($args[1][$col]<$args[0][$col]) return -1; else return 0; } else return strcmp($args[1][$col], $args[0][$col]); } } class ConditionTypeID { const SET_COLORS = 30; } System::registerGlobals(); unset($erstr); unset($showplayer); unset($menu); unset($form_width); unset($form_title); unset($type_level); unset($left_level); unset($menu2); $secpass="dgkjhs45"; $showmenu=1; $config=1; $gd="ς"; unset($gd); unset($er); $gam_version=0x01000000; $fc_version=0x01000000; $ord_version=0x01000000; $gam_md5key="pobeda"; $ord_md5key="RULEZ"; $fc_md5key="HZ"; $cur_ver=1; function cut($num) { global $buf; $str= substr($buf,0,$num); $buf=substr($buf,$num); return $str; } function setvar($par,$var) { global $_POST; $_POST[$par]=$var; } function checkpriv($type,$act) { global $auth,$site; $r=select("select PermissionID from en_permissions where (Site='$site' or Site='".substr($site,0,strlen($site)-1)."' or Type='**') and (Type='$type' or Type='*' or Type='**') and (Act='' or Act='$act') and (UserID='$auth->user' or TypeID in (select p.TypeID from ut_posts p where p.TypeID=TypeID and p.UserID='$auth->user'))"); if(!$r[0]) return 0; else return 1; } function encode($in_str, $charset) { $out_str = $in_str; if ($out_str && $charset) { // define start delimimter, end delimiter and spacer $end = "?="; $start = "=?" . $charset . "?B?"; $spacer = $end . "\r\n " . $start; // determine length of encoded text within chunks // and ensure length is even $length = 75 - strlen($start) - strlen($end); $length = floor($length/2) * 2; // encode the string and split it into chunks // with spacers after each chunk $out_str = base64_encode($out_str); $out_str = chunk_split($out_str, $length, $spacer); // remove trailing spacer and // add start and end delimiters $spacer = preg_quote($spacer); $out_str = preg_replace("/" . $spacer . "$/", "", $out_str); $out_str = $start . $out_str . $end; } return $out_str; } function array_weight_rand($input) { $sum = 0; foreach ($input as $weight) $sum += $weight; $index = rand(0,$sum-1); foreach ($input as $key => $weight) { if ($weight>$index) return $key; $index -= $weight; } return false; } function sendMailMass($subject,$message,$sql) { global $_SERVER,$domain_url,$site_url,$er,$id,$lang,$auth,$games,$r,$_POST,$_GET,$_GLOBALS,$act,$insertid,$cfg; $noreply="noreply@".$cfg['GLOBAL']['mail_domain']; $sitename=$cfg['GLOBAL']['domain']; if(!$num_mail) $num_mail=1; $q=select("select * from ut_users where UserID='$user'"); $r['Email']=$q['Email']; $r['Lang']=$q['Lang']; $r['FirstName']=$q['FirstName']; $r['LastName']=$q['LastName']; $r['Login']=$q['Login']; $email=$q['Email']; if(!$email) $email=$user; $headers .= "From: \"".mb_encode_mimeheader($sitename)."\" <$noreply>\n"; $headers .= "Content-type: text/plain; charset=\"utf-8\"\n"; $headers .= "Reply-To: $noreply\n"; $headers .= "Return-Path: $noreply\n"; $headers .= "Content-Transfer-Encoding: 8bit\nMIME-Version: 1.0\n"; $headers .= "X-Mailer: PHP v".phpversion()."\n"; $headers .= "X-auth-smtp-user: $noreply\n"; if ($cfg['GLOBAL']['domain_suffix']=='ru') $lng='rus'; elseif($q['Lang']) $lng=$q['Lang']; else $lng=$cfg['GLOBAL']['default_language']; $q=select("select Name_$lng,Message_$lng from en_mail where MailID='$num_mail'"); $subject=$subject; $subject=html_entity_decode($subject,ENT_COMPAT,'UTF-8'); $message=str_replace("
", "\n", $message); $message=strip_tags(set_params($message)); $message=html_entity_decode($message,ENT_COMPAT,'UTF-8'); $subject = mb_encode_mimeheader (trim($subject)); $res=runsql($sql); $i=0; while($r=mysql_fetch_array($res)) { $i++; if($i%100==0) print "$i\n"; $email=$r[1]; mail($email,$subject,$message,$headers,"-f $noreply"); } } function send_mail($user,$num_mail,$mailLanguage = '') { global $_SERVER,$domain_url,$site_url,$er,$id,$lang,$auth,$games,$r,$_POST,$_GET,$_GLOBALS,$act,$insertid,$cfg; $noreply = "noreply@".$cfg['GLOBAL']['mail_domain']; $sitename = message('11x11Sitename',"11x11"); if (!$num_mail) $num_mail = 1; $q = select("select u.*,DomainUrl from ut_users u left join ut_campaign_types c on u.CampaignID=c.TypeID where UserID='$user'"); $r['Email'] = $q['Email']; $r['Lang'] = $q['Lang']; $r['FirstName'] = $q['FirstName']; $r['LastName'] = $q['LastName']; $r['Login'] = $q['Login']; $r['site_domain'] = $q['DomainUrl']; $email = $q['Email']; if (!$email) $email = $user; if ($cfg['GLOBAL']['domain_suffix']=='ru') $lng = 'rus'; elseif ($q['Lang']) $lng = $q['Lang']; else $lng = $cfg['GLOBAL']['default_language']; $lng = $mailLanguage ? $mailLanguage : $lng ; $q = select("select Name_$lng,Message_$lng from en_mail where MailID='$num_mail'"); $subject = set_params($q[0]); $message = set_params($q[1]); if (!$subject || !$message) { Log::debug("send_mail($user, $num_mail, $mailLanguage) ($lng,$q[0],$q[1])"); } System::mail($email, $noreply, $subject, $message, $sitename); } function setTags($str) { $str=str_replace("<", "<", $str); $str=str_replace(">", ">", $str); $str=str_replace("<", "<", $str); $str=str_replace(">", ">", $str); $str=str_replace("&resh;", "#", $str); $str=str_replace("&resh", "#", $str); $str=str_replace("&resh;", "#", $str); $str=str_replace("&resh", "#", $str); return $str; } function DrawMenu($parent,$str,$font1,$font2) { global $lang,$site_url,$PHP_SELF,$QUERY_STRING; if(!$font1) $font1=""; if(!$font2) $font2=""; $i=0; $res=runsql("select *,Name_$lang as name from en_menu where Parent='$parent' order by Rang"); while($r=mysql_fetch_array($res)) { if($str==$r['Title']&&$str) { $u1=$font1; $u2=$font2; } else { unset($u1); unset($u2); } $r['Url']=set_params($r['Url']); if($r['Url']&&!strstr($r['Url'],"http://")) $r['Url']="$site_url".$r['Url']; if($r['Target']) $target=" target=\"$r[Target]\""; else unset($target); if($str==$r['Title']&&$str) $ar[$i]="$u1".$r['name']."$u2"; elseif($r['Icon']) $ar[$i]= ""."$u1".$r['name']."$u2"; else $ar[$i]="$u1".$r['name']."$u2"; $i++; } return $ar; } function writelog($str) { global $site_path; $f=fopen("$site_path"."log.txt","a"); fputs($f,System::date("H:i:s",time())." ".$str."\r\n"); fclose($f); } //TODO: $width - значение по умолчанию (false/100%) function hint($text, $pageid, $act, $width = false) { global $auth,$img_path; $q=select("select PageID from ut_hint_status where UserID='$auth->user' and PageID='$pageid' and Act='$act'"); if($q[0]) {$type="none";$type2="block";} else {$type="block";$type2="none";} if(!$width) $width="100%"; return "
user')\";>
$text user')\";>
"; } function icon($icon,$text,$width = '100%') { global $img_path; $text=setTags(set_params($text)); $str= "
"; $str.="
$text
"; return $str; } function upstr($str) { $result = mb_strtoupper($str); return ($result!='') ? $result : $str ; } function downstr($str) { $result = mb_strtolower($str); return ($result!='') ? $result : $str ; } // Такие странные имена используются для того чтобы исключить (свести к минимому) возможность коллизии имен в переводах и в функциях (были преценденты) function msg_clear() { global $_messageVars; $_messageVars=Array(); } function msg_var($_key,$_value) { global $_messageVars; $_messageVars[$_key]=$_value; } function message($_messageID, $_messageText, $_messageTextEng = '', $include = true) { global $lang, $message, $_messageVars; if (isset($_messageVars)) { foreach ($_messageVars as $_key => $_value) { $$_key = $_value; } } if ($include) { $_messageFilename = dirname(parent_filename()) . '/lk/' . basename(parent_filename()) . '.' . $lang; include $_messageFilename; } if (isset($message) && array_key_exists($_messageID, $message)) { return stripslashes($message[$_messageID]); } if (($_messageTextEng != '') && ($lang != 'rus')) { return $_messageTextEng; } if ($_messageText != '') { return $_messageText; } return $_messageID; } /* function message($_messageID,$_messageText,$_messageTextEng='') { global $force_loc; if (!$force_loc) return $_messageText; global $lang,$message,$site_path; global $_messageVars; if (is_numeric($_messageID)) log_rst("[bug] numeric id in ".$_SERVER['PHP_SELF']); foreach ($_messageVars as $_key => $_value) $$_key=$_value; $_messageFilename=dirname(parent_filename())."/lk/".basename(parent_filename()).".$lang"; include $_messageFilename; if ($message[$_messageID]) return stripslashes($message[$_messageID]); if ($_messageTextEng && $lang!='rus') return $_messageTextEng; if ($_messageText) return $_messageText; return $_messageID; } */ $secpass="dgkjhs45"; /* function dots($num) { $separator="."; if($num=='') return $num; if(strstr($num,".")) { $ost1=substr($num,1+strpos($num,".")); $num=substr($num,0,strpos($num,".")); } if(!is_numeric(substr($num,0,1))) {$sign=substr($num,0,1); $num=substr($num,1);} $result = "".$num; $len = strlen($result); for($i = 0; $i < $len/3 - 1; $i++) { $k = ($i*3)+3; $result = substr($result,0,$len-$k).$separator.substr($result,$len-$k,$len); } if($sign) $result=$sign.$result; if($ost1) $result=$result.",".$ost1; return $result; } */ //выбор строки из базы------------------------------------- function selectall($sql) { if(substr($sql,0,6)!="select") $sql="select * from $sql"; return select($sql); } //------------------------------------------------------- function pnname1($id) { global $lang,$site_url,$rst1,$rst2,$kit; if($rst1['Players'][$id]) { if($lang=='rus') $name=$rst1['Players'][$id]['Name_rus']; else $name=$rst1['Players'][$id]['Name_eng']; return $rst1['Players'][$id]['Number']." "."".$name.""; } elseif($rst2['Players'][$id]) { if($lang=='rus') $name=$rst2['Players'][$id]['Name_rus']; else $name=$rst2['Players'][$id]['Name_eng']; return $rst2['Players'][$id]['Number']." "."".$name.""; } elseif($id) return $id; } function pnname($id) { global $lang; $r=select("select Number, Name_$lang as Name FROM ut_players where PlayerID='$id'"); if(!$r['Number']) $r['Number']=""; if($r['Name']) return "$r[Number] ".$r['Name']; elseif($id) return $id; } function dec2roman($f) { return $f; } function roman2dec($str = '') { return $str; } function printdec2roman($n) { echo dec2roman($n); } class _ItemID { const TICKET = 1; const COMBINATION = 2; const PLAYER_BONUS = 3; const STAR_BONUS = 4; const STAR_TALISMAN = 5; const PLAYER = 12; const GENERIC_ART_ID_1 = 101; } function userGetItemsSlots($userID, $itemID) { list($level) = select("select max(Level) from tm_buildings where UserID=$userID and BuildingID=14"); $level = $level ? $level : 0; switch ($itemID) { case _ItemID::TICKET: $hz = Array(10, 15, 20, 25, 30); $result = $hz[$level]; break; case _ItemID::COMBINATION: $hz = Array(7, 9, 11, 13, 15); $result = $hz[$level]; break; case _ItemID::PLAYER_BONUS: $hz = Array(50, 100, 150, 200, 250); $result = $hz[$level]; break; } return $result; } function userGetItemsCount($userID, $itemID) { switch ($itemID) { case _ItemID::TICKET: list($tickets) = select("select count(*) from ut_arts where UserID=$userID and ArtID=2 and ActivationDate=0 and (ExpirationDate=0 or ExpirationDate>unix_timestamp())"); $count = $tickets ? $tickets : 0; break; case _ItemID::COMBINATION: list($combinations) = select("select Combinations from free_combinations where UserID=$userID"); $count = $combinations ? $combinations : 0; break; case _ItemID::PLAYER_BONUS: list($bonus) = select("select Bonus from free_bonus where UserID=$userID"); $count = $bonus ? $bonus : 0; break; case _ItemID::STAR_BONUS: list($stars) = select("select count(*) from ut_arts where UserID=$userID and ArtID=3 and ActivationDate=0 and (ExpirationDate=0 or ExpirationDate>unix_timestamp())"); $count = $stars ? $stars : 0; break; case _ItemID::STAR_TALISMAN: list($stars) = select("select count(*) from ut_arts where UserID=$userID and ArtID=6 and ActivationDate=0 and (ExpirationDate=0 or ExpirationDate>unix_timestamp())"); $count = $stars ? $stars : 0; break; case _ItemID::PLAYER: list($stars) = select("select count(*) from ut_arts where UserID=$userID and ArtID=12 and ActivationDate=0 and (ExpirationDate=0 or ExpirationDate>unix_timestamp())"); $count = $stars ? $stars : 0; break; case _ItemID::GENERIC_ART_ID_1: list($arts) = select("select count(*) from ut_arts where UserID=$userID and ArtID=1 and ActivationDate=0 and (ExpirationDate=0 or ExpirationDate>unix_timestamp())"); $count = $arts ? $arts : 0; break; } return $count; } function userAddItem($userID, $itemID, $count = 1) { $result = min($count, userGetItemsSlots($userID, $itemID) - userGetItemsCount($userID, $itemID)); $result = max(0, $result); switch ($itemID) { case _ItemID::TICKET: for ($i = 0; $i < $result; $i++) { runsql("insert into ut_arts(UserID,ArtID,Date) values ($userID,2,unix_timestamp())"); } break; case _ItemID::COMBINATION: runsql("insert into free_combinations(UserID,Combinations) values($userID,$result) on duplicate key update Combinations=Combinations+$result"); break; case _ItemID::PLAYER_BONUS: runsql("insert into free_bonus(UserID,Bonus) values($userID,$result) on duplicate key update Bonus=Bonus+$result"); break; } return $result; } function cookiesItemGetName($itemID) { //TODO: СookiesItemID //TODO: Качественный перевод (согласованный) $list = array( 1 => message('cookies_item_1', '5 приглашений', '5 invitations'), 2 => message('cookies_item_2', '10 приглашений', '10 invitations'), 3 => message('cookies_item_3', 'Бонус опыта 6х3', 'Experience bonus 6x3'), 4 => message('cookies_item_4', 'Бонус опыта 7х3', 'Experience bonus 7x3'), 5 => message('cookies_item_5', 'Бонус опыта 8х3', 'Experience bonus 8x3'), 6 => message('cookies_item_6', 'Бонус опыта 10х3', 'Experience bonus 10x3'), 7 => message('cookies_item_7', '5 бустеров', '5 boosters'), 8 => message('cookies_item_8', '10 бустеров', '10 boosters'), 9 => message('cookies_item_9', '20 бустеров', '20 boosters'), 10 => message('cookies_item_10', '50 бустеров', '50 boosters'), 11 => message('cookies_item_11', '100 бустеров', '100 boosters'), 12 => message('cookies_item_12', '3 звездных бонуса', '3 star bonuses'), 13 => message('cookies_item_13', '5 звездных бонусов', '5 star bonuses'), 14 => message('cookies_item_14', '10 звездных бонусов', '10 star bonuses'), 15 => message('cookies_item_15', '50 звездных бонусов', '50 star bonuses'), 16 => message('cookies_item_16', '10 звездных баллов', '10 star points'), 17 => message('cookies_item_17', '20 звездных баллов', '20 star points'), 18 => message('cookies_item_18', '30 звездных баллов', '30 star points'), 19 => message('cookies_item_19', '5 бесплатных самолетов', '5 free jets'), 20 => message('cookies_item_20', '10 бесплатных самолетов', '10 free jets'), 21 => message('cookies_item_21', '20 бесплатных самолетов', '20 free jets'), 22 => message('cookies_item_22', '3 звездных талисмана', '3 star talismans'), 23 => message('cookies_item_23', '5 звездных талисманов', '5 star talismans'), 24 => message('cookies_item_24', 'Звезда статус неизвестен', 'Unknown star player'), 25 => message('cookies_item_25', 'Звезда регионального уровня', 'Regional star player'), 26 => message('cookies_item_26', 'Звезда национального уровня', 'National star player'), 27 => message('cookies_item_27', 'Звезда международного уровня', 'International star player'), 28 => message('cookies_item_28', 'Легенда футбола', 'Legendary Star'), 29 => message('cookies_item_29', 'Легенда спорта', 'Super Legendary Star'), 30 => message('cookies_item_30', '5 продлений бонусов опыта', '5 renewals of experience bonuses'), 31 => message('cookies_item_31', '10 продлений бонусов опыта', '10 renewals of experience bonuses'), 32 => message('cookies_item_32', 'Сборы Кипр', 'Training camp Cyprus'), 33 => message('cookies_item_33', 'Сборы Израиль', 'Training camp Israel'), 34 => message('cookies_item_34', 'Сборы Испания', 'Training camp Spain'), 35 => message('cookies_item_35', 'Сборы ОАЭ', 'Training camp UAE') ); return $list[$itemID]; } function adventItemGetName($itemID) { //TODO: AdventItemID $list = array( 1 => message('advent_item_1', 'сборы Кипр', 'training camp Cyprus'), 2 => message('advent_item_2', 'самолет', 'personal jet'), 3 => message('advent_item_3', 'звездный талисман', 'star talisman'), 4 => message('advent_item_4', 'продление бонуса опыта', 'experience bonus extension'), 5 => message('advent_item_5', 'платный бустер', 'paid booster'), 6 => message( 'advent_item_6', 'бонус опыта х3 (1 час, годность сутки)', 'experience bonus x3 (1 hour, expiration 1 day)' ), 7 => message('advent_item_7', 'звездный балл', 'star point'), 8 => message('advent_item_8', 'сборы Израиль', 'training camp Israel'), 9 => message( 'advent_item_9', 'бонус опыта х4 (1 час, годность сутки)', 'experience bonus x4 (1 hour, expiration 1 day)' ), 10 => message('advent_item_10', 'деньги', 'money'), 11 => message('advent_item_11', 'сборы Испания', 'training camp Spain'), 12 => message('advent_item_12', 'спецумение', 'special ability'), 13 => message('advent_item_13', 'совмещение', 'combination'), 14 => message('advent_item_14', 'аренда слота на неделю', 'slot rent for week'), 15 => message('advent_item_15', 'звездный бонус', 'star bonus'), 16 => message('advent_item_16', 'аренда слота на 2 недели', 'slot rent for 2 weeks'), 17 => message( 'advent_item_17', 'бонус опыта х5 (1 час, годность сутки)', 'experience bonus x5 (1 hour, expiration 1 day)' ), 18 => message( 'advent_item_18', 'бонус опыта х6 (1 час, годность сутки)', 'experience bonus x6 (1 hour, expiration 1 day)' ), 19 => message('advent_item_19', 'приглашение', 'invitation'), 21 => message( 'advent_item_21', 'бонус опыта х8 (3 часа, годность неделя)', 'experience bonus x8 (3 hours, expiration 1 week)' ) ); return $list[$itemID]; } function null_bonus($userID,$logtype) { $level = 0; $money = 0; $operationobject = 0; runsql("insert into log_bonus(UserID,UserID2,TypeID,Date,Bonus,Level,Money,PayType,OperationObject) values('$userID','1','$logtype',unix_timestamp(),'0','$level','$money',2,'$operationobject')"); } function create_guild_rst($id) { $guild=runsql("select GuildID,Name,UserID,FounderID,ShortName,0 Money from gd_guilds where GuildID='$id'"); $guild=mysql_fetch_array($guild,1); return serialize($guild); } function write_guild_rst($id, $gld = null) { global $site_path,$secpass; if (empty($id) || !is_numeric($id)) return false; if(!$gld) $str=create_guild_rst($id); else $str=serialize($gld); $content="GLD".pack("N",0x01000000).md5($str.$secpass).$str; file_put_contents($site_path."files/gld/$id.gld",$content); file_put_contents($site_path."mirror/gld/$id.gld.bak",$content); unlink($site_path."mirror/gld/$id.gld"); rename($site_path."mirror/gld/$id.gld.bak", $site_path."mirror/gld/$id.gld"); } function lock_trn($id) { global $site_path,$PHP_SELF,$QUERY_STRING; $f=$site_path."files/trn/$id"; $f.=".locked"; @clearstatcache(); while (@file_exists($f)) { sleep(1); @clearstatcache(); $t=time(); $t2=@filectime($f); if (!($t2>0)) $t2=time(); if (($t-$t2)>10) { @unlink($f); @clearstatcache(); } } $fp=@fopen($f,"w"); @fclose($fp); @chmod($f,0666); } function unlock_trn($id) { global $site_path; $f=$site_path."files/trn/$id"; @unlink($f.".locked"); } function first_schedule_core($tournament,$numplayers,$date) { global $img_path,$stage,$id,$fights,$num,$auth; $id = $tournament; if ($date>time()) return false; $m = select("select count(UserID) from ft_tournament_members where TournamentID='$id'"); $q = select("select * from ft_tournaments where TournamentID='$id'"); // list($isBot) = select("select IsBot from ft_tournament_types where TournamentTypeID='$q[TournamentTypeID]'"); list($minLevel,$isBot) = select("select MinLevel,IsBot from ft_tournament_types where TournamentTypeID='$q[TournamentTypeID]'"); $TOURNAMENT_MODE = $isBot; $range = System::range('this day'); if (select("select * from gd_champ_seasons s join gd_champ_schedule sch on s.SeasonID=sch.SeasonID where s.StatusID=1 and sch.Date>=$range[0] and sch.Date<=$range[1] limit 1")) { $TOURNAMENT_MODE = 3; } if (select("select * from gd_cup_seasons s join gd_cup_schedule sch on s.SeasonID=sch.SeasonID where s.StatusID=1 and sch.Date>=$range[0] and sch.Date<=$range[1] limit 1")) { $TOURNAMENT_MODE = 3; } if (select("select * from ec_seasons where StatusID=2")) { $TOURNAMENT_MODE = 3; } if (in_array($q['TypeID'], array(TournamentTypeID::INTERNAL))) { $TOURNAMENT_MODE = 3; } if (in_array($q['TypeID'], array(TournamentTypeID::COMMERCIAL))) { $TOURNAMENT_MODE = 1; } switch ($TOURNAMENT_MODE) { case 0: if ($m[0]<$numplayers) return false; break; case 1: if ($m[0]<($numplayers / 2)) return false; break; case 2: if ($m[0]<($numplayers / 2)) { runsql("update ft_tournaments set StatusID=3,Date=unix_timestamp(),NumMembers=$m[0] where TournamentID='$id'"); runsql("delete from ft_tournament_members where TournamentID='$id'"); return; } break; case 3: if ($m[0]<1) return false; break; case 4: if ($m[0]<1) { runsql("update ft_tournaments set StatusID=3,Date=unix_timestamp(),NumMembers=$m[0] where TournamentID='$id'"); runsql("delete from ft_tournament_members where TournamentID='$id'"); return; } break; case 5: break; case 6: if ($m[0]<2) return false; break; } lock_trn($id); $q = select("select * from ft_tournaments where TournamentID='$id'"); if ($q['Date']>time()) { unlock_trn($id); return; } if ($q['StatusID']!=0) { unlock_trn($id); return; } if (!$q) { unlock_trn($id); return; } runsql("update ft_tournaments set StatusID=1,Date=unix_timestamp(),NumMembers=$m[0] where TournamentID='$id'"); unlock_trn($id); $r=select("select * from ft_stages where TournamentTypeID='$q[TournamentTypeID]' and Tour1=1 limit 0,1"); if (in_array($q['TypeID'], [26, 53])) { $res2 = runsql("select distinct(t.UserID) as UserID,t.Rang as Rang from ft_tournament_members as t join ut_users as u ON u.UserID=t.UserID where TournamentID='$id' order by t.Rang desc,rand($id) desc"); } else { $res2 = runsql("select distinct(t.UserID) as UserID,t.Rang as Rang from ft_tournament_members as t join ut_users as u ON u.UserID=t.UserID where TournamentID='$id' order by t.Rang desc,(u.Level+rand($id)) desc"); } //$res2=runsql("select distinct(t.UserID) as UserID,t.Rang as Rang from ft_tournament_members as t JOIN ut_users as u ON u.UserID=t.UserID where TournamentID='$id' order by t.Rang desc,(u.Level+rand($id)) desc"); //order by Exp desc $str=""; $marketingHits=Array(); for($k=1;$k<=$numplayers;$k++) { $r2=mysql_fetch_array($res2); $tmpusers[$k]=$r2['UserID']; $str.=" and UserID<>'$r2[UserID]'"; if($r2['Rang']==5) { // Билетики $used_art=select("select count(*) from ut_arts where UserID='$r2[UserID]' and OperationObject='$id'"); if($used_art[0]<1) runsql("update ut_arts set ActivationDate=unix_timestamp(),OperationObject='$id' where UserID='$r2[UserID]' and ActivationDate=0 and ArtID=2 limit 1"); } $marketingHits[]=$r2['UserID']; } for($k=$m[0]+1;$k<=$numplayers;$k++) $tmpusers[$k] = 2; $marketingMisses=Array(); while($r2=mysql_fetch_array($res2)) $marketingMisses[]=$r2['UserID']; $art=runsql("select * from ft_tournament_members m where TournamentID='$id' $str and userid not in (select UserID from ut_arts where ArtID=2);"); while($a=mysql_fetch_array($art)) { lock_rst($a['UserID']); $rst=read_rst($a['UserID']); if($rst['Level']<=2) { $rst['Messages'].="23,"; write_rst($a['UserID'],$rst); } unlock_rst($a['UserID']); if($rst['Level']<=2) { for($i=1;$i<=3;$i++) { runsql("insert into ut_arts (UserID,ArtID,Date) values ('$a[UserID]',2,unix_timestamp())"); } } } runsql("delete from ft_tournament_members where TournamentID='$id' $str"); for($k=1;$k<=$numplayers;$k=$k+2) { $users[$k]=$tmpusers[$k]; $users[$k+1]=$tmpusers[1+$numplayers-$k]; } if(count($users)!=$numplayers) { runsql("update ft_tournaments set StatusID=0 where TournamentID='$id'"); return 0; } /* if($q[Fee]&&!($q[TypeID]==5||$q[TypeID]==4) && $q[TypeID]==17) { foreach($users as $u) { transfer_money($q[Fee],$u,1,37,$id); } } if($q[Fee]&&$q[GuildID]&&($q[TypeID]==5||$q[TypeID]==4)) { foreach($users as $u) { transfer_user2guild($q[Fee],$u,$q[GuildID],37,$id); } } */ if ($q['Fee']) { if (!($q['TypeID'] == 5 || $q['TypeID'] == 4)) { foreach ($users as $u) { if ($u == Consts::BOT_ID) { continue; } transfer_money($q['Fee'], $u, 1, 37, $id); } } else { if ($q['GuildID']) { foreach ($users as $u) { if ($u == Consts::BOT_ID) { continue; } transfer_user2guild($q['Fee'], $u, $q['GuildID'], 37, $id); } } } } if($r['TypeID']==0) { for($k=1;$k<=$numplayers;$k++) { runsql("update ft_tmp_agreements set UserID1='$users[$k]', Login1=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$users[$k]') where TournamentID='$id' and Tour=1 and Pair1='$k'"); runsql("update ft_tmp_agreements set UserID2='$users[$k]', Login2=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$users[$k]') where TournamentID='$id' and Tour=1 and Pair2='$k'"); } } else { for($k=1;$k<=$numplayers;$k++) { runsql("update ft_tmp_agreements set UserID1='$users[$k]', Login1=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$users[$k]') where TournamentID='$id' and Stage=1 and Pair1='$k'"); runsql("update ft_tmp_agreements set UserID2='$users[$k]', Login2=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$users[$k]') where TournamentID='$id' and Stage=1 and Pair2='$k'"); runsql("update ft_groups set UserID='$users[$k]',Login=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$users[$k]') where TournamentID='$id' and Stage=1 and Pair='$k'"); } } runsql("delete from ft_agreements where TournamentID='$id'"); runsql("insert ignore into ft_agreements (UserID1,UserID2,TypeID,LimitSkl,Timeout,TournamentID,Stage,Tour,Fight,Pair,Pair1,Pair2,Place1,Place2,NumFights,StageTypeID,Approved,StatusID,Date,Login1,Login2) (select UserID1,UserID2,TypeID,LimitSkl,Timeout,TournamentID ,Stage,Tour,Fight,Pair,Pair1,Pair2,Place1,Place2,NumFights,StageTypeID, 1,2,unix_timestamp(),Login1,Login2 from ft_tmp_agreements where TournamentID='$id' and Tour=1 and Fight=1)"); foreach ($marketingHits as $userID) { $userMarketingStats=getMarketingStats($userID); $userMarketingStats['sessionTourmentHits']++; setMarketingStats($userID,$userMarketingStats); } foreach ($marketingMisses as $userID) { $userMarketingStats=getMarketingStats($userID); $userMarketingStats['sessionTourmentMisses']++; setMarketingStats($userID,$userMarketingStats); } tournamentProcessBotResults($q); } function gameProcessBotResults($tournament,$recordID) { global $affectedrows; $q = select("select RecordID from ft_agreements where RecordID='$recordID'"); if (!$q) return; $winner = 2; $score1 = 1; $score2 = 0; runsql("insert ignore into ft_matches(AB1,AB2,Visitors,RecordID,UserID1,UserID2,Date,TypeID, TournamentID,Stage,Tour,Fight,Pair,Pair1,Pair2,Place1,Place2,StageTypeID,WinnerID,Score1,Score2,Login1,Login2) (select '$ab1','$ab2','$res[Visitors]',RecordID,UserID1,UserID2,unix_timestamp(),TypeID, TournamentID,Stage,Tour,Fight,Pair,Pair1,Pair2,Place1,Place2,StageTypeID,'$winner','$score1','$score2',Login1,Login2 from ft_agreements where RecordID='$recordID')"); if (!$affectedrows){ return; } runsql("delete from ft_agreements where RecordID='$recordID'"); if ($tournament['TournamentID'] && $tournament['ModeID']!=19) next_schedule($recordID); if ($tournament['TournamentID'] && $tournament['ModeID']==19) gd_next_schedule($recordID); } function executor_cmd($command) { global $cfg; $fp = fsockopen($cfg['EXEC']['host'], $cfg['EXEC']['port'], $errno, $errstr, 30); fwrite($fp, "do:$command\r\n"); stream_set_timeout($fp, 5); $answer=fread($fp,2); if ($answer!='ok') log_rst("[error] Executor cant do $command"); fclose($fp); } function first_schedule($tournament,$numplayers,$date) { global $site_admin_path; executor_cmd("php $site_admin_path"."first_schedule.php $tournament $numplayers $date"); } function read_guild_rst($id) { global $site_path,$secpass,$PHP_SELF,$QUERY_STRING,$auth; if (empty($id) || !is_numeric($id)) return false; $guild_rstname=$site_path."files/gld/$id.gld"; $guild_mirror_rstname=$site_path."mirror/gld/$id.gld"; if (empty($id)) return false; $recovery=false; $result=read_guild_rst_core($id,$guild_rstname); if (!$result) { log_rst("[warn] Guild mirror recovery ( $auth->user : $id)"); $result=read_guild_rst_core($id,$guild_mirror_rstname); $recovery=true; } if (!$result) { log_rst("[warn] Guild mirror backup recovery ($auth->user : $id)"); $result=read_guild_rst_core($id,$guild_mirror_rstname.'.bak'); $recovery=true; } if ($recovery) { if (!$result) { log_rst("[error] Guild roster empty or damaged cant recover ($auth->user : $id)"); // $result['UserID'] = -1; // $result['Name'] = '---'; // $result['GuildID'] = $id; } else { log_rst(" [debug] Guild roster successful recovered ($auth->user : $id)"); write_guild_rst($id,$result); } } return $result; } function read_guild_rst_core($id,$filename) { global $site_path,$secpass; define('GLD_READ_TIMEOUT',100000); if(!file_exists($filename)) return ''; $str=file_get_contents($filename); $md5=substr($str,7,32); $str=substr($str,39); for($i=0;$i<10;$i++) { if((!$str) || ($md5!=md5($str.$secpass)) ) { // log_rst("[error] Guild Incorrect md5 ($id)"); usleep(GLD_READ_TIMEOUT); $str=file_get_contents($filename); $md5=substr($str,7,32); $str=substr($str,39); } } if($md5!=md5($str.$secpass)) { log_rst("[error] Guild Incorrect md5 ($id)"); return false; } $ar=unserialize($str); if (!empty($ar['GuildID']) && ($ar['GuildID']!=$id)) { log_rst("[error] Guild Incorrect GuildID ($id)"); return false; } if(!$ar['UserID']&&!$ar['Name']) return false; return $ar; } function transfer_user2guild($money,$sender,$receiver,$type,$info) { global $REMOTE_ADDR,$PHP_SELF,$QUERY_STRING,$auth; if($sender!=1) lock_rst($sender); if($money>0&&$sender>0&&$receiver>0) { lock_gld($receiver); if($sender==1) $senderbalance=''; else { $sender_rst=read_rst($sender); $senderbalance=$sender_rst['Money']-$money; $userMarketingStats=getMarketingStats($sender); $userMarketingStats['sessionMoneyOutcome']+=$money; $sender_rst['Money']=round($senderbalance); } if($receiver==1) $receiverbalance=''; else { $receiver_rst=read_guild_rst($receiver); $receiverbalance=$receiver_rst['Money']+$money; $receiver_rst['Money']=round($receiverbalance); } runsql("insert into fn_operations(ModeID,Money,SenderID,ReceiverID,SenderBalance,ReceiverBalance,TypeID,OperationDate,OperationObject) values(1,'$money','$sender','$receiver','$senderbalance','$receiverbalance','$type' ,unix_timestamp(),'$info')"); if($sender!=1) { if ($auth->user == $sender_rst['UserID']) { $auth->money = $sender_rst['Money']; $auth->rst['Money'] = $sender_rst['Money']; } write_rst($sender,$sender_rst); setMarketingStats($sender,$userMarketingStats); } if($receiver!=1) write_guild_rst($receiver,$receiver_rst); unlock_gld($receiver); } if($sender!=1) unlock_rst($sender); } function transfer_guild2user($money,$sender,$receiver,$type,$info) { global $REMOTE_ADDR,$PHP_SELF,$QUERY_STRING,$auth; if($receiver!=1) lock_rst($receiver); if($money>0&&$sender>0&&$receiver>0) { lock_gld($sender); if($sender==1) $senderbalance=''; else { $sender_rst=read_guild_rst($sender); $senderbalance=$sender_rst['Money']-$money; $sender_rst['Money']=round($senderbalance); } if($receiver==1) $receiverbalance=''; else { $receiver_rst=read_rst($receiver); $receiverbalance=$receiver_rst['Money']+$money; $userMarketingStats=getMarketingStats($receiver); $userMarketingStats['sessionMoneyIncome']+=$money; $receiver_rst['Money']=round($receiverbalance); } runsql("insert into fn_operations(ModeID,Money,SenderID,ReceiverID,SenderBalance,ReceiverBalance,TypeID,OperationDate,OperationObject) values(2,'$money','$sender','$receiver','$senderbalance','$receiverbalance','$type' ,unix_timestamp(),'$info')"); if($sender!=1) write_guild_rst($sender,$sender_rst); if($receiver!=1) { if ($auth->user == $receiver_rst['UserID']) { $auth->money = $receiver_rst['Money']; $auth->rst['Money'] = $receiver_rst['Money']; } write_rst($receiver,$receiver_rst); setMarketingStats($receiver,$userMarketingStats); } unlock_gld($sender); } if($receiver!=1) unlock_rst($receiver); } function short_transfer_guild2user($rst,$money,$sender,$receiver,$type,$info) { global $auth; if(!is_array($rst)) return 0; $guild=$rst['GuildID']; $user=$rst['UserID']; if($money>0) { $userMarketingStats=getMarketingStats($user); if($sender==1) { $balance=$rst['Money']+$money; $userMarketingStats['sessionMoneyIncome']+=$money; } else { $balance=$rst['Money']-$money; $userMarketingStats['sessionMoneyOutcome']+=$money; } setMarketingStats($user,$userMarketingStats); $rst['Money']=round($balance); if($sender==1) runsql("insert into fn_operations(ModeID,Money,SenderID,ReceiverID,SenderBalance,ReceiverBalance,TypeID,OperationDate,OperationObject) values(2,'$money','1','$guild','','$balance','$type' ,unix_timestamp(),'$info')"); else runsql("insert into fn_operations(ModeID,Money,SenderID,ReceiverID,SenderBalance,ReceiverBalance,TypeID,OperationDate,OperationObject) values(2,'$money','$guild','1','$balance','','$type' ,unix_timestamp(),'$info')"); } if ($auth->user == $rst['UserID']) { $auth->money = $rst['Money']; $auth->rst['Money'] = $rst['Money']; } return $rst; } function generateFullname($Zone,$countryID=false) { $tableSuffix = ($Zone=='rus') ? '' : '_global' ; $fields = ($Zone=='rus') ? ' * ' : ' Name Name_rus, Name Name_eng ' ; if ($countryID) { $qq = select("select rand()*max(WeightScaled) from ut_players_name$tableSuffix where countryid=$countryID"); $q1 = select("select $fields from ut_players_name$tableSuffix where WeightScaled>'$qq[0]' and countryid=$countryID order by WeightScaled asc limit 1"); if (!$q1[0]) $q1 = select("select $fields, Mono from ut_players_name$tableSuffix where countryid=$countryID order by rand() limit 1"); if (!$q1['Mono']) $q2 = select("select $fields from ut_players_surname$tableSuffix where countryid=$countryID order by rand() limit 1"); } if (!$q1[0]) { list($n) = select("select count(*) from ut_players_surname$tableSuffix;"); $gn = rand(0,$n-1); $q2 = select("select $fields,countryid from ut_players_surname$tableSuffix limit $gn,1;"); $countryID = $q2['countryid']; $q1 = select("select $fields,Mono from ut_players_name$tableSuffix where countryid=$countryID order by rand() limit 1"); if ($q1['Mono']) $q2 = null; } $result['name_rus'] = addslashes($q1['Name_rus']." ".$q2['Name_rus']); $result['name_eng'] = addslashes($q1['Name_eng']." ".$q2['Name_eng']); $result['countryid'] = $countryID; return $result; } function create_players($user) { $rr = select("select TeamCountryID from ut_users where UserID=$user"); $countryid=$rr[0]; runsql("delete from ut_players where UserID='$user'"); runsql("insert into ut_players (UserID, Position, CountryID, Age, Talent, Number,Stamina, Morale) (select '$user',(select PositionID from ut_positions where Type=1 order by rand() limit 0,1) Position, '$countryid' as CountryID, @age:=round(18+20*rand()) as Age, @talent:=if((select @a:=(1000*rand()))>0, if(@a<90,1,if(@a<280,2,if(@a<550,3,if(@a<740,4,if(@a<850,5,if(@a<950,6,if(@a<995,7,if(@a<999,7,7)))))))), if(@a<90,1,if(@a<280,2,if(@a<550,3,if(@a<740,4,if(@a<850,5,if(@a<950,6,if(@a<995,7,if(@a<999,7,7)))))))) ) as Talent, round(1+20*rand()) Number,100 Stamina, 0 Morale from en_numbers where Number<=18)"); $i=0; $res=runsql("select * from ut_positions where Type=1"); while($r=mysql_fetch_array($res)) $pos[$i++]=$r['PositionID']; $pos[$i++]='Cm'; $pos[$i++]='Cd'; $pos[$i++]='Cf'; $pos[$i++]='Gk'; $j=0; $res=runsql("select CountryID,PlayerID,Age from ut_players where UserID='$user'"); while($r=mysql_fetch_array($res)) { $countryid = $r['CountryID']; $name = ($j<13) ? generateFullname($_GET['ZoneID'],$countryid) : generateFullname($_GET['ZoneID']) ; $name_rus = mysql_real_escape_string($name['name_rus']); $name_eng = mysql_real_escape_string($name['name_eng']); $countryid = $name['countryid']; unset($a); $level=rand(52,62+($r['Age'] - 18)*3); for($i=1;$i<=$level;$i++) { $a[rand(0,7)]+=1; } runsql("update ut_players p set CountryID='$countryid',Name_rus='$name_rus',Name_eng='$name_eng', Level='$level',Tck=1+'$a[0]',Mrk=1+'$a[1]',Drb=1+'$a[2]',Rcv=1+'$a[3]', Edu=1+'$a[4]',Pas=1+'$a[5]',Shp=1+'$a[6]',Sha=1+'$a[7]' where PlayerID='$r[PlayerID]'"); runsql("update ut_players p set Skl=Tck+Mrk+Drb+Rcv+Edu+Pas+Shp+Sha, Price=round(3*(power(1.18,(Tck+Mrk+Drb+Rcv+Edu+Pas+Shp+Sha-8)/5)*(12/(10-Talent)-1)*1.5*EXP((Age-23)*(Age-23)/-200)*100)) where PlayerID='$r[PlayerID]'"); if($j<14) runsql("update ut_players p set Position='$pos[$j]' where PlayerID='$r[PlayerID]'"); $j++; } $n=1; $res=runsql("select CountryID,PlayerID from ut_players where UserID='$user' order by Position"); while($r=mysql_fetch_array($res)) { runsql("update ut_players p set Number='$n' where PlayerID='$r[PlayerID]'"); $n++; } lock_rst($user); $rst=read_rst($user); unset($rst['Players']); $res=runsql("select PlayerID from ut_players where UserID='$user'"); while($r=mysql_fetch_array($res)) { $id=$r['PlayerID']; $player=runsql("select PlayerID,Name_rus,Name_eng, Position, CountryID, Price, Age, Talent, Number,Stamina, Morale,Level,Skl,Tck,Mrk,Drb,Rcv,Edu,Pas,Shp,Sha from ut_players where PlayerID='$id'"); if(mysql_error()) {print mysql_error(); unlock_rst($user); exit;} $player=mysql_fetch_array($player,1); if(!$player['PlayerID']) {unlock_rst($user);exit;} unset($player['PlayerID']); $player['Date'] = time(); $rst['Players'][$id]=$player; } write_rst($user,$rst); unlock_rst($user); } function champgampath($id) { global $site_path; return $site_path."files/champgam/".path($id); } function generatechampgame($id,$next) { global $gladexplevels,$site_path,$secpass,$k,$serialized, $cfg; $path=champgampath($id); System::forceDirectory($path); $fname=$path."/".$id.".gam"; $q=runsql("select RecordID,a.Date,a.UserID1,a.UserID2, a.TournamentID,coalesce(m.Coefficient,1) TournamentFactor,tt.TypeID ModeID ,a.Tour, if(tt.TypeID=11,0,if(a.TournamentID >0 and a.StageTypeID=0 and a.NumFights=2 and (a.Tour-s.Tour1)%2=1,2,if(a.TournamentID >0 and a.StageTypeID=0,1,0))) TypeID, s.Number from champ_matches a left outer join champ_tournaments t using(TournamentID) left outer join ft_tournament_types tt on t.TournamentTypeID=tt.TournamentTypeID left outer join ft_tournament_modes m on tt.TypeID=m.TypeID left outer join ft_stages s on s.TournamentTypeID=tt.TournamentTypeID and (a.Tour>=s.Tour1 and a.Tour<=s.Tour2) where a.RecordID='$id' and Finished=0;"); $q=mysql_fetch_array($q,1); $gam=$q; $t1=select("select coalesce(Win/Lose,1) from stat_win where UserID='$gam[UserID1]';"); $t2=select("select coalesce(Win/Lose,1) from stat_win where UserID='$gam[UserID2]';"); $k=select("select sum(i.Slots) from tm_buildings b join fn_buildings_info i on b.BuildingID=i.BuildingID and b.Level=i.Level where b.UserID='$gam[UserID1]'"); if(!$t1[0]) $t1[0]=1; if(!$t2[0]) $t2[0]=1; if(!$gam['Number']) $gam['Number']=1; $k=0.4+0.01*$k[0]; $v1=select("select Visitors from ft_visitors where UserID='$gam[UserID1]'"); $v2=select("select Visitors from ft_visitors where UserID='$gam[UserID2]'"); if(!$v1[0]) $v1[0]=100; if(!$v2[0]) $v2[0]=100; $gam['Visitors']=round($k*$gam['Number']*($t1[0]*$v1[0]+$t2[0]*$v2[0]*0.3)); $rst=read_rst($gam['UserID1']); $capacity=$rst['Capacity']; if($capacity<$gam['Visitors']) $gam['Visitors']=$capacity; $gam['Visitors'] = (int)$gam['Visitors']; if(!$q['UserID1'] || !$q['UserID2']) return false; unset($gam['ModeID']); unset($gam['Number']); $kit = Array(); list($kit['ID1'],$kit['Color1'],$kit['Color2']) = userGetKitOld($q['UserID1']); $gam['Kit1'] = $kit; $kit = Array(); list($kit['ID1'],$kit['Color1'],$kit['Color2']) = userGetKitOld($q['UserID2']); $gam['Kit2'] = $kit; $expfactor=array(1,1.25,1.5,2,3); $q1=select("select coalesce(Rang,0),BanTime from ut_users where UserID='$q[UserID1]'"); $gam['Rang1']=$q1[0]; //$gam['Technical'][0] = !$q1 || ($q1['BanTime'] > time()); $gam['ExpFactor1']=$expfactor[$q1[0]]; $q1=select("select coalesce(Rang,0),BanTime from ut_users where UserID='$q[UserID2]'"); $gam['Rang2']=$q1[0]; //$gam['Technical'][1] = !$q1 || ($q1['BanTime'] > time()); $gam['ExpFactor2']=$expfactor[$q1[0]]; $gam['Degradation'][0] = 1; $gam['Degradation'][1] = 1; for ($i = 0; $i < 2; $i ++) { $index = $i + 1; $userID = $q["UserID$index"]; $q1 = select("select coalesce(Rang,0),BanTime from ut_users where UserID=$userID"); $technical = false; $technical = ( ! $q1 || ( $q1['BanTime'] > time() ) ) ? true : $technical; //$technical = ( ! file_exists($site_path . "files/champord/$id-$userID.ord") ) ? true : $technical; $technical = ($q['ModeID'] != TournamentTypeID::MELTING_POT && !file_exists($site_path . "files/champord/$id-$userID.ord")) ? true : $technical; $technical = ( $userID == Consts::BOT_ID ) ? false : $technical; $hurma = $technical ? 'yes' : 'no' ; // Log::debug("GENERATE $id,mode=$q[ModeID],tech=$hurma"); $gam['Technical'][$i] = $technical; } $gam['id']=$id; $gam['Champ']=1; // I need it for rating system $typeid=$q['TypeID']; userFlush($q['UserID1']); userFlush($q['UserID2']); if($q['RecordID']) { $str=get_rst_file($q['UserID1']).get_champord_file($id,$q['UserID1']).get_rst_file($q['UserID2']).get_champord_file($id,$q['UserID2']); $gam['Date']=time(); @clearstatcache(); if(file_exists($fname)) return false; //$res2=runsql("select d.* from champ_disqualify d join ut_players p on p.PlayerID=d.PlayerID and (UserID='$q[UserID1]' or UserID='$q[UserID2]') where TournamentID='$q[TournamentID]'"); $res2 = runsql("select d.* from champ_disqualify d join ut_players p on p.PlayerID=d.PlayerID and (UserID='$q[UserID1]' or UserID='$q[UserID2]') and UserID<>".Consts::BOT_ID." where TournamentID='$q[TournamentID]'"); while($r2=mysql_fetch_array($res2)) { $d=1+$r2['Length']+$r2['Tour']-$q['Tour']; if ($d>0) $gam['Disqualify'][$r2['PlayerID']]=$d; } @clearstatcache(); if(file_exists($fname)) return false; $str = serialize($gam).$str; file_put_contents($fname,"GAM".pack("N",0x01000000).md5($str.$secpass).$str); $fp = fsockopen($cfg['GEN']['host'], $cfg['GEN']['port'], $errno, $errstr, 30); fwrite($fp, $cfg['GEN']['string']."$fname:$id\r\n"); stream_set_timeout($fp, 5); $answer=fread($fp,2); if ($answer!='ok') { touch($site_path."files/demon/champ/".$id); } fclose($fp); } return true; } function next_champ_schedule($id) { global $site_path,$img_path; //выбираем описание текущего боя------------------ $q=select("select * from champ_matches where RecordID='$id' and Finished=1"); $tournament=select("select GuildID,TypeID,Name,Number,TournamentTypeID from champ_tournaments where TournamentID='$q[TournamentID]'"); $tournament['Name']=addslashes($tournament['Name']."-".dec2roman($tournament['Number'])); //if($q[NumFights]==2 && $q[StageTypeID]==1) //есть ли победитель в этой паре--------------- if($q['WinnerID']==$q['UserID1']) {$winner=$q['UserID1'];$loser=$q['UserID2'];} elseif($q['WinnerID']==$q['UserID2']) {$winner=$q['UserID2'];$loser=$q['UserID1'];} else $tie=1; if($winner || $tie) { $p=3*$q['Stage']; $p2=2*$q['Stage']; $p3=$q['Stage']; if($winner) { runsql("insert into ft_visitors(UserID,Visitors) values($winner,100+$p) on duplicate key update Visitors=Visitors+$p"); runsql("insert into ft_visitors(UserID,Visitors) values($loser,100-$p2) on duplicate key update Visitors=Visitors-$p2"); } else { runsql("insert into ft_visitors(UserID,Visitors) values($q[UserID1],100+$p3) on duplicate key update Visitors=Visitors+$p3"); runsql("insert into ft_visitors(UserID,Visitors) values($q[UserID2],100+$p3) on duplicate key update Visitors=Visitors+$p3"); } //print "Победитель определен
"; if($q['StageTypeID']==0) { //в плейофф------------------- //runsql("update ft_tournament_members set StatusID=1 where TournamentID='$q[TournamentID]' and UserID='$loser'"); $p=select("select Prize,StageID from ft_stages where TournamentTypeID='$tournament[TournamentTypeID]' and Number='$q[Stage]'-1"); $points = round($p['Prize']*getPointsFactor($tournament['TypeID'])); //$points=round($p[Prize]*4/100); //if($p[0]&&$tournament[TypeID]==1) userSetTournamentPoints($loser, $q, $p, $points, 0); //if($loser) //{ // runsql("insert into ft_glory(UserID,Points,Date,TournamentID,GuildID) values('$loser',$points,unix_timestamp(),$q[TournamentID],coalesce((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$loser'),0))"); // runsql("insert into ft_points(UserID,Points) values('$loser','$points') on duplicate key update Points=Points+'$points'"); //} if($p[0]&&$tournament['GuildID']) transfer_guild2user($p[0],$tournament['GuildID'],$loser,27,$q['TournamentID']); elseif($p[0]) transfer_money($p[0],1,$loser,27,$q['TournamentID']); //следующая стадия--------------- $u=select("select * from champ_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and (Pair1='$q[Pair]' or Pair2='$q[Pair]')"); //проверка на окончание турнира--------------- if(!$u[0]) { runsql("insert ignore into champ_winners(UserGuildID, GuildID,TournamentID,UserID,Date,Login,Tournament,Place,TypeID,TournamentTypeID) values((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$winner'),'$tournament[GuildID]','$q[TournamentID]','$winner',unix_timestamp(),(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$winner'),'$tournament[Name]',1,'$tournament[TypeID]','$tournament[TournamentTypeID]')"); runsql("insert ignore into champ_winners(UserGuildID, GuildID,TournamentID,UserID,Date,Login,Tournament,Place,TypeID,TournamentTypeID) values((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$loser'),'$tournament[GuildID]','$q[TournamentID]','$loser',unix_timestamp(),(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$loser'),'$tournament[Name]',2,'$tournament[TypeID]','$tournament[TournamentTypeID]')"); runsql("update champ_tournaments set StatusID=2 where TournamentID='$q[TournamentID]';"); $p=select("select Prize,StageID from ft_stages where TournamentTypeID='$tournament[TournamentTypeID]' and Number='$q[Stage]'"); $points = round($p['Prize']*getPointsFactor($tournament['TypeID'])); //$points=round($p[Prize]*4/100); //if($p[0]&&$tournament[TypeID]==1) userSetTournamentPoints($winner, $q, $p, $points, 0); //if($points) runsql("insert into ft_glory(UserID,Points,Date,TournamentID,GuildID) values('$winner','$points',unix_timestamp(),$q[TournamentID],coalesce((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$winner'),0))"); //if($points) runsql("insert into ft_points(UserID,Points) values('$winner','$points') on duplicate key update Points=Points+'$points'"); if($p[0]&&$tournament['GuildID']) transfer_guild2user($p[0],$tournament['GuildID'],$winner,27,$q['TournamentID']); elseif($p[0]) transfer_money($p[0],1,$winner,27,$q['TournamentID']); } else { if($u['StageTypeID']==0) { //обновляем следующий этап------------------------ runsql("update champ_tmp_agreements set UserID1='$winner', Login1=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$winner') where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Pair1='$q[Pair]'"); runsql("update champ_tmp_agreements set UserID2='$winner', Login2=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$winner') where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Pair2='$q[Pair]'"); //подстраховка $u=select("select * from champ_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and (Pair1='$q[Pair]' or Pair2='$q[Pair]')"); } //если оба соперника - добавляем бой ------------------------------- if($u['StageTypeID']==0&&($u['UserID1']>0||$u['Pair1']==$q['Pair'])&&($u['UserID2']>0||$u['Pair2']==$q['Pair'])) { runsql("insert ignore into champ_matches (UserID1,UserID2,TournamentID,Tour,GroupID,Stage,Fight,Pair,Pair1,Pair2,NumFights,StageTypeID) (select UserID1,UserID2,TournamentID,Tour,Pair,Stage,Fight,Pair,Pair1,Pair2,NumFights,StageTypeID from champ_tmp_agreements where RecordID='$u[RecordID]' and StatusID=0)"); runsql("update champ_tmp_agreements set StatusID=1 where RecordID='$u[RecordID]' and StatusID=0"); } elseif($u['StageTypeID']==1) { //обновляем следующий этап------------------------ runsql("update champ_tmp_agreements set UserID1='$winner', Login1=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$winner') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair1='$q[Pair]'"); runsql("update champ_tmp_agreements set UserID2='$winner', Login2=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$winner') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair2='$q[Pair]'"); //обновляем группу, куда выходит победитель-------------------- runsql("update champ_tournament_groups set UserID='$winner',Login=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$winner') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair='$q[Pair]'"); runsql("insert ignore into champ_matches (UserID1,UserID2,TournamentID,Tour,GroupID,Stage,Fight,Pair,Pair1,Pair2,NumFights,StageTypeID) (select UserID1,UserID2,TournamentID,Tour,Pair,Stage,Fight,Pair,Pair1,Pair2,NumFights,StageTypeID from champ_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and ((UserID1='$winner' and UserID2>0) or (UserID2='$winner' and UserID1>0)) and StatusID=0)"); runsql("update champ_tmp_agreements set StatusID=1 where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and ((UserID1='$winner' and UserID2>0) or (UserID2='$winner' and UserID1>0)) and StatusID=0"); } } } elseif($q['StageTypeID']==1) { //в группе------------------- $finished=1; $i=1; $p1=0; $p2=0; $w1=0; $w2=0; $t1=0; $t2=0; $l1=0; $l2=0; if($winner==$q['UserID1']) {$p1=3;$w1=1;$l2=1;} elseif($winner==$q['UserID2']) {$p2=3;$w2=1;$l1=1;} if($tie) {$p1=1;$p2=1;$t1=1;$t2=1;} runsql("update champ_tournament_groups set Games=Games+1,Tour='$q[Tour]',Points=Points+'$p1',Win=Win+'$w1',Tie=Tie+'$t1',Lose=Lose+'$l1',Score1=Score1+'".$q['Score1']."',Score2=Score2+'".$q['Score2']."' where TournamentID='$q[TournamentID]' and Stage='$q[Stage]' and UserID='$q[UserID1]' and (Tour='0' or '$q[Tour]'>Tour)"); runsql("update champ_tournament_groups set Games=Games+1,Tour='$q[Tour]',Points=Points+'$p2',Win=Win+'$w2',Tie=Tie+'$t2',Lose=Lose+'$l2',Score1=Score1+'".$q['Score2']."',Score2=Score2+'".$q['Score1']."' where TournamentID='$q[TournamentID]' and Stage='$q[Stage]' and UserID='$q[UserID2]' and (Tour='0' or '$q[Tour]'>Tour)"); $res=runsql("select * from champ_tournament_groups where TournamentID='$q[TournamentID]' and Stage='$q[Stage]' and Name='$q[Pair]' order by Points desc, Win desc, Score1-Score2 desc, Score1 desc, rand($q[TournamentID]*$q[Stage]*$q[Pair])"); while($r=mysql_fetch_array($res)) { if($r['Games']!=3) $finished=0; $place[$i]=$r['UserID']; $i++; } //если группа завершена----------------- if($finished) { //print "Группа завершена
"; //следующая стадия //runsql("update ft_tournament_members set StatusID=1 where TournamentID='$q[TournamentID]' and UserID='$place[3]'"); //runsql("update ft_tournament_members set StatusID=1 where TournamentID='$q[TournamentID]' and UserID='$place[4]'"); $p=select("select Prize,StageID from ft_stages where TournamentTypeID='$tournament[TournamentTypeID]' and Number='$q[Stage]'-1"); $points = round($p['Prize']*getPointsFactor($tournament['TypeID'])); //$points=round($p[Prize]*4/100); userSetTournamentPoints($place[3], $q, $p, $points, 0); userSetTournamentPoints($place[4], $q, $p, $points, 0); //if($points) runsql("insert into ft_glory(UserID,Points,Date,TournamentID,GuildID) values('$place[3]','$points',unix_timestamp(),$q[TournamentID],coalesce((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$place[3]'),0))"); //if($points) runsql("insert into ft_glory(UserID,Points,Date,TournamentID,GuildID) values('$place[4]','$points',unix_timestamp(),$q[TournamentID],coalesce((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$place[4]'),0))"); //if($p[0]&&$tournament[TypeID]==1) //runsql("insert into ft_points(UserID,Points) values('$place[3]','$points') on duplicate key update Points=Points+'$points'"); //if($p[0]&&$tournament[TypeID]==1) //runsql("insert into ft_points(UserID,Points) values('$place[4]','$points') on duplicate key update Points=Points+'$points'"); if($p[0]&&$tournament['GuildID']) transfer_guild2user($p[0],$tournament['GuildID'],$place[3],27,$q['TournamentID']); elseif($p[0]) transfer_money($p[0],1,$place[3],27,$q['TournamentID']); if($p[0]&&$tournament['GuildID']) transfer_guild2user($p[0],$tournament['GuildID'],$place[4],27,$q['TournamentID']); elseif($p[0]) transfer_money($p[0],1,$place[4],27,$q['TournamentID']); $u=select("select * from champ_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and (Pair1='$q[Pair]' or Pair2='$q[Pair]')"); if(!$u[0]) { userSetTournamentPoints($place[2], $q, $p, $points, 0); //runsql("insert into ft_points(UserID,Points) values('$place[2]','$points') on duplicate key update Points=Points+'$points'"); if($p[0]&&$tournament['GuildID']) transfer_guild2user($p[0],$tournament['GuildID'],$place[2],27,$q['TournamentID']); elseif($p[0]) transfer_money($p[0],1,$place[2],27,$q['TournamentID']); runsql("insert ignore into champ_winners(UserGuildID, GuildID,TournamentID,UserID,Date,Login,Tournament,Place,TypeID,TournamentTypeID) values((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$place[1]'),'$tournament[GuildID]','$q[TournamentID]','$place[1]',unix_timestamp(),(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[1]'),'$tournament[Name]',1,'$tournament[TypeID]','$tournament[TournamentTypeID]')"); runsql("insert ignore into champ_winners(UserGuildID, GuildID,TournamentID,UserID,Date,Login,Tournament,Place,TypeID,TournamentTypeID) values((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$place[2]'),'$tournament[GuildID]','$q[TournamentID]','$place[2]',unix_timestamp(),(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[2]'),'$tournament[Name]',2,'$tournament[TypeID]','$tournament[TournamentTypeID]')"); $p=select("select Prize,StageID from ft_stages where TournamentTypeID='$tournament[TournamentTypeID]' and Number='$q[Stage]'"); $points = round($p['Prize']*getPointsFactor($tournament['TypeID'])); //$points=round($p[Prize]*4/100); //if($p[0]&&$tournament[TypeID]==1) userSetTournamentPoints($place[1], $q, $p, $points, 0); //if($points) runsql("insert into ft_glory(UserID,Points,Date,TournamentID,GuildID) values('$place[1]','$points',unix_timestamp(),$q[TournamentID],coalesce((select if(GuildID>0 and GuildStatusID=1,GuildID,'') from ut_users where UserID='$place[1]'),0))"); //if($points) runsql("insert into ft_points(UserID,Points) values('$place[1]','$points') on duplicate key update Points=Points+'$points'"); if($p[0]&&$tournament['GuildID']) transfer_guild2user($p[0],$tournament['GuildID'],$place[1],27,$q['TournamentID']); elseif($p[0]) transfer_money($p[0],1,$place[1],27,$q['TournamentID']); runsql("update champ_tournaments set StatusID=2 where TournamentID='$q[TournamentID]';"); } else { if($u['StageTypeID']==0) { runsql("update champ_tmp_agreements set UserID1='$place[1]', Login1=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[1]') where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and ((Pair1='$q[Pair]' and Place1='1') or (Pair2='$q[Pair]' and Place2='1'))"); runsql("update champ_tmp_agreements set UserID2='$place[2]', Login2=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[2]') where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and ((Pair2='$q[Pair]' and Place2='2') or (Pair1='$q[Pair]' and Place1='2'))"); //бой за 3 место //runsql("update champ_tmp_agreements set UserID1='$place[3]',Login1=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[1]') where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and ((Pair1='$q[Pair]' and Place1='3') or (Pair2='$q[Pair]' and Place2='3'))"); //runsql("update champ_tmp_agreements set UserID2='$place[4]',Login2=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[2]') where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and ((Pair2='$q[Pair]' and Place2='4') or (Pair1='$q[Pair]' and Place1='4'))"); } elseif($u['StageTypeID']==1) { runsql("update champ_tournament_groups set UserID='$place[1]',Login=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[1]') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair='$q[Pair]' and Place='1'"); runsql("update champ_tournament_groups set UserID='$place[2]',Login=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[2]') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair='$q[Pair]' and Place='2'"); runsql("update champ_tmp_agreements set UserID1='$place[1]', Login1=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[1]') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair1='$q[Pair]' and Place1='1'"); runsql("update champ_tmp_agreements set UserID2='$place[1]', Login2=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[1]') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair2='$q[Pair]' and Place2='1'"); runsql("update champ_tmp_agreements set UserID2='$place[2]', Login2=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[2]') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair2='$q[Pair]' and Place2='2'"); runsql("update champ_tmp_agreements set UserID1='$place[2]', Login1=(select concat(if(GuildID>0 and GuildStatusID=1,concat('',' '),''),'',Login,'') from ut_users where UserID='$place[2]') where TournamentID='$q[TournamentID]' and Stage='$q[Stage]'+1 and Pair1='$q[Pair]' and Place1='2'"); } //группа соперника---------------------- if($u['Pair1']==$q['Pair']) $opgroup=$u['Pair2']; else $opgroup=$u['Pair1']; $g=select("select Finished from champ_tournament_groups where TournamentID='$q[TournamentID]' and Stage='$q[Stage]' and Name='$opgroup'"); if($g[0]==1 || $opgroup==$q['Pair']) { if($u['StageTypeID']==0) { runsql("insert ignore into champ_matches (UserID1,UserID2,TournamentID,Tour,GroupID,Stage,Fight,Pair,Pair1,Pair2,NumFights,StageTypeID) (select UserID1,UserID2,TournamentID,Tour,Pair,Stage,Fight,Pair,Pair1,Pair2,NumFights,StageTypeID from champ_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and (Pair1='$q[Pair]' or Pair2='$q[Pair]') and StatusID=0)"); runsql("update champ_tmp_agreements set StatusID=1 where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and (Pair1='$q[Pair]' or Pair2='$q[Pair]') and StatusID=0"); } elseif($u['StageTypeID']==1) { runsql("insert ignore into champ_matches (UserID1,UserID2,TournamentID,Tour,GroupID,Stage,Fight,Pair,Pair1,Pair2,NumFights,StageTypeID) (select UserID1,UserID2,TournamentID,Tour,Pair,Stage,Fight,Pair,Pair1,Pair2,NumFights,StageTypeID from champ_tmp_agreements where TournamentID='$q[TournamentID]' and ( (Tour='$q[Tour]'+1 and (Pair1='$q[Pair]' or Pair2='$q[Pair]') and Stage<>'$q[Stage]') or (Tour='$q[Tour]'+1 and (Pair='$q[Pair]') and Stage='$q[Stage]') ) and Fight=1 and StatusID=0)"); runsql("update champ_tmp_agreements set StatusID=1 where TournamentID='$q[TournamentID]' and ( (Tour='$q[Tour]'+1 and (Pair1='$q[Pair]' or Pair2='$q[Pair]') and Stage<>'$q[Stage]') or (Tour='$q[Tour]'+1 and (Pair='$q[Pair]') and Stage='$q[Stage]') ) and Fight=1 and StatusID=0"); } } } runsql("update champ_tournament_groups set Finished=1 where TournamentID='$q[TournamentID]' and Stage='$q[Stage]' and Name='$q[Pair]'"); } else { //print "Группа не завершена
"; $u=select("select * from champ_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and (UserID1='$q[UserID1]' or UserID2='$q[UserID1]')"); //доиграл ли соперник?--------- if($u['UserID1']==$q['UserID1']) $op=$u['UserID2']; elseif($u['UserID2']==$q['UserID1']) $op=$u['UserID1']; $q2=select("select RecordID from champ_matches where TournamentID='$q[TournamentID]' and Tour='$q[Tour]' and (UserID1='$op' or UserID2='$op') and Finished=1"); if($q2[0]) { //print "Бой соперника завершен
"; runsql("insert ignore into champ_matches (UserID1,UserID2,TournamentID,Tour,GroupID,Stage,Fight,Pair,Pair1,Pair2,NumFights,StageTypeID) (select UserID1,UserID2,TournamentID,Tour,Pair,Stage,Fight,Pair,Pair1,Pair2,NumFights,StageTypeID from champ_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and Pair='$q[Pair]' and StatusID=0)"); runsql("update champ_tmp_agreements set StatusID=1 where TournamentID='$q[TournamentID]' and Tour='$q[Tour]'+1 and Fight=1 and Pair='$q[Pair]' and StatusID=0"); } } } } else { //print "Победитель ещё не определен
"; //добавить следующий бой в серии runsql("insert ignore into champ_matches (UserID1,UserID2,TournamentID,Tour,GroupID,Stage,Fight,Pair,Pair1,Pair2,NumFights,StageTypeID) (select UserID1,UserID2,TournamentID,Tour,Pair,Stage,Fight,Pair,Pair1,Pair2,NumFights,StageTypeID from champ_tmp_agreements where TournamentID='$q[TournamentID]' and Tour='$q[Tour]' and Fight=1+'$q[Fight]' and (UserID1='$q[UserID1]' or UserID1='$q[UserID2]') and StatusID=0)"); runsql("update champ_tmp_agreements set StatusID=1 where TournamentID='$q[TournamentID]' and Tour='$q[Tour]' and Fight=1+'$q[Fight]' and (UserID1='$q[UserID1]' or UserID1='$q[UserID2]') and StatusID=0"); } } function convertBonus($id,$bonus) { $userMarketingStats=getMarketingStats($id); $userMarketingStats['sessionBonusPaidOutcome']+=$bonus; setMarketingStats($id,$userMarketingStats); } function transfer_bonus($user1,$user2,$bonus,$logtype,$free,$operationobject = '') { if (!is_numeric($bonus) || (float)$bonus <= 0) { Log::debug( "[SQLI] transfer_bonus($user1, $user2, $bonus, $logtype, $free, $operationobject)" . print_r( debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), true ) ); } if(!$user1 || !$user2 || !$bonus || !$logtype) return 0; if($user1==1) $user=$user2; if($user2==1) $user=$user1; if(!$free) $free=0; if($auth->user!=$user) { $rst=read_rst($user); $level=$rst['Level']; $money=$rst['Money']; } else { $level=$auth->level; $money=$auth->money; } if($user2==1) { $p=select("select Bonus from vp_bonus where UserID='$user'"); $f=select("select Bonus from vp_bonus2 where UserID='$user'"); if(!$f['Bonus']) $f['Bonus']=0; if(!$p['Bonus']) $p['Bonus']=0; $p['Bonus']=$p['Bonus']-$f['Bonus']; //$free=0 снятие только с платных //$free=1 снятие сперва бесплатных, потом платных if($free==1) { if($f['Bonus']>=$bonus) { runsql("update vp_bonus2 set Bonus=Bonus-$bonus where UserID=$user"); runsql("update vp_bonus set Bonus=Bonus-$bonus where UserID=$user"); runsql("insert into log_bonus (UserID,UserID2,TypeID,Date,Bonus,Level,Money,PayType,OperationObject) values ('$user','1','$logtype',unix_timestamp(),'$bonus','$level','$money',2,'$operationobject')"); $userMarketingStats=getMarketingStats($user); $userMarketingStats['sessionBonusFreeOutcome']+=$bonus; setMarketingStats($user,$userMarketingStats); } elseif($f['Bonus']<$bonus and $f['Bonus']!=0) { $ostatok=$bonus-$f['Bonus']; $freebonus=$f['Bonus']; runsql("update vp_bonus2 set Bonus=0 where UserID=$user"); runsql("update vp_bonus set Bonus=Bonus-$ostatok-$freebonus where UserID=$user"); runsql("insert into log_bonus (UserID,UserID2,TypeID,Date,Bonus,Level,Money,PayType,OperationObject) values ('$user','1','$logtype',unix_timestamp(),'$f[Bonus]','$level','$money',2,'$operationobject')"); runsql("insert into log_bonus (UserID,UserID2,TypeID,Date,Bonus,Level,Money,PayType,OperationObject) values ('$user','1','$logtype',unix_timestamp(),'$ostatok','$level','$money',1,'$operationobject')"); $userMarketingStats=getMarketingStats($user); $userMarketingStats['sessionBonusFreeOutcome']+=$f['Bonus']; $userMarketingStats['sessionBonusPaidOutcome']+=$ostatok; setMarketingStats($user,$userMarketingStats); } elseif($p['Bonus']>=$bonus) { runsql("update vp_bonus set Bonus=Bonus-$bonus where UserID=$user"); runsql("insert into log_bonus (UserID,UserID2,TypeID,Date,Bonus,Level,Money,PayType,OperationObject) values ('$user','1','$logtype',unix_timestamp(),'$bonus','$level','$money',1,'$operationobject')"); $userMarketingStats=getMarketingStats($user); $userMarketingStats['sessionBonusPaidOutcome']+=$bonus; setMarketingStats($user,$userMarketingStats); } } elseif($free==0) { if($p['Bonus']>=$bonus) { runsql("update vp_bonus set Bonus=Bonus-$bonus where UserID=$user"); runsql("insert into log_bonus (UserID,UserID2,TypeID,Date,Bonus,Level,Money,PayType,OperationObject) values ('$user','1','$logtype',unix_timestamp(),'$bonus','$level','$money',1,'$operationobject')"); $userMarketingStats=getMarketingStats($user); $userMarketingStats['sessionBonusPaidOutcome']+=$bonus; setMarketingStats($user,$userMarketingStats); } } } elseif($user1==1) { if($free==1) { runsql("insert into vp_bonus (UserID,Bonus) values($user,$bonus) on duplicate key update Bonus=Bonus+$bonus"); runsql("insert into vp_bonus2 (UserID,Bonus) values($user,$bonus) on duplicate key update Bonus=Bonus+$bonus"); runsql("insert into log_bonus (UserID,UserID2,TypeID,Date,Bonus,Level,Money,PayType,OperationObject) values ('1','$user','$logtype',unix_timestamp(),'$bonus','$level','$money',2,'$operationobject')"); $userMarketingStats=getMarketingStats($user); $userMarketingStats['sessionBonusFreeIncome']+=$bonus; setMarketingStats($user,$userMarketingStats); } elseif($free==0) { runsql("insert into vp_bonus (UserID,Bonus) values($user,$bonus) on duplicate key update Bonus=Bonus+$bonus"); runsql("insert into log_bonus (UserID,UserID2,TypeID,Date,Bonus,Level,Money,PayType,OperationObject) values ('1','$user','$logtype',unix_timestamp(),'$bonus','$level','$money',1,'$operationobject')"); $userMarketingStats=getMarketingStats($user); $userMarketingStats['sessionBonusPaidIncome']+=$bonus; setMarketingStats($user,$userMarketingStats); } } } function user_is_online($id) { global $img_path,$site_path,$secpass,$PHP_SELF,$QUERY_STRING,$auth,$onlinestatus,$onlineicon; $filename = $site_path."files/logon/$id"; if (file_exists($filename)) { //echo "Файл $filename в последний раз был изменен: " . System::date("F d Y H:i:s.", filectime($filename)); if((time()-filectime($filename))<300) { $onlinestatus=1; $onlineicon="".message("; } else { $onlinestatus=0; $onlineicon=""; } } else { $onlinestatus=0; $onlineicon="".message("; } } function division($id, $tournament = false) { global $auth; if($auth->zone=="rus") $min_tour=2; else $min_tour=1; $div_ar = array (1 => '1', 2 => '2-A', 3 => '2-B', 4 => '3-A', 5 => '3-B', 6 => '3-C', 7 => '3-D', 8 => '4-A', 9 => '4-B', 10 => '4-C', 11 => '4-D', 12 => '4-E', 13 => '4-F', 14 => '4-G', 15 => '4-H', 16 => '5-A', 17 => '5-B', 18 => '5-C', 19 => '5-D', 20 => '5-E', 21 => '5-F', 22 => '5-G', 23 => '5-H', 24 => '5-I', 25 => '5-J', 26 => '5-K', 27 => '5-L', 28 => '5-M', 29 => '5-N', 30 => '5-O', 31 => '5-P', 32 => '6-A', 33 => '6-B', 34 => '6-C', 35 => '6-D', 36 => '6-E', 37 => '6-F', 38 => '6-G', 39 => '6-H', 40 => '6-I', 41 => '6-J', 42 => '6-K', 43 => '6-L', 44 => '6-M', 45 => '6-N', 46 => '6-O', 47 => '6-P', 48 => '6-Q', 49 => '6-R', 50 => '6-S', 51 => '6-T', 52 => '6-U', 53 => '6-V', 54 => '6-W', 55 => '6-X', 56 => '6-Y', 57 => '6-Z', 58 => '6-AA', 59 => '6-AB', 60 => '6-AC', 61 => '6-AD', 62 => '6-AE', 63 => '6-AF',64=>'7-A'); if ($tournament && $tournament <= $min_tour) return $id; else return $div_ar[$id]; } function tournament_money($insertid2) { $t=select("select p.TournamentPrice,t.TournamentID,t.GuildID from ft_tournaments t left outer join ft_tournament_types p on p.TournamentTypeID=t.TournamentTypeID where t.TournamentID='$insertid2;' "); transfer_guild2user($t['TournamentPrice'],$t['GuildID'],1,45,$t['TournamentID']); } function parent_filename() { $call_stack=debug_backtrace(); return $call_stack[1]['file']; } function getLastGame($user) { return Cache_Memcache::getValue("${user}_LastGame"); } function setLastGame($user,$id) { return Cache_Memcache::setValue("${user}_LastGame",$id,3600); } function backtraceAsString($backtrace) { $result=Array(); foreach($backtrace as $item) $result[]="in $item[file] at $item[line]"; return implode("\n",$result); } function repairHash($array) { if (!is_array($array)) { Log::debug("repairHash".print_r($array,true)); return $array; } foreach ( $array as $k => $v ) { $result [$k] = $v; } return $result; } function userRosterRepair($userID) { $user=$userID; list($level) = select("select Level from ut_users where UserID=$user"); if ($level) return; $res=runsql("select * from `nekki-11x11-archive`.archive_matches where userid1=$user or userid2=$user order by date desc limit 5"); print "select * from `nekki-11x11-archive`.archive_matches where userid1=$user or userid2=$user order by date desc limit 5"; print " (".mysql_num_rows($res).")"; $ok=0; while($r=mysql_fetch_array($res)) { $id=$r['RecordID']; $fname=gampath($id)."/$id.gam"; print "$fname
"; if ($id && file_exists ( $fname )) { $file = fopen ( $fname, "r" ); $str = fread ( $file, filesize ( $fname ) ); $ar = explode ( "RST\x01\x00\x00\x00", $str ); $game= unserialize ( substr ( $ar [0], 39, strlen ( $ar [0] ) - 4 - 39 ) ); $ar2 = explode ( "ORD\x01\x00\x00\x00", $ar [1] ); $rst1 = unserialize ( substr ( $ar2 [0], 32 ) ); $ord1 = unserialize ( substr ( $ar2 [1], 32 ) ); $ar2 = explode ( "ORD\x01\x00\x00\x00", $ar [2] ); $rst2 = unserialize ( substr ( $ar2 [0], 32 ) ); $ord2 = unserialize ( substr ( $ar2 [1], 32 ) ); $ord1 ['Squad'] = repairHash ( $ord1 ['Squad'] ); $ord2 ['Squad'] = repairHash ( $ord2 ['Squad'] ); $rst1 ['Players'] = repairHash ( $rst1 ['Players'] ); $rst2 ['Players'] = repairHash ( $rst2 ['Players'] ); } if($rst1['UserID']==$user) { print_r($rst1); lock_rst($user); $rst=read_rst($user); $rst=$rst1; write_rst($user,$rst); unlock_rst($user); break; } elseif($rst2['UserID']==$user) { print_r($rst2); lock_rst($user); $rst=read_rst($user); $rst=$rst2; write_rst($user,$rst); unlock_rst($user); break; } } } function detectMobile() { $useragent = $_SERVER['HTTP_USER_AGENT']; return preg_match('/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)) ? true : false ; } function getMinAwardFee($id,$champ) { global $auth; if (!$id) return 0; if (!$champ) { $q = select("select f.*,t.NumStages,t.TypeID ModeID,f.TypeID MatchTypeID from ft_agreements f left outer join ft_tournaments t on t.TournamentID=f.TournamentID where (UserID1='$auth->user' or UserID2='$auth->user') and Approved=1"); if($q['MatchTypeID']==1) { $fee = ceil((pow(2,$auth->level))*5); } else { if ($q['ModeID']==19) $fee = ceil((pow(2,$auth->level))*pow(2,$q['Stage'])+500); else $fee = ceil((50*(pow(2,$auth->level))/($q['NumStages']-$q['Stage']+1))); } } else { $divisionid = select("select DivisionID,TournamentID,Stage from champ_matches where RecordID='$id' and Finished=0"); $tourtype = select("select TournamentTypeID,NumStages from champ_tournaments where TournamentID='$divisionid[TournamentID]'"); if ($tourtype[0]==73 || $tourtype[0]==3987) { $fee = ceil(1500*(pow(2,4))/($tourtype[1]-$tournament['Stage']+1)); } elseif ($tourtype[0]==66) { $levelid = select("select Level from champ_division_types where DivisionID='$divisionid[DivisionID]'"); $fee = ceil(375*(pow(2,4))/$levelid[0]); } else { $fee = 25000; } } return $fee; } function loginMarketingStats($auth,$active = true) { // На данный момент еще нет auth глобального, но можно его получить параметром $id=$auth->user; $rst=$auth->rst; $marketingStats=Cache_Memcache::getValue("${id}_sessions"); if (empty($marketingStats)) { $marketingStats['loginTimestamp']=time(); $marketingStats['loginMoney']=$rst['Money']; $marketingStats['loginExp']=$rst['Exp']; $marketingStats['loginLevel']=$auth->level; $playersExp=0; foreach ($rst['Players'] as $player) $playersExp+=$player['Exp']; $marketingStats['loginPlayersExp']=$playersExp; $marketingStats['sessionWinT']=0; $marketingStats['sessionLoseT']=0; $marketingStats['sessionTieT']=0; $marketingStats['sessionInjuriesCountT']=0; $marketingStats['sessionInjuriesHoursT']=0; $marketingStats['sessionYellowT']=0; $marketingStats['sessionYellowRedT']=0; $marketingStats['sessionRedT']=0; $marketingStats['sessionWin']=0; $marketingStats['sessionLose']=0; $marketingStats['sessionTie']=0; $marketingStats['sessionInjuriesCount']=0; $marketingStats['sessionInjuriesHours']=0; $marketingStats['sessionYellow']=0; $marketingStats['sessionYellowRed']=0; $marketingStats['sessionRed']=0; $marketingStats['sessionPMailsIn']=0; $marketingStats['sessionPMailsOut']=0; $marketingStats['sessionMoneyIncome']=0; $marketingStats['sessionMoneyOutcome']=0; $marketingStats['sessionTourmentHits']=0; $marketingStats['sessionTourmentMisses']=0; $marketingStats['sessionBonusFreeIncome']=0; $marketingStats['sessionBonusPaidIncome']=0; $marketingStats['sessionBonusFreeOutcome']=0; $marketingStats['sessionBonusPaidOutcome']=0; $marketingStats['sessionChatMessagesPrivateSend']=0; $marketingStats['sessionChatMessagesPrivateReceive']=0; $marketingStats['sessionChatMessagesSend']=0; $marketingStats['sessionActive']=$active; Cache_Memcache::setValue("${id}_sessions",$marketingStats,3600); } return $marketingStats; } function logoutMarketingStats($id) { global $cfg; $marketingStats = Cache_Memcache::getValue("${id}_sessions"); if (!empty($marketingStats)) { $rst = read_rst($id); $marketingStats['logoutTimestamp'] = time(); $marketingStats['logoutMoney'] = $rst['Money']; $marketingStats['logoutExp'] = $rst['Exp']; $playersExp = 0; foreach ($rst['Players'] as $player) $playersExp += $player['Exp']; $marketingStats['logoutPlayersExp'] = $playersExp; $line = Array(); foreach($marketingStats as $key => $value) $line[] = "$key => $value"; $line = implode(',',$line); $sql = "( `UserID`, `Level`, `LoginTimestamp`, `LoginMoney`, `LoginExp`, `LoginPlayersExp`, `LogoutTimestamp`, `LogoutMoney`, `LogoutExp`, `LogoutPlayersExp`, `SessionWinT`, `SessionLoseT`, `SessionTieT`, `SessionInjuriesCountT`, `SessionInjuriesHoursT`, `SessionYellowT`, `SessionYellowRedT`, `SessionRedT`, `SessionWinF`, `SessionLoseF`, `SessionTieF`, `SessionInjuriesCountF`, `SessionInjuriesHoursF`, `SessionYellowF`, `SessionYellowRedF`, `SessionRedF`, `SessionPMailsIn`, `SessionPMailsOut`, `SessionMoneyIncome`, `SessionMoneyOutcome`, `SessionTourmentHits`, `SessionTourmentMisses`, `SessionBonusFreeIncome`, `SessionBonusPaidIncome`, `SessionBonusFreeOutcome`, `SessionBonusPaidOutcome`, `SessionChatMessagesPrivateSend`, `SessionChatMessagesPrivateReceive`, `SessionChatMessagesSend`, `SessionActive` ) values( '$id', '$marketingStats[loginLevel]', '$marketingStats[loginTimestamp]', '$marketingStats[loginMoney]', '$marketingStats[loginExp]', '$marketingStats[loginPlayersExp]', '$marketingStats[logoutTimestamp]', '$marketingStats[logoutMoney]', '$marketingStats[logoutExp]', '$marketingStats[logoutPlayersExp]', '$marketingStats[sessionWinT]', '$marketingStats[sessionLoseT]', '$marketingStats[sessionTieT]', '$marketingStats[sessionInjuriesCountT]', '$marketingStats[sessionInjuriesHoursT]', '$marketingStats[sessionYellowT]', '$marketingStats[sessionYellowRedT]', '$marketingStats[sessionRedT]', '$marketingStats[sessionWinF]', '$marketingStats[sessionLoseF]', '$marketingStats[sessionTieF]', '$marketingStats[sessionInjuriesCountF]', '$marketingStats[sessionInjuriesHoursF]', '$marketingStats[sessionYellowF]', '$marketingStats[sessionYellowRedF]', '$marketingStats[sessionRedF]', '$marketingStats[sessionPMailsIn]', '$marketingStats[sessionPMailsOut]', '$marketingStats[sessionMoneyIncome]', '$marketingStats[sessionMoneyOutcome]', '$marketingStats[sessionTourmentHits]', '$marketingStats[sessionTourmentMisses]', '$marketingStats[sessionBonusFreeIncome]', '$marketingStats[sessionBonusPaidIncome]', '$marketingStats[sessionBonusFreeOutcome]', '$marketingStats[sessionBonusPaidOutcome]', '$marketingStats[sessionChatMessagesPrivateSend]', '$marketingStats[sessionChatMessagesPrivateReceive]', '$marketingStats[sessionChatMessagesSend]', '$marketingStats[sessionActive]' ) "; $name = $cfg['DB']['servers'][0]['name']; //[!!!] //runsql("insert into `marketing_sessions` $sql"); //runsql("insert into `$name-archive`.`marketing_sessions` $sql"); } $marketingStats = Array(); Cache_Memcache::setValue("${id}_sessions",$marketingStats,0); } function getMarketingStats($id) { $marketingStats = Cache_Memcache::getValue("${id}_sessions"); if ( empty($marketingStats) ) $marketingStats = loginMarketingStats($id,false); return $marketingStats; } function setMarketingStats($id,$marketingStats) { return Cache_Memcache::setValue("${id}_sessions",$marketingStats,3600); } function updateConsts() { global $cfg,$site_path,$site_admin_path; executor_cmd("php $site_admin_path"."update_consts.php"); syncFileFtp($site_path.'config/consts.inc.php',$cfg['GLOBAL']['localization']['servers']); } function updateHandlerMenuRebuild($id,$dataSource) { if ($dataSource==DATA_SOURCE_DB) { $row=select("select TableName from lk_db where DataID=$id"); if ($row['TableName'] == 'en_menu') updateConsts(); } } function shardlistRender($sender) { global $cfg,$ref; $visible = set_params($sender->visibility) != 'hidden'; if (!$visible) { $sharID = $cfg['GLOBAL']['shard_id']; echo "name\" value=\"$sharID\">"; return; } $randomShardID = rand(0,99) < 70 ? 1 : 2 ; $referalShardID = $ref ? System::shardGetID('userid',$ref) : $randomShardID ; $names = Array (1 => 'Классический', 2 => 'Новый'); echo "'; } function userGetFreePlayerNumber($rst) { $numbers = Array(); foreach($rst['Players'] as $player) $numbers[$player['Number']] = true; $result = 1; while ($numbers[$result]) $result++; return $result; } function get_free_bonuses() { global $auth; $free = $auth->rang-1; if (!$auth->rang) $free = 0; return $free; } function first_schedule_gd_tournament($id) { global $img_path,$auth; $q=select("select * from gd_tournaments where TournamentID='$id' limit 1"); if($q[0]) { if($q['StatusID']==1 and $q['StartDate']<=time()) { $m=select("select count(UserID) from gd_tournament_members where TournamentID='$id'"); if($m[0]<$q['NumPlayers']) return 0; runsql("update gd_tournaments set StatusID=2,StartDate=unix_timestamp() where TournamentID='$id'"); runsql("update ft_tournaments set StatusID=1 where TournamentID='$id'"); runsql("update gd_tournament_members set StatusID=1,StageID=0 where TournamentID='$id'"); $q['StatusID']=2; } if($q['StatusID']==2) { $tour=select("select TournamentID from ft_tournaments where TournamentID='$id'"); if(!$tour[0]) { runsql("insert into ft_tournaments (TournamentID,StatusID,TournamentTypeID,TypeID,GuildID,NumStages,NumPlayers,MaxLevel,MinLevel,Date,UserID,ZoneID) values ('$id',1,13227,19,'$q[GuildID2]','$q[NumStages]','$q[NumPlayers]','$q[MaxLevel]','$q[MinLevel]',unix_timestamp(),'$q[UserID]','$q[ZoneID]')"); } $stages=runsql("select distinct StageID from gd_tournament_members where StatusID=1 and TournamentID='$id'"); $max_stage=select("select max(StageID) from gd_tournament_members where StatusID=1 and TournamentID='$id'"); $end1=select("select count(*) from gd_tournament_members where StatusID>=1 and GuildID='$q[GuildID1]' and TournamentID='$id'"); $end2=select("select count(*) from gd_tournament_members where StatusID>=1 and GuildID='$q[GuildID2]' and TournamentID='$id'"); if($end2[0]==0) $winner=$q['GuildID1']; elseif($end1[0]==0) $winner=$q['GuildID2']; if($end1[0]==0 or $end2[0]==0) { runsql("update gd_tournaments set StatusID=3,WinnerID='$winner', Score1=(select sum(Score) from gd_tournament_members where TournamentID='$id' and GuildID='$q[GuildID1]'), Score2=(select sum(Score) from gd_tournament_members where TournamentID='$id' and GuildID='$q[GuildID2]') where TournamentID='$id'"); runsql("update ft_tournaments set StatusID=2 where TournamentID='$id'"); } while($s=mysql_fetch_array($stages)) { $stage=$max_stage[0]+1; $u1=select("select count(*) from gd_tournament_members where StatusID=1 and GuildID='$q[GuildID1]' and TournamentID='$id'"); $u2=select("select count(*) from gd_tournament_members where StatusID=1 and GuildID='$q[GuildID2]' and TournamentID='$id'"); if($u1[0]>$u2[0]) $numpairs=$u2[0]; elseif($u2[0]>$u1[0]) $numpairs=$u1[0]; else $numpairs=$u1[0]; if($numpairs>0) { for($i=1;$i<=$numpairs;$i++) { $user1=select("select * from gd_tournament_members where StatusID=1 and GuildID='$q[GuildID2]' and TournamentID='$id' order by Rand() limit 1"); $user2=select("select * from gd_tournament_members where StatusID=1 and GuildID='$q[GuildID1]' and TournamentID='$id' order by Rand() limit 1"); if($user1&&$user1) { runsql("insert ignore into ft_agreements (UserID1,UserID2,Timeout,TypeID,TournamentID,StatusID,Approved,Stage,Pair,Date,Login1,Login2) values ('$user1[UserID]','$user2[UserID]',5,0,'$id',2,1,'$stage','$i',unix_timestamp(),'$user1[Login]','$user2[Login]')"); runsql("update gd_tournament_members set StatusID=2 where TournamentID='$id' and (UserID='$user1[UserID]' or UserID='$user2[UserID]')"); } } } } //generate_gd($id); } } } function gd_next_schedule($id) { $q=select("select * from ft_matches where RecordID='$id'"); if($q['WinnerID']==$q['UserID1']) $loser=$q['UserID2']; else $loser=$q['UserID1']; $score=pow(2,$q['Stage']-1); runsql("update gd_tournament_members set StatusID=1,StageID=StageID+1,Score=Score+'$score' where TournamentID='$q[TournamentID]' and UserID='$q[WinnerID]'"); runsql("update gd_tournament_members set StatusID=0 where TournamentID='$q[TournamentID]' and UserID='$loser'"); } function userStartMoney() { global $auth; $userID = $auth->user; if ($auth->rst['MoneyDate']) { list($count) = select("select count(*) from vp_payments where UserID=$userID"); if (System::date("Ymd")>System::date("Ymd",$auth->rst['MoneyDate']) || $count) { lock_rst($userID); $rst = read_rst($userID); $rst = short_transfer_money($rst,Consts::START_MONEY,1,$userID,OperationType::START_MONEY); $rst['Messages'] .= PopupMessageType::START_MONEY."|0,"; unset($rst['MoneyDate']); runsql("delete from rg_start_money where UserID=$userID"); write_rst($userID,$rst); unlock_rst($userID); } } } function userGetKitOld($userID) { $kit = select("select KitID,Color1,Color2 from ut_settings where UserID=$userID"); $kitID = ($kit && $kit['KitID']) ? $kit['KitID'] : Consts::DEFAULT_KIT_ID; $primaryColor = ($kit && $kit['KitID']) ? $kit['Color1'] : Consts::DEFAULT_PRIMARY_COLOR; $secondaryColor = ($kit && $kit['KitID']) ? $kit['Color2'] : Consts::DEFAULT_SECONDARY_COLOR; return Array($kitID,$primaryColor,$secondaryColor); } /* function userGetKitImageURL($kit,$home,$dummy) { //[!!!] $home,$dummy return $dummy ? "/images/kit/home/".$kit['KitID']."/0x".$kit['PrimaryColor']."_0x".$kit['SecondaryColor'].".gif" : "/images/kit/home/".$kit['KitID']."/0x".$kit['PrimaryColor']."_0x".$kit['SecondaryColor']."_s.gif" ; } function gameGetKit($userID,$kit) { return $kit['ID1'] ? Array('KitID' => $kit['ID1'],'PrimaryColor' => $kit['Color1'],'SecondaryColor' => $kit['Color2']) : userGetKit($userID) ; } */ function userGetHTMLEnabled($userID) { //TODO: Это хорошая практика? $userID = (int)$userID; $settings = select("select HTML from ut_settings where UserID=$userID"); //TODO: bool vs int return ($settings['HTML'] ?? true) ? 1 : 0; } function userGetKit($userID) { $kit = select("select KitID,Color1,Color2 from ut_settings where UserID=$userID"); $kitID = ($kit && $kit['KitID']) ? $kit['KitID'] : Consts::DEFAULT_KIT_ID; $primaryColor = ($kit && $kit['KitID']) ? $kit['Color1'] : Consts::DEFAULT_PRIMARY_COLOR; $secondaryColor = ($kit && $kit['KitID']) ? $kit['Color2'] : Consts::DEFAULT_SECONDARY_COLOR; return Array('KitID' => $kitID, 'PrimaryColor' => $primaryColor, 'SecondaryColor' => $secondaryColor); } function userGetKitImageURL($kit, $home, $original) { $prefix = $home ? '/images/kit/home/' : '/images/kit/away/'; $suffix = $original ? '' : '_s'; return mb_strtolower( $prefix . $kit['KitID'] . "/0x" . $kit['PrimaryColor'] . "_0x" . $kit['SecondaryColor'] . $suffix . ".gif" ); } function gameGetKit($userID, $kit) { return $kit['ID1'] ? Array( 'KitID' => $kit['ID1'], 'PrimaryColor' => $kit['Color1'], 'SecondaryColor' => $kit['Color2'] ) : userGetKit($userID); } function userGetKitExID($userID) { $kit = select("select KitExID from ut_settings where UserID=$userID"); if (time() >= 1774990800 && time() < 1775682000) { $kitExID = ($kit && $kit['KitExID']) ? $kit['KitExID'] : 0; $kitExID = in_array($kitExID, Array(-1, 0, 7, 8, 9, 10, 11, 12)) ? $kitExID : 0; } else return 0; return $kitExID; } function userGetKitExImageURL($kitExID) { $kitExIndex = $kitExID; $kitExIndex = ($kitExID==-1) ? rand(7,12) : $kitExIndex; return $kitExIndex ? '/images/kit/ex/'.$kitExIndex.'.jpg' : '' ; } function userGetLogo($userID) { global $site_path; return file_exists($site_path."/images/ut_users/logo/$userID.png"); } function userGetLogoImageURL($userID) { global $img_path; return userGetLogo($userID) ? "$img_path"."ut_users/logo/$userID.png" : "$img_path"."shield.jpg" ; } function drawModalMessage($visible,$query,$name,$function) { global $auth; $userID = $auth->user; $level = $auth->level; if (!$visible) return false; list($messageID) = select($query); if (!$messageID) return false; if ($messageID<=$auth->rst[$name]) return false; lock_rst($userID); $rst = read_rst($userID); $rst[$name] = $messageID; write_rst($userID,$rst); unlock_rst($userID); if ($level) $function($messageID); return true; } /* function drawModalNews($visible) { global $auth; return drawModalMessage($visible,"select max(NewsID) from ut_news where Date>unix_timestamp()-7*86400 and ( TypeID=1 or (TypeID=2 and GuildID='$auth->guild') ) and ZoneID='$auth->zone'",'NewsID','showmodal_news'); } function drawModalEvents($visible) { global $auth; return drawModalMessage($visible,"select max(MaterialID) as Max from ut_competition where ZoneID='$auth->zone' and StartDate <= unix_timestamp() and EndDate >= unix_timestamp()",'EventID','showmodal_events'); } */ function drawModalNews($visible) { global $auth; return drawModalMessage($visible, "select max(NewsID) from ut_news where Date>unix_timestamp()-7*86400 and (TypeID=1 or (TypeID=2 and GuildID='$auth->guild')) and ZoneID='$auth->zone' and Active=1", 'NewsID', 'showmodal_news'); } function drawModalEvents($visible) { global $auth; return drawModalMessage($visible, "select max(MaterialID) from ut_competition where StartDate<=unix_timestamp() and EndDate>=unix_timestamp() and ZoneID='$auth->zone' and StatusID=1", 'EventID', 'showmodal_events'); } function generate_gd($id) { $q=runsql("select * from ft_agreements where TournamentID='$id'"); while($r=mysql_fetch_array($q)) { $win=rand(1,10); if($win<=5) { $winner=$r['UserID1']; $score1=1; $score2=0; } else { $winner=$r['UserID2']; $score1=0; $score2=1; } runsql("insert into ft_matches(AB1,AB2,Visitors,RecordID,UserID1,UserID2,Date,TypeID, TournamentID,Stage,Tour,Fight,Pair,StageTypeID,WinnerID,Score1,Score2,Login1,Login2) (select '$ab1','$ab2','999',RecordID,UserID1,UserID2,unix_timestamp(),TypeID, TournamentID,Stage,Tour,Fight,Pair,StageTypeID,'$winner','$score1','$score2',Login1,Login2 from ft_agreements where RecordID='$r[RecordID]')"); runsql("delete from ft_agreements where RecordID='$r[RecordID]'"); gd_next_schedule($r['RecordID']); } } function imagecreatefromhex($data,$width,$height,$format = 'zlib') { $bitmap = pack("H*",$data); if ($format == 'zlib') $bitmap = gzuncompress($bitmap); $bitmap = unpack("C*",$bitmap); $image = imagecreatetruecolor($width,$height); imagealphablending($image,false); imagesavealpha($image,true); $i = 1; for ($y = 0; $y < $height; $y++) for ($x = 0; $x < $width; $x++) { $a = 127-($bitmap[$i++] >> 1); $r = $bitmap[$i++]; $g = $bitmap[$i++]; $b = $bitmap[$i++]; $color = imagecolorallocatealpha($image,$r,$g,$b,$a); imagesetpixel($image,$x,$y,$color); } return $image; } function questTriggerCondition($dummy1,$dummy2) { //[!!!] } function getBottomMenuItem($item,$selected) { global $cfg; $u1 = $selected ? '' : '' ; $u2 = $selected ? '' : '' ; $style = $selected ? "style='color:#808080'" : ''; switch ($item['Title']) { case 'shop': if ($cfg['GLOBAL']['domain_suffix']!='ru') return false; break; } $url = set_params($item['Url']); $url = strstr($url,'http://') ? $url : "/$url" ; $target = $item['Target'] ? " target=\"$item[Target]\"" : ''; $name = settags($item['name']); $result = "$u1$name$u2"; return $result; } function drawBottomMenu($menu,$id,$visible,$selectedTitle) { echo $visible ? '' : "
"; $menuItems = Array(); foreach($menu as $item) { $selected = ($selectedTitle==$item['Title']) && $selectedTitle; if ($menuItem = getBottomMenuItem($item, $selected)) $menuItems[] = $menuItem; } $separator = count($menuItems) > 7 ? " | " : "   |   " ; echo implode($separator,$menuItems); echo $visible ? '' : "
" ; } function checkReferalOnMults($id) { //$id - UserID реферала, которого надо проверить на мульты $q=select("select ReferalID from ut_users where UserID='$id'"); $user=$q[0]; $m1=select("select count(*) from log_auth where (UserID='$user' and Control='$id') or (UserID='$id' and Control='$user')"); if($m1[0]>0) return true; $q=runsql("select * from ut_users where ReferalID='$user' and UserID!='$id'"); while($r=mysql_fetch_array($q)) { $m=select("select count(*) from log_auth where (UserID='$r[UserID]' and Control='$id') or (UserID='$id' and Control='$r[UserID]')"); if($m[0]>0) return true; } return false; } function onLogin($event) { $userID = $event->auth->user; } //function userGetSlots($userID, $rst = null) //{ // $rst = $rst ? $rst : read_rst($userID) ; // return $rst['Buildings'][2]*3 + 20; //} function userGetSlots($userID, $rst = null) { $rst = ($rst === null) ? read_rst($userID) : $rst; $result = $rst['Buildings'][2] * 3 + 20; list($premiumSlots) = select("select count(*) from vp_slots where UserID=$userID and End>unix_timestamp()"); $result += $premiumSlots; return $result; } //TODO: Именование userGetEnabledSlots, freeslots, usedslots function freeslots($userID, $rst = null) { $rst = ($rst === null) ? read_rst($userID) : $rst; $userID = $rst['UserID']; $slotsnum = userGetSlots($userID, $rst) - usedslots($userID, $rst); return $slotsnum; } function usedslots($userID, $rst = null) { $rst = ($rst === null) ? read_rst($userID) : $rst; $tmp = count($rst['Players']) + count($rst['Vacation']); return $tmp; } function humanizeFloat($value) { if (strstr($value,'.0')) return round($value); return (float)$value; } function userGetNickname($userID, $link = true) { $user = select("select * from ut_users where UserID=$userID"); return username($user,$link); } function GET_STAR_DATA() { $result = Array(); $result[] = Array('Exp' => 1.0, 'Skl' => 30, 'MaxSkl' => 240, 'Title' => message('star0', 'Неизвестен'), 'StarPoints' => 1); $result[] = Array( 'Exp' => 1.5, 'Skl' => 33, 'MaxSkl' => 264, 'Title' => message('star1', 'Звезда регионального уровня'), 'StarPoints' => 2 ); $result[] = Array( 'Exp' => 2.0, 'Skl' => 35, 'MaxSkl' => 280, 'Title' => message('star2', 'Звезда национального уровня'), 'StarPoints' => 3 ); $result[] = Array( 'Exp' => 2.5, 'Skl' => 37, 'MaxSkl' => 296, 'Title' => message('star3', 'Звезда международного уровня'), 'StarPoints' => 5 ); $result[] = Array('Exp' => 3.0, 'Skl' => 40, 'MaxSkl' => 320, 'Title' => message('star4', 'Легенда футбола'), 'StarPoints' => 7); $result[] = Array('Exp' => 5.0, 'Skl' => 50, 'MaxSkl' => 400, 'Title' => message('star5', 'Легенда спорта'), 'StarPoints' => 9); $result[] = Array('Exp' => 5.0, 'Skl' => 50, 'MaxSkl' => 400, 'Title' => message('star6', 'Легендарный игрок'), 'StarPoints' => 9); return $result; } class LocalConsts { const STAR_EXP = 25000; const STAR_MIN_SKL = 100; const STAR_MAX_SKL = 200; } function dobla() { $s = Array(11 => 100, 12 => 30, 13 => 10, 14 => 1); return array_weight_rand($s); } function openstar($player) { return ($player['Skl']>=LocalConsts::STAR_MIN_SKL) ? dobla() : 10 ; } function playerGetStarLevel($player) { return max(0,$player['StatusID']-10); } function playerIsStar($player) { return $player['StatusID'] >= 10; } function GET_STARS($userID = null) { global $auth; $userID = ($userID === null) ? $auth->user : $userID; $already = 0; $rst = read_rst($userID); foreach ($rst['Players'] as $k) { if (playerIsStar($k)) { $already++; } } foreach ($rst['Vacation'] as $k) { if (playerIsStar($k)) { $already++; } } return $already; } function GET_STARS_LIMITS($userID, $rst = null) { $rst = ($rst === null) ? read_rst($userID) : $rst; $allowed['Count'] = 0; $allowed['Total'] = 0; $already = GET_STARS($userID); $max = 22; $ha = Array( 0=> 0, 2500 => 1, 5000 => 2, 10000=> 3, 15000=> 4, 22500=> 5, 30000=> 6, 35000=> 7, 40000=> 8, 45000=> 9, 50000=> 10, 55000=> 11, 60000=> 12, 65000=> 13, 70000=> 14, 75000=> 15, 80000=> 16, 85000=> 17, 90000=> 18, 95000=> 19, 100000 => 20, 105000 => 21, 110000 => 22 ); foreach ($ha as $s => $p) { $sx = floor($s / Consts::STADIUM_FACTOR); if ($sx <= $rst['Capacity']) { $allowed['Total'] = $p; } if ($sx > $rst['Capacity']) { break; } } $allowed['Stadium'] = $sx; $allowed['Max'] = $max; //$allowed['Total'] = max($allowed['Total'], $already); //$allowed['Max'] = max($allowed['Max'], $already); list($count) = select("select count(*) from ut_arts where UserID=$userID and ArtID=8 and ActivationDate=0 and (ExpirationDate=0 or ExpirationDate>unix_timestamp())"); $count = $count ? $count : 0; foreach ($rst['Players'] as $player) { if ($player['StarSlot']) { $count++; } } foreach ($rst['Vacation'] as $player) { if ($player['StarSlot']) { $count++; } } $allowed['Extra'] = $count; $allowed['Total'] += $count; $allowed['Max'] += $count; $allowed['Count'] = max(0, $allowed['Total'] - $already); return $allowed; } function GET_STAR_ERROR() { global $auth; $star = GET_STARS_LIMITS($auth->user); if ($star['Count']<1) { if ($star['Total']<1) return System::error(message('starslimiterror1',"Для покупки звездных игроков увеличьте вместимость стадиона до").' '.$star['Stadium'].' '.message('stadseats','мест')); if ($star['Total']<$star['Max']) return System::error(message('starslimiterror2',"Максимальное число звездных игроков в вашей команде:")." ".$star['Total']."
".message('expandstad',"Для привлечения большего числа звезд расширьте стадион до")." ".$star['Stadium'].""); return System::error(message('starslimiterror3',"У вас максимально возможное число звездных игроков в команде.")); } return true; } function cashbackGetCompetition() { static $competition = null; $competition = $competition ?? select( "select * from ut_competition where TypeID in (16,25) and StartDate<=unix_timestamp() and EndDate>unix_timestamp() and StatusID=1 and ZoneID in ('rus','eng') limit 1" ); return $competition; } function cashbackEnabled() { $competition = cashbackGetCompetition(); return $competition !== false; //NOTE: Альтернатива //return (time() >= $competition['StartDate'] && time() < $competition['EndDate']); } function cashbackGetRate() { $competition = cashbackGetCompetition(); if ($competition['TypeID'] == 16) { return 0.5; } if ($competition['TypeID'] == 25) { return 0.2; } return 0; } function discountsGetCompetition() { static $competition = null; $competition = $competition ?? select( "select * from ut_competition where TypeID=10 and StartDate<=unix_timestamp() and EndDate>unix_timestamp() and StatusID=1 and ZoneID in ('rus','eng') limit 1" ); return $competition; } function discountsEnabled() { $competition = discountsGetCompetition(); return $competition !== false; //NOTE: Альтернатива //return (time() >= $competition['StartDate'] && time() < $competition['EndDate']); } function puzzleGetCompetition() { static $competition = null; $competition = $competition ?? select( "select * from ut_competition where TypeID in (8,9,21) and StartDate<=unix_timestamp() and EndDate>unix_timestamp() and StatusID=1 and ZoneID in ('rus','eng') limit 1" ); return $competition; } function puzzleEnabled() { $competition = puzzleGetCompetition(); return $competition !== false; //NOTE: Альтернатива //return (time() >= $competition['StartDate'] && time() < $competition['EndDate']); } function puzzleGetTypeID() { $competition = puzzleGetCompetition(); if ($competition['TypeID'] == 8) { return PuzzleTypeID::JACKPOT; } if ($competition['TypeID'] == 9) { return PuzzleTypeID::WIN_WIN; } if ($competition['TypeID'] == 21) { return PuzzleTypeID::LOTTO; } return null; } function pumpkinGetCompetition() { static $competition = null; $competition = $competition ?? select( "select * from ut_competition where TypeID in (27) and StartDate<=unix_timestamp() and EndDate>unix_timestamp() and StatusID=1 and ZoneID in ('rus','eng') limit 1" ); return $competition; } function pumpkinEnabled() { $competition = pumpkinGetCompetition(); return $competition !== false; //NOTE: Альтернатива //return (time() >= $competition['StartDate'] && time() < $competition['EndDate']); } function pumpkinClaimed() { global $auth; $userID = $auth->user; $competitionID = pumpkinGetCompetition()['MaterialID'] ?? 0; //TODO: Дублирование констант if (select("select * from vp_promo where UserID=$userID and TypeID=$competitionID")) { return true; } return false; } function pumpkinEligible() { global $auth; $userID = $auth->user; $competition = pumpkinGetCompetition(); if ($competition === false) { return false; } if (select( "select 1 from vp_payments where Date>=$competition[StartDate] and Date<$competition[EndDate] and StatusID=1 and UserID=$userID and Bonus>19 limit 1" )) { return true; } return false; } //TODO: Naming function mapPathFind($id1, $id2) { if (!select("select * from sn_cities where CityID=$id1")) { return false; } if (!select("select * from sn_cities where CityID=$id2")) { return false; } if ($id1 == $id2) { return array(array('node_identifier' => $id1, 'weight' => 0, 'accumulated_weight' => 0)); } $graph = array(); $data = runsql("select * from sn_paths"); while ($row = mysql_fetch_array($data)) { $graph[$row['CityID1']][$row['CityID2']] = 1; $graph[$row['CityID2']][$row['CityID1']] = 1; } $source = $id1; $dijkstra = new Dijkstra($graph, $source, true); $destination = $id2; $shortest_path1 = $dijkstra->shortestPathTo($destination); return $shortest_path1; } function userQuests() { global $auth; $userID = $auth->user; if (System::isSameDay($auth->rst['QuestsHelpersDailyDate'],time(),Consts::MAINTENANCE_TIME)) return; lock_rst($userID); $rst = read_rst($userID); $rst['QuestsHelpersDailyDate'] = time(); $rst['QuestsHelpers']['DailyMatchesCount'] = Array(); write_rst($userID,$rst); unlock_rst($userID); } function userGuild() { global $auth,$secpass2; $userID = $auth->user; $user = select("select * from ut_users where UserID=$userID"); $guildID = ($user['GuildStatusID']==1) ? $user['GuildID'] : '' ; if ($auth->guild==$guildID) return; $login = $auth->nick; $auth->loadProfile($login,$user); $auth->password = md5($user['Password'].$secpass2.$login); $auth->setupSession($login,'',$remember = true); } function userAgreement() { global $auth; $userID = $auth->user; if ($_SERVER['PHP_SELF']=='/agreement.php') return; if (!$userID) return; $user = select("select UserID from ut_users where UserID=$userID and Date<1362144505"); if (!$user) return; $agreement = select("select * from tmp_agreements where UserID=$userID"); if (!$agreement) System::redirect('/agreement.php'); } function userPromo11_11() { global $auth; $userID = $auth->user; if (time() < 1699650000 || time() >= 1699736400) { return; } if (System::isSameDay($auth->rst['Promo11_11Date'], time())) { return; } lock_rst($userID); $rst = read_rst($userID); transfer_bonus(1,$userID,1,BonusType::ADMINISTRATION_GIFT,false,$userID); transfer_bonus(1,$userID,10,BonusType::ADMINISTRATION_GIFT,true,$userID); //$rst['Messages'] .= PopupMessageType::PROMO_11_11 . ','; $rst['Promo11_11Date'] = time(); write_rst($userID, $rst); unlock_rst($userID); } function userMessages() { global $auth; $userID = $auth->user; list($count) = select("select count(*) from ut_messages where UserID=$userID"); if ($count==0) { return; } lock_rst($userID); $rst = read_rst($userID); $list = array(); $data = runsql("select * from ut_messages where UserID=$userID"); while ($row = mysql_fetch_array($data)) { $rst['Messages'] .= $row['Message']; $list[] = $row['ID']; } $list = count($list) ? implode(',', $list) : 'null'; runsql("delete from ut_messages where ID in ($list)"); write_rst($userID, $rst); unlock_rst($userID); } function onLoad($event) { global $authfast; if ($authfast) return; $event->auth->maxplayers = userGetSlots($event->auth->user,$event->auth->rst); $event->auth->numplayers = usedslots($event->auth->user, $event->auth->rst); userGuild(); userQuests(); userAgreement(); userPromo11_11(); userMessages(); } class ServiceID { const DSNR = 1; const ADSMARKET = 2; const FACEBOOK = 3; const ADVMARKET = 4; const _2PAY = 5; } function lottoAddTickets($UserID,$number=1) { global $cfg; //if(!$UserID || $cfg['GLOBAL']['domain_suffix']!='ru' || time()Consts::LOTTO_END) return; if (time()<1783285200 || time()>1784746800) return; srand(); //$num=round(rand(1,120)); //runsql("insert into vp_lotto (UserID,Number,Date) values ('$UserID','$num',unix_timestamp())"); lock_rst($UserID); $rst=read_rst($UserID); //$rst[Messages].=PopupMessageType::LOTTO."|$num,"; for ($i = 0; $i < $number; $i++) { $num=round(rand(1,120)); runsql("insert into vp_lotto (UserID,Number,Date) values ('$UserID','$num',unix_timestamp())"); $rst['Messages'].=PopupMessageType::LOTTO."|$num,"; } write_rst($UserID,$rst); unlock_rst($UserID); } function userGetExtra($userID) { $primary = select("select sum(Bonus) Bonus from ut_users u join vp_payments p on u.UserID=p.UserID where u.UserID=$userID and u.Level>=2 and u.Date5") ? true : false; list($paymentID) = select("select PaymentID from vp_payments where UserID=$userID order by Date desc limit 1"); srand($paymentID); $secondary = (rand(0, 99) < 95); return $primary && $secondary; } function checkgdX($userID, $guildID, $action) { global $auth; $userID = $userID ? $userID : $auth->user; $guildID = $guildID ? $guildID : $auth->guild; if (($action==2) || ($action==3) || ($action==4)) { //[!!!] OPS !!! //$season = select("select * from gd_tribune_seasons where StatusID<=1 limit 1"); //$season = select("select * from gd_tribune_seasons where StatusID<=2 order by Date desc limit 1"); $season = select("select * from gd_tribune_seasons where StatusID<=1 limit 1"); //$isSeason = $season || (time()>1586466000 && time()<1586552400); //$isSeason = (time()>1617951600 && time()<1618002000); //$isSeason = ($season && $season['Date']1649660400 && time()<1649710800); $isSeason = ($season && $season['Date'] 1788901200) && ($action==1)) { //return System::error('Вы не можете вступить футсоюз до завершения Кубка и Чемпионата Футсоюзов.'); //} //if ((time() > 1740430800) && ($action==2)) { //return System::error('Вы не можете покинуть футсоюз до завершения Кубка и Чемпионата Футсоюзов.'); //} //if (time() > 1786309200) //return System::error('Вы не можете покинуть/вступить в футсоюз до завершения Олимпиады.'); //$cur_season = select("select * from gd_champ_seasons where StatusID<=1 order by Number desc limit 1"); //if (select("select * from gd_champ_guilds where GuildID='$guildID' and SeasonID='$cur_season[SeasonID]'")) //return System::error('error'); //if (time()>1485723600) //return System::error('error'); //if (time()>1474232400 && time()<1476306000) //return System::error('error'); //return System::error('error'); return true; } function cookiesSurprice($userID) { $weights = array( 1 => 2000, 2 => 500, 3 => 500, 4 => 300, 5 => 150, 6 => 30, 7 => 500, 8 => 100, 9 => 20, 10 => 5, 11 => 2, 12 => 1000, 13 => 500, 14 => 100, 15 => 20, //16 => 5000, //17 => 2000, //18 => 500, 19 => 4000, 20 => 500, 21 => 200, 22 => 1000, 23 => 500, 24 => 50, 25 => 10, 26 => 5, 27 => 3, 28 => 2, 29 => 1, 30 => 5000, 31 => 2000, 32 => 2000, 33 => 1000, 34 => 500, 35 => 300 ); $value = array_weight_rand($weights); switch ($value) { case 1: // 5 приглашений for ($i = 0; $i < 5; $i++) { runsql( "insert into ut_arts(UserID,ArtID,Date,ExpirationDate) values ($userID,2,unix_timestamp(),unix_timestamp()+30*86400)" ); } break; case 2: //10 приглашений for ($i = 0; $i < 10; $i++) { runsql( "insert into ut_arts(UserID,ArtID,Date,ExpirationDate) values ($userID,2,unix_timestamp(),unix_timestamp()+30*86400)" ); } break; case 3: //Бонус опыта 6х3 runsql( "insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),6,3*3600,unix_timestamp()+30*86400)" ); break; case 4: //Бонус опыта 7х3 runsql( "insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),7,3*3600,unix_timestamp()+30*86400)" ); break; case 5: //Бонус опыта 8х3 runsql( "insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),8,3*3600,unix_timestamp()+30*86400)" ); break; case 6: //Бонус опыта 10х3 runsql( "insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),10,3*3600,unix_timestamp()+30*86400)" ); break; case 7: //5 бустеров transfer_bonus(1, $userID, 5, BonusType::ADMINISTRATION_GIFT, false, $userID); break; case 8: //10 бустеров transfer_bonus(1, $userID, 10, BonusType::ADMINISTRATION_GIFT, false, $userID); break; case 9: //20 бустеров transfer_bonus(1, $userID, 20, BonusType::ADMINISTRATION_GIFT, false, $userID); break; case 10: //50 бустеров transfer_bonus(1, $userID, 50, BonusType::ADMINISTRATION_GIFT, false, $userID); break; case 11: //100 бустеров transfer_bonus(1, $userID, 100, BonusType::ADMINISTRATION_GIFT, false, $userID); break; case 12: //3 звездных бонуса for ($i = 0; $i < 3; $i++) { runsql( "insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)" ); } break; case 13: //5 звездных бонусов for ($i = 0; $i < 5; $i++) { runsql( "insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)" ); } break; case 14: //10 звездных бонусов for ($i = 0; $i < 10; $i++) { runsql( "insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)" ); } break; case 15: //50 звездных бонусов for ($i = 0; $i < 50; $i++) { runsql( "insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)" ); } break; case 16: //10 звездных баллов //- break; case 17: //20 звездных баллов //- break; case 18: //30 звездных баллов //- break; case 19: //5 бесплатных самолетов for ($i = 0; $i < 5; $i++) { runsql( "insert into ut_arts(Date,ArtID,UserID,ExpirationDate) values(unix_timestamp(),27,$userID,unix_timestamp()+30*86400)" ); } break; case 20: //10 бесплатных самолетов for ($i = 0; $i < 10; $i++) { runsql( "insert into ut_arts(Date,ArtID,UserID,ExpirationDate) values(unix_timestamp(),27,$userID,unix_timestamp()+30*86400)" ); } break; case 21: //20 бесплатных самолетов for ($i = 0; $i < 20; $i++) { runsql( "insert into ut_arts(Date,ArtID,UserID,ExpirationDate) values(unix_timestamp(),27,$userID,unix_timestamp()+30*86400)" ); } break; case 22: //3 звездных талисмана for ($i = 0; $i < 3; $i++) { runsql( "insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),6,$userID,30000,0,unix_timestamp()+30*86400)" ); } break; case 23: //5 звездных талисманов for ($i = 0; $i < 5; $i++) { runsql( "insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),6,$userID,30000,0,unix_timestamp()+30*86400)" ); } break; case 24: //Звезда статус неизвестен runsql( "insert into ut_arts(UserID,ArtID,Date,ExpirationDate) values ($userID,17,unix_timestamp(),unix_timestamp()+3*86400)" ); break; case 25: //Звезда регионального уровня runsql( "insert into ut_arts(UserID,ArtID,Date,ExpirationDate) values ($userID,28,unix_timestamp(),unix_timestamp()+3*86400)" ); break; case 26: //Звезда национального уровня runsql( "insert into ut_arts(UserID,ArtID,Date,ExpirationDate) values ($userID,29,unix_timestamp(),unix_timestamp()+3*86400)" ); break; case 27: //Звезда международного уровня runsql( "insert into ut_arts(UserID,ArtID,Date,ExpirationDate) values ($userID,16,unix_timestamp(),unix_timestamp()+3*86400)" ); break; case 28: //Легенда футбола runsql( "insert into ut_arts(UserID,ArtID,Date,ExpirationDate) values ($userID,14,unix_timestamp(),unix_timestamp()+3*86400)" ); break; case 29: //Легенда спорта runsql( "insert into ut_arts(UserID,ArtID,Date,ExpirationDate) values ($userID,15,unix_timestamp(),unix_timestamp()+3*86400)" ); break; case 30: //5 продлений бонусов опыта for ($i = 0; $i < 5; $i++) { runsql("insert into ut_arts(UserID,ArtID,Date) values ($userID,18,unix_timestamp())"); } break; case 31: //10 продлений бонусов опыта for ($i = 0; $i < 10; $i++) { runsql("insert into ut_arts(UserID,ArtID,Date) values ($userID,18,unix_timestamp())"); } break; case 32: //Сборы Кипр runsql("insert into ut_free_practice(UserID,PracticeID,Date) values($userID,2,unix_timestamp())"); break; case 33: //Сборы Израиль runsql("insert into ut_free_practice(UserID,PracticeID,Date) values($userID,3,unix_timestamp())"); break; case 34: //Сборы Испания runsql("insert into ut_free_practice(UserID,PracticeID,Date) values($userID,4,unix_timestamp())"); break; case 35: //Сборы ОАЭ runsql("insert into ut_free_practice(UserID,PracticeID,Date) values($userID,5,unix_timestamp())"); break; } return $value; } function cookiesProcessBundle1($userID) { //5 бустеров, transfer_bonus(1, $userID, 5, BonusType::ADMINISTRATION_GIFT, false, $userID); //звездный бонус, runsql( "insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)" ); //бесплатный самолёт, runsql( "insert into ut_arts(Date,ArtID,UserID,ExpirationDate) values(unix_timestamp(),27,$userID,unix_timestamp()+30*86400)" ); //3 звездных балла, //- //сюрприз!* $i = cookiesSurprice($userID); $items = array($i => 1); $line = ''; foreach ($items as $itemID => $count) { $line .= "|$itemID|$count"; } $pu = PopupMessageType::PROMO_COOKIES; $ext = 1; $message = $pu . "|$ext" . "$line,"; runsql("insert into ut_messages(UserID,Message,Date) values($userID,'$message',unix_timestamp())"); //Log::debug("PROMO_COOKIES,1,$userID,$i"); } function cookiesProcessBundle2($userID) { //20 бустеров, transfer_bonus(1, $userID, 20, BonusType::ADMINISTRATION_GIFT, false, $userID); //2 звездных бонуса, runsql( "insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)" ); runsql( "insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)" ); //2 бесплатных самолёта, runsql( "insert into ut_arts(Date,ArtID,UserID,ExpirationDate) values(unix_timestamp(),27,$userID,unix_timestamp()+30*86400)" ); runsql( "insert into ut_arts(Date,ArtID,UserID,ExpirationDate) values(unix_timestamp(),27,$userID,unix_timestamp()+30*86400)" ); //бонус опыта х6 на 3 часа (срок годности 30 дней), runsql( "insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),6,3*3600,unix_timestamp()+30*86400)" ); //сюрприз!* $i = cookiesSurprice($userID); $items = array($i => 1); $line = ''; foreach ($items as $itemID => $count) { $line .= "|$itemID|$count"; } $pu = PopupMessageType::PROMO_COOKIES; $ext = 2; $message = $pu . "|$ext" . "$line,"; runsql("insert into ut_messages(UserID,Message,Date) values($userID,'$message',unix_timestamp())"); //Log::debug("PROMO_COOKIES,2,$userID,$i"); } function cookiesProcessBundle3($userID) { //60 бустеров, transfer_bonus(1, $userID, 60, BonusType::ADMINISTRATION_GIFT, false, $userID); //3 звездных бонуса, runsql( "insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)" ); runsql( "insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)" ); runsql( "insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)" ); //3 бесплатных самолёта, runsql( "insert into ut_arts(Date,ArtID,UserID,ExpirationDate) values(unix_timestamp(),27,$userID,unix_timestamp()+30*86400)" ); runsql( "insert into ut_arts(Date,ArtID,UserID,ExpirationDate) values(unix_timestamp(),27,$userID,unix_timestamp()+30*86400)" ); runsql( "insert into ut_arts(Date,ArtID,UserID,ExpirationDate) values(unix_timestamp(),27,$userID,unix_timestamp()+30*86400)" ); //бонус опыт х7 на 3 часа (срок годности 30 дней), runsql( "insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),7,3*3600,unix_timestamp()+30*86400)" ); //сюрприз!* $i = cookiesSurprice($userID); $items = array($i => 1); $line = ''; foreach ($items as $itemID => $count) { $line .= "|$itemID|$count"; } $pu = PopupMessageType::PROMO_COOKIES; $ext = 3; $message = $pu . "|$ext" . "$line,"; runsql("insert into ut_messages(UserID,Message,Date) values($userID,'$message',unix_timestamp())"); //Log::debug("PROMO_COOKIES,3,$userID,$i"); } function cookiesProcess($userID, $count) { if ($count > 4 && $count <= 9) { cookiesProcessBundle1($userID); } if ($count > 9 && $count <= 19) { cookiesProcessBundle2($userID); } if ($count > 19) { cookiesProcessBundle3($userID); } } function onPayment($event) { $userID = $event->data[0]; $money = $event->data[2]; list($countryID) = select("select CountryID from stat_users where UserID=$userID"); $time = time(); $promo = false; list($BID) = select("select BID from adcell_users where UserID=$userID"); if ($BID) file_get_contents("http://www.adcell.de/event.php?pid=1727&eventid=1761&referenz=$userID&betrag=$money&bid=$BID"); list($trackingCode) = select("select TrackingCode from ut_tracking_codes where UserID=$userID and ServiceID=".ServiceID::DSNR); if ($trackingCode) { if ($countryID=='fra') file_get_contents("http://pixel.traffiliate.com/pixel/serverPixels.php?master=91f3aefc-a2cd-11df-9e1f-005056a90ce7&context=$trackingCode"); if ($countryID=='ger') file_get_contents("http://pixel.traffiliate.com/pixel/serverPixels.php?master=ae16a18e-a2cd-11df-9e1f-005056a90ce7&context=$trackingCode"); } list($trackingCode) = select("select TrackingCode from ut_tracking_codes where UserID=$userID and ServiceID=".ServiceID::ADSMARKET); if ($trackingCode) file_get_contents("http://network.adsmarket.com/cevent?type=sale&programid=27411&visitor_cid=$trackingCode¤cy=EUR&value=$money&orderid=$time&p1=$userID"); /* list($discount) = select("select Discount from vp_discounts where UserID=$userID and StatusID=0"); if ($discount>0 && Consts::DISCOUNTS_DATE>time()) { if (Consts::DISCOUNTS_MODE == 'sum') $bonus = round($event->data[4] * $discount); else $bonus = round($event->data[4]*($discount-1)); if ($bonus>0) transfer_bonus(1,$userID,$bonus,BonusType::ADMINISTRATION_GIFT,false,$userID); } */ if (discountsEnabled()) { $competitionID = discountsGetCompetition()['MaterialID'] ?? 0; list($discount) = select("select Discount from vp_discounts where UserID=$userID and CompetitionID=$competitionID and StatusID=0"); if ($discount > 0) { if (Consts::DISCOUNTS_MODE == 'sum') { $bonus = round($event->data[4] * $discount); } else { $bonus = round($event->data[4] * ($discount - 1)); } if ($bonus > 0) { transfer_bonus(1, $userID, $bonus, BonusType::ADMINISTRATION_GIFT, false, $userID); } } } if ($event->data[1] == 2 && time() >= 1511125200 && time() < 1512075600) { $bonus = 0; $arts = 0; if ($event->data[4]>=20) { $bonus = 5; $arts = 2; } elseif ($event->data[4]>=10) { $bonus = 2; $arts = 1; } list($payments) = select("select count(*) from vp_payments where UserID=$userID and TypeID=2 and StatusID=1"); if ($payments==1 && $event->data[4]>=5) $bonus += 1; if ($bonus>0) transfer_bonus(1,$userID,$bonus,BonusType::ADMINISTRATION_GIFT,false,$userID); for ($i = 0; $i<$arts; $i++) runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),6,12*3600,unix_timestamp()+30*86400)"); } $bonus = $event->data[4]; $count = floor($bonus/2); if($count >= 1) lottoAddTickets($userID,$count); if (time() >= 1519592400 && time() < 1520024400) { $factor = 0.1; $range = System::range('last day'); while (($range[0]+$range[1])/2>1519592400) { list($volume) = select("select sum(Bonus) from vp_payments where StatusID=1 and UserID=$userID and Date>=$range[0] and Date<=$range[1]"); if ($volume<8) break; $factor += 0.1; $range[0] -= 86400; $range[1] -= 86400; } $factor = min(0.5,$factor); $bonus = round($event->data[4] * $factor); if ($bonus > 0) { transfer_bonus(1, $userID, $bonus, BonusType::ADMINISTRATION_GIFT, false, $userID); } } /* if (time()>=1390161600 && time()<1390766400) { $arts = 0; $tickets = 0; if ($event->data[4]>=15) { $arts = 1; $tickets = 0; } elseif ($event->data[4]>=10) { $arts = 0; $tickets = 3; } for ($i = 0; $i<$arts; $i++) runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time) values(1,$userID,unix_timestamp(),3,86400)"); for ($i = 0; $i<$tickets; $i++) runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time) values(2,$userID,unix_timestamp())"); } */ if (select( "select * from ut_competition where TypeID=18 and StartDate<=unix_timestamp() and EndDate>unix_timestamp() and StatusID=1 and ZoneID in ('rus','eng') limit 1" )) { list($count) = select("select count(*) from vp_payments where StatusID=1 and UserID=$userID"); if ($count==1) { $promo = true; $bonus = floor($event->data[4]*3); if ($bonus>0) transfer_bonus(1,$userID,$bonus,BonusType::ADMINISTRATION_GIFT,false,$userID); } } if (time() >= 1528146000 && time() < 1528405200) { $range = System::range('this day'); list($count) = select("select count(*) from vp_payments where StatusID=1 and UserID=$userID and Date>=$range[0] and Date<=$range[1]"); if ($count == 1) { $bonus = floor($event->data[4]); if ($bonus >= 1) { transfer_bonus(1, $userID, 10, BonusType::ADMINISTRATION_GIFT, false, $userID); } } } /* if (time() >= 1480021200 && time() < 1480280400 && $event->data[4] >= 20) { $range = System::range('this day'); list($count) = select("select count(*) from vp_payments where StatusID=1 and Bonus>=20 and UserID=$userID and Date>=$range[0] and Date<=$range[1]"); if ($count==1) { $bonus = floor($event->data[4] * 4); if ($bonus>0) transfer_bonus(1,$userID,$bonus,BonusType::ADMINISTRATION_GIFT,false,$userID); } }*/ if (time() >= 1515704400 && time() < 1515963600 && $event->data[4] >= 1) { $range = System::range('this day'); list($count) = select("select count(*) from vp_payments where StatusID=1 and Bonus>=1 and UserID=$userID and Date>=$range[0] and Date<=$range[1]"); if ($count<=3) { $bonus = floor($event->data[4] * 4); if ($bonus>0) transfer_bonus(1,$userID,$bonus,BonusType::ADMINISTRATION_GIFT,false,$userID); } } if (time() >= 1511470800 && time() < 1511557200 && $event->data[4] >= 5) { $range = System::range('this day'); list($count) = select("select count(*) from vp_payments where StatusID=1 and Bonus>=5 and UserID=$userID and Date>=$range[0] and Date<=$range[1]"); if (time() > 1511470800 && time() < 1511557200) { $count = 1; } if ($count == 1) { $bonus = floor(min(20,$event->data[4]) * 4); if ($bonus > 0) { transfer_bonus(1, $userID, $bonus, BonusType::ADMINISTRATION_GIFT, false, $userID); } } } if (time() >= 1699650000 && time() < 1699736400) { $range = System::range('this day'); list($count) = select("select count(*) from vp_payments where StatusID=1 and UserID=$userID and Date>=$range[0] and Date<=$range[1]"); if ($count == 1) { $pr_ = array( 0 => 100, 1 => 100, 2 => 100, 3 => 100, 4 => 50, 5 => 50, 6 => 25, 7 => 25, 8 => 50, 9 => 100, 10 => 50, 11 => 20, 12 => 10, 13 => 5, 14 => 2 ); $r = array_weight_rand($pr_); switch ($r) { case 0: runsql("insert into ut_arts(UserID,ArtID,Date,ExpirationDate) values ($userID,2,unix_timestamp(),unix_timestamp()+30*86400)"); runsql("insert into ut_arts(UserID,ArtID,Date,ExpirationDate) values ($userID,2,unix_timestamp(),unix_timestamp()+30*86400)"); runsql("insert into ut_arts(UserID,ArtID,Date,ExpirationDate) values ($userID,2,unix_timestamp(),unix_timestamp()+30*86400)"); runsql("insert into ut_arts(UserID,ArtID,Date,ExpirationDate) values ($userID,2,unix_timestamp(),unix_timestamp()+30*86400)"); runsql("insert into ut_arts(UserID,ArtID,Date,ExpirationDate) values ($userID,2,unix_timestamp(),unix_timestamp()+30*86400)"); break; case 1: runsql("insert into free_combinations(UserID,Combinations) values($userID,5) on duplicate key update Combinations=Combinations+5"); break; case 2: runsql("insert into free_bonus(UserID,Bonus) values($userID,5) on duplicate key update Bonus=Bonus+5"); break; case 3: runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)"); break; case 4: runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)"); break; case 5: runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)"); break; case 6: runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)"); break; case 7: runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)"); runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),3,$userID,25000,0,unix_timestamp()+30*86400)"); break; case 8: runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),6,$userID,30000,0,unix_timestamp()+30*86400)"); break; case 9: runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),3,3*3600,unix_timestamp()+30*86400)"); break; case 10: runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),4,3*3600,unix_timestamp()+30*86400)"); break; case 11: runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),5,3*3600,unix_timestamp()+30*86400)"); break; case 12: runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),6,3*3600,unix_timestamp()+30*86400)"); break; case 13: runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),7,3*3600,unix_timestamp()+30*86400)"); break; case 14: runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),8,3*3600,unix_timestamp()+30*86400)"); break; } } } if (time() >= 1774850400 && time() < 1774990800 && $event->data[4] >= 1) { $bonus = floor($event->data[4] * 4); if ($bonus > 0) { transfer_bonus(1, $userID, $bonus, BonusType::ADMINISTRATION_GIFT, false, $userID); } } if (select( "select * from ut_competition where TypeID=15 and StartDate<=unix_timestamp() and EndDate>unix_timestamp() and StatusID=1 and ZoneID in ('rus','eng') limit 1" )) { if ($event->data[4] >= 1) { $bonus = floor($event->data[4] * 4); if ($bonus > 0) { transfer_bonus(1, $userID, $bonus, BonusType::ADMINISTRATION_GIFT, false, $userID); } } } if (time() >= 1717016400 && time() < 1717189200) { cookiesProcess($userID, $event->data[4]); } if (time() >= 1632171600 && time() < 1632344400) { $bonus = 0; $stars = 0; if ($event->data[4] > 19 && $event->data[4] <= 49) { $bonus = round($event->data[4] * 0.2); $stars = 2; } if ($event->data[4] > 49 && $event->data[4] <= 99) { $bonus = round($event->data[4] * 0.3); $stars = 5; } if ($event->data[4] >= 100) { $bonus = round($event->data[4] * 0.5); $stars = 12; } if ($bonus > 0) { transfer_bonus(1, $userID, $bonus, BonusType::ADMINISTRATION_GIFT, false, $userID); } for ($i = 0; $i < $stars; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time) values(3,$userID,unix_timestamp(),25000,0)"); } } if (select( "select * from ut_competition where TypeID=19 and StartDate<=unix_timestamp() and EndDate>unix_timestamp() and StatusID=1 and ZoneID in ('rus','eng') limit 1" )) { $bonus = 0; $stars = 0; $xart = 0; $talismans = 0; $map = 0; if ($event->data[4] > 19 && $event->data[4] <= 49) { $bonus = round($event->data[4] * 2.0); $stars = 2; $xart = 4; $talismans = 1; $map = 1; } if ($event->data[4] > 49 && $event->data[4] <= 99) { $bonus = round($event->data[4] * 2.5); $stars = 5; $xart = 5; $talismans = 2; $map = 2; } if ($event->data[4] > 99) { $bonus = round($event->data[4] * 3.0); $stars = 10; $xart = 6; $talismans = 3; $map = 3; } if ($bonus > 0) { transfer_bonus(1, $userID, $bonus, BonusType::ADMINISTRATION_GIFT, false, $userID); } for ($i = 0; $i < $stars; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time) values(3,$userID,unix_timestamp(),25000,0)"); if ($xart>1) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),$xart,3*3600,unix_timestamp()+30*86400)"); } } for ($i = 0; $i < $talismans; $i++) { runsql("insert into ut_arts(Date,ArtID,UserID,Value,Time,ExpirationDate) values(unix_timestamp(),6,$userID,30000,0,unix_timestamp()+30*86400)"); } for ($i = 0; $i < $map; $i++) { runsql("insert into ut_arts(Date,ArtID,UserID,ExpirationDate) values(unix_timestamp(),27,$userID,unix_timestamp()+30*86400)"); } } if (!$promo) if (select( "select * from ut_competition where TypeID=20 and StartDate<=unix_timestamp() and EndDate>unix_timestamp() and StatusID=1 and ZoneID in ('rus','eng') limit 1" )) { $range = System::range('this day'); //list($count) = select("select count(*) from vp_payments where StatusID=1 and UserID=$userID and Date>=$range[0] and Date<=$range[1]"); $count = 1; $s = ($count == 1) ? Array('2' => 58, '3' => 8, '4' => 6, '5' => 5, '6' => 5, '7' => 4, '8' => 3, '9' => 2, '10' => 1) : Array('1' => 38, '2' => 20, '3' => 10, '4' => 8, '5' => 7, '6' => 6, '7' => 5, '8' => 3, '9' => 2, '10' => 1); $s = Array('2' => 30, '3' => 25, '4' => 20, '5' => 10, '6' => 5, '7' => 4, '8' => 3, '9' => 2, '10' => 1); $s = Array('1.5' => 30, '2' => 30, '2.5' => 25,'3' => 25, '3.5' => 20, '4' => 20,'4.5' => 10, '5' => 10, '5.5' => 5, '6' => 5, '6.5' => 4, '7' => 4, '7.5' => 3, '8' => 3, '8.5' => 2, '9' => 2, '9.5' => 1, '10' => 1); //[!!!] $s = Array('2' => 60, '2.5' => 25,'3' => 25, '3.5' => 20, '4' => 20,'4.5' => 10, '5' => 10, '5.5' => 5, '6' => 5, '6.5' => 4, '7' => 4, '7.5' => 3, '8' => 3, '8.5' => 2, '9' => 2, '9.5' => 1, '10' => 1); //[!!!] BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD $s = Array('3' => 40, '3.5' => 20, '4' => 20,'4.5' => 10, '5' => 10, '5.5' => 5, '6' => 5, '6.5' => 4, '7' => 4, '7.5' => 3, '8' => 3, '8.5' => 2, '9' => 2, '9.5' => 1, '10' => 1); //[!!!] NEW VERSION $s = Array('2' => 30, '3' => 25, '4' => 20, '5' => 10, '6' => 5, '7' => 4, '8' => 3, '9' => 2, '10' => 1); //[!!!] black //$s = Array(2.5 => 85,3 => 25, 3.5 => 20, 4 => 20,4.5 => 10, 5 => 10, 5.5 => 5, 6 => 5, 6.5 => 4, 7 => 4, 7.5 => 3, 8 => 3, 8.5 => 2, 9 => 2, 9.5 => 1, 10 => 1); //$s = Array('2.5' => 40,'3' => 25, '3.5' => 20, '4' => 20,'4.5' => 10, '5' => 10, '5.5' => 5, '6' => 5, '6.5' => 4, '7' => 4, '7.5' => 3, '8' => 3, '8.5' => 2, '9' => 2, '9.5' => 1, '10' => 1); //list($count) = select("select count(*) from vp_payments where StatusID=1 and UserID=$userID and Date>=1542920400 and Date<=1543179600"); //if ($count==1){$s = Array(3 => 110, 3.5 => 20, 4 => 20,4.5 => 10, 5 => 10, 5.5 => 5, 6 => 5, 6.5 => 4, 7 => 4, 7.5 => 3, 8 => 3, 8.5 => 2, 9 => 2, 9.5 => 1, 10 => 1);} /* list($lastFactor) = select("select Factor from vp_promo where UserID=$userID order by Date desc limit 1"); if ($lastFactor == 1) { $s[1] = 0; } */ //$s[1] = 0; $factor = array_weight_rand($s); $bonus= floor($event->data[4] * ($factor - 1)); if ($bonus > 0) { transfer_bonus(1, $userID, $bonus, BonusType::ADMINISTRATION_GIFT, false, $userID); lock_rst($userID); $rst = read_rst($userID); $rst['Messages'] .= PopupMessageType::PROMO_HALLOWEEN . "|$factor|$bonus,"; write_rst($userID, $rst); unlock_rst($userID); } if ($factor == 2) { $arts = floor($event->data[4] / 10); for ($i = 0; $i < $arts; $i++) { runsql("insert into ut_arts(ArtID,UserID,Date,Value,Time,ExpirationDate) values(1,$userID,unix_timestamp(),7,3*3600,unix_timestamp()+30*86400)"); } } runsql("insert into vp_promo(UserID,Factor,Date) values($userID,$factor,unix_timestamp())"); } $art = select("select * from ut_arts where UserID=$userID and ArtID=4 and ActivationDate=0 and (ExpirationDate=0 or ExpirationDate>unix_timestamp()) order by Date desc limit 1"); if ($art) { $bonus = floor($event->data[4] * $art['Value'] / 100); if ($bonus > 0) { transfer_bonus(1, $userID, $bonus, BonusType::ADMINISTRATION_GIFT, false, $userID); } runsql("update ut_arts set ActivationDate=unix_timestamp() where RecordID=$art[RecordID]"); runsql("update ut_arts set ActivationDate=unix_timestamp() where UserID=$userID and ArtID=4 and ActivationDate=0 and (ExpirationDate=0 or ExpirationDate>unix_timestamp())"); } if (time() >= 1550350800 && time() < 1550782800 && $event->data[4] >= 10) { $factor = 0.1; $n = 1; $range = System::range('last day'); while (true) { if (!select("select * from vp_payments where StatusID=1 and Bonus>=10 and UserID=$userID and Date>=1550350800 and Date<1550782800 and Date>=$range[0] and Date<=$range[1] limit 1")) { break; } $factor += 0.1; $n++; $range[0] -= 86400; $range[1] -= 86400; } $factor = min(0.5, $factor); $bonus = round($event->data[4] * $factor); if ($bonus > 0) { transfer_bonus(1, $userID, $bonus, BonusType::ADMINISTRATION_GIFT, false, $userID); } $n = min(5, $n); $list = Array(1 => 1, 2 => 3, 3 => 5, 4 => 7, 5 => 10); $points = floor($event->data[4] / 10) * $list[$n]; if ($points>0) { runsql("insert into vp_promo(UserID,Factor,Date,TypeID) values($userID,$points,unix_timestamp(),2)"); } } $bonus = $event->data[4]; userProcessReferalPayment($userID,$bonus); Log::debug('paygood os'); } function onRegistration($event) { global $site_id,$BID,$Token,$CeCid; $userID = $event->data[0]; if ($BID) runsql("insert into adcell_users(UserID,BID) values($userID,'$BID')"); if ($Token) runsql("insert into ut_tracking_codes(UserID,ServiceID,TrackingCode) values($userID,".ServiceID::DSNR.",'$Token')"); if ($CeCid) runsql("insert into ut_tracking_codes(UserID,ServiceID,TrackingCode) values($userID,".ServiceID::ADSMARKET.",'$CeCid')"); } function onActivation($event) { $userID = $event->data[0]; list($BID) = select("select BID from adcell_users where UserID=$userID"); if ($BID) file_get_contents("http://www.adcell.de/event.php?pid=1727&eventid=1760&referenz=$userID&bid=$BID"); } function onEffectiveRegistration($event) { $userID = $event->data[0]; } function onLevelUp($event) { $userID = $event->data[0]; $level = $event->data[1]; } function authAddEventListener($event,$listener) { global $_authEventListeners; $_authEventListeners[$event][]=$listener; } authAddEventListener('login','onLogin'); authAddEventListener('load','onLoad'); System::addEventListener(SystemEvent::PAYMENT,'onPayment'); System::addEventListener(SystemEvent::REGISTRATION,'onRegistration'); System::addEventListener(SystemEvent::ACTIVATION,'onActivation'); System::addEventListener(SystemEvent::EFFECTIVE_REGISTRATION,'onEffectiveRegistration'); System::addEventListener(SystemEvent::LEVEL_UP,'onLevelUp'); $_updateHandlers=Array(); $_updateHandlers[]='updateHandlerMenuRebuild'; require_once $site_path.'cls/common/cls_xml.php'; require_once $site_path.'cls/images/cls_image.php'; require_once $site_path.'cls/common/cls_db.php'; require_once $site_path.'cls/common/cls_root.php'; require_once $site_path.'cls/common/cls_menu.php'; require_once $site_path.'cls/common/cls_form.php'; require_once $site_path.'cls/common/Cache_Memcache.php'; require_once $site_path.'cls/utils/CensorFilter.php'; cls_controls::addRender('shardlist','shardlistRender'); ?>