* Simple elFinder driver for BoxDrive
* @author Dmitry (dio) Levashov
* @author Cem (discofever)
class elFinderVolumeBox extends elFinderVolumeDriver
* Must be started from letter and contains [a-z0-9]
* Used as part of volume id.
protected $driverId = 'bd';
* @var string The base URL for API requests
const API_URL = 'https://api.box.com/2.0';
* @var string The base URL for authorization requests
const AUTH_URL = 'https://account.box.com/api/oauth2/authorize';
* @var string The base URL for token requests
const TOKEN_URL = 'https://api.box.com/oauth2/token';
* @var string The base URL for upload requests
const UPLOAD_URL = 'https://upload.box.com/api/2.0';
const FETCHFIELDS = 'type,id,name,created_at,modified_at,description,size,parent,permissions,file_version,shared_link';
* Directory for tmp files
* If not set driver will try to use tmbDir as tmpDir.
public $netMountKey = '';
* Path to access token file for permanent mount
private $aTokenFile = '';
protected $HasdirsCache = array();
* Extend options with required fields.
* @author Dmitry (dio) Levashov
* @author Cem (DiscoFever)
public function __construct()
'acceptedName' => '#^[^\\\/]+$#',
'rootCssClass' => 'elfinder-navbar-root-box',
$this->options = array_merge($this->options, $opts);
$this->options['mimeDetect'] = 'internal';
/*********************************************************************/
/*********************************************************************/
* Get Parent ID, Item ID, Parent Path as an array from path.
protected function _bd_splitPath($path)
$path = trim($path, '/');
$paths = explode('/', trim($path, '/'));
$parent = '/' . implode('/', $paths);
$pid = array_pop($paths);
return array($pid, $id, $parent);
* Obtains a new access token from OAuth. This token is valid for one hour.
* @param string $clientSecret The Box client secret
* @param string $code The code returned by Box after
* @param string $redirectUri Must be the same as the redirect URI passed
* @throws \Exception Thrown if this Client instance's clientId is not set
* @throws \Exception Thrown if the redirect URI of this Client instance's
protected function _bd_obtainAccessToken($client_id, $client_secret, $code)
if (null === $client_id) {
return $this->setError('The client ID must be set to call obtainAccessToken()');
if (null === $client_secret) {
return $this->setError('The client Secret must be set to call obtainAccessToken()');
return $this->setError('Authorization code must be set to call obtainAccessToken()');
$fields = http_build_query(
'client_id' => $client_id,
'client_secret' => $client_secret,
'grant_type' => 'authorization_code',
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $fields,
$decoded = $this->_bd_curlExec($curl, true, array('Content-Length: ' . strlen($fields)));
'expires' => time() + $decoded->expires_in - 30,
if (!empty($decoded->refresh_token)) {
$res->initialToken = md5($client_id . $decoded->refresh_token);
* Get token and auto refresh.
* @return true|string error message
protected function _bd_refreshToken()
if (!property_exists($this->token, 'expires') || $this->token->expires < time()) {
if (!$this->options['client_id']) {
$this->options['client_id'] = ELFINDER_BOX_CLIENTID;
if (!$this->options['client_secret']) {
$this->options['client_secret'] = ELFINDER_BOX_CLIENTSECRET;
if (empty($this->token->data->refresh_token)) {
throw new \Exception(elFinder::ERROR_REAUTH_REQUIRE);
$refresh_token = $this->token->data->refresh_token;
$initialToken = $this->_bd_getInitialToken();
$aTokenFile = $this->aTokenFile? $this->aTokenFile : $this->_bd_getATokenFile();
if ($aTokenFile && is_file($aTokenFile)) {
$lock = $aTokenFile . '.lock';
if (file_exists($lock)) {
// Probably updating on other instance
$GLOBALS['elFinderTempFiles'][$lock] = true;
'client_id' => $this->options['client_id'],
'client_secret' => $this->options['client_secret'],
'grant_type' => 'refresh_token',
'refresh_token' => $refresh_token
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true, // i am sending post data
CURLOPT_POSTFIELDS => http_build_query($postData),
$decoded = $this->_bd_curlExec($curl, true, array(), $postData);
$error = $e->getMessage();
if (!$decoded && !$error) {
$error = 'Tried to renew the access token, but did not get a response from the Box server.';
throw new \Exception('Box access token update failed. ('.$error.') If this message appears repeatedly, please notify the administrator.');
if (empty($decoded->access_token)) {
if (is_file($aTokenFile)) {
$err = property_exists($decoded, 'error')? ' ' . $decoded->error : '';
$err .= property_exists($decoded, 'error_description')? ' ' . $decoded->error_description : '';
throw new \Exception($err? $err : elFinder::ERROR_REAUTH_REQUIRE);
'expires' => time() + $decoded->expires_in - 300,
'initialToken' => $initialToken,
$json = json_encode($token);
if (!empty($decoded->refresh_token)) {
if (empty($this->options['netkey']) && $aTokenFile) {
file_put_contents($aTokenFile, json_encode($token), LOCK_EX);
$this->options['accessToken'] = $json;
} else if (!empty($this->options['netkey'])) {
// OAuth2 refresh token can be used only once,
// so update it if it is the same as the token file
if ($aTokenFile && is_file($aTokenFile)) {
if ($_token = json_decode(file_get_contents($aTokenFile))) {
if ($_token->data->refresh_token === $refresh_token) {
file_put_contents($aTokenFile, $json, LOCK_EX);
$this->options['accessToken'] = $json;
elFinder::$instance->updateNetVolumeOption($this->options['netkey'], 'accessToken', $json);
$this->session->set('BoxTokens', $token);
throw new \Exception(ERROR_CREATING_TEMP_DIR);
* Creates a base cURL object which is compatible with the Box.com API.
* @param array $options cURL options
* @return resource A compatible cURL object
protected function _bd_prepareCurl($options = array())
CURLOPT_RETURNTRANSFER => true,
curl_setopt_array($curl, $options + $defaultOptions);
* Creates a base cURL object which is compatible with the Box.com API.
protected function _bd_fetch($url, $contents = false)
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
return $this->_bd_curlExec($curl, false);
$result = $this->_bd_curlExec($curl);
if (isset($result->entries)) {
$total = $result->total_count;
$offset = $result->offset;
$single = ($result->limit == 1) ? true : false;
if (!$single && $total > ($offset + $cnt)) {
$offset = $offset + $cnt;
if (strpos($url, 'offset=') === false) {
$url .= '&offset=' . $offset;
$url = preg_replace('/^(.+?offset=)\d+(.*)$/', '${1}' . $offset . '$2', $url);
$more = $this->_bd_fetch($url);
$res = array_merge($res, $more);
if (isset($result->type) && $result->type === 'error') {
* @param bool|string $decodeOrParent
protected function _bd_curlExec($curl, $decodeOrParent = true, $headers = array(), $postData = array())
$headers = array_merge(array(
'Authorization: Bearer ' . $this->token->data->access_token,
$result = elFinder::curlExec($curl, array(), $headers, $postData);
$decoded = json_decode($result);
if ($error = !empty($decoded->error_code)) {
$errmsg = $decoded->error_code;
if (!empty($decoded->message)) {
$errmsg .= ': ' . $decoded->message;
throw new \Exception($errmsg);
} else if ($error = !empty($decoded->error)) {
$errmsg = $decoded->error;
if (!empty($decoded->error_description)) {
$errmsg .= ': ' . $decoded->error_description;
throw new \Exception($errmsg);
if ($decodeOrParent && $decodeOrParent !== true) {
if (isset($decoded->entries)) {
$raws = $decoded->entries;
} elseif (isset($decoded->id)) {
foreach ($raws as $raw) {
$stat = $this->_bd_parseRaw($raw);
$itemPath = $this->_joinPath($decodeOrParent, $raw->id);
$this->updateCache($itemPath, $stat);
* Drive query and fetchAll.
* @param bool $fetch_self
protected function _bd_query($itemId, $fetch_self = false, $recursive = false)
$path = '/folders/' . $itemId . '?fields=' . self::FETCHFIELDS;
$path = '/folders/' . $itemId . '/items?limit=1000&fields=' . self::FETCHFIELDS;
$url = self::API_URL . $path;
foreach ($this->_bd_fetch($url) as $file) {
if ($file->type == 'folder') {
$result = array_merge($result, $this->_bd_query($file->id, $fetch_self = false, $recursive = true));
} elseif ($file->type == 'file') {
$result = $this->_bd_fetch($url);
if ($fetch_self && !$result) {
$path = '/files/' . $itemId . '?fields=' . self::FETCHFIELDS;
$url = self::API_URL . $path;