/
ActionRunner.php
265 lines (216 loc) · 8.73 KB
/
ActionRunner.php
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
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
<?php
namespace ru\yukosh\actions;
require_once __DIR__ . '/ActionsFactory.php';
require_once __DIR__ . '/vendor/autoload.php';
/**
* ActionRunner class
*
* Action runner via HTTP protocol, command-line interface or e-mail
*
* @package Actions
*/
class ActionRunner {
/**
* Command-line running arguments
*
* @var array
*/
private $_aRunningArguments = [];
public function __construct(array $_aArgs) {
$this->_aRunningArguments = $_aArgs;
}
/**
* Recognizes running type - HTTP or command-line
*
* @return boolean Is it command-line launch or not
*/
private function isCommandLineLaunch() {
return php_sapi_name() == 'cli' || (isset($_SERVER['argc']) &&
is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0);
}
/**
* Handles request, parses arguments, instantiate action and executes it
*
* @throws ActionException
*/
public function run() {
$aArguments = [];
$xActionName = '';
$bHttpCall = false;
if ($this->isCommandLineLaunch()) {
// Command-line call
if (count($this->_aRunningArguments) > 1) {
$xActionName = $this->_aRunningArguments[1];
if ($xActionName == '__email__') {
// E-mail call
$aResult = [];
$aActions = $this->_checkEmail();
if (!empty($aActions)) {
foreach ($aActions as $aCurrentAction) {
$sPathAlias = '';
if (isset($aCurrentAction['registerPath'])) {
ActionsFactory::registerPath($aCurrentAction['registerPath']['alias'],
$aCurrentAction['registerPath']['path']);
$sPathAlias = $aCurrentAction['registerPath']['alias'] . '/';
}
$aArguments = array_slice($this->_aRunningArguments, 2);
$aCurrentAction['args'] = array_merge($aCurrentAction['args'], $aArguments);
$aResult[] = ['name' => $sPathAlias . $aCurrentAction['name'], 'args' => $aCurrentAction['args']];
}
$xActionName = $aResult;
}
else {
// No Actions to execute...
return;
}
}
else {
$aArguments = array_slice($this->_aRunningArguments, 2);
}
}
}
else {
// HTTP call
$bHttpCall = true;
$aGetParams = $this->_parseGetParams($_SERVER['QUERY_STRING']);
if (isset($aGetParams['action'])) {
$xActionName = $aGetParams['action'];
unset($aGetParams['action']);
$aArguments = $aGetParams;
}
}
if (!empty($xActionName)) {
$oFactory = ActionsFactory::getInstance();
if (is_string($xActionName)) {
$xActionName = [['name' => $xActionName, 'args' => $aArguments]];
}
foreach ($xActionName as $aAction) {
// Fetch and execute action
$oAction = $oFactory->get($aAction['name']);
// Action must be "streamable" to return string result
if (is_a($oAction, 'ru\yukosh\actions\IStreamable')) {
call_user_func_array(array($oAction, ($bHttpCall) ? 'httpCall' : 'call'), $aAction['args']);
echo $sResult = $oAction->getResult();
}
else {
throw new ActionException($aAction['name'] . ' action should implement IStreamable interface');
}
}
}
}
/**
* Parses query string to array of parameters
* We can't use $_GET array because PHP transforms "." to "_" in parameters names
*
* @param $_sQueryString Query string
* @returns array Array of parameters
*/
private function _parseGetParams($_sQueryString) {
$aResult = [];
$aParams = explode('&', $_sQueryString);
foreach ($aParams as $sParam) {
$aParam = explode('=', $sParam);
if (count($aParam) == 2) {
$aResult[$aParam[0]] = urldecode($aParam[1]);
}
else {
$aResult[] = urldecode($aParam[0]);
}
}
return $aResult;
}
/**
* Checks e-mail and searches Actions that should be run
*
* @return array Array of Actions to execute
* @throws ActionException
*/
private function _checkEmail() {
$sConfig = file_get_contents('EmailCheckingConfig.json');
$aConfig = json_decode($sConfig, true);
// Get accounts
$aAccountsConfig = $aConfig['accounts'];
// Get Actions
$aActionsConfig = $aConfig['actions'];
// Select Actions to run
$aActionsToCheck = [];
// Actions to run
$aActionsToRun = [];
foreach ($aActionsConfig as $aActionConfig) {
// Check "check" parameter
$oCron = Cron\CronExpression::factory($aActionConfig['check']);
if ($oCron->isDue()) {
$aActionsToCheck[] = $aActionConfig;
}
}
// Check selected Actions for running letter
foreach ($aActionsToCheck as $aActionConfig) {
$aAccountConfig = $aAccountsConfig[$aActionConfig['account']];
if ($oConnection = imap_open($aAccountConfig['server'],
$aAccountConfig['user'], $aAccountConfig['password'])) {
$oCheck = imap_check($oConnection);
if ($oCheck->Nmsgs > 0) {
$aEmails = imap_search($oConnection, 'UNSEEN');
foreach ($aEmails as $iEmailNumber) {
$oOverview = imap_fetch_overview($oConnection, $iEmailNumber)[0];
// Match letter and Action run parameters
$bResult = preg_match('/' . $aActionConfig['email']['fromRegexp'] . '/i', $oOverview->from);
// Check subject patterns
$xCheckSubjectPatternsResult = $this->_checkSubjectPatterns($oOverview->subject,
$aActionConfig['email']['subjectRegexp']);
$bResult = $bResult && $xCheckSubjectPatternsResult !== false;
if ($bResult) {
$aArguments = [
$oOverview,
imap_body($oConnection, $iEmailNumber),
imap_fetchstructure($oConnection, $iEmailNumber)
];
if (is_array($xCheckSubjectPatternsResult) && count($xCheckSubjectPatternsResult) > 0) {
$aArguments[] = $xCheckSubjectPatternsResult;
}
$aAction = [
'name'=> $aActionConfig['name'],
'args' => $aArguments
];
if (isset($aActionConfig['registerPath'])) {
$aAction['registerPath'] = $aActionConfig['registerPath'];
}
$aActionsToRun[] = $aAction;
imap_delete($oConnection, $iEmailNumber);
}
}
}
imap_close($oConnection, CL_EXPUNGE);
}
else {
throw new ActionException('Can\'t connect to mail server');
}
}
return $aActionsToRun;
}
/**
* Checks subject patterns and returns matches
*
* @param string $_sSubject Letter subject
* @param string|array $_xPatterns Subject pattern or array of patterns
* @return array|bool False if appropriate subject haven't been found or array of matches
*/
private function _checkSubjectPatterns($_sSubject, $_xPatterns) {
$aPatterns = (!is_array($_xPatterns)) ? [$_xPatterns] : $_xPatterns;
foreach ($aPatterns as $sPattern) {
$sSubject = trim($_sSubject);
$sSubject = preg_replace('/ +/', ' ', $sSubject);
if (preg_match('/' . $sPattern . '/i', $sSubject, $aMatches)) {
return array_slice($aMatches, 1);
}
}
return false;
}
}
$oLauncher = new ActionRunner((isset($argv)) ? $argv : []);
try {
$oLauncher->run();
}
catch (ActionException $oException) {
echo $oException->getMessage();
}