/**
  * Returns an ArrayCollection with the contents of the current requested folder
  *
  * @param string $folder Request foldername relative to root folder
  *
  * @return ArrayCollection|boolean Content of folder as array collection. If folder does not exist false
  * @throws \Sabre\DAV\Exception
  */
 public function getDirectoryContents($folder = '')
 {
     try {
         return $this->parsePropResult($this->client->propFind($folder, array('{DAV:}resourcetype', '{DAV:}getcontentlength', '{DAV:}getlastmodified', '{DAV:}quota-used-bytes', '{DAV:}getcontenttype'), 1));
     } catch (Exception $e) {
         return false;
     }
 }
Example #2
0
/**
 * @param \Sabre\DAV\Client $client
 * @param $uploadUrl
 * @return mixed
 */
function request($client, $method, $uploadUrl, $data = null, $headers = [])
{
    echo "{$method} {$uploadUrl} ... ";
    $t0 = microtime(true);
    $result = $client->request($method, $uploadUrl, $data, $headers);
    $t1 = microtime(true);
    echo $result['statusCode'] . " - " . ($t1 - $t0) . ' seconds' . PHP_EOL;
    if (!in_array($result['statusCode'], [200, 201])) {
        echo $result['body'] . PHP_EOL;
    }
    return $result;
}
Example #3
0
 public function listFolder($user, $path, $folderDepth)
 {
     $fullUrl = substr($this->baseUrl, 0, -4);
     $settings = array('baseUri' => $fullUrl, 'userName' => $user);
     if ($user === 'admin') {
         $settings['password'] = $this->adminUser[1];
     } else {
         $settings['password'] = $this->regularUser;
     }
     $client = new SClient($settings);
     $response = $client->propfind($this->davPath . "/", array('{DAV:}getetag'), $folderDepth);
     return $response;
 }
Example #4
0
 protected function connect($url, $username, $password) {
     $client = new Client(array(
         'baseUri' => $url,
         'userName' => $username,
         'password' => $password,
     ));
     try {
         $response = $client->options();
         return $response ? $client : null;
     } catch (Exception $exc) {
         return null;
     }
 }
Example #5
0
 /**
  * check if a file or folder has been updated since $time
  *
  * @param string $path
  * @param int $time
  * @throws \OCP\Files\StorageNotAvailableException
  * @return bool
  */
 public function hasUpdated($path, $time)
 {
     $this->init();
     $path = $this->cleanPath($path);
     try {
         $response = $this->client->propfind($this->encodePath($path), array('{DAV:}getlastmodified', '{DAV:}getetag', '{http://owncloud.org/ns}permissions'));
         if (isset($response['{DAV:}getetag'])) {
             $cachedData = $this->getCache()->get($path);
             $etag = trim($response['{DAV:}getetag'], '"');
             if ($cachedData['etag'] !== $etag) {
                 return true;
             } else {
                 if (isset($response['{http://owncloud.org/ns}permissions'])) {
                     $permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
                     return $permissions !== $cachedData['permissions'];
                 } else {
                     return false;
                 }
             }
         } else {
             $remoteMtime = strtotime($response['{DAV:}getlastmodified']);
             return $remoteMtime > $time;
         }
     } catch (Exception\NotFound $e) {
         return false;
     } catch (Exception $e) {
         throw new StorageNotAvailableException();
     }
 }
Example #6
0
 public function parseMultiStatus($body)
 {
     $body = str_replace('<D:', '<d:', $body);
     $body = str_replace('</D:', '</d:', $body);
     $body = str_replace(':D=', ':d=', $body);
     return parent::parseMultiStatus($body);
 }
 public function __construct(array $a)
 {
     parent::__construct($a);
     //$this->requestLogFH = fopen('/var/log/tine20/requestLog', 'w');
     $this->propertyMap['{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set'] = 'Sabre\\CalDAV\\Property\\SupportedCalendarComponentSet';
     $this->propertyMap['{DAV:}acl'] = 'Sabre\\DAVACL\\Property\\Acl';
     $this->propertyMap['{DAV:}group-member-set'] = 'Tinebase_Import_CalDav_GroupMemberSet';
 }
Example #8
0
 protected function curlRequest($url, $settings)
 {
     if ($this->requestTimeout > 0) {
         $settings[CURLOPT_TIMEOUT] = $this->requestTimeout;
     }
     if (!is_null($this->verifyHost)) {
         $settings[CURLOPT_SSL_VERIFYHOST] = $this->verifyHost;
     }
     return parent::curlRequest($url, $settings);
 }
Example #9
0
    function testMultiGet()
    {
        $request = new HTTP\Request(array('REQUEST_METHOD' => 'REPORT', 'REQUEST_URI' => '/addressbooks/user1/book1'));
        $request->setBody('<?xml version="1.0"?>
<c:addressbook-multiget xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:carddav">
    <d:prop>
      <d:getetag />
      <c:address-data />
    </d:prop>
    <d:href>/addressbooks/user1/book1/card1</d:href>
</c:addressbook-multiget>');
        $response = new HTTP\ResponseMock();
        $this->server->httpRequest = $request;
        $this->server->httpResponse = $response;
        $this->server->exec();
        $this->assertEquals('HTTP/1.1 207 Multi-Status', $response->status, 'Incorrect status code. Full response body:' . $response->body);
        // using the client for parsing
        $client = new DAV\Client(array('baseUri' => '/'));
        $result = $client->parseMultiStatus($response->body);
        $this->assertEquals(array('/addressbooks/user1/book1/card1' => array(200 => array('{DAV:}getetag' => '"' . md5("BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD") . '"', '{urn:ietf:params:xml:ns:carddav}address-data' => "BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD"))), $result);
    }
Example #10
0
    function testMultiGetVCard4()
    {
        $request = HTTP\Sapi::createFromServerArray(['REQUEST_METHOD' => 'REPORT', 'REQUEST_URI' => '/addressbooks/user1/book1']);
        $request->setBody('<?xml version="1.0"?>
<c:addressbook-multiget xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:carddav">
    <d:prop>
      <d:getetag />
      <c:address-data content-type="text/vcard" version="4.0" />
    </d:prop>
    <d:href>/addressbooks/user1/book1/card1</d:href>
</c:addressbook-multiget>');
        $response = new HTTP\ResponseMock();
        $this->server->httpRequest = $request;
        $this->server->httpResponse = $response;
        $this->server->exec();
        $this->assertEquals(207, $response->status, 'Incorrect status code. Full response body:' . $response->body);
        // using the client for parsing
        $client = new DAV\Client(['baseUri' => '/']);
        $result = $client->parseMultiStatus($response->body);
        $prodId = "PRODID:-//Sabre//Sabre VObject " . \Sabre\VObject\Version::VERSION . "//EN";
        $this->assertEquals(['/addressbooks/user1/book1/card1' => [200 => ['{DAV:}getetag' => '"' . md5("BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD") . '"', '{urn:ietf:params:xml:ns:carddav}address-data' => "BEGIN:VCARD\r\nVERSION:4.0\r\n{$prodId}\r\nUID:12345\r\nEND:VCARD\r\n"]]], $result);
    }
 /**
  * {@inheritdoc}
  */
 public function listContents($directory = '', $recursive = false)
 {
     $location = $this->applyPathPrefix($directory);
     $response = $this->client->propFind($location, ['{DAV:}displayname', '{DAV:}getcontentlength', '{DAV:}getcontenttype', '{DAV:}getlastmodified'], 1);
     array_shift($response);
     $result = [];
     foreach ($response as $path => $object) {
         $path = $this->removePathPrefix($path);
         $object = $this->normalizeObject($object, $path);
         $result[] = $object;
         if ($recursive && $object['type'] === 'dir') {
             $result = array_merge($result, $this->listContents($object['path'], true));
         }
     }
     return $result;
 }
 /**
  * get nodes from adapter backend
  *
  * @param string $path
  * @return array nodes
  */
 private function getNodesFromBackend($path)
 {
     $response = $this->client->propfind($this->encodePath($path), array(), 1);
     $result = array();
     $statNode = true;
     $path = $path === false ? '' : $path;
     foreach ($response as $key => $value) {
         if ($statNode) {
             $nodePath = $path;
             $statNode = false;
         } else {
             $nodePath = $path . '/' . urldecode(basename($key));
         }
         $result[] = $this->rawDataToNode($nodePath, $value);
     }
     return $result;
 }
Example #13
0
 /**
  * @param string $method
  * @param string $path
  * @param string|resource|null $body
  * @param int $expected
  * @return bool
  * @throws StorageInvalidException
  * @throws StorageNotAvailableException
  */
 private function simpleResponse($method, $path, $body, $expected)
 {
     $path = $this->cleanPath($path);
     try {
         $response = $this->client->request($method, $this->encodePath($path), $body);
         return $response['statusCode'] == $expected;
     } catch (ClientHttpException $e) {
         if ($e->getHttpStatus() === 404 && $method === 'DELETE') {
             $this->statCache->clear($path . '/');
             $this->statCache->set($path, false);
             return false;
         }
         $this->convertException($e);
     } catch (\Exception $e) {
         $this->convertException($e);
     }
     return false;
 }
Example #14
0
File: Ical.php Project: horde/horde
 /**
  * Returns a configured, cached DAV client.
  *
  * @param string $uri  The base URI for any requests.
  *
  * @return \Sabre\DAV\Client  A DAV client.
  * @throws \Sabre\DAV\Exception
  * @throws \Sabre\HTTP\ClientException
  */
 protected function _getClient($uri)
 {
     global $conf;
     $options = array('baseUri' => $uri);
     if (!empty($this->_params['user'])) {
         $options['userName'] = $this->_params['user'];
         $options['password'] = $this->_params['password'];
     }
     $this->_client = new Client($options);
     $this->_client->addCurlSetting(CURLOPT_TIMEOUT, isset($this->_params['timeout']) ? $this->_params['timeout'] : 5);
     if (!empty($conf['http']['proxy']['proxy_host'])) {
         $this->_client->addCurlSetting(CURLOPT_PROXY, $conf['http']['proxy']['proxy_host']);
         $this->_client->addCurlSetting(CURLOPT_PROXYPORT, $conf['http']['proxy']['proxy_port']);
         if (!empty($conf['http']['proxy']['proxy_user']) && !empty($conf['http']['proxy']['proxy_pass'])) {
             $this->_client->addCurlSetting(CURLOPT_PROXYUSERPWD, $conf['http']['proxy']['proxy_user'] . ':' . $conf['http']['proxy']['proxy_pass']);
         }
     }
     return $this->_client;
 }
Example #15
0
 /** {@inheritdoc} */
 public function getPermissions($path)
 {
     $this->init();
     $path = $this->cleanPath($path);
     $response = $this->client->propfind($this->encodePath($path), array('{http://owncloud.org/ns}permissions'));
     if (isset($response['{http://owncloud.org/ns}permissions'])) {
         return $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
     } else {
         if ($this->is_dir($path)) {
             return \OCP\Constants::PERMISSION_ALL;
         } else {
             if ($this->file_exists($path)) {
                 return \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE;
             } else {
                 return 0;
             }
         }
     }
 }
 /**
  * Parses a WebDAV multistatus response body
  *
  * @param string $body xml body
  * @return array
  */
 public function parseMultiStatus($body)
 {
     $oldSetting = libxml_use_internal_errors(true);
     try {
         $result = parent::parseMultiStatus($body);
         if (count($xmlErrors = libxml_get_errors()) > 0) {
             if (Tinebase_Core::isLogLevel(Zend_Log::WARN)) {
                 Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' XML errors occured: ' . print_r($xmlErrors, true));
             }
         }
         libxml_clear_errors();
         libxml_use_internal_errors($oldSetting);
     } catch (InvalidArgumentException $e) {
         libxml_clear_errors();
         libxml_use_internal_errors($oldSetting);
         // remove possible broken chars here to avoid simplexml_load_string errors
         // this line may throw an Exception again! thats why the libxml_* functions are called in try and catch!
         $result = parent::parseMultiStatus(Tinebase_Helper::removeIllegalXMLChars($body));
     }
     return $result;
 }
Example #17
0
 /**
  * Just making this method public
  *
  * @param string $url
  * @return string
  */
 function getAbsoluteUrl($url)
 {
     return parent::getAbsoluteUrl($url);
 }
Example #18
0
 /**
  * Overwrite parent method so parameter $url is now optional
  * @param string $url
  *
  * @return string
  */
 public function getAbsoluteUrl($url = '')
 {
     return parent::getAbsoluteUrl($url);
 }
Example #19
0
 public function pingRemoteDAVPoint()
 {
     $fullPath = rtrim($this->getOcsDavUrl(), "/") . "/" . $this->getDocumentName();
     $parts = parse_url($fullPath);
     $client = new DAV\Client(array('baseUri' => $parts["scheme"] . "://" . $parts["host"], 'userName' => $this->getOcsToken(), 'password' => ''));
     try {
         $result = $client->propFind($parts["path"], ['{DAV:}getlastmodified', '{DAV:}getcontentlength', '{DAV:}resourcetype']);
     } catch (Exception\NotFound $e) {
         return false;
     } catch (Exception $e) {
         return false;
     }
     /**
      * @var \Sabre\DAV\Property\ResourceType $resType;
      */
     $resType = $result["{DAV:}resourcetype"];
     if ($resType->is("{DAV:}collection")) {
         $this->setDocumentIsLeaf(false);
     } else {
         $this->setDocumentIsLeaf(true);
     }
     $this->documentTypeResolved = true;
     return true;
 }
    function testVCard4()
    {
        $request = new HTTP\Request('REPORT', '/addressbooks/user1/book1/card1', ['Depth' => '0']);
        $request->setBody('<?xml version="1.0"?>
<c:addressbook-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:carddav">
    <d:prop>
      <c:address-data content-type="text/vcard" version="4.0" />
      <d:getetag />
    </d:prop>
</c:addressbook-query>');
        $response = new HTTP\ResponseMock();
        $this->server->httpRequest = $request;
        $this->server->httpResponse = $response;
        $this->server->exec();
        $this->assertEquals(207, $response->status, 'Incorrect status code. Full response body:' . $response->body);
        // using the client for parsing
        $client = new DAV\Client(['baseUri' => '/']);
        $result = $client->parseMultiStatus($response->body);
        $vobjVersion = \Sabre\VObject\Version::VERSION;
        $this->assertEquals(['/addressbooks/user1/book1/card1' => [200 => ['{DAV:}getetag' => '"' . md5("BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD") . '"', '{urn:ietf:params:xml:ns:carddav}address-data' => "BEGIN:VCARD\r\nVERSION:4.0\r\nPRODID:-//Sabre//Sabre VObject {$vobjVersion}//EN\r\nUID:12345\r\nEND:VCARD\r\n"]]], $result);
    }
Example #21
0
<?php

use Sabre\VObject;
use Sabre\DAV;
include 'vendor/autoload.php';
require_once realpath(dirname(__FILE__) . '/cardDav_connection.php');
$client = new DAV\Client($settings);
$method = filter_input(INPUT_GET, "method");
if (empty($method)) {
    $method = "calDAV";
}
if ($method == "cardDAV") {
    $firstresponse = $client->propfind('/remote.php/carddav/addressbooks/' . $settings["userName"], array('{DAV:}displayname'), 1);
    foreach ($firstresponse as $addressbook => $value) {
        if (empty($value)) {
            continue;
        }
        $response = $client->propfind($addressbook, array('{DAV:}displayname'), 1);
        foreach ($response as $vcardUrl => $value) {
            if ($vcardUrl == $addressbook) {
                continue;
            }
            $vcardresponse = $client->request('GET', $vcardUrl);
            $vcard = VObject\Reader::read($vcardresponse["body"]);
            $name = (string) $vcard->FN;
            $bday_raw = explode("-", (string) $vcard->BDAY);
            if (!empty($bday_raw[0])) {
                $bdays[$name] = mktime(0, 0, 0, $bday_raw[1], $bday_raw[2], $bday_raw[0]) * 1000;
            }
        }
    }
Example #22
0
 public function getRepo()
 {
     if (file_exists($this->git_dir)) {
         $this->recursiveRemoveDirectory($this->git_dir);
     }
     $repo = Gitonomy\Git\Admin::cloneTo($this->git_dir, $this->git_url, false);
     $tags = $repo->getReferences()->getTags();
     /**
      * If no tags, use master
      */
     if (empty($tags)) {
         $commitHash = $repo->getReferences()->getBranch('master')->getCommitHash();
     } else {
         rsort($tags);
         $commitHash = $tags[0]->getCommitHash();
     }
     if ($commitHash === $this->info["last_commit"]) {
         // No need of update
         return true;
     }
     $sql = \Lobby\DB::getDBH()->prepare("UPDATE `git_cache` SET `last_commit` = ? WHERE `git_url` = ?");
     $sql->execute(array($commitHash, $this->git_url));
     $this->recursiveRemoveDirectory($this->git_dir . "/.git");
     /**
      * Get screenshots
      */
     $manifest = json_decode(file_get_contents($this->git_dir . "/manifest.json"), true);
     // Manifest file is invalid
     if (!is_array($manifest)) {
         return false;
     }
     if (isset($manifest["version"])) {
         $latestVersion = $manifest["version"];
     } else {
         return false;
     }
     if (isset($manifest->screenshots)) {
         $screenshots = array();
         foreach ($manifest["screenshots"] as $img) {
             $url = parse_url($img);
             if ($url["host"] === "i.imgur.com") {
                 $path = $url["path"];
                 // $path has slash at beginning
                 $headers = @get_headers("http://i.imgur.com{$path}", 1);
                 if ($headers[0] === "HTTP/1.1 200 OK") {
                     $screenshots[] = "//i.imgur.com{$path}";
                 }
             }
         }
         if (empty($screenshots)) {
             unset($screenshots);
         }
     }
     if (exec("cd {$this->git_dir};zip -r '{$this->git_dir}/app.zip' ./ -1 -q;") !== false) {
         $logo = true;
         if (file_exists($this->git_dir . "/src/image/logo.svg")) {
             $this->convertLogoToPNG();
         } else {
             if (file_exists($this->git_dir . "/src/image/logo.png")) {
                 copy($this->git_dir . "/src/image/logo.png", $this->git_dir . "/logo.png");
             } else {
                 $logo = false;
             }
         }
         $webdavPass = getenv("SKY_WEBDAV_PASS");
         $settings = array('baseUri' => "https://sky-phpgeek.rhcloud.com/remote.php/webdav/Apps/{$this->id}/", 'userName' => 'lobby-apps', 'password' => $webdavPass);
         $client = new Client($settings);
         /**
          * Create folder
          */
         $client->request('MKCOL');
         /**
          * Upload files
          */
         $client->request('PUT', "{$this->id}.zip", file_get_contents($this->git_dir . "/app.zip"));
         if ($logo) {
             $client->request('PUT', "logo.png", file_get_contents($this->git_dir . "/logo.png"));
         }
         $request = \Requests::post("https://sky-phpgeek.rhcloud.com/ocs/v1.php/apps/files_sharing/api/v1/shares?format=json", array("Content-Type" => "application/x-www-form-urlencoded"), array("path" => "Apps/{$this->id}", "shareType" => "3"), array("auth" => array("lobby-apps", $webdavPass)));
         $response = json_decode($request->body);
         $this->cloud_id = $response->ocs->data->token;
         $extraColumnData = array("short_description" => $manifest["short_description"]);
         if (isset($latestVersion)) {
             $extraColumnData["version"] = $latestVersion;
         }
         if (isset($screenshots)) {
             $extraColumnData["screenshots"] = implode("\n", $screenshots);
         }
         if (isset($manifest["require"]) && is_array($manifest["require"])) {
             $extraColumnData["requires"] = json_encode($manifest["require"]);
         }
         /**
          * Update Cloud ID and download file size
          */
         $appInfoUpdate = array(":cloudID" => $this->cloud_id, ":downloadSize" => filesize($this->git_dir . "/app.zip"), ":appID" => $this->id);
         $extraColumns = "";
         if (!empty($extraColumnData)) {
             foreach ($extraColumnData as $k => $v) {
                 $extraColumns .= ", {$k} = :{$k}";
                 $appInfoUpdate[":{$k}"] = $v;
             }
         }
         $sql = \Lobby\DB::getDBH()->prepare("UPDATE `apps` SET `cloud_id` = :cloudID, `download_size` = :downloadSize, `updated` = NOW() {$extraColumns} WHERE `id` = :appID");
         $sql->execute($appInfoUpdate);
         $this->recursiveRemoveDirectory($this->git_dir);
         return true;
     }
     return false;
 }
Example #23
0
 public function changeFavStateOfAnElement($user, $path, $favOrUnfav, $folderDepth, $properties = null)
 {
     $fullUrl = substr($this->baseUrl, 0, -4);
     $settings = array('baseUri' => $fullUrl, 'userName' => $user);
     if ($user === 'admin') {
         $settings['password'] = $this->adminUser[1];
     } else {
         $settings['password'] = $this->regularUser;
     }
     $client = new SClient($settings);
     if (!$properties) {
         $properties = ['{http://owncloud.org/ns}favorite' => $favOrUnfav];
     }
     $response = $client->proppatch($this->davPath . '/' . ltrim($path, '/'), $properties, $folderDepth);
     return $response;
 }
Example #24
0
 /**
  * @param string $url
  * @param string $sharedSecret
  * @param string $resourcePath
  * @return array
  */
 protected function download($url, $sharedSecret, $resourcePath)
 {
     $settings = ['baseUri' => $url, 'userName' => 'system', 'password' => $sharedSecret];
     $client = new Client($settings);
     $client->setThrowExceptions(true);
     $response = $client->request('GET', $resourcePath);
     return $response;
 }
Example #25
0
<?php

require 'SabreDAV/vendor/autoload.php';
require 'credentials.php';
use Sabre\DAV\Client;
// Parameters
$serie = $_GET["s"];
$chapter = str_pad($_GET["c"], 4, "0", STR_PAD_LEFT);
$nextPage = str_pad(intval($_GET["p"]) + 1, 2, "0", STR_PAD_LEFT);
// Complete filename
$filename = '/' . $serie . '/' . $chapter . '/' . $chapter . '-' . $nextPage . '.jpg';
// Set credentials
$settings = getCredentials($serie, $chapter);
$client = new Client($settings);
$response = $client->request('GET', $filename);
$statusCode = $response["statusCode"];
if ($statusCode != 200) {
    // We try the next chapter
    $chapter = intval($chapter) + 1;
    $nextPage = 1;
}
$url = 'read.php?s=' . $serie . '&c=' . intval($chapter) . '&p=' . intval($nextPage);
echo $url;