/**
  * Process trackback request.
  */
 function _process()
 {
     // get ID
     global $ID;
     $ID = substr($_SERVER['PATH_INFO'], 1);
     $sourceUri = $_REQUEST['url'];
     if (is_null($this->tools) || !$this->tools->linkbackAllowed()) {
         $this->_printTrackbackError('Trackbacks disabled.');
         return;
     }
     // No POST request? Quit
     if ($_SERVER['REQUEST_METHOD'] != 'POST') {
         $this->_printTrackbackError('Trackback was not received via HTTP POST.');
         return;
     }
     // Given URL is not an url? Quit
     if (!preg_match("#^([a-z0-9\\-\\.+]+?)://.*#i", $sourceUri)) {
         $this->_printTrackbackError('Given trackback URL is not an URL.');
         return;
     }
     // Source does not exist? Quit
     $http = new DokuHTTPClient();
     $page = $http->get($sourceUri);
     if ($page === false) {
         $this->_printTrackbackError('Linked page cannot be reached');
         return;
     }
     if (!$this->tools->saveLinkback('trackback', strip_tags($_REQUEST['title']), $sourceUri, strip_tags($_REQUEST['excerpt']), $ID)) {
         $this->_printTrackbackError('Trackback already received.');
         return;
     }
     $this->_printTrackbackSuccess();
 }
Example #2
0
 private function get_language_data()
 {
     /* @var $cache door43Cache */
     $cache = $this->getCache();
     $cacheFile = 'langnames.json';
     $langs = $cache->getObject($cacheFile, true);
     // download from api.unfoldingWord.org if needed
     if (empty($langs)) {
         $http = new DokuHTTPClient();
         $raw = $http->get('https://td.unfoldingword.org/exports/langnames.json');
         $langs = json_decode($raw, true);
         $cache->saveString($cacheFile, $raw);
     }
     // if still empty, use the backup copy
     if (empty($langs)) {
         $langs = json_decode(file_get_contents(dirname(__FILE__) . '/lang/langnames.json'), true);
     }
     // $this->LN
     // $this->translations
     $ln = array();
     $translations = '';
     $langDir = array();
     foreach ($langs as $lang) {
         $ln[$lang['lc']] = $lang['ln'];
         $translations .= ' ' . $lang['lc'];
         $langDir[$lang['lc']] = $lang['ld'];
     }
     $cache->saveObject('helperLN.json', $ln);
     $cache->saveObject('languageDirection.json', $langDir);
     $sorted = array_unique(array_filter(explode(' ', $translations)));
     sort($sorted);
     $cache->saveObject('translations.json', $sorted);
 }
Example #3
0
/**
 * Check for new messages from upstream
 *
 * @author Andreas Gohr <*****@*****.**>
 */
function checkUpdateMessages()
{
    global $conf;
    global $INFO;
    global $updateVersion;
    if (!$conf['updatecheck']) {
        return;
    }
    if ($conf['useacl'] && !$INFO['ismanager']) {
        return;
    }
    $cf = $conf['cachedir'] . '/messages.txt';
    $lm = @filemtime($cf);
    // check if new messages needs to be fetched
    if ($lm < time() - 60 * 60 * 24 || $lm < @filemtime(DOKU_INC . DOKU_SCRIPT)) {
        @touch($cf);
        dbglog("checkUpdatesMessages(): downloading messages.txt");
        $http = new DokuHTTPClient();
        $http->timeout = 12;
        $data = $http->get(DOKU_MESSAGEURL . $updateVersion);
        io_saveFile($cf, $data);
    } else {
        dbglog("checkUpdatesMessages(): messages.txt up to date");
        $data = io_readFile($cf);
    }
    // show messages through the usual message mechanism
    $msgs = explode("\n%\n", $data);
    foreach ($msgs as $msg) {
        if ($msg) {
            msg($msg, 2);
        }
    }
}
Example #4
0
/**
 * Check for new messages from upstream
 *
 * @author Andreas Gohr <*****@*****.**>
 */
function checkUpdateMessages()
{
    global $conf;
    global $INFO;
    if (!$conf['updatecheck']) {
        return;
    }
    if ($conf['useacl'] && $INFO['perm'] < AUTH_ADMIN) {
        return;
    }
    $cf = $conf['cachedir'] . '/messages.txt';
    $lm = @filemtime($cf);
    // check if new messages needs to be fetched
    if ($lm < time() - 60 * 60 * 24 || $lm < @filemtime(DOKU_CONF . 'msg')) {
        $num = @file(DOKU_CONF . 'msg');
        $num = is_array($num) ? (int) $num[0] : 0;
        $http = new DokuHTTPClient();
        $http->timeout = 8;
        $data = $http->get(DOKU_MESSAGEURL . $num);
        io_saveFile($cf, $data);
    } else {
        $data = io_readFile($cf);
    }
    // show messages through the usual message mechanism
    $msgs = explode("\n%\n", $data);
    foreach ($msgs as $msg) {
        if ($msg) {
            msg($msg, 2);
        }
    }
}
Example #5
0
 /**
  * @param $sourceUri
  * @param $targetUri
  * @return IXR_Error
  */
 function ping($sourceUri, $targetUri)
 {
     global $ID;
     $ID = substr($_SERVER['PATH_INFO'], 1);
     if (is_null($this->tools) || !$this->tools->linkbackAllowed()) {
         return new IXR_Error(PINGBACK_ERROR_TARGETURI_CANNOT_BE_USED, '');
     }
     // Given URLs are no urls? Quit
     if (!preg_match("#^([a-z0-9\\-\\.+]+?)://.*#i", $sourceUri)) {
         return new IXR_Error(PINGBACK_ERROR_GENERIC, '');
     }
     if (!preg_match("#^([a-z0-9\\-\\.+]+?)://.*#i", $targetUri)) {
         return new IXR_Error(PINGBACK_ERROR_GENERIC, '');
     }
     // Source URL does not exist? Quit
     $http = new DokuHTTPClient();
     $page = $http->get($sourceUri);
     if ($page === false) {
         return new IXR_Error(PINGBACK_ERROR_SOURCEURI_DOES_NOT_EXIST, '');
     }
     // Target URL does not match with request? Quit
     if ($targetUri != wl($ID, '', true)) {
         return new IXR_Error(PINGBACK_ERROR_GENERIC, '');
     }
     // Retrieve data from source
     $linkback = $this->_getTrackbackData($sourceUri, $targetUri, $page);
     // Source URL does not contain link to target? Quit
     if (!$linkback) {
         return new IXR_Error(PINGBACK_ERROR_SOURCEURI_DOES_NOT_CONTAIN_LINK, '');
     }
     if (!$this->tools->saveLinkback('pingback', $linkback['title'], $sourceUri, $linkback['excerpt'], $ID)) {
         return new IXR_Error(PINGBACK_ERROR_PINGBACK_ALREADY_MADE, '');
     }
 }
 public function getInfoByHash($repository_id, $commit_id)
 {
     $gitlabServer = $this->getConf('server');
     $apiToken = $this->getConf('api_token');
     $http = new DokuHTTPClient();
     $reqUrl = $gitlabServer . '/api/v3/projects/' . $repository_id . '/repository/commits/' . $commit_id . '/?private_token=' . $apiToken;
     $data = json_decode($http->get($reqUrl), true);
     return array($data['message'], $data['id']);
 }
 /**
  * Use DokuWiki's HTTP Clients for downloading
  *
  * @param string $url
  * @throws Exception
  * @return string
  */
 protected function _getRemoteData($url)
 {
     $http = new DokuHTTPClient($url);
     $file = $http->get($url);
     if (!$file) {
         throw new Exception('Your server can\'t connect to external resources. Please update the file manually.');
     }
     return $file;
 }
Example #8
0
 public function execute_request()
 {
     global $INPUT;
     // if no contentType was passed, use application/json as the default
     $contentType = $INPUT->str('contentType');
     if (empty($contentType)) {
         $contentType = 'application/json';
     }
     header('Content-Type: ' . $contentType);
     $http = new DokuHTTPClient();
     // Get the list of source languages that are level 3.
     $url = $INPUT->str('requestUrl');
     echo $http->get($url);
 }
 private function _listhd()
 {
     require_once DOKU_INC . 'inc/HTTPClient.php';
     $url = 'https://xkcd.com/rss.xml';
     $ch = new DokuHTTPClient();
     $piece = $ch->get($url);
     $xml = simplexml_load_string($piece);
     $comicURL = $xml->channel->item->link;
     $description = (string) $xml->channel->item->description;
     $description = html_entity_decode($description, ENT_NOQUOTES);
     $feed_contents = $description;
     // Not used anymore because of new xml format
     //$dom = new DOMDocument();
     //$dom->loadXML($description);
     //$imgSrc = $dom->childNodes->item(0)->attributes->getNamedItem('src' )->value;
     //$imgTitle = $dom->childNodes->item(0)->attributes->getNamedItem('title' )->value;
     //$feed_contents = "<a href=\"$comicURL\"><img src=\"$imgSrc\" title=\"$imgTitle\" /></a>\n";
     return $feed_contents;
 }
Example #10
0
/**
 * Check for new messages from upstream
 *
 * @author Andreas Gohr <*****@*****.**>
 */
function checkUpdateMessages()
{
    global $conf;
    global $INFO;
    global $updateVersion;
    if (!$conf['updatecheck']) {
        return;
    }
    if ($conf['useacl'] && !$INFO['ismanager']) {
        return;
    }
    $cf = getCacheName($updateVersion, '.updmsg');
    $lm = @filemtime($cf);
    // check if new messages needs to be fetched
    if ($lm < time() - 60 * 60 * 24 || $lm < @filemtime(DOKU_INC . DOKU_SCRIPT)) {
        @touch($cf);
        dbglog("checkUpdateMessages(): downloading messages to " . $cf);
        $http = new DokuHTTPClient();
        $http->timeout = 12;
        $resp = $http->get(DOKU_MESSAGEURL . $updateVersion);
        if (is_string($resp) && ($resp == "" || substr(trim($resp), -1) == '%')) {
            // basic sanity check that this is either an empty string response (ie "no messages")
            // or it looks like one of our messages, not WiFi login or other interposed response
            io_saveFile($cf, $resp);
        } else {
            dbglog("checkUpdateMessages(): unexpected HTTP response received");
        }
    } else {
        dbglog("checkUpdateMessages(): messages up to date");
    }
    $data = io_readFile($cf);
    // show messages through the usual message mechanism
    $msgs = explode("\n%\n", $data);
    foreach ($msgs as $msg) {
        if ($msg) {
            msg($msg, 2);
        }
    }
}
 * DokuWiki Bootstrap3 Template: User Menu
 *
 * @link     http://dokuwiki.org/template:bootstrap3
 * @author   Giuseppe Di Terlizzi <*****@*****.**>
 * @license  GPL 2 (http://www.gnu.org/licenses/gpl.html)
 */
// must be run from within DokuWiki
if (!defined('DOKU_INC')) {
    die;
}
$gravatar_check = false;
if (bootstrap3_conf('useGravatar')) {
    $HTTP = new DokuHTTPClient();
    $gravatar_img_small = get_gravatar($INFO['userinfo']['mail'], 30);
    $gravatar_img = get_gravatar($INFO['userinfo']['mail'], 64);
    $gravatar_check = $HTTP->get($gravatar_img . '&d=404');
}
if (!empty($_SERVER['REMOTE_USER'])) {
    ?>
<ul class="nav navbar-nav" id="dw__user_menu">
  <li class="dropdown">

    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
      <?php 
    if ($gravatar_check) {
        ?>
        <img src="<?php 
        echo $gravatar_img_small;
        ?>
" class="img-circle profile-image" />
      <?php 
Example #12
0
 /**
  * Render the output remotely at plantuml.no-ip.org
  */
 function _remote($data, $in, $out)
 {
     if (!file_exists($in)) {
         dbglog($in, 'No such plantuml input file');
         return false;
     }
     dbglog("remote render image for {$in}");
     $http = new DokuHTTPClient();
     $http->timeout = 30;
     $remote_url = $this->getConf('remote_url');
     // strip trailing "/" if present
     $base_url = preg_replace('/(.+?)\\/$/', '$1', $remote_url);
     $uml = io_readFile($in);
     $uml = $this->encodep($uml);
     $url = "{$base_url}/img/{$uml}";
     dbglog("image url: {$url}");
     $img = $http->get($url);
     if (!$img) {
         dbglog("download image {$url} failed");
     }
     return $img ? io_saveFile($out, $img) : false;
 }
 /**
  * Get license under which the content is distributed
  */
 function _getWPlicense($wpUrl)
 {
     $url = $wpUrl . 'w/api.php?action=query&meta=siteinfo&siprop=rightsinfo&format=xml';
     // fetch license data from Wikipedia
     $http = new DokuHTTPClient();
     $http->agent .= ' (DokuWiki WikipediaSnippet Plugin)';
     $data = $http->get($url);
     if (!$data) {
         return false;
     }
     $xml = simplexml_load_string($data, 'SimpleXMLElement');
     if (!$xml) {
         return false;
     }
     $url = $xml->query->rightsinfo['url'];
     $text = $xml->query->rightsinfo['text'];
     return '<div class="wplicense"><a href="' . $url . '">' . $text . '</a></div>';
 }
 /**
  * Render an external media file
  *
  * @param string $src        full media URL
  * @param string $title      descriptive text
  * @param string $align      left|center|right
  * @param int    $width      width of media in pixel
  * @param int    $height     height of media in pixel
  * @param string $cache      cache|recache|nocache
  * @param string $linking    linkonly|detail|nolink
  * @param bool   $returnonly whether to return odt or write to doc attribute
  */
 function externalmedia($src, $title = NULL, $align = NULL, $width = NULL, $height = NULL, $cache = NULL, $linking = NULL, $returnonly = false)
 {
     list($ext, $mime) = mimetype($src);
     if (substr($mime, 0, 5) == 'image') {
         $tmp_dir = $this->config->getParam('tmpdir') . "/odt";
         $tmp_name = $tmp_dir . "/" . md5($src) . '.' . $ext;
         $final_name = 'Pictures/' . md5($tmp_name) . '.' . $ext;
         if (!$this->docHandler->fileExists($final_name)) {
             $client = new DokuHTTPClient();
             $img = $client->get($src);
             if ($img === FALSE) {
                 $tmp_name = $src;
                 // fallback to a simple link
             } else {
                 if (!is_dir($tmp_dir)) {
                     io_mkdir_p($tmp_dir);
                 }
                 $tmp_img = fopen($tmp_name, "w") or die("Can't create temp file {$tmp_img}");
                 fwrite($tmp_img, $img);
                 fclose($tmp_img);
             }
         }
         if ($returnonly) {
             $ret = $this->_odtAddImage($tmp_name, $width, $height, $align, $title, true);
             if (file_exists($tmp_name)) {
                 unlink($tmp_name);
             }
             return $ret;
         } else {
             $this->_odtAddImage($tmp_name, $width, $height, $align, $title);
             if (file_exists($tmp_name)) {
                 unlink($tmp_name);
             }
         }
     } else {
         if ($returnonly) {
             return $this->externallink($src, $title, true);
         } else {
             $this->externallink($src, $title);
         }
     }
 }
 function Parse($rss_url)
 {
     // Open and load RSS file
     $http = new DokuHTTPClient();
     if ($rss_content = $http->get($rss_url)) {
         // Parse document encoding
         $result['encoding'] = $this->my_preg_match("'encoding=[\\'\"](.*?)[\\'\"]'si", $rss_content);
         // if document codepage is specified, use it
         if ($result['encoding'] != '') {
             $this->rsscp = $result['encoding'];
         } else {
             $this->rsscp = $this->default_cp;
         }
         // This is used in my_preg_match()
         // Parse CHANNEL info
         preg_match("'<channel.*?>(.*?)</channel>'si", $rss_content, $out_channel);
         foreach ($this->channeltags as $channeltag) {
             $temp = $this->my_preg_match("'<{$channeltag}.*?>(.*?)</{$channeltag}>'si", $out_channel[1]);
             if ($temp != '') {
                 $result[$channeltag] = $temp;
             }
             // Set only if not empty
         }
         // If date_format is specified and lastBuildDate is valid
         if ($this->date_format != '' && ($timestamp = strtotime($result['lastBuildDate'])) !== -1) {
             // convert lastBuildDate to specified date format
             $result['lastBuildDate'] = strftime($this->date_format, $timestamp);
         }
         // Parse TEXTINPUT info
         preg_match("'<textinput(|[^>]*[^/])>(.*?)</textinput>'si", $rss_content, $out_textinfo);
         // This a little strange regexp means:
         // Look for tag <textinput> with or without any attributes, but skip truncated version <textinput /> (it's not beggining tag)
         if (isset($out_textinfo[2])) {
             foreach ($this->textinputtags as $textinputtag) {
                 $temp = $this->my_preg_match("'<{$textinputtag}.*?>(.*?)</{$textinputtag}>'si", $out_textinfo[2]);
                 if ($temp != '') {
                     $result['textinput_' . $textinputtag] = $temp;
                 }
                 // Set only if not empty
             }
         }
         // Parse IMAGE info
         preg_match("'<image.*?>(.*?)</image>'si", $rss_content, $out_imageinfo);
         if (isset($out_imageinfo[1])) {
             foreach ($this->imagetags as $imagetag) {
                 $temp = $this->my_preg_match("'<{$imagetag}.*?>(.*?)</{$imagetag}>'si", $out_imageinfo[1]);
                 if ($temp != '') {
                     $result['image_' . $imagetag] = $temp;
                 }
                 // Set only if not empty
             }
         }
         // Parse ITEMS
         preg_match_all("'<item(| .*?)>(.*?)</item>'si", $rss_content, $items);
         $rss_items = $items[2];
         $i = 0;
         $result['items'] = array();
         // create array even if there are no items
         foreach ($rss_items as $rss_item) {
             //check it is this UTF-8
             if ($this->check_utf8(utf8_decode($rss_item))) {
                 $rss_item = $rss_item;
             } else {
                 if ($this->check_utf8($rss_item)) {
                     $rss_item = utf8_decode($rss_item);
                 }
             }
             // If number of items is lower then limit: Parse one item
             if ($i < $this->items_limit || $this->items_limit == 0) {
                 foreach ($this->itemtags as $itemtag) {
                     $temp = $this->my_preg_match("'<{$itemtag}.*?>(.*?)</{$itemtag}>'si", $rss_item);
                     if ($temp != '') {
                         $result['items'][$i][$itemtag] = $temp;
                     }
                     // Set only if not empty
                 }
                 // Strip HTML tags and other bullshit from DESCRIPTION
                 if ($this->stripHTML && $result['items'][$i]['description']) {
                     $result['items'][$i]['description'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['description'])));
                 }
                 // Strip HTML tags and other bullshit from TITLE
                 if ($this->stripHTML && $result['items'][$i]['title']) {
                     $result['items'][$i]['title'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['title'])));
                 }
                 // If date_format is specified and pubDate is valid
                 if ($this->date_format != '' && ($timestamp = strtotime($result['items'][$i]['pubDate'])) !== -1) {
                     // convert pubDate to specified date format
                     $result['items'][$i]['pubDate'] = strftime($this->date_format, $timestamp);
                 }
                 // Item counter
                 $i++;
             }
         }
         $result['items_count'] = $i;
         return $result;
     } else {
         return False;
     }
 }
Example #16
0
/**
 * Download image files
 *
 * @author Andreas Gohr <*****@*****.**>
 */
function media_image_download($url, $file)
{
    global $conf;
    $http = new DokuHTTPClient();
    $http->keep_alive = false;
    // we do single ops here, no need for keep-alive
    $http->max_bodysize = $conf['fetchsize'];
    $http->timeout = 25;
    //max. 25 sec
    $http->header_regexp = '!\\r\\nContent-Type: image/(jpe?g|gif|png)!i';
    $data = $http->get($url);
    if (!$data) {
        return false;
    }
    $fileexists = @file_exists($file);
    $fp = @fopen($file, "w");
    if (!$fp) {
        return false;
    }
    fwrite($fp, $data);
    fclose($fp);
    if (!$fileexists and $conf['fperm']) {
        chmod($file, $conf['fperm']);
    }
    // check if it is really an image
    $info = @getimagesize($file);
    if (!$info) {
        @unlink($file);
        return false;
    }
    return true;
}
Example #17
0
 /**
  * Gets the OBS status of the requested language
  * @param $langCode
  * @return mixed   Returns the status block if successful, otherwise returns null
  */
 private function get_level_status_from_cache($langCode)
 {
     /* @var $cache door43Cache */
     $cache = $this->getCache();
     $cacheFile = 'obs-catalog.json';
     $levels = $cache->getObject($cacheFile, true);
     // download from api.unfoldingWord.org if needed
     if (empty($levels)) {
         $http = new DokuHTTPClient();
         $raw = $http->get('https://api.unfoldingword.org/obs/txt/1/obs-catalog.json');
         $levels = json_decode($raw, true);
         $cache->saveString($cacheFile, $raw);
     }
     // return null if there are still no levels
     if (empty($levels)) {
         return null;
     }
     foreach ($levels as $level) {
         if ($level['language'] == $langCode) {
             if (isset($level['status'])) {
                 return $level['status'];
             }
         }
     }
     return null;
 }
/**
 * downloads a file from the net and saves it
 *
 * if $useAttachment is false,
 * - $file is the full filename to save the file, incl. path
 * - if successful will return true, false otherwise
 *
 * if $useAttachment is true,
 * - $file is the directory where the file should be saved
 * - if successful will return the name used for the saved file, false otherwise
 *
 * @author Andreas Gohr <*****@*****.**>
 * @author Chris Smith <*****@*****.**>
 */
function io_download($url, $file, $useAttachment = false, $defaultName = '', $maxSize = 2097152)
{
    global $conf;
    $http = new DokuHTTPClient();
    $http->max_bodysize = $maxSize;
    $http->timeout = 25;
    //max. 25 sec
    $http->keep_alive = false;
    // we do single ops here, no need for keep-alive
    $data = $http->get($url);
    if (!$data) {
        return false;
    }
    $name = '';
    if ($useAttachment) {
        if (isset($http->resp_headers['content-disposition'])) {
            $content_disposition = $http->resp_headers['content-disposition'];
            $match = array();
            if (is_string($content_disposition) && preg_match('/attachment;\\s*filename\\s*=\\s*"([^"]*)"/i', $content_disposition, $match)) {
                $name = utf8_basename($match[1]);
            }
        }
        if (!$name) {
            if (!$defaultName) {
                return false;
            }
            $name = $defaultName;
        }
        $file = $file . $name;
    }
    $fileexists = @file_exists($file);
    $fp = @fopen($file, "w");
    if (!$fp) {
        return false;
    }
    fwrite($fp, $data);
    fclose($fp);
    if (!$fileexists and $conf['fperm']) {
        chmod($file, $conf['fperm']);
    }
    if ($useAttachment) {
        return $name;
    }
    return true;
}
Example #19
0
 /**
  * Load the iCalendar file from 'url' and parse all
  * events that are within the range
  * from <= eventdate <= from+previewSec
  *
  * @param url HTTP URL of an *.ics file
  * @param from unix timestamp in seconds (may be null)
  * @param to unix timestamp in seconds (may be null)
  * @param previewDays Limit the entries to 30 days in the future	 
  * @param numberOfEntries Number of entries to display
  * @param $sort_descending	 
  * @return an array of entries sorted by their startdate
  */
 function _parseIcs($url, $from, $to, $previewDays, $numberOfEntries, $sort_descending)
 {
     global $conf;
     $http = new DokuHTTPClient();
     if (!$http->get($url)) {
         $this->error = "Could not get '{$url}': " . $http->status;
         return array();
     }
     $content = $http->resp_body;
     $entries = array();
     # If dateformat is set in plugin configuration ('dformat'), then use it.
     # Otherwise fall back to dokuwiki's default dformat from the global /conf/dokuwiki.php.
     $dateFormat = $this->getConf('dformat') ? $this->getConf('dformat') : $conf['dformat'];
     //$timeFormat = $this->getConf('tformat') ? $this->getConf('tformat') : $conf['tformat'];
     # regular expressions for items that we want to extract from the iCalendar file
     $regex_vevent = '/BEGIN:VEVENT(.*?)END:VEVENT/s';
     #split the whole content into VEVENTs
     preg_match_all($regex_vevent, $content, $matches, PREG_PATTERN_ORDER);
     if ($previewDays > 0) {
         $previewSec = $previewDays * 24 * 3600;
     } else {
         $previewSec = -1;
     }
     // loop over VEVENTs and parse out some itmes
     foreach ($matches[1] as $vevent) {
         $entry = parse_vevent($vevent, $dateFormat);
         // if entry is to old then filter it
         if ($from && $entry['endunixdate']) {
             if ($entry['endunixdate'] < $from) {
                 continue;
             }
             if ($previewSec > 0 && $entry['startunixdate'] > time() + $previewSec) {
                 continue;
             }
         }
         // if entry is to new then filter it
         if ($to && $entry['startunixdate']) {
             if ($entry['startunixdate'] > $to) {
                 continue;
             }
         }
         $entries[] = $entry;
     }
     if ($to && $from == null) {
         // sort entries by startunixdate
         usort($entries, 'compareByEndUnixDate');
     } else {
         if ($from) {
             // sort entries by startunixdate
             usort($entries, 'compareByStartUnixDate');
         } else {
             if ($sort_descending) {
                 $entries = array_reverse($entries, true);
             }
         }
     }
     // See if a maximum number of entries was set
     if ($numberOfEntries > 0) {
         $entries = array_slice($entries, 0, $numberOfEntries);
         // Reverse array?
         if ($from && $sort_descending) {
             $entries = array_reverse($entries, true);
         } else {
             if ($to && !$from && !$sort_descending) {
                 $entries = array_reverse($entries, true);
             }
         }
     }
     return $entries;
 }
Example #20
0
 /**
  * Get the remote data of an individual plugin or template
  *
  * @param string $name  The plugin name to get the data for, template names need to be prefix by 'template:'
  * @return array The data or null if nothing was found (possibly no repository access)
  */
 public function getData($name)
 {
     $cache = new cache('##extension_manager##' . $name, '.repo');
     $result = null;
     if (!isset($this->loaded_extensions[$name]) && $this->hasAccess() && !$cache->useCache(array('age' => 3600 * 24))) {
         $this->loaded_extensions[$name] = true;
         $httpclient = new DokuHTTPClient();
         $data = $httpclient->get(EXTENSION_REPOSITORY_API . '?fmt=php&ext[]=' . urlencode($name));
         if ($data !== false) {
             $result = unserialize($data);
             $cache->storeCache(serialize($result[0]));
             return $result[0];
         } else {
             $this->has_access = false;
         }
     }
     if (file_exists($cache->cache)) {
         return unserialize($cache->retrieveCache(false));
     }
     return array();
 }
Example #21
0
 /**
  * Create output
  */
 function render($mode, Doku_Renderer &$renderer, $opt)
 {
     if ($mode == 'metadata') {
         return false;
     }
     // load file data
     if ($opt['file']) {
         if (preg_match('/^https?:\\/\\//i', $opt['file'])) {
             require_once DOKU_INC . 'inc/HTTPClient.php';
             $http = new DokuHTTPClient();
             $opt['content'] = $http->get($opt['file']);
             if ($opt['content'] === false) {
                 $renderer->cdata('Failed to fetch remote CSV data');
                 return true;
             }
         } else {
             $renderer->info['cache'] = false;
             if (auth_quickaclcheck(getNS($opt['file']) . ':*') < AUTH_READ) {
                 $renderer->cdata('Access denied to CSV data');
                 return true;
             } else {
                 $file = mediaFN($opt['file']);
                 $opt['content'] = io_readFile($file);
             }
         }
         // if not valid UTF-8 is given we assume ISO-8859-1
         if (!utf8_check($opt['content'])) {
             $opt['content'] = utf8_encode($opt['content']);
         }
     }
     // check if there is content
     $content =& $opt['content'];
     $content = trim($content);
     if ($content === '') {
         $renderer->cdata('No csv data found');
         return true;
     }
     // Export the csv file
     $targetfile = '';
     $export = $opt['export'];
     if ($export != '') {
         $targetfile = htmlspecialchars(trim($export));
         if (auth_quickaclcheck(getNS($targetfile . ':*')) < AUTH_EDIT) {
             $renderer->cdata('Access denied: Could not create download link.');
             $targetfile = '';
             return true;
         } else {
             $file = mediaFN($targetfile);
             if (file_put_contents($file, $content, LOCK_EX) > 0) {
                 $linkname = $opt['linkname'];
                 if ($linkname == '') {
                     $linkname = 'Download CSV file';
                 }
             } else {
                 $targetfile = '';
                 $renderer->cdata('Failed to write ' . $file . ': Could not create download link.');
                 return true;
             }
         }
     }
     // get the first row - it will define the structure
     $row = $this->csv_explode_row($content, $opt['delim'], $opt['enclosure'], $opt['escape']);
     $maxcol = count($row);
     $line = 0;
     // create the table and start rendering
     $renderer->table_open($maxcol);
     while ($row !== false) {
         // make sure we have enough columns
         $row = array_pad($row, $maxcol, '');
         // render
         $renderer->tablerow_open();
         for ($i = 0; $i < $maxcol;) {
             $span = 1;
             // lookahead to find spanning cells
             if ($opt['span_empty_cols']) {
                 for ($j = $i + 1; $j < $maxcol; $j++) {
                     if ($row[$j] === '') {
                         $span++;
                     } else {
                         break;
                     }
                 }
             }
             // open cell
             if ($line < $opt['hdr_rows'] || $i < $opt['hdr_cols']) {
                 $renderer->tableheader_open($span);
             } else {
                 $renderer->tablecell_open($span);
             }
             // print cell content, call linebreak() for newlines
             $lines = explode("\n", $row[$i]);
             $cnt = count($lines);
             for ($k = 0; $k < $cnt; $k++) {
                 $renderer->cdata($lines[$k]);
                 if ($k < $cnt - 1) {
                     $renderer->linebreak();
                 }
             }
             // close cell
             if ($line < $opt['hdr_rows'] || $i < $opt['hdr_cols']) {
                 $renderer->tableheader_close();
             } else {
                 $renderer->tablecell_close();
             }
             $i += $span;
         }
         $renderer->tablerow_close();
         // get next row
         $row = $this->csv_explode_row($content, $opt['delim'], $opt['enclosure'], $opt['escape']);
         $line++;
     }
     $renderer->table_close();
     if ($targetfile != '') {
         $renderer->internalmedia($targetfile, $linkname);
     }
     return true;
 }
Example #22
0
/**
 * Builds a Google Sitemap of all public pages known to the indexer
 *
 * The map is placed in the root directory named sitemap.xml.gz - This
 * file needs to be writable!
 *
 * @author Andreas Gohr
 * @link   https://www.google.com/webmasters/sitemaps/docs/en/about.html
 */
function runSitemapper()
{
    global $conf;
    print "runSitemapper(): started" . NL;
    if (!$conf['sitemap']) {
        return false;
    }
    if ($conf['compression'] == 'bz2' || $conf['compression'] == 'gz') {
        $sitemap = 'sitemap.xml.gz';
    } else {
        $sitemap = 'sitemap.xml';
    }
    print "runSitemapper(): using {$sitemap}" . NL;
    if (@file_exists(DOKU_INC . $sitemap)) {
        if (!is_writable(DOKU_INC . $sitemap)) {
            return false;
        }
    } else {
        if (!is_writable(DOKU_INC)) {
            return false;
        }
    }
    if (@filesize(DOKU_INC . $sitemap) && @filemtime(DOKU_INC . $sitemap) > time() - $conf['sitemap'] * 60 * 60 * 24) {
        print 'runSitemapper(): Sitemap up to date' . NL;
        return false;
    }
    $pages = file($conf['indexdir'] . '/page.idx');
    print 'runSitemapper(): creating sitemap using ' . count($pages) . ' pages' . NL;
    // build the sitemap
    ob_start();
    print '<?xml version="1.0" encoding="UTF-8"?>' . NL;
    print '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . NL;
    foreach ($pages as $id) {
        $id = trim($id);
        $file = wikiFN($id);
        //skip hidden, non existing and restricted files
        if (isHiddenPage($id)) {
            continue;
        }
        $date = @filemtime($file);
        if (!$date) {
            continue;
        }
        if (auth_aclcheck($id, '', '') < AUTH_READ) {
            continue;
        }
        print '  <url>' . NL;
        print '    <loc>' . wl($id, '', true) . '</loc>' . NL;
        print '    <lastmod>' . date_iso8601($date) . '</lastmod>' . NL;
        print '  </url>' . NL;
    }
    print '</urlset>' . NL;
    $data = ob_get_contents();
    ob_end_clean();
    //save the new sitemap
    io_saveFile(DOKU_INC . $sitemap, $data);
    //ping search engines...
    $http = new DokuHTTPClient();
    $http->timeout = 8;
    //ping google
    print 'runSitemapper(): pinging google' . NL;
    $url = 'http://www.google.com/webmasters/sitemaps/ping?sitemap=';
    $url .= urlencode(DOKU_URL . $sitemap);
    $resp = $http->get($url);
    if ($http->error) {
        print 'runSitemapper(): ' . $http->error . NL;
    }
    print 'runSitemapper(): ' . preg_replace('/[\\n\\r]/', ' ', strip_tags($resp)) . NL;
    //ping yahoo
    print 'runSitemapper(): pinging yahoo' . NL;
    $url = 'http://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid=dokuwiki&url=';
    $url .= urlencode(DOKU_URL . $sitemap);
    $resp = $http->get($url);
    if ($http->error) {
        print 'runSitemapper(): ' . $http->error . NL;
    }
    print 'runSitemapper(): ' . preg_replace('/[\\n\\r]/', ' ', strip_tags($resp)) . NL;
    //ping microsoft
    print 'runSitemapper(): pinging microsoft' . NL;
    $url = 'http://www.bing.com/webmaster/ping.aspx?siteMap=';
    $url .= urlencode(DOKU_URL . $sitemap);
    $resp = $http->get($url);
    if ($http->error) {
        print 'runSitemapper(): ' . $http->error . NL;
    }
    print 'runSitemapper(): ' . preg_replace('/[\\n\\r]/', ' ', strip_tags($resp)) . NL;
    print 'runSitemapper(): finished' . NL;
    return true;
}
Example #23
0
 /**
  * Get url response and check it
  *
  * @author Samuele Tognini <*****@*****.**>
  */
 function _remotequery($url, $tag = true)
 {
     require_once DOKU_INC . 'inc/HTTPClient.php';
     $http = new DokuHTTPClient();
     $http->timeout = 8;
     $data = $http->get($url);
     if ($tag) {
         if ($data === false) {
             msg($this->getLang('conn_err'), -1);
         } else {
             substr($data, 0, 9) === "indexmenu" ? $data = substr($data, 9) : ($data = "");
         }
     }
     return $data;
 }
Example #24
0
/**
 * Run a few sanity checks
 *
 * @author Andreas Gohr <*****@*****.**>
 */
function check()
{
    global $conf;
    global $INFO;
    if ($INFO['isadmin'] || $INFO['ismanager']) {
        msg('DokuWiki version: ' . getVersion(), 1);
    }
    if (version_compare(phpversion(), '5.1.2', '<')) {
        msg('Your PHP version is too old (' . phpversion() . ' vs. 5.1.2+ needed)', -1);
    } else {
        msg('PHP version ' . phpversion(), 1);
    }
    $mem = (int) php_to_byte(ini_get('memory_limit'));
    if ($mem) {
        if ($mem < 16777216) {
            msg('PHP is limited to less than 16MB RAM (' . $mem . ' bytes). Increase memory_limit in php.ini', -1);
        } elseif ($mem < 20971520) {
            msg('PHP is limited to less than 20MB RAM (' . $mem . ' bytes), you might encounter problems with bigger pages. Increase memory_limit in php.ini', -1);
        } elseif ($mem < 33554432) {
            msg('PHP is limited to less than 32MB RAM (' . $mem . ' bytes), but that should be enough in most cases. If not, increase memory_limit in php.ini', 0);
        } else {
            msg('More than 32MB RAM (' . $mem . ' bytes) available.', 1);
        }
    }
    if (is_writable($conf['changelog'])) {
        msg('Changelog is writable', 1);
    } else {
        if (@file_exists($conf['changelog'])) {
            msg('Changelog is not writable', -1);
        }
    }
    if (isset($conf['changelog_old']) && @file_exists($conf['changelog_old'])) {
        msg('Old changelog exists', 0);
    }
    if (@file_exists($conf['changelog'] . '_failed')) {
        msg('Importing old changelog failed', -1);
    } else {
        if (@file_exists($conf['changelog'] . '_importing')) {
            msg('Importing old changelog now.', 0);
        } else {
            if (@file_exists($conf['changelog'] . '_import_ok')) {
                msg('Old changelog imported', 1);
                if (!plugin_isdisabled('importoldchangelog')) {
                    msg('Importoldchangelog plugin not disabled after import', -1);
                }
            }
        }
    }
    if (is_writable($conf['datadir'])) {
        msg('Datadir is writable', 1);
    } else {
        msg('Datadir is not writable', -1);
    }
    if (is_writable($conf['olddir'])) {
        msg('Attic is writable', 1);
    } else {
        msg('Attic is not writable', -1);
    }
    if (is_writable($conf['mediadir'])) {
        msg('Mediadir is writable', 1);
    } else {
        msg('Mediadir is not writable', -1);
    }
    if (is_writable($conf['cachedir'])) {
        msg('Cachedir is writable', 1);
    } else {
        msg('Cachedir is not writable', -1);
    }
    if (is_writable($conf['lockdir'])) {
        msg('Lockdir is writable', 1);
    } else {
        msg('Lockdir is not writable', -1);
    }
    if (is_writable(DOKU_CONF)) {
        msg('conf directory is writable', 1);
    } else {
        msg('conf directory is not writable', -1);
    }
    if ($conf['authtype'] == 'plain') {
        global $config_cascade;
        if (is_writable($config_cascade['plainauth.users']['default'])) {
            msg('conf/users.auth.php is writable', 1);
        } else {
            msg('conf/users.auth.php is not writable', 0);
        }
    }
    if (function_exists('mb_strpos')) {
        if (defined('UTF8_NOMBSTRING')) {
            msg('mb_string extension is available but will not be used', 0);
        } else {
            msg('mb_string extension is available and will be used', 1);
            if (ini_get('mbstring.func_overload') != 0) {
                msg('mb_string function overloading is enabled, this will cause problems and should be disabled', -1);
            }
        }
    } else {
        msg('mb_string extension not available - PHP only replacements will be used', 0);
    }
    if ($conf['allowdebug']) {
        msg('Debugging support is enabled. If you don\'t need it you should set $conf[\'allowdebug\'] = 0', -1);
    } else {
        msg('Debugging support is disabled', 1);
    }
    if ($INFO['userinfo']['name']) {
        msg('You are currently logged in as ' . $_SERVER['REMOTE_USER'] . ' (' . $INFO['userinfo']['name'] . ')', 0);
        msg('You are part of the groups ' . join($INFO['userinfo']['grps'], ', '), 0);
    } else {
        msg('You are currently not logged in', 0);
    }
    msg('Your current permission for this page is ' . $INFO['perm'], 0);
    if (is_writable($INFO['filepath'])) {
        msg('The current page is writable by the webserver', 0);
    } else {
        msg('The current page is not writable by the webserver', 0);
    }
    if ($INFO['writable']) {
        msg('The current page is writable by you', 0);
    } else {
        msg('The current page is not writable by you', 0);
    }
    $check = wl('', '', true) . 'data/_dummy';
    $http = new DokuHTTPClient();
    $http->timeout = 6;
    $res = $http->get($check);
    if (strpos($res, 'data directory') !== false) {
        msg('It seems like the data directory is accessible from the web.
                Make sure this directory is properly protected
                (See <a href="http://www.dokuwiki.org/security">security</a>)', -1);
    } elseif ($http->status == 404 || $http->status == 403) {
        msg('The data directory seems to be properly protected', 1);
    } else {
        msg('Failed to check if the data directory is accessible from the web.
                Make sure this directory is properly protected
                (See <a href="http://www.dokuwiki.org/security">security</a>)', -1);
    }
    // Check for corrupted search index
    $lengths = idx_listIndexLengths();
    $index_corrupted = false;
    foreach ($lengths as $length) {
        if (count(idx_getIndex('w', $length)) != count(idx_getIndex('i', $length))) {
            $index_corrupted = true;
            break;
        }
    }
    foreach (idx_getIndex('metadata', '') as $index) {
        if (count(idx_getIndex($index . '_w', '')) != count(idx_getIndex($index . '_i', ''))) {
            $index_corrupted = true;
            break;
        }
    }
    if ($index_corrupted) {
        msg('The search index is corrupted. It might produce wrong results and most
                probably needs to be rebuilt. See
                <a href="http://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
                for ways to rebuild the search index.', -1);
    } elseif (!empty($lengths)) {
        msg('The search index seems to be working', 1);
    } else {
        msg('The search index is empty. See
                <a href="http://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
                for help on how to fix the search index. If the default indexer
                isn\'t used or the wiki is actually empty this is normal.');
    }
}
Example #25
0
 /**
  * Pings search engines with the sitemap url. Plugins can add or remove 
  * urls to ping using the SITEMAP_PING event.
  * 
  * @author Michael Hamann
  */
 public function pingSearchEngines()
 {
     //ping search engines...
     $http = new DokuHTTPClient();
     $http->timeout = 8;
     $encoded_sitemap_url = urlencode(wl('', array('do' => 'sitemap'), true, '&'));
     $ping_urls = array('google' => 'http://www.google.com/webmasters/sitemaps/ping?sitemap=' . $encoded_sitemap_url, 'yahoo' => 'http://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid=dokuwiki&url=' . $encoded_sitemap_url, 'microsoft' => 'http://www.bing.com/webmaster/ping.aspx?siteMap=' . $encoded_sitemap_url);
     $data = array('ping_urls' => $ping_urls, 'encoded_sitemap_url' => $encoded_sitemap_url);
     $event = new Doku_Event('SITEMAP_PING', $data);
     if ($event->advise_before(true)) {
         foreach ($data['ping_urls'] as $name => $url) {
             dbglog("Sitemapper::PingSearchEngines(): pinging {$name}");
             $resp = $http->get($url);
             if ($http->error) {
                 dbglog("Sitemapper:pingSearchengines(): {$http->error}");
             }
             dbglog('Sitemapper:pingSearchengines(): ' . preg_replace('/[\\n\\r]/', ' ', strip_tags($resp)));
         }
     }
     $event->advise_after();
     return true;
 }
Example #26
0
 function externalmedia($src, $title = NULL, $align = NULL, $width = NULL, $height = NULL, $cache = NULL, $linking = NULL)
 {
     global $conf;
     global $ID;
     list($ext, $mime) = mimetype($src);
     if (substr($mime, 0, 5) == 'image') {
         $tmp_dir = $conf['tmpdir'] . "/odt";
         $tmp_name = $tmp_dir . "/" . md5($src) . '.' . $ext;
         $final_name = 'Pictures/' . md5($tmp_name) . '.' . $ext;
         if (!isset($this->manifest[$final_name])) {
             $client = new DokuHTTPClient();
             $img = $client->get($src);
             if ($img === FALSE) {
                 $tmp_name = $src;
                 // fallback to a simple link
             } else {
                 if (!is_dir($tmp_dir)) {
                     io_mkdir_p($tmp_dir);
                 }
                 $tmp_img = fopen($tmp_name, "w") or die("Can't create temp file {$tmp_img}");
                 fwrite($tmp_img, $img);
                 fclose($tmp_img);
             }
         }
         $this->_odtAddImage($tmp_name, $width, $height, $align, $title);
         if (file_exists($tmp_name)) {
             unlink($tmp_name);
         }
     } else {
         $this->externallink($src, $title);
     }
 }
Example #27
0
/**
 * Run a few sanity checks
 *
 * @author Andreas Gohr <*****@*****.**>
 */
function check()
{
    global $conf;
    global $INFO;
    msg('DokuWiki version: ' . getVersion(), 1);
    if (version_compare(phpversion(), '5.1.2', '<')) {
        msg('Your PHP version is too old (' . phpversion() . ' vs. 5.1.2+ needed)', -1);
    } else {
        msg('PHP version ' . phpversion(), 1);
    }
    $mem = (int) php_to_byte(ini_get('memory_limit'));
    if ($mem) {
        if ($mem < 16777216) {
            msg('PHP is limited to less than 16MB RAM (' . $mem . ' bytes). Increase memory_limit in php.ini', -1);
        } elseif ($mem < 20971520) {
            msg('PHP is limited to less than 20MB RAM (' . $mem . ' bytes), you might encounter problems with bigger pages. Increase memory_limit in php.ini', -1);
        } elseif ($mem < 33554432) {
            msg('PHP is limited to less than 32MB RAM (' . $mem . ' bytes), but that should be enough in most cases. If not, increase memory_limit in php.ini', 0);
        } else {
            msg('More than 32MB RAM (' . $mem . ' bytes) available.', 1);
        }
    }
    if (is_writable($conf['changelog'])) {
        msg('Changelog is writable', 1);
    } else {
        if (@file_exists($conf['changelog'])) {
            msg('Changelog is not writable', -1);
        }
    }
    if (isset($conf['changelog_old']) && @file_exists($conf['changelog_old'])) {
        msg('Old changelog exists', 0);
    }
    if (@file_exists($conf['changelog'] . '_failed')) {
        msg('Importing old changelog failed', -1);
    } else {
        if (@file_exists($conf['changelog'] . '_importing')) {
            msg('Importing old changelog now.', 0);
        } else {
            if (@file_exists($conf['changelog'] . '_import_ok')) {
                msg('Old changelog imported', 1);
                if (!plugin_isdisabled('importoldchangelog')) {
                    msg('Importoldchangelog plugin not disabled after import', -1);
                }
            }
        }
    }
    if (is_writable($conf['datadir'])) {
        msg('Datadir is writable', 1);
    } else {
        msg('Datadir is not writable', -1);
    }
    if (is_writable($conf['olddir'])) {
        msg('Attic is writable', 1);
    } else {
        msg('Attic is not writable', -1);
    }
    if (is_writable($conf['mediadir'])) {
        msg('Mediadir is writable', 1);
    } else {
        msg('Mediadir is not writable', -1);
    }
    if (is_writable($conf['cachedir'])) {
        msg('Cachedir is writable', 1);
    } else {
        msg('Cachedir is not writable', -1);
    }
    if (is_writable($conf['lockdir'])) {
        msg('Lockdir is writable', 1);
    } else {
        msg('Lockdir is not writable', -1);
    }
    if ($conf['authtype'] == 'plain') {
        if (is_writable(DOKU_CONF . 'users.auth.php')) {
            msg('conf/users.auth.php is writable', 1);
        } else {
            msg('conf/users.auth.php is not writable', 0);
        }
    }
    if (function_exists('mb_strpos')) {
        if (defined('UTF8_NOMBSTRING')) {
            msg('mb_string extension is available but will not be used', 0);
        } else {
            msg('mb_string extension is available and will be used', 1);
            if (ini_get('mbstring.func_overload') != 0) {
                msg('mb_string function overloading is enabled, this will cause problems and should be disabled', -1);
            }
        }
    } else {
        msg('mb_string extension not available - PHP only replacements will be used', 0);
    }
    if ($conf['allowdebug']) {
        msg('Debugging support is enabled. If you don\'t need it you should set $conf[\'allowdebug\'] = 0', -1);
    } else {
        msg('Debugging support is disabled', 1);
    }
    if ($INFO['userinfo']['name']) {
        msg('You are currently logged in as ' . $_SERVER['REMOTE_USER'] . ' (' . $INFO['userinfo']['name'] . ')', 0);
        msg('You are part of the groups ' . join($INFO['userinfo']['grps'], ', '), 0);
    } else {
        msg('You are currently not logged in', 0);
    }
    msg('Your current permission for this page is ' . $INFO['perm'], 0);
    if (is_writable($INFO['filepath'])) {
        msg('The current page is writable by the webserver', 0);
    } else {
        msg('The current page is not writable by the webserver', 0);
    }
    if ($INFO['writable']) {
        msg('The current page is writable by you', 0);
    } else {
        msg('The current page is not writable by you', 0);
    }
    require_once DOKU_INC . 'inc/HTTPClient.php';
    $check = wl('', '', true) . 'data/_dummy';
    $http = new DokuHTTPClient();
    $http->timeout = 6;
    $res = $http->get($check);
    if (strpos($res, 'data directory') !== false) {
        msg('It seems like the data directory is accessible from the web.
                Make sure this directory is properly protected
                (See <a href="http://www.dokuwiki.org/security">security</a>)', -1);
    } elseif ($http->status == 404 || $http->status == 403) {
        msg('The data directory seems to be properly protected', 1);
    } else {
        msg('Failed to check if the data directory is accessible from the web.
                Make sure this directory is properly protected
                (See <a href="http://www.dokuwiki.org/security">security</a>)', -1);
    }
}
Example #28
0
 /**
  * Do all the API work, fetch the data, parse it and return it for the renderer
  */
 function handle($match, $state, $pos, &$handler)
 {
     // check type and remove markup
     if (substr($match, 2, 8) == 'wishlist') {
         $match = substr($match, 11, -2);
         $type = 'wishlist';
     } elseif (substr($match, 2, 10) == 'amazonlist') {
         $match = substr($match, 13, -2);
         $type = 'amazonlist';
     } else {
         $match = substr($match, 9, -2);
         $type = 'product';
     }
     list($ctry, $asin) = explode(':', $match, 2);
     // default parameters...
     $params = array('type' => $type, 'imgw' => $this->getConf('imgw'), 'imgh' => $this->getConf('imgh'), 'maxlen' => $this->getConf('maxlen'), 'price' => $this->getConf('showprice'), 'purchased' => $this->getConf('showpurchased'), 'sort' => $this->getConf('sort'));
     // ...can be overridden
     list($asin, $more) = explode(' ', $asin, 2);
     if (preg_match('/(\\d+)x(\\d+)/i', $more, $match)) {
         $params['imgw'] = $match[1];
         $params['imgh'] = $match[2];
     }
     if (preg_match('/=(\\d+)/', $more, $match)) {
         $params['maxlen'] = $match[1];
     }
     if (preg_match('/noprice/i', $more, $match)) {
         $params['price'] = false;
     } elseif (preg_match('/(show)?price/i', $more, $match)) {
         $params['price'] = true;
     }
     if (preg_match('/nopurchased/i', $more, $match)) {
         $params['purchased'] = false;
     } elseif (preg_match('/(show)?purchased/i', $more, $match)) {
         $params['purchased'] = true;
     }
     if (preg_match('/sortprice/i', $more, $match)) {
         $params['sort'] = 'Price';
     } elseif (preg_match('/sortpriority/i', $more, $match)) {
         $params['sort'] = 'Priority';
     } elseif (preg_match('/sortadded/i', $more, $match)) {
         $params['sort'] = 'DateAdded';
     }
     // no country given?
     if (empty($asin)) {
         $asin = $ctry;
         $ctry = 'us';
     }
     // correct country given?
     if (!preg_match('/^(us|uk|jp|de|fr|ca)$/', $ctry)) {
         $ctry = 'us';
     }
     // get partner id
     $partner = $this->getConf('partner_' . $ctry);
     // correct domains
     if ($ctry == 'us') {
         $ctry = 'com';
     }
     if ($ctry == 'uk') {
         $ctry = 'co.uk';
     }
     // basic API parameters
     $opts = array();
     $opts['Service'] = 'AWSECommerceService';
     $opts['AWSAccessKeyId'] = AMAZON_APIKEY;
     $opts['AssociateTag'] = $partner;
     if ($type == 'product') {
         // parameters for querying a single product
         $opts['Operation'] = 'ItemLookup';
         $opts['ResponseGroup'] = 'Medium,OfferSummary';
         if (strlen($asin) < 13) {
             $opts['IdType'] = 'ASIN';
             $opts['ItemId'] = $asin;
         } else {
             $opts['SearchIndex'] = 'Books';
             $opts['IdType'] = 'ISBN';
             $opts['ItemId'] = $asin;
         }
     } else {
         // parameters to query a wishlist
         $opts['Operation'] = 'ListLookup';
         $opts['ResponseGroup'] = 'ListItems,Medium,OfferSummary';
         $opts['ListId'] = $asin;
         $opts['Sort'] = $params['sort'];
         $opts['IsIncludeUniversal'] = 'True';
         $opts['IsOmitPurchasedItems'] = $params['purchased'] ? 'False' : 'True';
         if ($type == 'wishlist') {
             $opts['ListType'] = 'WishList';
         } else {
             $opts['ListType'] = 'Listmania';
         }
     }
     // support paged results
     $result = array();
     $pages = 1;
     for ($page = 1; $page <= $pages; $page++) {
         $opts['ProductPage'] = $page;
         // fetch it
         $http = new DokuHTTPClient();
         $url = $this->_signedRequestURI($ctry, $opts, $this->getConf('publickey'), $this->getConf('privatekey'));
         $xml = $http->get($url);
         if (empty($xml)) {
             if ($http->error) {
                 return $http->error;
             }
             if ($http->status == 403) {
                 return 'Signature check failed, did you set your Access Keys in config?';
             }
             return 'unkown error';
         }
         // parse it
         require_once dirname(__FILE__) . '/XMLParser.php';
         $xmlp = new XMLParser($xml);
         $data = $xmlp->getTree();
         //dbg($data);
         // check for errors and return the item(s)
         if ($type == 'product') {
             // error?
             if ($data['ITEMLOOKUPRESPONSE'][0]['ITEMS'][0]['REQUEST'][0]['ERRORS']) {
                 return $data['ITEMLOOKUPRESPONSE'][0]['ITEMS'][0]['REQUEST'][0]['ERRORS'][0]['ERROR'][0]['MESSAGE'][0]['VALUE'];
             }
             // return item
             $result = array_merge($result, (array) $data['ITEMLOOKUPRESPONSE'][0]['ITEMS'][0]['ITEM']);
         } else {
             // error?
             if ($data['LISTLOOKUPRESPONSE'][0]['LISTS'][0]['REQUEST'][0]['ERRORS']) {
                 return $data['LISTLOOKUPRESPONSE'][0]['LISTS'][0]['REQUEST'][0]['ERRORS'][0]['ERROR'][0]['MESSAGE'][0]['VALUE'];
             }
             // multiple pages?
             $pages = (int) $data['LISTLOOKUPRESPONSE'][0]['LISTS'][0]['LIST'][0]['TOTALPAGES'][0]['VALUE'];
             // return items
             $result = array_merge($result, (array) $data['LISTLOOKUPRESPONSE'][0]['LISTS'][0]['LIST'][0]['LISTITEM']);
         }
     }
     return array($result, $params);
 }
Example #29
0
 /**
  * Download the tarball
  *
  * @return bool
  */
 private function _step_download()
 {
     $this->_say($this->getLang('dl_from'), $this->tgzurl);
     @set_time_limit(120);
     @ignore_user_abort();
     $http = new DokuHTTPClient();
     $http->timeout = 120;
     $data = $http->get($this->tgzurl);
     if (!$data) {
         $this->_warn($http->error);
         $this->_warn($this->getLang('dl_fail'));
         return false;
     }
     if (!io_saveFile($this->tgzfile, $data)) {
         $this->_warn($this->getLang('dl_fail'));
         return false;
     }
     $this->_say($this->getLang('dl_done'), filesize_h(strlen($data)));
     return true;
 }
/**
 * Print some info about the current page
 *
 * @author  Andreas Gohr <*****@*****.**>
 * @author  Giuseppe Di Terlizzi <*****@*****.**>
 *
 * @param   bool $ret return content instead of printing it
 * @return  bool|string
 */
function bootstrap3_pageinfo($ret = false)
{
    global $conf;
    global $lang;
    global $INFO;
    global $ID;
    // return if we are not allowed to view the page
    if (!auth_quickaclcheck($ID)) {
        return false;
    }
    // prepare date and path
    $fn = $INFO['filepath'];
    if (!$conf['fullpath']) {
        if ($INFO['rev']) {
            $fn = str_replace(fullpath($conf['olddir']) . '/', '', $fn);
        } else {
            $fn = str_replace(fullpath($conf['datadir']) . '/', '', $fn);
        }
    }
    $date_format = bootstrap3_conf('pageInfoDateFormat');
    $page_info = bootstrap3_conf('pageInfo');
    $fn = utf8_decodeFN($fn);
    $date = $date_format == 'dformat' ? dformat($INFO['lastmod']) : datetime_h($INFO['lastmod']);
    // print it
    if ($INFO['exists']) {
        $fn_full = $fn;
        if (!in_array('extension', $page_info)) {
            $fn = str_replace(array('.txt.gz', '.txt'), '', $fn);
        }
        $out = '<ul class="list-inline">';
        if (in_array('filename', $page_info)) {
            $out .= sprintf('<li><i class="fa fa-fw fa-file-text-o text-muted"></i> <span title="%s">%s</span></li>', $fn_full, $fn);
        }
        if (in_array('date', $page_info)) {
            $out .= sprintf('<li><i class="fa fa-fw fa-calendar text-muted"></i> %s <span title="%s">%s</span></li>', $lang['lastmod'], dformat($INFO['lastmod']), $date);
        }
        if (in_array('editor', $page_info)) {
            if (isset($INFO['editor'])) {
                $user = editorinfo($INFO['editor']);
                if (bootstrap3_conf('useGravatar')) {
                    global $auth;
                    $user_data = $auth->getUserData($INFO['editor']);
                    $HTTP = new DokuHTTPClient();
                    $gravatar_img = get_gravatar($user_data['mail'], 16);
                    $gravatar_check = $HTTP->get($gravatar_img . '&d=404');
                    if ($gravatar_check) {
                        $user_img = sprintf('<img src="%s" alt="" width="16" class="img-rounded" /> ', $gravatar_img);
                        $user = str_replace(array('iw_user', 'interwiki'), '', $user);
                        $user = $user_img . $user;
                    }
                }
                $out .= sprintf('<li class="text-muted">%s %s</li>', $lang['by'], $user);
            } else {
                $out .= sprintf('<li>(%s)</li>', $lang['external_edit']);
            }
        }
        if ($INFO['locked'] && in_array('locked', $page_info)) {
            $out .= sprintf('<li><i class="fa fa-fw fa-lock text-muted"></i> %s %s</li>', $lang['lockedby'], editorinfo($INFO['locked']));
        }
        $out .= '</ul>';
        if ($ret) {
            return $out;
        } else {
            echo $out;
            return true;
        }
    }
    return false;
}