NAME

Net::SharePoint::Basic - Basic interface to Microsoft SharePoint REST API

VERSION

Version 0.11

SYNOPSIS

Net::SharePoint::Basic - Basic interface to Microsoft SharePoint REST API.

This module provides a basic interface for managing the Shared Documents catalog in the Microsoft SharePoint site via its REST API. In the current version only the following actions are supported:

 * generating a connection token
 * upload file or string
 * download file content and save it
 * list contents of folder
 * create new folder
 * delete file or folder

More actions are expected to be added in the future as well as we plan to increase the versatility of the arguments accepted by this module and the sample implementation of a client, 'sp-client', that comes with it.

The interface is object oriented. A few constants are exported.

The full testing (and naturally the full usage) of the module requires a working SharePoint site configuration. The structure of the configuration file will be described in this manual as well. The sample configuration file provided in this distribution will not work against SharePoint and plays the role of a placeholder only.

    use Net::SharePoint::Basic;

    my $sp = Net::SharePoint::Basic->new({config_file => 'sharepoint.conf'});
    # creates Shared Documents/test
    my $response = $sp->makedir({retries => 1}, '/test');
    # uploads a string as Shared Documents/test/teststring
    $sp->upload({}, '/test/teststring', 'abcd');
    # uploads a file 'testfile' into Shared Documents/test/
    $sp->upload({type => 'file'}, '/test/', 'testfile');
    # downloads contents of a file
    $sp->download({}, '/test/teststring');
    # downloads contents and saves it to a file
    $sp->download({save_file => 'testfile'}, '/test/teststring');
    # lists contents of a folder
    $sp->list({}, '/test');
    # deletes the folder
    $sp->delete({}, '/test');
    # moves an object
    $sp->move({}, '/test-file', '/test-moved-file');
    # copies an object
    $sp->copy({}, '/test-moved-file', '/test-file');

This module was developed based on the MSDN SharePoint REST API at https://msdn.microsoft.com/en-us/library/office/jj860569.aspx .

EXPORT

The following constants (all can be overridden through either configuration file or constructor options) are exported:

$DEFAULT_SHAREPOINT_TOKEN_FILE

The default location of the authorization token file (/var/run/sharepoint.token'

$DEFAULT_SHAREPOINT_CONFIG_FILE

The default location of the SharePoint portal configuration (/etc/sharepoint.conf)

$DEFAULT_RETRIES

The default number of retries to perform a REST action (3)

$DEFAULT_CHUNK_SIZE

The default chunk size for uploading large items. (200000000 bytes)

$MAX_LOG_SIZE

The maxium number of logged actions to keep (see log_it method (500000)

CONFIGURATION FILE

The module can work with a configuration file of the following format:

configuration_option <whitespace> value

The lines starting with '#' are ignored. The multiline values can be broken by using a backslash '\' sign. A sample configuration file is provided in the 't/' directory. It will NOT work with a Microsoft SharePoint instance, it is a placeholder file, useful only for internal tests. The default location of the configuration file assumed by the module is /etc/sharepoint.conf . The recognized options in the configuration file are:

 * module configuration:
   o token_file   - where to store the SharePoint token
   o max_log_size - maximum log size of $object->{log} (q.v.)
   o retries      - number of retries
   o chunk_size   - size of a chunk for upload in chunks of large files
 * SharePoint configuration:
   o sharepoint_client_id     - UUID of this client for SharePoint
   o sharepoint_client_secret - client secret for generating the access token
   o sharepoint_tenant_id     - UUID of the SharePoint tenant
   o sharepoint_principal_id  - UUID of the SharePoint principal
   o sharepoint_host          - the hostname of the SharePoint portal
   o sharepoint_site          - the site to work with in SharePoint
   o sharepoint_access_url    - URL to request the token from

ENVIROMENT VARIABLES

The following environment variables control the SharePoint client's behavior, for the purpose of debugging output:

 * NET_SHAREPOINT_VERBOSE - enable verbose output
 * NET_SHAREPOINT_DEBUG   - enable debug output

SUBROUTINES/METHODS

verbose ($)

 Utility function printing some extra messages. Newline is automatically appended.
 Parameters: the message to print (if a verbosity setting is on).
 Returns: void

debug ($)

 Utility function printing some debug messages. Newline is automatically appended.
 Parameters: the message to print (if a verbosity setting is on).
 Returns: void

timedebug ($)

 Utility function printing some debug messages with timestamp prepended. Newline is automatically appended.
 Parameters: the message to print (if a verbosity setting is on).
 Returns: void

version (;$)

 Utility function returning the version of the package
 Parameters: Do not exit after printing version (optional)
 Returns: never.

read_file ($)

 Utility function that reads file into a string or dies if the file is not available.
 Parameters: the file to read
 Returns: the contents of the file as a string

write_file ($$;$)

 Utility function thgat writes the given string into a file, creating the necessary directories above it if necessary. Dies if the write is unsuccessful.
 Parameters: the contents
             the file to write
             [optional] force binary mode in writing
 Returns: the file path that was written.

read_config ($)

 Utility function that reads the sharepoint configuration file of whitespace separated values. See the detailed description of C<Configuration File>
 Parameters: the configuration file
 Returns: Hash of configuration parameters and their values.

new ($;$)

 The constructor. Creates the Net::SharePoint::Basic object
 Parameters: optional hash with keys corresponding to the configuration file fields. Will override even the given a specific configuration file.
 Returns: Net::SharePoint::Basic object.

dump_config ($)

 Dumps the supplied config and exits
 Arguments: the options hash
 Returns: void
 Caveat: will dump the credentials as well. Use with caution.

validate_config ($;@)

 Validates the configuration for the SharePoint client. Checks basic syntactic requirements for the key configuration parameters expected to make connection with the REST API.
 Parameters: [optional] a list of extra options that would require to be defined by the application
 Returns: Error string if there was an error, empty string otherwise.

log_it ($$;$)

 Log a message into the object. The messages are stored in the $object->{log} array reference. If the amount of messages exceeds $MAX_LOG_SIZE or $self->{config}{max_log_size} (if set), the older messages are shifted out of the log.
 Parameters: the message
             [optional] the severity (default - 'info')
 Returns: the shifted discarded message if any

create_payload ($)

 Creates an authorization request payload
 Arguments: the options hashref containing the sharepoint data
 Returns: the escaped payload

update_token ($$)

 Updates the SharePoint Token
 Arguments: the options hashref containing sharepoint data
 Returns: 1 upon success
          undef upon failure

init_token ($)

 Initializes a SharePoint token ( by calling ->update_token() ) and stores it in the $self->{config}{token_file}
 Parameters: none
 Returns: 1 if success
          undef if failure

create_sharepoint_url ($$;@)

 Creates the SharePoint URL to operate against, filling the relevant pattern with the actual data.
 Parameters: the options hashref of the following keys
             pattern - the ready pattern (usually used in chunk upload) - or
             type - the type of the pattern
               (upload, download, list, makedir, delete) and
             subtype (for list only) - "files" or "folders"
             folder - the sharepoint folder/path to operate upon
             object - the sharepoint object to operate upon
 See %PATTERNS in the source code for more details on the URL construction.
 Returns: the filled URL string

try ($$$%)

 Tries to execute a SharePoint REST API call
 Parameters: the options hashref with the following parameters:
               action - mandatory, one of upload, download, list, makedir, delete,
                 chunk_upload_start, chunk_upload_continue, chunk_upload_finish
               retries - optional, number of retries defaults to $DEFAULT_RETRIES
             the url to try
             extra http header options hash:
               Accept         => 'application/json;odata=verbose',
               Content_Type   => 'application/json;odata=verbose',
               Authorization  => 'Bearer TOKEN_STRING',
             and for upload also:
               Content_Length => length($data),
               Content        => $data,
 Returns: the HTTP response if the API call was successful
          undef otherwise

get_chunk_pattern ($$)

 Selects correct pattern for uploading a chunk, depending on the stage of the upload.
 Parameters: the chunk's number (0..N)
             the number of total chunks (N)
 Returns: the start upload pattern for the first chunk
          the finish upload pattern for the last chunk
          the continue upload pattern for the rest
 Caveat: uses when() feature.

upload_in_chunks ($$$$$;$)

 Uploads a string in chunks, useful for uploading large volumes of data above the default SharePoint limit, usually 250000000 bytes.
 Parameters: the options hash with the number of retries as the only used key.
             the string scalar of data to upload
             the SharePoint object basename to create
             the SharePoint path to put the object in
             (optional) the chunk size. Defaults to either configured chunk size or to $DEFAULT_CHUNK_SIZE.
 Returns: the cumulative C<try()> response. If any of the tries fails aborts and returns 0.
 Caveat: the object must already be exist in SharePoint, even with zero size. See C<upload>.

upload ($$$$)

 Uploads a file or a string to SharePoint. Initiates the upload in chunks if necessary, generating the zero sized file for it before calling C<upload_in_chunks>
 Parameters: the options hash with
               type - "file" means we're uploading a file
               retries - the number of retries
             the SharePoint target. If it's a path ending with '/', basename of the file is being appended.
             the item - file or data string
 Returns: the HTTP response object if successful.
          0 when the upload fails or
            when the file is unreadable or
            when the upload is of a string and no target filename is specified.

download ($$$;$)

 Downloads an object from SharePoint, optionally saving it into a file.
 Parameters: the options hashref
               save_file - the local path to save (or see target below)
               retries - the number of retries
             the SharePoint path to download
             (optional) the target local path to save. If target (or save_file value) is a directory, use basename of the SharePoint path for filename. The directory tree is created via C<write_file>.
 Returns: 0 if download failed
          path contents as a string scalar if string is requested
          saved path if a file save is requested

list ($$;$)

 Gets the contents of a given SharePoint folder. Note that you cannot list a file, you need to provide its path (event if it is root), and filter the results. Two API calls are issued, one to list files in the folders, one to list subfolders.
 Parameters: the options hashref
               path - the path to list
               retries - the number of retries
             path - (optional) - alternative way to specify path to list
 Returns: a decoded JSON structure of the REST API response or
          an empty list in case of failure.
 For the interpretation of the results for an actual listing, see the print_list_reports subroutine in the example SharePoint client provided in the package.

makedir ($$$)

 Creates a new folder in SharePoint.
 Parameters: the options hashref
               retries - the number of retries
             the folder to create
 Returns: the REST API response as returned by C<try()>

delete ($$$)

 Deletes an item in SharePoint.
 Parameters: the options hashref
               retries - the number of retries
             the item to delete
 Returns: the REST API response as returned by C<try()>
 Note: any item will be deleted (put to Recycle Bin), even a non-empty folder. If a non-existent item is requested for deletion, the deletion will still return success, but the resulting response will have field $json->{d}{Recycle} set to "00000000-0000-0000-0000-000000000000"

move ($$$$)

 Moves an item in SharePoint
 Parameters: the options hashref
               retries - the number of retries
             the item to move
             the destination to move to
 Returns: the REST API response as returned by C<try()>

copy ($$$$)

 Copies an item in SharePoint
 Parameters: the options hashref
               retries - the number of retries
             the item to copy
             the destination to copy to
 Returns: the REST API response as returned by C<try()>

AUTHOR

Roman Parparov, <rparparov at vmware.com>

BUGS

Please report any bugs or feature requests to bug-net-sharepoint-simple at rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-SharePoint-Basic. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc Net::SharePoint::Basic

You can also look for information at:

ACKNOWLEDGEMENTS

Special thanks to Andre Abramenko https://www.pilothouseconsulting.com/ for helping me figure out the REST API when I initially implemented it at VMware.

LICENSE AND COPYRIGHT

Copyright 2018 VMware.com

This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.

See http://dev.perl.org/licenses/ for more information.