/** * * @param AJXP_Node $oldFile * @param AJXP_Node $newFile * @param Boolean $copy */ public function moveMeta($oldFile, $newFile = null, $copy = false) { if ($oldFile == null) { return; } $feedStore = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("feed"); if ($feedStore !== false) { $feedStore->updateMetaObject($oldFile->getRepositoryId(), $oldFile->getPath(), $newFile != null ? $newFile->getPath() : null, $copy); return; } if (!$copy && $this->metaStore->inherentMetaMove()) { return; } $oldMeta = $this->metaStore->retrieveMetadata($oldFile, AJXP_META_SPACE_COMMENTS); if (!count($oldMeta)) { return; } // If it's a move or a delete, delete old data if (!$copy) { $this->metaStore->removeMetadata($oldFile, AJXP_META_SPACE_COMMENTS); } // If copy or move, copy data. if ($newFile != null) { $this->metaStore->setMetadata($newFile, AJXP_META_SPACE_COMMENTS, $oldMeta); } }
/** * @param AJXP_Node $ajxpNode * @return null|string */ protected function extractIndexableContent($ajxpNode) { $ext = strtolower(pathinfo($ajxpNode->getLabel(), PATHINFO_EXTENSION)); if (in_array($ext, explode(",", $this->getFilteredOption("PARSE_CONTENT_TXT")))) { return file_get_contents($ajxpNode->getUrl()); } $unoconv = $this->getFilteredOption("UNOCONV"); $pipe = false; if (!empty($unoconv) && in_array($ext, array("doc", "odt", "xls", "ods"))) { $targetExt = "txt"; if (in_array($ext, array("xls", "ods"))) { $targetExt = "csv"; } else { if (in_array($ext, array("odp", "ppt"))) { $targetExt = "pdf"; $pipe = true; } } $realFile = call_user_func(array($ajxpNode->wrapperClassName, "getRealFSReference"), $ajxpNode->getUrl()); $unoconv = "HOME=" . AJXP_Utils::getAjxpTmpDir() . " " . $unoconv . " --stdout -f {$targetExt} " . escapeshellarg($realFile); if ($pipe) { $newTarget = str_replace(".{$ext}", ".pdf", $realFile); $unoconv .= " > {$newTarget}"; register_shutdown_function("unlink", $newTarget); } $output = array(); exec($unoconv, $output, $return); if (!$pipe) { $out = implode("\n", $output); $enc = 'ISO-8859-1'; $asciiString = iconv($enc, 'ASCII//TRANSLIT//IGNORE', $out); return $asciiString; } else { $ext = "pdf"; } } $pdftotext = $this->getFilteredOption("PDFTOTEXT"); if (!empty($pdftotext) && in_array($ext, array("pdf"))) { $realFile = call_user_func(array($ajxpNode->wrapperClassName, "getRealFSReference"), $ajxpNode->getUrl()); if ($pipe && isset($newTarget) && is_file($newTarget)) { $realFile = $newTarget; } $cmd = $pdftotext . " " . escapeshellarg($realFile) . " -"; $output = array(); exec($cmd, $output, $return); $out = implode("\n", $output); $enc = 'UTF8'; $asciiString = iconv($enc, 'ASCII//TRANSLIT//IGNORE', $out); return $asciiString; } return null; }
protected function replaceVars($tplString, $mess, $rich = true) { $tplString = SystemTextEncoding::fromUTF8($tplString); $repoId = $this->getNode()->getRepositoryId(); $repoObject = ConfService::getRepositoryById($repoId); if ($repoObject != null) { $repoLabel = $repoObject->getDisplay(); } else { $repoLabel = "Repository"; } $uLabel = ""; if (strstr($tplString, "AJXP_USER") !== false) { $uLabel = $this->getAuthorLabel(); } $em = $rich ? "<em>" : ""; $me = $rich ? "</em>" : ""; $replaces = array("AJXP_NODE_PATH" => $em . $this->getRoot($this->getNode()->getPath()) . $me, "AJXP_NODE_LABEL" => $em . $this->getNode()->getLabel() . $me, "AJXP_PARENT_PATH" => $em . $this->getRoot(dirname($this->getNode()->getPath())) . $me, "AJXP_PARENT_LABEL" => $em . $this->getRoot(basename(dirname($this->getNode()->getPath()))) . $me, "AJXP_REPOSITORY_ID" => $em . $repoId . $me, "AJXP_REPOSITORY_LABEL" => $em . $repoLabel . $me, "AJXP_LINK" => $this->getMainLink(), "AJXP_USER" => $uLabel, "AJXP_DATE" => SystemTextEncoding::fromUTF8(AJXP_Utils::relativeDate($this->getDate(), $mess))); if ($replaces["AJXP_NODE_LABEL"] == $em . $me || $replaces["AJXP_NODE_LABEL"] == $em . "/" . $me) { $replaces["AJXP_NODE_LABEL"] = $replaces["AJXP_REPOSITORY_LABEL"]; } if ($replaces["AJXP_PARENT_LABEL"] == $em . $me || $replaces["AJXP_PARENT_LABEL"] == $em . "/" . $me) { $replaces["AJXP_PARENT_LABEL"] = $replaces["AJXP_REPOSITORY_LABEL"]; } if ((strstr($tplString, "AJXP_TARGET_FOLDER") !== false || strstr($tplString, "AJXP_SOURCE_FOLDER")) && isset($this->secondaryNode)) { $p = $this->secondaryNode->getPath(); if ($this->secondaryNode->isLeaf()) { $p = $this->getRoot(dirname($p)); } $replaces["AJXP_TARGET_FOLDER"] = $replaces["AJXP_SOURCE_FOLDER"] = $em . $p . $me; } if ((strstr($tplString, "AJXP_TARGET_LABEL") !== false || strstr($tplString, "AJXP_SOURCE_LABEL") !== false) && isset($this->secondaryNode)) { $replaces["AJXP_TARGET_LABEL"] = $replaces["AJXP_SOURCE_LABEL"] = $em . $this->secondaryNode->getLabel() . $me; } return str_replace(array_keys($replaces), array_values($replaces), $tplString); }
/** * Enter description here... * */ public function stream_close() { if ($this->fp !== null) { fclose($this->fp); if (self::$linkNode !== null) { ConfService::loadDriverForRepository(self::$linkNode->getRepository()); } } }
/** * @param AJXP_Node $node * @param string $cacheType * @param string $details * @return string */ public static function computeIdForNode($node, $cacheType, $details = '') { $repo = $node->getRepository(); if ($repo == null) { return "failed-id"; } $scope = $repo->securityScope(); $additional = ""; if ($scope === "USER") { $additional = AuthService::getLoggedUser()->getId() . "@"; } else { if ($scope == "GROUP") { $additional = ltrim(str_replace("/", "__", AuthService::getLoggedUser()->getGroupPath()), "__") . "@"; } } $scheme = parse_url($node->getUrl(), PHP_URL_SCHEME); return str_replace($scheme . "://", $cacheType . "://" . $additional, $node->getUrl()) . ($details ? "##" . $details : ""); }
protected function updateMetaShort($file, $elementId, $shortUrl) { $driver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access"); $streamData = $driver->detectStreamWrapper(false); $baseUrl = $streamData["protocol"] . "://" . ConfService::getRepository()->getId(); $node = new AJXP_Node($baseUrl . $file); if ($node->hasMetaStore()) { $metadata = $node->retrieveMetadata("ajxp_shared", true, AJXP_METADATA_SCOPE_REPOSITORY); if ($elementId != -1) { if (!is_array($metadata["element"][$elementId])) { $metadata["element"][$elementId] = array(); } $metadata["element"][$elementId]["short_form_url"] = $shortUrl; } else { $metadata['short_form_url'] = $shortUrl; } $node->setMetadata("ajxp_shared", $metadata, true, AJXP_METADATA_SCOPE_REPOSITORY); } }
/** * @return string */ public function getMainLink() { $repoId = $this->getNode()->getRepositoryId(); if (isset($_SESSION["CURRENT_MINISITE"])) { $hash = $_SESSION["CURRENT_MINISITE"]; $shareCenter = ShareCenter::getShareCenter(); if (!empty($shareCenter)) { return $shareCenter->buildPublicletLink($hash); } } return trim(AJXP_Utils::detectServerURL(true), "/") . "/?goto=" . $repoId . $this->node->getPath(); }
protected function updateMetaShort($file, $elementId, $shortUrl) { $context = new UserSelection(ConfService::getRepository()); $baseUrl = $context->currentBaseUrl(); $node = new AJXP_Node($baseUrl . $file); if ($node->hasMetaStore()) { $metadata = $node->retrieveMetadata("ajxp_shared", true, AJXP_METADATA_SCOPE_REPOSITORY); if ($elementId != -1) { if (!is_array($metadata["element"][$elementId])) { $metadata["element"][$elementId] = array(); } $metadata["element"][$elementId]["short_form_url"] = $shortUrl; } else { if (isset($metadata["shares"])) { $key = array_pop(array_keys($metadata["shares"])); $metadata["shares"][$key]["short_form_url"] = $shortUrl; } else { $metadata['short_form_url'] = $shortUrl; } } $node->setMetadata("ajxp_shared", $metadata, true, AJXP_METADATA_SCOPE_REPOSITORY); } }
protected function replaceVars($tplString, $mess, $rich = true) { $tplString = SystemTextEncoding::fromUTF8($tplString); $repoId = $this->getNode()->getRepositoryId(); if (ConfService::getRepositoryById($repoId) != null) { $repoLabel = ConfService::getRepositoryById($repoId)->getDisplay(); } else { $repoLabel = "Repository"; } $uLabel = ""; if (array_key_exists($this->getAuthor(), self::$usersCaches)) { if (self::$usersCaches[$this->getAuthor()] != 'AJXP_USER_DONT_EXISTS') { $uLabel = self::$usersCaches[$this->getAuthor()]; } } else { if (strstr($tplString, "AJXP_USER") !== false) { if (AuthService::userExists($this->getAuthor())) { $obj = ConfService::getConfStorageImpl()->createUserObject($this->getAuthor()); $uLabel = $obj->personalRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, ""); self::$usersCaches[$this->getAuthor()] = $uLabel; } else { self::$usersCaches[$this->getAuthor()] = 'AJXP_USER_DONT_EXISTS'; } } } if (empty($uLabel)) { $uLabel = $this->getAuthor(); } $em = $rich ? "<em>" : ""; $me = $rich ? "</em>" : ""; $replaces = array("AJXP_NODE_PATH" => $em . $this->getRoot($this->getNode()->getPath()) . $me, "AJXP_NODE_LABEL" => $em . $this->getNode()->getLabel() . $me, "AJXP_PARENT_PATH" => $em . $this->getRoot(dirname($this->getNode()->getPath())) . $me, "AJXP_PARENT_LABEL" => $em . $this->getRoot(basename(dirname($this->getNode()->getPath()))) . $me, "AJXP_REPOSITORY_ID" => $em . $repoId . $me, "AJXP_REPOSITORY_LABEL" => $em . $repoLabel . $me, "AJXP_LINK" => $this->getMainLink(), "AJXP_USER" => $uLabel, "AJXP_DATE" => SystemTextEncoding::fromUTF8(AJXP_Utils::relativeDate($this->getDate(), $mess))); if ($replaces["AJXP_NODE_LABEL"] == $em . $me) { $replaces["AJXP_NODE_LABEL"] = $em . "[" . $replaces["AJXP_REPOSITORY_LABEL"] . "]" . $me; } if ($replaces["AJXP_PARENT_LABEL"] == $em . $me) { $replaces["AJXP_PARENT_LABEL"] = $em . "[" . $replaces["AJXP_REPOSITORY_LABEL"] . "]" . $me; } if ((strstr($tplString, "AJXP_TARGET_FOLDER") !== false || strstr($tplString, "AJXP_SOURCE_FOLDER")) && isset($this->secondaryNode)) { $p = $this->secondaryNode->getPath(); if ($this->secondaryNode->isLeaf()) { $p = $this->getRoot(dirname($p)); } $replaces["AJXP_TARGET_FOLDER"] = $replaces["AJXP_SOURCE_FOLDER"] = $em . $p . $me; } if ((strstr($tplString, "AJXP_TARGET_LABEL") !== false || strstr($tplString, "AJXP_SOURCE_LABEL") !== false) && isset($this->secondaryNode)) { $replaces["AJXP_TARGET_LABEL"] = $replaces["AJXP_SOURCE_LABEL"] = $em . $this->secondaryNode->getLabel() . $me; } return str_replace(array_keys($replaces), array_values($replaces), $tplString); }
public function switchAction($action, $httpVars, $postProcessData) { if (!isset($this->actions[$action])) { return false; } $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(false)) { return false; } $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType()); $streamData = $plugin->detectStreamWrapper(true); $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . "/"; if ($action == "audio_proxy") { $selection = new UserSelection($repository, $httpVars); // Backward compat $file = $selection->getUniqueFile(); if (!file_exists($destStreamURL . $file) && strpos($httpVars["file"], "base64encoded:") === false) { // May be a backward compatibility problem, try to base64decode the filepath $file = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"])); if (!file_exists($destStreamURL . $file)) { throw new Exception("Cannot find file!"); } } $cType = "audio/" . array_pop(explode(".", $file)); $localName = basename($file); $node = new AJXP_Node($destStreamURL . $file); if (method_exists($node->getDriver(), "filesystemFileSize")) { $size = $node->getDriver()->filesystemFileSize($node->getUrl()); } else { $size = filesize($node->getUrl()); } header("Content-Type: " . $cType . "; name=\"" . $localName . "\""); header("Content-Length: " . $size); $stream = fopen("php://output", "a"); call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream); fflush($stream); fclose($stream); AJXP_Controller::applyHook("node.read", array($node)); $this->logInfo('Preview', 'Read content of ' . $node->getUrl()); //exit(1); } else { if ($action == "ls") { if (!isset($httpVars["playlist"])) { // This should not happen anyway, because of the applyCondition. AJXP_Controller::passProcessDataThrough($postProcessData); return; } // We transform the XML into XSPF $xmlString = $postProcessData["ob_output"]; $xmlDoc = new DOMDocument(); $xmlDoc->loadXML($xmlString); $xElement = $xmlDoc->documentElement; header("Content-Type:application/xspf+xml;charset=UTF-8"); print '<?xml version="1.0" encoding="UTF-8"?>'; print '<playlist version="1" xmlns="http://xspf.org/ns/0/">'; print "<trackList>"; foreach ($xElement->childNodes as $child) { $isFile = $child->getAttribute("is_file") == "true"; $label = $child->getAttribute("text"); $ar = explode(".", $label); $ext = strtolower(end($ar)); if (!$isFile || $ext != "mp3") { continue; } print "<track><location>" . AJXP_SERVER_ACCESS . "?secure_token=" . AuthService::getSecureToken() . "&get_action=audio_proxy&file=" . base64_encode($child->getAttribute("filename")) . "</location><title>" . $label . "</title></track>"; } print "</trackList>"; AJXP_XMLWriter::close("playlist"); } } }
/** * @param AJXP_Node $ajxpNode */ public function extractMeta(&$ajxpNode) { $currentFile = $ajxpNode->getUrl(); if (!$ajxpNode->isLeaf() || preg_match("/\\.zip\\//", $currentFile)) { return; } if (!preg_match("/\\.jpg\$|\\.jpeg\$|\\.tif\$|\\.tiff\$/i", $currentFile)) { return; } $definitions = $this->getMetaDefinition(); if (!count($definitions)) { return; } if (!function_exists("exif_read_data")) { return; } //if(!exif_imagetype($currentFile)) return ; $realFile = $ajxpNode->getRealFile(); $exif = @exif_read_data($realFile, 0, TRUE); $iptc = $this->extractIPTC($realFile); if ($exif === false) { return; } $additionalMeta = array(); foreach ($definitions as $def => $label) { list($exifSection, $exifName) = explode("-", $def); if ($exifSection == "COMPUTED_GPS" && !isset($exif["COMPUTED_GPS"])) { $exif['COMPUTED_GPS'] = $this->convertGPSData($exif); } if (isset($exif[$exifSection]) && isset($exif[$exifSection][$exifName])) { $additionalMeta[$def] = $exif[$exifSection][$exifName]; } if ($exifSection == "IPTC" && isset($iptc[$exifName])) { $additionalMeta[$def] = $iptc[$exifName]; } } $ajxpNode->mergeMetadata($additionalMeta); }
/** * @param AJXP_Node $ajxpNode * @param Boolean $isParent */ public function extractMimeHeaders(&$ajxpNode, $isParent = false) { if ($isParent) { return; } $currentNode = $ajxpNode->getUrl(); $metadata = $ajxpNode->metadata; $wrapperClassName = $ajxpNode->wrapperClassName; $noMail = true; if ($metadata["is_file"] && ($wrapperClassName == "imapAccessWrapper" || preg_match("/\\.eml\$/i", $currentNode))) { $noMail = false; } if ($wrapperClassName == "imapAccessWrapper" && !$metadata["is_file"]) { $metadata["mimestring"] = "Mailbox"; } $parsed = parse_url($currentNode); if ($noMail || isset($parsed["fragment"]) && strpos($parsed["fragment"], "attachments") === 0) { EmlParser::$currentListingOnlyEmails = FALSE; return; } if (EmlParser::$currentListingOnlyEmails === NULL) { EmlParser::$currentListingOnlyEmails = true; } if ($wrapperClassName == "imapAccessWrapper") { $cachedFile = AJXP_Cache::getItem("eml_remote", $currentNode, null, array("EmlParser", "computeCacheId")); $realFile = $cachedFile->getId(); if (!is_file($realFile)) { $cachedFile->getData(); // trigger loading! } } else { $realFile = $ajxpNode->getRealFile(); } $cacheItem = AJXP_Cache::getItem("eml_mimes", $realFile, array($this, "mimeExtractorCallback")); $data = unserialize($cacheItem->getData()); $data["ajxp_mime"] = "eml"; $data["mimestring"] = "Email"; $metadata = array_merge($metadata, $data); if ($wrapperClassName == "imapAccessWrapper" && $metadata["eml_attachments"] != "0" && strpos($_SERVER["HTTP_USER_AGENT"], "ajaxplorer-ios") !== false) { $metadata["is_file"] = false; $metadata["nodeName"] = basename($currentNode) . "#attachments"; } $ajxpNode->metadata = $metadata; }
/** * @param array $shares * @param String $operation * @param AJXP_Node $oldNode * @param AJXP_Node $newNode * @param array $collectRepositories * @param string|null $parentRepositoryPath * @return array * @throws Exception */ public function moveSharesFromMeta($shares, $operation = "move", $oldNode, $newNode = null, &$collectRepositories = array(), $parentRepositoryPath = null) { $privateShares = array(); $publicShares = array(); foreach ($shares as $id => $data) { $type = $data["type"]; if ($operation == "delete") { $this->deleteShare($type, $id, false, true); continue; } if ($type == "minisite") { $share = $this->loadShare($id); $repo = ConfService::getRepositoryById($share["REPOSITORY"]); } else { if ($type == "repository") { $repo = ConfService::getRepositoryById($id); } else { if ($type == "file") { $publicLink = $this->loadShare($id); } } } if (isset($repo)) { $oldNodeLabel = SystemTextEncoding::toUTF8($oldNode->getLabel()); $newNodeLabel = SystemTextEncoding::toUTF8($newNode->getLabel()); if ($newNode != null && $newNodeLabel != $oldNodeLabel && $repo->getDisplay() == $oldNodeLabel) { $repo->setDisplay($newNodeLabel); } $cFilter = $repo->getContentFilter(); $path = $repo->getOption("PATH", true); $save = false; if (isset($cFilter)) { if ($parentRepositoryPath !== null) { $repo->addOption("PATH", $parentRepositoryPath); } else { $cFilter->movePath($oldNode->getPath(), $newNode->getPath()); $repo->setContentFilter($cFilter); } $save = true; } else { if (!empty($path)) { $oldNodePath = SystemTextEncoding::toUTF8($oldNode->getPath()); $newNodePath = SystemTextEncoding::toUTF8($newNode->getPath()); $path = preg_replace("#" . preg_quote($oldNodePath, "#") . "\$#", $newNodePath, $path); $repo->addOption("PATH", $path); $save = true; $collectRepositories[$repo->getId()] = $path; } } if ($save) { //ConfService::getConfStorageImpl()->saveRepository($repo, true); ConfService::replaceRepository($repo->getId(), $repo); } $access = $repo->getOption("SHARE_ACCESS"); if (!empty($access) && $access == "PUBLIC") { $publicShares[$id] = $data; } else { $privateShares[$id] = $data; } } else { if (isset($publicLink) && is_array($publicLink) && isset($publicLink["FILE_PATH"])) { $oldNodePath = SystemTextEncoding::toUTF8($oldNode->getPath()); $newNodePath = SystemTextEncoding::toUTF8($newNode->getPath()); $publicLink["FILE_PATH"] = str_replace($oldNodePath, $newNodePath, $publicLink["FILE_PATH"]); $this->deleteShare("file", $id); $this->storeShare($newNode->getRepositoryId(), $publicLink, "file", $id); $privateShares[$id] = $data; } } } return array($privateShares, $publicShares); }
public function switchAction($action, $httpVars, $filesVars) { if (!isset($this->actions[$action])) { return false; } $repository = ConfService::getRepositoryById($httpVars["repository_id"]); if (!$repository->detectStreamWrapper(true)) { return false; } if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if ($loggedUser === null && ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth")) { AuthService::logUser("guest", null); $loggedUser = AuthService::getLoggedUser(); } if (!$loggedUser->canSwitchTo($repository->getId())) { echo "You do not have permissions to access this resource"; return false; } } $streamData = $repository->streamData; $destStreamURL = $streamData["protocol"] . "://" . $repository->getId(); $selection = new UserSelection($repository, $httpVars); if ($action == "open_file") { $file = $selection->getUniqueFile(); if (!file_exists($destStreamURL . $file)) { echo "File does not exist"; return false; } $node = new AJXP_Node($destStreamURL . $file); if (method_exists($node->getDriver(), "filesystemFileSize")) { $filesize = $node->getDriver()->filesystemFileSize($node->getUrl()); } else { $filesize = filesize($node->getUrl()); } $fp = fopen($destStreamURL . $file, "rb"); $fileMime = "application/octet-stream"; //Get mimetype with fileinfo PECL extension if (class_exists("finfo")) { $finfo = new finfo(FILEINFO_MIME); $fileMime = $finfo->buffer(fread($fp, 100)); } //Get mimetype with (deprecated) mime_content_type if (strpos($fileMime, "application/octet-stream") === 0 && function_exists("mime_content_type")) { $fileMime = @mime_content_type($fp); } //Guess mimetype based on file extension if (strpos($fileMime, "application/octet-stream") === 0) { $fileExt = substr(strrchr(basename($file), '.'), 1); if (empty($fileExt)) { $fileMime = "application/octet-stream"; } else { $regex = "/^([\\w\\+\\-\\.\\/]+)\\s+(\\w+\\s)*({$fileExt}\\s)/i"; $lines = file($this->getBaseDir() . "/resources/other/mime.types"); foreach ($lines as $line) { if (substr($line, 0, 1) == '#') { continue; } // skip comments $line = rtrim($line) . " "; if (!preg_match($regex, $line, $matches)) { continue; } // no match to the extension $fileMime = $matches[1]; } } } fclose($fp); // If still no mimetype, give up and serve application/octet-stream if (empty($fileMime)) { $fileMime = "application/octet-stream"; } //Send headers HTMLWriter::generateInlineHeaders(basename($file), $filesize, $fileMime); $class = $streamData["classname"]; $stream = fopen("php://output", "a"); call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream); fflush($stream); fclose($stream); $node = new AJXP_Node($destStreamURL . $file); AJXP_Controller::applyHook("node.read", array($node)); $this->logInfo('Download', 'Read content of ' . $node->getUrl()); } }
/** * * @param AJXP_Node $node * @param int $depth * @throws Exception */ public function recursiveIndexation($node, $depth = 0) { $repository = $node->getRepository(); $user = $node->getUser(); $messages = ConfService::getMessages(); if ($user == null && AuthService::usersEnabled()) { $user = AuthService::getLoggedUser(); } if ($depth == 0) { $this->logDebug("Starting indexation - node.index.recursive.start - " . memory_get_usage(true) . " - " . $node->getUrl()); $this->setIndexStatus("RUNNING", str_replace("%s", $node->getPath(), $messages["core.index.8"]), $repository, $user); AJXP_Controller::applyHook("node.index.recursive.start", array($node)); } else { if ($this->isInterruptRequired($repository, $user)) { $this->logDebug("Interrupting indexation! - node.index.recursive.end - " . $node->getUrl()); AJXP_Controller::applyHook("node.index.recursive.end", array($node)); $this->releaseStatus($repository, $user); throw new Exception("User interrupted"); } } if (!ConfService::currentContextIsCommandLine()) { @set_time_limit(120); } $url = $node->getUrl(); $this->logDebug("Indexing Node parent node " . $url); $this->setIndexStatus("RUNNING", str_replace("%s", $node->getPath(), $messages["core.index.8"]), $repository, $user); try { AJXP_Controller::applyHook("node.index", array($node)); } catch (Exception $e) { $this->logDebug("Error Indexing Node " . $url . " (" . $e->getMessage() . ")"); } $handle = opendir($url); if ($handle !== false) { while (($child = readdir($handle)) != false) { if ($child[0] == ".") { continue; } $childNode = new AJXP_Node(rtrim($url, "/") . "/" . $child); $childUrl = $childNode->getUrl(); if (is_dir($childUrl)) { $this->logDebug("Entering recursive indexation for " . $childUrl); $this->recursiveIndexation($childNode, $depth + 1); } else { try { $this->logDebug("Indexing Node " . $childUrl); AJXP_Controller::applyHook("node.index", array($childNode)); } catch (Exception $e) { $this->logDebug("Error Indexing Node " . $childUrl . " (" . $e->getMessage() . ")"); } } } closedir($handle); } else { $this->logDebug("Cannot open {$url}!!"); } if ($depth == 0) { $this->logDebug("End indexation - node.index.recursive.end - " . memory_get_usage(true) . " - " . $node->getUrl()); $this->setIndexStatus("RUNNING", "Indexation finished, cleaning...", $repository, $user); AJXP_Controller::applyHook("node.index.recursive.end", array($node)); $this->releaseStatus($repository, $user); $this->logDebug("End indexation - After node.index.recursive.end - " . memory_get_usage(true) . " - " . $node->getUrl()); } }
/** * @param String $type * @param String $element * @param AJXP_Node $oldNode * @param AJXP_Node $newNode * @return bool */ public function moveShareIfPossible($type, $element, $oldNode, $newNode) { if (!$this->sqlSupported) { return false; } $this->confStorage->simpleStoreGet("share", $element, "serial", $data); if ($oldNode->isLeaf() && $type == "minisite" && is_array($data)) { $repo = ConfService::getRepositoryById($data["REPOSITORY"]); $cFilter = $repo->getContentFilter(); if (isset($cFilter)) { $cFilter->movePath($oldNode->getPath(), $newNode->getPath()); } } }
/** * * @param AJXP_Node $ajxpNode * @param bool $contextNode * @param bool $details * @return void */ public function extractMeta(&$ajxpNode, $contextNode = false, $details = false) { $metadata = $ajxpNode->retrieveMetadata("users_meta", false, AJXP_METADATA_SCOPE_GLOBAL); if (empty($metadata)) { $metadata = array(); } $ajxpNode->mergeMetadata($metadata); }
/** * * @param AJXP_Node $ajxpNode */ public function enrichMetadata(&$ajxpNode) { $currentNode = $ajxpNode->getUrl(); $metadata = $ajxpNode->metadata; $parsed = parse_url($currentNode); if (isset($parsed["fragment"]) && strpos($parsed["fragment"], "attachments") === 0) { list(, $attachmentId) = explode("/", $parsed["fragment"]); $meta = imapAccessWrapper::getCurrentAttachmentsMetadata(); if ($meta != null) { foreach ($meta as $attach) { if ($attach["x-attachment-id"] == $attachmentId) { $metadata["text"] = $attach["filename"]; $metadata["icon"] = AJXP_Utils::mimetype($attach["filename"], "image", false); $metadata["mimestring"] = AJXP_Utils::mimetype($attach["filename"], "text", false); } } } } if (!$metadata["is_file"] && $currentNode != "") { $metadata["icon"] = "imap_images/ICON_SIZE/mail_folder_sent.png"; } if (basename($currentNode) == "INBOX") { $metadata["text"] = "Incoming Mails"; } if (strstr($currentNode, "__delim__") !== false) { $parts = explode("/", $currentNode); $metadata["text"] = str_replace("__delim__", "/", array_pop($parts)); } $ajxpNode->metadata = $metadata; }
/** * @param AJXP_Node $node * @param float $offset * @param float $length * @return String md5 */ public function getPartialHash($node, $offset, $length) { $this->logDebug('Getting partial hash from ' . $offset . ' to ' . $length); $fp = fopen($node->getUrl(), "r"); $ctx = hash_init('md5'); if ($offset > 0) { fseek($fp, $offset); } hash_update_stream($ctx, $fp, $length); $hash = hash_final($ctx); $this->logDebug('Partial hash is ' . $hash); fclose($fp); return $hash; }
/** * * @param AJXP_Node $ajxpNode */ public function extractMeta(&$ajxpNode) { //if(isSet($_SESSION["SVN_COMMAND_RUNNING"]) && $_SESSION["SVN_COMMAND_RUNNING"] === true) return ; $realDir = dirname($ajxpNode->getRealFile()); if (SvnManager::$svnListDir == $realDir) { $entries = SvnManager::$svnListCache; } else { try { SvnManager::$svnListDir = $realDir; $entries = $this->svnListNode($realDir); SvnManager::$svnListCache = $entries; } catch (Exception $e) { $this->logError("ExtractMeta", $e->getMessage()); } } $fileId = SystemTextEncoding::toUTF8(basename($ajxpNode->getUrl())); if (isset($entries[$fileId])) { $ajxpNode->mergeMetadata($entries[$fileId]); } }
public function switchAction($action, $httpVars, $filesVars) { $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $selection = new UserSelection($repository, $httpVars); $selectedNode = $selection->getUniqueNode(); $selectedNodeUrl = $selectedNode->getUrl(); if ($action == "post_to_server") { // Backward compat if (strpos($httpVars["file"], "base64encoded:") !== 0) { $legacyFilePath = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"])); $selectedNode = new AJXP_Node($selection->currentBaseUrl() . $legacyFilePath); $selectedNodeUrl = $selectedNode->getUrl(); } $target = rtrim(base64_decode($httpVars["parent_url"]), '/') . "/plugins/editor.pixlr"; $tmp = AJXP_MetaStreamWrapper::getRealFSReference($selectedNodeUrl); $tmp = SystemTextEncoding::fromUTF8($tmp); $this->logInfo('Preview', 'Sending content of ' . $selectedNodeUrl . ' to Pixlr server.', array("files" => $selectedNodeUrl)); AJXP_Controller::applyHook("node.read", array($selectedNode)); $saveTarget = $target . "/fake_save_pixlr.php"; if ($this->getFilteredOption("CHECK_SECURITY_TOKEN", $repository->getId())) { $saveTarget = $target . "/fake_save_pixlr_" . md5($httpVars["secure_token"]) . ".php"; } $params = array("referrer" => "Pydio", "method" => "get", "loc" => ConfService::getLanguage(), "target" => $saveTarget, "exit" => $target . "/fake_close_pixlr.php", "title" => urlencode(basename($selectedNodeUrl)), "locktarget" => "false", "locktitle" => "true", "locktype" => "source"); require_once AJXP_BIN_FOLDER . "/http_class/http_class.php"; $arguments = array(); $httpClient = new http_class(); $httpClient->request_method = "POST"; $httpClient->GetRequestArguments("https://pixlr.com/editor/", $arguments); $arguments["PostValues"] = $params; $arguments["PostFiles"] = array("image" => array("FileName" => $tmp, "Content-Type" => "automatic/name")); $err = $httpClient->Open($arguments); if (empty($err)) { $err = $httpClient->SendRequest($arguments); if (empty($err)) { $response = ""; while (true) { $header = array(); $error = $httpClient->ReadReplyHeaders($header, 1000); if ($error != "" || $header != null) { break; } $response .= $header; } } } header("Location: {$header['location']}"); //$response"); } else { if ($action == "retrieve_pixlr_image") { $file = AJXP_Utils::decodeSecureMagic($httpVars["original_file"]); $selectedNode = new AJXP_Node($selection->currentBaseUrl() . $file); $selectedNode->loadNodeInfo(); $this->logInfo('Edit', 'Retrieving content of ' . $file . ' from Pixlr server.', array("files" => $file)); AJXP_Controller::applyHook("node.before_change", array(&$selectedNode)); $url = $httpVars["new_url"]; $urlParts = parse_url($url); $query = $urlParts["query"]; if ($this->getFilteredOption("CHECK_SECURITY_TOKEN", $repository->getId())) { $scriptName = basename($urlParts["path"]); $token = str_replace(array("fake_save_pixlr_", ".php"), "", $scriptName); if ($token != md5($httpVars["secure_token"])) { throw new AJXP_Exception("Invalid Token, this could mean some security problem!"); } } $params = array(); parse_str($query, $params); $image = $params['image']; $headers = get_headers($image, 1); $content_type = explode("/", $headers['Content-Type']); if ($content_type[0] != "image") { throw new AJXP_Exception("Invalid File Type"); } $content_length = intval($headers["Content-Length"]); if ($content_length != 0) { AJXP_Controller::applyHook("node.before_change", array(&$selectedNode, $content_length)); } $orig = fopen($image, "r"); $target = fopen($selectedNode->getUrl(), "w"); if (is_resource($orig) && is_resource($target)) { while (!feof($orig)) { fwrite($target, fread($orig, 4096)); } fclose($orig); fclose($target); } clearstatcache(true, $selectedNode->getUrl()); $selectedNode->loadNodeInfo(true); AJXP_Controller::applyHook("node.change", array(&$selectedNode, &$selectedNode)); } } }
/** * @param AJXP_Node $fromNode * @param AJXP_Node $toNode * @param bool $copy */ public function handleNodeChange($fromNode = null, $toNode = null, $copy = false) { if ($fromNode == null) { return; } if ($toNode == null) { $fromNode->removeMetadata("etherpad", AJXP_METADATA_ALLUSERS, AJXP_METADATA_SCOPE_GLOBAL, false); } else { if (!$copy) { $toNode->copyOrMoveMetadataFromNode($fromNode, "etherpad", "move", AJXP_METADATA_ALLUSERS, AJXP_METADATA_SCOPE_GLOBAL, false); } } }
/** * @param AJXP_Node $oldNode * @param AJXP_Node $newNode * @param bool $copy */ public function updateNodesIndex($oldNode = null, $newNode = null, $copy = false) { if (!dibi::isConnected()) { dibi::connect($this->sqlDriver); } //$this->logInfo("Syncable index", array($oldNode == null?'null':$oldNode->getUrl(), $newNode == null?'null':$newNode->getUrl())); try { if ($newNode != null && $this->excludeNode($newNode)) { // CREATE if ($oldNode == null) { AJXP_Logger::debug("Ignoring " . $newNode->getUrl() . " for indexation"); return; } else { AJXP_Logger::debug("Target node is excluded, see it as a deletion: " . $newNode->getUrl()); $newNode = null; } } if ($newNode == null) { $repoId = $this->computeIdentifier($oldNode->getRepository(), $oldNode->getUser()); // DELETE $this->logDebug('DELETE', $oldNode->getUrl()); dibi::query("DELETE FROM [ajxp_index] WHERE [node_path] LIKE %like~ AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId); } else { if ($oldNode == null || $copy) { // CREATE $stat = stat($newNode->getUrl()); $newNode->setLeaf(!($stat['mode'] & 040000)); $this->logDebug('INSERT', $newNode->getUrl()); dibi::query("INSERT INTO [ajxp_index]", array("node_path" => SystemTextEncoding::toUTF8($newNode->getPath()), "bytesize" => $stat["size"], "mtime" => $stat["mtime"], "md5" => $newNode->isLeaf() ? md5_file($newNode->getUrl()) : "directory", "repository_identifier" => $repoId = $this->computeIdentifier($newNode->getRepository(), $newNode->getUser()))); } else { $repoId = $this->computeIdentifier($oldNode->getRepository(), $oldNode->getUser()); if ($oldNode->getPath() == $newNode->getPath()) { // CONTENT CHANGE clearstatcache(); $stat = stat($newNode->getUrl()); $this->logDebug("Content changed", "current stat size is : " . $stat["size"]); $this->logDebug('UPDATE CONTENT', $newNode->getUrl()); dibi::query("UPDATE [ajxp_index] SET ", array("bytesize" => $stat["size"], "mtime" => $stat["mtime"], "md5" => md5_file($newNode->getUrl())), "WHERE [node_path] = %s AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId); try { $rowCount = dibi::getAffectedRows(); if ($rowCount === 0) { $this->logError(__FUNCTION__, "There was an update event on a non-indexed node (" . $newNode->getPath() . "), creating index entry!"); $this->updateNodesIndex(null, $newNode, false); } } catch (Exception $e) { } } else { // PATH CHANGE ONLY $newNode->loadNodeInfo(); if ($newNode->isLeaf()) { $this->logDebug('UPDATE LEAF PATH', $newNode->getUrl()); dibi::query("UPDATE [ajxp_index] SET ", array("node_path" => SystemTextEncoding::toUTF8($newNode->getPath())), "WHERE [node_path] = %s AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId); try { $rowCount = dibi::getAffectedRows(); if ($rowCount === 0) { $this->logError(__FUNCTION__, "There was an update event on a non-indexed node (" . $newNode->getPath() . "), creating index entry!"); $this->updateNodesIndex(null, $newNode, false); } } catch (Exception $e) { } } else { $this->logDebug('UPDATE FOLDER PATH', $newNode->getUrl()); dibi::query("UPDATE [ajxp_index] SET [node_path]=REPLACE( REPLACE(CONCAT('\$\$\$',[node_path]), CONCAT('\$\$\$', %s), CONCAT('\$\$\$', %s)) , '\$\$\$', '') ", $oldNode->getPath(), $newNode->getPath(), "WHERE [node_path] LIKE %like~ AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId); try { $rowCount = dibi::getAffectedRows(); if ($rowCount === 0) { $this->logError(__FUNCTION__, "There was an update event on a non-indexed folder (" . $newNode->getPath() . "), relaunching a recursive indexation!"); AJXP_Controller::findActionAndApply("index", array("file" => $newNode->getPath()), array()); } } catch (Exception $e) { } } } } } } catch (Exception $e) { AJXP_Logger::error("[meta.syncable]", "Exception", $e->getTraceAsString()); AJXP_Logger::error("[meta.syncable]", "Indexation", $e->getMessage()); } }
public function generateJpegsCallback($masterFile, $targetFile) { $unoconv = $this->getFilteredOption("UNOCONV"); if (!empty($unoconv)) { $officeExt = array('xls', 'xlsx', 'ods', 'doc', 'docx', 'odt', 'ppt', 'pptx', 'odp', 'rtf'); } else { $unoconv = false; } $extension = pathinfo($masterFile, PATHINFO_EXTENSION); $node = new AJXP_Node($masterFile); $masterFile = $node->getRealFile(); if (DIRECTORY_SEPARATOR == "\\") { $masterFile = str_replace("/", "\\", $masterFile); } $wrappers = stream_get_wrappers(); $wrappers_re = '(' . join('|', $wrappers) . ')'; $isStream = preg_match("!^{$wrappers_re}://!", $targetFile) === 1; if ($isStream) { $backToStreamTarget = $targetFile; $targetFile = tempnam(AJXP_Utils::getAjxpTmpDir(), "imagick_") . ".pdf"; } $workingDir = dirname($targetFile); $out = array(); $return = 0; $tmpFileThumb = str_replace(".{$extension}", ".jpg", $targetFile); if (DIRECTORY_SEPARATOR == "\\") { $tmpFileThumb = str_replace("/", "\\", $tmpFileThumb); } if (!$this->extractAll) { //register_shutdown_function("unlink", $tmpFileThumb); } else { @set_time_limit(90); } chdir($workingDir); if ($unoconv !== false && in_array(strtolower($extension), $officeExt)) { $unoDoc = preg_replace("/(-[0-9]+)?\\.jpg/", "_unoconv.pdf", $tmpFileThumb); if (!is_file($unoDoc)) { if (stripos(PHP_OS, "win") === 0) { $unoconv = $this->pluginConf["UNOCONV"] . " -o " . escapeshellarg(basename($unoDoc)) . " -f pdf " . escapeshellarg($masterFile); } else { $unoconv = "HOME=/tmp " . $unoconv . " --stdout -f pdf " . escapeshellarg($masterFile) . " > " . escapeshellarg(basename($unoDoc)); } exec($unoconv, $out, $return); } if (is_file($unoDoc)) { $masterFile = basename($unoDoc); } } if ($this->onTheFly) { $pageNumber = strrchr($targetFile, "-"); $pageNumber = str_replace(array(".jpg", "-"), "", $pageNumber); $pageLimit = "[" . $pageNumber . "]"; $this->extractAll = true; } else { if (!$this->useOnTheFly) { $pageLimit = $this->extractAll ? "" : "[0]"; } else { $pageLimit = "[0]"; if ($this->extractAll) { $tmpFileThumb = str_replace(".jpg", "-0.jpg", $tmpFileThumb); } } } $customOptions = $this->getFilteredOption("IM_CUSTOM_OPTIONS"); $customEnvPath = $this->getFilteredOption("ADDITIONAL_ENV_PATH"); $viewerQuality = $this->getFilteredOption("IM_VIEWER_QUALITY"); $thumbQuality = $this->getFilteredOption("IM_THUMB_QUALITY"); if (empty($customOptions)) { $customOptions = ""; } if (!empty($customEnvPath)) { putenv("PATH=" . getenv("PATH") . ":" . $customEnvPath); } $params = $customOptions . " " . ($this->extractAll ? $viewerQuality : $thumbQuality); $cmd = $this->getFilteredOption("IMAGE_MAGICK_CONVERT") . " " . escapeshellarg($masterFile . $pageLimit) . " " . $params . " " . escapeshellarg($tmpFileThumb); $this->logDebug("IMagick Command : {$cmd}"); session_write_close(); // Be sure to give the hand back exec($cmd, $out, $return); if (is_array($out) && count($out)) { throw new AJXP_Exception(implode("\n", $out)); } if (!$this->extractAll) { rename($tmpFileThumb, $targetFile); if ($isStream) { $this->logDebug("Copy preview file to remote", $backToStreamTarget); copy($targetFile, $backToStreamTarget); unlink($targetFile); } } else { if ($isStream) { if (is_file(str_replace(".{$extension}", "", $targetFile))) { $targetFile = str_replace(".{$extension}", "", $targetFile); } if (is_file($targetFile)) { $this->logDebug("Copy preview file to remote", $backToStreamTarget); copy($targetFile, $backToStreamTarget); unlink($targetFile); } $this->logDebug("Searching for ", str_replace(".jpg", "-0.jpg", $tmpFileThumb)); $i = 0; while (file_exists(str_replace(".jpg", "-{$i}.jpg", $tmpFileThumb))) { $page = str_replace(".jpg", "-{$i}.jpg", $tmpFileThumb); $remote_page = str_replace(".{$extension}", "-{$i}.jpg", $backToStreamTarget); $this->logDebug("Copy preview file to remote", $remote_page); copy($page, $remote_page); unlink($page); $i++; } } } return true; }
/** * @param String $action * @param Array $httpVars * @param Array $fileVars * @throws Exception */ public function receiveAction($action, $httpVars, $fileVars) { //VAR CREATION OUTSIDE OF ALL CONDITIONS, THEY ARE "MUST HAVE" VAR !! $messages = ConfService::getMessages(); $repository = ConfService::getRepository(); $userSelection = new UserSelection($repository, $httpVars); $nodes = $userSelection->buildNodes(); $currentDirPath = AJXP_Utils::safeDirname($userSelection->getUniqueNode()->getPath()); $currentDirPath = rtrim($currentDirPath, "/") . "/"; $currentDirUrl = $userSelection->currentBaseUrl() . $currentDirPath; if (empty($httpVars["compression_id"])) { $compressionId = sha1(rand()); $httpVars["compression_id"] = $compressionId; } else { $compressionId = $httpVars["compression_id"]; } $progressCompressionFileName = $this->getPluginCacheDir(false, true) . DIRECTORY_SEPARATOR . "progressCompressionID-" . $compressionId . ".txt"; if (empty($httpVars["extraction_id"])) { $extractId = sha1(rand()); $httpVars["extraction_id"] = $extractId; } else { $extractId = $httpVars["extraction_id"]; } $progressExtractFileName = $this->getPluginCacheDir(false, true) . DIRECTORY_SEPARATOR . "progressExtractID-" . $extractId . ".txt"; if ($action == "compression") { $archiveName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME); $archiveFormat = $httpVars["type_archive"]; $tabTypeArchive = array(".tar", ".tar.gz", ".tar.bz2"); $acceptedExtension = false; foreach ($tabTypeArchive as $extensionArchive) { if ($extensionArchive == $archiveFormat) { $acceptedExtension = true; break; } } if ($acceptedExtension == false) { file_put_contents($progressCompressionFileName, "Error : " . $messages["compression.16"]); throw new AJXP_Exception($messages["compression.16"]); } $typeArchive = $httpVars["type_archive"]; //if we can run in background we do it if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) { $archivePath = $currentDirPath . $archiveName; file_put_contents($progressCompressionFileName, $messages["compression.5"]); AJXP_Controller::applyActionInBackground($repository->getId(), "compression", $httpVars); AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("check_compression_status", array("repository_id" => $repository->getId(), "compression_id" => $compressionId, "archive_path" => SystemTextEncoding::toUTF8($archivePath)), $messages["compression.5"], true, 2); AJXP_XMLWriter::close(); return null; } else { $maxAuthorizedSize = 4294967296; $currentDirUrlLength = strlen($currentDirUrl); $tabFolders = array(); $tabAllRecursiveFiles = array(); $tabFilesNames = array(); foreach ($nodes as $node) { $nodeUrl = $node->getUrl(); if (is_file($nodeUrl) && filesize($nodeUrl) < $maxAuthorizedSize) { array_push($tabAllRecursiveFiles, $nodeUrl); array_push($tabFilesNames, substr($nodeUrl, $currentDirUrlLength)); } if (is_dir($nodeUrl)) { array_push($tabFolders, $nodeUrl); } } //DO A FOREACH OR IT'S GONNA HAVE SOME SAMES FILES NAMES foreach ($tabFolders as $value) { $dossiers = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($value)); foreach ($dossiers as $file) { if ($file->isDir()) { continue; } array_push($tabAllRecursiveFiles, $file->getPathname()); array_push($tabFilesNames, substr($file->getPathname(), $currentDirUrlLength)); } } //WE STOP IF IT'S JUST AN EMPTY FOLDER OR NO FILES if (empty($tabFilesNames)) { file_put_contents($progressCompressionFileName, "Error : " . $messages["compression.17"]); throw new AJXP_Exception($messages["compression.17"]); } try { $tmpArchiveName = tempnam(AJXP_Utils::getAjxpTmpDir(), "tar-compression") . ".tar"; $archive = new PharData($tmpArchiveName); } catch (Exception $e) { file_put_contents($progressCompressionFileName, "Error : " . $e->getMessage()); throw $e; } $counterCompression = 0; //THE TWO ARRAY ARE MERGED FOR THE FOREACH LOOP $tabAllFiles = array_combine($tabAllRecursiveFiles, $tabFilesNames); foreach ($tabAllFiles as $fullPath => $fileName) { try { $archive->addFile(AJXP_MetaStreamWrapper::getRealFSReference($fullPath), $fileName); $counterCompression++; file_put_contents($progressCompressionFileName, sprintf($messages["compression.6"], round($counterCompression / count($tabAllFiles) * 100, 0, PHP_ROUND_HALF_DOWN) . " %")); } catch (Exception $e) { unlink($tmpArchiveName); file_put_contents($progressCompressionFileName, "Error : " . $e->getMessage()); throw $e; } } $finalArchive = $tmpArchiveName; if ($typeArchive != ".tar") { $archiveTypeCompress = substr(strrchr($typeArchive, "."), 1); file_put_contents($progressCompressionFileName, sprintf($messages["compression.7"], strtoupper($archiveTypeCompress))); if ($archiveTypeCompress == "gz") { $archive->compress(Phar::GZ); } elseif ($archiveTypeCompress == "bz2") { $archive->compress(Phar::BZ2); } $finalArchive = $tmpArchiveName . "." . $archiveTypeCompress; } $destArchive = AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $archiveName); rename($finalArchive, $destArchive); AJXP_Controller::applyHook("node.before_create", array($destArchive, filesize($destArchive))); if (file_exists($tmpArchiveName)) { unlink($tmpArchiveName); unlink(substr($tmpArchiveName, 0, -4)); } $newNode = new AJXP_Node($currentDirUrl . $archiveName); AJXP_Controller::applyHook("node.change", array(null, $newNode, false)); file_put_contents($progressCompressionFileName, "SUCCESS"); } } elseif ($action == "check_compression_status") { $archivePath = AJXP_Utils::decodeSecureMagic($httpVars["archive_path"]); $progressCompression = file_get_contents($progressCompressionFileName); $substrProgressCompression = substr($progressCompression, 0, 5); if ($progressCompression != "SUCCESS" && $substrProgressCompression != "Error") { AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("check_compression_status", array("repository_id" => $repository->getId(), "compression_id" => $compressionId, "archive_path" => SystemTextEncoding::toUTF8($archivePath)), $progressCompression, true, 5); AJXP_XMLWriter::close(); } elseif ($progressCompression == "SUCCESS") { $newNode = new AJXP_Node($userSelection->currentBaseUrl() . $archivePath); $nodesDiffs = array("ADD" => array($newNode), "REMOVE" => array(), "UPDATE" => array()); AJXP_Controller::applyHook("node.change", array(null, $newNode, false)); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($messages["compression.8"], null); AJXP_XMLWriter::writeNodesDiff($nodesDiffs, true); AJXP_XMLWriter::close(); if (file_exists($progressCompressionFileName)) { unlink($progressCompressionFileName); } } elseif ($substrProgressCompression == "Error") { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $progressCompression); AJXP_XMLWriter::close(); if (file_exists($progressCompressionFileName)) { unlink($progressCompressionFileName); } } } elseif ($action == "extraction") { $fileArchive = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["file"]), AJXP_SANITIZE_DIRNAME); $fileArchive = substr(strrchr($fileArchive, DIRECTORY_SEPARATOR), 1); $authorizedExtension = array("tar" => 4, "gz" => 7, "bz2" => 8); $acceptedArchive = false; $extensionLength = 0; $counterExtract = 0; $currentAllPydioPath = $currentDirUrl . $fileArchive; $pharCurrentAllPydioPath = "phar://" . AJXP_MetaStreamWrapper::getRealFSReference($currentAllPydioPath); $pathInfoCurrentAllPydioPath = pathinfo($currentAllPydioPath, PATHINFO_EXTENSION); //WE TAKE ONLY TAR, TAR.GZ AND TAR.BZ2 ARCHIVES foreach ($authorizedExtension as $extension => $strlenExtension) { if ($pathInfoCurrentAllPydioPath == $extension) { $acceptedArchive = true; $extensionLength = $strlenExtension; break; } } if ($acceptedArchive == false) { file_put_contents($progressExtractFileName, "Error : " . $messages["compression.15"]); throw new AJXP_Exception($messages["compression.15"]); } $onlyFileName = substr($fileArchive, 0, -$extensionLength); $lastPosOnlyFileName = strrpos($onlyFileName, "-"); $tmpOnlyFileName = substr($onlyFileName, 0, $lastPosOnlyFileName); $counterDuplicate = substr($onlyFileName, $lastPosOnlyFileName + 1); if (!is_int($lastPosOnlyFileName) || !is_int($counterDuplicate)) { $tmpOnlyFileName = $onlyFileName; $counterDuplicate = 1; } while (file_exists($currentDirUrl . $onlyFileName)) { $onlyFileName = $tmpOnlyFileName . "-" . $counterDuplicate; $counterDuplicate++; } if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) { file_put_contents($progressExtractFileName, $messages["compression.12"]); AJXP_Controller::applyActionInBackground($repository->getId(), "extraction", $httpVars); AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("check_extraction_status", array("repository_id" => $repository->getId(), "extraction_id" => $extractId, "currentDirUrl" => $currentDirUrl, "onlyFileName" => $onlyFileName), $messages["compression.12"], true, 2); AJXP_XMLWriter::close(); return null; } mkdir($currentDirUrl . $onlyFileName, 0777, true); chmod(AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $onlyFileName), 0777); try { $archive = new PharData(AJXP_MetaStreamWrapper::getRealFSReference($currentAllPydioPath)); $fichiersArchive = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pharCurrentAllPydioPath)); foreach ($fichiersArchive as $file) { $fileGetPathName = $file->getPathname(); if ($file->isDir()) { continue; } $fileNameInArchive = substr(strstr($fileGetPathName, $fileArchive), strlen($fileArchive) + 1); try { $archive->extractTo(AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $onlyFileName), $fileNameInArchive, false); } catch (Exception $e) { file_put_contents($progressExtractFileName, "Error : " . $e->getMessage()); throw new AJXP_Exception($e); } $counterExtract++; file_put_contents($progressExtractFileName, sprintf($messages["compression.13"], round($counterExtract / $archive->count() * 100, 0, PHP_ROUND_HALF_DOWN) . " %")); } } catch (Exception $e) { file_put_contents($progressExtractFileName, "Error : " . $e->getMessage()); throw new AJXP_Exception($e); } file_put_contents($progressExtractFileName, "SUCCESS"); $newNode = new AJXP_Node($currentDirUrl . $onlyFileName); AJXP_Controller::findActionAndApply("index", array("file" => $newNode->getPath()), array()); } elseif ($action == "check_extraction_status") { $currentDirUrl = $httpVars["currentDirUrl"]; $onlyFileName = $httpVars["onlyFileName"]; $progressExtract = file_get_contents($progressExtractFileName); $substrProgressExtract = substr($progressExtract, 0, 5); if ($progressExtract != "SUCCESS" && $progressExtract != "INDEX" && $substrProgressExtract != "Error") { AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("check_extraction_status", array("repository_id" => $repository->getId(), "extraction_id" => $extractId, "currentDirUrl" => $currentDirUrl, "onlyFileName" => $onlyFileName), $progressExtract, true, 4); AJXP_XMLWriter::close(); } elseif ($progressExtract == "SUCCESS") { $newNode = new AJXP_Node($currentDirUrl . $onlyFileName); $nodesDiffs = array("ADD" => array($newNode), "REMOVE" => array(), "UPDATE" => array()); AJXP_Controller::applyHook("node.change", array(null, $newNode, false)); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(sprintf($messages["compression.14"], $onlyFileName), null); AJXP_XMLWriter::triggerBgAction("check_index_status", array("repository_id" => $newNode->getRepositoryId()), "starting indexation", true, 5); AJXP_XMLWriter::writeNodesDiff($nodesDiffs, true); AJXP_XMLWriter::close(); if (file_exists($progressExtractFileName)) { unlink($progressExtractFileName); } } elseif ($substrProgressExtract == "Error") { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $progressExtract); AJXP_XMLWriter::close(); if (file_exists($progressExtractFileName)) { unlink($progressExtractFileName); } } } }
/** * @static * @param AJXP_Node $ajxpNode * @param bool $close * @param bool $print * @return void|string */ public static function renderAjxpNode($ajxpNode, $close = true, $print = true) { return AJXP_XMLWriter::renderNode($ajxpNode->getPath(), $ajxpNode->getLabel(), $ajxpNode->isLeaf(), $ajxpNode->metadata, $close, $print); }
/** * @param String $watchType * @param String $currentUserId * @param AJXP_Node $node * @param array|bool $watchMeta * @param array|bool $usersMeta * @return array */ private function loadWatchesFromMeta($watchType, $currentUserId, $node, $watchMeta = false, $usersMeta = false) { $IDS = array(); if ($usersMeta !== false) { if ($watchType == self::$META_WATCH_CHANGE && isset($usersMeta[self::$META_WATCH_USERS_CHANGE])) { $usersMeta = $usersMeta[self::$META_WATCH_USERS_CHANGE]; } else { if ($watchType == self::$META_WATCH_READ && isset($usersMeta[self::$META_WATCH_USERS_READ])) { $usersMeta = $usersMeta[self::$META_WATCH_USERS_READ]; } else { $usersMeta = null; } } } if (!empty($watchMeta) && is_array($watchMeta)) { foreach ($watchMeta as $id => $type) { if ($type == $watchType || $type == self::$META_WATCH_BOTH) { $IDS[] = $id; } } } if (!empty($usersMeta) && is_array($usersMeta)) { foreach ($usersMeta as $id => $targetUsers) { if (in_array($currentUserId, $targetUsers)) { $IDS[] = $id; } } } if (count($IDS)) { $changes = false; foreach ($IDS as $index => $id) { if ($currentUserId == $id && !AJXP_SERVER_DEBUG) { // In non-debug mode, do not send notifications to watcher! unset($IDS[$index]); continue; } if (!AuthService::userExists($id)) { unset($IDS[$index]); if (is_array($watchMeta)) { $changes = true; $watchMeta[$id] = AJXP_VALUE_CLEAR; } } else { // Make sure the user is still authorized on this node, otherwise remove it. $uObject = ConfService::getConfStorageImpl()->createUserObject($id); $acl = $uObject->mergedRole->getAcl($node->getRepositoryId()); $isOwner = $node->getRepository()->getOwner() == $uObject->getId(); if (!$isOwner && (empty($acl) || strpos($acl, "r") === FALSE)) { unset($IDS[$index]); if (is_array($watchMeta)) { $changes = true; $watchMeta[$id] = AJXP_VALUE_CLEAR; } } } } if ($changes) { $node->setMetadata(self::$META_WATCH_NAMESPACE, $watchMeta, false, AJXP_METADATA_SCOPE_REPOSITORY); } } return $IDS; }
/** * @param AJXP_Node $ajxpNode * @return */ function nodeBookmarkMetadata(&$ajxpNode) { $user = AuthService::getLoggedUser(); if ($user == null) { return; } if (!isset(self::$loadedBookmarks)) { self::$loadedBookmarks = $user->getBookmarks(); } foreach (self::$loadedBookmarks as $bm) { if ($bm["PATH"] == $ajxpNode->getPath()) { $ajxpNode->mergeMetadata(array("ajxp_bookmarked" => "true", "overlay_icon" => "bookmark.png"), true); /* * TESTING MULTIPLE OVERLAYS $ajxpNode->mergeMetadata(array( "overlay_icon" => "shared.png" ), true); */ } } }
public function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } $xmlBuffer = ""; foreach ($httpVars as $getName => $getValue) { ${$getName} = AJXP_Utils::securePath($getValue); } if (isset($dir) && $action != "upload") { $dir = SystemTextEncoding::fromUTF8($dir); } $mess = ConfService::getMessages(); switch ($action) { //------------------------------------ // SWITCH THE ROOT REPOSITORY //------------------------------------ case "switch_repository": if (!isset($repository_id)) { break; } $dirList = ConfService::getRepositoriesList(); /** @var $repository_id string */ if (!isset($dirList[$repository_id])) { $errorMessage = "Trying to switch to an unkown repository!"; break; } ConfService::switchRootDir($repository_id); // Load try to init the driver now, to trigger an exception // if it's not loading right. ConfService::loadRepositoryDriver(); if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) { $user = AuthService::getLoggedUser(); $activeRepId = ConfService::getCurrentRepositoryId(); $user->setArrayPref("history", "last_repository", $activeRepId); $user->save("user"); } //$logMessage = "Successfully Switched!"; $this->logInfo("Switch Repository", array("rep. id" => $repository_id)); break; //------------------------------------ // SEND XML REGISTRY //------------------------------------ //------------------------------------ // SEND XML REGISTRY //------------------------------------ case "get_xml_registry": case "state": $regDoc = AJXP_PluginsService::getXmlRegistry(); $changes = AJXP_Controller::filterRegistryFromRole($regDoc); if ($changes) { AJXP_PluginsService::updateXmlRegistry($regDoc); } $clone = $regDoc->cloneNode(true); $clonePath = new DOMXPath($clone); $serverCallbacks = $clonePath->query("//serverCallback|hooks"); foreach ($serverCallbacks as $callback) { $callback->parentNode->removeChild($callback); } $xPath = ''; if (isset($httpVars["xPath"])) { $xPath = ltrim(AJXP_Utils::securePath($httpVars["xPath"]), "/"); } if (!empty($xPath)) { $nodes = $clonePath->query($xPath); if ($httpVars["format"] == "json") { $data = AJXP_XMLWriter::xmlToArray($nodes->item(0)); HTMLWriter::charsetHeader("application/json"); echo json_encode($data); } else { AJXP_XMLWriter::header("ajxp_registry_part", array("xPath" => $xPath)); if ($nodes->length) { print AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->saveXML($nodes->item(0))); } AJXP_XMLWriter::close("ajxp_registry_part"); } } else { AJXP_Utils::safeIniSet("zlib.output_compression", "4096"); if ($httpVars["format"] == "json") { $data = AJXP_XMLWriter::xmlToArray($clone); HTMLWriter::charsetHeader("application/json"); echo json_encode($data); } else { header('Content-Type: application/xml; charset=UTF-8'); print AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->saveXML()); } } break; //------------------------------------ // BOOKMARK BAR //------------------------------------ //------------------------------------ // BOOKMARK BAR //------------------------------------ case "get_bookmarks": $bmUser = null; if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) { $bmUser = AuthService::getLoggedUser(); } else { if (!AuthService::usersEnabled()) { $confStorage = ConfService::getConfStorageImpl(); $bmUser = $confStorage->createUserObject("shared"); } } if ($bmUser == null) { AJXP_XMLWriter::header(); AJXP_XMLWriter::close(); } $driver = ConfService::loadRepositoryDriver(); if (!is_a($driver, "AjxpWrapperProvider")) { $driver = false; } if (isset($httpVars["bm_action"]) && isset($httpVars["bm_path"])) { $bmPath = AJXP_Utils::decodeSecureMagic($httpVars["bm_path"]); if ($httpVars["bm_action"] == "add_bookmark") { $title = ""; if (isset($httpVars["bm_title"])) { $title = AJXP_Utils::decodeSecureMagic($httpVars["bm_title"]); } if ($title == "" && $bmPath == "/") { $title = ConfService::getCurrentRootDirDisplay(); } $bmUser->addBookMark($bmPath, $title); if ($driver) { $node = new AJXP_Node($driver->getResourceUrl($bmPath)); $node->setMetadata("ajxp_bookmarked", array("ajxp_bookmarked" => "true"), true, AJXP_METADATA_SCOPE_REPOSITORY, true); } } else { if ($httpVars["bm_action"] == "delete_bookmark") { $bmUser->removeBookmark($bmPath); if ($driver) { $node = new AJXP_Node($driver->getResourceUrl($bmPath)); $node->removeMetadata("ajxp_bookmarked", true, AJXP_METADATA_SCOPE_REPOSITORY, true); } } else { if ($httpVars["bm_action"] == "rename_bookmark" && isset($httpVars["bm_title"])) { $title = AJXP_Utils::decodeSecureMagic($httpVars["bm_title"]); $bmUser->renameBookmark($bmPath, $title); } } } AJXP_Controller::applyHook("msg.instant", array("<reload_bookmarks/>", ConfService::getRepository()->getId())); if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) { $bmUser->save("user"); AuthService::updateUser($bmUser); } else { if (!AuthService::usersEnabled()) { $bmUser->save("user"); } } } AJXP_XMLWriter::header(); AJXP_XMLWriter::writeBookmarks($bmUser->getBookmarks(), true, isset($httpVars["format"]) ? $httpVars["format"] : "legacy"); AJXP_XMLWriter::close(); break; //------------------------------------ // SAVE USER PREFERENCE //------------------------------------ //------------------------------------ // SAVE USER PREFERENCE //------------------------------------ case "save_user_pref": $userObject = AuthService::getLoggedUser(); $i = 0; while (isset($httpVars["pref_name_" . $i]) && isset($httpVars["pref_value_" . $i])) { $prefName = AJXP_Utils::sanitize($httpVars["pref_name_" . $i], AJXP_SANITIZE_ALPHANUM); $prefValue = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["pref_value_" . $i])); if ($prefName == "password") { continue; } if ($prefName != "pending_folder" && $userObject == null) { $i++; continue; } $userObject->setPref($prefName, $prefValue); $userObject->save("user"); AuthService::updateUser($userObject); //setcookie("AJXP_$prefName", $prefValue); $i++; } header("Content-Type:text/plain"); print "SUCCESS"; break; //------------------------------------ // SAVE USER PREFERENCE //------------------------------------ //------------------------------------ // SAVE USER PREFERENCE //------------------------------------ case "custom_data_edit": case "user_create_user": $data = array(); if ($action == "user_create_user" && isset($httpVars["NEW_new_user_id"])) { $updating = false; AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "NEW_"); $original_id = AJXP_Utils::decodeSecureMagic($data["new_user_id"]); $data["new_user_id"] = AJXP_Utils::decodeSecureMagic($data["new_user_id"], AJXP_SANITIZE_EMAILCHARS); if ($original_id != $data["new_user_id"]) { throw new Exception(str_replace("%s", $data["new_user_id"], $mess["ajxp_conf.127"])); } if (AuthService::userExists($data["new_user_id"], "w")) { throw new Exception($mess["ajxp_conf.43"]); } $loggedUser = AuthService::getLoggedUser(); $limit = $loggedUser->personalRole->filterParameterValue("core.conf", "USER_SHARED_USERS_LIMIT", AJXP_REPO_SCOPE_ALL, ""); if (!empty($limit) && intval($limit) > 0) { $count = count($this->getUserChildren($loggedUser->getId())); if ($count >= $limit) { throw new Exception($mess['483']); } } AuthService::createUser($data["new_user_id"], $data["new_password"]); $userObject = ConfService::getConfStorageImpl()->createUserObject($data["new_user_id"]); $userObject->setParent($loggedUser->getId()); $userObject->save('superuser'); $userObject->personalRole->clearAcls(); $userObject->setGroupPath($loggedUser->getGroupPath()); $userObject->setProfile("shared"); } else { if ($action == "user_create_user" && isset($httpVars["NEW_existing_user_id"])) { $updating = true; AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "NEW_"); $userId = $data["existing_user_id"]; if (!AuthService::userExists($userId)) { throw new Exception("Cannot find user"); } $userObject = ConfService::getConfStorageImpl()->createUserObject($userId); if ($userObject->getParent() != AuthService::getLoggedUser()->getId()) { throw new Exception("Cannot find user"); } if (!empty($data["new_password"])) { AuthService::updatePassword($userId, $data["new_password"]); } } else { $updating = false; $userObject = AuthService::getLoggedUser(); AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "PREFERENCES_"); } } $paramNodes = AJXP_PluginsService::searchAllManifests("//server_settings/param[contains(@scope,'user') and @expose='true']", "node", false, false, true); $rChanges = false; if (is_array($paramNodes) && count($paramNodes)) { foreach ($paramNodes as $xmlNode) { if ($xmlNode->getAttribute("expose") == "true") { $parentNode = $xmlNode->parentNode->parentNode; $pluginId = $parentNode->getAttribute("id"); if (empty($pluginId)) { $pluginId = $parentNode->nodeName . "." . $parentNode->getAttribute("name"); } $name = $xmlNode->getAttribute("name"); if (isset($data[$name]) || $data[$name] === "") { if ($data[$name] == "__AJXP_VALUE_SET__") { continue; } if ($data[$name] === "" || $userObject->parentRole == null || $userObject->parentRole->filterParameterValue($pluginId, $name, AJXP_REPO_SCOPE_ALL, "") != $data[$name] || $userObject->personalRole->filterParameterValue($pluginId, $name, AJXP_REPO_SCOPE_ALL, "") != $data[$name]) { $userObject->personalRole->setParameterValue($pluginId, $name, $data[$name]); $rChanges = true; } } } } } if ($rChanges) { AuthService::updateRole($userObject->personalRole, $userObject); $userObject->recomputeMergedRole(); if ($action == "custom_data_edit") { AuthService::updateUser($userObject); } } if ($action == "user_create_user") { AJXP_Controller::applyHook($updating ? "user.after_update" : "user.after_create", array($userObject)); if (isset($data["send_email"]) && $data["send_email"] == true && !empty($data["email"])) { $mailer = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("mailer"); if ($mailer !== false) { $mess = ConfService::getMessages(); $link = AJXP_Utils::detectServerURL(); $apptitle = ConfService::getCoreConf("APPLICATION_TITLE"); $subject = str_replace("%s", $apptitle, $mess["507"]); $body = str_replace(array("%s", "%link", "%user", "%pass"), array($apptitle, $link, $data["new_user_id"], $data["new_password"]), $mess["508"]); $mailer->sendMail(array($data["email"]), $subject, $body); } } echo "SUCCESS"; } else { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["241"], null); AJXP_XMLWriter::close(); } break; case "user_update_user": if (!isset($httpVars["user_id"])) { throw new Exception("invalid arguments"); } $userId = $httpVars["user_id"]; if (!AuthService::userExists($userId)) { throw new Exception("Cannot find user"); } $userObject = ConfService::getConfStorageImpl()->createUserObject($userId); if ($userObject->getParent() != AuthService::getLoggedUser()->getId()) { throw new Exception("Cannot find user"); } $paramsString = ConfService::getCoreConf("NEWUSERS_EDIT_PARAMETERS", "conf"); $result = array(); $params = explode(",", $paramsString); foreach ($params as $p) { $result[$p] = $userObject->personalRole->filterParameterValue("core.conf", $p, AJXP_REPO_SCOPE_ALL, ""); } HTMLWriter::charsetHeader("application/json"); echo json_encode($result); break; //------------------------------------ // WEBDAV PREFERENCES //------------------------------------ //------------------------------------ // WEBDAV PREFERENCES //------------------------------------ case "webdav_preferences": $userObject = AuthService::getLoggedUser(); $webdavActive = false; $passSet = false; $digestSet = false; // Detect http/https and host if (ConfService::getCoreConf("WEBDAV_BASEHOST") != "") { $baseURL = ConfService::getCoreConf("WEBDAV_BASEHOST"); } else { $baseURL = AJXP_Utils::detectServerURL(); } $webdavBaseUrl = $baseURL . ConfService::getCoreConf("WEBDAV_BASEURI") . "/"; $davData = $userObject->getPref("AJXP_WEBDAV_DATA"); $digestSet = isset($davData["HA1"]); if (isset($httpVars["activate"]) || isset($httpVars["webdav_pass"])) { if (!empty($httpVars["activate"])) { $activate = $httpVars["activate"] == "true" ? true : false; if (empty($davData)) { $davData = array(); } $davData["ACTIVE"] = $activate; } if (!empty($httpVars["webdav_pass"])) { $password = $httpVars["webdav_pass"]; if (function_exists('mcrypt_encrypt')) { $user = $userObject->getId(); $secret = defined("AJXP_SAFE_SECRET_KEY") ? AJXP_SAFE_SECRET_KEY : "CDAFx¨op#"; $password = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($user . $secret), $password, MCRYPT_MODE_ECB)); } $davData["PASS"] = $password; } $userObject->setPref("AJXP_WEBDAV_DATA", $davData); $userObject->save("user"); } if (!empty($davData)) { $webdavActive = isset($davData["ACTIVE"]) && $davData["ACTIVE"] === true; $passSet = isset($davData["PASS"]); } $repoList = ConfService::getRepositoriesList(); $davRepos = array(); $loggedUser = AuthService::getLoggedUser(); foreach ($repoList as $repoIndex => $repoObject) { $accessType = $repoObject->getAccessType(); $driver = AJXP_PluginsService::getInstance()->getPluginByTypeName("access", $accessType); if (is_a($driver, "AjxpWrapperProvider") && !$repoObject->getOption("AJXP_WEBDAV_DISABLED") && ($loggedUser->canRead($repoIndex) || $loggedUser->canWrite($repoIndex))) { $davRepos[$repoIndex] = $webdavBaseUrl . "" . ($repoObject->getSlug() == null ? $repoObject->getId() : $repoObject->getSlug()); } } $prefs = array("webdav_active" => $webdavActive, "password_set" => $passSet, "digest_set" => $digestSet, "webdav_force_basic" => ConfService::getCoreConf("WEBDAV_FORCE_BASIC") === true, "webdav_base_url" => $webdavBaseUrl, "webdav_repositories" => $davRepos); HTMLWriter::charsetHeader("application/json"); print json_encode($prefs); break; case "get_user_template_logo": $tplId = $httpVars["template_id"]; $iconFormat = $httpVars["icon_format"]; $repo = ConfService::getRepositoryById($tplId); $logo = $repo->getOption("TPL_ICON_" . strtoupper($iconFormat)); if (isset($logo) && is_file(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo)) { header("Content-Type: " . AJXP_Utils::getImageMimeType($logo) . "; name=\"" . $logo . "\""); header("Content-Length: " . filesize(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo)); header('Pragma:'); header('Cache-Control: public'); header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT"); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT"); readfile(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo); } else { $logo = "default_template_logo-" . ($iconFormat == "small" ? 16 : 22) . ".png"; header("Content-Type: " . AJXP_Utils::getImageMimeType($logo) . "; name=\"" . $logo . "\""); header("Content-Length: " . filesize(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/core.conf/" . $logo)); header('Pragma:'); header('Cache-Control: public'); header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT"); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT"); readfile(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/core.conf/" . $logo); } break; case "get_user_templates_definition": AJXP_XMLWriter::header("repository_templates"); $count = 0; $repositories = ConfService::listRepositoriesWithCriteria(array("isTemplate" => 1), $count); $pServ = AJXP_PluginsService::getInstance(); foreach ($repositories as $repo) { if (!$repo->isTemplate) { continue; } if (!$repo->getOption("TPL_USER_CAN_CREATE")) { continue; } $repoId = $repo->getId(); $repoLabel = $repo->getDisplay(); $repoType = $repo->getAccessType(); print "<template repository_id=\"{$repoId}\" repository_label=\"{$repoLabel}\" repository_type=\"{$repoType}\">"; $driverPlug = $pServ->getPluginByTypeName("access", $repoType); $params = $driverPlug->getManifestRawContent("//param", "node"); $tplDefined = $repo->getOptionsDefined(); $defaultLabel = ''; foreach ($params as $paramNode) { $name = $paramNode->getAttribute("name"); if (strpos($name, "TPL_") === 0) { if ($name == "TPL_DEFAULT_LABEL") { $defaultLabel = str_replace("AJXP_USER", AuthService::getLoggedUser()->getId(), $repo->getOption($name)); } continue; } if (in_array($paramNode->getAttribute("name"), $tplDefined)) { continue; } if ($paramNode->getAttribute('no_templates') == 'true') { continue; } print AJXP_XMLWriter::replaceAjxpXmlKeywords($paramNode->ownerDocument->saveXML($paramNode)); } // ADD LABEL echo '<param name="DISPLAY" type="string" label="' . $mess[359] . '" description="' . $mess[429] . '" mandatory="true" default="' . $defaultLabel . '"/>'; print "</template>"; } AJXP_XMLWriter::close("repository_templates"); break; case "user_create_repository": $tplId = $httpVars["template_id"]; $tplRepo = ConfService::getRepositoryById($tplId); $options = array(); AJXP_Utils::parseStandardFormParameters($httpVars, $options); $loggedUser = AuthService::getLoggedUser(); $newRep = $tplRepo->createTemplateChild(AJXP_Utils::sanitize($httpVars["DISPLAY"]), $options, null, $loggedUser->getId()); $gPath = $loggedUser->getGroupPath(); if (!empty($gPath)) { $newRep->setGroupPath($gPath); } $res = ConfService::addRepository($newRep); AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess[426]); } else { // Make sure we do not overwrite otherwise loaded rights. $loggedUser->load(); $loggedUser->personalRole->setAcl($newRep->getUniqueId(), "rw"); $loggedUser->save("superuser"); $loggedUser->recomputeMergedRole(); AuthService::updateUser($loggedUser); AJXP_XMLWriter::sendMessage($mess[425], null); AJXP_XMLWriter::reloadDataNode("", $newRep->getUniqueId()); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); break; case "user_delete_repository": $repoId = $httpVars["repository_id"]; $repository = ConfService::getRepositoryById($repoId); if (!$repository->getUniqueUser() || $repository->getUniqueUser() != AuthService::getLoggedUser()->getId()) { throw new Exception("You are not allowed to perform this operation!"); } $res = ConfService::deleteRepository($repoId); AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess[427]); } else { $loggedUser = AuthService::getLoggedUser(); // Make sure we do not override remotely set rights $loggedUser->load(); $loggedUser->personalRole->setAcl($repoId, ""); $loggedUser->save("superuser"); AuthService::updateUser($loggedUser); AJXP_XMLWriter::sendMessage($mess[428], null); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); break; case "user_delete_user": $userId = $httpVars["user_id"]; $userObject = ConfService::getConfStorageImpl()->createUserObject($userId); if ($userObject == null || !$userObject->hasParent() || $userObject->getParent() != AuthService::getLoggedUser()->getId()) { throw new Exception("You are not allowed to edit this user"); } AuthService::deleteUser($userId); echo "SUCCESS"; break; case "user_list_authorized_users": $defaultFormat = "html"; HTMLWriter::charsetHeader(); if (!ConfService::getAuthDriverImpl()->usersEditable()) { break; } $loggedUser = AuthService::getLoggedUser(); $crtValue = $httpVars["value"]; $usersOnly = isset($httpVars["users_only"]) && $httpVars["users_only"] == "true"; $existingOnly = isset($httpVars["existing_only"]) && $httpVars["existing_only"] == "true"; if (!empty($crtValue)) { $regexp = '^' . $crtValue; } else { $regexp = null; } $skipDisplayWithoutRegexp = ConfService::getCoreConf("USERS_LIST_REGEXP_MANDATORY", "conf"); if ($skipDisplayWithoutRegexp && $regexp == null) { print "<ul></ul>"; break; } $limit = intval(ConfService::getCoreConf("USERS_LIST_COMPLETE_LIMIT", "conf")); $searchAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf"); $displayAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS_DISPLAY", "conf"); $baseGroup = "/"; if ($regexp == null && !$displayAll || $regexp != null && !$searchAll) { $baseGroup = AuthService::filterBaseGroup("/"); } AuthService::setGroupFiltering(false); $allUsers = AuthService::listUsers($baseGroup, $regexp, 0, $limit, false); if (!$usersOnly) { $allGroups = array(); $roleOrGroup = ConfService::getCoreConf("GROUP_OR_ROLE", "conf"); $rolePrefix = $excludeString = $includeString = null; if (!is_array($roleOrGroup)) { $roleOrGroup = array("group_switch_value" => $roleOrGroup); } $listRoleType = false; if (isset($roleOrGroup["PREFIX"])) { $rolePrefix = $loggedUser->mergedRole->filterParameterValue("core.conf", "PREFIX", null, $roleOrGroup["PREFIX"]); $excludeString = $loggedUser->mergedRole->filterParameterValue("core.conf", "EXCLUDED", null, $roleOrGroup["EXCLUDED"]); $includeString = $loggedUser->mergedRole->filterParameterValue("core.conf", "INCLUDED", null, $roleOrGroup["INCLUDED"]); $listUserRolesOnly = $loggedUser->mergedRole->filterParameterValue("core.conf", "LIST_ROLE_BY", null, $roleOrGroup["LIST_ROLE_BY"]); if (is_array($listUserRolesOnly) && isset($listUserRolesOnly["group_switch_value"])) { switch ($listUserRolesOnly["group_switch_value"]) { case "userroles": $listRoleType = true; break; case "allroles": $listRoleType = false; break; default: break; } } } switch (strtolower($roleOrGroup["group_switch_value"])) { case 'user': // donothing break; case 'group': $authGroups = AuthService::listChildrenGroups($baseGroup); foreach ($authGroups as $gId => $gName) { $allGroups["AJXP_GRP_" . rtrim($baseGroup, "/") . "/" . ltrim($gId, "/")] = $gName; } break; case 'role': $allGroups = $this->getUserRoleList($loggedUser, $rolePrefix, $includeString, $excludeString, $listRoleType); break; case 'rolegroup': $groups = array(); $authGroups = AuthService::listChildrenGroups($baseGroup); foreach ($authGroups as $gId => $gName) { $groups["AJXP_GRP_" . rtrim($baseGroup, "/") . "/" . ltrim($gId, "/")] = $gName; } $roles = $this->getUserRoleList($loggedUser, $rolePrefix, $includeString, $excludeString, $listRoleType); empty($groups) ? $allGroups = $roles : (empty($roles) ? $allGroups = $groups : ($allGroups = array_merge($groups, $roles))); //$allGroups = array_merge($groups, $roles); break; default: break; } } $users = ""; $index = 0; if ($regexp != null && (!count($allUsers) || !empty($crtValue) && !array_key_exists(strtolower($crtValue), $allUsers)) && ConfService::getCoreConf("USER_CREATE_USERS", "conf") && !$existingOnly) { $users .= "<li class='complete_user_entry_temp' data-temporary='true' data-label='{$crtValue}'><span class='user_entry_label'>{$crtValue} (" . $mess["448"] . ")</span></li>"; } else { if ($existingOnly && !empty($crtValue)) { $users .= "<li class='complete_user_entry_temp' data-temporary='true' data-label='{$crtValue}' data-entry_id='{$crtValue}'><span class='user_entry_label'>{$crtValue}</span></li>"; } } $mess = ConfService::getMessages(); if ($regexp == null && !$usersOnly) { $users .= "<li class='complete_group_entry' data-group='AJXP_GRP_/' data-label='" . $mess["447"] . "'><span class='user_entry_label'>" . $mess["447"] . "</span></li>"; } $indexGroup = 0; if (!$usersOnly && is_array($allGroups)) { foreach ($allGroups as $groupId => $groupLabel) { if ($regexp == null || preg_match("/{$regexp}/i", $groupLabel)) { $users .= "<li class='complete_group_entry' data-group='{$groupId}' data-label='{$groupLabel}' data-entry_id='{$groupId}'><span class='user_entry_label'>" . $groupLabel . "</span></li>"; $indexGroup++; } if ($indexGroup == $limit) { break; } } } if ($regexp == null && method_exists($this, "listUserTeams")) { $teams = $this->listUserTeams(); foreach ($teams as $tId => $tData) { $users .= "<li class='complete_group_entry' data-group='/AJXP_TEAM/{$tId}' data-label='[team] " . $tData["LABEL"] . "'><span class='user_entry_label'>[team] " . $tData["LABEL"] . "</span></li>"; } } foreach ($allUsers as $userId => $userObject) { if ($userObject->getId() == $loggedUser->getId()) { continue; } if (!$userObject->hasParent() && ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING", "conf") || $userObject->getParent() == $loggedUser->getId()) { $userLabel = $userObject->personalRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $userId); //if($regexp != null && ! (preg_match("/$regexp/i", $userId) || preg_match("/$regexp/i", $userLabel)) ) continue; if (empty($userLabel)) { $userLabel = $userId; } $userDisplay = $userLabel == $userId ? $userId : $userLabel . " ({$userId})"; if (ConfService::getCoreConf("USERS_LIST_HIDE_LOGIN", "conf") == true && $userLabel != $userId) { $userDisplay = $userLabel; } $users .= "<li class='complete_user_entry' data-label='{$userLabel}' data-entry_id='{$userId}'><span class='user_entry_label'>" . $userDisplay . "</span></li>"; $index++; } if ($index == $limit) { break; } } if (strlen($users)) { print "<ul>" . $users . "</ul>"; } AuthService::setGroupFiltering(true); break; case "load_repository_info": $data = array(); $repo = ConfService::getRepository(); if ($repo != null) { $users = AuthService::countUsersForRepository(ConfService::getRepository()->getId(), true); $data["core.users"] = $users; if (isset($httpVars["collect"]) && $httpVars["collect"] == "true") { AJXP_Controller::applyHook("repository.load_info", array(&$data)); } } HTMLWriter::charsetHeader("application/json"); echo json_encode($data); break; case "get_binary_param": if (isset($httpVars["tmp_file"])) { $file = AJXP_Utils::getAjxpTmpDir() . "/" . AJXP_Utils::securePath($httpVars["tmp_file"]); if (isset($file)) { header("Content-Type:image/png"); readfile($file); } } else { if (isset($httpVars["binary_id"])) { if (isset($httpVars["user_id"]) && AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->isAdmin()) { $context = array("USER" => $httpVars["user_id"]); } else { $context = array("USER" => AuthService::getLoggedUser()->getId()); } $this->loadBinary($context, $httpVars["binary_id"]); } } break; case "get_global_binary_param": if (isset($httpVars["tmp_file"])) { $file = AJXP_Utils::getAjxpTmpDir() . "/" . AJXP_Utils::securePath($httpVars["tmp_file"]); if (isset($file)) { header("Content-Type:image/png"); readfile($file); } } else { if (isset($httpVars["binary_id"])) { $this->loadBinary(array(), $httpVars["binary_id"]); } } break; case "store_binary_temp": if (count($fileVars)) { $keys = array_keys($fileVars); $boxData = $fileVars[$keys[0]]; $err = AJXP_Utils::parseFileDataErrors($boxData); if ($err != null) { } else { $rand = substr(md5(time()), 0, 6); $tmp = $rand . "-" . $boxData["name"]; @move_uploaded_file($boxData["tmp_name"], AJXP_Utils::getAjxpTmpDir() . "/" . $tmp); } } if (isset($tmp) && file_exists(AJXP_Utils::getAjxpTmpDir() . "/" . $tmp)) { print '<script type="text/javascript">'; print 'parent.formManagerHiddenIFrameSubmission("' . $tmp . '");'; print '</script>'; } break; default: break; } if (isset($logMessage) || isset($errorMessage)) { $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false); } if (isset($requireAuth)) { $xmlBuffer .= AJXP_XMLWriter::requireAuth(false); } return $xmlBuffer; }
public function switchAction($action, $httpVars, $filesVars) { if (!isset($this->actions[$action])) { return false; } $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $streamData = $repository->streamData; $destStreamURL = $streamData["protocol"] . "://" . $repository->getId(); if ($action == "post_to_zohoserver") { $sheetExt = explode(",", "xls,xlsx,ods,sxc,csv,tsv"); $presExt = explode(",", "ppt,pps,odp,sxi"); $docExt = explode(",", "doc,docx,rtf,odt,sxw"); require_once AJXP_BIN_FOLDER . "/http_class/http_class.php"; $selection = new UserSelection($repository, $httpVars); // Backward compat if (strpos($httpVars["file"], "base64encoded:") !== 0) { $file = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"])); } else { $file = $selection->getUniqueFile(); } $target = base64_decode($httpVars["parent_url"]); $tmp = call_user_func(array($streamData["classname"], "getRealFSReference"), $destStreamURL . $file); $tmp = SystemTextEncoding::fromUTF8($tmp); $node = new AJXP_Node($destStreamURL . $file); AJXP_Controller::applyHook("node.read", array($node)); $this->logInfo('Preview', 'Posting content of ' . $file . ' to Zoho server'); $extension = strtolower(pathinfo(urlencode(basename($file)), PATHINFO_EXTENSION)); $httpClient = new http_class(); $httpClient->request_method = "POST"; $secureToken = $httpVars["secure_token"]; $_SESSION["ZOHO_CURRENT_EDITED"] = $destStreamURL . $file; $_SESSION["ZOHO_CURRENT_UUID"] = md5(rand() . "-" . microtime()); if ($this->getFilteredOption("USE_ZOHO_AGENT", $repository->getId())) { $saveUrl = $this->getFilteredOption("ZOHO_AGENT_URL", $repository->getId()); } else { $saveUrl = $target . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/save_zoho.php"; } $b64Sig = $this->signID($_SESSION["ZOHO_CURRENT_UUID"]); $params = array('id' => $_SESSION["ZOHO_CURRENT_UUID"], 'apikey' => $this->getFilteredOption("ZOHO_API_KEY", $repository->getId()), 'output' => 'url', 'lang' => "en", 'filename' => urlencode(basename($file)), 'persistence' => 'false', 'format' => $extension, 'mode' => 'normaledit', 'saveurl' => $saveUrl . "?signature=" . $b64Sig); $service = "exportwriter"; if (in_array($extension, $sheetExt)) { $service = "sheet"; } else { if (in_array($extension, $presExt)) { $service = "show"; } else { if (in_array($extension, $docExt)) { $service = "exportwriter"; } } } $arguments = array(); $httpClient->GetRequestArguments("https://" . $service . ".zoho.com/remotedoc.im", $arguments); $arguments["PostValues"] = $params; $arguments["PostFiles"] = array("content" => array("FileName" => $tmp, "Content-Type" => "automatic/name")); $err = $httpClient->Open($arguments); if (empty($err)) { $err = $httpClient->SendRequest($arguments); if (empty($err)) { $response = ""; while (true) { $body = ""; $error = $httpClient->ReadReplyBody($body, 1000); if ($error != "" || strlen($body) == 0) { break; } $response .= $body; } $result = trim($response); $matchlines = explode("\n", $result); $resultValues = array(); foreach ($matchlines as $line) { list($key, $val) = explode("=", $line, 2); $resultValues[$key] = $val; } if ($resultValues["RESULT"] == "TRUE" && isset($resultValues["URL"])) { header("Location: " . $resultValues["URL"]); } else { echo "Zoho API Error " . $resultValues["ERROR_CODE"] . " : " . $resultValues["WARNING"]; echo "<script>window.parent.setTimeout(function(){parent.hideLightBox();}, 2000);</script>"; } } $httpClient->Close(); } } else { if ($action == "retrieve_from_zohoagent") { $targetFile = $_SESSION["ZOHO_CURRENT_EDITED"]; $id = $_SESSION["ZOHO_CURRENT_UUID"]; $ext = pathinfo($targetFile, PATHINFO_EXTENSION); $node = new AJXP_Node($targetFile); $node->loadNodeInfo(); AJXP_Controller::applyHook("node.before_change", array(&$node)); $b64Sig = $this->signID($id); if ($this->getFilteredOption("USE_ZOHO_AGENT", $repository->getId())) { $url = $this->getFilteredOption("ZOHO_AGENT_URL", $repository->getId()) . "?ajxp_action=get_file&name=" . $id . "&ext=" . $ext . "&signature=" . $b64Sig; $data = AJXP_Utils::getRemoteContent($url); if (strlen($data)) { file_put_contents($targetFile, $data); echo "MODIFIED"; } } else { if (is_file(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext)) { copy(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext, $targetFile); unlink(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext); echo "MODIFIED"; } } $this->logInfo('Edit', 'Retrieved content of ' . $node->getUrl()); AJXP_Controller::applyHook("node.change", array(null, &$node)); } } }