Commits

beholder committed a3d85d2

Initial commit.

Comments (0)

Files changed (37)

+deny from all
+debug = 0
+mail = YOUR@MAIL
+db_file = app/data.csv
+
+[pocket]
+
+login = LOGIN
+password = PASSWORD
+api_key = POCKET_KEY
+parse_step = 3
+tags =
+
+[dropbox]
+
+consumer_key = KEY
+consumer_secret = SECRET
+token = TOKEN
+token_secret = TOKEN_SECRET
+sandbox = true
+<?php
+
+require_once 'vendors/Dropbox/autoload.php';
+
+class DropboxClient {
+  var $config;
+  var $sandbox;
+  var $oauth;
+  var $authenticated = false;
+  var $dropbox;
+
+  function __construct($config) {
+    $this->config = $config;
+    $this->sandbox = $config['sandbox'] ? 'sandbox' : 'dropbox';
+
+    if (!$this->checkAuth()) return false;
+
+    $this->dropbox = new Dropbox_API($this->oauth);
+  }
+
+  /**
+   * Return basic info about Dropbox account.
+   * @return array Info array
+   */
+  public function getInfo() {
+    if (!$this->authenticated) return false;
+
+    return $this->dropbox->getAccountInfo();
+  }
+
+  /**
+   * Upload file to Dropbox.
+   * @param  string $filename Filename
+   * @return boolean
+   */
+  public function uploadFile($filename) {
+    if (!$this->authenticated) return false;
+
+    return $this->dropbox->putFile(basename($filename), $filename, $this->sandbox);
+  }
+
+  /**
+   * Delete file in Dropbox.
+   * @param  string $filename Filename
+   * @return boolean
+   */
+  public function deleteFile($filename) {
+    if (!$this->authenticated) return false;
+
+    return $this->dropbox->delete($filename, $this->sandbox);
+  }
+
+  /**
+   * Get file list from given directory.
+   * @param  string $path Path to directory or empty for root.
+   * @return array        Array of files and folders.
+   */
+  public function getFilesList($path = '') {
+    if (!$this->authenticated) return false;
+
+    if (!$ret = $this->dropbox->getMetaData($path, true, null, null, $this->sandbox)) return false;
+    return $ret['contents'];
+  }
+
+  /**
+   * Checks if current app is verified in Dropbox account.
+   * @return boolean True if verified and calls showAuthSteps() if otherwise
+   */
+  private function checkAuth() {
+    $this->oauth = new Dropbox_OAuth_Curl($this->config['consumer_key'], $this->config['consumer_secret']);
+    // if app is verified
+    if (!empty($this->config['token']) && !empty($this->config['token_secret'])) {
+      $oauth_tokens = array(
+        'token' => $this->config['token'],
+        'token_secret' => $this->config['token_secret'],
+      );
+      $this->oauth->setToken($oauth_tokens);
+      $this->authenticated = true;
+    }
+    else {
+      return $this->showAuthSteps();
+    }
+    return true;
+  }
+
+  /**
+   * Shows app verification steps for get OAuth tokens.
+   */
+  private function showAuthSteps() {
+    session_start();
+    header('Content-Type: text/plain'); // for better readability
+
+    $state = (isset($_SESSION['state'])) ? $_SESSION['state'] : 1;
+    switch ($state) {
+      case 1: {
+        echo "Step 1: Acquire request tokens\n";
+        $tokens = $this->oauth->getRequestToken();
+        print_r($tokens);
+        // Note that if you want the user to automatically redirect back, you can
+        // add the 'callback' argument to getAuthorizeUrl.
+        echo "Step 2: You must now redirect the user to:\n";
+        echo $this->oauth->getAuthorizeUrl() . "\n";
+        $_SESSION['state'] = 2;
+        $_SESSION['oauth_tokens'] = $tokens;
+        die();
+        break;
+      }
+      case 2: {
+        echo "Step 3: Acquiring access tokens\n";
+        $this->oauth->setToken($_SESSION['oauth_tokens']);
+        $tokens = $this->oauth->getAccessToken();
+        print_r($tokens);
+        $_SESSION['state'] = 3;
+        $_SESSION['oauth_tokens'] = $tokens;
+        // There is no break here, intentional
+      }
+      case 3: {
+        echo "The user is authenticated\n";
+        echo "Save oauth tokens to config.ini file\n";
+        print_r($_SESSION['oauth_tokens']);
+        $this->oauth->setToken($_SESSION['oauth_tokens']);
+        break;
+      }
+    }
+    return true;
+  }
+}
+<?php
+
+require_once 'vendors/epub/EPub.php';
+
+class EpubGenerator {
+  public $header = "<?xml version='1.0' encoding='utf-8'?><!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.1//EN' 'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'><html xmlns='http://www.w3.org/1999/xhtml'><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><title>Test Book</title></head><body>";
+  public $footer = "</body></html>";
+  public $saveDir = 'tmp';
+
+  protected $book;
+
+  public function generate($item) {
+    if (empty($item->article)) return;
+
+    $article = $item->article;
+    $this->book = new EPub();
+
+    $this->book->setTitle($this->escape($article->title));
+    $this->book->setIdentifier("POCKET:". $article->resolved_id, EPub::IDENTIFIER_URI);
+    $this->book->setDescription($this->escape($article->excerpt));
+    $this->book->setAuthor($article->host, $article->host);
+    $this->book->setSourceURL($article->resolvedUrl);
+    $this->book->setDate(time());
+
+    $css = 'blockquote{font-style:italic}code{font-family:use-lang-def;font-size:0.81em;margin:0.7em 0}';
+    $this->book->addCSSFile("styles.css", "css1", $css);
+    //$this->book->setCoverImage("Cover.jpg", file_get_contents("misc/pocket-cover.png"), "image/png");
+
+    $content = $article->article;
+    // content images
+    $article_images = array();
+    if (!empty($article->images)) {
+      foreach ((array)$article->images as $img) {
+        $img_info = pathinfo($img->src);
+        $img_name = 'tmp/img_'.$img->image_id .'.'. $img_info['extension'];
+        if (file_put_contents($img_name, file_get_contents($img->src))) {
+          if ($this->checkImageSize($img_name)) {
+            $article_images[$img->image_id] = $img_name;
+          } else {
+            unlink($img_name);
+          }
+        }
+      }
+      $html = str_get_dom($content);
+      foreach ($html->select('div.RIL_IMG') as $element) {
+        $img_id = str_replace('RIL_IMG_', '', $element->getAttribute('id'));
+        if (!empty($article_images[$img_id])) {
+          $element->setInnerText('<img src="'. $article_images[$img_id] .'" alt="" />');
+        }
+      }
+      $content = $html;
+    }
+
+    $text = $this->header .'<h1>'. $article->title .'</h1>'. $content .'<p><small><em>Original</em>: <a href="'. $this->escape($article->resolvedUrl) .'">'. $this->escape($article->resolvedUrl) .'<a></small></p>'. $this->footer;
+    $this->book->addChapter($article->title, "Content.html", $text, false, EPub::EXTERNAL_REF_ADD, 'pocketbox');
+
+    $this->book->finalize();
+
+    $filename = $this->safeName($article->resolved_id .'-'. $article->title);
+    $result = $this->book->saveBook($filename, $this->saveDir);
+
+    // clean old images
+    foreach ($article_images as $img) {
+      unlink($img);
+    }
+
+    return $result ? $this->saveDir .'/'. $filename . '.epub' : false;
+  }
+
+  /**
+   * Check and resize image if it's too big.
+   * Work with ImageMagick for better memory usage (GD use much more).
+   * @param  string $source Path to image file
+   * @return boolean
+   */
+  private function checkImageSize($source) {
+    list($width, $height, $type) = getimagesize($source);
+    if ($width > 1200 || $height > 1200) {
+      if (extension_loaded('imagick')) {
+        $image = new Imagick($source);
+        $maxwidth = $this->book->maxImageWidth;
+        $maxheight = $this->book->maxImageHeight;
+        if ($width > $height) {
+          $ret = $image->scaleImage($maxwidth, 0);
+        } else {
+          $ret = $image->scaleImage(0, $maxheight);
+        }
+        if ($ret) {
+          $ret = $image->writeImage();
+          $image->clear();
+          $image->destroy();
+        }
+        return $ret;
+      } else {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  private function escape($val) {
+    return htmlspecialchars($val, ENT_QUOTES);
+  }
+
+  private function translit($string) {
+    $converter = array(
+      'а' => 'a',   'б' => 'b',   'в' => 'v',
+      'г' => 'g',   'д' => 'd',   'е' => 'e',
+      'ё' => 'e',   'ж' => 'zh',  'з' => 'z',
+      'и' => 'i',   'й' => 'y',   'к' => 'k',
+      'л' => 'l',   'м' => 'm',   'н' => 'n',
+      'о' => 'o',   'п' => 'p',   'р' => 'r',
+      'с' => 's',   'т' => 't',   'у' => 'u',
+      'ф' => 'f',   'х' => 'h',   'ц' => 'c',
+      'ч' => 'ch',  'ш' => 'sh',  'щ' => 'sch',
+      'ь' => '\'',  'ы' => 'y',   'ъ' => '\'',
+      'э' => 'e',   'ю' => 'yu',  'я' => 'ya',
+
+      'А' => 'A',   'Б' => 'B',   'В' => 'V',
+      'Г' => 'G',   'Д' => 'D',   'Е' => 'E',
+      'Ё' => 'E',   'Ж' => 'Zh',  'З' => 'Z',
+      'И' => 'I',   'Й' => 'Y',   'К' => 'K',
+      'Л' => 'L',   'М' => 'M',   'Н' => 'N',
+      'О' => 'O',   'П' => 'P',   'Р' => 'R',
+      'С' => 'S',   'Т' => 'T',   'У' => 'U',
+      'Ф' => 'F',   'Х' => 'H',   'Ц' => 'C',
+      'Ч' => 'Ch',  'Ш' => 'Sh',  'Щ' => 'Sch',
+      'Ь' => '\'',  'Ы' => 'Y',   'Ъ' => '\'',
+      'Э' => 'E',   'Ю' => 'Yu',  'Я' => 'Ya',
+    );
+    return strtr($string, $converter);
+  }
+
+  public function safeName($fileName) {
+    $fileName = $this->translit($fileName);
+    $forbidden_character = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}");
+    $fileName = str_replace($forbidden_character, '', $fileName);
+    $fileName = mb_strtolower($fileName, 'utf-8');
+    $fileName = preg_replace('/[\s]+/', '-', $fileName);
+    $fileName = preg_replace('/[^-a-z0-9_]+/u', '', $fileName);
+    $fileName = preg_replace('/-+/', '-', $fileName);
+    $fileName = trim($fileName, '.-_');
+    return $fileName;
+  }
+}
+<?php
+
+/**
+ * Based on https://github.com/kiranruth/Read-it-later-list-library
+ * but modified for new Pocket API to retrieve single articles.
+ */
+
+class PocketAPI {
+
+    public $url = 'https://readitlaterlist.com/v2/';
+    public $login_page = 'http://getpocket.com/l/';
+    public $login_action = 'http://getpocket.com/login_process/';
+
+    // get ur key from http://readitlaterlist.com/api/signup/
+    public $api_key  = '';
+    public $username = '';
+    public $password = '';
+
+    private $settings = array();
+    private $cookies = 'app/cookies.txt';
+
+    public function PocketAPI($username, $password, $settings) {
+      $this->settings = $settings;
+      $this->api_key = $this->settings['api_key'];
+      try {
+        if ($username && $password) {
+          $this->username = $username;
+          $this->password = $password;
+        } else {
+          throw new Exception("Please pass username and password");
+        }
+        return $this->authenticate();
+      }
+      catch(Exception $e) {
+        echo $e->getMessage();
+        return false;
+      }
+    }
+
+    public function authenticate() {
+      // API auth
+      $data = "username=". $this->username .
+              "&password=". $this->password .
+              "&apikey=". $this->api_key;
+      if (!$this->serverCall('auth', $data)) {
+        throw new Exception("Error while authorize with API key.");
+      }
+
+      // try to get session cookies
+      if (!$this->checkCookies()) {
+        throw new Exception("Error while grabbing session cookies.");
+      }
+      return true;
+    }
+
+    private function checkCookies() {
+      if (is_file($this->cookies)) {
+        $file = file($this->cookies);
+        foreach ($file as $line) {
+          $data = explode("\t", $line);
+          if (!empty($data[5]) && $data[5] == 'sess_user_id') {
+            return (time() >= $data[4]) ? $this->grabCookies() : true;
+          }
+        }
+      }
+      else {
+        return $this->grabCookies();
+      }
+    }
+
+    private function grabCookies() {
+      $ch = curl_init();
+
+      // get login page and form fields
+      curl_setopt($ch, CURLOPT_URL, $this->login_page);
+      curl_setopt($ch, CURLOPT_HEADER, false);
+      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+      curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookies);
+      $response = curl_exec($ch);
+      if ($err = curl_error($ch)) {
+        return false;
+      }
+
+      $login_page = str_get_dom($response);
+      $form_check = $login_page->select('input[name=form_check]', 0)->getAttribute('value');
+
+      // submit form
+      $data = array(
+        'feed_id'    => $this->username,
+        'password'   => $this->password,
+        'form_check' => $form_check,
+      );
+      curl_setopt($ch, CURLOPT_URL, $this->login_action);
+      curl_setopt($ch, CURLOPT_POST, true);
+      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
+      $response = curl_exec($ch);
+      if ($err = curl_error($ch)) {
+        return false;
+      }
+
+      curl_close($ch);
+      return true;
+    }
+
+    public function register() {
+      $data = "username=".$this->username.
+               "&password=".$this->password.
+               "&apikey=".$this->api_key;
+      return $this->serverCall('signup', $data);
+    }
+
+    public function addSingle($url, $title='', $ref_id='') {
+      $data = "username=".$this->username.
+               "&password=".$this->password.
+               "&apikey=".$this->api_key.
+               "&url=".$url.
+               "&title=".$title.
+               "&ref_id=".$ref_id;
+      return $this->serverCall('add', $data);
+    }
+
+    public function retreiveUsersList($since = "", $page = "", $state = "", $count = "", $tags = "0", $myAppOnly = "0", $format = 'json') {
+      $data = "username=".$this->username.
+               "&password=".$this->password.
+               "&apikey=".$this->api_key.
+               "&format=".$format.
+               "&state=".$state.
+               "&myAppOnly=".$myAppOnly.
+               "&since=".$since.
+               "&count=".$count.
+               "&page=".$page.
+               "&tags=".$tags;
+      return $this->serverCall('get', $data);
+    }
+
+    public function sendChanges($new, $read, $updateTitle, $updateTag) {
+      $data = "username=".$this->username.
+               "&password=".$this->password.
+               "&apikey=".$this->api_key.
+               "&new=". json_encode($new).
+               "&read=". json_encode($read).
+               "&update_title=". json_encode($updateTitle).
+               "&update_tags=". json_encode($updateTag);
+      return $this->serverCall('send', $data);
+    }
+
+    public function getArticles($count = 0) {
+      $tags = !empty($this->settings['tags']) ? 1 : 0;
+      $response = $this->retreiveUsersList(0, 0, 'unread', $count, $tags);
+      if (!$response) return false;
+      $ret = json_decode($response);
+      return (array) $ret->list;
+    }
+
+    public function markAsRead($data) {
+      $url = array();
+      if (is_array($data)) {
+        foreach ($data as $value) {
+          $url[] = array('url' => $value);
+        }
+      } else {
+        $url[] = array('url' => $data);
+      }
+      return $this->sendChanges(
+        array(),
+        $url,
+        array(),
+        array()
+      );
+    }
+
+    public function getSingleArticle($pid) {
+      $data = array(
+        'itemId' => $pid,
+      );
+      $response = $this->serverCall('a/x/getArticle.php', $data, 'http://getpocket.com/', true, true);
+      $ret = json_decode($response);
+      if (!$ret->status) {
+        mail($this->settings['mail'], 'Pocketbox auth error', 'There is some error with Pocketbox auth! Please check it out.');
+        return false;
+      }
+
+      // overwrite resolved_id field because sometimes it's not equal given id
+      $ret->article->resolved_id = $pid;
+
+      return $ret;
+    }
+
+    private function serverCall($method, $data, $url = NULL, $emulate = false, $ajax = false) {
+      try {
+        $link = $url ? $url . $method : $this->url . $method;
+
+        $ch = curl_init();
+
+        curl_setopt($ch, CURLOPT_URL, $link);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+        curl_setopt($ch, CURLOPT_FAILONERROR, true);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+        curl_setopt($ch, CURLOPT_POST, true);
+        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
+        curl_setopt($ch, CURLOPT_HEADER, false);
+        if ($emulate) {
+          curl_setopt($ch, CURLOPT_USERAGENT, "User-Agent: Opera/9.80 (Macintosh; Intel Mac OS X 10.7.4; U; en) Presto/2.10.289 Version/12.00");
+          curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookies);
+          $header = array();
+          $header[] = "Accept-Language: en-us,en;q=0.5";
+          if ($ajax) {
+            $header[] = "Accept: application/json, text/javascript, */*; q=0.01";
+            $header[] = "X-Requested-With: XMLHttpRequest";
+          }
+          $header[] = "Pragma: ";
+          curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
+        }
+
+        $response = curl_exec($ch);
+        $err = curl_error($ch);
+
+        curl_close($ch);
+
+        if ($err) {
+          switch ($err){
+            case 'The requested URL returned error: 400 ':
+                  throw new Exception("Invalid request, please make sure you follow the documentation for proper syntax: ");
+                  break;
+            case 'The requested URL returned error: 401':
+                  throw new Exception("Username and/or password is incorrect: ");
+                  break;
+            case 'The requested URL returned error: 403':
+                  throw new Exception("Rate limit exceeded, please wait a little bit before resubmitting: ");
+                  break;
+            case 'The requested URL returned error: 503':
+                  throw new Exception("Read It Later's sync server is down for scheduled maintenance: ");
+                  break;
+            default:
+                  throw new Exception($err);
+          }
+      }
+      else {
+        return $response;
+      }
+    } catch (Exception $e) {
+      echo $e->getMessage();
+      exit;
+    }
+  }
+}

app/pocketbox.php

+<?php
+
+require_once 'vendors/ganon/ganon.php';
+require_once 'app/pocket.php';
+require_once 'app/epub.php';
+require_once 'app/dropbox.php';
+
+class Pocketbox {
+  protected $config;
+  protected $db_file;
+  protected $pocket;
+  protected $dropbox;
+
+  protected $pocket_data;
+  protected $dropbox_data;
+  protected $local_data;
+
+  /**
+   * Constructor.
+   * @param string $config_file Path to main .ini file
+   */
+  function __construct($config_file) {
+    $this->config = parse_ini_file($config_file, true);
+    $this->db_file = $this->config['db_file'];
+
+    if ($this->config['debug']) ini_set('display_errors', 1);
+
+    $pcfg = $this->config['pocket'];
+    if (!$this->pocket = new PocketAPI($pcfg['login'], $pcfg['password'], $pcfg)) {
+      $this->log('Pocket auth error.', true);
+      throw new Exception("Pocket auth error.");
+    }
+    $this->dropbox = new DropboxClient($this->config['dropbox']);
+  }
+
+  /**
+   * Loads data from all sources: Pocket, Dropbox, local.
+   */
+  public function getData() {
+    if (!$this->pocket_data = $this->pocket->getArticles()) {
+      $this->log('Pocket load data error.', true);
+      throw new Exception("Pocket load data error.");
+    }
+    if (!$this->dropbox_data = $this->dropbox->getFilesList()) {
+      $this->log('Dropbox load data error.', true);
+      throw new Exception("Dropbox load data error.");
+    }
+    $this->local_data = $this->getLocalData();
+
+    return true;
+  }
+
+  /**
+   * Load local list of the articles from file.
+   * @return array Local list array
+   */
+  private function getLocalData() {
+    if (!is_file($this->db_file)) return array();
+
+    $ret = file($this->db_file);
+    foreach ($ret as $key => $val) {
+      $ret[$key] = trim($val);
+    }
+    return $ret;
+  }
+
+  /**
+   * Saves local list to file.
+   */
+  private function saveLocalData() {
+    return file_put_contents($this->db_file, implode("\n", $this->local_data));
+  }
+
+  /**
+   * Removes ID from local list of articles.
+   * @param  int $id ID of the article
+   */
+  private function removeFromLocalData($id) {
+    foreach ($this->local_data as $key => $value) {
+      if ($value == $id) {
+        unset($this->local_data[$key]);
+        break;
+      }
+    }
+  }
+
+  /**
+   * Process function for articles from Pocket - new and deleted from Dropbox.
+   */
+  public function processPocketData() {
+    $max_steps = $this->config['pocket']['parse_step'];
+    $parsed = 0;
+    foreach ($this->pocket_data as $value) {
+      $id = $value->item_id;
+      $in_local = $this->foundInLocalData($id);
+      $in_dropbox = $this->foundInDropbox($id);
+
+      // if processed: in local and in dropbox - skip
+      if ($in_local && $in_dropbox) {
+        // skip
+      }
+      // if readed: in local, but not in dropbox - mark as read
+      else if ($in_local && !$in_dropbox) {
+        $this->markAsRead($value);
+      }
+      // if new: not in local and not in dropbox - epub and upload
+      else if (!$in_local && !$in_dropbox && $parsed < $max_steps) {
+        if (!$this->exportItem($value)) return false;
+        $parsed++;
+        sleep(2); // pause for the next request
+      }
+    }
+  }
+
+  /**
+   * Process function for articles that already was marked as read in Pocket.
+   */
+  public function processLocalData() {
+    foreach ($this->local_data as $id) {
+      $in_pocket = $this->foundInPocket($id);
+      $in_dropbox = $this->foundInDropbox($id);
+      // ID in local list but not in Pocket - marked as read elsewhere
+      if (!$in_pocket) {
+        // remove from local list
+        $this->removeFromLocalData($id);
+        $this->saveLocalData();
+        $this->log($id .' - remove from local!');
+
+        // if file in dropbox - remove it
+        if ($in_dropbox) {
+          $dropbox_file = $this->getDropboxFilename($id);
+          if ($dropbox_file) {
+            $this->dropbox->deleteFile($dropbox_file);
+            $this->log($id .' - remove from dropbox!');
+          }
+        }
+      }
+    }
+  }
+
+  /**
+   * Mark article as read in Pocket.
+   * @param  obj $value Article object
+   */
+  protected function markAsRead($value) {
+    if (!$this->pocket->markAsRead($value->url)) {
+      $this->log('Error while mark article as read! ID: '. $value->item_id, true);
+    }
+    $this->removeFromLocalData($value->item_id);
+    $this->saveLocalData();
+    $this->log($value->item_id .' - mark as read!');
+  }
+
+  /**
+   * Export article as epub from Pocket.
+   * @param  obj $value Article object
+   * @return boolean
+   */
+  protected function exportItem($value) {
+    $id = $value->item_id;
+    if (!$item = $this->pocket->getSingleArticle($id)) {
+      $this->log('Error while loading article! ID: '. $id, true);
+      return false;
+    }
+
+    // generate epub file
+    $epub = new EpubGenerator();
+    if (!$file = $epub->generate($item)) {
+      $this->log('Error generating epub! ID: '. $id, true);
+      return false;
+    }
+    // upload to Dropbox
+    if (!$this->dropbox->uploadFile($file)) {
+      $this->log('Error uploading to Dropbox! ID: '. $id, true);
+      return false;
+    }
+    if (!unlink($file)) {
+      $this->log('Error while deleting temporary file! ID: '. $id, true);
+    }
+    $this->local_data[] = $id;
+    $this->saveLocalData();
+    $this->log($id .' - export epub!');
+    return true;
+  }
+
+  /**
+   * Try to find article in Pocket list.
+   * @param  int $id ID of the article
+   * @return boolean
+   */
+  protected function foundInPocket($id) {
+    foreach ($this->pocket_data as $value) {
+      if ($value->item_id == $id) return true;
+    }
+    return false;
+  }
+
+  /**
+   * Try to find article in local list of the files.
+   * @param  int $id ID of the article
+   * @return boolean
+   */
+  protected function foundInLocalData($id) {
+    foreach ($this->local_data as $key => $value) {
+      $data = trim($value);
+      if ($data == $id) return true;
+    }
+    return false;
+  }
+
+  /**
+   * Try to find article in Dropbox files.
+   * @param  int $id ID of the article
+   * @return boolean
+   */
+  protected function foundInDropbox($id) {
+    foreach ($this->dropbox_data as $key => $value) {
+      $data = explode('-', substr($value['path'], 1));
+      if ($data[0] == $id) return true;
+    }
+    return false;
+  }
+
+  protected function getDropboxFilename($id) {
+    if (!$this->foundInDropbox($id)) return false;
+    foreach ($this->dropbox_data as $key => $value) {
+      $data = explode('-', substr($value['path'], 1));
+      if ($data[0] == $id) return $value['path'];
+    }
+    return false;
+  }
+
+  /**
+   * Notify/error log. Show on screen if debug mode on, send mail.
+   * @param  string  $msg    Message text
+   * @param  boolean $notify Flag for sending error by mail
+   */
+  protected function log($msg, $notify = false) {
+    if ($this->config['debug']) {
+      echo '<p>'. $msg .'</p>';
+    }
+    file_put_contents('log.txt', date('r') .': '. $msg."\n", FILE_APPEND);
+    if ($notify && !empty($this->settings['mail'])) {
+      mail($this->settings['mail'], 'Pocketbox error', $msg);
+    }
+  }
+}
+<?php
+
+/**
+ * TODO:
+ *  - check Pocket API and Dropbox API rejection
+ *  - make dropbox auth process more interactive (add callback)
+ *  - clean (remove tokens etc) and make public
+ *
+ * Uses:
+ *  - https://github.com/Grandt/PHPePub
+ *  - https://github.com/Dropbox-PHP/dropbox-php
+ *  - https://github.com/kiranruth/Read-it-later-list-library (modified)
+ *  - http://code.google.com/p/ganon/
+ */
+
+require_once 'app/pocketbox.php';
+
+@dl('curl.so');    // curl is required
+@dl('imagick.so'); // if no imagick then big images will be stripped
+@ini_set('max_execution_time', 600);
+//@ini_set('memory_limit', '128M'); // may need for big articles
+
+$pocketbox = new Pocketbox('app/config.ini');
+$pocketbox->getData();
+$pocketbox->processPocketData();
+$pocketbox->processLocalData();

vendors/Dropbox/API.php

+<?php
+
+/**
+ * Dropbox API class 
+ * 
+ * @package Dropbox 
+ * @copyright Copyright (C) 2010 Rooftop Solutions. All rights reserved.
+ * @author Evert Pot (http://www.rooftopsolutions.nl/) 
+ * @license http://code.google.com/p/dropbox-php/wiki/License MIT
+ */
+class Dropbox_API {
+
+    /**
+     * Sandbox root-path
+     */
+    const ROOT_SANDBOX = 'sandbox';
+
+    /**
+     * Dropbox root-path
+     */
+    const ROOT_DROPBOX = 'dropbox';
+    
+    /**
+     * API URl
+     */
+    protected $api_url = 'https://api.dropbox.com/1/';
+    
+    /**
+     * Content API URl
+     */
+    protected $api_content_url = 'https://api-content.dropbox.com/1/';
+
+    /**
+     * OAuth object 
+     * 
+     * @var Dropbox_OAuth
+     */
+    protected $oauth;
+    
+    /**
+     * Default root-path, this will most likely be 'sandbox' or 'dropbox' 
+     * 
+     * @var string 
+     */
+    protected $root;
+    protected $useSSL;
+
+    /**
+     * Constructor 
+     * 
+     * @param Dropbox_OAuth Dropbox_Auth object
+     * @param string $root default root path (sandbox or dropbox) 
+     */
+    public function __construct(Dropbox_OAuth $oauth, $root = self::ROOT_DROPBOX, $useSSL = true) {
+
+        $this->oauth = $oauth;
+        $this->root = $root;
+        $this->useSSL = $useSSL;
+        if (!$this->useSSL)
+        {
+            throw new Dropbox_Exception('Dropbox REST API now requires that all requests use SSL');
+        }
+
+    }
+
+    /**
+     * Returns information about the current dropbox account 
+     * 
+     * @return stdclass 
+     */
+    public function getAccountInfo() {
+
+        $data = $this->oauth->fetch($this->api_url . 'account/info');
+        return json_decode($data['body'],true);
+
+    }
+
+    /**
+     * Returns a file's contents 
+     * 
+     * @param string $path path 
+     * @param string $root Use this to override the default root path (sandbox/dropbox) 
+     * @return string 
+     */
+    public function getFile($path = '', $root = null) {
+
+        if (is_null($root)) $root = $this->root;
+        $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
+        $result = $this->oauth->fetch($this->api_content_url . 'files/' . $root . '/' . ltrim($path,'/'));
+        return $result['body'];
+
+    }
+
+    /**
+     * Uploads a new file
+     *
+     * @param string $path Target path (including filename) 
+     * @param string $file Either a path to a file or a stream resource 
+     * @param string $root Use this to override the default root path (sandbox/dropbox)  
+     * @return bool 
+     */
+    public function putFile($path, $file, $root = null) {
+
+        $directory = dirname($path);
+        $filename = basename($path);
+
+        if($directory==='.') $directory = '';
+        $directory = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($directory));
+        $filename = str_replace('~', '%7E', rawurlencode($filename));
+        if (is_null($root)) $root = $this->root;
+
+        if (is_string($file)) {
+
+            $file = fopen($file,'rb');
+
+        } elseif (!is_resource($file)) {
+            throw new Dropbox_Exception('File must be a file-resource or a string');
+        }
+        $result=$this->multipartFetch($this->api_content_url . 'files/' . 
+                $root . '/' . trim($directory,'/'), $file, $filename);
+        
+        if(!isset($result["httpStatus"]) || $result["httpStatus"] != 200) 
+            throw new Dropbox_Exception("Uploading file to Dropbox failed");
+
+        return true;
+    }
+
+
+    /**
+     * Copies a file or directory from one location to another 
+     *
+     * This method returns the file information of the newly created file.
+     *
+     * @param string $from source path 
+     * @param string $to destination path 
+     * @param string $root Use this to override the default root path (sandbox/dropbox)  
+     * @return stdclass 
+     */
+    public function copy($from, $to, $root = null) {
+
+        if (is_null($root)) $root = $this->root;
+        $response = $this->oauth->fetch($this->api_url . 'fileops/copy', array('from_path' => $from, 'to_path' => $to, 'root' => $root));
+
+        return json_decode($response['body'],true);
+
+    }
+
+    /**
+     * Creates a new folder 
+     *
+     * This method returns the information from the newly created directory
+     *
+     * @param string $path 
+     * @param string $root Use this to override the default root path (sandbox/dropbox)  
+     * @return stdclass 
+     */
+    public function createFolder($path, $root = null) {
+
+        if (is_null($root)) $root = $this->root;
+
+        // Making sure the path starts with a /
+        $path = '/' . ltrim($path,'/');
+
+        $response = $this->oauth->fetch($this->api_url . 'fileops/create_folder', array('path' => $path, 'root' => $root),'POST');
+        return json_decode($response['body'],true);
+
+    }
+
+    /**
+     * Deletes a file or folder.
+     *
+     * This method will return the metadata information from the deleted file or folder, if successful.
+     * 
+     * @param string $path Path to new folder 
+     * @param string $root Use this to override the default root path (sandbox/dropbox)  
+     * @return array 
+     */
+    public function delete($path, $root = null) {
+
+        if (is_null($root)) $root = $this->root;
+        $response = $this->oauth->fetch($this->api_url . 'fileops/delete', array('path' => $path, 'root' => $root));
+        return json_decode($response['body']);
+
+    }
+
+    /**
+     * Moves a file or directory to a new location 
+     *
+     * This method returns the information from the newly created directory
+     *
+     * @param mixed $from Source path 
+     * @param mixed $to destination path
+     * @param string $root Use this to override the default root path (sandbox/dropbox) 
+     * @return stdclass 
+     */
+    public function move($from, $to, $root = null) {
+
+        if (is_null($root)) $root = $this->root;
+        $response = $this->oauth->fetch($this->api_url . 'fileops/move', array('from_path' => rawurldecode($from), 'to_path' => rawurldecode($to), 'root' => $root));
+
+        return json_decode($response['body'],true);
+
+    }
+
+    /**
+     * Returns file and directory information
+     * 
+     * @param string $path Path to receive information from 
+     * @param bool $list When set to true, this method returns information from all files in a directory. When set to false it will only return infromation from the specified directory.
+     * @param string $hash If a hash is supplied, this method simply returns true if nothing has changed since the last request. Good for caching.
+     * @param int $fileLimit Maximum number of file-information to receive 
+     * @param string $root Use this to override the default root path (sandbox/dropbox) 
+     * @return array|true 
+     */
+    public function getMetaData($path, $list = true, $hash = null, $fileLimit = null, $root = null) {
+
+        if (is_null($root)) $root = $this->root;
+
+        $args = array(
+            'list' => $list,
+        );
+
+        if (!is_null($hash)) $args['hash'] = $hash; 
+        if (!is_null($fileLimit)) $args['file_limit'] = $fileLimit; 
+
+        $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
+        $response = $this->oauth->fetch($this->api_url . 'metadata/' . $root . '/' . ltrim($path,'/'), $args);
+
+        /* 304 is not modified */
+        if ($response['httpStatus']==304) {
+            return true; 
+        } else {
+            return json_decode($response['body'],true);
+        }
+
+    } 
+
+    /**
+    * A way of letting you keep up with changes to files and folders in a user's Dropbox. You can periodically call /delta to get a list of "delta entries", which are instructions on how to update your local state to match the server's state.
+    *
+    * This method returns the information from the newly created directory
+    *
+    * @param string $cursor A string that is used to keep track of your current state. On the next call pass in this value to return delta entries that have been recorded since the cursor was returned.
+    * @return stdclass
+    */
+    public function delta($cursor) {
+    
+    	$arg['cursor'] = $cursor;
+    
+    	$response = $this->oauth->fetch($this->api_url . 'delta', $arg, 'POST');
+    	return json_decode($response['body'],true);
+    
+    }
+
+    /**
+     * Returns a thumbnail (as a string) for a file path. 
+     * 
+     * @param string $path Path to file 
+     * @param string $size small, medium or large 
+     * @param string $root Use this to override the default root path (sandbox/dropbox)  
+     * @return string 
+     */
+    public function getThumbnail($path, $size = 'small', $root = null) {
+
+        if (is_null($root)) $root = $this->root;
+        $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
+        $response = $this->oauth->fetch($this->api_content_url . 'thumbnails/' . $root . '/' . ltrim($path,'/'),array('size' => $size));
+
+        return $response['body'];
+
+    }
+
+    /**
+     * This method is used to generate multipart POST requests for file upload 
+     * 
+     * @param string $uri 
+     * @param array $arguments 
+     * @return bool 
+     */
+    protected function multipartFetch($uri, $file, $filename) {
+
+        /* random string */
+        $boundary = 'R50hrfBj5JYyfR3vF3wR96GPCC9Fd2q2pVMERvEaOE3D8LZTgLLbRpNwXek3';
+
+        $headers = array(
+            'Content-Type' => 'multipart/form-data; boundary=' . $boundary,
+        );
+
+        $body="--" . $boundary . "\r\n";
+        $body.="Content-Disposition: form-data; name=file; filename=".rawurldecode($filename)."\r\n";
+        $body.="Content-type: application/octet-stream\r\n";
+        $body.="\r\n";
+        $body.=stream_get_contents($file);
+        $body.="\r\n";
+        $body.="--" . $boundary . "--";
+
+        // Dropbox requires the filename to also be part of the regular arguments, so it becomes
+        // part of the signature. 
+        $uri.='?file=' . $filename;
+
+        return $this->oauth->fetch($uri, $body, 'POST', $headers);
+
+    }
+	
+	
+	/**
+     * Search
+     *
+     * Returns metadata for all files and folders that match the search query.
+     *
+	 * @added by: diszo.sasil 
+	 *
+     * @param string $query	 
+     * @param string $root Use this to override the default root path (sandbox/dropbox)
+	 * @param string $path
+     * @return array
+     */
+	public function search($query = '', $root = null, $path = ''){
+		if (is_null($root)) $root = $this->root;
+		if(!empty($path)){
+			$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
+		}
+        $response = $this->oauth->fetch($this->api_url . 'search/' . $root . '/' . ltrim($path,'/'),array('query' => $query));
+        return json_decode($response['body'],true);
+	}
+
+    /**
+     * Creates and returns a shareable link to files or folders.
+     * 
+     * Note: Links created by the /shares API call expire after thirty days.
+     * 
+     * @param type $path
+     * @param type $root
+     * @return type 
+     */
+    public function share($path, $root = null) {
+        if (is_null($root)) $root = $this->root;
+        $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
+        $response = $this->oauth->fetch($this->api_url.  'shares/'. $root . '/' . ltrim($path, '/'), array(), 'POST');
+        return json_decode($response['body'],true);
+
+    }
+
+    /**
+    * Returns a link directly to a file.
+    * Similar to /shares. The difference is that this bypasses the Dropbox webserver, used to provide a preview of the file, so that you can effectively stream the contents of your media.
+    *
+    * Note: The /media link expires after four hours, allotting enough time to stream files, but not enough to leave a connection open indefinitely.
+    *
+    * @param type $path
+    * @param type $root
+    * @return type
+    */
+    public function media($path, $root = null) {
+
+    	if (is_null($root)) $root = $this->root;
+    	$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
+    	$response = $this->oauth->fetch($this->api_url.  'media/'. $root . '/' . ltrim($path, '/'), array(), 'POST');
+    	return json_decode($response['body'],true);
+    
+    }
+
+    /**
+    * Creates and returns a copy_ref to a file. This reference string can be used to copy that file to another user's Dropbox by passing it in as the from_copy_ref parameter on /fileops/copy.
+    *
+    * @param type $path
+    * @param type $root
+    * @return type
+    */
+    public function copy_ref($path, $root = null) {
+
+    	if (is_null($root)) $root = $this->root;
+    	$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
+    	$response = $this->oauth->fetch($this->api_url.  'copy_ref/'. $root . '/' . ltrim($path, '/'));
+    	return json_decode($response['body'],true);
+    
+    }
+    
+
+}

vendors/Dropbox/Exception.php

+<?php
+
+/**
+ * Dropbox base exception 
+ * 
+ * @package Dropbox 
+ * @copyright Copyright (C) 2010 Rooftop Solutions. All rights reserved.
+ * @author Evert Pot (http://www.rooftopsolutions.nl/) 
+ * @license http://code.google.com/p/dropbox-php/wiki/License MIT
+ */
+
+/**
+ * Base exception class
+ */
+class Dropbox_Exception extends Exception { }

vendors/Dropbox/Exception/Forbidden.php

+<?php
+
+/**
+ * Dropbox Forbidden exception
+ * 
+ * @package Dropbox 
+ * @copyright Copyright (C) 2010 Rooftop Solutions. All rights reserved.
+ * @author Evert Pot (http://www.rooftopsolutions.nl/) 
+ * @license http://code.google.com/p/dropbox-php/wiki/License MIT
+ */
+
+/**
+ * This exception is thrown when we receive the 403 forbidden response
+ */
+class Dropbox_Exception_Forbidden extends Dropbox_Exception {
+
+
+}

vendors/Dropbox/Exception/NotFound.php

+<?php
+
+/**
+ * Dropbox Not Found exception
+ * 
+ * @package Dropbox 
+ * @copyright Copyright (C) 2010 Rooftop Solutions. All rights reserved.
+ * @author Evert Pot (http://www.rooftopsolutions.nl/) 
+ * @license http://code.google.com/p/dropbox-php/wiki/License MIT
+ */
+
+/**
+ * This exception is thrown when a non-existant uri is accessed.
+ * 
+ * Basically, this exception is used when we get back a 404.
+ */
+class Dropbox_Exception_NotFound extends Dropbox_Exception {
+
+
+}

vendors/Dropbox/Exception/OverQuota.php

+<?php
+
+/**
+ * Dropbox Over Quota exception
+ * 
+ * @package Dropbox 
+ * @copyright Copyright (C) 2010 Rooftop Solutions. All rights reserved.
+ * @author Evert Pot (http://www.rooftopsolutions.nl/) 
+ * @license http://code.google.com/p/dropbox-php/wiki/License MIT
+ */
+
+/**
+ * This exception is thrown when the operation required more space than the available quota.
+ * 
+ * Basically, this exception is used when we get back a 507.
+ */
+class Dropbox_Exception_OverQuota extends Dropbox_Exception {
+
+
+}

vendors/Dropbox/Exception/RequestToken.php

+<?php
+
+/**
+ * Dropbox RequestToken exception
+ * 
+ * @package Dropbox 
+ * @copyright Copyright (C) 2010 Rooftop Solutions. All rights reserved.
+ * @author Evert Pot (http://www.rooftopsolutions.nl/) 
+ * @license http://code.google.com/p/dropbox-php/wiki/License MIT
+ */
+
+/**
+ * This exception is thrown when an error occured during the request_token process.
+ */
+class Dropbox_Exception_RequestToken extends Dropbox_Exception {
+
+
+}

vendors/Dropbox/OAuth.php

+<?php
+
+/**
+ * Dropbox OAuth
+ * 
+ * @package Dropbox 
+ * @copyright Copyright (C) 2010 Rooftop Solutions. All rights reserved.
+ * @author Evert Pot (http://www.rooftopsolutions.nl/) 
+ * @license http://code.google.com/p/dropbox-php/wiki/License MIT
+ */
+
+
+/**
+ * This class is an abstract OAuth class.
+ *
+ * It must be extended by classes who wish to provide OAuth functionality
+ * using different libraries.
+ */
+abstract class Dropbox_OAuth {
+
+    /**
+     * After a user has authorized access, dropbox can redirect the user back
+     * to this url.
+     * 
+     * @var string
+     */
+    public $authorizeCallbackUrl = null; 
+   
+    /**
+     * Uri used to fetch request tokens 
+     * 
+     * @var string
+     */
+    const URI_REQUEST_TOKEN = 'https://api.dropbox.com/1/oauth/request_token';
+
+    /**
+     * Uri used to redirect the user to for authorization.
+     * 
+     * @var string
+     */
+    const URI_AUTHORIZE = 'https://www.dropbox.com/1/oauth/authorize';
+
+    /**
+     * Uri used to 
+     * 
+     * @var string
+     */
+    const URI_ACCESS_TOKEN = 'https://api.dropbox.com/1/oauth/access_token';
+
+    /**
+     * An OAuth request token. 
+     * 
+     * @var string 
+     */
+    protected $oauth_token = null;
+
+    /**
+     * OAuth token secret 
+     * 
+     * @var string 
+     */
+    protected $oauth_token_secret = null;
+
+
+    /**
+     * Constructor
+     * 
+     * @param string $consumerKey 
+     * @param string $consumerSecret 
+     */
+    abstract public function __construct($consumerKey, $consumerSecret);
+
+    /**
+     * Sets the request token and secret.
+     *
+     * The tokens can also be passed as an array into the first argument.
+     * The array must have the elements token and token_secret.
+     * 
+     * @param string|array $token 
+     * @param string $token_secret 
+     * @return void
+     */
+    public function setToken($token, $token_secret = null) {
+
+        if (is_array($token)) {
+            $this->oauth_token = $token['token'];
+            $this->oauth_token_secret = $token['token_secret'];
+        } else {
+            $this->oauth_token = $token;
+            $this->oauth_token_secret = $token_secret;
+        }
+
+    }
+
+    /**
+     * Returns the oauth request tokens as an associative array.
+     *
+     * The array will contain the elements 'token' and 'token_secret'.
+     * 
+     * @return array 
+     */
+    public function getToken() {
+
+        return array(
+            'token' => $this->oauth_token,
+            'token_secret' => $this->oauth_token_secret,
+        );
+
+    }
+
+    /**
+     * Returns the authorization url
+     * 
+     * @param string $callBack Specify a callback url to automatically redirect the user back 
+     * @return string 
+     */
+    public function getAuthorizeUrl($callBack = null) {
+        
+        // Building the redirect uri
+        $token = $this->getToken();
+        $uri = self::URI_AUTHORIZE . '?oauth_token=' . $token['token'];
+        if ($callBack) $uri.='&oauth_callback=' . $callBack;
+        return $uri;
+    }
+
+    /**
+     * Fetches a secured oauth url and returns the response body. 
+     * 
+     * @param string $uri 
+     * @param mixed $arguments 
+     * @param string $method 
+     * @param array $httpHeaders 
+     * @return string 
+     */
+    public abstract function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array()); 
+
+    /**
+     * Requests the OAuth request token.
+     * 
+     * @return array 
+     */
+    abstract public function getRequestToken(); 
+
+    /**
+     * Requests the OAuth access tokens.
+     *
+     * @return array
+     */
+    abstract public function getAccessToken(); 
+
+}

vendors/Dropbox/OAuth/Consumer/Dropbox.php

+<?php
+/**
+ * HTTP OAuth Consumer
+ * 
+ * Adapted from halldirector's code in 
+ * http://code.google.com/p/dropbox-php/issues/detail?id=36#c5
+ * 
+ * @package Dropbox
+ * @copyright Copyright (C) 2011 Joe Constant / halldirector. All rights reserved.
+ * @author Joe Constant / halldirector
+ * @license http://code.google.com/p/dropbox-php/wiki/License MIT
+ */
+
+require_once 'HTTP/OAuth.php';
+require_once 'HTTP/OAuth/Consumer.php';
+
+/* 
+ * This class is to help work around aomw ssl issues.
+ */
+class Dropbox_OAuth_Consumer_Dropbox extends  HTTP_OAuth_Consumer
+{
+    public function getOAuthConsumerRequest()
+    {
+        if (!$this->consumerRequest instanceof HTTP_OAuth_Consumer_Request) {
+            $this->consumerRequest = new HTTP_OAuth_Consumer_Request;
+        }
+        
+        // TODO: Change this and add in code to validate the SSL cert.
+        // see https://github.com/bagder/curl/blob/master/lib/mk-ca-bundle.pl
+        $this->consumerRequest->setConfig(array(
+                    'ssl_verify_peer' => false, 
+                    'ssl_verify_host' => false
+                ));
+        
+        return $this->consumerRequest;
+    }
+}

vendors/Dropbox/OAuth/Curl.php

+<?php
+
+/**
+ * Dropbox OAuth
+ * 
+ * @package Dropbox 
+ * @copyright Copyright (C) 2011 Daniel Huesken
+ * @author Daniel Huesken (http://www.danielhuesken.de/)
+ * @license MIT
+ */
+
+/**
+ * This class is used to sign all requests to dropbox.
+ *
+ * This specific class uses WordPress WP_Http to authenticate.
+ */
+class Dropbox_OAuth_Curl extends Dropbox_OAuth {
+
+    /**
+     *
+     * @var string ConsumerKey
+     */
+    protected $consumerKey = null;
+    /**
+     *
+     * @var string ConsumerSecret
+     */
+    protected $consumerSecret = null;
+    /**
+     *
+     * @var string ProzessCallBack
+     */
+    public $ProgressFunction = false;
+	
+    /**
+     * Constructor
+     * 
+     * @param string $consumerKey 
+     * @param string $consumerSecret 
+     */
+    public function __construct($consumerKey, $consumerSecret) {
+        if (!function_exists('curl_exec')) 
+            throw new Dropbox_Exception('The PHP curl functions not available!');
+
+        $this->consumerKey = $consumerKey;
+        $this->consumerSecret = $consumerSecret;
+    }
+
+    /**
+     * Fetches a secured oauth url and returns the response body. 
+     * 
+     * @param string $uri 
+     * @param mixed $arguments 
+     * @param string $method 
+     * @param array $httpHeaders 
+     * @return string 
+     */
+    public function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array()) {
+		
+		$uri=str_replace('http://', 'https://', $uri); // all https, upload makes problems if not
+		if (is_string($arguments) and strtoupper($method) == 'POST') {
+		    preg_match("/\?file=(.*)$/i", $uri, $matches);
+			if (isset($matches[1])) {
+                $uri = str_replace($matches[0], "", $uri);
+                $filename = $matches[1];
+				$httpHeaders=array_merge($httpHeaders,$this->getOAuthHeader($uri, array("file" => $filename), $method));
+            }
+		} else {
+			$httpHeaders=array_merge($httpHeaders,$this->getOAuthHeader($uri, $arguments, $method));
+		}
+		
+		$ch = curl_init();	
+		if (strtoupper($method) == 'POST') {
+			curl_setopt($ch, CURLOPT_URL, $uri);
+			curl_setopt($ch, CURLOPT_POST, true);
+			if (is_array($arguments))
+				$arguments=http_build_query($arguments);
+			curl_setopt($ch, CURLOPT_POSTFIELDS, $arguments);
+			$httpHeaders['Content-Length']=strlen($arguments);
+		} else {
+			curl_setopt($ch, CURLOPT_URL, $uri.'?'.http_build_query($arguments));
+			curl_setopt($ch, CURLOPT_POST, false);
+		}
+		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+		curl_setopt($ch, CURLOPT_TIMEOUT, 300);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
+        curl_setopt($ch, CURLOPT_CAINFO, "rootca");
+		curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
+		//Build header
+		$headers = array();
+		foreach ($httpHeaders as $name => $value) {
+			$headers[] = "{$name}: $value";
+		}
+		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+		if (!ini_get('safe_mode') && !ini_get('open_basedir'))
+			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
+		if (function_exists($this->ProgressFunction) and defined('CURLOPT_PROGRESSFUNCTION')) {
+			curl_setopt($ch, CURLOPT_NOPROGRESS, false);
+			curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, $this->ProgressFunction);
+			curl_setopt($ch, CURLOPT_BUFFERSIZE, 512);
+		}
+		$response=curl_exec($ch);
+		$errorno=curl_errno($ch);
+		$error=curl_error($ch);
+		$status=curl_getinfo($ch,CURLINFO_HTTP_CODE);
+		curl_close($ch);
+		
+		
+		if (!empty($errorno))
+			throw new Dropbox_Exception_NotFound('Curl error: ('.$errorno.') '.$error."\n");
+						
+		if ($status>=300) {
+			$body = json_decode($response,true);
+			switch ($status) {
+				// Not modified
+				case 304 :
+					return array(
+						'httpStatus' => 304,
+						'body' => null,
+					);
+					break;
+				case 403 :
+					throw new Dropbox_Exception_Forbidden('Forbidden.
+						This could mean a bad OAuth request, or a file or folder already existing at the target location.
+						' . $body["error"] . "\n");
+				case 404 :
+					throw new Dropbox_Exception_NotFound('Resource at uri: ' . $uri . ' could not be found. ' .
+							$body["error"] . "\n");
+				case 507 :
+					throw new Dropbox_Exception_OverQuota('This dropbox is full. ' .
+							$body["error"] . "\n");
+			}
+			if (!empty($body["error"]))
+				throw new Dropbox_Exception_RequestToken('Error: ('.$status.') '.$body["error"]."\n");	
+		}
+		
+        return array(
+			'body' => $response,
+            'httpStatus' => $status
+        );
+    }
+
+    /**
+     * Returns named array with oauth parameters for further use
+     * @return array Array with oauth_ parameters
+     */
+    private function getOAuthBaseParams() {
+        $params['oauth_version'] = '1.0';
+        $params['oauth_signature_method'] = 'HMAC-SHA1';
+
+        $params['oauth_consumer_key'] = $this->consumerKey;
+        $tokens = $this->getToken();
+        if (isset($tokens['token']) && $tokens['token']) {
+            $params['oauth_token'] = $tokens['token'];
+        }
+        $params['oauth_timestamp'] = time();
+        $params['oauth_nonce'] = md5(microtime() . mt_rand());
+        return $params;
+    }
+
+    /**
+     * Creates valid Authorization header for OAuth, based on URI and Params
+     *
+     * @param string $uri
+     * @param array $params
+     * @param string $method GET or POST, standard is GET
+     * @param array $oAuthParams optional, pass your own oauth_params here
+     * @return array Array for request's headers section like
+     * array('Authorization' => 'OAuth ...');
+     */
+    private function getOAuthHeader($uri, $params, $method = 'GET', $oAuthParams = null) {
+        $oAuthParams = $oAuthParams ? $oAuthParams : $this->getOAuthBaseParams();
+
+        // create baseString to encode for the sent parameters
+        $baseString = $method . '&';
+        $baseString .= $this->oauth_urlencode($uri) . "&";
+
+        // OAuth header does not include GET-Parameters
+        $signatureParams = array_merge($params, $oAuthParams);
+
+        // sorting the parameters
+        ksort($signatureParams);
+
+        $encodedParams = array();
+        foreach ($signatureParams as $key => $value) {
+            $encodedParams[] = $this->oauth_urlencode($key) . '=' . $this->oauth_urlencode($value);
+        }
+
+        $baseString .= $this->oauth_urlencode(implode('&', $encodedParams));
+
+        // encode the signature
+        $tokens = $this->getToken();
+        $hash = $this->hash_hmac_sha1($this->consumerSecret.'&'.$tokens['token_secret'], $baseString);
+        $signature = base64_encode($hash);
+
+        // add signature to oAuthParams
+        $oAuthParams['oauth_signature'] = $signature;
+
+        $oAuthEncoded = array();
+        foreach ($oAuthParams as $key => $value) {
+            $oAuthEncoded[] = $key . '="' . $this->oauth_urlencode($value) . '"';
+        }
+
+        return array('Authorization' => 'OAuth ' . implode(', ', $oAuthEncoded));
+    }
+
+    /**
+     * Requests the OAuth request token.
+     *
+     * @return void 
+     */
+    public function getRequestToken() {
+        $result = $this->fetch(self::URI_REQUEST_TOKEN, array(), 'POST');
+        if ($result['httpStatus'] == "200") {
+            $tokens = array();
+            parse_str($result['body'], $tokens);
+            $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']);
+            return $this->getToken();
+        } else {
+            throw new Dropbox_Exception_RequestToken('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.');
+        }
+    }
+
+    /**
+     * Requests the OAuth access tokens.
+     *
+     * This method requires the 'unauthorized' request tokens
+     * and, if successful will set the authorized request tokens.
+     * 
+     * @return void 
+     */
+    public function getAccessToken() {
+        $result = $this->fetch(self::URI_ACCESS_TOKEN, array(), 'POST');
+        if ($result['httpStatus'] == "200") {
+            $tokens = array();
+            parse_str($result['body'], $tokens);
+            $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']);
+            return $this->getToken();
+        } else {
+            throw new Dropbox_Exception_RequestToken('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.');
+        }
+    }
+
+    /**
+     * Helper function to properly urlencode parameters.
+     * See http://php.net/manual/en/function.oauth-urlencode.php
+     *
+     * @param string $string
+     * @return string
+     */
+    private function oauth_urlencode($string) {
+        return str_replace('%E7', '~', rawurlencode($string));
+    }
+
+    /**
+     * Hash function for hmac_sha1; uses native function if available.
+     *
+     * @param string $key
+     * @param string $data
+     * @return string
+     */
+    private function hash_hmac_sha1($key, $data) {
+        if (function_exists('hash_hmac') && in_array('sha1', hash_algos())) {
+            return hash_hmac('sha1', $data, $key, true);
+        } else {
+            $blocksize = 64;
+            $hashfunc = 'sha1';
+            if (strlen($key) > $blocksize) {
+                $key = pack('H*', $hashfunc($key));
+            }
+
+            $key = str_pad($key, $blocksize, chr(0x00));
+            $ipad = str_repeat(chr(0x36), $blocksize);
+            $opad = str_repeat(chr(0x5c), $blocksize);
+            $hash = pack('H*', $hashfunc(( $key ^ $opad ) . pack('H*', $hashfunc(($key ^ $ipad) . $data))));
+
+            return $hash;
+        }
+    }
+	
+
+}

vendors/Dropbox/OAuth/PEAR.php

+<?php
+
+/**
+ * Dropbox OAuth
+ * 
+ * @package Dropbox 
+ * @copyright Copyright (C) 2010 Rooftop Solutions. All rights reserved.
+ * @author Evert Pot (http://www.rooftopsolutions.nl/) 
+ * @license http://code.google.com/p/dropbox-php/wiki/License MIT
+ */
+
+if (!class_exists('HTTP_OAuth_Consumer')) {
+
+    // We're going to try to load in manually
+    include 'HTTP/OAuth/Consumer.php';
+
+}
+if (!class_exists('HTTP_OAuth_Consumer')) 
+    throw new Dropbox_Exception('The HTTP_OAuth_Consumer class could not be found! Did you install the pear HTTP_OAUTH class?');
+
+/**
+ * This class is used to sign all requests to dropbox
+ * 
+ * This classes use the PEAR HTTP_OAuth package. Make sure this is installed.
+ */
+class Dropbox_OAuth_PEAR extends Dropbox_OAuth {
+
+    /**
+     * OAuth object
+     *
+     * @var OAuth
+     */
+    protected $oAuth;
+
+    /**
+     * OAuth consumer key
+     * 
+     * We need to keep this around for later. 
+     * 
+     * @var string 
+     */
+    protected $consumerKey;
+
+    /**
+     * Constructor
+     * 
+     * @param string $consumerKey 
+     * @param string $consumerSecret 
+     */
+    public function __construct($consumerKey, $consumerSecret)
+    {
+        $this->OAuth = new Dropbox_OAuth_Consumer_Dropbox($consumerKey, $consumerSecret);
+        $this->consumerKey = $consumerKey;
+    }
+
+    /**
+     * Sets the request token and secret.
+     *
+     * The tokens can also be passed as an array into the first argument.
+     * The array must have the elements token and token_secret.
+     * 
+     * @param string|array $token 
+     * @param string $token_secret 
+     * @return void
+     */
+    public function setToken($token, $token_secret = null) {
+
+        parent::setToken($token,$token_secret);
+        $this->OAuth->setToken($this->oauth_token);
+        $this->OAuth->setTokenSecret($this->oauth_token_secret);
+
+    }
+
+    /**
+     * Fetches a secured oauth url and returns the response body. 
+     * 
+     * @param string $uri 
+     * @param mixed $arguments 
+     * @param string $method 
+     * @param array $httpHeaders 
+     * @return string 
+     */
+    public function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array())
+    {
+        $httpRequest = new HTTP_Request2(null, 
+                HTTP_Request2::METHOD_GET, 
+                array(
+                    'ssl_verify_peer' => false, 
+                    'ssl_verify_host' => false
+                )
+        );
+
+        $consumerRequest = new HTTP_OAuth_Consumer_Request();
+        $consumerRequest->accept($httpRequest);
+        $consumerRequest->setUrl($uri);
+        $consumerRequest->setMethod($method);
+        $consumerRequest->setSecrets($this->OAuth->getSecrets());
+     
+        $parameters = array(
+            'oauth_consumer_key'     => $this->consumerKey,
+            'oauth_signature_method' => 'HMAC-SHA1',
+            'oauth_token'            => $this->oauth_token,
+        );
+
+
+        if (is_array($arguments)) {
+            $parameters = array_merge($parameters,$arguments);
+        } elseif (is_string($arguments)) {
+            $consumerRequest->setBody($arguments);
+        }
+        $consumerRequest->setParameters($parameters);
+
+
+        if (count($httpHeaders)) {
+            foreach($httpHeaders as $k=>$v) {
+                $consumerRequest->setHeader($k, $v);
+            }
+        }
+
+        $response = $consumerRequest->send();
+
+        switch($response->getStatus()) {
+
+              // Not modified
+            case 304 :
+                return array(
+                    'httpStatus' => 304,
+                    'body'       => null,
+                );
+                break;
+            case 400 :
+                throw new Dropbox_Exception_Forbidden('Forbidden. Bad input parameter. Error message should indicate which one and why.');
+            case 401 :
+                throw new Dropbox_Exception_Forbidden('Forbidden. Bad or expired token. This can happen if the user or Dropbox revoked or expired an access token. To fix, you should re-authenticate the user.');
+            case 403 :
+                throw new Dropbox_Exception_Forbidden('Forbidden. This could mean a bad OAuth request, or a file or folder already existing at the target location.');
+            case 404 : 
+                throw new Dropbox_Exception_NotFound('Resource at uri: ' . $uri . ' could not be found');
+            case 405 : 
+                throw new Dropbox_Exception_Forbidden('Forbidden. Request method not expected (generally should be GET or POST).');
+            case 503 : 
+                throw new Dropbox_Exception_Forbidden('Forbidden. Your app is making too many requests and is being rate limited. 503s can trigger on a per-app or per-user basis.');
+            case 507 : 
+                throw new Dropbox_Exception_OverQuota('This dropbox is full');
+                
+        }
+
+        return array(
+            'httpStatus' => $response->getStatus(),
+            'body' => $response->getBody()
+        );
+
+    }
+
+    /**
+     * Requests the OAuth request token.
+     * 
+     * @return void
+     */
+    public function getRequestToken() {
+        
+        $this->OAuth->getRequestToken(self::URI_REQUEST_TOKEN);
+        $this->setToken($this->OAuth->getToken(), $this->OAuth->getTokenSecret());
+        return $this->getToken();
+
+    }
+
+    /**
+     * Requests the OAuth access tokens.
+     *
+     * This method requires the 'unauthorized' request tokens
+     * and, if successful will set the authorized request tokens.
+     * 
+     * @return void 
+     */
+    public function getAccessToken() {
+
+        $this->OAuth->getAccessToken(self::URI_ACCESS_TOKEN);
+        $this->setToken($this->OAuth->getToken(), $this->OAuth->getTokenSecret());
+        return $this->getToken();
+
+    }
+
+
+}

vendors/Dropbox/OAuth/PHP.php

+<?php
+
+/**
+ * Dropbox OAuth
+ * 
+ * @package Dropbox 
+ * @copyright Copyright (C) 2010 Rooftop Solutions. All rights reserved.
+ * @author Evert Pot (http://www.rooftopsolutions.nl/) 
+ * @license http://code.google.com/p/dropbox-php/wiki/License MIT
+ */
+
+
+/**
+ * This class is used to sign all requests to dropbox.
+ *
+ * This specific class uses the PHP OAuth extension
+ */
+class Dropbox_OAuth_PHP extends Dropbox_OAuth {
+
+    /**
+     * OAuth object
+     *
+     * @var OAuth
+     */
+    protected $oAuth;
+
+    /**
+     * Constructor
+     * 
+     * @param string $consumerKey 
+     * @param string $consumerSecret 
+     */
+    public function __construct($consumerKey, $consumerSecret) {
+
+        if (!class_exists('OAuth')) 
+            throw new Dropbox_Exception('The OAuth class could not be found! Did you install and enable the oauth extension?');
+
+        $this->OAuth = new OAuth($consumerKey, $consumerSecret,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
+        $this->OAuth->enableDebug();
+
+    }
+
+    /**
+     * Sets the request token and secret.
+     *
+     * The tokens can also be passed as an array into the first argument.
+     * The array must have the elements token and token_secret.
+     * 
+     * @param string|array $token 
+     * @param string $token_secret 
+     * @return void
+     */
+    public function setToken($token, $token_secret = null) {
+
+        parent::setToken($token,$token_secret);
+        $this->OAuth->setToken($this->oauth_token, $this->oauth_token_secret);
+
+    }
+
+
+    /**
+     * Fetches a secured oauth url and returns the response body. 
+     * 
+     * @param string $uri 
+     * @param mixed $arguments 
+     * @param string $method 
+     * @param array $httpHeaders 
+     * @return string 
+     */
+    public function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array()) {
+
+        try { 
+            $this->OAuth->fetch($uri, $arguments, $method, $httpHeaders);
+            $result = $this->OAuth->getLastResponse();
+            $lastResponseInfo = $this->OAuth->getLastResponseInfo();
+            return array(
+                'httpStatus' => $lastResponseInfo['http_code'],
+                'body'       => $result,
+            );
+        } catch (OAuthException $e) {
+
+            $lastResponseInfo = $this->OAuth->getLastResponseInfo();
+            switch($lastResponseInfo['http_code']) {
+
+                  // Not modified
+                case 304 :
+                    return array(
+                        'httpStatus' => 304,
+                        'body'       => null,
+                    );
+                    break;
+                case 400 :
+                    throw new Dropbox_Exception_Forbidden('Forbidden. Bad input parameter. Error message should indicate which one and why.');
+                case 401 :
+                    throw new Dropbox_Exception_Forbidden('Forbidden. Bad or expired token. This can happen if the user or Dropbox revoked or expired an access token. To fix, you should re-authenticate the user.');
+                case 403 :
+                    throw new Dropbox_Exception_Forbidden('Forbidden. This could mean a bad OAuth request, or a file or folder already existing at the target location.');
+                case 404 : 
+                    throw new Dropbox_Exception_NotFound('Resource at uri: ' . $uri . ' could not be found');
+                case 405 : 
+                    throw new Dropbox_Exception_Forbidden('Forbidden. Request method not expected (generally should be GET or POST).');
+                case 503 : 
+                    throw new Dropbox_Exception_Forbidden('Forbidden. Your app is making too many requests and is being rate limited. 503s can trigger on a per-app or per-user basis.');
+                case 507 : 
+                    throw new Dropbox_Exception_OverQuota('This dropbox is full');
+                default:
+                    // rethrowing
+                    throw $e;
+            }
+
+        }
+
+    }
+
+    /**
+     * Requests the OAuth request token.
+     *
+     * @return void 
+     */
+    public function getRequestToken() {
+        
+        try {
+
+            $tokens = $this->OAuth->getRequestToken(self::URI_REQUEST_TOKEN);
+            $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']);
+            return $this->getToken();
+
+        } catch (OAuthException $e) {
+
+            throw new Dropbox_Exception_RequestToken('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.',0,$e);
+
+        }
+
+    }
+
+
+    /**
+     * Requests the OAuth access tokens.
+     *
+     * This method requires the 'unauthorized' request tokens
+     * and, if successful will set the authorized request tokens.
+     * 
+     * @return void 
+     */
+    public function getAccessToken() {
+
+        $uri = self::URI_ACCESS_TOKEN;
+        $tokens = $this->OAuth->getAccessToken($uri);
+        $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']);
+        return $this->getToken();
+
+    }
+
+
+}

vendors/Dropbox/OAuth/Wordpress.php

+<?php
+
+/**
+ * Dropbox OAuth
+ * 
+ * @package Dropbox 
+ * @copyright Copyright (C) 2010 Stefan Motz
+ * @author Stefan Motz (http://www.multimediamotz.de/)
+ * @license MIT
+ */
+
+/**
+ * This class is used to sign all requests to dropbox.
+ *
+ * This specific class uses WordPress WP_Http to authenticate.
+ */
+class Dropbox_OAuth_Wordpress extends Dropbox_OAuth {
+
+    /**
+     *
+     * @var string ConsumerKey
+     */
+    protected $consumerKey = null;
+    /**
+     *
+     * @var string ConsumerSecret
+     */
+    protected $consumerSecret = null;
+
+    /**
+     * Constructor
+     * 
+     * @param string $consumerKey 
+     * @param string $consumerSecret