Blame view

genpdf/genpdf2.php 21 KB
redmine authored
1 2 3 4 5 6 7 8 9 10 11 12 13 14 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 89 90 91 92 93 94 95 96 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 161 162 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 189 190 191 192 193 194 195 196 197
<?php

require_once "lib/3rdparty/Inflect/Inflect.php";
require_once '/var/www/ut.mephi.ru/ut-tex/genpdf/3rdparty/number-to-words/src/NumberToWords.php';
require_once '/var/www/ut.mephi.ru/ut-tex/genpdf/3rdparty/number-to-words/src/Legacy/Numbers/Words.php';
require_once '/var/www/ut.mephi.ru/ut-tex/genpdf/3rdparty/number-to-words/src/Legacy/Numbers/Words/Locale/Ru.php';
require_once '/var/www/ut.mephi.ru/ut-tex/genpdf/3rdparty/number-to-words/src/Exception/NumberToWordsException.php';
require_once '/var/www/ut.mephi.ru/ut-tex/genpdf/3rdparty/number-to-words/src/NumberTransformer/NumberTransformer.php';
require_once '/var/www/ut.mephi.ru/ut-tex/genpdf/3rdparty/number-to-words/src/NumberTransformer/RussianNumberTransformer.php';
require_once "config.php";

use NumberToWords\NumberToWords;


$_GET = array_merge ($_GET, $_POST);
header( "Content-Type: text/plain" );
//print_r ($_GET); die();
//print_r($_GET);

$me = NULL;

$inflect = new Inflect();

if (!isset($_GET['signer-serialized']))
	die('Not authed');

$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;
$username_real   = $username_drupal;

if (in_array($username_real, $ADMINS)) {
	if (!empty($_GET['force-login'])) {
		$username_drupal = $_GET['force-login'];
			$user		 = json_decode(file_get_contents("https://ut.mephi.ru/getldapentry.php?username=".     urlencode($username_drupal) )); 
		@$user->employee = json_decode(file_get_contents("https://cps.mephi.ru/?cmd=getemployeeinfo&usevoip=true&username=".urlencode($username_drupal) )); 
		@$user->oauth	 = $user_oauth;
		@$user->login	 = $login;
		//print_r($user);
		$_GET['signer-appointment-id'] = empty($_GET['force-appointment-id']) ? $user->employee->WORKPOSITIONS[0]->w_id : $_GET['force-appointment-id'];
	}
}

$subordinate_units = array();

if (!empty($user->employee->WORKPOSITIONS)) {
	foreach($user->employee->WORKPOSITIONS as $workposition) {
		if ($workposition->is_head) {
			$subordinate_units[$workposition->subdivision->s_id] = $workposition->subdivision;
		}
	}
}


//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 (empty($employee)) {
	die("The employee doesn't exists");
}

$dont_inflect_patterns = array(
	'/^нач\./',
	'/^зам\./',
	'/^заф\./',
	'/^нач\./',
	'/^\./',
	'/^спец\./',
);

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

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

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

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, $data) {
	$data_withbraces = array();

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

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

	return $body;
}

function error($str) {
	die($str);
	header('Location: '.$_GET['callback_url'].'?errmsg='.urlencode($str));
	error_log($str);
	exit(0);
}

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


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

function formatDate($date) {
	$date = split('T', split(' ', $date)[0])[0];
	$words = split('-', $date);
	return $words[2].'.'.$words[1].'.'.$words[0];
}

$file = $_GET['file'];

$datas = array();

switch ($file) {
	case 'form/updatesalary':
	case 'form/updateenddate': {
		$themes_raw = json_decode(file_get_contents('https://sd.mephi.ru/api/9/get_themes.json?api_key=JY3FUioBmsu1o'), 1);

		$themes = array();
		foreach($themes_raw as $theme_raw) {
			$themes['1'.$theme_raw['bcod'].$theme_raw['ecod']] = $theme_raw;
		}
		//print_r($themes);die();

		function newFormularData($stfCardId) {
xaionaro authored
198
			global $themes, $inflect;
redmine authored
199

xaionaro authored
200 201
			/*
			// 2017
redmine authored
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
			$salaries = array(
				'1-1'	=> 7800,
				'1-2'	=> 7810,

				'2-1'	=> 7820,
				'2-2'	=> 7830,
				'2-3'	=> 7840,
				'2-4'	=> 7850,
				'2-5'	=> 7855,

				'3-1'	=> 7860,
				'3-2'	=> 7870,
				'3-3'	=> 7880,
				'3-4'	=> 7890,
				'3-5'	=> 7900,

				'4-1'	=> 7910,
				'4-2'	=> 7920,
				'4-3'	=> 7930,
				'4-4'	=> 8240,
				'4-5'	=> 8585,
				'4-6'	=> 8925,
xaionaro authored
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
			);*/
			// 2018
			$salaries = array(
				'1-1'	=> 11200,
				'1-2'	=> 11210,

				'2-1'	=> 11220,
				'2-2'	=> 11230,
				'2-3'	=> 11240,
				'2-4'	=> 11250,
				'2-5'	=> 11260,

				'3-1'	=> 11270,
				'3-2'	=> 11280,
				'3-3'	=> 11290,
				'3-4'	=> 11300,
				'3-5'	=> 11310,

				'4-1'	=> 11320,
				'4-2'	=> 11330,
				'4-3'	=> 12420,
				'4-4'	=> 12430,
				'4-5'	=> 12500,
				'4-6'	=> 12760,
redmine authored
248 249
			);

xaionaro authored
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
			$stfCardId = preg_replace('/[^0-9]+/', '', $stfCardId);

			$a = json_decode(file_get_contents('https://sd.mephi.ru/api/1/formulars.json?from_local_db=true&active_only=true&api_key='.SDAPI_KEY.'&filter_StfCardId='.$stfCardId), 1)[0];
			if (empty($a)) {
				$voipAppointment = json_decode(file_get_contents('https://voip.mephi.ru/appointments/'.$stfCardId.'.json'), 1)['appointment_selected'];
				if ($voipAppointment['Id'] != $voipAppointment['StfCardId']) {
					$a = json_decode(file_get_contents('https://sd.mephi.ru/api/1/formulars.json?from_local_db=true&active_only=true&api_key='.SDAPI_KEY.'&filter_StfCardId='.$voipAppointment['Id']), 1)[0];
				}
				if (!empty($a)) {
					mail('dyokunev@mephi.ru', 'Wrong StfCardId '.$stfCardId, 'Wrong StfCardId '.$stfCardId.' (sent by /var/www/ut.mephi.ru/root/genpdf2.php)');
				}
			}

			if ((int)$a['Cod_Tip_formular'] == 8) {
				$a_prev = json_decode(file_get_contents('https://sd.mephi.ru/api/1/formulars.json?from_local_db=true&last_only=true&api_key='.SDAPI_KEY.'&filter_EmpGUID='.$a['EmpGUID'].'&filter_Cod_Tip_formular=!8'), 1)[0];
				error_log('https://sd.mephi.ru/api/1/formulars.json?from_local_db=true&last_only=true&api_key='.SDAPI_KEY.'&filter_EmpGUID='.$a['EmpGUID'].'&filter_Cod_Tip_formular=!8');
				if (!empty($a_prev)) {
					$a['RateAmount'] = $a_prev['RateAmount'];
				}
			}
redmine authored
270 271 272 273 274

			$profKvalLevel = preg_replace('/[.].*+/', '', @$a['ProfKvalLevel']);
			$salary = $a['RateAmount']*$salaries[(@$a['ProfKvalGroup']).'-'.$profKvalLevel];

			$employeePrefix = '';
xaionaro authored
275
			/*if ($a['Cod_Tip_formular']==3 || $a['Cod_Tip_formular']==5) { // Совместитель
xaionaro authored
276 277
				$as = json_decode(file_get_contents('https://sd.mephi.ru/api/1/formulars.json?from_local_db=true&active_only=true&api_key='.SDAPI_KEY.'&filter_EmpGUID='.preg_replace('/[^0-9]+/', '', $a['EmpGUID'])), 1);
				//die('https://sd.mephi.ru/api/1/formulars.json?from_local_db=true&active_only=true&api_key='.SDAPI_KEY.'&filter_EmpGUID'.preg_replace('/[^0-9]+/', '', $a['EmpGUID']));
redmine authored
278 279 280 281
				$employeePrefix = '________________________________';
				foreach ($as as $_a) {
					if ($_a['Cod_Tip_formular'] == 2) {
						$words0 = split(' ', chop($a['Name']));
xaionaro authored
282
						$words1 = split(' ', $inflect->getInflectNoun($a['Name_podr'], 0));
redmine authored
283 284 285 286 287 288 289
						if ($words0[count($words0)-1] == $words1[0]) {
							unset($words0[count($words0)-1]);
						}
						$employeePrefix = join(' ', array_merge($words0, $words1));
						break;
					}
				}
xaionaro authored
290 291 292 293 294 295 296 297 298 299 300 301 302
			}*/

			$employeeAppointmentPart0 = $a['Name'];
			$employeeAppointmentPart1 = $inflect->getInflectNoun($a['Name_podr'], 0);
			$employeeAppointmentPart0Words = split(' ', $employeeAppointmentPart0);
			$employeeAppointmentPart1Words = split(' ', $employeeAppointmentPart1);
			if (mb_strtolower($employeeAppointmentPart0Words[count($employeeAppointmentPart0Words)-1]) === mb_strtolower($employeeAppointmentPart1Words[0])) {
				unset($employeeAppointmentPart0Words[count($employeeAppointmentPart0Words)-1]);
			}
			$employeeAppointment = join(' ', $employeeAppointmentPart0Words).' '.join(' ', $employeeAppointmentPart1Words);

			if ($a['Cod_Tip_formular']==3 || $a['Cod_Tip_formular']==5) { // Совместитель
				$employeeAppointment .= ' (совместитель)';
redmine authored
303 304
			}

xaionaro authored
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
			$curUnit = json_decode(file_get_contents('https://sd.mephi.ru/api/1/units.json?from_local_db=true&active_only=true&api_key='.SDAPI_KEY.'&filter_id='.preg_replace('/[^0-9]+/', '', $a['OrgDiv'])), 1)[0];

			$unitCode = $curUnit['Code'];
			while (substr($unitCode, strlen($unitCode)-2, 2) != '00') {
				$curUnit = json_decode(file_get_contents('https://sd.mephi.ru/api/1/units.json?from_local_db=true&active_only=true&api_key='.SDAPI_KEY.'&filter_id='.preg_replace('/[^0-9]+/', '', $curUnit['ParentId'])), 1)[0];
				$unitCode = $curUnit['Code'];
				if (empty($unitCode)) {
					error_log('empty unitCode');
					break;
				}
			}

			$unitName = mb_strtoupper(chop($curUnit['BriefName'])).' ['.$curUnit['Code'].']';
			$unitHeadFullname = $curUnit['ChiefName'];
			$unitHeadNameWords = split(' ', preg_replace('/[А-Я][.]/', '', $unitHeadFullname));
			$unitHeadLastname = $unitHeadNameWords[0];
			if (mb_strtoupper($a['SurName']) == mb_strtoupper($unitHeadLastname)) {
				
				$parentUnit = json_decode(file_get_contents('https://sd.mephi.ru/api/1/units.json?from_local_db=true&active_only=true&api_key='.SDAPI_KEY.'&filter_id='.preg_replace('/[^0-9]+/', '', $curUnit['ParentId'])), 1)[0];
				$unitName = mb_strtoupper(chop($parentUnit['BriefName'])).' ['.$parentUnit['Code'].']';
				$unitHeadFullname = $parentUnit['ChiefName'];
redmine authored
326 327
				$unitHeadNameWords = split(' ', preg_replace('/[А-Я][.]/', '', $unitHeadFullname));
				$unitHeadLastname = $unitHeadNameWords[0];
xaionaro authored
328
			}
redmine authored
329

xaionaro authored
330 331 332 333 334
			if (count($unitHeadNameWords) != 3) {
				$employeesByLastname = json_decode(file_get_contents('https://sd.mephi.ru/api/1/formulars.json?from_local_db=true&active_only=true&api_key='.SDAPI_KEY.'&filter_SurName='.preg_replace('/[^а-яА-Я]+/', '', $unitHeadLastname)), 1);
				$fullnames = array();
				foreach ($employeesByLastname as $employee) {
					$fullnames[$employee['SurName'].' '.$employee['FirstName'].' '.$employee['MiddleName']] = true;
redmine authored
335
				}
xaionaro authored
336 337 338
				if (count($fullnames) == 1) {
					$unitHeadFullname = $fullnames[0];
					$unitHeadNameWords = split(' ', $unitHeadFullname);
redmine authored
339 340 341
				}
			}

xaionaro authored
342 343 344 345
			if (count($unitHeadNameWords) == 3) {
				$unitHead = $unitHeadNameWords[0].' '.mb_substr($unitHeadNameWords[1], 0, 1).'.'.mb_substr($unitHeadNameWords[2], 0, 1).'.';
			}

xaionaro authored
346 347 348 349 350 351 352 353 354 355
			if ($unitHead === 'Стриханов М.Н.') {
				$unitHead = '_____________';
				$unitName = '_____________';
			}

			if (empty($_REQUEST['auto-director'])) {
				$unitHead = '_____________';
				$unitName = '_____________';
			}

redmine authored
356 357 358 359 360 361
			$numberToWords = new NumberToWords();
			$numberTransformer = $numberToWords->getNumberTransformer('ru');

			$account = '_____________';
			$account_manager = '_________________';

xaionaro authored
362 363 364 365 366 367 368 369
			if (!empty($_GET['account'])) {
				$account = $_GET['account'];
			}

			if (!empty($_GET['account-manager'])) {
				$account_manager = $_GET['account-manager'];
			}

redmine authored
370 371 372 373
			if (!empty($themes[$a['Code']])) {
				//$account = $themes[$a['Code']]['theme'];
			}

xaionaro authored
374 375 376 377 378 379 380
			$prorector_appointment_id = @$_GET['prorector-appointment-id'];

			$prorector_appointment = json_decode(file_get_contents('https://voip.mephi.ru/appointments/'.$prorector_appointment_id.'.json'), 1)['appointment_selected'];

			$attorney_date = '«___» __________ 20___г';
			$attorney_code = '_____________';
			switch ((int)$prorector_appointment_id) {
xaionaro authored
381 382 383 384 385 386 387
				case 161842: // Нагорнов
					// 2017
					//$attorney_code = '329-17-001/17';
					//$attorney_date = '«30» декабря 2016г';
					// 2018
					$attorney_code = '329-017-001/18';
					$attorney_date = '«29» декабря 2017г';
xaionaro authored
388
					break;
xaionaro authored
389 390 391 392 393 394 395
				case 163540: // Ужва
					// 2017
					//$attorney_code = '329-17-009/17';
					//$attorney_date = '«30» декабря 2016г';
					// 2018
					$attorney_code = '329-017-003/18';
					$attorney_date = '«29» декабря 2017г';
xaionaro authored
396
					break;
xaionaro authored
397 398 399 400 401 402 403
				case 162863: // Весна
					// 2017
					//$attorney_code = '329-17-008/17';
					//$attorney_date = '«30» декабря 2016г';
					// 2018
					$attorney_code = '329-017-008/18';
					$attorney_date = '«29» декабря 2017г';
xaionaro authored
404 405 406
					break;
				case 158626: // Каргин
				case -27400500:
xaionaro authored
407 408 409 410 411 412
					// 2017
					//$attorney_code = '329-17-002/17';
					//$attorney_date = '«30» декабря 2016г';
					// 2018
					$attorney_code = '329-017-005/18';
					$attorney_date = '«29» декабря 2017г';
xaionaro authored
413 414 415 416 417 418
					break;
			}

			if (empty($prorector_appointment['Name']) || $prorector_appointment['Name'] == '-') {
				$prorector_appointment['Name'] = $prorector_appointment['Description'];
			}
xaionaro authored
419

redmine authored
420
			return array(
xaionaro authored
421
				'of-prorector' => $inflect->getInflectNoun($prorector_appointment['Name'], 0).' '.explode(' ', $inflect->getInflectName($prorector_appointment['Subscriber']['Fullname'], 0))[0].' '.mb_substr($prorector_appointment['Subscriber']['Firstname'], 0, 1).'.'.mb_substr($prorector_appointment['Subscriber']['Patronymic'], 0, 1).'.',
xaionaro authored
422
				'prorector' => $prorector_appointment['Subscriber']['Lastname'].' '.mb_substr($prorector_appointment['Subscriber']['Firstname'], 0, 1).'.'.mb_substr($prorector_appointment['Subscriber']['Patronymic'], 0, 1).'.',
xaionaro authored
423 424
				'attorney-date' => $attorney_date,
				'attorney-code' => $attorney_code,
redmine authored
425 426 427 428 429

				'of-unit' => $unitName,
				'unit-head' => $unitHead,
				'employee' => $a['SurName'].' '.mb_substr($a['FirstName'], 0, 1).'.'.mb_substr($a['MiddleName'], 0, 1).'.',
				'employee-full' => $employeePrefix.$a['SurName'].' '.$a['FirstName'].' '.$a['MiddleName'],
xaionaro authored
430
				'employee-appointment' => $employeeAppointment,
xaionaro authored
431 432
				//'employee-full' => /*$employeePrefix.' '.*/$a['SurName'].' '.$a['FirstName'].' '.$a['MiddleName'],
				//'appointment-full' => $employeePrefix,
redmine authored
433 434 435 436 437
				'employment-contract-date' => formatDate($a['ContDate']),
				'employment-contract-code' => $a['ContNo'],
				'ProfKvalGroup' => @$a['ProfKvalGroup'],
				'ProfKvalLevel' => $profKvalLevel,
				'Salary' => $salary.' руб.',
xaionaro authored
438
				'SalaryText' => $numberTransformer->toWords($salary).' рублей '.($numberTransformer->toWords((int)(($salary - floor($salary))*100))).' копеек',
redmine authored
439 440
				'MultiplyingFactor' => '______',
				'MultiplyingFactorReason' => '_________________________________',
xaionaro authored
441 442
				'endDateWas' => @formatDate(@$a['EndDate']),
				'endDateBecame' => @$_GET['newEndDate'],
redmine authored
443 444
				'account' => $account,
				'account-manager' => $account_manager,
xaionaro authored
445
				'change-date' => $_REQUEST['change-date'],
redmine authored
446 447 448 449 450 451 452 453 454 455
			);
		}
		switch ($_GET['object-type']) {
			case 'employee':
				$employee_id = @$_GET['employee-id'];
				if (empty($employee_id))
					die('employee_id is empty');

				$employee = json_decode(file_get_contents("https://cps.mephi.ru/?cmd=getemployeeinfo&e_id=".urlencode($employee_id) ), 1)[$employee_id]; 

xaionaro authored
456 457 458 459 460 461 462
				$mySids = array();
				foreach ($user->employee->WORKPOSITIONS as $idx => $workposition) {
					$mySids[$workposition->s_id] = true;
				}
				//print_r($user);
				//die();

redmine authored
463
				foreach ($employee['WORKPOSITIONS'] as $idx => $workposition) {
xaionaro authored
464
					if (empty($subordinate_units[$workposition['s_id']]) && ($mySids[$workposition['s_id']] !== true)) {
redmine authored
465 466 467 468 469 470 471 472
						unset($employee['WORKPOSITIONS'][$idx]);
					}
				}

				if (empty($employee['WORKPOSITIONS'])) {
					die("Нет должностей данного сотрудника в вашем подчинении");
				}

xaionaro authored
473 474
				if ($employee_id == $user->employee->e_id) {
					$newData = newFormularData((int)$_REQUEST['signer-appointment-id']);
redmine authored
475 476 477
					if (!empty($newData)) {
						$datas[] = $newData;
					}
xaionaro authored
478 479 480 481 482 483 484
				} else {
					foreach ($employee['WORKPOSITIONS'] as $workposition) {
						$newData = newFormularData($workposition['w_id']);
						if (!empty($newData)) {
							$datas[] = $newData;
						}
					}
redmine authored
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
				}

//				$unit;
				break;
			case 'unit':
				$unit_id = @$_GET['unit-id'];
				if (empty($unit_id))
					die('unit_id is empty');

				if (empty($subordinate_units[$unit_id]))
					die('У вас нет прав для доступа к данному подразделению');

				$unit_id_asu = preg_replace('/[^0-9]+/', '', $unit_id);

				$unit_ids = array($unit_id_asu);
				$check_unit_ids = array($unit_id_asu);
				while ($id = array_shift($check_unit_ids)) {
					$units = json_decode(file_get_contents('https://sd.mephi.ru/api/1/units.json?from_local_db=true&active_only=true&api_key='.SDAPI_KEY.'&filter_ParentId='.$id), 1);
xaionaro authored
503
					//error_log('https://sd.mephi.ru/api/1/units.json?from_local_db=true&active_only=true&api_key='.SDAPI_KEY.'&filter_ParentId='.$id);
redmine authored
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
					foreach ($units as &$unit) {
						array_push($unit_ids, $unit['id']);
						array_push($check_unit_ids, $unit['id']);
					}
				}

				$formulars = array();

				foreach($unit_ids as $unit_id) {
					$l_formulars = json_decode(file_get_contents('https://sd.mephi.ru/api/1/formulars.json?from_local_db=true&active_only=true&api_key='.SDAPI_KEY.'&filter_OrgDiv='.$unit_id), 1);
					$formulars = array_merge($formulars, $l_formulars);
				}

				foreach ($formulars as &$formular) {
					$newData = newFormularData($formular['StfCardId']);
					if (!empty($newData)) {
						$datas[] = $newData;
					}
				}

				break;
			default:
				die('Unknown object type: '.$_GET['object-type']);
		}

		break;
	}

	default:
		die("Don't know how to generate PDF for ".$file);
}

//print_r($_GET); print_r($user); print_r($datas);die();

xaionaro authored
538 539 540 541 542
/*foreach ($datas as $data) {
	print $data['appointment-full']."\t".$data['employee-full']."\n";
}
die();*/

redmine authored
543 544 545 546
if (empty($datas)) {
	die("Нет данных для обработки");
}

xaionaro authored
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
$monthName = array(
	1 => 'январь',
	2 => 'февраль',
	3 => 'март',
	4 => 'апрель',
	5 => 'май',
	6 => 'июнь',
	7 => 'июль',
	8 => 'август',
	9 => 'сентябрь',
	10 => 'октябрь',
	11 => 'ноябрь',
	12 => 'декабрь',
);

redmine authored
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
foreach ($datas as $data) {

	$tempdir = tempdir();

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

	exec('cp -a /var/www/'.$_SERVER['SERVER_NAME'].'/ut-tex/mephimemo "'.$tempdir.'/"');
	chdir($tempdir.'/mephimemo');
	file_put_contents("request.data", print_r($data, true));

	foreach ($data as $key => &$value)
		$value = latexSpecialChars($value);

	file_put_contents("request.data.fixed", print_r($data, true));

xaionaro authored
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
	foreach (array('change') as $key) {
		$key .= '-date';
		if (empty($data[$key])) {
			$data[$key] = '«\_\_\_» \_\_\_\_\_\_\_\_\_\_ 20\_\_\_г';
			continue;
		}

		$date = split('\.', $data[$key]);
		if (empty(date[2])) {
			$data[$key] = '«\_\_\_» \_\_\_\_\_\_\_\_\_\_ 20\_\_\_г';
			continue;
		}

		$data[$key] = '«'.$date[0].'» '.$inflect->getInflectNoun($monthName[$date[1]+0], 0).' '.$date[2].'г';
	}

redmine authored
594 595 596
	switch ($file) {
		case 'form/updatesalary':
		case 'form/updateenddate':
xaionaro authored
597
			$header = '\mmsagreementheader{'.$data['of-prorector'].'}{'.$data['attorney-date'].'}{'.$data['attorney-code'].'}{'.$data['employee-full'].'}{'.$data['employee-appointment'].'}{'.$data['employment-contract-date'].'}{'.$data['employment-contract-code'].'}{'.$data['change-date'].'}';
redmine authored
598 599 600 601 602 603 604 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
			$footer = '\mmsagreementfooter{'.$data['prorector'].'}{'.$data['of-unit'].'}{'.$data['unit-head'].'}{'.$data['account'].'}{'.$data['account-manager'].'}{}{}{'.$data['employee'].'}';
			break;
	}

	$body_template = file_get_contents('template/'.$file.'.tex');
	$body          = body_parse($body_template, $data);

	file_put_contents('header.tex',		$header);
	file_put_contents('body.tex',		$body);
	file_put_contents('footer.tex',		$footer);
	file_put_contents('responsible.tex',	'');
	file_put_contents('urlqr.tex',		'');

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

	if ( empty($pdf_content) )
	{
		error('Can not create 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);
}

header('Content-type: application/pdf');

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

?>