1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
uploader.php
См. документацию.
1<?
2namespace Bitrix\Main\UI\Uploader;
3
4use Bitrix\Main\AccessDeniedException;
5use Bitrix\Main\ArgumentOutOfRangeException;
6use Bitrix\Main\HttpRequest;
7use Bitrix\Main\NotImplementedException;
8use Bitrix\Main\UI\FileInputUtility;
9use Bitrix\Main\Web\Json;
10use Bitrix\Main\Context;
11use Bitrix\Main\Loader;
12use Bitrix\Main\Localization\Loc;
13use Bitrix\Main;
14
15Loc::loadMessages(__FILE__);
17 "main",
18 array(
19 "bitrix\\main\\ui\\uploader\\storage" => "lib/ui/uploader/storage.php",
20 "bitrix\\main\\ui\\uploader\\cloudstorage" => "lib/ui/uploader/storage.php"
21 ));
22
23class Log implements \ArrayAccess
24{
25 /*
26 * @var \CBXVirtualFileFileSystem $file
27 */
28 protected $file = null;
29 var $data = array();
30
37 {
38 try
39 {
40 $this->file = \CBXVirtualIo::GetInstance()->GetFile($path);
41
42 if ($this->file->IsExists())
43 {
44 $data = unserialize($this->file->GetContents(), ["allowed_classes" => false]);
45 foreach($data as $key => $val)
46 {
47 if (array_key_exists($key , $this->data) && is_array($this->data[$key]) && is_array($val))
48 $this->data[$key] = array_merge($this->data[$key], $val);
49 else
50 $this->data[$key] = $val;
51 }
52 }
53 }
54 catch (\Throwable $e)
55 {
56 throw new Main\SystemException("Temporary file has wrong structure.", "BXU351.01");
57 }
58 }
59
66 public function setLog($key, $value)
67 {
68 if (array_key_exists($key, $this->data) && is_array($this->data) && is_array($value))
69 $this->data[$key] = array_merge($this->data[$key], $value);
70 else
71 $this->data[$key] = $value;
72 $this->save();
73
74 return $this;
75 }
76
81 public function getValue($key)
82 {
83 return $this->data[$key];
84 }
85
89 public function save()
90 {
91 try
92 {
93 $this->file->PutContents(serialize($this->data));
94 }
95 catch (\Throwable $e)
96 {
97 throw new Main\SystemException("Temporary file was not saved.", "BXU351.02");
98 }
99 }
100
104 public function getLog()
105 {
106 return $this->data;
107 }
108
112 public function unlink()
113 {
114 try
115 {
116 if ($this->file instanceof \CBXVirtualFileFileSystem && $this->file->IsExists())
117 $this->file->unlink();
118 }
119 catch (\Throwable $e)
120 {
121 throw new Main\SystemException("Temporary file was not deleted.", "BXU351.03");
122 }
123 }
124
129 public function offsetExists($offset): bool
130 {
131 return array_key_exists($offset, $this->data);
132 }
133
138 #[\ReturnTypeWillChange]
139 public function offsetGet($offset)
140 {
141 if (array_key_exists($offset, $this->data))
142 return $this->data[$offset];
143 return null;
144 }
145
150 public function offsetSet($offset, $value): void
151 {
152 $this->setLog($offset, $value);
153 }
154
158 public function offsetUnset($offset): void
159 {
160 if (array_key_exists($offset, $this->data))
161 {
162 unset($this->data[$offset]);
163 $this->save();
164 }
165 }
166}
167
169{
170 public $files = array();
171 public $controlId = "fileUploader";
172 public $params = array(
173 "allowUpload" => "A",
174 "allowUploadExt" => "",
175 "copies" => array(
176 "default" => array(
177 "width" => null,
178 "height" => null
179 ),
180 /* "copyName" => array(
181 "width" => 100,
182 "height" => 100
183 )*/
184 ),
185 "storage" => array(
186 "moduleId" => "main",
187 "cloud" => false
188 )
189 );
190/*
191 * @var string $script Url to uploading page for forming url to view
192 * @var string $path Path to temp directory
193 * @var string $CID Controller ID
194 * @var string $mode
195 * @var array $processTime Time limits
196 * @var HttpClient $http
197*/
198 public $script;
199 protected $path = "";
200 protected $CID = null;
201 protected int $version = 0;
202 protected $mode = "view";
203 protected $param = array();
205 "get" => true,
206 "post" => true
207 );
208 /* @var HttpRequest $request */
209 protected $request;
210 protected $http;
211
212 const FILE_NAME = "bxu_files";
213 const INFO_NAME = "bxu_info";
214 const EVENT_NAME = "main_bxu";
215 const SESSION_LIST = "MFI_SESSIONS";
216 const SESSION_TTL = 86400;
217
218 public function __construct($params = array())
219 {
220 global $APPLICATION;
221
222 $this->script = $APPLICATION->GetCurPageParam();
223
224 $params = is_array($params) ? $params : array($params);
225 $params["copies"] = (isset($params["copies"]) && is_array($params["copies"]) ? $params["copies"] : array()) + $this->params["copies"];
226 $params["storage"] = (isset($params["storage"]) && is_array($params["storage"]) ? $params["storage"] : array()) + $this->params["storage"];
227 $params["storage"]["moduleId"] = preg_replace("/[^a-z_-]/i", "_", $params["storage"]["moduleId"]);
228 $this->params = $params;
229 if (array_key_exists("controlId", $params))
230 $this->controlId = $params["controlId"];
231 if (array_key_exists("events", $params) && is_array($params["events"]))
232 {
233 foreach($params["events"] as $key => $val)
234 {
235 $this->setHandler($key, $val);
236 }
237 }
238 unset($this->params["events"]);
239
240 $this->path = \CTempFile::GetDirectoryName(
241 12,
242 array(
243 "bxu",
244 $this->params["storage"]["moduleId"],
245 md5(serialize(array(
246 $this->controlId,
248 \CMain::GetServerUniqID()
249 ))
250 )
251 )
252 );
253 $this->request = Context::getCurrent()->getRequest();
254 }
255
256 public function setControlId($controlId)
257 {
258 $this->controlId = $controlId;
259 }
260
261 public function setHandler($name, $callback)
262 {
263 AddEventHandler(self::EVENT_NAME, $name, $callback);
264 return $this;
265 }
266
271 protected static function removeTmpPath($item)
272 {
273 if (is_array($item))
274 {
275 if (array_key_exists("tmp_name", $item))
276 {
277 unset($item["tmp_name"]);
278 }
279 foreach ($item as $key => $val)
280 {
281 if ($key == "chunksInfo")
282 {
283 $item[$key]["uploaded"] = count($item[$key]["uploaded"]);
284 $item[$key]["written"] = count($item[$key]["written"]);
285 }
286 else if (is_array($val))
287 {
288 $item[$key] = self::removeTmpPath($val);
289 }
290 }
291 }
292 return $item;
293 }
294
295 public static function prepareData($data)
296 {
297 array_walk_recursive(
298 $data,
299 function(&$v, $k) {
300 if ($k == "error")
301 {
302 $v = preg_replace("/<(.+?)>/isu", "", $v);
303 }
304 }
305 );
307 }
308
315 protected function fillRequireData()
316 {
317 $this->mode = $this->getRequest("mode");
318 if (!in_array($this->mode, array("upload", "delete", "view")))
319 throw new ArgumentOutOfRangeException("mode");
320
321 if ($this->mode != "view" && !check_bitrix_sessid())
322 throw new AccessDeniedException("Bad sessid.");
323
324 $this->version = (int) $this->getRequest("version");
325
326 $directory = \CBXVirtualIo::GetInstance()->GetDirectory($this->path);
327 $directoryExists = $directory->IsExists();
328 if (!$directory->Create())
329 throw new NotImplementedException("Mandatory directory has not been created.");
330 if (!$directoryExists)
331 {
332 $access = \CBXVirtualIo::GetInstance()->GetFile($directory->GetPath()."/.access.php");
333 $content = '<?$PERM["'.$directory->GetName().'"]["*"]="X";?>';
334
335 if (!$access->IsExists() || mb_strpos($access->GetContents(), $content) === false)
336 {
337 if (($fd = $access->Open('ab')))
338 {
339 fwrite($fd, $content);
340 }
341 fclose($fd);
342 }
343 }
344
345 return false;
346 }
347
348 protected function showJsonAnswer($result)
349 {
350 if (!defined("PUBLIC_AJAX_MODE"))
351 define("PUBLIC_AJAX_MODE", true);
352 if (!defined("NO_KEEP_STATISTIC"))
353 define("NO_KEEP_STATISTIC", "Y");
354 if (!defined("NO_AGENT_STATISTIC"))
355 define("NO_AGENT_STATISTIC", "Y");
356 if (!defined("NO_AGENT_CHECK"))
357 define("NO_AGENT_CHECK", true);
358 if (!defined("DisableEventsCheck"))
359 define("DisableEventsCheck", true);
360
361 require_once(\Bitrix\Main\Application::getInstance()->getContext()->getServer()->getDocumentRoot()."/bitrix/modules/main/include/prolog_before.php");
362 global $APPLICATION;
363
364 $APPLICATION->RestartBuffer();
365
366 $version = IsIE();
367 if ( !(0 < $version && $version < 10) )
368 header('Content-Type:application/json; charset=UTF-8');
369
370 echo Json::encode($result);
371 \CMain::finalActions();
372 die;
373 }
374
380 protected function setRequestMethodToCheck(array $methods)
381 {
382 foreach ($this->requestMethods as $method => $value)
383 $this->requestMethods[$method] = in_array($method, $methods);
384 return $this;
385 }
386
390 protected function getRequest($key)
391 {
392 if ($this->requestMethods["post"] &&
393 is_array($this->request->getPost(self::INFO_NAME)) &&
394 array_key_exists($key, $this->request->getPost(self::INFO_NAME)))
395 {
396 $res = $this->request->getPost(self::INFO_NAME);
397 return $res[$key];
398 }
399 if ($this->requestMethods["get"] &&
400 is_array($this->request->getQuery(self::INFO_NAME)) &&
401 array_key_exists($key, $this->request->getQuery(self::INFO_NAME)))
402 {
403 $res = $this->request->getQuery(self::INFO_NAME);
404 return $res[$key];
405 }
406
407 return null;
408 }
409
414 public function getParam($key)
415 {
416 return $this->params[$key];
417 }
418
423 public function checkPost($checkPost = true)
424 {
425 if ($checkPost === false && !is_array($this->request->getQuery(self::INFO_NAME)) ||
426 $checkPost !== false && !is_array($this->request->getPost(self::INFO_NAME)))
427 return false;
428
429 if ($checkPost === false)
430 $this->setRequestMethodToCheck(array("get"));
431
432 try
433 {
434 $this->fillRequireData();
435 $cid = FileInputUtility::instance()->registerControl($this->getRequest("CID"), $this->controlId);
436
437 if ($this->mode == "upload")
438 {
439 $package = new Package(
440 $this->path,
441 $cid,
442 $this->getRequest("packageIndex")
443 );
444 $package
445 ->setStorage($this->params["storage"])
446 ->setCopies($this->params["copies"]);
447
448 $response = $package->checkPost($this->params);
449
450 if ($this->version <= 1)
451 {
452 $response2 = array();
453 foreach ($response as $k => $r)
454 {
455 $response2[$k] = array(
456 "hash" => $r["hash"],
457 "status" => $r["status"],
458 "file" => $r
459 );
460 if (isset($r["error"]))
461 $response2[$k]["error"] = $r["error"];
462 }
463 $result = array(
464 "status" => $package->getLog("uploadStatus") == "uploaded" ? "done" : "inprogress",
465 "package" => array(
466 $package->getIndex() => array_merge(
467 $package->getLog(),
468 array(
469 "executed" => $package->getLog("executeStatus") == "executed",
470 "filesCount" => $package->getLog("filesCount")
471 )
472 )
473 ),
474 "report" => array(
475 "uploading" => array(
476 $package->getCid() => $package->getCidLog()
477 )
478 ),
479 "files" => self::prepareData($response2)
480 );
481 $this->showJsonAnswer($result);
482 }
483 }
484 else if ($this->mode == "delete")
485 {
486 $cid = FileInputUtility::instance()->registerControl($this->getRequest("CID"), $this->controlId);
487 File::deleteFile($cid, $this->getRequest("hash"), $this->path);
488 }
489 else
490 {
491 File::viewFile($cid, $this->getRequest("hash"), $this->path);
492 }
493 return true;
494 }
495 catch (Main\IO\IoException $e)
496 {
497 $this->showJsonAnswer(array(
498 "status" => "error",
499 "error" => "Something went wrong with the temporary file."
500 ));
501 }
502 catch (\Exception $e)
503 {
504 $this->showJsonAnswer(array(
505 "status" => "error",
506 "error" => $e->getMessage()
507 ));
508 }
509 return false;
510 }
511
519 public function checkCanvases($hash, &$file, $canvases = array(), $watermark = array())
520 {
521 if (!empty($watermark))
522 {
523 $file["files"]["default"] = File::createCanvas(
524 $file["files"]["default"],
525 $file["files"]["default"],
526 array(),
527 $watermark
528 );
529 }
530 if (is_array($canvases))
531 {
532 foreach ($canvases as $canvas => $canvasParams)
533 {
534 if (!array_key_exists($canvas, $file["files"]))
535 {
536 $source = $file["files"]["default"]; // TODO pick up more appropriate copy by params
537 $file["files"][$canvas] = File::createCanvas($source,
538 array(
539 "code" => $canvas,
540 "tmp_name" => mb_substr($source["tmp_name"], 0, -7).$canvas,
541 "url" => mb_substr($source["url"], 0, -7).$canvas
542 ), $canvasParams, $watermark);
543 }
544 }
545 }
546 return $file;
547 }
548 public function deleteFile($hash) {
549 $cid = FileInputUtility::instance()->registerControl($this->getRequest("CID"), $this->controlId);
550 File::deleteFile($cid, $hash, $this->path);
551 }
552
557 public static function getPaths($tmpName)
558 {
559 $docRoot = null;
561 if (($tempRoot = \CTempFile::GetAbsoluteRoot()) && ($strFilePath = $tempRoot.$tmpName) &&
562 $io->FileExists($strFilePath) && ($url = File::getUrlFromRelativePath($tmpName)))
563 {
564 return array(
565 "tmp_url" => $url,
566 "tmp_name" => $strFilePath
567 );
568 }
569 else if ((($docRoot = \Bitrix\Main\Application::getInstance()->getContext()->getServer()->getDocumentRoot()) && $strFilePath = $docRoot.$tmpName) && $io->FileExists($strFilePath))
570 {
571 return array(
572 "tmp_url" => $tmpName,
573 "tmp_name" => $strFilePath
574 );
575 }
576 else if ($io->FileExists($tmpName) && ($docRoot = \Bitrix\Main\Application::getInstance()->getContext()->getServer()->getDocumentRoot()) &&
577 mb_strpos($tmpName, $docRoot) === 0)
578 {
579 return array(
580 "tmp_url" => str_replace("//", "/", "/".mb_substr($tmpName, mb_strlen($docRoot))),
581 "tmp_name" => $tmpName
582 );
583 }
584 return false;
585 }
586
587}
$path
Определения access_edit.php:21
$hash
Определения ajax_redirector.php:8
global $APPLICATION
Определения include.php:80
xml version
Определения yandex.php:67
static getInstance()
Определения application.php:98
static registerAutoLoadClasses($moduleName, array $classes)
Определения loader.php:273
static viewFile($cid, $hash, $path)
Определения file.php:471
static createCanvas($source, $dest, $canvasParams=array(), $watermarkParams=array())
Определения file.php:695
static getUrlFromRelativePath($tmpName)
Определения file.php:520
static deleteFile($cid, $hash, $path)
Определения file.php:450
__construct($path)
Определения uploader.php:36
offsetUnset($offset)
Определения uploader.php:158
offsetExists($offset)
Определения uploader.php:129
offsetGet($offset)
Определения uploader.php:139
setLog($key, $value)
Определения uploader.php:66
getValue($key)
Определения uploader.php:81
offsetSet($offset, $value)
Определения uploader.php:150
setControlId($controlId)
Определения uploader.php:256
static getPaths($tmpName)
Определения uploader.php:557
showJsonAnswer($result)
Определения uploader.php:348
static prepareData($data)
Определения uploader.php:295
const SESSION_TTL
Определения uploader.php:216
const SESSION_LIST
Определения uploader.php:215
__construct($params=array())
Определения uploader.php:218
checkCanvases($hash, &$file, $canvases=array(), $watermark=array())
Определения uploader.php:519
checkPost($checkPost=true)
Определения uploader.php:423
setHandler($name, $callback)
Определения uploader.php:261
deleteFile($hash)
Определения uploader.php:548
setRequestMethodToCheck(array $methods)
Определения uploader.php:380
static removeTmpPath($item)
Определения uploader.php:271
static GetInstance()
Определения virtual_io.php:60
$content
Определения commerceml.php:144
$data['IS_AVAILABLE']
Определения .description.php:13
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$res
Определения filter_act.php:7
$result
Определения get_property_values.php:14
$docRoot
Определения options.php:20
$io
Определения csv_new_run.php:98
if(!is_array($deviceNotifyCodes)) $access
Определения options.php:174
check_bitrix_sessid($varname='sessid')
Определения tools.php:4686
bitrix_sessid()
Определения tools.php:4656
AddEventHandler($FROM_MODULE_ID, $MESSAGE_ID, $CALLBACK, $SORT=100, $FULL_PATH=false)
Определения tools.php:5165
IsIE()
Определения tools.php:4103
$name
Определения menu_edit.php:35
Определения directory.php:3
if(empty($signedUserToken)) $key
Определения quickway.php:257
die
Определения quickway.php:367
</p ></td >< td valign=top style='border-top:none;border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;padding:0cm 2.0pt 0cm 2.0pt;height:9.0pt'>< p class=Normal align=center style='margin:0cm;margin-bottom:.0001pt;text-align:center;line-height:normal'>< a name=ТекстовоеПоле54 ></a ><?=($taxRate > count( $arTaxList) > 0) ? $taxRate."%"
Определения waybill.php:936
$val
Определения options.php:1793
$response
Определения result.php:21
$method
Определения index.php:27
$k
Определения template_pdf.php:567
path
Определения template_copy.php:201
$url
Определения iframe.php:7