Blame view

genpdf/genpdf.php 35.5 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
$_GET = array_merge ($_GET, $_POST);
redmine authored
91
header( "Content-Type: text/plain" );
redmine authored
92
//print_r ($_GET); die();
redmine authored
93 94
//print_r($_GET);

redmine authored
95 96
$me = NULL;

redmine authored
97 98 99 100 101 102 103 104 105 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 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
$inflect = new Inflect();
$redmine_admin = new Redmine\Client('https://redmine.ut.mephi.ru', REDMINE_LOGIN, REDMINE_PASSWORD);

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;

	//print_r($user);

	$employee = $user->employee;

	$appointment = null;

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

	if (is_null($appointment)) {
		die('Wrong appointment ID');
	}

	$appointment_name = preg_replace('/ [0-9]*.[0-9]$/', '', $appointment->name);
	$appointments = $appointment_name.' '.mb_strtoupper($appointment->subdivision->shortname);
	$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]);
	}
	if ($appointment_ofsubdivfull_words[0] == 'ректората') {
		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;

	$_GET['signer-fullname']             = $user->employee->fullname;
redmine authored
161 162
	$_GET['signer-appointment']          = $appointments_full;
	$_GET['signer-appointment-wosubdiv'] = $appointments_wosubdiv;
redmine authored
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
	$_GET['signer-subdivs']              = $signer_subdivs;
	$_GET['signer-subdivs-full']         = $signer_subdivs_full;

	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 = new Redmine\Client('https://redmine.ut.mephi.ru', $api_key);

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

redmine authored
189
//print_r($redmine);print_r($_GET);die();
redmine authored
190

redmine authored
191
$dont_inflect_patterns = array(
redmine authored
192 193 194 195 196 197
	'/^нач\./',
	'/^зам\./',
	'/^заф\./',
	'/^нач\./',
	'/^\./',
	'/^спец\./',
redmine authored
198 199 200 201
);

$inflect_cut_patterns = array(
	'/^(.*)[иы]й[ ]/',
redmine authored
202
	'/^\[\d+\] /',
redmine authored
203 204 205 206 207 208
);

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

redmine authored
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
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
248 249 250 251 252
function error($str) {
	die($str);
	header('Location: '.$_GET['callback_url'].'?errmsg='.urlencode($str));
	error_log($str);
	exit(0);
redmine authored
253 254
}

redmine authored
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
function latexSpecialChars( $string ) {
	$string = str_replace("\\textbackslash", "\\", $string );
	$string = str_replace("\\", "\\textbackslash", $string );

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

redmine authored
274

redmine authored
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 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
$test = "Test characters: # $ % & ~ _ ^ \ { }.";

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
332
}
redmine authored
333 334 335 336 337


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
338
}
redmine authored
339

redmine authored
340 341 342 343 344 345
//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
346
		$employees = json_decode(file_get_contents("https://cps.mephi.ru/?cmd=getemployeeinfo&e_id=".    urlencode($e_id)  ));
redmine authored
347 348 349 350 351
		$employee  = ((array)$employees);
		$employee  = reset($employee);
	} else
	if (!empty($_GET[$key.'-login'])) {
		$login     = $_GET[$key.'-login'];
redmine authored
352
		$employees = json_decode(file_get_contents("https://cps.mephi.ru/?cmd=getemployeeinfo&username=".urlencode($login) ));
redmine authored
353 354 355 356 357
		$employee  = ((array)$employees);
		$employee  = reset($employee);
	} else
		continue;

redmine authored
358 359 360 361
	$appointments         = array();
	$subdivs              = array();
	$subdivs_full         = array();
	$appointments_wosubdiv = array();
redmine authored
362
	foreach($employee->WORKPOSITIONS as $workposition) {
redmine authored
363 364 365 366
		$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
367
	}
redmine authored
368

redmine authored
369 370 371
	$fullname    = $employee->fullname;
	$name        = mb_substr($employee->firstname, 0, 1).'.'.mb_substr($employee->middlename, 0, 1).'. '. $employee->lastname;
	$appointment = join(', ',$appointments);
redmine authored
372 373 374 375 376 377 378 379 380
 
	$_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
381

redmine authored
382 383 384 385
//DE base64 subdivs
foreach (array('signer', 'contact', 'user') as $key) {
	if (!empty($_GET[$key.'-e_id']))
		continue;
redmine authored
386

redmine authored
387
	if (isset($_GET[$key.'-subdivs'])){
redmine authored
388
		$_GET[$key.'-subdivs']      = $_GET[$key.'-subdivs'];
redmine authored
389 390
	}
	if (isset($_GET[$key.'-subdivs-full'])){
redmine authored
391
		$_GET[$key.'-subdivs-full'] = $_GET[$key.'-subdivs-full'];
redmine authored
392
	}
redmine authored
393
}
redmine authored
394

redmine authored
395 396 397
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
398

redmine authored
399 400 401 402
	if (empty($_GET['user-'.$key]))
		$_GET['user-'.$key]   = str_pad('', $space, '_');

	if (empty($_GET['contact-'.$key]))
redmine authored
403
		$_GET['contact-'.$key] = $_GET['user-'.$key];
redmine authored
404
}
redmine authored
405

redmine authored
406 407 408 409 410 411 412 413
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
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
		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
430 431
		}

redmine authored
432 433 434 435 436 437 438
		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
439
		}
redmine authored
440 441

// working with appointments
redmine authored
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
		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
457 458 459
					}
				}

redmine authored
460
				$appointment  = $inflect->getInflectNoun($appointment, $case);
redmine authored
461

redmine authored
462 463 464
				$appointment .= $ignored_ending;
				$_GET[$key_prefix.'-'.$key.'-appointment'.$postfix] = $appointment;
			}
redmine authored
465

redmine authored
466 467
			$_GET[$key_prefix.'-'.$key.'-appointment'.$postfix] = join(', ', $appointments);
		}
redmine authored
468 469 470
	}
}

redmine authored
471 472 473 474 475 476 477 478 479 480 481 482 483 484
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
485

redmine authored
486 487 488 489 490 491 492 493 494 495 496 497 498
			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
499 500
		$_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
501 502 503 504

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

redmine authored
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
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
525 526 527 528 529 530 531 532 533 534 535
}

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
536 537 538
}


redmine authored
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
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
559

redmine authored
560
$custom_fields = NULL;
redmine authored
561

redmine authored
562 563 564 565 566 567
$custom_fields_keys = array();

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

$pdfs = array();
foreach ($files as $file) {
redmine authored
568 569 570
	$split_appointments = false;
//	$replacement_is_already_done = false;

redmine authored
571
	$file_eff = $file;
redmine authored
572
	switch ($file) {
redmine authored
573 574 575 576 577 578
		case 'request/domain-name':
			$project_id   = 12886;
			$memo_subject = 'Запрос на регистрацию доменного имени';
			$file_eff = $file;//.' '.$_GET['target-type'];

			break;
redmine authored
579
		case 'request/vpn':
redmine authored
580
			$project_id   = 84;
redmine authored
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
			$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
613

redmine authored
614 615 616 617
			$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
618
	//			$project_id   = 1;
redmine authored
619 620 621 622 623 624 625 626 627 628 629
			$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
630

redmine authored
631 632
			$split_appointments = true;

redmine authored
633 634
			break;
		case 'request/temporary-acting':
redmine authored
635
		//	print_r($_GET); die();
redmine authored
636 637
			if (!isset($_GET['user-e_id']))
				continue 2;
redmine authored
638

redmine authored
639
			if (substr($_GET['of-user-fullname'], 0, 2) == '\_')
redmine authored
640 641 642
					$_GET['of-user-fullname'] = '\\\\'."\n".$_GET['of-user-fullname'];

			$split_appointments = true;
redmine authored
643 644 645 646 647 648 649 650 651 652 653 654 655 656
			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
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
		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
673 674 675 676
		default:
			die('unknown memo-type');
	}

redmine authored
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
	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
708
			}
redmine authored
709 710 711 712
			
			else {
				$result = $redmine_admin->api('membership')->create($project_id, array('user_id' => $me['id'], 'role_ids' => array(ROLE_CUSTOMER)));

redmine authored
713
			}
redmine authored
714 715 716 717 718 719


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

	}
redmine authored
722

redmine authored
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
//	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
750

redmine authored
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
	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
777

redmine authored
778
	$appointment_count = $signer_appointment_count * $user_appointment_count;
redmine authored
779

redmine authored
780 781 782 783 784
	$appointment_i = 0;
	do {
		foreach ($_GET_array as $k => $v) {
			$_GET[$k] = $v[$appointment_i];
		}
redmine authored
785

redmine authored
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
		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
815

redmine authored
816 817 818 819 820 821 822 823 824 825 826 827 828 829
			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
830

redmine authored
831
				break;
redmine authored
832

redmine authored
833
		}
redmine authored
834

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

redmine authored
838
		$tempdir = tempdir();
redmine authored
839

redmine authored
840 841
		if ($tempdir === FALSE)
			die('Cannot create temporary directory');
redmine authored
842 843


redmine authored
844
		exec('cp -a /var/www/'.$_SERVER['SERVER_NAME'].'/ut-tex/mephimemo "'.$tempdir.'/"');
redmine authored
845 846 847 848 849 850 851 852 853 854 855 856 857
		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
858 859


redmine authored
860 861 862 863
		#ob_start();
		#print_r($_GET);
		#$_GET_print_r = ob_get_clean();
		$text = '';
redmine authored
864

redmine authored
865 866 867 868
		/*
		if (empty($_GET['date-end']))
			$_GET['date-end'] = (date('Y')+1).'-12-31';
		*/
redmine authored
869

redmine authored
870 871 872
		if (!empty($_GET['category_id'])) {
			$category = $redmine_admin->api('issue_category')->show($_GET['category_id']);
			$_GET['category'] = $category['issue_category']['name'];
redmine authored
873 874
		}

redmine authored
875 876 877 878 879 880 881 882 883 884 885
		$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 = '
redmine authored
886
\mmfooter{'.my_mb_ucfirst($_GET['signer-appointment-w-fullsubdiv']).'}{'.$_GET{'signer-name'}.'}{}{}
redmine authored
887
\\
redmine authored
888
\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
889 890 891 892
';
				break;
			case 'request/voip-transfer-equipment':
				$header = '\mmfullheader{'.$_GET['subdiv-name'].'}{Начальнику управления информатизации}{Романову Н.Н.}';
redmine authored
893
				$footer = '';
redmine authored
894 895 896
				break;
			case 'request/video';
				$header = '\mmfullheader{Утверждаю}{Начальник управления информатизации}{/Романов Н.Н./}';
redmine authored
897
				$footer = '';
redmine authored
898 899 900 901 902 903 904 905
				break;

			case 'request/itsupport':
				$header = '\mmheader{Начальнику отдела технической поддержки}{Солодовникову А.В}';
				$footer ='';
				break; 
			case 'request/php':
				$header = '\mmheader{Начальнику управления информатизации}{Н. Н. Романову}';
redmine authored
906
				$footer = '';
redmine authored
907 908 909 910 911 912 913 914 915 916 917
				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{Начальнику управления информатизации}{Н. Н. Романову}';
redmine authored
918
				$footer = '\mmfooter{'.my_mb_ucfirst($_GET['signer-appointment']).'}{'.$_GET{'signer-name'}.'}{}{}';
redmine authored
919 920 921 922 923 924
		}
		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
925
		//print_r($_GET);die();
redmine authored
926

redmine authored
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 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 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
		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
1024

redmine authored
1025 1026
				if (!is_null($custom_fields))
					$issue_props['custom_fields'] = $custom_fields;
redmine authored
1027

redmine authored
1028 1029
				if (!empty($_GET['category_id']))
					$issue_props['category_id'] = $_GET['category_id'];
redmine authored
1030

redmine authored
1031 1032
			//	print_r ($issue_props);
				error_log(base64_encode(serialize($issue_props)));
redmine authored
1033

redmine authored
1034
				$result = $redmine->api('issue')->create($issue_props);
redmine authored
1035
				error_log('$result: '.serialize($result));
redmine authored
1036 1037 1038 1039 1040 1041
				$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
1042

redmine authored
1043
				$issue_id = $issue->id;
redmine authored
1044

redmine authored
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
			} 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
1080

redmine authored
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
		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
1107 1108 1109 1110 1111 1112 1113
}

$count = count($pdfs_path);

if ($count == 0) {
	exit(0);
}
redmine authored
1114 1115

header('Content-type: application/pdf');
redmine authored
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127

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
1128
}
redmine authored
1129 1130

?>