This repository has been archived by the owner on Nov 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 289
/
class.MqManager.php
executable file
·363 lines (329 loc) · 13.8 KB
/
class.MqManager.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
266
267
268
269
270
271
272
273
274
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
<?php
/*
* Copyright 2007-2012 Charles du Jeu <contact (at) cdujeu.me>
* This file is part of Pydio.
*
* Pydio is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <http://pyd.io/>.
*/
defined('AJXP_EXEC') or die( 'Access not allowed');
// DL and install install vendor (composer?) https://github.com/Devristo/phpws
/**
* Websocket JS Sample
*
* var websocket = new WebSocket("ws://serverURL:8090/echo");
websocket.onmessage = function(event){console.log(event.data);};
*
* new PeriodicalExecuter(function(pe){
var conn = new Connexion();
conn.setParameters($H({get_action:'client_consume_channel',channel:'nodes:0',client_id:'toto'}));
conn.onComplete = function(transport){PydioApi.getClient().parseXmlMessage(transport.responseXML);};
conn.sendAsync();
}, 5);
*
* @package AjaXplorer_Plugins
* @subpackage Core
*
*/
class MqManager extends AJXP_Plugin
{
private $wsClient;
/**
* @var AJXP_MessageExchanger;
*/
private $msgExchanger = false;
private $useQueue = false ;
public function init($options)
{
parent::init($options);
$this->useQueue = $this->pluginConf["USE_QUEUE"];
try {
$this->msgExchanger = ConfService::instanciatePluginFromGlobalParams($this->pluginConf["UNIQUE_MS_INSTANCE"], "AJXP_MessageExchanger");
if(AuthService::$bufferedMessage != null && AuthService::getLoggedUser() != null){
$this->sendInstantMessage(AuthService::$bufferedMessage, ConfService::getCurrentRepositoryId(), AuthService::getLoggedUser()->getId());
AuthService::$bufferedMessage = null;
}
} catch (Exception $e) {}
}
public function sendToQueue(AJXP_Notification $notification)
{
if (!$this->useQueue) {
$this->logDebug("SHOULD DISPATCH NOTIFICATION ON ".$notification->getNode()->getUrl()." ACTION ".$notification->getAction());
AJXP_Controller::applyHook("msg.notification", array(&$notification));
} else {
if($this->msgExchanger) $this->msgExchanger->publishWorkerMessage("user_notifications", $notification);
}
}
public function consumeQueue($action, $httpVars, $fileVars)
{
if($action != "consume_notification_queue" || $this->msgExchanger === false) return;
$queueObjects = $this->msgExchanger->consumeWorkerChannel("user_notifications");
if (is_array($queueObjects)) {
$this->logDebug("Processing notification queue, ".count($queueObjects)." notifs to handle");
foreach ($queueObjects as $notification) {
AJXP_Controller::applyHook("msg.notification", array(&$notification));
}
}
}
/**
* @param AJXP_Node $origNode
* @param AJXP_Node $newNode
* @param bool $copy
*/
public function publishNodeChange($origNode = null, $newNode = null, $copy = false)
{
$content = "";$repo = "";$targetUserId=null; $nodePathes = array();
$update = false;
if ($newNode != null) {
$repo = $newNode->getRepositoryId();
$targetUserId = $newNode->getUser();
$nodePathes[] = $newNode->getPath();
$update = false;
$data = array();
if ($origNode != null && !$copy) {
$update = true;
$data[$origNode->getPath()] = $newNode;
} else {
$data[] = $newNode;
}
$content = AJXP_XMLWriter::writeNodesDiff(array(($update?"UPDATE":"ADD") => $data));
}
if ($origNode != null && ! $update && !$copy) {
$repo = $origNode->getRepositoryId();
$targetUserId = $origNode->getUser();
$nodePathes[] = $origNode->getPath();
$content = AJXP_XMLWriter::writeNodesDiff(array("REMOVE" => array($origNode->getPath())));
}
if (!empty($content) && $repo != "") {
$this->sendInstantMessage($content, $repo, $targetUserId, null, $nodePathes);
}
}
public function sendInstantMessage($xmlContent, $repositoryId, $targetUserId = null, $targetGroupPath = null, $nodePathes = array())
{
if ($repositoryId === AJXP_REPO_SCOPE_ALL) {
$userId = $targetUserId;
} else {
$scope = ConfService::getRepositoryById($repositoryId)->securityScope();
if ($scope == "USER") {
if($targetUserId) $userId = $targetUserId;
else $userId = AuthService::getLoggedUser()->getId();
} else if ($scope == "GROUP") {
$gPath = AuthService::getLoggedUser()->getGroupPath();
} else if (isSet($targetUserId)) {
$userId = $targetUserId;
} else if (isSet($targetGroupPath)) {
$gPath = $targetGroupPath;
}
}
// Publish for pollers
$message = new stdClass();
$message->content = $xmlContent;
if(isSet($userId)) {
$message->userId = $userId;
}
if(isSet($gPath)) {
$message->groupPath = $gPath;
}
if(count($nodePathes)) {
$message->nodePathes = $nodePathes;
}
if ($this->msgExchanger) {
$this->msgExchanger->publishInstantMessage("nodes:$repositoryId", $message);
}
/*
// Publish on NSQ
require_once(AJXP_INSTALL_PATH."core/classes/vendor/autoload.php");
$nsq = new nsqphp\nsqphp;
$nsq->publishTo("localhost", 1);
$nsq->publish('pydio', new nsqphp\Message\Message(json_encode(array('msg' => 'im', 'run' => $message))));
*/
// Publish for WebSockets
$configs = $this->getConfigs();
if ($configs["WS_SERVER_ACTIVE"]) {
require_once($this->getBaseDir()."/vendor/phpws/websocket.client.php");
// Publish for websockets
$input = array("REPO_ID" => $repositoryId, "CONTENT" => "<tree>".$xmlContent."</tree>");
if(isSet($userId)){
$input["USER_ID"] = $userId;
} else if(isSet($gPath)) {
$input["GROUP_PATH"] = $gPath;
}
if(count($nodePathes)) {
$input["NODE_PATHES"] = $nodePathes;
}
$input = serialize($input);
$msg = WebSocketMessage::create($input);
if (!isset($this->wsClient)) {
$this->wsClient = new WebSocket("ws://".$configs["WS_SERVER_BIND_HOST"].":".$configs["WS_SERVER_BIND_PORT"].$configs["WS_SERVER_PATH"]);
$this->wsClient->addHeader("Admin-Key", $configs["WS_SERVER_ADMIN"]);
@$this->wsClient->open();
}
@$this->wsClient->sendMessage($msg);
}
}
/**
* @param $action
* @param $httpVars
* @param $fileVars
*
*/
public function clientChannelMethod($action, $httpVars, $fileVars)
{
if(!$this->msgExchanger) return;
switch ($action) {
case "client_register_channel":
$this->msgExchanger->suscribeToChannel($httpVars["channel"], $httpVars["client_id"]);
break;
case "client_unregister_channel":
$this->msgExchanger->unsuscribeFromChannel($httpVars["channel"], $httpVars["client_id"]);
break;
case "client_consume_channel":
if (AuthService::usersEnabled()) {
$user = AuthService::getLoggedUser();
if ($user == null) {
AJXP_XMLWriter::header();
AJXP_XMLWriter::requireAuth();
AJXP_XMLWriter::close();
return;
}
$GROUP_PATH = $user->getGroupPath();
if($GROUP_PATH == null) $GROUP_PATH = false;
$uId = $user->getId();
} else {
$GROUP_PATH = '/';
$uId = 'shared';
}
$currentRepository = ConfService::getCurrentRepositoryId();
$currentRepoMasks = array(); $regexp = null;
AJXP_Controller::applyHook("role.masks", array($currentRepository, &$currentRepoMasks, AJXP_Permission::READ));
if(count($currentRepoMasks)){
$regexps = array();
foreach($currentRepoMasks as $path){
$regexps[] = '^'.preg_quote($path, '/');
}
$regexp = '/'.implode("|", $regexps).'/';
}
$channelRepository = str_replace("nodes:", "", $httpVars["channel"]);
if($channelRepository != $currentRepository){
AJXP_XMLWriter::header();
echo "<require_registry_reload repositoryId=\"$currentRepository\"/>";
AJXP_XMLWriter::close();
return;
}
$data = $this->msgExchanger->consumeInstantChannel($httpVars["channel"], $httpVars["client_id"], $uId, $GROUP_PATH);
if (count($data)) {
AJXP_XMLWriter::header();
ksort($data);
foreach ($data as $messageObject) {
if(isSet($regexp) && isSet($messageObject->nodePathes)){
$pathIncluded = false;
foreach($messageObject->nodePathes as $nodePath){
if(preg_match($regexp, $nodePath)){
$pathIncluded = true;
break;
}
}
if(!$pathIncluded) continue;
}
echo $messageObject->content;
}
AJXP_XMLWriter::close();
}
break;
default:
break;
}
}
public function wsAuthenticate($action, $httpVars, $fileVars)
{
$this->logDebug("Entering wsAuthenticate");
$configs = $this->getConfigs();
if (!isSet($httpVars["key"]) || $httpVars["key"] != $configs["WS_SERVER_ADMIN"]) {
throw new Exception("Cannot authentify admin key");
}
$user = AuthService::getLoggedUser();
if ($user == null) {
$this->logDebug("Error Authenticating through WebSocket (not logged)");
throw new Exception("You must be logged in");
}
$xml = AJXP_XMLWriter::getUserXML($user);
// add groupPath
if ($user->getGroupPath() != null) {
$groupString = "groupPath=\"".AJXP_Utils::xmlEntities($user->getGroupPath())."\"";
$xml = str_replace("<user id=", "<user {$groupString} id=", $xml);
}
$this->logDebug("Authenticating user ".$user->id." through WebSocket");
AJXP_XMLWriter::header();
echo $xml;
AJXP_XMLWriter::close();
}
public function switchWebSocketOn($params)
{
$wDir = $this->getPluginWorkDir(true);
$pidFile = $wDir.DIRECTORY_SEPARATOR."ws-pid";
if (file_exists($pidFile)) {
$pId = file_get_contents($pidFile);
$unixProcess = new UnixProcess();
$unixProcess->setPid($pId);
$status = $unixProcess->status();
if ($status) {
throw new Exception("Web Socket server seems to already be running!");
}
}
$host = escapeshellarg($params["WS_SERVER_BIND_HOST"]);
$port = escapeshellarg($params["WS_SERVER_BIND_PORT"]);
$path = escapeshellarg($params["WS_SERVER_PATH"]);
$cmd = ConfService::getCoreConf("CLI_PHP")." ws-server.php -host=".$host." -port=".$port." -path=".$path;
chdir(AJXP_INSTALL_PATH.DIRECTORY_SEPARATOR.AJXP_PLUGINS_FOLDER.DIRECTORY_SEPARATOR."core.mq");
$process = AJXP_Controller::runCommandInBackground($cmd, null);
if ($process != null) {
$pId = $process->getPid();
$wDir = $this->getPluginWorkDir(true);
file_put_contents($wDir.DIRECTORY_SEPARATOR."ws-pid", $pId);
return "SUCCESS: Started WebSocket Server with process ID $pId";
}
return "SUCCESS: Started WebSocket Server";
}
public function switchWebSocketOff($params)
{
$wDir = $this->getPluginWorkDir(true);
$pidFile = $wDir.DIRECTORY_SEPARATOR."ws-pid";
if (!file_exists($pidFile)) {
throw new Exception("No information found about WebSocket server");
} else {
$pId = file_get_contents($pidFile);
$unixProcess = new UnixProcess();
$unixProcess->setPid($pId);
$unixProcess->stop();
unlink($pidFile);
}
return "SUCCESS: Killed WebSocket Server";
}
public function getWebSocketStatus()
{
$wDir = $this->getPluginWorkDir(true);
$pidFile = $wDir.DIRECTORY_SEPARATOR."ws-pid";
if (!file_exists($pidFile)) {
return "OFF";
} else {
$pId = file_get_contents($pidFile);
$unixProcess = new UnixProcess();
$unixProcess->setPid($pId);
$status = $unixProcess->status();
if($status) return "ON";
else return "OFF";
}
}
}