cron-unconfirmednotes.php 7.05 KB
<?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";
require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Api/IssueStatus.php";
require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Api/User.php";
require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Api/Issue.php";
require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Api/Attachment.php";
require_once "lib/3rdparty/php-redmine-api/lib/Redmine/Client.php";

require_once "lib/3rdparty/Inflect/Inflect.php";

require_once "config.php";

define('IMG_SCALE',	0.3);

$redmine = new Redmine\Client('https://redmine.ut.mephi.ru', REDMINE_API);
$inflect = new Inflect();

$answer = $redmine->api('issue')->all(array(
		'project_id'		=> '15971', 			// project "hpc-request"
		'status_id'		=> STATUSID_NEW,
	));

if (!isset($answer['issues']))
	exit(0);

$time = time();

/*
// http://stackoverflow.com/questions/1707801/making-a-temporary-dir-for-unpacking-a-zipfile-into
function tempdir() {
	$tempfile=tempnam(sys_get_temp_dir(),'');
	$tempfile=str_replace("'", "", $tempfile);
	if (file_exists($tempfile)) { unlink($tempfile); }
	print "|".$tempfile."|\n";
	mkdir($tempfile);
	if (is_dir($tempfile)) { return $tempfile; }

	return NULL;
}
*/

function sendConfirmationRequest($issueId, $recipient, $toName, $authorName, $pdf) {

	//// CONVERTING PDF -> PNG ////

	$im = new Imagick();

	$im->setResolution(((float)300)*IMG_SCALE , ((float)300)*IMG_SCALE);
	$im->readImageBlob($pdf);
	$im->setImageFormat('png');
	$png = $im->getImageBlob(); 
	$im->clear(); 
	$im->destroy();

	//// BOUNDARY & SIGNATURE////

	$boundary  = sha1(time().'XbwwamQgIT70IWqzFDzhi8MmoU');
	$signature = sha1($issueId . SECRET);

	//// HEADERS ////

	$headers = str_replace("\n", "\r\n",
'From: =?utf-8?B?'.base64_encode('Система «Задачи»').'?= <tasks@mephi.ru>
Mime-Version: 1.0
Content-Type: multipart/related; boundary="'.$boundary.'"; type="text/html"
');

	//// BODY ////

	$body = str_replace("\n", "\r\n",
'--'.$boundary.'
Content-Type: text/html; charset="UTF-8"

Сотрудник '.$authorName.' подготовил(а) проект служебной записки (см. ниже):<br>
<br>
<br>
<div style="width:740px">
	<div style="font-size:80px;display:inline-block;text-align:center"><a style="text-decoration:none;color:green" href="http://ut.mephi.ru/decide-note.php?issueId='.$issueId.'&action=agree&signature='.$signature.'">&#10003;<br><span style="font-size:10px">(подтвердить)</span></a></div>
	<div style="font-size:80px;display:inline-block;text-align:center"><a style="text-decoration:none;color:red"   href="http://ut.mephi.ru/decide-note.php?issueId='.$issueId.'&action=decline&signature='.$signature.'">✗<br><span style="font-size:10px">(отклонить)</span></a></div>

	<img style="border:1px dotted #aaa;margin:0;padding:0" src="cid:note-'.$issueId.'@tasks.mephi.ru" alt="Проект служебной записки"><br>

	<div style="font-size:80px;display:inline-block;text-align:center"><a style="text-decoration:none;color:green" href="http://ut.mephi.ru/decide-note.php?issueId='.$issueId.'&action=agree&signature='.$signature.'">&#10003;<br><span style="font-size:10px">(подтвердить)</span></a></div>
	<div style="font-size:80px;display:inline-block;text-align:center"><a style="text-decoration:none;color:red"   href="http://ut.mephi.ru/decide-note.php?issueId='.$issueId.'&action=decline&signature='.$signature.'">✗<br><span style="font-size:10px">(отклонить)</span></a></div>
</div>
<hr style="width:100%;padding-top:10px;border:none;border-bottom:1px solid #aaa">
Служба технической поддержки: <a href="tasks@mephi.ru">tasks@mephi.ru</a>

--'.$boundary.'
Content-ID: <note-'.$issueId.'@tasks.mephi.ru>
Content-Type: image/png
Content-Transfer-Encoding: BASE64

'.wordwrap(base64_encode($png), 70, "\n").'

--'.$boundary.'--
');

	//// SENDING ////

	//print_r(array($recipient, "Проект служебной записки №".$issueId, $body, $headers));die();
	mail($recipient, "Проект служебной записки ".$toName." №".$issueId.' (на согласование)', $body, $headers);
}

/*$tmp = tempdir();
if (empty($tmp))
	die('Cannot create temporary directory');

chdir($tmp);*/

foreach ($answer['issues'] as &$issue) {
	$issues_full = $redmine->api('issue')->show($issue['id'], array('include' => 'attachments'));
	$issue_full  = reset($issues_full);

	//print_r($redmine->api('user')->show(3));
	//print_r($issue_full);die();

	$author      = $redmine->api('user')->show($issue['author'     ]['id'])['user'];
	$assignedTo  = $redmine->api('user')->show($issue['assigned_to']['id'])['user'];

	$pdfUrl = NULL;
	$have_memo = 0;
	if (isset($issue_full['attachments']))
		foreach ($issue_full['attachments'] as &$attachment)
			if ($attachment['filename'] == 'sluzhebnaya_zapiska.pdf' || $attachment['description'] == 'Служебная записка') {
				$have_memo = 1;
				$pdfUrl    = str_replace("redmine.ut.mephi.ru", "tasks.mephi.ru", $attachment['content_url']);
				break;
			}

	if ($have_memo != 1)
		continue;

	$recipientId = NULL;
	foreach ( $issue['custom_fields'] as $cf) {
		if ($cf['id'] == 95) {
			$recipientId = $cf['value'];
			break;
		}
	}

	if (is_null($recipientId) || ($recipientId == $assignedTo['id'])) {
		continue;
	}

	$recipient = $redmine->api('user')->show($recipientId);
	if (empty($recipient['user'])) {
		mail('admin@ut.mephi.ru', 'Got error on cron-unconfirmednotes.php (1) #'.$issue['id'], print_r($_GET, 1).print_r($recipient ,1));
		continue;
	}
	$recipient = $recipient['user'];

	if (empty($recipient['mail'])) {
		mail('admin@ut.mephi.ru', 'Got error on cron-unconfirmednotes.php #'.$issue['id'], print_r($_GET, 1));
		continue;
	}


	/*
	$fname = 'note-'.$issue['id'].'.pdf';

	$f = fopen($fname, 'w');
	if ($f === NULL) {
		die('Cannot open file for editing');
	}*/

	$c = curl_init(); 

	curl_setopt($c, CURLOPT_URL,			$pdfUrl); 
	curl_setopt($c, CURLOPT_HTTPHEADER,		array('X-Redmine-API-Key: '.REDMINE_API));
	curl_setopt($c, CURLOPT_TIMEOUT,		60);
	//curl_setopt($c, CURLOPT_FILE,			$f); 
	curl_setopt($c, CURLOPT_FOLLOWLOCATION,		true);
	curl_setopt($c, CURLOPT_RETURNTRANSFER,		true);  

	$note = curl_exec($c);
	if ($note === FALSE) {
		echo("Cannot download an attachment \"".$pdfUrl."\": ".curl_error($c)."\n");
		continue;
	}

	curl_close($c);

	$toNameWords = explode(' ', $inflect->getInflectName($recipient['lastname'].' '.$recipient['firstname'], 1));
	$toName      = $toNameWords[0].' '.mb_substr($toNameWords[1], 0, 1).'. '.mb_substr($toNameWords[2], 0, 1).'.';

	//$assignedTo['mail'] = 'dyokunev@mephi.ru';
	sendConfirmationRequest($issue['id'], $assignedTo['mail'], $toName, '<a href="http://new.voip.mephi.ru/subscribers/?q='.explode('@', $author['mail'])[0].'" target="_blank">'.$author['firstname'].' '.$author['lastname'].'</a>', $note);

	$redmine->api('issue')->update($issue['id'], array('status_id' => STATUSID_QUEUED));
}

/*
chdir("/");
system("rm --one-file-system -- '".$tmp."'/* 2>/dev/null");
system("rmdir -- '".$tmp."'");
*/

?>