function get_content()
 {
     global $CFG, $USER;
     if ($this->content !== NULL) {
         return $this->content;
     }
     $content = '';
     $footer = '';
     $nologin_auths = block_repository_nopasswd_auths();
     if (!empty($USER->auth) && in_array($USER->auth, $nologin_auths)) {
         return '';
     }
     if (isloggedin() && file_exists($CFG->dirroot . '/file/repository/alfresco/repository.php')) {
         require_once $CFG->dirroot . '/file/repository/repository.class.php';
         if (isset($CFG->repository_plugins_enabled) && strstr($CFG->repository_plugins_enabled, 'alfresco')) {
             if ($repo = repository_factory::factory('alfresco')) {
                 if ($repo->alfresco_userdir($USER->username) !== false) {
                     // Fix username
                     $username = repository_plugin_alfresco::fix_username($USER->username);
                     // So that we don't conflict with the default Alfresco admin account.
                     $username = $username == 'admin' ? $CFG->repository_alfresco_admin_username : $username;
                     $hastenant = false;
                     // We must include the tenant portion of the username here.
                     if (($tenantname = strpos($CFG->repository_alfresco_server_username, '@')) > 0) {
                         $username .= substr($CFG->repository_alfresco_server_username, $tenantname);
                         $hastenant = true;
                     }
                     // Display a link to access the Alfresco repository directly.
                     $content .= get_string('webappaccess', 'block_repository', $repo->get_webapp_url()) . '<br /><br />';
                     // Display a link to the configured embedded WebDAV client (if defined).
                     if (!empty($CFG->block_course_repository_webdav_client)) {
                         $content .= get_string('embeddedwebdavlink', 'block_repository', $CFG->block_course_repository_webdav_client) . '<br /><br />';
                     }
                     if ($hastenant || $username != $USER->username) {
                         $content .= get_string('usernametenantinfo', 'block_repository', $username);
                     } else {
                         $content .= get_string('usernameinfo', 'block_repository', $username);
                     }
                     // Display a link to defined help files
                     if (!empty($CFG->block_course_repository_help_link)) {
                         $footer = get_string('helpfileslink', 'block_repository', $CFG->block_course_repository_help_link);
                     }
                 }
             }
         }
     }
     // If there is no content and the current user can actually modify the site settings, display some text
     // in the block explaining what is happening.
     if (empty($content) && has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
         if (file_exists($CFG->dirroot . '/admin/file/repositories.php')) {
             $content = get_string('alfresconotconfigured', 'block_repository', $CFG->wwwroot . '/admin/file/' . 'repositories.php');
         } else {
             $content = get_string('norepositorypluginsystem', 'block_repository');
         }
     }
     $this->content = new stdClass();
     $this->content->text = $content;
     $this->content->footer = $footer;
     return $this->content;
 }
Example #2
0
/**
 * Upload a file into the repository.
 *
 * @uses $CFG
 * @uses $USER
 * @param string $upload   The array index of the uploaded file.
 * @param string $path     The full path to the file on the local filesystem.
 * @param string $uuid     The UUID of the folder where the file is being uploaded to.
 * @param bool   $useadmin Set to false to make sure that the administrative user configured in
 *                         the plug-in is not used for this operation (default: true).
 * @return object Node values for the uploaded file.
 */
function alfresco_upload_file($upload = '', $path = '', $uuid = '', $useadmin = true)
{
    global $CFG, $USER;
    require_once $CFG->libdir . '/filelib.php';
    if (!empty($upload)) {
        if (!isset($_FILES[$upload]) || !empty($_FILES[$upload]->error)) {
            return false;
        }
        $filename = $_FILES[$upload]['name'];
        $filepath = $_FILES[$upload]['tmp_name'];
        $filemime = $_FILES[$upload]['type'];
        $filesize = $_FILES[$upload]['size'];
    } else {
        if (!empty($path)) {
            if (!is_file($path)) {
                return false;
            }
            $filename = basename($path);
            $filepath = $path;
            $filemime = mimeinfo('type', $filename);
            $filesize = filesize($path);
        } else {
            return false;
        }
    }
    if (empty($uuid)) {
        $uuid = $USER->repo->get_root()->uuid;
    }
    $chunksize = 8192;
    /// We need to write the XML structure for the upload out to a file on disk to accomdate large files
    /// that will potentially overrun the maximum memory allowed to a PHP script.
    $data1 = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
    if (repository_plugin_alfresco::is_version('3.2')) {
        $data1 .= '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" ' . 'xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200901" xmlns:alf="http://www.alfresco.org">' . "\n" . '  <link rel="type" href="' . alfresco_base_url() . '/api/type/document"/>' . "\n" . '  <link rel="repository" href="' . alfresco_base_url() . '/api/repository"/>' . "\n";
    } else {
        if (repository_plugin_alfresco::is_version('3.4')) {
            $data1 .= '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:cmis="http://www.cmis.org/2008/05">' . "\n";
        }
    }
    $data1 .= '  <title>' . $filename . '</title>' . "\n" . '  <summary>' . get_string('uploadedbymoodle', 'repository_alfresco') . '</summary>' . "\n" . '  <content type="' . $filemime . '">';
    $data2 = '</content>' . "\n" . '  <cmis:object>' . "\n" . '    <cmis:properties>' . "\n" . '      <cmis:propertyString cmis:name="ObjectTypeId">' . "\n" . '        <cmis:value>document</cmis:value>' . "\n" . '      </cmis:propertyString>' . "\n" . '    </cmis:properties>' . "\n" . '  </cmis:object>' . "\n" . '</entry>';
    $encodedbytes = 0;
    /// Use a stream filter to base64 encode the file contents to a temporary file.
    if ($fi = fopen($filepath, 'r')) {
        if ($fo = tmpfile()) {
            stream_filter_append($fi, 'convert.base64-encode');
            /// Write the beginning of the XML document to the temporary file.
            $encodedbytes += fwrite($fo, $data1, strlen($data1));
            /// Copy the uploaded file into the temporary file (usng the base64 encode stream filter)
            /// in 8K chunks to conserve memory.
            while (!feof($fi)) {
                $encodedbytes += fwrite($fo, fread($fi, 8192));
            }
            fclose($fi);
            /// Write the end of the XML document to the temporary file.
            $encodedbytes += fwrite($fo, $data2, strlen($data2));
        }
    }
    rewind($fo);
    // Force the usage of the configured Alfresco admin account, if requested.
    if ($useadmin) {
        $username = '';
    } else {
        $username = $USER->username;
        // Fix username
        $username = repository_plugin_alfresco::fix_username($username);
    }
    if (repository_plugin_alfresco::is_version('3.2')) {
        $serviceuri = '/api/node/workspace/SpacesStore/' . $uuid . '/descendants';
    } else {
        if (repository_plugin_alfresco::is_version('3.4')) {
            $serviceuri = '/cmis/i/' . $uuid . '/children';
        }
    }
    $url = alfresco_utils_get_wc_url($serviceuri, 'refresh', $username);
    $uri = parse_url($url);
    switch ($uri['scheme']) {
        case 'http':
            $port = isset($uri['port']) ? $uri['port'] : 80;
            $host = $uri['host'] . ($port != 80 ? ':' . $port : '');
            $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
            break;
        case 'https':
            /// Note: Only works for PHP 4.3 compiled with OpenSSL.
            $port = isset($uri['port']) ? $uri['port'] : 443;
            $host = $uri['host'] . ($port != 443 ? ':' . $port : '');
            $fp = @fsockopen('ssl://' . $uri['host'], $port, $errno, $errstr, 20);
            break;
        default:
            $result->error = 'invalid schema ' . $uri['scheme'];
            return $result;
    }
    /// Make sure the socket opened properly.
    if (!$fp) {
        $result->error = trim($errno . ' ' . $errstr);
        return $result;
    }
    /// Construct the path to act on.
    $path = isset($uri['path']) ? $uri['path'] : '/';
    if (isset($uri['query'])) {
        $path .= '?' . $uri['query'];
    }
    /// Create HTTP request.
    $headers = array('Host' => "Host: {$host}", 'Content-type' => 'Content-type: application/atom+xml;type=entry', 'User-Agent' => 'User-Agent: Moodle (+http://moodle.org/)', 'Content-Length' => 'Content-Length: ' . $encodedbytes, 'MIME-Version' => 'MIME-Version: 1.0');
    $request = 'POST  ' . $path . " HTTP/1.0\r\n";
    $request .= implode("\r\n", $headers);
    $request .= "\r\n\r\n";
    fwrite($fp, $request);
    /// Write the XML request (which contains the base64-encoded uploaded file contents) into the socket.
    while (!feof($fo)) {
        fwrite($fp, fread($fo, 8192));
    }
    fclose($fo);
    fwrite($fp, "\r\n");
    /// Fetch response.
    $response = '';
    while (!feof($fp) && ($chunk = fread($fp, 8192))) {
        $response .= $chunk;
    }
    fclose($fp);
    /// Parse response.
    list($split, $result->data) = explode("\r\n\r\n", $response, 2);
    $split = preg_split("/\r\n|\n|\r/", $split);
    list($protocol, $code, $text) = explode(' ', trim(array_shift($split)), 3);
    $result->headers = array();
    /// Parse headers.
    while ($line = trim(array_shift($split))) {
        list($header, $value) = explode(':', $line, 2);
        if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
            /// RFC 2109: the Set-Cookie response header comprises the token Set-
            /// Cookie:, followed by a comma-separated list of one or more cookies.
            $result->headers[$header] .= ',' . trim($value);
        } else {
            $result->headers[$header] = trim($value);
        }
    }
    $responses = array(100 => 'Continue', 101 => 'Switching Protocols', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported');
    /// RFC 2616 states that all unknown HTTP codes must be treated the same as
    /// the base code in their class.
    if (!isset($responses[$code])) {
        $code = floor($code / 100) * 100;
    }
    //TODO: check for $code 500 and add menu to replace copy or cancel the uploaded file with the same name as an existing file
    //        if($code == 500) {
    //
    //        } else
    if ($code != 200 && $code != 201 && $code != 304) {
        debugging(get_string('couldnotaccessserviceat', 'repository_alfresco', $serviceuri), DEBUG_DEVELOPER);
        return false;
    }
    $response = preg_replace('/(&[^amp;])+/', '&amp;', $response);
    $dom = new DOMDocument();
    $dom->preserveWhiteSpace = false;
    $dom->loadXML($result->data);
    $nodes = $dom->getElementsByTagName('entry');
    if (!$nodes->length) {
        return false;
    }
    $type = '';
    $properties = alfresco_process_node($dom, $nodes->item(0), $type);
    // Ensure that we set the current user to be the owner of the newly created directory.
    if (!empty($properties->uuid)) {
        $username = alfresco_transform_username($USER->username);
        // We're not going to check the response for this right now.
        alfresco_request('/moodle/nodeowner/' . $properties->uuid . '?username=' . $username);
    }
    return $properties;
}
 function get_defaults()
 {
     // Initialize the alfresco version
     if (!($this->version = self::$version = alfresco_get_repository_version())) {
         return false;
     }
     // Set the file and folder type
     if (!defined('ALFRESCO_TYPE_FOLDER')) {
         if (self::is_version('3.2')) {
             define('ALFRESCO_TYPE_FOLDER', 'folder');
             define('ALFRESCO_TYPE_DOCUMENT', 'document');
         } else {
             if (self::is_version('3.4')) {
                 define('ALFRESCO_TYPE_FOLDER', 'cmis:folder');
                 define('ALFRESCO_TYPE_DOCUMENT', 'cmis:document');
             }
         }
     }
     return true;
 }