public static function getRealFSReference($path) { $fake = new ftpAccessWrapper(); $tmpFile = AJXP_Utils::getAjxpTmpDir() . "/" . md5(time()); $tmpHandle = fopen($tmpFile, "wb"); $fake->copyFileInStream($path, $tmpHandle); fclose($tmpHandle); //register_shutdown_function("unlink", $tmpFile); return $tmpFile; }
public static function getRealFSReference($path, $persistent = false) { $tmpFile = AJXP_Utils::getAjxpTmpDir() . "/" . md5(time()); $tmpHandle = fopen($tmpFile, "wb"); self::copyFileInStream($path, $tmpHandle); fclose($tmpHandle); if (!$persistent) { register_shutdown_function(array("AJXP_Utils", "silentUnlink"), $tmpFile); } return $tmpFile; }
/** * Implementation of AjxpStream * * @param String $path * @return string */ public static function getRealFSReference($path, $persistent = false) { if ($persistent) { $tmpFile = AJXP_Utils::getAjxpTmpDir() . "/" . md5(time()); $tmpHandle = fopen($tmpFile, "wb"); self::copyFileInStream($path, $tmpHandle); fclose($tmpHandle); return $tmpFile; } else { return self::initPath($path); } }
/** * @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; }
public function stream_open($url, $mode, $options, &$context) { if ($mode == "w" || $mode == "rw") { $this->crtMode = 'write'; $parts = $this->parseUrl($url); $this->crtParameters = array("get_action" => "put_content", "encode" => "base64", "file" => urldecode(AJXP_Utils::securePath($parts["path"]))); $tmpFileBuffer = realpath(AJXP_Utils::getAjxpTmpDir()) . md5(time()); $this->postFileData = $tmpFileBuffer; $this->fp = fopen($tmpFileBuffer, "w"); } else { $this->crtMode = 'read'; $this->fp = tmpfile(); $this->copyFileInStream($url, $this->fp); rewind($this->fp); } return $this->fp !== false; }
/** * Store the array * @static * @param $loginArray * @return void */ static function setBruteForceLoginArray($loginArray) { $failedLog = AJXP_Utils::getAjxpTmpDir() . "/failedAJXP.log"; @file_put_contents($failedLog, serialize($loginArray)); }
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; }
/** * Prints out and cache the thumbnail. Returns verbose errors. * * @access public * @param string $image The Relative Path to the image * @param integer $width The Width of the new thumbnail * @param integer $height The Height of the thumbnail * @param boolean $return_img Set to true to return the string instead of outputting it. Default to false * @param boolean $display_inline If set to true, heaers sent to browser will instruct it to display the image inline instead of asking the user to download. Defaults to true. * @return string * */ function print_thumbnail($image, $width, $height, $return_img = false, $display_inline = true, $target_file = false) { //Check parameters if (empty($image) || empty($width) || empty($height)) { return $this->set_error("Method print_thumbnail: Missing Parameters"); } if (isset($this->currentRealFile) && is_file($this->currentRealFile)) { $image = $this->currentRealFile; } //Check whether $image is a remote address if ($this->is_remote($image) == 1) { $is_remote = true; //Check that file exists (Check only enabled in PHP 5 because only PHP 5 supports for checking remote files if (phpversion() >= 5) { if (!file_exists($image)) { return $this->set_error("Method print_thumbnail: Error. The file '{$image}' you specified does not exists or cannot be accessed."); } } $image_data = $this->retrieve_remote_file($image, true, false, 1); } elseif ($this->is_remote($image) == 0) { $is_remote = false; if (!file_exists($image)) { return $this->set_error("Method print_thumbnail: Error. The file '{$image}' you specified does not exists or cannot be accessed."); } $image_data = implode("", file($image)); } if (!is_string($image_data)) { return $this->set_error("Method print_thumbnail: Error, could not read image file '{$image}'."); } $array = $this->retrieve_image_data($image); if (!$array) { return $this->set_error("Method print_thumbnail: Unable to determine Image '{$image}' type and/or dimensions."); } list($ori_width, $ori_height, $format) = $array; //Check whether format is supported if (!array_key_exists($format, $this->file_ext)) { return $this->set_error("Method print_thumbnail: Image '{$image}' format is not supported."); } //Check that cache is enabled, cache DIR is writable, cache DIR exists if ($this->is_cacheable()) { //Passed eh? Generate the root dir of request file if ($is_remote != true) { $transformed = realpath($image); $hash = sha1_file($image); } else { $transformed = $image; $hash = sha1($image_data); } //Check if a version exists if ($this->exif_rotation) { $cache_file = $this->cache_dir . sha1($transformed) . "." . $width . "." . $height . ".rotated." . $hash . "." . $this->file_ext[$format]; } else { $cache_file = $this->cache_dir . sha1($transformed) . "." . $width . "." . $height . "." . $hash . "." . $this->file_ext[$format]; } if (file_exists($cache_file)) { if ($return_img == false) { //AJXP_Logger::debug("Using Cache"); //die($cache_file); header("Expires: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Pragma: no-cache"); header("Content-Transfer-Encoding: binary"); header("Content-type: " . image_type_to_mime_type($format)); if ($display_inline == true) { header("Content-Disposition: inline; filename=\"" . time() . "." . $this->file_ext[$format] . "\""); } else { header("Content-Disposition: attachment; filename=\"" . time() . "." . $this->file_ext[$format] . "\""); } print implode("", file($cache_file)); die; //Prepare redirectional URL $redir_url = $_SERVER["HTTP_HOST"] . dirname($_SERVER["PHP_SELF"]) . "/" . $cache_file; //Remove instances of double slashes "//" $redir_url = str_replace("//", "/", $redir_url); header("Location: http://{$redir_url}"); die; } else { return implode("", file($cache_file)); } } else { $handle = @opendir($this->cache_dir); if ($handle !== FALSE) { while (false !== ($file = readdir($handle))) { if ($this->exif_rotation) { $rotated = "\\.rotated"; } else { $rotated = ""; } if (preg_match("/^" . preg_quote(sha1($transformed)) . "\\.[0-9]+\\.[0-9]+" . $rotated . "\\.([0-9a-z]{40})\\.(.+?)\$/i", $file, $matches)) { //Hash is in [1] //Check to see if the file data is the same. If it is, then don't delete it. if ($matches[1] != $hash) { $matched[] = $file; } } } closedir($handle); if (!empty($matched)) { for ($i = 0; $i <= count($matched) - 1; $i++) { @unlink($this->cache_dir . $matched[$i]); } } } } } $gd_info = gd_info(); //Special GIF handling if ($format == 1 && $gd_info["GIF Create Support"] != true) { //return $this -> set_error("Method print_thumbnail: Error, GIF support is unavaliable for PHP Version ".phpversion()); //Image Outputted will be in PNG Format $format = 3; } $handle = @imagecreatefromstring($image_data); if ($handle == false) { return $this->set_error("Method print_thumbnail: Unsupported Image '{$image}' type"); } //Exif Orientation patch $orientation = $this->exiforientation($image, true); if ($this->rotationsupported($orientation) and $orientation > 4) { $width2 = $width; $width = $height; $height = $width2; } //Now lets resize it //First lets create a new image handler which will be the thumbnailed image $thumbnail = imagecreatetruecolor($width, $height); if (!$thumbnail) { return $this->set_error("Method print_thumbnail: A thumbnail image '{$image}' could not be created"); } /* Image Format Special Handlinng */ //GIF truecolour to palette - preserve transparency if ($format == 1) { imagetruecolortopalette($handle, true, 256); } //PNG Alpha Channel saving if ($format == 3) { //Set to save alpha channel info in source and destination imagealphablending($handle, false); imagesavealpha($handle, true); imagealphablending($thumbnail, false); imagesavealpha($thumbnail, true); } //Resize it if (!$this->fastimagecopyresampled($thumbnail, $handle, 0, 0, 0, 0, $width, $height, ImageSX($handle), ImageSY($handle), $this->thumb_quality)) { return $this->set_error("Method print_thumbnail: Failed resizing image '{$image}'."); } // Rotate if JPEG and Exif Information is available $orientation = $this->exiforientation($image, true); if ($this->rotationsupported($orientation)) { switch ($orientation) { case 2: // mirror horizontal @imageflip($thumbnail, IMG_FLIP_HORIZONTAL); break; case 3: // rotate 180 $thumbnail = @imagerotate($thumbnail, 180, imagecolorallocate($thumbnail, 255, 255, 255)); break; case 4: // mirror vertical @imageflip($thumbnail, IMG_FLIP_VERTICAL); break; case 5: // mirror horizontal, 90 rotate left @imageflip($thumbnail, IMG_FLIP_HORIZONTAL); $thumbnail = @imagerotate($thumbnail, 90, imagecolorallocate($thumbnail, 255, 255, 255)); break; case 6: // 90 rotate right $thumbnail = @imagerotate($thumbnail, -90, imagecolorallocate($thumbnail, 255, 255, 255)); break; case 7: // mirror horizontal, 90 rotate right @imageflip($thumbnail, IMG_FLIP_HORIZONTAL); $thumbnail = @imagerotate($thumbnail, -90, imagecolorallocate($thumbnail, 255, 255, 255)); break; case 8: // 90 rotate left $thumbnail = @imagerotate($thumbnail, 90, imagecolorallocate($thumbnail, 255, 255, 255)); break; } } //Cache it if ($this->is_cacheable()) { switch ($format) { case 1: $cached = @imagegif($thumbnail, $cache_file); break; case 2: $cached = @imageJPEG($thumbnail, $cache_file, 100); break; case 3: $cached = @imagepng($thumbnail, $cache_file); break; case 15: $cached = @imagewbmp($thumbnail, $cache_file); break; case 16: $cached = @imagexbm($thumbnail, $cache_file); break; default: $cached = false; } if (!$cached) { return $this->set_error("Method print_thumbnail 1: Error in cache generation of image '{$image}'."); } } if ($target_file != false) { $wrappers = stream_get_wrappers(); $wrappers_re = '(' . implode('|', $wrappers) . ')'; $isStream = preg_match("!^{$wrappers_re}://!", $target_file) === 1; if ($isStream) { $backToStreamTarget = $target_file; $target_file = tempnam(AJXP_Utils::getAjxpTmpDir(), "pthumb_"); } switch ($format) { case 1: $cached = @imagegif($thumbnail, $target_file); break; case 2: $cached = @imageJPEG($thumbnail, $target_file, 100); break; case 3: $cached = @imagepng($thumbnail, $target_file); break; case 15: $cached = @imagewbmp($thumbnail, $target_file); break; case 16: $cached = @imagexbm($thumbnail, $target_file); break; default: $cached = false; } if ($cached && $isStream) { $cached = @copy($target_file, $backToStreamTarget); @unlink($target_file); } if (!$cached) { return $this->set_error("Method print_thumbnail: Error in cache generation of image '{$image}'."); } return true; } if ($return_img == false) { header("Expires: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Pragma: no-cache"); header("Content-Transfer-Encoding: binary"); header("Content-type: " . image_type_to_mime_type($format)); if ($display_inline == true) { header("Content-Disposition: inline; filename=\"" . time() . "." . $this->file_ext[$format] . "\""); } else { header("Content-Disposition: attachment; filename=\"" . time() . "." . $this->file_ext[$format] . "\""); } if ($this->is_cacheable()) { echo implode("", file($cache_file)); } else { switch ($format) { case 1: $outputed = @imagegif($thumbnail); break; case 2: $outputed = @imageJPEG($thumbnail, null, 100); break; case 3: $outputed = @imagepng($thumbnail); break; case 15: $outpupted = @imagewbmp($thumbnail); break; case 16: $outputed = @imagexbm($thumbnail, NULL); break; default: $outputed = false; } if (!$outputed) { return $this->set_error("Method print_thumbnail: Error outputting Image '{$image}'"); } } } else { if ($this->is_cacheable()) { return implode("", file($cache_file)); } else { return $this->set_error("Method print_thumbnail: Cannot return image '{$image}'! Cache must be enabled!"); } } //Destroy the image imagedestroy($handle); imagedestroy($thumbnail); //Clear any cache; if needed $this->clear_cache(); }
// you must ensure that you have included PclError library. // [2,...] : reserved for futur use if (!defined('PCLZIP_ERROR_EXTERNAL')) { define('PCLZIP_ERROR_EXTERNAL', 0); } // ----- Optional static temporary directory // By default temporary files are generated in the script current // path. // If defined : // - MUST BE terminated by a '/'. // - MUST be a valid, already created directory // Samples : // define( 'PCLZIP_TEMPORARY_DIR', '/temp/' ); // define( 'PCLZIP_TEMPORARY_DIR', 'C:/Temp/' ); if (!defined('PCLZIP_TEMPORARY_DIR')) { define('PCLZIP_TEMPORARY_DIR', AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR); } // ----- Optional threshold ratio for use of temporary files // Pclzip sense the size of the file to add/extract and decide to // use or not temporary file. The algorythm is looking for // memory_limit of PHP and apply a ratio. // threshold = memory_limit * ratio. // Recommended values are under 0.5. Default 0.47. // Samples : // define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.5 ); if (!defined('PCLZIP_TEMPORARY_FILE_RATIO')) { define('PCLZIP_TEMPORARY_FILE_RATIO', 0.47); } // -------------------------------------------------------------------------------- // ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED ***** // --------------------------------------------------------------------------------
/** * Initialize the stream from the given path. * * @param string $path * @return mixed Real path or -1 if currentListing contains the listing : original path converted to real path */ protected static function initPath($path, $streamType, $storeOpenContext = false, $skipZip = false) { $path = self::unPatchPathForBaseDir($path); $url = parse_url($path); $repoId = $url["host"]; if (isset($url["fragment"]) && strlen($url["fragment"]) > 0) { $url["path"] .= "#" . $url["fragment"]; } $repoObject = ConfService::getRepositoryById($repoId); if (!isset($repoObject)) { throw new Exception("Cannot find repository with id " . $repoId); } $split = UserSelection::detectZip($url["path"]); $insideZip = false; if ($split && $streamType == "file" && $split[1] != "/") { $insideZip = true; } if ($split && $streamType == "dir") { $insideZip = true; } if ($skipZip) { $insideZip = false; } //var_dump($path); //var_dump($skipZip); // Inside a zip : copy the file to a tmp file and return a reference to it if ($insideZip) { $zipPath = $split[0]; $localPath = $split[1]; require_once AJXP_BIN_FOLDER . "/pclzip.lib.php"; //print($streamType.$path); if ($streamType == "file") { if (self::$crtZip == null || !is_array(self::$currentListingKeys)) { $tmpDir = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . md5(time() - rand()); mkdir($tmpDir); $tmpFileName = $tmpDir . DIRECTORY_SEPARATOR . basename($localPath); AJXP_Logger::debug("Tmp file {$tmpFileName}"); register_shutdown_function(array("fsAccessWrapper", "removeTmpFile"), $tmpDir, $tmpFileName); $crtZip = new PclZip(AJXP_Utils::securePath(realpath($repoObject->getOption("PATH")) . $zipPath)); $content = $crtZip->listContent(); foreach ($content as $item) { $fName = AJXP_Utils::securePath($item["stored_filename"]); if ($fName == $localPath || "/" . $fName == $localPath) { $localPath = $fName; break; } } $res = $crtZip->extract(PCLZIP_OPT_BY_NAME, $localPath, PCLZIP_OPT_PATH, $tmpDir, PCLZIP_OPT_REMOVE_ALL_PATH); AJXP_Logger::debug("Extracted " . $path . " to " . dirname($localPath)); if ($storeOpenContext) { self::$crtZip = $crtZip; } return $tmpFileName; } else { $key = basename($localPath); if (array_key_exists($key, self::$currentListing)) { self::$currentFileKey = $key; return -1; } else { throw new AJXP_Exception("Cannot find key"); } } } else { $crtZip = new PclZip(AJXP_Utils::securePath(realpath($repoObject->getOption("PATH")) . $zipPath)); $liste = $crtZip->listContent(); if ($storeOpenContext) { self::$crtZip = $crtZip; } $folders = array(); $files = array(); $builtFolders = array(); if ($localPath[strlen($localPath) - 1] != "/") { $localPath .= "/"; } foreach ($liste as $item) { $stored = $item["stored_filename"]; if ($stored[0] != "/") { $stored = "/" . $stored; } $pathPos = strpos($stored, $localPath); if ($pathPos !== false) { $afterPath = substr($stored, $pathPos + strlen($localPath)); if ($afterPath != "" && substr_count($afterPath, "/") < 2) { $statValue = array(); if (substr_count($afterPath, "/") == 0) { $statValue[2] = $statValue["mode"] = $item["folder"] ? "00040000" : "0100000"; $statValue[7] = $statValue["size"] = $item["size"]; $statValue[8] = $statValue["atime"] = $item["mtime"]; $statValue[9] = $statValue["mtime"] = $item["mtime"]; $statValue[10] = $statValue["ctime"] = $item["mtime"]; if (strpos($afterPath, "/") == strlen($afterPath) - 1) { $afterPath = substr($afterPath, 0, strlen($afterPath) - 1); } //$statValue["filename"] = $zipPath.$localPath.$afterPath; if ($item["folder"]) { $folders[$afterPath] = $statValue; } else { $files[$afterPath] = $statValue; } } else { $arr = explode("/", $afterPath); $afterPath = array_shift($arr); if (isset($folders[$afterPath]) || isset($builtFolders[$afterPath])) { continue; } $statValue[2] = $statValue["mode"] = "00040000"; $statValue[7] = $statValue["size"] = 0; $statValue[8] = $statValue["atime"] = $item["mtime"]; $statValue[9] = $statValue["mtime"] = $item["mtime"]; $statValue[10] = $statValue["ctime"] = $item["mtime"]; $builtFolders[$afterPath] = $statValue; } } } } self::$currentListing = array_merge($folders, $builtFolders, $files); self::$currentListingKeys = array_keys(self::$currentListing); self::$currentListingIndex = 0; return -1; } } else { return realpath($repoObject->getOption("PATH")) . $url["path"]; } }
public static function parseStandardFormParameters(&$repDef, &$options, $userId = null, $prefix = "DRIVER_OPTION_", $binariesContext = null, $cypheredPassPrefix = "") { if ($binariesContext === null) { $binariesContext = array("USER" => AuthService::getLoggedUser() != null ? AuthService::getLoggedUser()->getId() : "shared"); } $replicationGroups = array(); $switchesGroups = array(); foreach ($repDef as $key => $value) { if ((!empty($prefix) && strpos($key, $prefix) !== false && strpos($key, $prefix) == 0 || empty($prefix)) && strpos($key, "ajxptype") === false && strpos($key, "_original_binary") === false && strpos($key, "_replication") === false && strpos($key, "_checkbox") === false) { if (isset($repDef[$key . "_ajxptype"])) { $type = $repDef[$key . "_ajxptype"]; if ($type == "boolean") { $value = $value == "true" ? true : false; } else { if ($type == "integer") { $value = intval($value); } else { if ($type == "array") { $value = explode(",", $value); } else { if ($type == "password" && $userId != null) { if (trim($value) != "" && $value != "__AJXP_VALUE_SET__" && function_exists('mcrypt_encrypt')) { // We encode as base64 so if we need to store the result in a database, it can be stored in text column $value = $cypheredPassPrefix . base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($userId . "CDAFx¨op#"), $value, MCRYPT_MODE_ECB)); } } else { if ($type == "binary" && $binariesContext !== null) { if (!empty($value)) { if ($value == "ajxp-remove-original") { if (!empty($repDef[$key . "_original_binary"])) { ConfService::getConfStorageImpl()->deleteBinary($binariesContext, $repDef[$key . "_original_binary"]); } $value = ""; } else { $file = AJXP_Utils::getAjxpTmpDir() . "/" . $value; if (file_exists($file)) { $id = !empty($repDef[$key . "_original_binary"]) ? $repDef[$key . "_original_binary"] : null; $id = ConfService::getConfStorageImpl()->saveBinary($binariesContext, $file, $id); $value = $id; } } } else { if (!empty($repDef[$key . "_original_binary"])) { $value = $repDef[$key . "_original_binary"]; } } } else { if (strpos($type, "group_switch:") === 0) { $tmp = explode(":", $type); $gSwitchName = $tmp[1]; $switchesGroups[substr($key, strlen($prefix))] = $gSwitchName; } else { if ($type == "text/json") { $value = json_decode($value, true); } } } } } } } if (!in_array($type, array("textarea", "boolean", "text/json"))) { $value = AJXP_Utils::sanitize($value, AJXP_SANITIZE_HTML); } unset($repDef[$key . "_ajxptype"]); } if (isset($repDef[$key . "_checkbox"])) { $checked = $repDef[$key . "_checkbox"] == "checked"; unset($repDef[$key . "_checkbox"]); if (!$checked) { continue; } } if (isset($repDef[$key . "_replication"])) { $repKey = $repDef[$key . "_replication"]; if (!is_array($replicationGroups[$repKey])) { $replicationGroups[$repKey] = array(); } $replicationGroups[$repKey][] = $key; } $options[substr($key, strlen($prefix))] = $value; unset($repDef[$key]); } else { $repDef[$key] = $value; } } // DO SOMETHING WITH REPLICATED PARAMETERS? if (count($switchesGroups)) { $gValues = array(); foreach ($switchesGroups as $fieldName => $groupName) { if (isset($options[$fieldName])) { $gValues = array(); $radic = $groupName . "_" . $options[$fieldName] . "_"; foreach ($options as $optN => $optV) { if (strpos($optN, $radic) === 0) { $newName = substr($optN, strlen($radic)); $gValues[$newName] = $optV; } } } $options[$fieldName . "_group_switch"] = $options[$fieldName]; $options[$fieldName] = $gValues; } } }
/** * @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); } } } }
public function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } parent::accessPreprocess($action, $httpVars, $fileVars); $selection = new UserSelection(); $dir = $httpVars["dir"] or ""; if ($this->wrapperClassName == "fsAccessWrapper") { $dir = fsAccessWrapper::patchPathForBaseDir($dir); } $dir = AJXP_Utils::securePath($dir); if ($action != "upload") { $dir = AJXP_Utils::decodeSecureMagic($dir); } $selection->initFromHttpVars($httpVars); if (!$selection->isEmpty()) { $this->filterUserSelectionToHidden($selection->getFiles()); } $mess = ConfService::getMessages(); $newArgs = RecycleBinManager::filterActions($action, $selection, $dir, $httpVars); if (isset($newArgs["action"])) { $action = $newArgs["action"]; } if (isset($newArgs["dest"])) { $httpVars["dest"] = SystemTextEncoding::toUTF8($newArgs["dest"]); } //Re-encode! // FILTER DIR PAGINATION ANCHOR $page = null; if (isset($dir) && strstr($dir, "%23") !== false) { $parts = explode("%23", $dir); $dir = $parts[0]; $page = $parts[1]; } $pendingSelection = ""; $logMessage = null; $reloadContextNode = false; switch ($action) { //------------------------------------ // DOWNLOAD //------------------------------------ case "download": $this->logInfo("Download", array("files" => $this->addSlugToPath($selection))); @set_error_handler(array("HTMLWriter", "javascriptErrorHandler"), E_ALL & ~E_NOTICE); @register_shutdown_function("restore_error_handler"); $zip = false; if ($selection->isUnique()) { if (is_dir($this->urlBase . $selection->getUniqueFile())) { $zip = true; $base = basename($selection->getUniqueFile()); $uniqDir = dirname($selection->getUniqueFile()); if (!empty($uniqDir) && $uniqDir != "/") { $dir = dirname($selection->getUniqueFile()); } } else { if (!file_exists($this->urlBase . $selection->getUniqueFile())) { throw new Exception("Cannot find file!"); } } $node = $selection->getUniqueNode($this); } else { $zip = true; } if ($zip) { // Make a temp zip and send it as download $loggedUser = AuthService::getLoggedUser(); $file = AJXP_Utils::getAjxpTmpDir() . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "_" . time() . "tmpDownload.zip"; $zipFile = $this->makeZip($selection->getFiles(), $file, empty($dir) ? "/" : $dir); if (!$zipFile) { throw new AJXP_Exception("Error while compressing"); } if (!$this->getFilteredOption("USE_XSENDFILE", $this->repository->getId()) && !$this->getFilteredOption("USE_XACCELREDIRECT", $this->repository->getId())) { register_shutdown_function("unlink", $file); } $localName = ($base == "" ? "Files" : $base) . ".zip"; if (isset($httpVars["archive_name"])) { $localName = AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]); } $this->readFile($file, "force-download", $localName, false, false, true); } else { $localName = ""; AJXP_Controller::applyHook("dl.localname", array($this->urlBase . $selection->getUniqueFile(), &$localName, $this->wrapperClassName)); $this->readFile($this->urlBase . $selection->getUniqueFile(), "force-download", $localName); } if (isset($node)) { AJXP_Controller::applyHook("node.read", array(&$node)); } break; case "prepare_chunk_dl": $chunkCount = intval($httpVars["chunk_count"]); $fileId = $this->urlBase . $selection->getUniqueFile(); $sessionKey = "chunk_file_" . md5($fileId . time()); $totalSize = $this->filesystemFileSize($fileId); $chunkSize = intval($totalSize / $chunkCount); $realFile = call_user_func(array($this->wrapperClassName, "getRealFSReference"), $fileId, true); $chunkData = array("localname" => basename($fileId), "chunk_count" => $chunkCount, "chunk_size" => $chunkSize, "total_size" => $totalSize, "file_id" => $sessionKey); $_SESSION[$sessionKey] = array_merge($chunkData, array("file" => $realFile)); HTMLWriter::charsetHeader("application/json"); print json_encode($chunkData); $node = $selection->getUniqueNode($this); AJXP_Controller::applyHook("node.read", array(&$node)); break; case "download_chunk": $chunkIndex = intval($httpVars["chunk_index"]); $chunkKey = $httpVars["file_id"]; $sessData = $_SESSION[$chunkKey]; $realFile = $sessData["file"]; $chunkSize = $sessData["chunk_size"]; $offset = $chunkSize * $chunkIndex; if ($chunkIndex == $sessData["chunk_count"] - 1) { // Compute the last chunk real length $chunkSize = $sessData["total_size"] - $chunkSize * ($sessData["chunk_count"] - 1); if (call_user_func(array($this->wrapperClassName, "isRemote"))) { register_shutdown_function("unlink", $realFile); } } $this->readFile($realFile, "force-download", $sessData["localname"] . "." . sprintf("%03d", $chunkIndex + 1), false, false, true, $offset, $chunkSize); break; case "compress": // Make a temp zip and send it as download $loggedUser = AuthService::getLoggedUser(); if (isset($httpVars["archive_name"])) { $localName = AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]); $this->filterUserSelectionToHidden(array($localName)); } else { $localName = (basename($dir) == "" ? "Files" : basename($dir)) . ".zip"; } $file = AJXP_Utils::getAjxpTmpDir() . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "_" . time() . "tmpCompression.zip"; if (isset($httpVars["compress_flat"])) { $baseDir = "__AJXP_ZIP_FLAT__/"; } else { $baseDir = $dir; } $zipFile = $this->makeZip($selection->getFiles(), $file, $baseDir); if (!$zipFile) { throw new AJXP_Exception("Error while compressing file {$localName}"); } register_shutdown_function("unlink", $file); $tmpFNAME = $this->urlBase . $dir . "/" . str_replace(".zip", ".tmp", $localName); copy($file, $tmpFNAME); try { AJXP_Controller::applyHook("node.before_create", array(new AJXP_Node($tmpFNAME), filesize($tmpFNAME))); } catch (Exception $e) { @unlink($tmpFNAME); throw $e; } @rename($tmpFNAME, $this->urlBase . $dir . "/" . $localName); AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($this->urlBase . $dir . "/" . $localName), false)); //$reloadContextNode = true; //$pendingSelection = $localName; $newNode = new AJXP_Node($this->urlBase . $dir . "/" . $localName); if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } $nodesDiffs["ADD"][] = $newNode; break; case "stat": clearstatcache(); header("Content-type:application/json"); if ($selection->isUnique()) { $stat = @stat($this->urlBase . $selection->getUniqueFile()); if (!$stat) { print '{}'; } else { print json_encode($stat); } } else { $files = $selection->getFiles(); print '{'; foreach ($files as $index => $path) { $stat = @stat($this->urlBase . $path); if (!$stat) { $stat = '{}'; } else { $stat = json_encode($stat); } print json_encode($path) . ':' . $stat . ($index < count($files) - 1 ? "," : ""); } print '}'; } break; //------------------------------------ // ONLINE EDIT //------------------------------------ //------------------------------------ // ONLINE EDIT //------------------------------------ case "get_content": $dlFile = $this->urlBase . $selection->getUniqueFile(); $this->logInfo("Get_content", array("files" => $this->addSlugToPath($selection))); if (AJXP_Utils::getStreamingMimeType(basename($dlFile)) !== false) { $this->readFile($this->urlBase . $selection->getUniqueFile(), "stream_content"); } else { $this->readFile($this->urlBase . $selection->getUniqueFile(), "plain"); } $node = $selection->getUniqueNode($this); AJXP_Controller::applyHook("node.read", array(&$node)); break; case "put_content": if (!isset($httpVars["content"])) { break; } // Load "code" variable directly from POST array, do not "securePath" or "sanitize"... $code = $httpVars["content"]; $file = $selection->getUniqueFile(); $this->logInfo("Online Edition", array("file" => $this->addSlugToPath($file))); if (isset($httpVars["encode"]) && $httpVars["encode"] == "base64") { $code = base64_decode($code); } else { $code = str_replace("<", "<", SystemTextEncoding::magicDequote($code)); } $fileName = $this->urlBase . $file; $currentNode = new AJXP_Node($fileName); try { AJXP_Controller::applyHook("node.before_change", array(&$currentNode, strlen($code))); } catch (Exception $e) { header("Content-Type:text/plain"); print $e->getMessage(); return; } if (!is_file($fileName) || !$this->isWriteable($fileName, "file")) { header("Content-Type:text/plain"); print !$this->isWriteable($fileName, "file") ? "1001" : "1002"; return; } $fp = fopen($fileName, "w"); fputs($fp, $code); fclose($fp); clearstatcache(true, $fileName); AJXP_Controller::applyHook("node.change", array($currentNode, $currentNode, false)); header("Content-Type:text/plain"); print $mess[115]; break; //------------------------------------ // COPY / MOVE //------------------------------------ //------------------------------------ // COPY / MOVE //------------------------------------ case "copy": case "move": //throw new AJXP_Exception("", 113); if ($selection->isEmpty()) { throw new AJXP_Exception("", 113); } $loggedUser = AuthService::getLoggedUser(); if ($loggedUser != null && !$loggedUser->canWrite(ConfService::getCurrentRepositoryId())) { throw new AJXP_Exception("You are not allowed to write", 207); } $success = $error = array(); $dest = AJXP_Utils::decodeSecureMagic($httpVars["dest"]); $this->filterUserSelectionToHidden(array($httpVars["dest"])); if ($selection->inZip()) { // Set action to copy anycase (cannot move from the zip). $action = "copy"; $this->extractArchive($dest, $selection, $error, $success); } else { $move = $action == "move" ? true : false; if ($move && isset($httpVars["force_copy_delete"])) { $move = false; } $this->copyOrMove($dest, $selection->getFiles(), $error, $success, $move); } if (count($error)) { throw new AJXP_Exception(SystemTextEncoding::toUTF8(join("\n", $error))); } else { if (isset($httpVars["force_copy_delete"])) { $errorMessage = $this->delete($selection->getFiles(), $logMessages); if ($errorMessage) { throw new AJXP_Exception(SystemTextEncoding::toUTF8($errorMessage)); } $this->logInfo("Copy/Delete", array("files" => $this->addSlugToPath($selection), "destination" => $this->addSlugToPath($dest))); } else { $this->logInfo($action == "move" ? "Move" : "Copy", array("files" => $this->addSlugToPath($selection), "destination" => $this->addSlugToPath($dest))); } $logMessage = join("\n", $success); } if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } // Assume new nodes are correctly created $selectedItems = $selection->getFiles(); foreach ($selectedItems as $selectedPath) { $newPath = $this->urlBase . $dest . "/" . basename($selectedPath); $newNode = new AJXP_Node($newPath); $nodesDiffs["ADD"][] = $newNode; if ($action == "move") { $nodesDiffs["REMOVE"][] = $selectedPath; } } if (!(RecycleBinManager::getRelativeRecycle() == $dest && $this->getFilteredOption("HIDE_RECYCLE", $this->repository->getId()) == true)) { //$reloadDataNode = $dest; } break; //------------------------------------ // DELETE //------------------------------------ //------------------------------------ // DELETE //------------------------------------ case "delete": if ($selection->isEmpty()) { throw new AJXP_Exception("", 113); } $logMessages = array(); $errorMessage = $this->delete($selection->getFiles(), $logMessages); if (count($logMessages)) { $logMessage = join("\n", $logMessages); } if ($errorMessage) { throw new AJXP_Exception(SystemTextEncoding::toUTF8($errorMessage)); } $this->logInfo("Delete", array("files" => $this->addSlugToPath($selection))); if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } $nodesDiffs["REMOVE"] = array_merge($nodesDiffs["REMOVE"], $selection->getFiles()); break; case "purge": $hardPurgeTime = intval($this->repository->getOption("PURGE_AFTER")) * 3600 * 24; $softPurgeTime = intval($this->repository->getOption("PURGE_AFTER_SOFT")) * 3600 * 24; $shareCenter = AJXP_PluginsService::findPluginById('action.share'); if (!($shareCenter && $shareCenter->isEnabled())) { //action.share is disabled, don't look at the softPurgeTime $softPurgeTime = 0; } if ($hardPurgeTime > 0 || $softPurgeTime > 0) { $this->recursivePurge($this->urlBase, $hardPurgeTime, $softPurgeTime); } break; //------------------------------------ // RENAME //------------------------------------ //------------------------------------ // RENAME //------------------------------------ case "rename": $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); $filename_new = AJXP_Utils::decodeSecureMagic($httpVars["filename_new"]); $dest = null; if (isset($httpVars["dest"])) { $dest = AJXP_Utils::decodeSecureMagic($httpVars["dest"]); $filename_new = ""; } $this->filterUserSelectionToHidden(array($filename_new)); $this->rename($file, $filename_new, $dest); $logMessage = SystemTextEncoding::toUTF8($file) . " {$mess['41']} " . SystemTextEncoding::toUTF8($filename_new); //$reloadContextNode = true; //$pendingSelection = $filename_new; if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } if ($dest == null) { $dest = AJXP_Utils::safeDirname($file); } $nodesDiffs["UPDATE"][$file] = new AJXP_Node($this->urlBase . $dest . "/" . $filename_new); $this->logInfo("Rename", array("original" => $this->addSlugToPath($file), "new" => $filename_new)); break; //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ case "mkdir": $messtmp = ""; if (!isset($httpVars["dirname"])) { $uniq = $selection->getUniqueFile(); $dir = AJXP_Utils::safeDirname($uniq); $dirname = AJXP_Utils::safeBasename($uniq); } else { $dirname = AJXP_Utils::decodeSecureMagic($httpVars["dirname"], AJXP_SANITIZE_FILENAME); } $dirname = substr($dirname, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH")); $this->filterUserSelectionToHidden(array($dirname)); AJXP_Controller::applyHook("node.before_create", array(new AJXP_Node($dir . "/" . $dirname), -2)); $error = $this->mkDir($dir, $dirname, isset($httpVars["ignore_exists"]) ? true : false); if (isset($error)) { throw new AJXP_Exception($error); } $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; //$pendingSelection = $dirname; //$reloadContextNode = true; $newNode = new AJXP_Node($this->urlBase . $dir . "/" . $dirname); if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } array_push($nodesDiffs["ADD"], $newNode); $this->logInfo("Create Dir", array("dir" => $this->addSlugToPath($dir) . "/" . $dirname)); break; //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ case "mkfile": $messtmp = ""; if (empty($httpVars["filename"]) && isset($httpVars["node"])) { $filename = AJXP_Utils::decodeSecureMagic($httpVars["node"], AJXP_SANITIZE_FILENAME); } else { $filename = AJXP_Utils::decodeSecureMagic($httpVars["filename"], AJXP_SANITIZE_FILENAME); } $filename = substr($filename, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH")); $this->filterUserSelectionToHidden(array($filename)); $content = ""; if (isset($httpVars["content"])) { $content = $httpVars["content"]; } $error = $this->createEmptyFile($dir, $filename, $content); if (isset($error)) { throw new AJXP_Exception($error); } $messtmp .= "{$mess['34']} " . SystemTextEncoding::toUTF8($filename) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; //$reloadContextNode = true; //$pendingSelection = $dir."/".$filename; $this->logInfo("Create File", array("file" => $this->addSlugToPath($dir) . "/" . $filename)); $newNode = new AJXP_Node($this->urlBase . $dir . "/" . $filename); if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } array_push($nodesDiffs["ADD"], $newNode); break; //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ case "chmod": $files = $selection->getFiles(); $changedFiles = array(); $chmod_value = $httpVars["chmod_value"]; $recursive = $httpVars["recursive"]; $recur_apply_to = $httpVars["recur_apply_to"]; foreach ($files as $fileName) { $this->chmod($fileName, $chmod_value, $recursive == "on", $recursive == "on" ? $recur_apply_to : "both", $changedFiles); } $logMessage = "Successfully changed permission to " . $chmod_value . " for " . count($changedFiles) . " files or folders"; $this->logInfo("Chmod", array("dir" => $this->addSlugToPath($dir), "filesCount" => count($changedFiles))); if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } $nodesDiffs["UPDATE"] = array_merge($nodesDiffs["UPDATE"], $selection->buildNodes($this)); break; //------------------------------------ // UPLOAD //------------------------------------ //------------------------------------ // UPLOAD //------------------------------------ case "upload": $repoData = array('base_url' => $this->urlBase, 'wrapper_name' => $this->wrapperClassName, 'chmod' => $this->repository->getOption('CHMOD_VALUE'), 'recycle' => $this->repository->getOption('RECYCLE_BIN')); $this->logDebug("Upload Files Data", $fileVars); $destination = $this->urlBase . AJXP_Utils::decodeSecureMagic($dir); $this->logDebug("Upload inside", array("destination" => $this->addSlugToPath($destination))); if (!$this->isWriteable($destination)) { $errorCode = 412; $errorMessage = "{$mess['38']} " . SystemTextEncoding::toUTF8($dir) . " {$mess['99']}."; $this->logDebug("Upload error 412", array("destination" => $this->addSlugToPath($destination))); return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage)); } foreach ($fileVars as $boxName => $boxData) { if (substr($boxName, 0, 9) != "userfile_") { continue; } $err = AJXP_Utils::parseFileDataErrors($boxData); if ($err != null) { $errorCode = $err[0]; $errorMessage = $err[1]; break; } $userfile_name = $boxData["name"]; try { $this->filterUserSelectionToHidden(array($userfile_name)); } catch (Exception $e) { return array("ERROR" => array("CODE" => 411, "MESSAGE" => "Forbidden")); } $userfile_name = AJXP_Utils::sanitize(SystemTextEncoding::fromPostedFileName($userfile_name), AJXP_SANITIZE_FILENAME); if (isset($httpVars["urlencoded_filename"])) { $userfile_name = AJXP_Utils::sanitize(SystemTextEncoding::fromUTF8(urldecode($httpVars["urlencoded_filename"])), AJXP_SANITIZE_FILENAME); } $this->logDebug("User filename " . $userfile_name); $userfile_name = substr($userfile_name, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH")); if (isset($httpVars["auto_rename"])) { $userfile_name = self::autoRenameForDest($destination, $userfile_name); } $already_existed = false; try { if (file_exists($destination . "/" . $userfile_name)) { $already_existed = true; AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($destination . "/" . $userfile_name), $boxData["size"])); } else { AJXP_Controller::applyHook("node.before_create", array(new AJXP_Node($destination . "/" . $userfile_name), $boxData["size"])); } AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($destination))); } catch (Exception $e) { $errorCode = 507; $errorMessage = $e->getMessage(); break; } if (isset($boxData["input_upload"])) { try { $this->logDebug("Begining reading INPUT stream"); $input = fopen("php://input", "r"); $output = fopen("{$destination}/" . $userfile_name, "w"); $sizeRead = 0; while ($sizeRead < intval($boxData["size"])) { $chunk = fread($input, 4096); $sizeRead += strlen($chunk); fwrite($output, $chunk, strlen($chunk)); } fclose($input); fclose($output); $this->logDebug("End reading INPUT stream"); } catch (Exception $e) { $errorCode = 411; $errorMessage = $e->getMessage(); break; } } else { $result = @move_uploaded_file($boxData["tmp_name"], "{$destination}/" . $userfile_name); if (!$result) { $realPath = call_user_func(array($this->wrapperClassName, "getRealFSReference"), "{$destination}/" . $userfile_name); $result = move_uploaded_file($boxData["tmp_name"], $realPath); } if (!$result) { $errorCode = 411; $errorMessage = "{$mess['33']} " . $userfile_name; break; } } if (isset($httpVars["appendto_urlencoded_part"])) { $appendTo = AJXP_Utils::sanitize(SystemTextEncoding::fromUTF8(urldecode($httpVars["appendto_urlencoded_part"])), AJXP_SANITIZE_FILENAME); if (file_exists($destination . "/" . $appendTo)) { $this->logDebug("Should copy stream from {$userfile_name} to {$appendTo}"); $partO = fopen($destination . "/" . $userfile_name, "r"); $appendF = fopen($destination . "/" . $appendTo, "a+"); while (!feof($partO)) { $buf = fread($partO, 1024); fwrite($appendF, $buf, strlen($buf)); } fclose($partO); fclose($appendF); $this->logDebug("Done, closing streams!"); } @unlink($destination . "/" . $userfile_name); $userfile_name = $appendTo; } $this->changeMode($destination . "/" . $userfile_name, $repoData); $createdNode = new AJXP_Node($destination . "/" . $userfile_name); //AJXP_Controller::applyHook("node.change", array(null, $createdNode, false)); $logMessage .= "{$mess['34']} " . SystemTextEncoding::toUTF8($userfile_name) . " {$mess['35']} {$dir}"; $this->logInfo("Upload File", array("file" => $this->addSlugToPath(SystemTextEncoding::fromUTF8($dir)) . "/" . $userfile_name)); } if (isset($errorMessage)) { $this->logDebug("Return error {$errorCode} {$errorMessage}"); return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage)); } else { $this->logDebug("Return success"); if ($already_existed) { return array("SUCCESS" => true, "UPDATED_NODE" => $createdNode); } else { return array("SUCCESS" => true, "CREATED_NODE" => $createdNode); } } return; break; case "lsync": if (!ConfService::currentContextIsCommandLine()) { die("This command must be accessed via CLI only."); } $fromNode = null; $toNode = null; $copyOrMove = false; if (isset($httpVars["from"])) { $fromNode = new AJXP_Node($this->urlBase . AJXP_Utils::decodeSecureMagic($httpVars["from"])); } if (isset($httpVars["to"])) { $toNode = new AJXP_Node($this->urlBase . AJXP_Utils::decodeSecureMagic($httpVars["to"])); } if (isset($httpVars["copy"]) && $httpVars["copy"] == "true") { $copyOrMove = true; } AJXP_Controller::applyHook("node.change", array($fromNode, $toNode, $copyOrMove)); break; //------------------------------------ // XML LISTING //------------------------------------ //------------------------------------ // XML LISTING //------------------------------------ case "ls": if (!isset($dir) || $dir == "/") { $dir = ""; } $lsOptions = $this->parseLsOptions(isset($httpVars["options"]) ? $httpVars["options"] : "a"); $startTime = microtime(); if (isset($httpVars["file"])) { $uniqueFile = AJXP_Utils::decodeSecureMagic($httpVars["file"]); } $dir = AJXP_Utils::securePath($dir); $path = $this->urlBase . ($dir != "" ? ($dir[0] == "/" ? "" : "/") . $dir : ""); $nonPatchedPath = $path; if ($this->wrapperClassName == "fsAccessWrapper") { $nonPatchedPath = fsAccessWrapper::unPatchPathForBaseDir($path); } if ($this->getFilteredOption("REMOTE_SORTING")) { $orderDirection = isset($httpVars["order_direction"]) ? strtolower($httpVars["order_direction"]) : "asc"; $orderField = isset($httpVars["order_column"]) ? $httpVars["order_column"] : null; if ($orderField != null && !in_array($orderField, array("ajxp_label", "filesize", "ajxp_modiftime", "mimestring"))) { $orderField = "ajxp_label"; } } if (isset($httpVars["recursive"]) && $httpVars["recursive"] == "true") { $max_depth = isset($httpVars["max_depth"]) ? intval($httpVars["max_depth"]) : 0; $max_nodes = isset($httpVars["max_nodes"]) ? intval($httpVars["max_nodes"]) : 0; $crt_depth = isset($httpVars["crt_depth"]) ? intval($httpVars["crt_depth"]) + 1 : 1; $crt_nodes = isset($httpVars["crt_nodes"]) ? intval($httpVars["crt_nodes"]) : 0; } else { $threshold = $this->repository->getOption("PAGINATION_THRESHOLD"); if (!isset($threshold) || intval($threshold) == 0) { $threshold = 500; } $limitPerPage = $this->repository->getOption("PAGINATION_NUMBER"); if (!isset($limitPerPage) || intval($limitPerPage) == 0) { $limitPerPage = 200; } } $countFiles = $this->countFiles($path, !$lsOptions["f"]); if (isset($crt_nodes)) { $crt_nodes += $countFiles; } if (isset($threshold) && isset($limitPerPage) && $countFiles > $threshold) { if (isset($uniqueFile)) { $originalLimitPerPage = $limitPerPage; $offset = $limitPerPage = 0; } else { $offset = 0; $crtPage = 1; if (isset($page)) { $offset = (intval($page) - 1) * $limitPerPage; $crtPage = $page; } $totalPages = floor($countFiles / $limitPerPage) + 1; } } else { $offset = $limitPerPage = 0; } $metaData = array(); if (RecycleBinManager::recycleEnabled() && $dir == "") { $metaData["repo_has_recycle"] = "true"; } $parentAjxpNode = new AJXP_Node($nonPatchedPath, $metaData); $parentAjxpNode->loadNodeInfo(false, true, $lsOptions["l"] ? "all" : "minimal"); AJXP_Controller::applyHook("node.read", array(&$parentAjxpNode)); if (AJXP_XMLWriter::$headerSent == "tree") { AJXP_XMLWriter::renderAjxpNode($parentAjxpNode, false); } else { AJXP_XMLWriter::renderAjxpHeaderNode($parentAjxpNode); } if (isset($totalPages) && isset($crtPage)) { $remoteOptions = null; if ($this->getFilteredOption("REMOTE_SORTING")) { $remoteOptions = array("remote_order" => "true", "currentOrderCol" => isset($orderField) ? $orderField : "ajxp_label", "currentOrderDir" => isset($orderDirection) ? $orderDirection : "asc"); } AJXP_XMLWriter::renderPaginationData($countFiles, $crtPage, $totalPages, $this->countFiles($path, TRUE), $remoteOptions); if (!$lsOptions["f"]) { AJXP_XMLWriter::close(); exit(1); } } $cursor = 0; $handle = opendir($path); if (!$handle) { throw new AJXP_Exception("Cannot open dir " . $nonPatchedPath); } closedir($handle); $fullList = array("d" => array(), "z" => array(), "f" => array()); if (isset($orderField) && isset($orderDirection) && $orderField == "ajxp_label" && $orderDirection == "desc") { $nodes = scandir($path, 1); } else { $nodes = scandir($path); } if (!empty($this->driverConf["SCANDIR_RESULT_SORTFONC"])) { usort($nodes, $this->driverConf["SCANDIR_RESULT_SORTFONC"]); } if (isset($orderField) && isset($orderDirection) && $orderField != "ajxp_label") { $toSort = array(); foreach ($nodes as $node) { if ($orderField == "filesize") { $toSort[$node] = is_file($nonPatchedPath . "/" . $node) ? $this->filesystemFileSize($nonPatchedPath . "/" . $node) : 0; } else { if ($orderField == "ajxp_modiftime") { $toSort[$node] = filemtime($nonPatchedPath . "/" . $node); } else { if ($orderField == "mimestring") { $toSort[$node] = pathinfo($node, PATHINFO_EXTENSION); } } } } if ($orderDirection == "asc") { asort($toSort); } else { arsort($toSort); } $nodes = array_keys($toSort); } //while (strlen($nodeName = readdir($handle)) > 0) { foreach ($nodes as $nodeName) { if ($nodeName == "." || $nodeName == "..") { continue; } if (isset($uniqueFile) && $nodeName != $uniqueFile) { $cursor++; continue; } if ($offset > 0 && $cursor < $offset) { $cursor++; continue; } $isLeaf = ""; if (!$this->filterNodeName($path, $nodeName, $isLeaf, $lsOptions)) { continue; } if (RecycleBinManager::recycleEnabled() && $dir == "" && "/" . $nodeName == RecycleBinManager::getRecyclePath()) { continue; } if ($limitPerPage > 0 && $cursor - $offset >= $limitPerPage) { break; } $currentFile = $nonPatchedPath . "/" . $nodeName; $meta = array(); if ($isLeaf != "") { $meta = array("is_file" => $isLeaf ? "1" : "0"); } $node = new AJXP_Node($currentFile, $meta); $node->setLabel($nodeName); $node->loadNodeInfo(false, false, $lsOptions["l"] ? "all" : "minimal"); if (!empty($node->metaData["nodeName"]) && $node->metaData["nodeName"] != $nodeName) { $node->setUrl($nonPatchedPath . "/" . $node->metaData["nodeName"]); } if (!empty($node->metaData["hidden"]) && $node->metaData["hidden"] === true) { continue; } if (!empty($node->metaData["mimestring_id"]) && array_key_exists($node->metaData["mimestring_id"], $mess)) { $node->mergeMetadata(array("mimestring" => $mess[$node->metaData["mimestring_id"]])); } if (isset($originalLimitPerPage) && $cursor > $originalLimitPerPage) { $node->mergeMetadata(array("page_position" => floor($cursor / $originalLimitPerPage) + 1)); } $nodeType = "d"; if ($node->isLeaf()) { if (AJXP_Utils::isBrowsableArchive($nodeName)) { if ($lsOptions["f"] && $lsOptions["z"]) { $nodeType = "f"; } else { $nodeType = "z"; } } else { $nodeType = "f"; } } // There is a special sorting, cancel the reordering of files & folders. if (isset($orderField) && $orderField != "ajxp_label") { $nodeType = "f"; } $fullList[$nodeType][$nodeName] = $node; $cursor++; if (isset($uniqueFile) && $nodeName != $uniqueFile) { break; } } if (isset($httpVars["recursive"]) && $httpVars["recursive"] == "true") { $breakNow = false; if (isset($max_depth) && $max_depth > 0 && $crt_depth >= $max_depth) { $breakNow = true; } if (isset($max_nodes) && $max_nodes > 0 && $crt_nodes >= $max_nodes) { $breakNow = true; } foreach ($fullList["d"] as &$nodeDir) { if ($breakNow) { $nodeDir->mergeMetadata(array("ajxp_has_children" => $this->countFiles($nodeDir->getUrl(), false, true) ? "true" : "false")); AJXP_XMLWriter::renderAjxpNode($nodeDir, true); continue; } $this->switchAction("ls", array("dir" => SystemTextEncoding::toUTF8($nodeDir->getPath()), "options" => $httpVars["options"], "recursive" => "true", "max_depth" => $max_depth, "max_nodes" => $max_nodes, "crt_depth" => $crt_depth, "crt_nodes" => $crt_nodes), array()); } } else { array_map(array("AJXP_XMLWriter", "renderAjxpNode"), $fullList["d"]); } array_map(array("AJXP_XMLWriter", "renderAjxpNode"), $fullList["z"]); array_map(array("AJXP_XMLWriter", "renderAjxpNode"), $fullList["f"]); // ADD RECYCLE BIN TO THE LIST if ($dir == "" && !$uniqueFile && RecycleBinManager::recycleEnabled() && $this->getFilteredOption("HIDE_RECYCLE", $this->repository->getId()) !== true) { $recycleBinOption = RecycleBinManager::getRelativeRecycle(); if (file_exists($this->urlBase . $recycleBinOption)) { $recycleNode = new AJXP_Node($this->urlBase . $recycleBinOption); $recycleNode->loadNodeInfo(); AJXP_XMLWriter::renderAjxpNode($recycleNode); } } $this->logDebug("LS Time : " . intval((microtime() - $startTime) * 1000) . "ms"); AJXP_XMLWriter::close(); break; } $xmlBuffer = ""; if (isset($logMessage) || isset($errorMessage)) { $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false); } if ($reloadContextNode) { if (!isset($pendingSelection)) { $pendingSelection = ""; } $xmlBuffer .= AJXP_XMLWriter::reloadDataNode("", $pendingSelection, false); } if (isset($reloadDataNode)) { $xmlBuffer .= AJXP_XMLWriter::reloadDataNode($reloadDataNode, "", false); } if (isset($nodesDiffs)) { $xmlBuffer .= AJXP_XMLWriter::writeNodesDiff($nodesDiffs, false); } return $xmlBuffer; }
/** * Get a "usable" reference to a file : the real file or a tmp copy. * * @param string $path * @param bool $persistent * @return string */ public static function getRealFSReference($path, $persistent = false) { $url = self::translateURL($path); if (self::$linkNode !== null) { $isRemote = AJXP_MetaStreamWrapper::wrapperIsRemote($url); $realFilePointer = AJXP_MetaStreamWrapper::getRealFSReference($url, true); if (!$isRemote) { $ext = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION); $tmpname = tempnam(AJXP_Utils::getAjxpTmpDir(), "real-file-inbox-pointer") . "." . $ext; copy($realFilePointer, $tmpname); $realFilePointer = $tmpname; } ConfService::loadDriverForRepository(self::$linkNode->getRepository()); return $realFilePointer; } else { $tmpname = tempnam(AJXP_Utils::getAjxpTmpDir(), "real-file-inbox-pointer"); $source = fopen($url, "r"); $dest = fopen($tmpname, "w"); stream_copy_to_stream($source, $dest); return $tmpname; } }
public function switchAction($action, $httpVars, $fileVars) { $selection = new UserSelection(); $dir = $httpVars["dir"] or ""; $dir = AJXP_Utils::decodeSecureMagic($dir); if ($dir == "/") { $dir = ""; } $selection->initFromHttpVars($httpVars); if (!$selection->isEmpty()) { //$this->filterUserSelectionToHidden($selection->getFiles()); } $urlBase = "pydio://" . ConfService::getRepository()->getId(); $mess = ConfService::getMessages(); switch ($action) { case "monitor_compression": $percentFile = fsAccessWrapper::getRealFSReference($urlBase . $dir . "/.zip_operation_" . $httpVars["ope_id"]); $percent = 0; if (is_file($percentFile)) { $percent = intval(file_get_contents($percentFile)); } if ($percent < 100) { AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("monitor_compression", $httpVars, $mess["powerfs.1"] . " ({$percent}%)", true, 1); AJXP_XMLWriter::close(); } else { @unlink($percentFile); AJXP_XMLWriter::header(); if ($httpVars["on_end"] == "reload") { AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2); } else { $archiveName = AJXP_Utils::sanitize($httpVars["archive_name"], AJXP_SANITIZE_FILENAME); $archiveName = str_replace("'", "\\'", $archiveName); $jsCode = "\n PydioApi.getClient().downloadSelection(null, \$('download_form'), 'postcompress_download', {ope_id:'" . $httpVars["ope_id"] . "',archive_name:'" . $archiveName . "'});\n "; AJXP_XMLWriter::triggerBgJsAction($jsCode, $mess["powerfs.3"], true); AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2); } AJXP_XMLWriter::close(); } break; case "postcompress_download": $archive = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . $httpVars["ope_id"] . "_" . AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME); $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access"); if (is_file($archive)) { if (!$fsDriver->getFilteredOption("USE_XSENDFILE", ConfService::getRepository()) && !$fsDriver->getFilteredOption("USE_XACCELREDIRECT", ConfService::getRepository())) { register_shutdown_function("unlink", $archive); } $fsDriver->readFile($archive, "force-download", $httpVars["archive_name"], false, null, true); } else { echo "<script>alert('Cannot find archive! Is ZIP correctly installed?');</script>"; } break; case "compress": case "precompress": $archiveName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME); if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) { $opeId = substr(md5(time()), 0, 10); $httpVars["ope_id"] = $opeId; AJXP_Controller::applyActionInBackground(ConfService::getRepository()->getId(), $action, $httpVars); AJXP_XMLWriter::header(); $bgParameters = array("dir" => SystemTextEncoding::toUTF8($dir), "archive_name" => SystemTextEncoding::toUTF8($archiveName), "on_end" => isset($httpVars["on_end"]) ? $httpVars["on_end"] : "reload", "ope_id" => $opeId); AJXP_XMLWriter::triggerBgAction("monitor_compression", $bgParameters, $mess["powerfs.1"] . " (0%)", true); AJXP_XMLWriter::close(); session_write_close(); exit; } $rootDir = fsAccessWrapper::getRealFSReference($urlBase) . $dir; $percentFile = $rootDir . "/.zip_operation_" . $httpVars["ope_id"]; $compressLocally = $action == "compress" ? true : false; // List all files $todo = array(); $args = array(); $replaceSearch = array($rootDir, "\\"); $replaceReplace = array("", "/"); foreach ($selection->getFiles() as $selectionFile) { $baseFile = $selectionFile; $args[] = escapeshellarg(substr($selectionFile, strlen($dir) + ($dir == "/" ? 0 : 1))); $selectionFile = fsAccessWrapper::getRealFSReference($urlBase . $selectionFile); $todo[] = ltrim(str_replace($replaceSearch, $replaceReplace, $selectionFile), "/"); if (is_dir($selectionFile)) { $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($selectionFile), RecursiveIteratorIterator::SELF_FIRST); foreach ($objects as $name => $object) { $todo[] = str_replace($replaceSearch, $replaceReplace, $name); } } if (trim($baseFile, "/") == "") { // ROOT IS SELECTED, FIX IT $args = array(escapeshellarg(basename($rootDir))); $rootDir = dirname($rootDir); break; } } $cmdSeparator = PHP_OS == "WIN32" || PHP_OS == "WINNT" || PHP_OS == "Windows" ? "&" : ";"; if (!$compressLocally) { $archiveName = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . $httpVars["ope_id"] . "_" . $archiveName; } chdir($rootDir); $cmd = $this->getFilteredOption("ZIP_PATH") . " -r " . escapeshellarg($archiveName) . " " . implode(" ", $args); $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access"); $c = $fsDriver->getConfigs(); if ((!isset($c["SHOW_HIDDEN_FILES"]) || $c["SHOW_HIDDEN_FILES"] == false) && stripos(PHP_OS, "win") === false) { $cmd .= " -x .\\*"; } $cmd .= " " . $cmdSeparator . " echo ZIP_FINISHED"; $proc = popen($cmd, "r"); $toks = array(); $handled = array(); $finishedEchoed = false; while (!feof($proc)) { set_time_limit(20); $results = fgets($proc, 256); if (strlen($results) == 0) { } else { $tok = strtok($results, "\n"); while ($tok !== false) { $toks[] = $tok; if ($tok == "ZIP_FINISHED") { $finishedEchoed = true; } else { $test = preg_match('/(\\w+): (.*) \\(([^\\(]+)\\) \\(([^\\(]+)\\)/', $tok, $matches); if ($test !== false) { $handled[] = $matches[2]; } } $tok = strtok("\n"); } if ($finishedEchoed) { $percent = 100; } else { $percent = min(round(count($handled) / count($todo) * 100), 100); } file_put_contents($percentFile, $percent); } // avoid a busy wait if ($percent < 100) { usleep(1); } } pclose($proc); file_put_contents($percentFile, 100); break; default: break; } }
public function switchActions($actionName, $httpVars, $fileVars) { //$urlBase = $this->accessDriver $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } if (!isset($this->pluginConf)) { $this->pluginConf = array("GENERATE_THUMBNAIL" => false); } $streamData = $repository->streamData; $this->streamData = $streamData; $destStreamURL = $streamData["protocol"] . "://" . $repository->getId(); switch ($actionName) { case "filehasher_signature": $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); if (!file_exists($destStreamURL . $file)) { break; } $cacheItem = AJXP_Cache::getItem("signatures", $destStreamURL . $file, array($this, "generateSignature")); $data = $cacheItem->getData(); header("Content-Type:application/octet-stream"); header("Content-Length", strlen($data)); echo $data; break; case "filehasher_delta": case "filehasher_patch": // HANDLE UPLOAD DATA if (!isset($fileVars) && !is_array($fileVars["userfile_0"])) { throw new Exception("These action should find uploaded data"); } $uploadedData = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-sig"); move_uploaded_file($fileVars["userfile_0"]["tmp_name"], $uploadedData); $fileUrl = $destStreamURL . AJXP_Utils::decodeSecureMagic($httpVars["file"]); $file = call_user_func(array($this->streamData["classname"], "getRealFSReference"), $fileUrl, true); if ($actionName == "filehasher_delta") { $signatureFile = $uploadedData; $deltaFile = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-delta"); rsync_generate_delta($signatureFile, $file, $deltaFile); header("Content-Type:application/octet-stream"); header("Content-Length:" . filesize($deltaFile)); readfile($deltaFile); unlink($signatureFile); unlink($deltaFile); } else { $patched = $file . ".rdiff_patched"; $deltaFile = $uploadedData; rsync_patch_file($file, $deltaFile, $patched); rename($patched, $file); header("Content-Type:text/plain"); unlink($deltaFile); echo md5_file($file); } break; } }
/** * @param AJXP_Node $ajxpNode * @param Zend_Search_Lucene_Interface $index * @throws Exception * @return Zend_Search_Lucene_Document */ public function createIndexedDocument($ajxpNode, &$index) { $ajxpNode->loadNodeInfo(); $ext = strtolower(pathinfo($ajxpNode->getLabel(), PATHINFO_EXTENSION)); $parseContent = $this->indexContent; if ($parseContent && $ajxpNode->bytesize > $this->getFilteredOption("PARSE_CONTENT_MAX_SIZE")) { $parseContent = false; } if ($parseContent && in_array($ext, explode(",", $this->getFilteredOption("PARSE_CONTENT_HTML")))) { $doc = @Zend_Search_Lucene_Document_Html::loadHTMLFile($ajxpNode->getUrl()); } elseif ($parseContent && $ext == "docx" && class_exists("Zend_Search_Lucene_Document_Docx")) { $realFile = call_user_func(array($ajxpNode->wrapperClassName, "getRealFSReference"), $ajxpNode->getUrl()); $doc = @Zend_Search_Lucene_Document_Docx::loadDocxFile($realFile); } elseif ($parseContent && $ext == "docx" && class_exists("Zend_Search_Lucene_Document_Pptx")) { $realFile = call_user_func(array($ajxpNode->wrapperClassName, "getRealFSReference"), $ajxpNode->getUrl()); $doc = @Zend_Search_Lucene_Document_Pptx::loadPptxFile($realFile); } elseif ($parseContent && $ext == "xlsx" && class_exists("Zend_Search_Lucene_Document_Xlsx")) { $realFile = call_user_func(array($ajxpNode->wrapperClassName, "getRealFSReference"), $ajxpNode->getUrl()); $doc = @Zend_Search_Lucene_Document_Xlsx::loadXlsxFile($realFile); } else { $doc = new Zend_Search_Lucene_Document(); } if ($doc == null) { throw new Exception("Could not load document"); } $doc->addField(Zend_Search_Lucene_Field::Keyword("node_url", $ajxpNode->getUrl()), SystemTextEncoding::getEncoding()); $doc->addField(Zend_Search_Lucene_Field::Keyword("node_path", str_replace("/", "AJXPFAKESEP", $ajxpNode->getPath())), SystemTextEncoding::getEncoding()); $doc->addField(Zend_Search_Lucene_Field::Text("basename", basename($ajxpNode->getPath())), SystemTextEncoding::getEncoding()); $doc->addField(Zend_Search_Lucene_Field::Keyword("ajxp_node", "yes"), SystemTextEncoding::getEncoding()); $doc->addField(Zend_Search_Lucene_Field::Keyword("ajxp_scope", "shared")); $doc->addField(Zend_Search_Lucene_Field::Keyword("ajxp_modiftime", date("Ymd", $ajxpNode->ajxp_modiftime))); $doc->addField(Zend_Search_Lucene_Field::Keyword("ajxp_bytesize", $ajxpNode->bytesize)); $ajxpMime = $ajxpNode->ajxp_mime; if (empty($ajxpMime)) { $doc->addField(Zend_Search_Lucene_Field::Keyword("ajxp_mime", pathinfo($ajxpNode->getLabel(), PATHINFO_EXTENSION))); } else { $doc->addField(Zend_Search_Lucene_Field::Keyword("ajxp_mime", $ajxpNode->ajxp_mime)); } // Store a cached copy of the metadata $serializedMeta = base64_encode(serialize($ajxpNode->metadata)); $doc->addField(Zend_Search_Lucene_Field::Binary("serialized_metadata", $serializedMeta)); if (isset($ajxpNode->indexableMetaKeys["shared"])) { foreach ($ajxpNode->indexableMetaKeys["shared"] as $sharedField) { if ($ajxpNode->{$sharedField}) { $doc->addField(Zend_search_Lucene_Field::keyword($sharedField, $ajxpNode->{$sharedField})); } } } foreach ($this->metaFields as $field) { if ($ajxpNode->{$field} != null) { $doc->addField(Zend_Search_Lucene_Field::Text("ajxp_meta_{$field}", $ajxpNode->{$field}), SystemTextEncoding::getEncoding()); } } if (isset($ajxpNode->indexableMetaKeys["user"]) && count($ajxpNode->indexableMetaKeys["user"]) && AuthService::usersEnabled() && AuthService::getLoggedUser() != null) { $privateDoc = new Zend_Search_Lucene_Document(); $privateDoc->addField(Zend_Search_Lucene_Field::Keyword("node_url", $ajxpNode->getUrl(), SystemTextEncoding::getEncoding())); $privateDoc->addField(Zend_Search_Lucene_Field::Keyword("node_path", str_replace("/", "AJXPFAKESEP", $ajxpNode->getPath()), SystemTextEncoding::getEncoding())); $privateDoc->addField(Zend_Search_Lucene_Field::Keyword("ajxp_scope", "user")); $privateDoc->addField(Zend_Search_Lucene_Field::Keyword("ajxp_user", AuthService::getLoggedUser()->getId())); foreach ($ajxpNode->indexableMetaKeys["user"] as $userField) { if ($ajxpNode->{$userField}) { $privateDoc->addField(Zend_search_Lucene_Field::keyword($userField, $ajxpNode->{$userField})); } } $privateDoc->addField(Zend_Search_Lucene_Field::Binary("serialized_metadata", $serializedMeta)); $index->addDocument($privateDoc); } if ($parseContent && in_array($ext, explode(",", $this->getFilteredOption("PARSE_CONTENT_TXT")))) { $doc->addField(Zend_Search_Lucene_Field::unStored("body", file_get_contents($ajxpNode->getUrl()))); } $unoconv = $this->getFilteredOption("UNOCONV"); $pipe = false; if ($parseContent && !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); $doc->addField(Zend_Search_Lucene_Field::unStored("body", $asciiString)); } else { $ext = "pdf"; } } $pdftotext = $this->getFilteredOption("PDFTOTEXT"); if ($parseContent && !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); $doc->addField(Zend_Search_Lucene_Field::unStored("body", $asciiString)); } $index->addDocument($doc); return $doc; }
public static function getNodes($checkStats = false, $touch = true) { if (isset(self::$output)) { return self::$output; } $mess = ConfService::getMessages(); $repos = ConfService::getAccessibleRepositories(); $output = array(); $touchReposIds = array(); foreach ($repos as $repo) { if (!$repo->hasOwner() || !$repo->hasContentFilter()) { continue; } $repoId = $repo->getId(); if (strpos("ocs_remote_share_", $repoId) !== 0) { $touchReposIds[] = $repoId; } $url = "pydio://" . $repoId . "/"; $meta = array("shared_repository_id" => $repoId, "ajxp_description" => "File shared by " . $repo->getOwner() . " " . AJXP_Utils::relativeDate($repo->getOption("CREATION_TIME"), $mess), "share_meta_type" => 1); $cFilter = $repo->getContentFilter(); $filter = $cFilter instanceof ContentFilter ? array_keys($cFilter->filters)[0] : $cFilter; if (!is_array($filter)) { $label = basename($filter); } else { $label = $repo->getDisplay(); } if (strpos($repoId, "ocs_remote_share") !== 0) { // FOR REMOTE SHARES, DO NOT APPEND THE DOCUMENTNAME, WE STAT THE ROOT DIRECTLY $url .= $label; } $status = null; $remoteShare = null; $name = pathinfo($label, PATHINFO_FILENAME); $ext = pathinfo($label, PATHINFO_EXTENSION); $node = new AJXP_Node($url); $node->setLabel($label); if ($checkStats) { $node->getRepository()->driverInstance = null; try { ConfService::loadDriverForRepository($node->getRepository()); } catch (Exception $e) { $ext = "error"; $meta["ajxp_mime"] = "error"; } $node->getRepository()->detectStreamWrapper(true); $stat = @stat($url); if ($stat === false) { $ext = "error"; $meta["ajxp_mime"] = "error"; $meta["share_meta_type"] = 2; } else { if (strpos($repoId, "ocs_remote_share_") === 0) { // Check Status $linkId = str_replace("ocs_remote_share_", "", $repoId); $ocsStore = new \Pydio\OCS\Model\SQLStore(); $remoteShare = $ocsStore->remoteShareById($linkId); $status = $remoteShare->getStatus(); if ($status == OCS_INVITATION_STATUS_PENDING) { $stat = stat(AJXP_Utils::getAjxpTmpDir()); $ext = "invitation"; $meta["ajxp_mime"] = "invitation"; $meta["share_meta_type"] = 0; } else { $meta["remote_share_accepted"] = "true"; } $meta["remote_share_id"] = $remoteShare->getId(); } } if ($ext == "invitation") { $label .= " (" . $mess["inbox_driver.4"] . ")"; } else { if ($ext == "error") { $label .= " (" . $mess["inbox_driver.5"] . ")"; } } if (is_array($stat) && AuthService::getLoggedUser() != null) { $acl = AuthService::getLoggedUser()->mergedRole->getAcl($repoId); if ($acl == "r") { self::disableWriteInStat($stat); } } } $index = 0; $suffix = ""; while (isset($output[$name . $suffix . "." . $ext])) { $index++; $suffix = " ({$index})"; } $output[$name . $suffix . "." . $ext] = ["label" => $label, "url" => $url, "remote_share" => $remoteShare, "meta" => $meta]; if (isset($stat)) { $output[$name . $suffix . "." . $ext]['stat'] = $stat; } } ConfService::loadDriverForRepository(ConfService::getRepository()); self::$output = $output; if ($touch) { if (count($touchReposIds) && AuthService::getLoggedUser() != null) { $uPref = AuthService::getLoggedUser()->getPref("repository_last_connected"); if (empty($uPref)) { $uPref = array(); } foreach ($touchReposIds as $rId) { $uPref[$rId] = time(); } AuthService::getLoggedUser()->setPref("repository_last_connected", $uPref); } } return $output; }
public function postProcess($action, $httpVars, $postProcessData) { if (isset($httpVars["simple_uploader"]) || isset($httpVars["xhr_uploader"])) { return; } /* If set resumeFileId and resumePartitionIndex, cross-session resume is requested. */ if (isset($httpVars["resumeFileId"]) && isset($httpVars["resumePartitionIndex"])) { header("HTTP/1.1 200 OK"); print "fileId: " . $httpVars["resumeFileId"] . "\n"; print "partitionIndex: " . $httpVars["resumePartitionIndex"]; return; } /*if (self::$skipDecoding) { }*/ if (isset($postProcessData["processor_result"]["ERROR"])) { if (isset($httpVars["lastPartition"]) && isset($httpVars["partitionCount"])) { /* we get the stream url (where all the partitions have been uploaded so far) */ $repository = ConfService::getRepository(); $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]); $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType()); $streamData = $plugin->detectStreamWrapper(true); $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/"; if ($httpVars["partitionCount"] > 1) { /* we fetch the information that help us to construct the temp files name */ $fileId = $httpVars["fileId"]; $fileHash = md5($httpVars["fileName"]); /* deletion of all the partitions that have been uploaded */ for ($i = 0; $i < $httpVars["partitionCount"]; $i++) { if (file_exists($destStreamURL . "{$fileHash}.{$fileId}.{$i}")) { unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}"); } } } else { $fileName = $httpVars["fileName"]; unlink($destStreamURL . $fileName); } } echo "Error: " . $postProcessData["processor_result"]["ERROR"]["MESSAGE"]; return; } if (!isset($httpVars["partitionRealName"]) && !isset($httpVars["lastPartition"])) { return; } $repository = ConfService::getRepository(); $driver = ConfService::loadDriverForRepository($repository); if (!$repository->detectStreamWrapper(false)) { return false; } if ($httpVars["lastPartition"]) { $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType()); $streamData = $plugin->detectStreamWrapper(true); $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]); $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/"; /* we check if the current file has a relative path (aka we want to upload an entire directory) */ $this->logDebug("Now dispatching relativePath dest:", $httpVars["relativePath"]); $subs = explode("/", $httpVars["relativePath"]); $userfile_name = array_pop($subs); $folderForbidden = false; $all_in_place = true; $partitions_length = 0; $fileId = $httpVars["fileId"]; $fileHash = md5($userfile_name); $partitionCount = $httpVars["partitionCount"]; $fileLength = $_POST["fileLength"]; /* * * Now, we supposed that access driver has already saved uploaded file in to * folderServer with file name is md5 relativePath value. * We try to copy this file to right location in recovery his name. * */ $userfile_name = md5($httpVars["relativePath"]); if (self::$remote) { $partitions = array(); $newPartitions = array(); $index_first_partition = -1; $i = 0; do { $currentFileName = $driver->getFileNameToCopy(); $partitions[] = $driver->getNextFileToCopy(); if ($index_first_partition < 0 && strstr($currentFileName, $fileHash) != false) { $index_first_partition = $i; } else { if ($index_first_partition < 0) { $newPartitions[] = array_pop($partitions); } } } while ($driver->hasFilesToCopy()); } /* if partitionned */ if ($partitionCount > 1) { if (self::$remote) { for ($i = 0; $all_in_place && $i < $partitionCount; $i++) { $partition_file = "{$fileHash}.{$fileId}.{$i}"; if (strstr($partitions[$i]["name"], $partition_file) != false) { $partitions_length += filesize($partitions[$i]["tmp_name"]); } else { $all_in_place = false; } } } else { for ($i = 0; $all_in_place && $i < $partitionCount; $i++) { $partition_file = $destStreamURL . "{$fileHash}.{$fileId}.{$i}"; if (file_exists($partition_file)) { $partitions_length += filesize($partition_file); } else { $all_in_place = false; } } } } else { if (self::$remote) { if (strstr($newPartitions[count($newPartitions) - 1]["name"], $userfile_name) != false) { $partitions_length += filesize($newPartitions[count($newPartitions) - 1]["tmp_name"]); } } else { if (file_exists($destStreamURL . $userfile_name)) { $partitions_length += filesize($destStreamURL . $userfile_name); } } } if (!$all_in_place || $partitions_length != floatval($fileLength)) { echo "Error: Upload validation error!"; /* we delete all the uploaded partitions */ if ($httpVars["partitionCount"] > 1) { for ($i = 0; $i < $partitionCount; $i++) { if (file_exists($destStreamURL . "{$fileHash}.{$fileId}.{$i}")) { unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}"); } } } else { $fileName = $httpVars["partitionRealName"]; unlink($destStreamURL . $fileName); } return; } if (count($subs) > 0 && !self::$remote) { $curDir = ""; if (substr($curDir, -1) == "/") { $curDir = substr($curDir, 0, -1); } // Create the folder tree as necessary foreach ($subs as $key => $spath) { $messtmp = ""; $dirname = AJXP_Utils::decodeSecureMagic($spath, AJXP_SANITIZE_FILENAME); $dirname = substr($dirname, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH")); //$this->filterUserSelectionToHidden(array($dirname)); if (AJXP_Utils::isHidden($dirname)) { $folderForbidden = true; break; } if (file_exists($destStreamURL . "{$curDir}/{$dirname}")) { // if the folder exists, traverse $this->logDebug("{$curDir}/{$dirname} existing, traversing for {$userfile_name} out of", $httpVars["relativePath"]); $curDir .= "/" . $dirname; continue; } $this->logDebug($destStreamURL . $curDir); $dirMode = 0775; $chmodValue = $repository->getOption("CHMOD_VALUE"); if (isset($chmodValue) && $chmodValue != "") { $dirMode = octdec(ltrim($chmodValue, "0")); if ($dirMode & 0400) { $dirMode |= 0100; } // Owner is allowed to read, allow to list the directory if ($dirMode & 040) { $dirMode |= 010; } // Group is allowed to read, allow to list the directory if ($dirMode & 04) { $dirMode |= 01; } // Other are allowed to read, allow to list the directory } $url = $destStreamURL . $curDir . "/" . $dirname; $old = umask(0); mkdir($url, $dirMode); umask($old); AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($url), false)); $curDir .= "/" . $dirname; } } if (!$folderForbidden) { $fileId = $httpVars["fileId"]; $this->logDebug("Should now rebuild file!", $httpVars); // Now move the final file to the right folder // Currently the file is at the base of the current $this->logDebug("PartitionRealName", $destStreamURL . $httpVars["partitionRealName"]); // Get file by name (md5 value) $relPath_md5 = AJXP_Utils::decodeSecureMagic(md5($httpVars["relativePath"])); // original file name $relPath = AJXP_Utils::decodeSecureMagic($httpVars["relativePath"]); $target = $destStreamURL; $target .= self::$remote ? basename($relPath) : $relPath; /* * $current is uploaded file with md5 value as his name * we copy to $relPath and delete md5 file */ $current = $destStreamURL . basename($relPath_md5); if ($httpVars["partitionCount"] > 1) { if (self::$remote) { $test = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"]; $newDest = fopen(AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"], "w"); $newFile = array(); $length = 0; for ($i = 0, $count = count($partitions); $i < $count; $i++) { $currentFile = $partitions[$i]; $currentFileName = $currentFile["tmp_name"]; $part = fopen($currentFileName, "r"); while (!feof($part)) { $length += fwrite($newDest, fread($part, 4096)); } fclose($part); unlink($currentFileName); } $newFile["type"] = $partitions[0]["type"]; $newFile["name"] = $httpVars["partitionRealName"]; $newFile["error"] = 0; $newFile["size"] = $length; $newFile["tmp_name"] = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"]; $newFile["destination"] = $partitions[0]["destination"]; $newPartitions[] = $newFile; } else { $newDest = fopen($destStreamURL . $httpVars["partitionRealName"], "w"); $fileHash = md5($httpVars["partitionRealName"]); for ($i = 0; $i < $httpVars["partitionCount"]; $i++) { $part = fopen($destStreamURL . "{$fileHash}.{$fileId}.{$i}", "r"); while (!feof($part)) { fwrite($newDest, fread($part, 4096)); } fclose($part); unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}"); } } fclose($newDest); } if (!self::$remote && (!self::$wrapperIsRemote || $relPath != $httpVars["partitionRealName"])) { $err = copy($current, $target); } else { for ($i = 0, $count = count($newPartitions); $i < $count; $i++) { $driver->storeFileToCopy($newPartitions[$i]); } } if ($err !== false) { if (!self::$remote) { unlink($current); } AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($target), false)); } else { if ($current == $target) { AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($target), false)); } } } else { // Remove the file, as it should not have been uploaded! //if(!self::$remote) unlink($current); } } }
public function switchAction($action, $httpVars, $filesVars) { if (!isset($this->actions[$action])) { return false; } $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } if (!is_array($this->pluginConf) || !isset($this->pluginConf["IMAGE_MAGICK_CONVERT"])) { return false; } $streamData = $repository->streamData; $destStreamURL = $streamData["protocol"] . "://" . $repository->getId(); if ($action == "imagick_data_proxy") { $extractAll = false; if (isset($httpVars["all"])) { $extractAll = true; } $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); $extension = pathinfo($file, PATHINFO_EXTENSION); if (in_array(strtolower($extension), array("svg"))) { $extractAll = true; } if (!filesize($destStreamURL . "/" . $file)) { return; } $fp = fopen($destStreamURL . "/" . $file, "r"); $tmpFileName = AJXP_Utils::getAjxpTmpDir() . "/ajxp_tmp_" . md5(time()) . ".{$extension}"; $tmpFile = fopen($tmpFileName, "w"); register_shutdown_function("unlink", $tmpFileName); while (!feof($fp)) { stream_copy_to_stream($fp, $tmpFile, 4096); } fclose($tmpFile); fclose($fp); $out = array(); $return = 0; $tmpFileThumb = str_replace(".{$extension}", ".jpg", $tmpFileName); if (!$extractAll) { register_shutdown_function("unlink", $tmpFileThumb); } else { @set_time_limit(90); } chdir(AJXP_Utils::getAjxpTmpDir()); $pageLimit = $extractAll ? "" : "[0]"; $params = $extractAll ? "-quality " . $this->pluginConf["IM_VIEWER_QUALITY"] : "-resize 250 -quality " . $this->pluginConf["IM_THUMB_QUALITY"]; $cmd = $this->pluginConf["IMAGE_MAGICK_CONVERT"] . " " . basename($tmpFileName) . $pageLimit . " " . $params . " " . basename($tmpFileThumb); AJXP_Logger::debug("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 (isset($httpVars["all"])) { $prefix = str_replace(".{$extension}", "", $tmpFileName); $files = $this->listExtractedJpg($prefix); header("Content-Type: application/json"); print json_encode($files); exit(1); } else { header("Content-Type: image/jpeg; name=\"" . basename($file) . "\""); header("Content-Length: " . filesize($tmpFileThumb)); header('Cache-Control: public'); readfile($tmpFileThumb); exit(1); } } else { if ($action == "get_extracted_page" && isset($httpVars["file"])) { $file = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["file"]; if (!is_file($file)) { return; } header("Content-Type: image/jpeg; name=\"" . basename($file) . "\""); header("Content-Length: " . filesize($file)); header('Cache-Control: public'); readfile($file); exit(1); } else { if ($action == "delete_imagick_data" && isset($httpVars["file"])) { $files = $this->listExtractedJpg(AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["file"]); foreach ($files as $file) { if (is_file(AJXP_Utils::getAjxpTmpDir() . "/" . $file["file"])) { unlink(AJXP_Utils::getAjxpTmpDir() . "/" . $file["file"]); } } } } } }
function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } $selection = new UserSelection(); $dir = $httpVars["dir"] or ""; $dir = AJXP_Utils::securePath($dir); if ($dir == "/") { $dir = ""; } $selection->initFromHttpVars($httpVars); if (!$selection->isEmpty()) { //$this->filterUserSelectionToHidden($selection->getFiles()); } $urlBase = "ajxp.fs://" . ConfService::getRepository()->getId(); $mess = ConfService::getMessages(); switch ($action) { case "monitor_compression": $percentFile = fsAccessWrapper::getRealFSReference($urlBase . $dir . "/.zip_operation_" . $httpVars["ope_id"]); $percent = 0; if (is_file($percentFile)) { $percent = intval(file_get_contents($percentFile)); } if ($percent < 100) { AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("monitor_compression", $httpVars, $mess["powerfs.1"] . " ({$percent}%)", true, 1); AJXP_XMLWriter::close(); } else { @unlink($percentFile); AJXP_XMLWriter::header(); if ($httpVars["on_end"] == "reload") { AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2); } else { $archiveName = $httpVars["archive_name"]; $jsCode = "\n \$('download_form').action = window.ajxpServerAccessPath;\n \$('download_form').secure_token.value = window.Connexion.SECURE_TOKEN;\n \$('download_form').select('input').each(function(input){\n if(input.name!='get_action' && input.name!='secure_token') input.remove();\n });\n \$('download_form').insert(new Element('input', {type:'hidden', name:'ope_id', value:'" . $httpVars["ope_id"] . "'}));\n \$('download_form').insert(new Element('input', {type:'hidden', name:'archive_name', value:'" . $archiveName . "'}));\n \$('download_form').insert(new Element('input', {type:'hidden', name:'get_action', value:'postcompress_download'}));\n \$('download_form').submit();\n "; AJXP_XMLWriter::triggerBgJsAction($jsCode, "powerfs.3", true); AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2); } AJXP_XMLWriter::close(); } break; case "postcompress_download": $archive = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["ope_id"] . "_" . $httpVars["archive_name"]; //$fsDriver = new fsAccessDriver("fake", ""); $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access"); $fsDriver->readFile($archive, "force-download", $httpVars["archive_name"], false, null, true); break; case "compress": case "precompress": if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) { $opeId = substr(md5(time()), 0, 10); $httpVars["ope_id"] = $opeId; AJXP_Controller::applyActionInBackground(ConfService::getRepository()->getId(), $action, $httpVars); AJXP_XMLWriter::header(); $bgParameters = array("dir" => $dir, "archive_name" => $httpVars["archive_name"], "on_end" => isset($httpVars["on_end"]) ? $httpVars["on_end"] : "reload", "ope_id" => $opeId); AJXP_XMLWriter::triggerBgAction("monitor_compression", $bgParameters, $mess["powerfs.1"] . " (0%)", true); AJXP_XMLWriter::close(); session_write_close(); exit; } $rootDir = fsAccessWrapper::getRealFSReference($urlBase) . $dir; $percentFile = $rootDir . "/.zip_operation_" . $httpVars["ope_id"]; $compressLocally = $action == "compress" ? true : false; // List all files $todo = array(); $args = array(); $replaceSearch = array($rootDir, "\\"); $replaceReplace = array("", "/"); foreach ($selection->getFiles() as $selectionFile) { $args[] = '"' . substr($selectionFile, strlen($dir) + ($dir == "/" ? 0 : 1)) . '"'; $selectionFile = fsAccessWrapper::getRealFSReference($urlBase . $selectionFile); $todo[] = ltrim(str_replace($replaceSearch, $replaceReplace, $selectionFile), "/"); if (is_dir($selectionFile)) { $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($selectionFile), RecursiveIteratorIterator::SELF_FIRST); foreach ($objects as $name => $object) { $todo[] = str_replace($replaceSearch, $replaceReplace, $name); } } } $cmdSeparator = PHP_OS == "WIN32" || PHP_OS == "WINNT" || PHP_OS == "Windows" ? "&" : ";"; $archiveName = $httpVars["archive_name"]; if (!$compressLocally) { $archiveName = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["ope_id"] . "_" . $archiveName; } chdir($rootDir); $cmd = "zip -r \"" . $archiveName . "\" " . implode(" ", $args); $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access"); $c = $fsDriver->getConfigs(); if (!isset($c["SHOW_HIDDEN_FILES"]) || $c["SHOW_HIDDEN_FILES"] == false) { $cmd .= " -x .\\*"; } $cmd .= " " . $cmdSeparator . " echo ZIP_FINISHED"; $proc = popen($cmd, "r"); $toks = array(); $handled = array(); $finishedEchoed = false; while (!feof($proc)) { set_time_limit(20); $results = fgets($proc, 256); if (strlen($results) == 0) { } else { $tok = strtok($results, "\n"); while ($tok !== false) { $toks[] = $tok; if ($tok == "ZIP_FINISHED") { $finishedEchoed = true; } else { $test = preg_match('/(\\w+): (.*) \\(([^\\(]+)\\) \\(([^\\(]+)\\)/', $tok, $matches); if ($test !== false) { $handled[] = $matches[2]; } } $tok = strtok("\n"); } if ($finishedEchoed) { $percent = 100; } else { $percent = min(round(count($handled) / count($todo) * 100), 100); } file_put_contents($percentFile, $percent); } // avoid a busy wait if ($percent < 100) { usleep(1); } } pclose($proc); file_put_contents($percentFile, 100); break; default: break; } }
public function stream_open($path, $mode, $options, &$opened_path) { if (strstr($mode, "r") !== false) { self::$crtTmpFile = self::getRealFSReference($path); self::$crtWritePath = null; } else { self::$crtTmpFile = AJXP_Utils::getAjxpTmpDir() . "/" . rand(); self::$crtWritePath = $path; } self::$crtHandle = fopen(self::$crtTmpFile, $mode); return true; }
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; }
public function unifyChunks($action, &$httpVars, &$fileVars) { $filename = AJXP_Utils::decodeSecureMagic($httpVars["name"]); $tmpName = $fileVars["file"]["tmp_name"]; $chunk = $httpVars["chunk"]; $chunks = $httpVars["chunks"]; //error_log("currentChunk:".$chunk." chunks: ".$chunks); $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(false)) { return false; } $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType()); $streamData = $plugin->detectStreamWrapper(true); $wrapperName = $streamData["classname"]; $dir = AJXP_Utils::securePath($httpVars["dir"]); $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/"; $driver = ConfService::loadDriverForRepository($repository); $remote = false; if (method_exists($driver, "storeFileToCopy")) { $remote = true; $destCopy = AJXP_XMLWriter::replaceAjxpXmlKeywords($repository->getOption("TMP_UPLOAD")); // Make tmp folder a bit more unique using secure_token $tmpFolder = $destCopy . "/" . $httpVars["secure_token"]; if (!is_dir($tmpFolder)) { @mkdir($tmpFolder, 0700, true); } $target = $tmpFolder . '/' . $filename; $fileVars["file"]["destination"] = base64_encode($dir); } else { if (call_user_func(array($wrapperName, "isRemote"))) { $remote = true; $tmpFolder = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["secure_token"]; if (!is_dir($tmpFolder)) { @mkdir($tmpFolder, 0700, true); } $target = $tmpFolder . '/' . $filename; } else { $target = $destStreamURL . $filename; } } //error_log("Directory: ".$dir); // Clean the fileName for security reasons //$filename = preg_replace('/[^\w\._]+/', '', $filename); // Look for the content type header if (isset($_SERVER["HTTP_CONTENT_TYPE"])) { $contentType = $_SERVER["HTTP_CONTENT_TYPE"]; } if (isset($_SERVER["CONTENT_TYPE"])) { $contentType = $_SERVER["CONTENT_TYPE"]; } // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5 if (strpos($contentType, "multipart") !== false) { if (isset($tmpName) && is_uploaded_file($tmpName)) { //error_log("tmpName: ".$tmpName); // Open temp file $out = fopen($target, $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = fopen($tmpName, "rb"); if ($in) { while ($buff = fread($in, 4096)) { fwrite($out, $buff); } } else { die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); } fclose($in); fclose($out); @unlink($tmpName); } else { die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } } else { die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'); } } else { // Open temp file $out = fopen($target, $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = fopen("php://input", "rb"); if ($in) { while ($buff = fread($in, 4096)) { fwrite($out, $buff); } } else { die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); } fclose($in); fclose($out); } else { die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } } /* we apply the hook if we are uploading the last chunk */ if ($chunk == $chunks - 1) { if (!$remote) { AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($destStreamURL . $filename), false)); } else { if (method_exists($driver, "storeFileToCopy")) { $fileVars["file"]["tmp_name"] = $target; $fileVars["file"]["name"] = $filename; $driver->storeFileToCopy($fileVars["file"]); AJXP_Controller::findActionAndApply("next_to_remote", array(), array()); } else { // Remote Driver case: copy temp file to destination $node = new AJXP_Node($destStreamURL . $filename); AJXP_Controller::applyHook("node.before_create", array($node, filesize($target))); AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($destStreamURL))); $res = copy($target, $destStreamURL . $filename); if ($res) { @unlink($target); } AJXP_Controller::applyHook("node.change", array(null, $node, false)); } } } // Return JSON-RPC response die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'); }
public function switchActions($actionName, $httpVars, $fileVars) { //$urlBase = $this->accessDriver $repository = $this->accessDriver->repository; if (!$repository->detectStreamWrapper(true)) { return false; } $selection = new UserSelection($repository, $httpVars); switch ($actionName) { case "filehasher_signature": $file = $selection->getUniqueNode(); if (!file_exists($file->getUrl())) { break; } $cacheItem = AJXP_Cache::getItem("signatures", $file->getUrl(), array($this, "generateSignature")); $data = $cacheItem->getData(); header("Content-Type:application/octet-stream"); header("Content-Length", strlen($data)); echo $data; break; case "filehasher_delta": case "filehasher_patch": // HANDLE UPLOAD DATA $this->logDebug("Received signature file, should compute delta now"); if (!isset($fileVars) && !is_array($fileVars["userfile_0"])) { throw new Exception("These action should find uploaded data"); } $signature_delta_file = $fileVars["userfile_0"]["tmp_name"]; $fileUrl = $selection->getUniqueNode()->getUrl(); $file = AJXP_MetaStreamWrapper::getRealFSReference($fileUrl, true); if ($actionName == "filehasher_delta") { $deltaFile = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-delta"); $this->logDebug("Received signature file, should compute delta now"); rsync_generate_delta($signature_delta_file, $file, $deltaFile); $this->logDebug("Computed delta file, size is " . filesize($deltaFile)); header("Content-Type:application/octet-stream"); header("Content-Length:" . filesize($deltaFile)); readfile($deltaFile); unlink($deltaFile); } else { $patched = $file . ".rdiff_patched"; rsync_patch_file($file, $signature_delta_file, $patched); rename($patched, $file); $node = $selection->getUniqueNode(); AJXP_Controller::applyHook("node.change", array($node, $node, false)); header("Content-Type:text/plain"); echo md5_file($file); } break; case "stat_hash": clearstatcache(); header("Content-type:application/json"); if ($selection->isUnique()) { $node = $selection->getUniqueNode(); $stat = @stat($node->getUrl()); if (!$stat || !is_readable($node->getUrl())) { print '{}'; } else { if (is_file($node->getUrl())) { if (isset($_SERVER["HTTP_RANGE"])) { $fullSize = floatval($stat['size']); $ranges = explode('=', $_SERVER["HTTP_RANGE"]); $offsets = explode('-', $ranges[1]); $offset = floatval($offsets[0]); $length = floatval($offsets[1]) - $offset; if (!$length) { $length = $fullSize - $offset; } if ($length + $offset > $fullSize || $length < 0) { $length = $fullSize - $offset; } $hash = $this->getPartialHash($node, $offset, $length); } else { $hash = $this->getFileHash($selection->getUniqueNode()); } } else { $hash = 'directory'; } $stat[13] = $stat["hash"] = $hash; print json_encode($stat); } } else { $files = $selection->getFiles(); print '{'; foreach ($files as $index => $path) { $node = new AJXP_Node($selection->currentBaseUrl() . $path); $stat = @stat($selection->currentBaseUrl() . $path); if (!$stat || !is_readable($node->getUrl())) { $stat = '{}'; } else { if (!is_dir($node->getUrl())) { $hash = $this->getFileHash($node); } else { $hash = 'directory'; } $stat[13] = $stat["hash"] = $hash; $stat = json_encode($stat); } print json_encode(SystemTextEncoding::toUTF8($path)) . ':' . $stat . ($index < count($files) - 1 ? "," : ""); } print '}'; } break; break; } }
public function switchActions($actionName, $httpVars, $fileVars) { //$urlBase = $this->accessDriver $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $streamData = $repository->streamData; $this->streamData = $streamData; $destStreamURL = $streamData["protocol"] . "://" . $repository->getId(); switch ($actionName) { case "filehasher_signature": $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); if (!file_exists($destStreamURL . $file)) { break; } $cacheItem = AJXP_Cache::getItem("signatures", $destStreamURL . $file, array($this, "generateSignature")); $data = $cacheItem->getData(); header("Content-Type:application/octet-stream"); header("Content-Length", strlen($data)); echo $data; break; case "filehasher_delta": case "filehasher_patch": // HANDLE UPLOAD DATA $this->logDebug("Received signature file, should compute delta now"); if (!isset($fileVars) && !is_array($fileVars["userfile_0"])) { throw new Exception("These action should find uploaded data"); } $uploadedData = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-sig"); move_uploaded_file($fileVars["userfile_0"]["tmp_name"], $uploadedData); $fileUrl = $destStreamURL . AJXP_Utils::decodeSecureMagic($httpVars["file"]); $file = call_user_func(array($this->streamData["classname"], "getRealFSReference"), $fileUrl, true); if ($actionName == "filehasher_delta") { $signatureFile = $uploadedData; $deltaFile = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-delta"); $this->logDebug("Received signature file, should compute delta now"); rsync_generate_delta($signatureFile, $file, $deltaFile); $this->logDebug("Computed delta file, size is " . filesize($deltaFile)); header("Content-Type:application/octet-stream"); header("Content-Length:" . filesize($deltaFile)); readfile($deltaFile); unlink($signatureFile); unlink($deltaFile); } else { $patched = $file . ".rdiff_patched"; $deltaFile = $uploadedData; rsync_patch_file($file, $deltaFile, $patched); rename($patched, $file); unlink($deltaFile); header("Content-Type:text/plain"); echo md5_file($file); } break; case "stat_hash": $selection = new UserSelection(); $selection->initFromArray($httpVars); clearstatcache(); header("Content-type:application/json"); if ($selection->isUnique()) { $node = $selection->getUniqueNode($this->accessDriver); $stat = @stat($node->getUrl()); if (!$stat) { print '{}'; } else { if ($node->isLeaf()) { $hash = $this->getFileHash($selection->getUniqueNode($this->accessDriver)); } else { $hash = 'directory'; } $stat[13] = $stat["hash"] = $hash; print json_encode($stat); } } else { $files = $selection->getFiles(); print '{'; foreach ($files as $index => $path) { $node = new AJXP_Node($destStreamURL . $path); $stat = @stat($destStreamURL . $path); if (!$stat) { $stat = '{}'; } else { if (!is_dir($node->getUrl())) { $hash = $this->getFileHash($node); } else { $hash = 'directory'; } $stat[13] = $stat["hash"] = $hash; $stat = json_encode($stat); } print json_encode($path) . ':' . $stat . ($index < count($files) - 1 ? "," : ""); } print '}'; } break; break; } }