Blame view

genpdf/genpdf.php 33.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
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 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 89
/*

$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
90 91 92
$_GET = array_merge ($_GET, $_POST);
//print_r ($_GET); die();

redmine authored
93
$dont_inflect_patterns = array(
redmine authored
94 95 96 97 98 99
	'/^нач\./',
	'/^зам\./',
	'/^заф\./',
	'/^нач\./',
	'/^\./',
	'/^спец\./',
redmine authored
100 101 102 103
);

$inflect_cut_patterns = array(
	'/^(.*)[иы]й[ ]/',
redmine authored
104
	'/^\[\d+\] /',
redmine authored
105 106 107 108 109 110
);

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

redmine authored
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 145 146 147 148 149
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
150 151 152 153 154
function error($str) {
	die($str);
	header('Location: '.$_GET['callback_url'].'?errmsg='.urlencode($str));
	error_log($str);
	exit(0);
redmine authored
155 156
}

redmine authored
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
function latexSpecialChars( $string ) {
	$string = str_replace("\\textbackslash", "\\", $string );
	$string = str_replace("\\", "\\textbackslash", $string );

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

redmine authored
176

redmine authored
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
$test = "Test characters: # $ % & ~ _ ^ \ { }.";
header( "content-type:text/plain" );

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





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

	if (empty($login2id)) {
		$lines = split("\n", file_get_contents('/home/xaionaro/redmine_users.csv'));

		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)) {
		$lines = split("\n", file_get_contents('/home/xaionaro/redmine_projects.csv'));

		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
235
}
redmine authored
236 237 238 239 240


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
241
}
redmine authored
242

redmine authored
243 244 245 246 247 248 249 250
$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'];

redmine authored
251
		$employees = json_decode(file_get_contents("https://cps.mephi.ru/?cmd=getemployeeinfo&e_id=".    urlencode($e_id)  ));
redmine authored
252 253 254 255 256
		$employee  = ((array)$employees);
		$employee  = reset($employee);
	} else
	if (!empty($_GET[$key.'-login'])) {
		$login     = $_GET[$key.'-login'];
redmine authored
257
		$employees = json_decode(file_get_contents("https://cps.mephi.ru/?cmd=getemployeeinfo&username=".urlencode($login) ));
redmine authored
258 259 260 261 262
		$employee  = ((array)$employees);
		$employee  = reset($employee);
	} else
		continue;

redmine authored
263 264 265 266
	$appointments         = array();
	$subdivs              = array();
	$subdivs_full         = array();
	$appointments_wosubdiv = array();
redmine authored
267
	foreach($employee->WORKPOSITIONS as $workposition) {
redmine authored
268 269 270 271
		$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
272
	}
redmine authored
273

redmine authored
274 275 276
	$fullname    = $employee->fullname;
	$name        = mb_substr($employee->firstname, 0, 1).'.'.mb_substr($employee->middlename, 0, 1).'. '. $employee->lastname;
	$appointment = join(', ',$appointments);
redmine authored
277 278 279 280 281 282 283 284 285
 
	$_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
286

redmine authored
287 288 289 290
//DE base64 subdivs
foreach (array('signer', 'contact', 'user') as $key) {
	if (!empty($_GET[$key.'-e_id']))
		continue;
redmine authored
291

redmine authored
292 293 294 295 296 297
	if (isset($_GET[$key.'-subdivs'])){
		$_GET[$key.'-subdivs']      = base64_decode($_GET[$key.'-subdivs']);
	}
	if (isset($_GET[$key.'-subdivs-full'])){
		$_GET[$key.'-subdivs-full'] = base64_decode($_GET[$key.'-subdivs-full']);
	}
redmine authored
298
}
redmine authored
299

redmine authored
300 301 302
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
303

redmine authored
304 305 306 307
	if (empty($_GET['user-'.$key]))
		$_GET['user-'.$key]   = str_pad('', $space, '_');

	if (empty($_GET['contact-'.$key]))
redmine authored
308
		$_GET['contact-'.$key] = $_GET['user-'.$key];
redmine authored
309
}
redmine authored
310

redmine authored
311 312 313 314 315 316 317 318
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);

redmine authored
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
		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
335 336
		}

redmine authored
337 338 339 340 341 342 343
		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
344
		}
redmine authored
345 346

// working with appointments
redmine authored
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
		foreach (array('', '-wosubdiv') as $postfix) {
			$appointments = split(', ', $_GET[$key.'-appointment'.$postfix]);
			foreach ($appointments as &$appointment) {
				$matches        = NULL;
				$ignored_ending = '';

				$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
362 363 364
					}
				}

redmine authored
365
				$appointment  = $inflect->getInflectNoun($appointment, $case);
redmine authored
366

redmine authored
367 368 369
				$appointment .= $ignored_ending;
				$_GET[$key_prefix.'-'.$key.'-appointment'.$postfix] = $appointment;
			}
redmine authored
370

redmine authored
371 372
			$_GET[$key_prefix.'-'.$key.'-appointment'.$postfix] = join(', ', $appointments);
		}
redmine authored
373 374 375
	}
}

redmine authored
376 377 378 379 380 381 382 383 384 385 386 387 388 389
foreach (array('signer', 'contact', 'user') as $key) {
	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
390

redmine authored
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
			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;

		}

		$_GET[$key_prefix.$key.'-appointment-w-fullsubdiv'] = $appointment_w_fullsubdiv;//join(', ', $appointment_w_fullsubdiv);

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

redmine authored
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
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
429 430 431 432 433 434 435 436 437 438 439
}

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

//govnocode 2.0
	else{
		$_GET[$key] = 'Нет';
		
	}
redmine authored
440 441
}

redmine authored
442 443 444 445

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

redmine authored
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
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;
redmine authored
462 463 464 465 466 467

	$username_drupal = strtolower(split('@', $user_drupal->user_id)[0]);

	foreach ($redmine_admin->api('user')->all(array('name' => $username_drupal))['users'] as &$_user) {
		$_user['login'] = strtolower($_user['login']);
		if ($_user['login'] == $username_drupal) {
redmine authored
468 469 470 471 472 473
			$user_redmine = $redmine_admin->api('user')->show($_user['id']);
			break;
		}
	}

	if (is_null($user_redmine))
redmine authored
474
		die('Cannot find user "'.$username_drupal.'" in Redmine');
redmine authored
475 476 477 478 479 480


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

redmine authored
482 483 484 485
	$me = $redmine->api('user')->getCurrentUser()['user'];
} else {
	die('Not authed');
	$redmine = &$redmine_admin;
redmine authored
486 487
}

redmine authored
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
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;
}

$_GET_orig = $_GET;
redmine authored
508

redmine authored
509
$custom_fields = NULL;
redmine authored
510

redmine authored
511 512 513 514 515 516
$custom_fields_keys = array();

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

$pdfs = array();
foreach ($files as $file) {
redmine authored
517 518 519
	$split_appointments = false;
//	$replacement_is_already_done = false;

redmine authored
520
	$file_eff = $file;
redmine authored
521
	switch ($file) {
redmine authored
522 523 524 525 526 527
		case 'request/domain-name':
			$project_id   = 12886;
			$memo_subject = 'Запрос на регистрацию доменного имени';
			$file_eff = $file;//.' '.$_GET['target-type'];

			break;
redmine authored
528
		case 'request/vpn':
redmine authored
529
			$project_id   = 84;
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
			$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
562

redmine authored
563 564 565 566
			$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
567
	//			$project_id   = 1;
redmine authored
568 569 570 571 572 573 574 575 576 577 578
			$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
579

redmine authored
580 581
			$split_appointments = true;

redmine authored
582 583
			break;
		case 'request/temporary-acting':
redmine authored
584
		//	print_r($_GET); die();
redmine authored
585 586
			if (!isset($_GET['user-e_id']))
				continue 2;
redmine authored
587

redmine authored
588
			if (substr($_GET['of-user-fullname'], 0, 2) == '\_')
redmine authored
589 590 591
					$_GET['of-user-fullname'] = '\\\\'."\n".$_GET['of-user-fullname'];

			$split_appointments = true;
redmine authored
592 593 594 595 596 597 598 599 600 601 602 603 604 605
			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;
redmine authored
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
		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':
			$project_id = redmine_proj_identifier2id ($_GET['credentials']);
			$memo_subject = 'Служебная записка';
			$me['id'] = $user_redmine['user']['id'];
			$replacement_is_already_done = true;

			break;
redmine authored
622 623 624 625
		default:
			die('unknown memo-type');
	}

redmine authored
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
	if (!is_null($me)) {
	//	$membership = $redmine_admin->api('user')->show($me['id'], array('include' => array('memberships',)));
		$current_membership = $redmine_admin->api('membership')->all($project_id); 



		//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
657
			}
redmine authored
658 659 660 661
			
			else {
				$result = $redmine_admin->api('membership')->create($project_id, array('user_id' => $me['id'], 'role_ids' => array(ROLE_CUSTOMER)));

redmine authored
662
			}
redmine authored
663 664 665 666 667 668


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

	}
redmine authored
671

redmine authored
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
//	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
699

redmine authored
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
	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
726

redmine authored
727
	$appointment_count = $signer_appointment_count * $user_appointment_count;
redmine authored
728

redmine authored
729 730 731 732 733
	$appointment_i = 0;
	do {
		foreach ($_GET_array as $k => $v) {
			$_GET[$k] = $v[$appointment_i];
		}
redmine authored
734

redmine authored
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
		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;
			case 'request/domain-name':
			$_GET['domain-name'] = $_GET['domain-name'].'.mephi.ru';
redmine authored
764

redmine authored
765 766 767 768 769 770 771 772 773 774 775 776 777 778
			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
779

redmine authored
780
				break;
redmine authored
781

redmine authored
782
		}
redmine authored
783

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

redmine authored
787
		$tempdir = tempdir();
redmine authored
788

redmine authored
789 790
		if ($tempdir === FALSE)
			die('Cannot create temporary directory');
redmine authored
791 792


redmine authored
793 794 795 796 797 798 799 800 801 802 803 804 805 806
		exec('cp -a /var/www/ut.mephi.ru/ut-tex/mephimemo "'.$tempdir.'/"');
		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
807 808


redmine authored
809 810 811 812
		#ob_start();
		#print_r($_GET);
		#$_GET_print_r = ob_get_clean();
		$text = '';
redmine authored
813

redmine authored
814 815 816 817
		/*
		if (empty($_GET['date-end']))
			$_GET['date-end'] = (date('Y')+1).'-12-31';
		*/
redmine authored
818

redmine authored
819 820 821
		if (!empty($_GET['category_id'])) {
			$category = $redmine_admin->api('issue_category')->show($_GET['category_id']);
			$_GET['category'] = $category['issue_category']['name'];
redmine authored
822 823
		}

redmine authored
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 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 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 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 966 967 968
		$body_template = file_get_contents('template/'.$file_eff.'.tex');
		$body          = body_parse($body_template);

		switch ($file) {
			case 'request/vacation':
				$header = '\mmheaderstatement{Начальнику отдела кадров НИЯУ МИФИ}{от '.$_GET['of-signer-appointment-w-fullsubdiv'].' '.$_GET{'of-signer-fullname'}.'}';
				$footer = '';
				break;
			case 'request/temporary-acting':
				$header = '\mmheadermemo{\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_}{\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_}';
				$footer = '
\mmfooter{'.$_GET['signer-appointment-w-fullsubdiv'].'}{'.$_GET{'signer-name'}.'}{}{}
\\
\mmfooter{'.(empty($_GET['user-appointment-w-fullsubdiv'])||$_GET['user-appointment-w-fullsubdiv']==" "?'\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_':$_GET['user-appointment-w-fullsubdiv']).'}{'.$_GET{'user-name'}.'}{}{}
';
				break;
			case 'request/voip-transfer-equipment':
				$header = '\mmfullheader{'.$_GET['subdiv-name'].'}{Начальнику управления информатизации}{Романову Н.Н.}';
				break;
			case 'request/video';
				$header = '\mmfullheader{Утверждаю}{Начальник управления информатизации}{/Романов Н.Н./}';

				break;

			case 'request/itsupport':
				$header = '\mmheader{Начальнику отдела технической поддержки}{Солодовникову А.В}';
				$footer ='';
				break; 
			case 'request/php':
				$header = '\mmheader{Начальнику управления информатизации}{Н. Н. Романову}';
				break;
			case 'request/custom':
				$cred_parts = split('<br>', $_GET['cred-id']);
				$header = '\mmheader{'.$cred_parts[0].'}{'.$cred_parts[1].'}';
				$body = latexSpecialChars1(str_replace("\n", "\n\n", $body));
				$footer = '\mmfooter{'.my_mb_ucfirst($_GET['signer-appointment']).'}{'.$_GET['signer-name'].'}{'.$_GET['current-date'].'}{}';
		//		$footer = '\mmfooter{'.my_mb_ucfirst($_GET['signer-appointment']).'}{'.$_GET['current-date'].'}{'.$_GET['signer-name'].'}{}';
				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');

				switch($file) {
						case 'request/php':
							$issue_props = 
								array(
									'assigned_to_id'	=> USERID_KVMARTINOV,
									'project_id'		=> $project_id,
									'subject'		=> $memo_subject,
									'description'		=> $text,
								);
							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;



						case 'request/custom': //AASD
							$issue_props = 
								array(
									'assigned_to_id'	=> redmine_login2id($_GET['credentials']),
									'project_id'		=> $project_id, 
									'subject'		=> 'Служебная записка '.(explode('<br>', $_GET['cred-id'])[1]).' от '.$_GET['of-signer-name'].', '.date(" Y.m.d, H:i:s"),
									'description'		=> "<pre>".$text."</pre>",
									
								);
							break;

						case 'request/vacation':
							$issue_props = 
								array(
									'project_id'		=> $project_id,
									'subject'		=> $memo_subject,
									'description'		=> "<pre>".$text."</pre>",
								);
							break;

						default:
							$issue_props = 
								array(
									'assigned_to_id'	=> USERID_EVVLASOV,
									'project_id'		=> $project_id,
									'subject'		=> $memo_subject,
									'description'		=> $text,
								);
				}
redmine authored
969

redmine authored
970 971
				if (!is_null($custom_fields))
					$issue_props['custom_fields'] = $custom_fields;
redmine authored
972

redmine authored
973 974
				if (!empty($_GET['category_id']))
					$issue_props['category_id'] = $_GET['category_id'];
redmine authored
975

redmine authored
976 977
			//	print_r ($issue_props);
				error_log(base64_encode(serialize($issue_props)));
redmine authored
978

redmine authored
979 980 981 982 983 984 985
				$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);
redmine authored
986

redmine authored
987
				$issue_id = $issue->id;
redmine authored
988

redmine authored
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
			} 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/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':
			case 'request/php':
			case 'request/itsupport':
			case 'request/custom':
				break;
			default:
				file_put_contents('responsible.tex', '\mmresponsible{'.$_GET['contact-name'].'}{'.$_GET{'contact-phonenumber'}.'}{'.$_GET['contact-email'].'}');
		}
redmine authored
1024

redmine authored
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
		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;
		error_log("$appointment_i < $appointment_count");
	} while (++$appointment_i < $appointment_count);
redmine authored
1051 1052 1053 1054 1055 1056 1057
}

$count = count($pdfs_path);

if ($count == 0) {
	exit(0);
}
redmine authored
1058 1059

header('Content-type: application/pdf');
redmine authored
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071

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
1072
}
redmine authored
1073 1074

?>