Blame view

genpdf/genpdf.php 48 KB
redmine authored
1 2 3 4
<?php

require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Api/AbstractApi.php";
require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Api/SimpleXMLElement.php";
redmine authored
5
require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Api/User.php";
redmine authored
6
require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Api/Issue.php";
redmine authored
7
require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Api/IssueCategory.php";
redmine authored
8
require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Api/Attachment.php";
redmine authored
9
require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Api/Membership.php";
redmine authored
10 11
require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Client.php";

redmine authored
12 13
require_once "lib/3rdparty/Inflect/Inflect.php";

redmine authored
14 15
require_once "config.php";

redmine authored
16 17 18 19 20 21 22
// Anti-repeater:
$request_hash = sha1(serialize($_GET).serialize($_POST));
foreach(split("\n", file_get_contents("/tmp/gethashes")) as $request_hash_already) {
	if ($request_hash == $request_hash_already) {
		//die('Такой запрос уже был сгенерирован сегодня');
	}
}
redmine authored
23
file_put_contents("/tmp/gethashes", $request_hash."\n", FILE_APPEND|LOCK_EX);
redmine authored
24

redmine authored
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
/*

$user_redmine

Array
(
    [user] => Array
        (
            [id] => 17
            [login] => AAAnikeyev
            [firstname] => Артем
            [lastname] => Аникеев
            [mail] => AAAnikeyev@mephi.ru
            [created_on] => 2014-03-05T06:25:14Z
            [last_login_on] => 2014-07-17T11:10:01Z
            [api_key] => xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
            [status] => 1
            [custom_fields] => Array
                (
                    [0] => Array
                        (
                            [id] => 19
                            [name] => Отчество
                            [value] => Андреевич
                        )

                )

            [groups] => Array
                (
                    [0] => Array
                        (
                            [id] => 7
                            [name] => отдел юникс-технологий
                        )

                    [1] => Array
                        (
                            [id] => 55
                            [name] => группа HPC
                        )

                )

            [memberships] => Array
                (
                    [0] => Array
                        (
                            [id] => 777
                            [project] => Array
                                (
                                    [id] => 102
                                    [name] => *nix hosting request
                                )

                            [roles] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 4
                                            [name] => Разработчик
                                            [inherited] => 1
                                        )

                                )

                        )
                )

        )

)
*/

redmine authored
99 100 101 102 103 104 105
function stfcardid2login($stfcardid) {
	error_log("stfcardid2login($stfcardid)");
	static $stfcardid2login = array();

	$filename = '/opt/tmp/stfcardid2login.json';
	$s = stat($filename);
	if ($s === FALSE || (@$s[9]+3600*24) < time()) {
redmine authored
106
		system("bash /var/www/ut.mephi.ru/ut-tex/genpdf/cron.sh");
redmine authored
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
	}

	if (empty($stfcardid2login)) {
		$stfcardid2login = json_decode(file_get_contents($filename), 1);
	}

	error_log ('RS:'.$stfcardid2login[$stfcardid]);
	

	return $stfcardid2login[$stfcardid];

}

function considerAppointment($key, &$appointment) {
	global $inflect;
redmine authored
122 123
	$appointment_name  = preg_replace('/ [0-9]*.[0-9]$/', '', $appointment->name);
	$appointment_short = preg_replace('/ [0-9]\.[0-9]$/', '', trim($appointment->shortname));
redmine authored
124
	$appointments = $appointment_name.' '.mb_strtoupper($appointment->subdivision->shortname);
redmine authored
125
	$appointment_short_full = trim($appointment_short.' '.mb_strtoupper($appointment->subdivision->shortname));
redmine authored
126 127 128 129 130 131
	$appointment_ofsubdivfull       = $inflect->getInflectNoun($appointment->subdivision->name, 0);
	$appointment_name_words         = explode(' ', $appointment_name);
	$appointment_ofsubdivfull_words = explode(' ', $appointment_ofsubdivfull);
	if ($appointment_name_words[count($appointment_name_words)-1] == $appointment_ofsubdivfull_words[0]) {
		unset($appointment_name_words[count($appointment_name_words)-1]);
	}
redmine authored
132
	if ($appointment_ofsubdivfull_words[0] == 'ректората' || $appointment_ofsubdivfull_words[0] == 'аспирантуры') {
redmine authored
133 134 135 136 137 138 139
		unset($appointment_ofsubdivfull_words[0]);
	}
	$appointments_full = join(' ', $appointment_name_words).' '.join(' ', $appointment_ofsubdivfull_words);
	$appointments_wosubdiv = preg_replace('/ [0-9]*.[0-9]$/', '', $appointment->name);
	$signer_subdivs      = '['.$appointment->subdivision->s_code.'] '.mb_strtoupper($appointment->subdivision->shortname);
	$signer_subdivs_full = $appointment->subdivision->name;

redmine authored
140 141
	//error_log(serialize($appointment));

redmine authored
142 143 144 145 146 147 148
	$_GET[$key.'-appointment-id']       = $appointment->w_id;
	$_GET[$key.'-fullname']             = $appointment->employee->fullname;
	$fullname_words                     = explode(' ', $_GET[$key.'-fullname']);
	$_GET[$key.'-login']                = stfcardid2login($appointment->w_id);
	$_GET[$key.'-name']                 = mb_substr($fullname_words[1], 0, 1).'. '.mb_substr($fullname_words[2], 0, 1).'. '.$fullname_words[0];
	$_GET[$key.'-appointment']          = $appointments_full;
	$_GET[$key.'-appointment-wosubdiv'] = $appointments_wosubdiv;
redmine authored
149 150
	$_GET[$key.'-appointment-short']    = $appointment_short_full;
	$_GET[$key.'-appointment-short-wosubdiv'] = $appointment_short;
redmine authored
151 152
	$_GET[$key.'-subdivs']              = $signer_subdivs;
	$_GET[$key.'-subdivs-full']         = $signer_subdivs_full;
redmine authored
153
	//print_r($appointment);
redmine authored
154 155 156
}


redmine authored
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
function appointment_voip2cps($appointment_voip) {
	//if (!empty($_COOKIE['debug'])) { print_r($appointment_voip);die(); }

	$subscriber = $appointment_voip['Subscriber'];
	$unit       = $appointment_voip['Unit'];

	@$employee->fullname  = $subscriber['Lastname'].' '.$subscriber['Firstname'].' '.$subscriber['Patronymic'];

	@$subdivision->s_code    = $unit['CodeStr'];
	@$subdivision->shortname = $unit['Shortname'];
	@$subdivision->name      = $unit['Fullname'];
	

	@$appointment->w_id        = $appointment_voip['StfCardId'];
	@$appointment->employee    = $employee;
	@$appointment->subdivision = $subdivision;

	//if (!empty($_COOKIE['debug'])) { print_r($appointment);die(); }

	return $appointment;
}

redmine authored
179
$_GET = array_merge ($_GET, $_POST);
redmine authored
180
header( "Content-Type: text/plain" );
redmine authored
181
//print_r ($_GET); die();
redmine authored
182 183
//print_r($_GET);

redmine authored
184
if (isset($_GET['signer2user']) && empty($_GET['user-appointment-id'])) {
redmine authored
185 186 187
	$_GET['user-appointment-id'] = $_GET['signer-appointment-id'];
}

redmine authored
188 189
$me = NULL;

redmine authored
190
$inflect = new Inflect();
redmine authored
191
$redmine_admin = new Redmine\Client('http://redmine.ut.mephi.ru', REDMINE_LOGIN, REDMINE_PASSWORD);
redmine authored
192
//$redmine_admin = new Redmine\Client('https://tasks.mephi.ru', REDMINE_LOGIN, REDMINE_PASSWORD);
redmine authored
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219

if (isset($_GET['signer-serialized'])) {
	$user_serialized = base64_decode($_GET['signer-serialized']);
	$hash		 = $_GET['signer-signature'];
	$date		 = $_GET['signature-date'];

	$good_dates = array(date('Ymd', strtotime('-1 day')), date('Ymd'), date('Ymd', strtotime('+1 day')));

	if (!in_array($date, $good_dates)) {
		die('Bad date');
	}

	$_GET['current-date'] = substr($date, 6, 2).".".substr($date, 4, 2).".".substr($date, 0, 4);

	$good_signature = 0;
	foreach ($SIGNKEYS as $key) {
		if (sha1($user_serialized.$key.$date) === $hash) {
			$good_signature = 1;
			break;
		}
	}
	if ($good_signature == 0)
		die('Bad signature');

	$user            = unserialize($user_serialized);
	$user_redmine    = NULL;
	$username_drupal = $user->login;
redmine authored
220 221 222 223 224 225
	$username_real   = $username_drupal;

	if (in_array($username_real, $ADMINS)) {
		if (!empty($_GET['force-login'])) {
			$username_drupal = $_GET['force-login'];
			 $user		 = json_decode(file_get_contents("https://ut.mephi.ru/getldapentry.php?username=".     urlencode($username_drupal) )); 
redmine authored
226
			@$user->employee = json_decode(file_get_contents("https://cps.mephi.ru/?cmd=getemployeeinfo&usevoip=true&username=".urlencode($username_drupal) )); 
redmine authored
227 228
			@$user->oauth	 = $user_oauth;
			@$user->login	 = $login;
redmine authored
229
			//print_r($user);
redmine authored
230
			$_GET['signer-appointment-id'] = empty($_GET['force-appointment-id']) ? $user->employee->WORKPOSITIONS[0]->w_id : $_GET['force-appointment-id'];
redmine authored
231 232
		}
	}
redmine authored
233 234 235 236 237 238 239 240 241 242 243 244 245 246

	//print_r($user);

	$employee = $user->employee;

	$appointment = null;

	foreach ($employee->WORKPOSITIONS as $_appointment) {
		if ($_appointment->w_id == $_GET['signer-appointment-id']) {
			$appointment = $_appointment;
			break;
		}
	}

redmine authored
247
	/*if (is_null($appointment)) {
redmine authored
248
		die('Wrong appointment ID ('.$_GET['signer-appointment-id'].')');
redmine authored
249
	}*/
redmine authored
250

redmine authored
251 252
	@$appointment->employee = $user->employee;
	considerAppointment('signer', $appointment);
redmine authored
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

	foreach ($redmine_admin->api('user')->all(array('name' => $username_drupal))['users'] as &$_user) {
		$_user['login'] = strtolower($_user['login']);
		if ($_user['login'] == $username_drupal) {
			$user_redmine = $redmine_admin->api('user')->show($_user['id']);
			break;
		}
	}

	if (is_null($user_redmine))
		die('Cannot find user "'.$username_drupal.'" in Redmine');


	$api_key = $user_redmine['user']['api_key'];

//	file_put_contents("/tmp/user", print_r($user_redmine)); die();
redmine authored
269
	$redmine = new Redmine\Client('http://redmine.ut.mephi.ru', $api_key);
redmine authored
270 271 272 273 274 275 276

	$me = $redmine->api('user')->getCurrentUser()['user'];
} else {
	die('Not authed');
	$redmine = &$redmine_admin;
}

redmine authored
277 278 279 280 281 282 283 284 285 286
if (isset($_GET['subdiv-code'])) {
	$subdiv_info = @json_decode(file_get_contents("http://cps.mephi.ru/?cmd=getsubdivinfo&s_code=".urlencode($_GET['subdiv-code'])), 1);

	foreach ($subdiv_info['result']['s0'] as $k => $v) {
		$_GET['subdiv-'.$k] = $v;
	}

//	print_r($_GET);die();
}

redmine authored
287 288
//if (!empty($_COOKIE['debug'])) { print_r($_GET);die(); }

redmine authored
289 290 291 292
foreach (array('contact', 'user', 'recipient') as $key) {
	if (empty($_GET[$key.'-appointment-id']))
		continue;

redmine authored
293 294 295 296
	if ($key == 'user' && !empty($_GET['user-fullname'])) {
		continue;
	}

redmine authored
297 298
	$w_id = $_GET[$key.'-appointment-id'];

redmine authored
299 300 301 302 303
	$appointment = null;

	$url = "https://cps.mephi.ru/?cmd=getworkpositioninfo&usevoip=true&w_id=".urlencode($w_id);
	error_log($w_id.": ".$url );
	$appointment = json_decode(file_get_contents( $url ));
redmine authored
304

redmine authored
305 306 307 308
	/*if (empty($appointment)) {
		$url = "https://voip.mephi.ru/appointments/".urlencode($w_id).".json?renderFilter=appointment_selected";
		error_log($w_id.": ".$url );
		$appointment_voip = json_decode(file_get_contents( $url ), 1)['appointment_selected'];
redmine authored
309
		$appointment = appointment_voip2cps($appointment_voip);
redmine authored
310 311
	}*/

redmine authored
312
	//if ($key == "user") { if (!empty($_COOKIE['debug'])) { print_r($_GET);var_dump($w_id);print_r($appointment);die(); } }
redmine authored
313 314 315 316

	considerAppointment($key, $appointment);
}

redmine authored
317
//if (!empty($_COOKIE['debug'])) { print_r($redmine);print_r($_GET);die(); }
redmine authored
318

redmine authored
319
$dont_inflect_patterns = array(
redmine authored
320 321 322 323 324 325
	'/^нач\./',
	'/^зам\./',
	'/^заф\./',
	'/^нач\./',
	'/^\./',
	'/^спец\./',
redmine authored
326 327 328
);

$inflect_cut_patterns = array(
redmine authored
329
	//'/^(.*)[иы]й[ ]/',	// Commented due to task: https://tasks.mephi.ru/issues/49157
redmine authored
330
	'/^\[\d+\] /',
redmine authored
331 332
);

redmine authored
333 334 335 336
$inflect_appointment_abj_patterns = array(
	'/^(.*)[иы]й[ ]/',	// https://tasks.mephi.ru/issues/49157
);

redmine authored
337 338 339 340
$inflect_ignore_ending_patterns = array(
	'[ ].*',
);

redmine authored
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
function _tempdir_cleanup($dir) {
#	system('rm -rf "'.$dir.'"');
}

function tempdir($dir=FALSE, $prefix='php') {
	$tempfile = tempnam(sys_get_temp_dir(),'');

	if (file_exists($tempfile)) 
		unlink($tempfile);

	mkdir($tempfile);
	if (is_dir($tempfile)) {
		register_shutdown_function("_tempdir_cleanup", $tempfile);
		return $tempfile;
	}

	return FALSE;
}

function body_parse($body) {
	$_GET_withbraces = array();

	foreach ($_GET as $key => $value)
		$_GET_withbraces['[{'.$key.'}]'] = $value;

	switch ($_GET['file']) {
		case 'request/vpn':
			if (isset($_GET['vlan']))
				$_GET_withbraces['[{additional-access}]'] = 'Также прошу предоставить доступ к VLAN '. $_GET['vlan']. ' через данную учётную запись.';
			if (!isset($_GET_withbraces['[{is-additional-login}]']));
				$_GET_withbraces['[{is-additional-login}]'] = '';
			break;
	}

	$body = str_replace(array_keys($_GET_withbraces), array_values($_GET_withbraces), $body);

	return $body;
}

redmine authored
380 381 382 383 384
function error($str) {
	die($str);
	header('Location: '.$_GET['callback_url'].'?errmsg='.urlencode($str));
	error_log($str);
	exit(0);
redmine authored
385 386
}

redmine authored
387 388
function latexSpecialChars( $string ) {
	$string = str_replace("\\textbackslash", "\\", $string );
redmine authored
389
	$string = str_replace("\\", "\\textbackslash ", $string );
redmine authored
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405

	$map = array( 
		"#"=>"\\#",
		"$"=>"\\$",
		"%"=>"\\%",
		"&"=>"\\&",
		"~"=>"\\~{}",
		"_"=>"\\_",
		"^"=>"\\^{}",
		"{"=>"\\{",
		"}"=>"\\}",
	
	);
	return preg_replace( "/([\^\%~#\$%&_\{\}])/e", "\$map['$1']", $string );
}

redmine authored
406

redmine authored
407 408 409 410 411 412 413 414 415 416 417 418
$test = "Test characters: # $ % & ~ _ ^ \ { }.";

function latexSpecialChars1( $string )
{
    $map = array( 
            "#"=>"\\#",
            "$"=>"\\$",
            "%"=>"\\%",
            "&"=>"\\&",
            "~"=>"\\~{}",
            "_"=>"\\_",
            "^"=>"\\^{}",
redmine authored
419
            "\\"=>"\\textbackslash ",
redmine authored
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
            "{"=>"\\{",
            "}"=>"\\}",
    );
    return preg_replace( "/([\^\%~\\\\#\$%&_\{\}])/e", "\$map['$1']", $string );
}





function redmine_login2id ($login) {
	error_log("redmine_login2id($login)");
	static $login2id = array();

	if (empty($login2id)) {
redmine authored
435
		$lines = split("\n", file_get_contents('/opt/redmine_users.csv'));
redmine authored
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451

		foreach ($lines as &$line) {
			$words = split("\t", $line);
			$login2id[strtolower($words[1])] = $words[0];
		}
	}

	error_log('R: '.$login2id[strtolower($login)]);
	return $login2id[strtolower($login)];
}

function redmine_proj_identifier2id ($ident) {
	error_log("redmine_proj_identifier($ident)");
	static $ident2id = array();

	if (empty($ident2id)) {
redmine authored
452
		$lines = split("\n", file_get_contents('/opt/redmine_projects.csv'));
redmine authored
453 454 455 456 457 458 459 460 461 462 463

		foreach ($lines as &$line) {
			$words = split("\t", $line);
			$ident2id[strtolower($words[1])] = $words[0];
		}
	}

	error_log ('RI:'.$ident2id[strtolower($ident)]);
	

	return $ident2id[strtolower($ident)];
redmine authored
464
}
redmine authored
465 466 467 468 469


function my_mb_ucfirst($str, $e='utf-8') {
	$fc = mb_strtoupper(mb_substr($str, 0, 1, $e), $e);
	return $fc.mb_substr($str, 1, mb_strlen($str, $e), $e);
redmine authored
470
}
redmine authored
471

redmine authored
472
//This cycle for situation when we could not receive enought info from node_common
redmine authored
473 474
// TODO: remove this block, it's obsolete
foreach (array('signer', 'contact', 'user', 'recipient') as $key) {
redmine authored
475 476 477
	if (!empty($_GET[$key.'-e_id'])) {
		$e_id = $_GET[$key.'-e_id'];

redmine authored
478
		$employees = json_decode(file_get_contents("https://cps.mephi.ru/?cmd=getemployeeinfo&e_id=".    urlencode($e_id)  ));
redmine authored
479 480 481
		$employee  = ((array)$employees);
		$employee  = reset($employee);
	} else
redmine authored
482
	/*if (!empty($_GET[$key.'-login'])) {
redmine authored
483
		$login     = $_GET[$key.'-login'];
redmine authored
484
		$employees = json_decode(file_get_contents("https://cps.mephi.ru/?cmd=getemployeeinfo&username=".urlencode($login) ));
redmine authored
485 486
		$employee  = ((array)$employees);
		$employee  = reset($employee);
redmine authored
487
	} else*/
redmine authored
488 489
		continue;

redmine authored
490 491 492 493
	$appointments         = array();
	$subdivs              = array();
	$subdivs_full         = array();
	$appointments_wosubdiv = array();
redmine authored
494
	foreach($employee->WORKPOSITIONS as $workposition) {
redmine authored
495 496 497 498
		$appointments[]	= preg_replace('/ [0-9]*.[0-9]$/', '', $workposition->name).' '.mb_strtoupper($workposition->subdivision->shortname);
		$subdivs[]	= $workposition->subdivision->shortname;
		$subdivs_full[]	= $workposition->subdivision->name;
		$appointments_wosubdiv[] = preg_replace('/ [0-9]*.[0-9]$/', '', $workposition->name);
redmine authored
499
	}
redmine authored
500

redmine authored
501 502 503
	$fullname    = $employee->fullname;
	$name        = mb_substr($employee->firstname, 0, 1).'.'.mb_substr($employee->middlename, 0, 1).'. '. $employee->lastname;
	$appointment = join(', ',$appointments);
redmine authored
504 505 506 507 508 509 510 511 512
 
	$_GET[$key.'-fullname']			= $fullname;
	$_GET[$key.'-name']			= $name;
	$_GET[$key.'-appointment']		= $appointment;
	$_GET[$key.'-subdivs']			= join(', ',$subdivs);
	$_GET[$key.'-subdivs-full']		= join('; ',$subdivs_full);
	$_GET[$key.'-appointment-wosubdiv']	= join(', ',$appointments_wosubdiv);
	//$appointments_wosubdiv      = split(', ', $_GET[$key.'-appointment-wosubdiv']);
}
redmine authored
513

redmine authored
514
//DE base64 subdivs
redmine authored
515
foreach (array('signer', 'contact', 'user', 'recipient') as $key) {
redmine authored
516 517
	if (!empty($_GET[$key.'-e_id']))
		continue;
redmine authored
518

redmine authored
519
	if (isset($_GET[$key.'-subdivs'])){
redmine authored
520
		$_GET[$key.'-subdivs']      = $_GET[$key.'-subdivs'];
redmine authored
521 522
	}
	if (isset($_GET[$key.'-subdivs-full'])){
redmine authored
523
		$_GET[$key.'-subdivs-full'] = $_GET[$key.'-subdivs-full'];
redmine authored
524
	}
redmine authored
525
}
redmine authored
526

redmine authored
527
foreach (array('fullname' => 40, 'phonenumber' => 20, 'email' => 30, 'appointment' => 40, 'pgp-id' => 12) as $key => $space) {
redmine authored
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
	if (empty($_GET['signer-'.$key])) {
		switch ($key) {
			case 'phonenumber':
				if (isset($_GET['signer-appointment-id']) && !empty($_GET['signer-login'])) {
					$voip_result = json_decode(file_get_contents('http://new.voip.mephi.ru/subscribers.json?login='.$_GET['signer-login']), 1);
					$_GET['signer-phonenumber'] = @$voip_result['appointments'][0]['EffectiveExtension'];
				}
				break;
			case 'email':
				if (isset($_GET['signer-appointment-id']) && !empty($_GET['signer-login']))
					$_GET['signer-email'] = strtolower($_GET['signer-login']).'@mephi.ru';
				break;
		}
		if (empty($_GET['signer-'.$key]))
			$_GET['signer-'.$key] = str_pad('', $space, '_');
	}
redmine authored
544

redmine authored
545 546 547 548
	if (empty($_GET['user-'.$key]))
		$_GET['user-'.$key]   = str_pad('', $space, '_');

	if (empty($_GET['contact-'.$key]))
redmine authored
549
		$_GET['contact-'.$key] = $_GET['user-'.$key];
redmine authored
550
}
redmine authored
551

redmine authored
552
foreach (array('signer', 'contact', 'user', 'recipient') as $key) {
redmine authored
553 554 555 556 557 558 559
	if (empty($_GET[$key.'-name']))
		$_GET[$key.'-name'] = $_GET[$key.'-fullname'];

	foreach (array('of', 'to') as $case => $key_prefix) {
		if (empty($_GET[$key_prefix.'-'.$key.'-fullname']))
			$_GET[$key_prefix.'-'.$key.'-fullname'] = $inflect->getInflectName($_GET[$key.'-fullname'], $case);

redmine authored
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
		if (empty($_GET[$key_prefix.'-'.$key.'-name'])) {
			$words = explode(' ', $_GET[$key.'-name']);
			$fwords = explode(' ', $_GET[$key_prefix.'-'.$key.'-fullname']);
			$_GET[$key_prefix.'-'.$key.'-name'] = $words[0].' '.$words[1].' '.$fwords[0];
		}

		if (empty($_GET[$key_prefix.'-'.$key.'-subdivs-full']) && !empty($_GET[$key.'-subdivs-full'])) {
			$subdivs_full = split('; ', $_GET[$key.'-subdivs-full']);

			foreach($subdivs_full as &$subdiv_full) {
				$words = split(' ', $subdiv_full);
				$words[0] = $inflect->getInflectNoun($words[0], $case);
				$subdiv_full = join(' ', $words);
			}

			$_GET[$key_prefix.'-'.$key.'-subdivs-full'] = $subdivs_full;
redmine authored
576 577
		}

redmine authored
578 579 580 581 582 583 584
		if (empty($_GET[$key_prefix.'-'.$key.'-appointment'])) {
			foreach ($dont_inflect_patterns as &$dont_inflect_pattern) {
				if (preg_match($dont_inflect_pattern, $_GET[$key.'-appointment'])) {
					$_GET[$key_prefix.'-'.$key.'-appointment'] = $_GET[$key.'-appointment'];
					continue 2;
				}
			}
redmine authored
585
		}
redmine authored
586 587

// working with appointments
redmine authored
588 589 590 591
		foreach (array('', '-wosubdiv') as $postfix) {
			$appointments = split(', ', $_GET[$key.'-appointment'.$postfix]);
			foreach ($appointments as &$appointment) {
				$matches        = NULL;
redmine authored
592
				$prefix         = '';
redmine authored
593 594
				$ignored_ending = '';

redmine authored
595 596 597 598 599 600 601 602 603 604
				foreach($inflect_appointment_abj_patterns as $inflect_appointment_abj_pattern) {
					if (preg_match($inflect_appointment_abj_pattern, $appointment, $matches, PREG_OFFSET_CAPTURE)) {
						foreach ($matches as &$match) {
							$prefix .= $inflect->getInflectAbjective($match[0], $case);
							$appointment = mb_substr($appointment, mb_strlen($match[0]));
							break;
						}
					}
				}

redmine authored
605 606 607 608 609 610 611 612 613
				$appointment  = preg_replace($inflect_cut_patterns, '', $appointment);
				error_log('Appointment'.$postfix.': '.$appointment);

				foreach($inflect_ignore_ending_patterns as $inflect_ignore_ending_pattern) {
					if (preg_match('/'.$inflect_ignore_ending_pattern.'$/u', $appointment, $matches, PREG_OFFSET_CAPTURE)) {
						foreach ($matches as &$match) {
							$ignored_ending .= $match[0];
							$appointment = mb_substr($appointment, 0, -mb_strlen($match[0]));
						}
redmine authored
614 615 616
					}
				}

redmine authored
617
				$appointment  = $inflect->getInflectNoun($appointment, $case);
redmine authored
618
				$appointment = $prefix . $appointment . $ignored_ending;
redmine authored
619 620
				$_GET[$key_prefix.'-'.$key.'-appointment'.$postfix] = $appointment;
			}
redmine authored
621

redmine authored
622 623
			$_GET[$key_prefix.'-'.$key.'-appointment'.$postfix] = join(', ', $appointments);
		}
redmine authored
624 625 626
	}
}

redmine authored
627 628 629 630 631
/*if (!empty($_COOKIE['debug'])) {
	print 'TEST: ';
	print_r($_GET);die();
}*/

redmine authored
632
foreach (array('signer', 'contact', 'user', 'recipient') as $key) {
redmine authored
633 634 635 636 637 638 639 640 641 642 643 644 645
	foreach (array('', 'of-', 'to-') as $key_prefix) {
		$appointment_w_fullsubdiv = array();

		$appointments_wosubdiv    = is_array($_GET[$key_prefix.$key.'-appointment-wosubdiv']) ? $_GET[$key_prefix.$key.'-appointment-wosubdiv'] : split(', ', $_GET[$key_prefix.$key.'-appointment-wosubdiv']);

		foreach ($appointments_wosubdiv as $id => &$appointment_wosubdiv) {

			$appointment_wosubdiv_words = split(' ', $appointment_wosubdiv);
			$subdivs_full_words         = split(' ', $_GET['of-'.$key.'-subdivs-full'][$id]);
			if ($appointment_wosubdiv_words[count($appointment_wosubdiv_words)-1] === $subdivs_full_words[0])
				unset($appointment_wosubdiv_words[count($appointment_wosubdiv_words)-1]);

			$appointment_wosubdiv_dedup = join(' ', $appointment_wosubdiv_words);
redmine authored
646

redmine authored
647 648 649 650 651 652 653 654 655 656 657 658 659
			if ($_GET['of-'.$key.'-subdivs-full'][$id] == 'ректората') {
				$appointment_w_fullsubdiv_item = $appointment_wosubdiv_dedup;
			} else {
				$appointment_w_fullsubdiv_item = $appointment_wosubdiv_dedup.' '.$_GET['of-'.$key.'-subdivs-full'][$id];
			}

			if ($appointment_w_fullsubdiv_item == " ") {
				$appointment_w_fullsubdiv_item = str_pad('', 60, '_');
			}
			$appointment_w_fullsubdiv[] = $appointment_w_fullsubdiv_item;

		}

redmine authored
660 661
		$_GET[$key_prefix.$key.'-appointment-w-fullsubdiv']     = $appointment_w_fullsubdiv;
		$_GET[$key_prefix.$key.'-appointment-w-fullsubdiv-cap'] = array(my_mb_ucfirst($appointment_w_fullsubdiv[0]));
redmine authored
662 663 664 665

	}
}
//print_r($_GET); die();
redmine authored
666

redmine authored
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
foreach (array('work-date-end' => 'Срок окончания работ') as $key => $descr) {
	$_GET[$key.'-descr'] = $descr.': '. 
		( 
			isset($_GET['no-'.$key]) ?
				'Бессрочно'      :
				(isset ($_GET['work-date-end']) ?
					$_GET['work-date-end']  :
					'__.__.____'
				)
		).'.';
}
foreach (array('ram-amount' => 'GB', 'hdd-amount' => 'GB', 'ic-bandwidth' => 'Gbps') as $key => $descr) {
	$_GET[$key.'-descr'] =  empty($_GET[$key]) ? '' : $_GET[$key].' '.$descr;
}

foreach ($_GET as $key => &$value) {
	if (substr($key, -12) == "-other-value")
		if ($_GET[substr($key, 0, strlen($key)-12)] == "other")
			$_GET[substr($key, 0, strlen($key)-12)] = $value;
redmine authored
686 687
}

redmine authored
688
foreach (array('audio', 'proektor', 'light', 'videocheck', 'confcheck', 'webtrans', 'telebridge', 'otherconf', 'record1', 'record2', 'record3') as $key ) {
redmine authored
689 690 691 692 693 694 695 696
	if  (isset($_GET[$key]))
		$_GET[$key] = 'Да';

//govnocode 2.0
	else{
		$_GET[$key] = 'Нет';
		
	}
redmine authored
697 698 699
}


redmine authored
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
switch($_GET['vacation-type']) {
	case 'main':
		$_GET['vacation-type'] = 'ежегодный основной оплачиваемый отпуск';
		$_GET['of-vacation']   = 'ежегодного основного оплачиваемого отпуска';
		break;
	case 'educational':
		$_GET['vacation-type'] = 'учебный отпуск';
		$_GET['of-vacation']   = 'учебного отпуска';
		break;
	case 'free':
		$_GET['vacation-type'] = 'отпуск без сохранения заработной платы';
		$_GET['of-vacation']   = 'отпуска без сохранения заработной платы';
		break;
	case 'parental':
		$_GET['vacation-type'] = 'отпуск по уходу за ребёнком до достижения им возраста трёх лет';
		$_GET['of-vacation']   = 'отпуска по уходу за ребёнком до достижения им возраста трёх лет';
		break;
}

redmine authored
719 720
$already_created = array();

redmine authored
721
$_GET_orig = $_GET;
redmine authored
722

redmine authored
723
$custom_fields = NULL;
redmine authored
724

redmine authored
725 726
$custom_fields_keys = array();

redmine authored
727 728
$issue_id = NULL;

redmine authored
729 730 731
$files = split(',', $_GET['file']);

$pdfs = array();
redmine authored
732 733
//if (!empty($_COOKIE['debug'])) { print_r($files);die(); }
$replacement_is_already_done = false;
redmine authored
734
foreach ($files as $file) {
redmine authored
735 736
	$split_appointments = false;

redmine authored
737
	$file_eff = $file;
redmine authored
738
	switch ($file) {
redmine authored
739 740 741 742 743 744
		case 'request/domain-name':
			$project_id   = 12886;
			$memo_subject = 'Запрос на регистрацию доменного имени';
			$file_eff = $file;//.' '.$_GET['target-type'];

			break;
redmine authored
745
		case 'request/vpn':
redmine authored
746
			$project_id   = 84;
redmine authored
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
			$memo_subject = 'Запрос на учётную запись к vpn.mephi.ru';
			break;
		case 'request/vpn-private-net':
			$project_id   = 1;
			$memo_subject = 'Запрос на доступ к VLAN через vpn.mephi.ru';
			break;
		case 'request/nix-hosting':
			$project_id   = 102;
			$memo_subject = 'Заявка на предоставление nix-хостинга';
			$custom_fields_keys = array (4 => 'signer-subdivs', 85=> 'domainnames');
			break;
		case 'request/win-hosting':
			$project_id   = 1;
			$memo_subject = 'Заявка на предоставление win-хостинга';
			break;
		case 'request/voip-softphone':
			$project_id   = 18;
			$memo_subject = 'Заявка на создание учётной записи к softphone';
			break;
		case 'request/voip3':
			$project_id   = 124;
			$memo_subject = 'Заявка на доступ к систему «Биллинг» IP-телефонии';
			break;
		case 'request/cps':
			$project_id   = 109;
	//		$project_id   = 1;
			$memo_subject = 'Заявка на доступ к системе учёта рабочего времени';
			break;
		case 'request/hpc':
	//		$project_id   = NULL; //38;
			$project_id   = 38;
			$memo_subject = 'Запрос на учётную запись к HPC-кластерам';
redmine authored
779

redmine authored
780 781 782 783
			$custom_fields_keys = array(2 => 'hdd-amount', 3 => 'cpu-amount', 4 => 'subdivision', 5 => 'scientific-director', 6 => 'ram-amount', 7 => 'preffered-login', 8 => 'ic-bandwidth', 16 => 'contact-email');
			break;
		case 'request/vacation':
			$project_id   = 118;
redmine authored
784
	//			$project_id   = 1;
redmine authored
785 786 787 788 789 790 791 792 793 794 795
			$memo_subject = 'Заявление на отпуск';


			$time_from = strtotime($_GET['days-from']);
			$time_to   = strtotime($_GET['days-to']);

			$time_diff = $time_to - $time_from;

			$days_diff = floor(($time_diff / (3600*24)) + 0.5);

			$_GET['days-count'] = ($days_diff + 1);
redmine authored
796

redmine authored
797 798
			$split_appointments = true;

redmine authored
799 800
			break;
		case 'request/temporary-acting':
redmine authored
801
		//	print_r($_GET); die();
redmine authored
802 803
			if (!isset($_GET['user-e_id']))
				continue 2;
redmine authored
804

redmine authored
805
			if (substr($_GET['of-user-fullname'], 0, 2) == '\_')
redmine authored
806 807 808
					$_GET['of-user-fullname'] = '\\\\'."\n".$_GET['of-user-fullname'];

			$split_appointments = true;
redmine authored
809 810 811 812 813 814 815 816 817
			break;
		case 'request/voip-transfer-equipment':
			$project_id   = 1;//18;
			$memo_subject = 'Заявка на передачу телефонных аппаратов в ОСП';
			break;
		case 'request/video':
			$project_id = 1;
			$memo_subject = 'Заявка на сопровождение мероприятия видеосъемкой, проведение видеоконференции и веб-трансляции';
			break;
redmine authored
818 819 820 821
		case 'request/zal':
			$project_id = 16910;
			$memo_subject = 'Заявка на проведение мероприятия в актовом зале';
			break;	//	die ('working on that');
redmine authored
822
		case 'request/iis':
redmine authored
823 824
		case 'request/php':
			$project_id = 12871;
redmine authored
825 826 827 828 829 830 831 832 833

			switch ($file) {
				case 'request/php':
					$memo_subject = 'Заявка на предоставление PHP хостинга';
					break;
				case 'request/iis':
					$memo_subject = 'Заявка на предоставление IIS хостинга';
					break;
			}
redmine authored
834 835 836


			if (isset($_GET['resourse-sshrequired'])) {
redmine authored
837
				$project_id = 102;
redmine authored
838 839

				$custom_fields_keys = array (4 => 'signer-subdivs', 85=> 'domainnames');
redmine authored
840
				$_GET['domainnames']=$_GET['resourse-domain'];
redmine authored
841 842
				//print_r($_GET['resourse-domain']);die('.uck');
				//$_GET['signer-subdivs']=NULL;
redmine authored
843 844
			}

redmine authored
845
			break;
redmine authored
846 847 848 849
		case 'request/customform':
			$project_id = 15905;
			$memo_subject = 'Заявка на доступ к ИТ-услуге «Конструктор веб-форм» НИЯУ МИФИ';
			break;
redmine authored
850 851 852 853 854 855
		case 'request/voip-unit-operator':
			$project_id = 15967;
			$memo_subject = 'Уведомление о назначении оператора справочных данных по подразделению';
			$_GET_orig['user-login'] = strtolower($_GET_orig['user-login']);
			$custom_fields_keys = array ( 7 => 'user-login', 4 => 'subdiv-code' ); 
			break;
redmine authored
856 857 858 859 860 861 862 863 864 865
		case 'request/itsupport':
			$project_id = 121;
			$memo_subject = 'Заявка в службу технической поддержки';
			$custom_fields_keys = array ( 14 => 'contact-phonenumber', 13 => 'contact-place', 4 => 'subdivision'); 
			break;
		case 'request/lanmodern':
			$project_id = 31;
			$memo_subject = 'Заявка на модернизацию ЛВС';
			break;
		case 'request/custom':
redmine authored
866 867 868
			if (!empty($_COOKIE['debug'])) {
				//print_r($_GET);die();
			}
redmine authored
869 870 871 872 873 874 875
			if ($_GET['user-appointment-id'] != $_GET['signer-appointment-id']) {
				$project_id = 15971;
				$_GET['recipient-redmine-id'] = redmine_login2id($_GET['recipient-login']);
				$custom_fields_keys = array (95 => 'recipient-redmine-id');
			} else {
				$project_id = redmine_proj_identifier2id ($_GET['recipient-login']);
			}
redmine authored
876 877 878 879 880
			$memo_subject = 'Служебная записка';
			$me['id'] = $user_redmine['user']['id'];
			$replacement_is_already_done = true;

			break;
redmine authored
881 882 883 884 885 886 887

		case 'request/forhire':
			$project_id = 15927;
			$memo_subject = 'Заявка на подбор персонала';
			
			break;

redmine authored
888
		default:
redmine authored
889
			die('unknown memo-type - '.$file);
redmine authored
890
	}
redmine authored
891
        
redmine authored
892 893
	if (!is_null($me)) {
	//	$membership = $redmine_admin->api('user')->show($me['id'], array('include' => array('memberships',)));
redmine authored
894
		$current_membership = $redmine_admin->api('membership')->all($project_id, array('limit' => '1000')); 
redmine authored
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922



		//History of issue: If we have one user with role id:20, we can't create a custumer role. 
		//We must update roles for this user, for update we must know inner structure of memberships

		//for debug
	 //	print_r ($current_membership['memberships']);


//		echo "ME:".$me['id']."\n";

		foreach ($current_membership['memberships'] as $global_key => $member){

		//	echo "MEMBER KEY: $global_key\n";
		//	print_r ($member); die();

		//	echo $member['user']['id']."\n";
			
			if ($member['user']['id'] == $me['id']){
				$cur_roles=array();
				$membership_id = $current_membership['memberships'][$global_key]['id'];
				foreach($current_membership['memberships'][$global_key]['roles'] as $role) {
					$cur_roles[] = $role['id'];
				}
				//print_r($current_membership['memberships'][$global_key]);print_r($cur_roles);die();
				$result = $redmine_admin->api('membership')->update($membership_id, array ('role_ids' => array_merge($cur_roles, array(ROLE_CUSTOMER))));
			//	echo "RESULT $result \n @ $membership_id \n"; die();
redmine authored
923
			}
redmine authored
924 925 926 927
			
			else {
				$result = $redmine_admin->api('membership')->create($project_id, array('user_id' => $me['id'], 'role_ids' => array(ROLE_CUSTOMER)));

redmine authored
928
			}
redmine authored
929 930 931 932 933 934


		}
	//TODO: PUT ALL ROLES	
	//	echo $result;
	//	die();
redmine authored
935 936

	}
redmine authored
937

redmine authored
938
	//print_r($_GET_orig);
redmine authored
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
//	error_log(print_r($_GET_orig, 1));

	$signer_appointment_count = 1;
	$user_appointment_count = 1;
	foreach ($_GET_orig as $k => $v) {
		if ($split_appointments) {
			if ($split_appointments && (strstr($k, "signer-") || strstr($k, "user-")) && (strstr($k, "appointment") || strstr($k, "subdiv"))) {
					error_log($k.' => '.print_r($v, 1));
					if (is_array($v)) {
						$_GET_array[$k] = $v;
					} else {
						$_GET_array[$k] = split(',', $v);
					}
					if (strstr($k, "signer-")) {
						$signer_appointment_count = count($_GET_array[$k]);
					} else
					if (strstr($k, "user-")) {
						$user_appointment_count   = count($_GET_array[$k]);
					}
					continue;
			}
		}
		if (is_array($v)) {
			$v = join(', ', $v);
		}
		$_GET_array[$k] = array($v, $v, $v, $v, $v, $v, $v, $v, $v, $v, $v, $v, $v, $v, $v, $v, $v);
	}
redmine authored
966

redmine authored
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
	if ($split_appointments) {
		$_GET_array_new = array();
		$i = 0;
		while ($i < $signer_appointment_count) {
			$j = 0;
			while ($j < $user_appointment_count) {
				$appointment_i = $i + $j * $signer_appointment_count;
				
				foreach ($_GET_array as $k => $v) {
					if (strstr($k, "appointment") || strstr($k, "subdiv")) {
						if (strstr($k, "signer-")) {
							$_GET_array_new[$k][$appointment_i] = $v[$i];
						} else
						if (strstr($k, "user-")) {
							$_GET_array_new[$k][$appointment_i] = $v[$j];
						}
					} else {
						$_GET_array_new[$k] = $v;
					}
				}
				$j++;
			}
			$i++;
		}
		$_GET_array = $_GET_array_new;
	}
redmine authored
993

redmine authored
994
	$appointment_count = $signer_appointment_count * $user_appointment_count;
redmine authored
995

redmine authored
996 997 998 999 1000
	$appointment_i = 0;
	do {
		foreach ($_GET_array as $k => $v) {
			$_GET[$k] = $v[$appointment_i];
		}
redmine authored
1001

redmine authored
1002 1003 1004
		switch ($file) {
			case 'request/voip3':
			case 'request/cps':
redmine authored
1005
			case 'request/iis':
redmine authored
1006
			case 'request/php':
redmine authored
1007
			case 'request/customform':
redmine authored
1008 1009 1010 1011 1012 1013 1014
				if (empty($_GET['subdiv-code'])) {
					if (!empty($_SERVER['HTTP_REFERER'])) {
						header('Location: '.$_SERVER['HTTP_REFERER'].'?errmsg='.urlencode('Не указан код подразделения'));
						exit(0);
					} else
						die('"subdiv-code" is not set');
				}
redmine authored
1015 1016
				if (isset($_GET['resourse-sshrequired'])) {
					$_GET['resourse-sshrequired'] = 'да';
redmine authored
1017 1018
					$project_id = 102;

redmine authored
1019 1020 1021
				} else {
					$_GET['resourse-sshrequired'] = 'нет';
				}
redmine authored
1022
				$subdivs      = json_decode(file_get_contents('https://cps.mephi.ru/?cmd=getsubdivinfo&s_code='.urlencode($_GET['subdiv-code'])));
redmine authored
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
				$subdiv       = $subdivs->result->s0;
				$_GET['subdiv-name'] = $subdiv->name;
				break;
			case 'request/video':
				if (empty($_GET['subdiv-code'])) {
					if (!empty($_SERVER['HTTP_REFERER'])) {
						header('Location: '.$_SERVER['HTTP_REFERER'].'?errmsg='.urlencode('Не указан код подразделения'));
						exit(0);
					} else
						die('"subdiv-code" is not set');
				}
redmine authored
1034
				$subdivs      = json_decode(file_get_contents('https://cps.mephi.ru/?cmd=getsubdivinfo&s_code='.urlencode($_GET['subdiv-code'])));
redmine authored
1035 1036 1037
				$subdiv       = $subdivs->result->s0;
				$_GET['subdiv-name'] = $subdiv->name;
				break;
redmine authored
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
			case 'request/zal':
				if (empty($_GET['subdiv-code'])) {
					if (!empty($_SERVER['HTTP_REFERER'])) {
						header('Location: '.$_SERVER['HTTP_REFERER'].'?errmsg='.urlencode('Не указан код подразделения'));
						exit(0);
					} else
						die('"subdiv-code" is not set');
				}
				$subdivs      = json_decode(file_get_contents('https://cps.mephi.ru/?cmd=getsubdivinfo&s_code='.urlencode($_GET['subdiv-code'])));
				$subdiv       = $subdivs->result->s0;
				$_GET['subdiv-name'] = $subdiv->name;
				break;
redmine authored
1050 1051
			case 'request/domain-name':
			$_GET['domain-name'] = $_GET['domain-name'].'.mephi.ru';
redmine authored
1052

redmine authored
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
			switch ($_GET['target-type']) {
				case 'ipaddr':
					$_GET['target-type'] = 'IP-адресом';
					$_GET['target-id']   = $_GET['ipaddr'];
					break;
				case 'container-name':
					$_GET['target-type'] = 'контейнером';
					$_GET['target-id']   = '«'.$_GET['container-name'].'»';
					break;
				case 'issue-id':
					$_GET['target-type'] = 'ранее предоставленным хостингом по заявке';
					$_GET['target-id']   = '#'.$_GET['issue-id'];
					break;
			}
redmine authored
1067

redmine authored
1068
				break;
redmine authored
1069

redmine authored
1070
		}
redmine authored
1071

redmine authored
1072 1073
		foreach($custom_fields_keys as $id => $key)
			$custom_fields[] = array('id' => $id, 'value' => empty($_GET[$key]) ? '0' : $_GET[$key]);
redmine authored
1074

redmine authored
1075
		$tempdir = tempdir();
redmine authored
1076

redmine authored
1077 1078
		if ($tempdir === FALSE)
			die('Cannot create temporary directory');
redmine authored
1079 1080


redmine authored
1081
		exec('cp -a /var/www/'.$_SERVER['SERVER_NAME'].'/ut-tex/mephimemo "'.$tempdir.'/"');
redmine authored
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
		chdir($tempdir.'/mephimemo');
		file_put_contents("request.get", print_r($_GET, true));


		if (!$replacement_is_already_done) {
	
			foreach ($_GET as $key => &$value)
				$value = str_replace(array('\\', '_', '#', '&quot;', '&quot', '&', '$'), array('{\textbackslash}', '\_', '\\#', '"', '"', '\&', '\$'), $value);

			$replacement_is_already_done = true;
		}

		file_put_contents("request.get.fixed", print_r($_GET, true));
redmine authored
1095 1096


redmine authored
1097 1098 1099 1100
		#ob_start();
		#print_r($_GET);
		#$_GET_print_r = ob_get_clean();
		$text = '';
redmine authored
1101

redmine authored
1102 1103 1104 1105
		/*
		if (empty($_GET['date-end']))
			$_GET['date-end'] = (date('Y')+1).'-12-31';
		*/
redmine authored
1106

redmine authored
1107 1108 1109
		if (!empty($_GET['category_id'])) {
			$category = $redmine_admin->api('issue_category')->show($_GET['category_id']);
			$_GET['category'] = $category['issue_category']['name'];
redmine authored
1110
		}
redmine authored
1111
                
redmine authored
1112
		$body_template = file_get_contents('template/'.$file_eff.'.tex');
redmine authored
1113
                
redmine authored
1114 1115 1116 1117
		$body          = body_parse($body_template);

		switch ($file) {
			case 'request/vacation':
redmine authored
1118 1119 1120
				if (!empty($_COOKIE['debug'])) {
					//print_r($_GET);die();
				}
redmine authored
1121
				$header = '\mmheaderstatement{В Дирекцию по управлению персоналом НИЯУ МИФИ}{от '.$_GET['of-signer-appointment-w-fullsubdiv'].' '.$_GET{'of-signer-fullname'}.'}';
redmine authored
1122 1123 1124 1125 1126
				$footer = '';
				break;
			case 'request/temporary-acting':
				$header = '\mmheadermemo{\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_}{\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_}';
				$footer = '
redmine authored
1127
\mmfooter{'.my_mb_ucfirst($_GET['signer-appointment-w-fullsubdiv']).'}{'.$_GET{'signer-name'}.'}{}{}
redmine authored
1128
\\
redmine authored
1129
\mmfooter{'.(empty($_GET['user-appointment-w-fullsubdiv'])||$_GET['user-appointment-w-fullsubdiv']==" "?'\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_':my_mb_ucfirst($_GET['user-appointment-w-fullsubdiv'])).'}{'.$_GET{'user-name'}.'}{}{}
redmine authored
1130 1131 1132 1133
';
				break;
			case 'request/voip-transfer-equipment':
				$header = '\mmfullheader{'.$_GET['subdiv-name'].'}{Начальнику управления информатизации}{Романову Н.Н.}';
redmine authored
1134
				$footer = '';
redmine authored
1135 1136 1137
				break;
			case 'request/video';
				$header = '\mmfullheader{Утверждаю}{Начальник управления информатизации}{/Романов Н.Н./}';
redmine authored
1138
				$footer = '';
redmine authored
1139
				break;
redmine authored
1140 1141 1142 1143
			case 'request/zal';
				$header = '\mmheaderzal{Начальник управления информатизации}{/Романов Н.Н./}';
				$footer = '';
				break;
redmine authored
1144 1145 1146 1147
			case 'request/itsupport':
				$header = '\mmheader{Начальнику отдела технической поддержки}{Солодовникову А.В}';
				$footer ='';
				break; 
redmine authored
1148
			case 'request/iis':
redmine authored
1149 1150
			case 'request/php':
				$header = '\mmheader{Начальнику управления информатизации}{Н. Н. Романову}';
redmine authored
1151
				$footer = '';
redmine authored
1152 1153
				break;
			case 'request/custom':
redmine authored
1154
				$header = '\mmheader{'.my_mb_ucfirst($_GET['to-recipient-appointment-w-fullsubdiv-cap']).'}{'.my_mb_ucfirst($_GET['to-recipient-name']).'}';
redmine authored
1155
				$body = latexSpecialChars1(str_replace("\n", "\n\n", $body));
redmine authored
1156 1157
				$footer = '\mmfooter{'.my_mb_ucfirst($_GET['user-appointment']).'}{'.$_GET['user-name'].'}{'.$_GET['current-date'].'}{}';

redmine authored
1158 1159

 
redmine authored
1160
		//		$footer = '\mmfooter{'.my_mb_ucfirst($_GET['signer-appointment']).'}{'.$_GET['current-date'].'}{'.$_GET['signer-name'].'}{}';
redmine authored
1161 1162 1163 1164 1165 1166 1167


				break;
			case 'request/forhire':
				$header = '';
				$footer = '\mmfooter{'.my_mb_ucfirst($_GET['signer-appointment']).'}{'.$_GET{'signer-name'}.'}{'.$_GET['current-date'].'}{}';

redmine authored
1168 1169
				break;

redmine authored
1170

redmine authored
1171
			default:
redmine authored
1172 1173
				$signerAppointment = trim(my_mb_ucfirst($_GET['signer-appointment']));
				
redmine authored
1174
				$header = '\mmheader{Начальнику управления информатизации}{Н. Н. Романову}';
redmine authored
1175
				$footer = '\mmfooter{'.(empty($signerAppointment) ? '(не сотрудник)' : $signerAppointment).'}{'.$_GET{'signer-name'}.'}{'.$_GET['current-date'].'}{}';
redmine authored
1176 1177 1178 1179 1180 1181
		}
		file_put_contents('header.tex',		$header);
		file_put_contents('body.tex',		$body);
		file_put_contents('footer.tex',		$footer);
		file_put_contents('responsible.tex',	'\mmresponsibleskip');

redmine authored
1182
		//print_r($_GET);die();
redmine authored
1183

redmine authored
1184
		if (empty($issue_id)) {
redmine authored
1185 1186
			//error_log('FI:'.$project_id.'|'.@$_GET['force-issue-id'].'('.(empty($_GET['force-issue-id']) ? "true" : "false").')|'.strtolower($username_real).'('.(!in_array(strtolower($username_real), $ADMINS) ? "true" : "false").')|');
			if (!is_null($project_id) && (empty($_GET['force-issue-id']) || !in_array(strtolower($username_real), $ADMINS))) {
redmine authored
1187 1188 1189 1190 1191 1192 1193 1194
				file_put_contents('urlqr.tex',	'');
				exec('make');
				exec('pdftotext memo.pdf');

				$text = file_get_contents('memo.txt');
				unlink('memo.pdf');

				switch($file) {
redmine authored
1195 1196 1197 1198 1199 1200 1201 1202 1203
						case 'request/customform':
							$issue_props = 
								array(
									'assigned_to_id'	=> USERID_KVMARTINOV,
									'project_id'		=> $project_id,
									'subject'		=> $memo_subject,
									'description'		=> $text,
								);
							break;
redmine authored
1204
						case 'request/iis':
redmine authored
1205 1206 1207 1208 1209 1210 1211 1212
						case 'request/php':
							$issue_props = 
								array(
									'assigned_to_id'	=> USERID_KVMARTINOV,
									'project_id'		=> $project_id,
									'subject'		=> $memo_subject,
									'description'		=> $text,
								);
redmine authored
1213 1214 1215 1216
							if ($project_id == 102) {
								$issue_props['assigned_to_id'] = USERID_AMGLADTSIN;
							}
							//if ($project_id == 102) {print_r($issue_props);die();}
redmine authored
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
							break;
						case 'request/nix-hosting':
							$issue_props = 
								array(
									'assigned_to_id'	=> USERID_AMGLADTSIN,
									'project_id'		=> $project_id,
									'subject'		=> $memo_subject,
									'description'		=> $text,
								);
							break;
						case 'request/hpc':
							$issue_props = 
								array(
									'assigned_to_id'	=> USERID_AAANIKEEV,
									'project_id'		=> $project_id,
									'subject'		=> $memo_subject,
									'description'		=> $text,
								);
							break;
						case 'request/itsupport':
							$issue_props =
								array(
									'assigned_to_id'	=> USERID_AVSOLODOVNIKOV,
									'project_id'		=> $project_id,
									'subject'		=> $memo_subject,
									'description'		=> $text,
								);
							break;
						case 'request/lanmodern':
							$issue_props =
								array(
									'assigned_to_id'	=> USERID_VSSKIBA,
									'project_id'		=> $project_id,
									'subject'		=> $memo_subject,
									'description'		=> $text,
								);
							break;

						case 'request/video':
							$issue_props =
								array(
									'assigned_to_id'	=> USERID_OYMAZETOV,
									'project_id'		=> $project_id,
									'subject'		=> $memo_subject,
									'description'		=> $text,
								);
							break;
redmine authored
1264 1265 1266 1267 1268 1269 1270 1271 1272
						case 'request/zal':
							$issue_props =
								array(
									'assigned_to_id'	=> USERID_VANAZAROV,
									'project_id'		=> $project_id,
									'subject'		=> $memo_subject,
									'description'		=> $text,
								);
							break;
redmine authored
1273

redmine authored
1274
						case 'request/custom':
redmine authored
1275
							$issue_props = array();
redmine authored
1276 1277
							if ($_GET['user-appointment-id'] != $_GET['signer-appointment-id']) {
								$assigned_to_id = redmine_login2id($_GET['user-login']);
redmine authored
1278 1279 1280 1281
								$issue_props = 
									array(
										'tracker_id'		=> TRACKERID_NOTE,
									);
redmine authored
1282 1283 1284 1285
							} else {
								$assigned_to_id = redmine_login2id($_GET['recepient-login']);
							}

redmine authored
1286
							$issue_props = 
redmine authored
1287 1288 1289 1290 1291 1292 1293 1294
								array_merge(
									$issue_props,
									array(
										'assigned_to_id'	=> $assigned_to_id,
										'project_id'		=> $project_id, 
										'subject'		=> 'Служебная записка '.$_GET['to-recipient-name'].' от '.$_GET['of-user-name'].', '.date(" Y.m.d, H:i:s"),
										'description'		=> "<pre>".$text."</pre>",
									)
redmine authored
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
								);
							break;

						case 'request/vacation':
							$issue_props = 
								array(
									'project_id'		=> $project_id,
									'subject'		=> $memo_subject,
									'description'		=> "<pre>".$text."</pre>",
								);
							break;
redmine authored
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
						case 'request/forhire':
							$issue_props = 
								array(
									'assigned_to_id' => USERID_EGMAKSIMOVA,
									'project_id'		=> $project_id,
									'subject'		=> 'Заявка на подбор персонала',

								);
							break;

redmine authored
1316

redmine authored
1317 1318 1319 1320 1321 1322 1323 1324 1325
						case 'request/voip-unit-operator':
							$issue_props = 
								array(
									'project_id'		=> $project_id,
									'subject'		=> $memo_subject,
									'description'		=> $text,
								);
							break;

redmine authored
1326 1327 1328
						default:
							$issue_props = 
								array(
redmine authored
1329
									'assigned_to_id'	=> USERID_DYOKUNEV,
redmine authored
1330 1331 1332 1333 1334
									'project_id'		=> $project_id,
									'subject'		=> $memo_subject,
									'description'		=> $text,
								);
				}
redmine authored
1335

redmine authored
1336 1337
				if (!is_null($custom_fields))
					$issue_props['custom_fields'] = $custom_fields;
redmine authored
1338

redmine authored
1339 1340
				if (!empty($_GET['category_id']))
					$issue_props['category_id'] = $_GET['category_id'];
redmine authored
1341

redmine authored
1342 1343
				//print_r($issue_props);die();

redmine authored
1344
				error_log(base64_encode(serialize($issue_props)));
redmine authored
1345

redmine authored
1346 1347 1348 1349
				$key = serialize($issue_props);
				if (isset($already_created[$key])) {

					error_log('ERROR! Tried to create a task twice!');
redmine authored
1350

redmine authored
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
				} else {

					$result = $redmine->api('issue')->create($issue_props);
					error_log('$result: '.serialize($result));
					$issue = json_decode($result);
					$issue = $issue->issue;
					error_log(base64_encode(serialize($issue)));
					error_log('issue: '.$issue->id);
					if (empty($issue->id)) {
						//print_r($issue);
						error('Wrong parameters: '.serialize($result));
					}

					$already_created[$key] = true;

					$issue_id = $issue->id;
				}
redmine authored
1368

redmine authored
1369
			} else {
redmine authored
1370
				$issue_id = empty($_GET['force-issue-id']) ? $_GET['issue-id'] : $_GET['force-issue-id'];
redmine authored
1371 1372 1373
			}
		}

redmine authored
1374 1375 1376 1377 1378 1379 1380
		$qr = '\mmredmineurlqr{'.$issue_id.'}';
		switch($file) {
			case 'request/custom':
				if ($_GET['user-appointment-id'] != $_GET['signer-appointment-id']) {
					$qr .= '
\vspace{-2.8cm}
\begin{flushleft}
redmine authored
1381 1382
	{\small
		\begin{tabular}{ r l }
redmine authored
1383
			\multicolumn{2}{ l }{ Подготовлено: } 		\\\\
redmine authored
1384 1385 1386
			ФИО:	& '.latexSpecialChars1($_GET['signer-name']).' 	\\\\
			Тел.:	& '.latexSpecialChars1($_GET['signer-phonenumber']).'	\\\\
			Email:	& '.latexSpecialChars1($_GET['signer-email']).'		\\\\
redmine authored
1387 1388
		\end{tabular}
	}
redmine authored
1389 1390 1391 1392 1393 1394
\end{flushleft}';
				}
				break;
		}

		file_put_contents('urlqr.tex',		$qr);
redmine authored
1395 1396 1397 1398 1399 1400 1401 1402 1403

		if (isset($user_redmine['user']['id']))
			$redmine_admin->api('issue')->addWatcher($issue_id, $user_redmine['user']['id']);

		switch ($file) {
			case 'request/hpc':
				file_put_contents('responsible.tex', '\mmresponsible{'.$_GET['contact-name'].'}{'.$_GET{'contact-phonenumber'}.'}{'.$_GET['contact-email'].'}');
				$redmine_admin->api('issue')->addWatcher($issue_id, USERID_AAANIKEEV);
				$redmine_admin->api('issue')->addWatcher($issue_id, USERID_BIRCOPH);
redmine authored
1404
				break;
redmine authored
1405 1406 1407
			case 'request/cps':
			case 'request/voip3':
			case 'request/voip-softphone':
redmine authored
1408
				$redmine_admin->api('issue')->addWatcher($issue_id, USERID_AMGLADTSIN);
redmine authored
1409 1410 1411 1412 1413 1414 1415 1416 1417
				$redmine_admin->api('issue')->addWatcher($issue_id, USERID_DYOKUNEV);
				break;
			case 'request/lanmodern':
			//	$redmine_admin->api('issue')->addWatcher($issue_id, USERID_PVMAKAROV);
			//	$redmine_admin->api('issue')->addWatcher($issue_id, USERID_RYVORONINA);
				break;
			case 'request/voip-transfer-equipment':
			case 'request/vacation':
			case 'request/temporary-acting':
redmine authored
1418
			case 'request/iis':
redmine authored
1419 1420 1421
			case 'request/php':
			case 'request/itsupport':
			case 'request/custom':
redmine authored
1422
			case 'request/forhire':
redmine authored
1423
			case 'request/customform':
redmine authored
1424
			case 'request/voip-unit-operator':
redmine authored
1425 1426 1427 1428
                                break;
			case 'request/zal':
				$redmine_admin->api('issue')->addWatcher($issue_id, USERID_SVSOLOVYEV);
				$redmine_admin->api('issue')->addWatcher($issue_id, USERID_NNROMANOV);
redmine authored
1429 1430 1431 1432
				break;
			default:
				file_put_contents('responsible.tex', '\mmresponsible{'.$_GET['contact-name'].'}{'.$_GET{'contact-phonenumber'}.'}{'.$_GET['contact-email'].'}');
		}
redmine authored
1433

redmine authored
1434 1435 1436

	

redmine authored
1437 1438 1439
		exec('make');
		$pdf_content = file_get_contents('memo.pdf');

redmine authored
1440 1441 1442 1443 1444
		if ( empty($pdf_content) )
		{
			error('Can not create pdf');
		}

redmine authored
1445
		$pdf_upload = json_decode( $redmine_admin->api('attachment')->upload($pdf_content) );
redmine authored
1446
		error_log('upload:'.serialize($pdf_upload));
redmine authored
1447

redmine authored
1448
		error_log('attach:'.serialize($redmine_admin->api('issue')->attach(
redmine authored
1449 1450 1451 1452 1453 1454 1455
			$issue_id,
			array(
				'token'       => $pdf_upload->upload->token,
				'filename'    => 'sluzhebnaya_zapiska.pdf',
				'description' => 'Служебная записка',
				'content_type'=> 'application/pdf'
			)
redmine authored
1456
		)));
redmine authored
1457 1458 1459

		if (preg_match('/Firefox/i', $_SERVER['HTTP_USER_AGENT'])) {
			system('convert -density 400 memo.pdf memo.png');
redmine authored
1460
			system('convert -density 400 memo*.png memo_png.pdf');
redmine authored
1461 1462 1463 1464 1465 1466 1467 1468
			$pdfs_path[] = getcwd().'/memo_png.pdf';
			$pdf_content = file_get_contents('memo_png.pdf');
		} else
			$pdfs_path[] = getcwd().'/memo.pdf';

		$pdfs_content[] = $pdf_content;
		error_log("$appointment_i < $appointment_count");
	} while (++$appointment_i < $appointment_count);
redmine authored
1469 1470 1471 1472 1473 1474 1475
}

$count = count($pdfs_path);

if ($count == 0) {
	exit(0);
}
redmine authored
1476 1477

header('Content-type: application/pdf');
redmine authored
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489

if ($count == 1) {
	print $pdfs_content[0];
	exit(0);
}

if ($count >  1) {
	$tempdir = tempdir();
	chdir($tempdir);
	system('pdfunite '.join(' ', $pdfs_path).' memo_unite.pdf');
	print file_get_contents('memo_unite.pdf');
	exit(0);
redmine authored
1490
}
redmine authored
1491

redmine authored
1492 1493
//if (!empty($_COOKIE['debug'])) { die(); }

redmine authored
1494
?>