Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
connectionmanager.php
1<?php
2
4
15use Bitrix\Dav\Internals\DavConnectionTable;
16use Bitrix\Dav\Internals\EO_DavConnection_Collection;
26use CDavConnection;
27use Exception;
28
30{
31 public const INIT_STATUS = [
32 'existed' => 'existed',
33 'created' => 'created',
34 'activated' => 'activated',
35 ];
36
38 private $mapperFactory;
39
40 public function __construct()
41 {
42 $this->mapperFactory = ServiceLocator::getInstance()->get('calendar.service.mappers.factory');
43 }
44
56 public function getConnection(Role $owner, string $accountType, array $optionalFilter = []): ?Connection
57 {
58 $connection = null;
59 $connectionData = $this->getConnectionsData($owner, [$accountType], $optionalFilter);
60 foreach ($connectionData as $con)
61 {
62 $connection = $con;
63 break;
64 }
65
66 return $connection
67 ? (new BuilderConnectionFromDM($connection))->build()
68 : null
69 ;
70 }
71
83 public function getConnectionsData(
84 Role $owner,
85 array $type,
86 array $optionalFilter = []
87 ): ?EO_DavConnection_Collection
88 {
89 $statement = DavConnectionTable::query()
90 ->setSelect(['*'])
91 ->addFilter('=ENTITY_TYPE', $owner->getType())
92 ->addFilter('=ENTITY_ID', $owner->getId())
93 ->addFilter('=ACCOUNT_TYPE', $type)
94 ;
95
96 if (!empty($optionalFilter))
97 {
98 foreach ($optionalFilter as $key => $value)
99 {
100 $statement->addFilter($key, $value);
101 }
102 }
103
104 return $statement->fetchCollection() ?: null;
105 }
106
112 public function update(Connection $connection): Result
113 {
114 try
115 {
116 $lastModified = new DateTime();
117 $fields = [
118 'ENTITY_TYPE' => $connection->getOwner()->getType(),
119 'ENTITY_ID' => $connection->getOwner()->getId(),
120 'ACCOUNT_TYPE' => $connection->getVendor()->getCode(),
121 'SYNC_TOKEN' => $connection->getToken(),
122 'NAME' => $connection->getName(),
123 'SERVER_SCHEME' => $connection->getServer()->getScheme(),
124 'SERVER_HOST' => $connection->getServer()->getHost(),
125 'SERVER_PORT' => $connection->getServer()->getPort(),
126 'SERVER_USERNAME' => $connection->getServer()->getUserName(),
127 'SERVER_PASSWORD' => $connection->getServer()->getPassword(),
128 'SERVER_PATH' => $connection->getServer()->getBasePath(),
129 'MODIFIED' => $lastModified,
130 'SYNCHRONIZED' => $lastModified,
131 'LAST_RESULT' => $connection->getStatus(),
132 'IS_DELETED' => $connection->isDeleted() ? 'Y' : 'N'
133 ];
134 $data = DavConnectionTable::update($connection->getId(), $fields)->getData();
135 $data['ID'] = $connection->getId();
136
137 return (new Result())->setData($data);
138 }
139 catch (Exception $e)
140 {
141 return (new Result())->addError(new Error($e->getMessage()));
142 }
143 }
144
154 public function initConnection(Role $owner, string $accountType, string $server): Result
155 {
156 $result = new Result();
157 $resultData = [];
158 try {
159 if (!Loader::includeModule('dav'))
160 {
161 throw new LoaderException('Module dav is required');
162 }
163 $accountName = $this->getSocialUserLogin($owner, $accountType);
164 if ($connection = $this->getConnection($owner, $accountType, ['=NAME' => $accountName]))
165 {
166 if ($connection->isDeleted())
167 {
168 $connection->setDeleted(false);
169 $this->update($connection);
170 $resultData['status'] = self::INIT_STATUS['activated'];
171 }
172 else
173 {
174 $resultData['status'] = self::INIT_STATUS['existed'];
175 }
176 }
177 else
178 {
179 $connection = $this->createConnection(
180 $owner,
181 $accountType,
182 $accountName,
183 $server,
184 );
185 $resultData['status'] = self::INIT_STATUS['created'];
186 }
187 $resultData['connection'] = $connection;
188 }
189 catch (Exception $e)
190 {
191 $result->addError(new Error($e->getMessage()));
192 }
193
194 $result->setData($resultData);
195
196 return $result;
197 }
198
212 protected function createConnection(
213 Role $owner,
214 string $type,
215 string $name,
216 string $serverPath
217 ): Connection
218 {
219 $fields = [
220 'ENTITY_TYPE' => $owner->getType(),
221 'ENTITY_ID' => $owner->getId(),
222 'ACCOUNT_TYPE' => $type,
223 'NAME' => $name,
224 'SERVER' => $serverPath,
225 ];
226 if ($connectionId = CDavConnection::Add($fields))
227 {
228 return $this->mapperFactory->getConnection()->getById($connectionId);
229 }
230
231 throw new BaseException('Error of create new Dav connection');
232 }
233
244 protected function getSocialUserLogin(Role $owner, string $accountType): string
245 {
246 $user = UserTable::query()
247 ->addFilter('=USER_ID', $owner->getId())
248 ->addFilter('=EXTERNAL_AUTH_ID', $accountType)
249 ->setSelect(['LOGIN'])
250 ->fetch();
251
252 return $user['LOGIN'] ?? '';
253 }
254
266 public function deactivateConnection(Connection $connection): Result
267 {
268 $result = new Result();
269
270 if (!Loader::includeModule('dav'))
271 {
272 $result->addError(new Error('Module dav required'));
273 }
274
275 $updateResult = DavConnectionTable::update($connection->getId(), [
276 'IS_DELETED' => 'Y',
277 'SYNC_TOKEN' => null,
278 ]);
279 if ($updateResult->isSuccess())
280 {
281 $this->unsubscribeConnection($connection);
282
283 $accountType = $connection->getAccountType() === Sync\Google\Helper::GOOGLE_ACCOUNT_TYPE_API
284 ? 'google'
285 : $connection->getAccountType()
286 ;
287
289 'delete_sync_connection',
290 $connection->getOwner()->getId(),
291 [
292 'syncInfo' => [
293 $accountType => [
294 'type' => $accountType,
295 ],
296 ],
297 'connectionId' => $connection->getId()
298 ]
299 );
300 }
301 else
302 {
303 $result->addErrors($updateResult->getErrors());
304 }
305
306 return $result;
307 }
308
321 public function unsubscribeConnection(Connection $connection)
322 {
323 $links = SectionConnectionTable::query()
324 ->addFilter('CONNECTION_ID', $connection->getId())
325 ->setSelect(['ID'])
326 ->exec()
327 ;
328
329 while ($link = $links->fetchObject())
330 {
331 SectionConnectionTable::update($link->getId(), [
332 'SYNC_TOKEN' => '',
333 'PAGE_TOKEN' => '',
334 ]);
335 PushTable::delete([
336 'ENTITY_TYPE' => 'SECTION_CONNECTION',
337 'ENTITY_ID' => $link->getId(),
338 ]);
339 }
340 }
341
342 public function disableConnection(Connection $connection)
343 {
344 global $DB;
345 $id = $connection->getId();
346 $DB->Query(
347 "UPDATE `b_dav_connections` as con SET con.IS_DELETED ='Y' WHERE con.ID = $id;",
348 true
349 );
350 $DB->Query(
351 "DELETE FROM `b_calendar_section_connection` WHERE CONNECTION_ID = $id;",
352 true
353 );
354 $DB->Query(
355 "DELETE FROM b_calendar_event_connection WHERE CONNECTION_ID = $id;",
356 true
357 );
358
359 $DB->Query("DELETE sect FROM b_calendar_section sect
360 LEFT JOIN b_calendar_section_connection link ON sect.ID = link.SECTION_ID
361 WHERE link.ID IS NULL
362 AND sect.EXTERNAL_TYPE = '{$connection->getVendor()->getCode()}'
363 AND sect.OWNER_ID = '{$connection->getOwner()->getId()}'
364 ;",
365 true
366 );
367 $DB->Query("DELETE event FROM `b_calendar_event` event
368 LEFT JOIN b_calendar_section sec ON event.SECTION_ID = sec.ID
369 WHERE sec.ID IS NULL
370 AND event.OWNER_ID = '{$connection->getOwner()->getId()}'
371 ;",
372 true
373 );
374 $DB->Query("DELETE push FROM b_calendar_push push
375 LEFT JOIN b_calendar_section_connection as sc on push.ENTITY_ID=sc.ID and push.ENTITY_TYPE='SECTION_CONNECTION'
376 WHERE sc.ID IS NULL;",
377 true
378 );
379 }
380}
getConnection(Role $owner, string $accountType, array $optionalFilter=[])
initConnection(Role $owner, string $accountType, string $server)
getConnectionsData(Role $owner, array $type, array $optionalFilter=[])
getSocialUserLogin(Role $owner, string $accountType)
createConnection(Role $owner, string $type, string $name, string $serverPath)
static addPullEvent(string $command, int $userId, array $params=[])
Definition util.php:373