Removed Dropbox scripts from JCB, will ship with sermon distributor

This commit is contained in:
Llewellyn van der Merwe 2018-02-06 13:02:55 +02:00
parent 655bf3b0b9
commit c78ef21678
No known key found for this signature in database
GPG Key ID: CAD7B16D27AF28C5
5 changed files with 2 additions and 1433 deletions

View File

@ -132,7 +132,7 @@ Component Builder is mapped as a component in itself on my local development env
+ *License*: GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
+ *Line count*: **180952**
+ *Field count*: **1577**
+ *File count*: **1162**
+ *File count*: **1159**
+ *Folder count*: **186**
> This **component** was build with a Joomla [Automated Component Builder](http://joomlacomponentbuilder.com).

View File

@ -132,7 +132,7 @@ Component Builder is mapped as a component in itself on my local development env
+ *License*: GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
+ *Line count*: **180952**
+ *Field count*: **1577**
+ *File count*: **1162**
+ *File count*: **1159**
+ *Folder count*: **186**
> This **component** was build with a Joomla [Automated Component Builder](http://joomlacomponentbuilder.com).

View File

@ -1,171 +0,0 @@
<?php
/**
*
*@version 2.0.0 - September 03, 2014
*@package Component Builder
*@author Llewellyn van de Merwe <http://www.vdm.io>
*@copyright Copyright (C) 2014. All Rights Reserved
*@license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
*
**/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
?>
###BOM###
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla controllerform library
jimport('joomla.application.component.controller');
/**
* ###Component### Download Controller
*/
class ###Component###ControllerDownload extends JControllerLegacy
{
public function __construct($config)
{
parent::__construct($config);
// load the tasks
$this->registerTask('file', 'download');
}
public function download()
{
$jinput = JFactory::getApplication()->input;
// Check Token!
$token = JSession::getFormToken();
$call_token = $jinput->get('token', 0, 'ALNUM');
if($token == $call_token)
{
$task = $this->getTask();
switch($task)
{
case 'file':
$keys = ###Component###Helper::base64_urldecode($jinput->get('key', NULL, 'STRING'));
$enUrl = ###Component###Helper::base64_urldecode($jinput->get('link', NULL, 'STRING'));
$filename = $jinput->get('filename', NULL, 'CMD');
if((base64_encode(base64_decode($enUrl, true)) === $enUrl) && (base64_encode(base64_decode($keys, true)) === $keys) && $filename)
{
// we must first count this download
if (###Component###Helper::countDownload($keys,$filename))
{
// get Site name
$config = JFactory::getConfig();
$vendor = $config->get('sitename');
$name = ###Component###Helper::safeString($filename, 'Ww');
// Get local key
$localkey = ###Component###Helper::getLocalKey();
$opener = new FOFEncryptAes($localkey, 128);
$link = rtrim($opener->decryptString($enUrl), "\0");
$info = $this->getContentInfo($link);
// set headers
$app = JFactory::getApplication();
$app->setHeader('Accept-ranges', 'bytes', true);
$app->setHeader('Connection', 'keep-alive', true);
$app->setHeader('Content-Encoding', 'none', true);
$app->setHeader('Content-disposition', 'attachment; filename="'.$filename.'";', true);
if (isset($info['type']) && $info['type'])
{
$app->setHeader('Content-Type', $info['type'], true);
}
elseif (strpos($filename, '.mp3') !== false)
{
$app->setHeader('Content-Type', 'audio/mpeg', true);
}
else
{
$app->setHeader('Content-Type', 'application/octet-stream', true);
}
// important to have the file size.
if (isset($info['filesize']) && $info['filesize'])
{
$app->setHeader('Content-Length', (int) $info['filesize'], true);
$app->setHeader('Content-Size', (int) $info['filesize'], true);
}
$app->setHeader('Content-security-policy', 'referrer no-referrer', true);
$app->setHeader('Content-Name', '"'.$name.'"', true);
$app->setHeader('Content-Version', '1.0', true);
$app->setHeader('Content-Vendor', '"'.$vendor.'"', true);
$app->setHeader('Content-URL', '"'.JUri::getInstance().'"', true);
$app->setHeader('etag', md5($enUrl), true);
$app->setHeader('Pragma', 'public', true);
$app->setHeader('cache-control', 'max-age=0', true);
$app->setHeader('x-robots-tag', 'noindex, nofollow, noimageindex', true);
$app->setHeader('x-content-security-policy', 'referrer no-referrer', true);
$app->setHeader('x-webkit-csp', 'referrer no-referrer', true);
$app->setHeader('x-content-security-policy', 'referrer no-referrer', true);
// get the file
readfile($link);
$app->sendHeaders();
$app->close();
jexit();
}
}
break;
}
}
die('Restricted access');
}
protected function getContentInfo($url)
{
// we first try the curl option
if ($this->_isCurl())
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
curl_close($ch);
}
else
{
// then we try getheaders (this is slower)
stream_context_set_default( array('http' => array('method' => 'HEAD')));
$headers = get_headers($url);
if (###Component###Helper::checkArray($headers))
{
$data = implode("\n", $headers);
}
}
// get the Content Length
if (preg_match('/Content-Length: (\d+)/', $data, $matches))
{
// Contains file size in bytes
$found['filesize'] = (int) $matches[1];
}
// get the Content Type
if (preg_match_all('/Content-Type: (.+)/', $data, $matches))
{
foreach ($matches[1] as $match)
{
// not the html
if (strpos( $match, 'text/html') === false)
{
$found['type'] = $match;
break;
}
}
}
// return found values
if (isset($found) && ###Component###Helper::checkArray($found))
{
return $found;
}
return false;
}
protected function _isCurl()
{
return function_exists('curl_version');
}
}

View File

@ -1,818 +0,0 @@
<?php
/*----------------------------------------------------------------------------------| www.vdm.io |----/
Vast Development Method
/-------------------------------------------------------------------------------------------------------/
@version 2.0.3 - 27th January, 2018
@package Dropbox API 2
@subpackage dropbox.php
@author Llewellyn van der Merwe <http://www.vdm.io>
@copyright Copyright (C) 2015. All Rights Reserved
@license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
/------------------------------------------------------------------------------------------------------*/
// No direct access.
defined('_JEXEC') or die;
/**
* Dropbox class to get shared links
*/
class Dropbox
{
/**
* final url
*/
protected $url;
/**
* The array for the post url
*/
protected $postUrl = array(
"protocol" => "https://",
"suddomain" => "api.",
"domain" => "dropboxapi.com",
"path" => "/2/"
);
/**
* the verious pathes we need
*/
protected $domainpath = array(
"list_shared_links" => "sharing/list_shared_links",
"list_folder" => "files/list_folder",
"list_folder_continue" => "files/list_folder/continue",
"create_shared_link_with_settings" => "sharing/create_shared_link_with_settings",
"get_shared_link_metadata" => "sharing/get_shared_link_metadata",
"revoke" => "auth/token/revoke"
);
/**
* the target path to get
*/
protected $targetPath = false;
protected $targetPathOriginal = false;
/**
* oauth token
*/
protected $oauthToken = array();
protected $token = 0;
/**
* the verious pathes we need
*/
protected $permissionType;
/**
* The array of queries for creating shared links
*/
protected $createSharedLinks = array();
protected $createSharedLinks_ = array(); // retry array
/**
* The array of queries for getting shared links
*/
protected $getSharedLinks = array();
protected $getSharedLinks_ = array(); // retry array
/**
* the success switch
*/
protected $succes;
/**
* the type call
*/
protected $type;
/**
* the query for the call
*/
protected $query;
/**
* the query for the call
*/
protected $model;
/**
* the slow down timer
*/
protected $slowdown = 0;
/**
* the speed up switch
*/
protected $speedup = false;
/**
* the mediaData bucket
*/
public $mediaData = array();
/**
* the error messages
*/
public $error_summary = array();
/**
* force the update to reset
**/
public $forceReset = false;
/**
* Constructor
*/
public function __construct(JModelLegacy $model, $buildType)
{
// set the first call
$this->firstCall = 'get'; // TODO (we may what to make this dynamic)
// set the second call
$this->secondCall = 'create'; // TODO (we may what to make this dynamic)
// set the url at this point for now
$this->url = $this->postUrl["protocol"].$this->postUrl["suddomain"].$this->postUrl["domain"].$this->postUrl["path"];
// set the local model
$this->model = $model;
// set the build type
$this->build = (int) $buildType;
}
/**
* getFiles
*
* =============
* $details
* =============
* sourceID
* dropboxOption
* dropboxTarget
* addTypes
*
*/
public function getFiles($token, $permissiontype, $details = array())
{
// we need more then the normal time to run this script 5 minutes at least.
ini_set('max_execution_time', 500);
// little tweak for big folders (use multy tokens)
if (strpos($token, '____') !== false)
{
$this->oauthToken = array_filter((array) explode('____', $token),
function ($string) {
return $this->checkString($string);
});
}
else
{
// set the oauth toke
$this->oauthToken = array($token);
}
// set the permission type
$this->permissionType = $permissiontype;
// set the details
if ($this->checkArray($details))
{
foreach ($details as $detail => $value)
{
$this->$detail = $value;
}
}
// set the curent folder path
if (!$this->setFolderPath())
{
return false;
}
// start the main factory that calles for the folder data
$this->query = array("path" => $this->targetPath, "recursive" => true, "include_media_info" => true);
$this->type = 'list_folder';
if ($this->makeCall())
{
if ($this->_isCurl())
{
// run the share link builder
return $this->makeMultiExecCalls();
}
return true;
}
return false;
}
protected function getToken()
{
$key = $this->token;
if (isset($this->oauthToken[$key]))
{
// update key
$this->token++;
return $this->oauthToken[$key];
}
// reset key
$this->token = 1;
// return first token
return $this->oauthToken[0];
}
protected function makeMultiExecCalls()
{
$this->succesCall = true;
// make the fist call
$this->multiSharedLinks($this->firstCall);
// make the second call
$this->multiSharedLinks($this->secondCall);
// slow down if needed
$this->speedup = false;
// for safety
if (($this->checkArray($this->createSharedLinks) || $this->checkArray($this->createSharedLinks_) ||
$this->checkArray($this->getSharedLinks) || $this->checkArray($this->getSharedLinks_)) &&
$this->succesCall)
{
return $this->makeMultiExecCalls();
}
// all done
return $this->succesCall;
}
protected function multiSharedLinks($type)
{
switch ($type)
{
case "create":
// great links if not made already
if ($this->checkArray($this->createSharedLinks) || $this->checkArray($this->createSharedLinks_))
{
$url = $this->url.$this->domainpath['create_shared_link_with_settings'];
$this->type = 'create_shared_link_with_settings';
// build return function
$storeSharedLink = function ($data, $target) {
// check if we are going to fast
if (isset($data->error_summary) && strpos($data->error_summary, 'too_many_requests') !== false)
{
$this->slowDown($data);
// this call was droped, so we must try again
$this->createSharedLinks_[] = json_encode(array("path" => $target, "settings" => array("requested_visibility" => "public")));
}
// check if link already made
elseif (isset($data->error_summary) && strpos($data->error_summary, 'shared_link_already_exists') !== false)
{
$this->getSharedLinks[] = json_encode(array("path" => $target));
}
else
{
$this->curlCallResult($data);
}
};
// run call
if ($this->checkArray($this->createSharedLinks))
{
$this->multiCall($url, 'createSharedLinks', $storeSharedLink);
}
// also run the retries
if ($this->checkArray($this->createSharedLinks_))
{
$this->multiCall($url, 'createSharedLinks_', $storeSharedLink);
}
}
break;
case "get":
// now get the already made links
if ($this->checkArray($this->getSharedLinks) || $this->checkArray($this->getSharedLinks_))
{
$url = $this->url.$this->domainpath['list_shared_links'];
$this->type = 'list_shared_links';
// build return function
$storeSharedLink = function ($data, $target) {
// check if link not made
if (isset($data->error_summary) && strpos($data->error_summary, 'too_many_requests') !== false)
{
$this->slowDown($data);
// this call was droped, so we must try again
$this->getSharedLinks_[] = json_encode(array("path" => $target));
}
elseif (isset($data->error_summary))
{
$this->createSharedLinks[] = json_encode(array("path" => $target, "settings" => array("requested_visibility" => "public")));
}
else
{
$this->curlCallResult($data);
}
};
// run call
if ($this->checkArray($this->getSharedLinks))
{
$this->multiCall($url, 'getSharedLinks', $storeSharedLink);
}
// also run the retries
if ($this->checkArray($this->getSharedLinks_))
{
$this->multiCall($url, 'getSharedLinks_', $storeSharedLink);
}
}
break;
}
}
protected function multiCall(&$url, $type, &$storeSharedLink)
{
$timer = 1;
$options = array();
// set the options array and make the calls every 550
foreach ($this->{$type} as $query)
{
$options[] = array(CURLOPT_HTTPHEADER => array('Authorization: Bearer ' . $this->getToken(), 'Content-Type: application/json'), CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $query); $timer++;
// check timer
if ($timer >= 550)
{
// run multi curl
$this->curlMultiExec($url, $options, $storeSharedLink);
// reset
$timer = 1;
$options = array();
}
}
// make sure all was done
if ($timer > 1 && $this->checkArray($options))
{
// run multi curl
$this->curlMultiExec($url, $options, $storeSharedLink);
}
// reset the values
$this->{$type} = array();
// check if we have errors
if ($this->checkArray($this->error_summary))
{
$this->succesCall = false;
}
}
public function slowDown($data)
{
if (!$this->speedup)
{
// set default
$this->slowdown = 300000000;
// can we set it dynamicly
if (isset($data->error) && isset($data->error->retry_after))
{
// convert retry_after minutes to microseconds
$this->slowdown = (int) bcmul($data->error->retry_after, 1000000);
}
}
}
public function revokeToken($token = null)
{
if ($token)
{
// set the oauth toke
$this->oauthToken[] = $token;
}
// set the call to revoke the token
$this->query = 'null';
$this->type = 'revoke';
// remove all tokens
$removed = true;
if ($this->checkArray($this->oauthToken))
{
foreach($this->oauthToken as $token)
{
if (!$this->makeCall())
{
$removed = false;
}
}
return $removed;
}
return false;
}
protected function setFolderPath()
{
if ('full' == $this->permissionType && isset($this->dropboxOption) && isset($this->dropboxTarget) && $this->checkString($this->dropboxTarget))
{
if (2 == $this->dropboxOption)
{
// simply set the path
$this->targetPath = '/'.trim(strtolower($this->dropboxTarget), '/');
return true;
}
elseif (1 == $this->dropboxOption)
{
// make a call to get the path
$this->query = array("url" => $this->dropboxTarget);
$this->type = 'get_shared_link_metadata';
if ($this->makeCall())
{
return true;
}
}
}
elseif ('app' == $this->permissionType)
{
$this->targetPath = "";
return true;
}
return false;
}
protected function makeCall()
{
if ($this->_isCurl())
{
return $this->makeCurlCall();
}
else
{
return $this->makeGetCall();
}
}
protected function makeGetCall()
{
$options = array(
'http' => array(
'header' => "Content-Type: application/json\r\n".
"Authorization: Bearer ".$this->getToken(),
'method' => "POST"
),
);
if ($this->checkArray($this->query))
{
$this->query = json_encode($this->query);
}
// add the query
if ($this->checkString($this->query))
{
$options['http']['content'] = $this->query;
}
$context = stream_context_create($options);
$response = file_get_contents($this->url.$this->domainpath[$this->type], false, $context);
// store the result
return $this->getCallResult($response);
}
protected function getCallResult($response)
{
if ($response === FALSE)
{
$this->error_summary[] = $this->type.'_error';
return false;
}
// store the result
return $this->setTheResult(json_decode($response));
}
protected function makeCurlCall()
{
// do not run creat shared link this way
$headers = array('Authorization: Bearer '. $this->getToken(),
'Content-Type: application/json'
);
$ch = curl_init($this->url.$this->domainpath[$this->type]);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// check if query is set
if ($this->checkArray($this->query))
{
$this->query = json_encode($this->query);
}
// add the query
if ($this->checkString($this->query))
{
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->query);
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_VERBOSE, 1); // debug
$response = curl_exec($ch);
curl_close($ch);
// store the result
return $this->curlCallResult($response);
}
public function curlCallResult($response)
{
if ($this->checkJson($response))
{
$response = json_decode($response);
}
// store the result
return $this->setTheResult($response);
}
protected function setTheResult($data)
{
// if there was an error stop!!!
if (isset($data->error_summary))
{
$this->error_summary[] = $data->error_summary;
$this->forceReset = true;
return false;
}
// deal with each type
switch ($this->type)
{
case "list_folder":
case "list_folder_continue":
if (isset($data->entries) && $this->checkArray($data->entries))
{
if ($this->storeFiles($data->entries))
{
// run the continue if needed
if (isset($data->has_more) && $data->has_more && isset($data->cursor))
{
// start the main factory that calles for the folder data
$this->query = array("cursor" => $data->cursor);
$this->type = 'list_folder_continue';
if ($this->makeCall())
{
return true;
}
}
return true;
}
}
$this->error_summary[] = $this->type.'_error';
break;
case "list_shared_links":
if (isset($data->links) && $this->checkArray($data->links))
{
foreach ($data->links as $link)
{
if (!$this->storeSharedLink($link))
{
// we could not stored the link
return false;
}
}
return true;
}
$this->error_summary[] = $this->type.'_error';
break;
case "create_shared_link_with_settings":
if ($this->storeSharedLink($data))
{
// we stored the link
return true;
}
$this->error_summary[] = $this->type.'_error';
break;
case "get_shared_link_metadata":
if (isset($data->path_lower))
{
$this->targetPath = $data->path_lower;
return true;
}
$this->error_summary[] = $this->type.'_error';
break;
case "revoke":
if (is_null($data))
{
return true;
}
$this->error_summary[] = $this->type.'_error';
break;
}
$this->forceReset = true;
return false;
}
protected function storeSharedLink($data)
{
// we need to store the url to DB
if (isset($data->url) && isset($data->name) && isset($data->size) && (isset($data->path) || isset($data->path_lower)))
{
$path = (isset($data->path)) ? $data->path : $data->path_lower;
$localListing = array();
$localListing['id'] = 0;
$localListing['name'] = $data->name;
$localListing['size'] = $data->size;
$localListing['key'] = $this->fixPath($path);
$localListing['url'] = str_replace('?dl=0','?dl=1',$data->url);
$localListing['build'] = $this->build;
$localListing['external_source'] = (int) $this->sourceID;
// check if item already set
if ($id = $this->model->searchForId($localListing['key']))
{
// update item
$localListing['id'] = $id;
}
return $this->model->save($localListing);
}
return false;
}
protected function storeFiles($entries)
{
foreach ($entries as $item)
{
if (isset($item->{'.tag'}) && 'file' == $item->{'.tag'} && isset($item->name))
{
$addLink = false;
// remove if not related to type
if (isset($this->addTypes) && $this->checkArray($this->addTypes))
{
foreach ($this->addTypes as $add)
{
if (strpos($item->name,$add) !== false)
{
$addLink = true;
}
}
}
if ($addLink && isset($item->path_lower))
{
// set based on first call
if ('get' === $this->firstCall)
{
// first check if shared link exist
$this->query = array("path" => $item->path_lower);
// set the type of call
$this->type = 'list_shared_links';
}
else
{
// first check if shared link exist
$this->query = array("path" => $item->path_lower, "settings" => array("requested_visibility" => "public"));
// set the type of call
$this->type = 'create_shared_link_with_settings';
}
// if we have curl the use multi curl execution
if ($this->_isCurl())
{
// set query to worker
$this->{$this->firstCall."SharedLinks"}[] = json_encode($this->query);
}
elseif (!$this->makeCall())
{
return false;
}
}
}
}
return true;
}
protected function fixPath($path)
{
if ($this->checkString($this->targetPath))
{
$path = str_replace($this->targetPath, 'VDM_pLeK_h0uEr', $path);
}
else
{
$path = 'VDM_pLeK_h0uEr'.$path;
}
return $path;
}
protected function checkObject($object)
{
if (isset($object) && is_object($object) && count($object) > 0)
{
return true;
}
return false;
}
protected function checkArray($array)
{
if (isset($array) && is_array($array) && count($array) > 0)
{
return true;
}
return false;
}
protected function checkJson($string)
{
if ($this->checkString($string))
{
json_decode($string);
return (json_last_error() === JSON_ERROR_NONE);
}
return false;
}
protected function checkString($string)
{
if (isset($string) && is_string($string) && strlen($string) > 0)
{
return true;
}
return false;
}
protected function _isCurl()
{
return function_exists('curl_version');
}
protected function curlMultiExec(&$url, &$_options, $callback = null)
{
if ($this->checkString($url))
{
// check if we should slow down
if ($this->slowdown > 0)
{
usleep($this->slowdown);
// reset the trafic speed
$this->slowdown = 0;
$this->speedup = true; // we should only sleep once per/bunch
}
// make sure the thread size isn't greater than the # of _options
$threadSize = 50;
$threadSize = (sizeof($_options) < $threadSize) ? sizeof($_options) : $threadSize;
// set the options
$options = array();
$options[CURLOPT_URL] = $url;
$options[CURLOPT_USERAGENT] = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12';
$options[CURLOPT_RETURNTRANSFER] = TRUE;
$options[CURLOPT_SSL_VERIFYPEER] = FALSE;
// start multi threading :)
$handle = curl_multi_init();
// start the first batch of requests
for ($i = 0; $i < $threadSize; $i++)
{
if (isset($_options[$i]))
{
$ch = curl_init();
foreach ($_options[$i] as $curlopt => $string)
{
$options[$curlopt] = $string;
}
curl_setopt_array($ch, $options);
curl_multi_add_handle($handle, $ch);
}
}
// we wait for all the calls to finish (should not take long)
do {
while(($execrun = curl_multi_exec($handle, $working)) == CURLM_CALL_MULTI_PERFORM);
if($execrun != CURLM_OK)
break;
// a request was just completed -- find out which one
while($done = curl_multi_info_read($handle))
{
if (is_callable($callback))
{
// $info = curl_getinfo($done['handle']);
// request successful. process output using the callback function.
$output = curl_multi_getcontent($done['handle']);
if ($this->checkJson($output) && isset($_options[$i]))
{
$callback(json_decode($output), json_decode(end($_options[$i]))->path);
}
}
// check if we should slow down
if ($this->slowdown > 0)
{
usleep($this->slowdown);
// reset the trafic speed
$this->slowdown = 0;
$this->speedup = true; // we should only sleep once per/bunch
}
// next key
$key = $i + 1;
if(isset($_options[$key]))
{
// start a new request (it's important to do this before removing the old one)
$ch = curl_init(); $i++;
// add options
foreach ($_options[$key] as $curlopt => $string)
{
$options[$curlopt] = $string;
}
curl_setopt_array($ch, $options);
curl_multi_add_handle($handle, $ch);
// remove options again
foreach ($_options[$key] as $curlopt => $string)
{
unset($options[$curlopt]);
}
}
// remove the curl handle that just completed
curl_multi_remove_handle($handle, $done['handle']);
}
// stop wasting CPU cycles and rest for a couple ms
usleep(10000);
} while ($working);
// close the curl multi thread
curl_multi_close($handle);
// okay done
return true;
}
return false;
}
}

View File

@ -1,442 +0,0 @@
<?php
/**
*
*@version 2.0.0 - September 03, 2014
*@package Component Builder
*@author Llewellyn van de Merwe <http://www.vdm.io>
*@copyright Copyright (C) 2014. All Rights Reserved
*@license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
*
**/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
?>
###BOM###
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
/**
* Dropbox updater component helper
*/
class Dropboxupdater
{
/**
* update flag (if false update will not happen)
**/
protected $okay = true;
/**
* update flag (if false update will not happen)
**/
protected $data = null;
/**
* the file Key
**/
protected $fileKey;
/**
* allow a forced update
**/
protected $forceUpdate;
/**
* Todays date-time
**/
protected $today;
/**
* Next updat date-time
**/
protected $next;
/**
* update method
**/
protected $updateMethod;
/**
* update targets
**/
protected $updateTarget;
/**
* info related to this update
**/
protected $updateInfo;
protected $infoFilePath;
/**
* Main dropbox class
**/
protected $dropbox;
/**
* component parameters
**/
protected $app_params;
/**
* the errors
**/
protected $errors = array();
/**
* everything we want done when initialized
**/
public function __construct()
{
// get params
$this->app_params = JComponentHelper::getParams('com_###component###');
}
/**
* get the logged errors array
**/
public function getErrors()
{
return $this->errors;
}
/**
* set the error to the log
**/
protected function setErrors($error)
{
if (###Component###Helper::checkString($error))
{
$this->errors[] = $error;
}
elseif (###Component###Helper::checkArray($error))
{
foreach($error as $log)
{
if (###Component###Helper::checkString($log))
{
$this->errors[] = $log;
}
}
}
}
/**
* update method
**/
public function update($id, $target, $type = false, $forceUpdate = false, $sleutel = null)
{
if ($type)
{
// start fresh
$this->okay = true;
$this->data = null;
// is this a forced run
$this->forceUpdate = $forceUpdate;
// the file key
$this->fileKey = ###Component###Helper::safeString($id.$target.$type);
// set the type of this listing
$this->type = $type;
// get the external source data being updated
$this->setExternalSourceData($id);
// load the token if manualy set
if ($sleutel)
{
$this->setExternalSourceData($id, array('oauthtoken' => $sleutel));
}
// what update method is set
$this->setUpdateMethod();
// set the update links
$this->setUpdateTarget($target);
// set needed dates
if ($this->okay)
{
$this->setDates();
}
// get info data or set if not found
if ($this->okay)
{
$this->setUpdateInfoData();
}
// check if update should run now
if ($this->okay)
{
$this->checkUpdateStatus();
}
// before update save update info incase class is called again
if($this->okay)
{
if ($this->updateInfo->updatenow)
{
// turn update to active
$this->updateInfo->updatenow = false;
$this->updateInfo->updateactive = true;
// now save the date
$this->okay = $this->saveUpdateInfo();
}
else
{
$this->okay = false;
}
}
// run the update if all is okay
if ($this->okay)
{
// set the config
$this->setDetailsConfig();
// load the file
JLoader::import('dropbox', JPATH_COMPONENT_SITE.'/helpers');
$build = 1;
if ('auto' == $this->type)
{
$build = 2;
}
// load the dropbox class
$this->dropbox = new Dropbox(###Component###Helper::getModel('local_listing', JPATH_COMPONENT_ADMINISTRATOR), $build);
// okay now update
$this->okay = $this->doUpdate();
}
// always reset if all okay
return $this->resetUpdate();
}
$this->setErrors('The update type is unknown.');
return false;
}
/**
* set the exsternal source data
*/
protected function setExternalSourceData($id, $data = array())
{
// get the data if not set
if (!$this->data || !###Component###Helper::checkObject($this->data))
{
// load model to get the data
$model = ###Component###Helper::getModel('external_source', JPATH_COMPONENT_ADMINISTRATOR);
$this->data = $model->getItem($id);
}
// if new data is set load it
if (###Component###Helper::checkArray($data))
{
foreach ($data as $key => $value)
{
$this->data->$key = $value;
}
}
}
/**
* set update mehtod
**/
protected function setUpdateMethod()
{
if ($this->forceUpdate)
{
// this is a manual method
$this->updateMethod = 'manual';
}
elseif (2 == $this->data->update_method)
{
// this it an auto mehtod
$this->updateMethod = 'auto';
}
else
{
$this->okay = false;
}
}
/**
* set update target
**/
protected function setUpdateTarget($nr)
{
// get target based on type and position
if ('full' == $this->data->permissiontype && $nr > 0)
{
$position = $nr - 1;
if (1 == $this->data->dropboxoptions && ###Component###Helper::checkJson($this->data->sharedurl))
{
$targets = json_decode($this->data->sharedurl)->tsharedurl;
}
elseif (2 == $this->data->dropboxoptions && ###Component###Helper::checkJson($this->data->folder))
{
$targets = json_decode($this->data->folder)->tfolder;
}
// check if we found any
if (!isset($targets[$position]) || !###Component###Helper::checkString($targets[$position]))
{
$this->setErrors('The target Shared-url or Folder is not set.');
$this->okay = false;
}
else
{
$this->updateTarget = $targets[$position];
}
}
else
{
$this->updateTarget = '';
}
}
/**
* set the configeration for exsternal source class
**/
protected function setDetailsConfig()
{
// reset config
$this->detailsConfig = array();
// the source ID
$this->detailsConfig['sourceID'] = $this->data->id;
// get the legal files set
$this->detailsConfig['addTypes'] = $this->data->filetypes;
// set other config settings
$this->detailsConfig['dropboxOption'] = $this->data->dropboxoptions;
// set dropbox target
$this->detailsConfig['dropboxTarget'] = $this->updateTarget;
}
/**
* set next update time
**/
protected function setDates()
{
// set todays date/time
$this->today = time();
// set the next update date/time
if ('manual' == $this->updateMethod)
{
// set the date to two days ago to ensure the update runs now
$this->next = strtotime("-2 days");
}
else
{
// based on the auto time we will set the next update date/time
$timer = $this->data->update_timer;
if ($timer != 0)
{
// Get Next Update Time
$this->next = strtotime('+'.$timer.' minutes', $this->today);
}
// if timer is 0 we should not update
else
{
$this->setErrors('The timer is not setup correctly.');
$this->okay = false;
}
}
}
/**
* set update info data
**/
protected function setUpdateInfoData()
{
// set the info file name
$fileName = md5($this->fileKey.'info');
// set file path
$this->infoFilePath = JPATH_COMPONENT_SITE.'/helpers/'.$fileName.'.json';
if (($json = @file_get_contents($this->infoFilePath)) !== FALSE)
{
$this->updateInfo = json_decode($json);
}
else
{
$this->updateInfo = new stdClass;
$this->updateInfo->nextupdate = 0;
$this->updateInfo->updateactive = false;
$this->updateInfo->updatenow = false;
}
}
/**
* check update status
**/
protected function checkUpdateStatus()
{
// check if there is already an update running
if ($this->updateInfo->updateactive)
{
$this->okay = false;
$this->setErrors('There is an update already running.');
}
// check if the time has come to do the next update
elseif (('auto' == $this->updateMethod) && ($this->updateInfo->nextupdate > $this->today))
{
$this->okay = false;
$this->setErrors('It is not yet time to run this update.');
}
else
{
$this->updateInfo->updatenow = true;
}
}
/**
* save the update info
**/
protected function saveUpdateInfo()
{
return $this->saveJson(json_encode($this->updateInfo),$this->infoFilePath);
}
/**
* update the local listing
**/
protected function doUpdate()
{
// we need more then the normal time to run this script 5 minutes at least.
ini_set('max_execution_time', $this->app_params->get('max_execution_time', 500));
// get data of all the shared links of all target items
if (!$this->dropbox->getFiles($this->data->oauthtoken, $this->data->permissiontype, $this->detailsConfig))
{
$this->setErrors($this->dropbox->error_summary);
return false;
}
// if this is a manual update, then revoke the token
if ($this->forceUpdate)
{
$this->dropbox->revokeToken();
}
return true;
}
public function resetUpdate()
{
if ($this->okay || (isset($this->dropbox->forceReset) && $this->dropbox->forceReset))
{
// make sure the update reset
$this->updateInfo->nextupdate = $this->next;
$this->updateInfo->updateactive = false;
$this->updateInfo->updatenow = false;
// store final update
$this->saveUpdateInfo();
}
return $this->okay;
}
protected function saveJson($data,$filename)
{
if (###Component###Helper::checkString($data))
{
$fp = fopen($filename, 'w');
fwrite($fp, $data);
fclose($fp);
return true;
}
return false;
}
}