Blame view

genpdf/genpdf.php 21.3 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 7
require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Api/Issue.php";
require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Api/Attachment.php";
redmine authored
8
require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Api/Membership.php";
redmine authored
9 10
require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Client.php";

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

redmine authored
13 14
require_once "config.php";

redmine authored
15 16 17 18 19 20 21 22 23 24 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
/*

$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
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
$dont_inflect_patterns = array(
	'/^нач./',
	'/^зам./',
	'/^заф./',
	'/^нач./',
	'/^./',
	'/^спец./',
);

$inflect_cut_patterns = array(
	'/^(.*)[иы]й[ ]/',
);

$inflect_ignore_ending_patterns = array(
	'[ ].*',
);

redmine authored
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
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
145 146 147 148 149
function error($str) {
	die($str);
	header('Location: '.$_GET['callback_url'].'?errmsg='.urlencode($str));
	error_log($str);
	exit(0);
redmine authored
150 151
}

redmine authored
152

redmine authored
153 154 155 156 157
//DE base64 subdivs
if (isset($_GET['signer-subdivs'])){
	$_GET['signer-subdivs'] = base64_decode($_GET['signer-subdivs']);
	
}
redmine authored
158

redmine authored
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
$inflect = new Inflect();

//This cycle for situation when we could not receive enought info from node_common

foreach (array('signer', 'contact', 'user') as $key) {
	if (!empty($_GET[$key.'-e_id'])) {
		$e_id = $_GET[$key.'-e_id'];

		$employees = json_decode(file_get_contents("http://cps.mephi.ru/?cmd=getemployeeinfo&e_id=".    urlencode($e_id)  ));
		$employee  = ((array)$employees);
		$employee  = reset($employee);
	} else
	if (!empty($_GET[$key.'-login'])) {
		$login     = $_GET[$key.'-login'];
		$employees = json_decode(file_get_contents("http://cps.mephi.ru/?cmd=getemployeeinfo&username=".urlencode($login) ));
		$employee  = ((array)$employees);
		$employee  = reset($employee);
	} else
		continue;

	$appointments = array();
	foreach($employee->WORKPOSITIONS as $workposition) {
		$appointments[] = preg_replace('/ [0-9]*.[0-9]$/', '', $workposition->name).' '.mb_strtoupper($workposition->subdivision->shortname);
	}
redmine authored
183

redmine authored
184 185 186
	$fullname    = $employee->fullname;
	$name        = mb_substr($employee->firstname, 0, 1).'.'.mb_substr($employee->middlename, 0, 1).'. '. $employee->lastname;
	$appointment = join(', ',$appointments);
redmine authored
187

redmine authored
188 189 190
	$_GET[$key.'-fullname']    = $fullname;
	$_GET[$key.'-name']        = $name;
	$_GET[$key.'-appointment'] = $appointment;
redmine authored
191

redmine authored
192
}
redmine authored
193

redmine authored
194 195 196
foreach (array('fullname' => 40, 'phonenumber' => 20, 'email' => 30, 'appointment' => 40, 'pgp-id' => 12) as $key => $space) {
	if (empty($_GET['signer-'.$key]))
		$_GET['signer-'.$key] = str_pad('', $space, '_');
redmine authored
197

redmine authored
198 199 200 201
	if (empty($_GET['user-'.$key]))
		$_GET['user-'.$key]   = str_pad('', $space, '_');

	if (empty($_GET['contact-'.$key]))
redmine authored
202
		$_GET['contact-'.$key] = $_GET['user-'.$key];
redmine authored
203
}
redmine authored
204

redmine authored
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
foreach (array('signer', 'contact', 'user') as $key) {
	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);

		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;
				}
			}

// working with appointments
			$appointments = split(', ', $_GET[$key.'-appointment']);
			foreach ($appointments as &$appointment) {
				$matches        = NULL;
				$ignored_ending = '';

				$appointment  = preg_replace($inflect_cut_patterns, '', $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]));
						}
					}
				}

				$appointment  = $inflect->getInflectNoun($appointment, $case);

				$appointment .= $ignored_ending;
				$_GET[$key_prefix.'-'.$key.'-appointment'] = $appointment;
			}

			$_GET[$key_prefix.'-'.$key.'-appointment'] = join(', ', $appointments);
		
		}
	}
}

redmine authored
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
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
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
}

foreach (array('videocheck', 'confcheck', 'webtrans', 'telebridge', 'otherconf', 'record1', 'record2', 'record3') as $key ) {
	if  (isset($_GET[$key]))
		$_GET[$key] = 'Да';

//govnocode 2.0
	else{
/*
//		if ($_GET['video-type'] == 'Нет')
//			die('Ошибка: не выбран флажок видеосъемки');
		if (isset($_GET['usermount1']) || isset($__GET['record1']))
			die('Ошибка: не выбран флажок видеоконференции');
		if (isset($_GET['record2']))
			die('Ошибка: не выбран флажок вебтрансляции');
		if (isset($_GET['usermount2']) || isset($_GET['record3']))
			die('Ошибка: не выбран флажок проведения телемоста');
		if (isset($_GET['otherconftext']))
			die('Ошибка: не выбран флажок "Другое"');
*/

		$_GET[$key] = 'Нет';
		
	}
redmine authored
293 294
}

redmine authored
295 296 297 298 299 300
//Jim's simple diagnostics
//print_r($_GET);die();

$redmine_admin = new Redmine\Client('https://redmine.ut.mephi.ru', REDMINE_LOGIN, REDMINE_PASSWORD);
$me = NULL;

redmine authored
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
if (isset($_GET['user-serialized'])) {
	$user_drupal_serialized = base64_decode($_GET['user-serialized']);
	$hash = $_GET['user-signature'];
	$good_signature = 0;
	foreach ($SIGNKEYS as $key) {
		if (sha1($user_drupal_serialized.$key) === $hash) {
			$good_signature = 1;
			break;
		}
	}
	if ($good_signature == 0)
		die('Bad signature');

	$user_drupal = unserialize($user_drupal_serialized);

	$user_redmine = NULL;
	foreach ($redmine_admin->api('user')->all(array('name' => split('@', $user_drupal->user_id)[0]))['users'] as &$_user) {
		if (strtolower($_user['login']).'@mephi.ru' == strtolower($user_drupal->user_id)) {
			$user_redmine = $redmine_admin->api('user')->show($_user['id']);
			break;
		}
	}

	if (is_null($user_redmine))
		die('Cannot find user "'.$user_drupal->name.'" in Redmine');


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

//	file_put_contents("/tmp/user", print_r($user_redmine)); die();
	$redmine = new Redmine\Client('https://redmine.ut.mephi.ru', $api_key);
redmine authored
332

redmine authored
333 334 335 336
	$me = $redmine->api('user')->getCurrentUser()['user'];
} else {
	die('Not authed');
	$redmine = &$redmine_admin;
redmine authored
337 338
}

redmine authored
339
	
redmine authored
340

redmine authored
341
$custom_fields = NULL;
redmine authored
342

redmine authored
343 344 345 346 347 348
$custom_fields_keys = array();

$files = split(',', $_GET['file']);

$pdfs = array();
foreach ($files as $file) {
redmine authored
349
	$file_eff = $file;
redmine authored
350
	switch ($file) {
redmine authored
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
		case 'request/domain-name':
			$project_id   = 12886;
			$memo_subject = 'Запрос на регистрацию доменного имени';
			$file_eff = $file;//.' '.$_GET['target-type'];

			$_GET['domain-name'] = $_GET['domain-name'].'.mephi.ru';

			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;
			}
			break;
redmine authored
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
		case 'request/vpn':
			$project_id   = 1;
			$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
407

redmine authored
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
			$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;
//			$project_id   = 1;
			$memo_subject = 'Заявление на отпуск';

			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;
			}

			$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
442

redmine authored
443 444 445 446
			break;
		case 'request/temporary-acting':
			if (!isset($_GET['user-e_id']))
				continue 2;
redmine authored
447

redmine authored
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
			if (substr($_GET['of-user-fullname'], 0, 2) == '\_')
				$_GET['of-user-fullname'] = '\\\\'."\n".$_GET['of-user-fullname'];
			break;
		case 'request/voip-transfer-equipment':
			$project_id   = 1;//18;
			$memo_subject = 'Заявка на передачу телефонных аппаратов в ОСП';
			break;
		case 'request/video':
			$project_id = 1;
			$memo_subject = 'Заявка на сопровождение мероприятия видеосъемкой, проведение видеоконференции и веб-трансляции';
			break;
		//	die ('working on that');
		case 'request/php':
			$project_id = 12871;
			$memo_subject = 'Заявка на предоставление PHP хостинга';
			break;
		default:
			die('unknown memo-type');
redmine authored
466

redmine authored
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
	}
	
	if (!is_null($me))
		$redmine_admin->api('membership')->create($project_id, array('user_id' => $me['id'], 'role_ids' => array(ROLE_CUSTOMER)));

	switch ($file) {
		case 'request/voip3':
		case 'request/cps':
		case 'request/php':
			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='.$_GET['subdiv-code']));
			$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');
			}
			$subdivs      = json_decode(file_get_contents('https://cps.mephi.ru/?cmd=getsubdivinfo&s_code='.$_GET['subdiv-code']));
			$subdiv       = $subdivs->result->s0;
			$_GET['subdiv-name'] = $subdiv->name;
			break;

	}
redmine authored
501

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

redmine authored
505 506 507
	foreach ($_GET as $key => &$value) {
		$value = str_replace(array('\\', '_', '#'), array('{\textbackslash}', '\_', '\\#'), $value);
	}
redmine authored
508

redmine authored
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
	$tempdir = tempdir();

	if ($tempdir === FALSE)
		die('Cannot create temporary directory');


	exec('cp -a /var/www/ut.mephi.ru/ut-tex/mephimemo "'.$tempdir.'/"');
	chdir($tempdir.'/mephimemo');
	file_put_contents("request.get", print_r($_GET, true));

	#ob_start();
	#print_r($_GET);
	#$_GET_print_r = ob_get_clean();
	$text = '';

	/*
	if (empty($_GET['date-end']))
		$_GET['date-end'] = (date('Y')+1).'-12-31';
	*/

redmine authored
529
	$body_template = file_get_contents('template/'.$file_eff.'.tex');
redmine authored
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
	$body          = body_parse($body_template);

	switch ($file) {
		case 'request/vacation':
			$header = '\mmheaderstatement{Начальнику отдела кадров НИЯУ МИФИ}{}';
			$footer = '';
			break;
		case 'request/temporary-acting':
			$header = '\mmheadermemo{\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_}{\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_}';
			$footer = '
\mmfooter{'.$_GET['signer-appointment'].'}{'.$_GET{'signer-name'}.'}{}{}
\\
\mmfooter{'.$_GET['user-appointment'].'}{'.$_GET{'user-name'}.'}{}{Согласен:}
';
			break;
		case 'request/voip-transfer-equipment':
			$header = '\mmfullheader{'.$_GET['subdiv-name'].'}{Начальнику управления информатизации}{Романову Н.Н.}';
			break;
		case 'request/video';
			$header = '\mmfullheader{Утверждаю}{Начальник управления информатизации}{/Романов Н.Н./}';
			break;
		default:
			$header = '\mmheader{Начальнику управления информатизации}{Н. Н. Романову}';
			$footer = '\mmfooter{'.$_GET['signer-appointment'].'}{'.$_GET{'signer-name'}.'}{}{}';
	}
	file_put_contents('header.tex',		$header);
	file_put_contents('body.tex',		$body);
	file_put_contents('footer.tex',		$footer);
	file_put_contents('responsible.tex',	'\mmresponsibleskip');

	if (empty($issue_id)) {
		if (!is_null($project_id)) {
			file_put_contents('urlqr.tex',	'');
			exec('make');
			exec('pdftotext memo.pdf');

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

redmine authored
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
			switch($file) {
					case 'request/php':
						$issue_props = 
							array(
								'assigned_to_id'	=> USERID_KVMARTINOV,
								'project_id'		=> $project_id,
								'subject'		=> $memo_subject,
								'description'		=> $text,
							);
						break;
					default:
						$issue_props = 
							array(
								'assigned_to_id'	=> USERID_DYOKUNEV,
								'project_id'		=> $project_id,
								'subject'		=> $memo_subject,
								'description'		=> $text,
							);
			}
redmine authored
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603

			if (!is_null($custom_fields))
				$issue_props['custom_fields'] = $custom_fields;

		//	print_r ($issue_props);
			error_log(base64_encode(serialize($issue_props)));

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

			$issue_id = $issue->id;
redmine authored
604

redmine authored
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
		} else {
			$issue_id = $_GET['issue-id'];
		}
	}

	file_put_contents('urlqr.tex',		'\mmredmineurlqr{'.$issue_id.'}');

	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);
		case 'request/cps':
		case 'request/voip3':
		case 'request/voip-softphone':
			$redmine_admin->api('issue')->addWatcher($issue_id, USERID_NNROMANOV);
			$redmine_admin->api('issue')->addWatcher($issue_id, USERID_DYOKUNEV);
			break;
		case 'request/voip-transfer-equipment':
		case 'request/vacation':
		case 'request/temporary-acting':
			break;
		default:
			file_put_contents('responsible.tex', '\mmresponsible{'.$_GET['contact-name'].'}{'.$_GET{'contact-phonenumber'}.'}{'.$_GET['contact-email'].'}');
	}

	exec('make');
	$pdf_content = file_get_contents('memo.pdf');

	$pdf_upload = json_decode( $redmine_admin->api('attachment')->upload($pdf_content) );

	$redmine_admin->api('issue')->attach(
		$issue_id,
		array(
			'token'       => $pdf_upload->upload->token,
			'filename'    => 'sluzhebnaya_zapiska.pdf',
			'description' => 'Служебная записка',
			'content_type'=> 'application/pdf'
		)
	);

	if (preg_match('/Firefox/i', $_SERVER['HTTP_USER_AGENT'])) {
		system('convert -density 400 memo.pdf memo.png');
		system('convert -density 400 memo.png memo_png.pdf');
		$pdfs_path[] = getcwd().'/memo_png.pdf';
		$pdf_content = file_get_contents('memo_png.pdf');
	} else
		$pdfs_path[] = getcwd().'/memo.pdf';

	$pdfs_content[] = $pdf_content;
}

$count = count($pdfs_path);

if ($count == 0) {
	exit(0);
}
redmine authored
665 666

header('Content-type: application/pdf');
redmine authored
667 668 669 670 671 672 673 674 675 676 677 678

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
679
}
redmine authored
680 681

?>