function do_autosave($formatter, $options) { global $DBInfo; if (session_id() == '') { // ip based if ($DBInfo->user->id == 'Anonymous') { $myid = md5($_SERVER['REMOTE_ADDR'] . '.' . 'MONIWIKI'); // IP based for Anonymous user XXX } else { $myid = md5($DBInfo->user->id . $_SERVER['REMOTE_ADDR'] . '.' . 'MONIWIKI'); } } else { if (0) { if ($_SESSION['_autosave']) { $myid = $_SESSION['_autosave']; } else { $myid = session_id(); $_SESSION['_autosave'] = $myid; } } else { if ($DBInfo->user->id == 'Anonymous') { $myid = md5($_SERVER['REMOTE_ADDR'] . '.' . 'MONIWIKI'); // IP based for Anonymous user XXX } else { $myid = md5($DBInfo->user->id . $_SERVER['REMOTE_ADDR'] . '.' . 'MONIWIKI'); } } } $myid = md5($myid . $formatter->page->name); if (isset($options['section'])) { $myid .= '.' . $options['section']; } // XXX section support $save = new Cache_text('autosave'); if (!empty($options['retrive'])) { $saved = $save->fetch($myid); $os = rtrim($saved); $stamp = $save->mtime($myid); echo $stamp . "\n" . $os; return true; } else { if (!empty($options['remove'])) { $save->remove($myid); echo 'true'; return true; } } $savetext = $options['savetext']; $datestamp = substr($options['datestamp'], 0, 10); // only 10-digits used $savetext = preg_replace("/\r\n|\r/", "\n", $savetext); $savetext = _stripslashes($savetext); if ($save->exists($myid) and $save->mtime($myid) > $datestamp) { echo 'false'; return false; } $save->update($myid, $savetext); echo 'true'; return true; }
function macro_UrlMapping($formatter, $value, $options = array()) { global $DBInfo; #$options['load']=1; $mapping_rule = ''; while (!isset($DBInfo->url_mapping_rule) or $options['init']) { #or $options['load']) { $mappings = array(); $cf = new Cache_text('settings'); $force_init = 0; if ($DBInfo->shared_url_mappings and $cf->mtime('urlmapping') < filemtime($DBInfo->shared_url_mappings)) { $force_init = 1; } if (!empty($formatter->refresh) and $cf->exists('urlmapping') and !$force_init) { $info = $cf->fetch('urlmapping'); $DBInfo->url_mappings = $info['urlmapping']; $DBInfo->url_mapping_rule = $info['urlmappingrule']; break; } $DBInfo->url_mappings = array(); $DBInfo->url_mapping_rule = ''; if (file_exists($DBInfo->shared_url_mappings)) { $map = file($DBInfo->shared_url_mappings); for ($i = 0, $sz = sizeof($map); $i < $sz; $i++) { $line = rtrim($map[$i]); if (!$line || $line[0] == '#' || $line[0] == ' ') { continue; } if (preg_match("/^(http|ftp|mailto):/", $line)) { $url = strtok($line, ' '); $val = strtok(''); $mappings[$url] = trim($val); $mapping_rule .= preg_quote($url, '/') . '|'; } } $mapping_rule = substr($mapping_rule, 0, -1); $DBInfo->url_mappings = array_merge($DBInfo->url_mappings, $mappings); $DBInfo->url_mapping_rule .= $DBInfo->url_mapping_rule ? '|' . $mapping_rule : $mapping_rule; } $mappinginfo = array('urlmapping' => $DBInfo->url_mappings, 'urlmappingrule' => $DBInfo->url_mapping_rule); $cf->update('urlmapping', $mappinginfo); break; } if ($options['init'] or !$DBInfo->url_mappings) { return ''; } $out = array(); foreach ($DBInfo->url_mappings as $k => $v) { if (preg_match('/^(http|ftp|mailto)/', $v)) { $v = '<a href="' . $v . '">' . $v . '</a>'; } $out[] = '<tr><td>' . $k . '</td><td>' . $v . '</td></tr>'; } return "<table class='urlMapping'>\n" . implode("\n", $out) . "</table>\n"; }
function do_trackback($formatter, $options) { global $DBInfo, $_release; $entry = ''; if (!$formatter->page->exists()) { $pos = strrpos($formatter->page->name, '/'); if ($pos > 0) { $entry = substr($formatter->page->name, $pos + 1); $pagename = substr($formatter->page->name, 0, $pos); $page = new WikiPage($pagename); $formatter = new Formatter($page, $options); $options['page'] = $pagename; } else { $options['msg'] = _("Error: Page Not found !"); send_error(1, $options['msg']); } } if (empty($options['url'])) { $anchor = ''; if ($options['value']) { $anchor = '/' . $options['value']; } $formatter->send_header("", $options); if ($DBInfo->use_trackback) { $ping_url = qualifiedUrl($formatter->link_url($formatter->page->urlname . $anchor, "?action=trackback")); } else { $ping_url = _("TrackBack is not activated !"); } $sendping_action = $formatter->link_tag($formatter->page->urlname, "?action=sendping&value={$options['value']}", _("send ping")); $tb_cache = new Cache_text('trackback'); if ($tb_cache->exists($options['page'])) { $formatter->send_title(sprintf(_("TrackBack list of %s"), $options['page']), "", $options); $trackbacks = explode("\n", $tb_cache->fetch($options['page'])); unset($trackbacks[sizeof($trackbacks) - 1]); # trim the last empty line print "<div class='trackback-hint'><b>" . _("TrackBack URL for this page:") . "</b><br />\n{$ping_url}<br /><br />\n"; print "<b>" . _("Send TrackBack Ping to another Blog:") . "</b> {$sendping_action}</div>\n<br />"; foreach ($trackbacks as $trackback) { list($dummy, $entry, $url, $date, $sitename, $title, $excerpt) = explode("\t", $trackback); if ($anchor and '/' . $entry != $anchor) { continue; } $date[10] = " "; # 2003-07-11T12:08:33+09:00 # $time=strtotime($date); $time = strtotime($date); $date = date("@ m-d [h:i a]", $time); print "<div class='blog'>\n"; print "<div class='blog-title'><a href='{$url}'>{$title}</a></div>\n"; print "<div class='blog-user'>Submitted by <a href='{$url}'>{$sitename}</a> {$date}</div>\n"; print "<div class='blog-comment'>{$excerpt}</div>\n</div><br />\n"; } } else { $formatter->send_title(sprintf(_("No TrackBack entry found for %s"), $options['page']), "", $options); print "<div class='trackback-hint'><b>" . _("TrackBack URL for this page:") . "</b><br />\n{$ping_url}<br /><br />\n"; print "<b>" . _("Send TrackBack Ping to another Blog:") . "</b> {$sendping_action}</div>\n"; } $formatter->send_footer("", $options); return; } if (!$DBInfo->use_trackback) { send_error(1, "TrackBack is not enabled"); } if (empty($options['title']) or empty($options['excerpt']) or empty($options['blog_name']) or empty($options['url'])) { send_error(1, "Invalid TrackBack Ping"); } # receivie Trackback ping # strip \n $title = strtr(_stripslashes($options['title']), "\t\n", " \r"); $excerpt = strtr(_stripslashes($options['excerpt']), "\t\n", " \r"); $blog_name = strtr(_stripslashes($options['blog_name']), "\t\n", " \r"); $url = strtr(_stripslashes($options['url']), "\t\n", " \r"); $timestamp = time(); $date = gmdate("Y-m-d\\TH:i:s", $timestamp); $receive = $timestamp . "\t" . $entry . "\t" . $url . "\t" . $date . "\t" . $blog_name . "\t" . $title . "\t" . $excerpt . "\n"; $tb_cache = new Cache_text('trackback'); $old = $tb_cache->fetch($options['page']); $ret = $tb_cache->update($options['page'], $old . $receive, time()); if ($ret === false) { send_error(0, "Can't update Trackback list. Please try again"); } send_error(0, 'Successfully added'); }
function Security_ACL($DB = "") { $this->DB = $DB; # load ACL if (!empty($DB->config_dir)) { $config_dir = $DB->config_dir; } else { $config_dir = dirname(__FILE__) . '/../../config'; } if (!empty($DB->acl_type) and file_exists($config_dir . '/acl.' . $DB->acl_type . '.php')) { $acl_file = $config_dir . '/acl.' . $DB->acl_type . '.php'; } else { $acl_file = $config_dir . '/acl.default.php'; } if (is_readable($acl_file)) { $this->cache = new Cache_text('acl'); $this->aux_cache = new Cache_text('aux_acl'); // merge all acl files $cache = new Cache_text('settings', array('depth' => 0)); $acl_lines = $cache->fetch('acl'); if ($acl_lines === false) { $params = array(); // save dependencies $deps = array($acl_file); $params['deps'] =& $deps; // read ACL files $acl_lines = $this->read_acl($acl_file, $params); $cache->update('acl', $acl_lines, 0, $params); // parse ACL file list($pages, $rules, $group) = $this->parse_acl($acl_lines); // save group definitions $cache->update('acl_group', $group); // save individual acl of all pages foreach ($pages as $pagename => $acl) { $this->cache->update($pagename, $acl, 0, $params); } // save default ACL $cache->update('acl_default', $rules['*']); unset($rules['*']); // make all in one regex for all patthern $tmp = array_keys($rules); $rule = '(' . implode(')|(', $tmp) . ')'; $vals = array_values($rules); $vals['*'] = $rule; $cache->update('acl_rules', $vals); } $this->AUTH_ACL = $acl_lines; $this->default = $cache->fetch('acl_default'); $this->rules = $cache->fetch('acl_rules'); $this->rule = $this->rules['*']; $this->group = $cache->fetch('acl_group'); } else { $this->AUTH_ACL = array('* @ALL allow *'); $this->default = array('@ALL' => array('allow' => array('*'))); $this->rules = null; $this->rule = null; $this->group = null; } $wikimasters = isset($DB->wikimasters) ? $DB->wikimasters : array(); $owners = isset($DB->owners) ? $DB->owners : array(); $this->allowed_users = array_merge($wikimasters, $owners); }
function macro_Rss($formatter, $value) { global $DBInfo; $xml_parser = xml_parser_create(); $rss_parser = new WikiRSSParser(); xml_set_object($xml_parser, $rss_parser); xml_set_element_handler($xml_parser, "startElement", "endElement"); xml_set_character_data_handler($xml_parser, "characterData"); $key = _rawurlencode($value); $cache = new Cache_text("rss"); # reflash rss each 7200 second (60*60*2) if (!$cache->exists($key) or time() > $cache->mtime($key) + 7200) { $fp = @fopen("{$value}", "r"); if (!$fp) { return "[[RSS(ERR: not a valid URL! {$value})]]"; } while ($data = fread($fp, 4096)) { $xml_data .= $data; } fclose($fp); $cache->update($key, $xml_data); } else { $xml_data = $cache->fetch($key); } list($line, $dummy) = explode("\n", $xml_data, 2); preg_match("/\\sencoding=?(\"|')([^'\"]+)/", $line, $match); if ($match) { $charset = strtoupper($match[2]); } else { $charset = 'UTF-8'; } # override $charset for php5 if ((int) phpversion() >= 5) { $charset = 'UTF-8'; } ob_start(); $ret = xml_parse($xml_parser, $xml_data); if (!$ret) { return sprintf("[[RSS(XML error: %s at line %d)]]", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)); } $out = ob_get_contents(); ob_end_clean(); xml_parser_free($xml_parser); # if (strtolower(str_replace("-","",$options['oe'])) == 'euckr') if (function_exists('iconv') and strtoupper($DBInfo->charset) != $charset) { $new = iconv($charset, $DBInfo->charset, $out); if ($new !== false) { return $new; } } return $out; }
function macro_Pull($formatter, $pagename = '', $params = array()) { global $DBInfo; if (empty($pagename)) { $params['retval']['error'] = _("Empty PageName"); return false; } if (empty($DBInfo->pull_url)) { $params['retval']['error'] = _("Empty \$pull_url"); return false; } if (strpos($DBInfo->pull_url, '$PAGE') === false) { $url = $DBInfo->pull_url . _rawurlencode($pagename); } else { $url = preg_replace('/\\$PAGE/', _rawurlencode($pagename), $DBInfo->pull_url); } $url .= '?action=raw'; require_once "lib/HTTPClient.php"; $sz = 0; // set default params $maxage = !empty($DBInfo->pull_maxage) ? (int) $DBInfo->pull_maxage : 60 * 60 * 24 * 7; $timeout = !empty($DBInfo->pull_timeout) ? (int) $DBInfo->pull_timeout : 15; $maxage = (int) $maxage; // check connection $http = new HTTPClient(); $sc = new Cache_text('mirrorinfo'); $error = null; $headers = array(); while ($sc->exists($pagename) and time() < $sc->mtime($pagename) + $maxage) { $info = $sc->fetch($pagename); if ($info == false) { break; } $sz = $info['size']; $etag = $info['etag']; $lastmod = $info['last-modified']; $error = !empty($info['error']) ? $info['error'] : null; // already retrived and found some error if (empty($params['refresh']) and !empty($error)) { return false; } // conditional get $headers['Cache-Control'] = 'maxage=0'; $headers['If-Modified-Since'] = $lastmod; if (empty($DBInfo->pull_no_etag)) { $headers['If-None-Match'] = $etag; } // do not refresh for no error cases if (empty($error)) { unset($params['refresh']); } break; } // get file header $http->nobody = true; if (!empty($headers)) { $http->headers = array_merge($http->headers, $headers); } $http->sendRequest($url, array(), 'GET'); if ($http->status == 304) { // not modified $params['retval']['status'] = 304; return true; } if ($http->status != 200) { $params['retval']['error'] = sprintf(_("Invalid Status %d"), $http->status); $params['retval']['status'] = $http->status; return false; } else { if (!empty($params['check'])) { $params['retval']['status'] = 200; return true; } } if (isset($http->resp_headers['content-length'])) { $sz = $http->resp_headers['content-length']; } $etag = ''; $lastmod = ''; if (isset($http->resp_headers['etag'])) { $etag = $http->resp_headers['etag']; } if (isset($http->resp_headers['last-modified'])) { $lastmod = $http->resp_headers['last-modified']; } $sc->update($pagename, array('size' => $sz, 'etag' => $etag, 'last-modified' => $lastmod)); // size info if (is_numeric($sz)) { $unit = array('Bytes', 'KB', 'MB', 'GB'); $tmp = $sz; for ($i = 0; $i < 4; $i++) { if ($tmp <= 1024) { break; } $tmp = $tmp / 1024; } $hsz = round($tmp, 2) . ' ' . $unit[$i]; } else { $params['retval']['error'] = _("Can't get file size info"); $params['retval']['mimetype'] = $mimetype; return false; } $pagefile = $DBInfo->getPageKey($pagename); $mtime = @strtotime($lastmod); $my_mtime = $formatter->page->mtime(); // not exactly same file. if ($my_mtime != $mtime or abs($mtime - $my_mtime) > 60) { $params['refresh'] = 1; } // force refresh // real fetch job. if (!empty($params['refresh']) or !file_exists($pagefile)) { @unlink($pagefile); $fp = fopen($pagefile, 'w'); if (!is_resource($fp)) { $params['retval']['error'] = sprintf(_("Fail to open %s"), $pagefile); return false; } // retry to get all info $http = new HTTPClient(); $save = ini_get('max_execution_time'); set_time_limit(0); $http->timeout = $timeout; $http->sendRequest($url, array(), 'GET'); set_time_limit($save); if ($http->status != 200) { fclose($fp); unlink($pagefile); // Error found! save error status to the info cache $params['retval']['error'] = !empty($http->error) ? $http->error : sprintf(_("Invalid Status %d"), $http->status); $params['retval']['status'] = $http->status; $params['retval']['etag'] = $etag; $params['retval']['last-modified'] = $lastmod; $params['retval']['size'] = $sz; $sc->update($pagename, array('size' => $sz, 'etag' => $mimetype, 'last-modified' => $lastmod, 'error' => $http->error, 'status' => $params['retval']['status'])); return false; } if (!empty($http->resp_body)) { fwrite($fp, $http->resp_body); } fclose($fp); //$mtime = @strtotime($lastmod); //touch($pagefile, $mtime); // remove PI cache to update $pi = new Cache_text('PI'); $pi->remove($formatter->page->name); // update error status. if (!empty($error)) { $sc->update($pagename, array('size' => $sz, 'etag' => $etag, 'last-modified' => $lastmod)); } $loc = $formatter->link_url($pagename); $loc = preg_replace('/&/', '&', $loc); $formatter->send_header(array('Status: 302', 'Location: ' . $loc), $params); echo 'Successfully fetched'; } else { echo 'Not modified'; } return null; }
function macro_FullSearch($formatter, $value = "", &$opts) { global $DBInfo; $needle = $value; if ($value === true) { $needle = $value = $formatter->page->name; $options['noexpr'] = 1; } else { # for MoinMoin compatibility with [[FullSearch("blah blah")]] #$needle = preg_replace("/^('|\")([^\\1]*)\\1/","\\2",$value); $needle = $value; } // for pagination $offset = ''; if (!empty($opts['offset']) and is_numeric($opts['offset'])) { if ($opts['offset'] > 0) { $offset = $opts['offset']; } } $url = $formatter->link_url($formatter->page->urlname); $fneedle = _html_escape($needle); $tooshort = !empty($DBInfo->fullsearch_tooshort) ? $DBInfo->fullsearch_tooshort : 2; $m1 = _("Display context of search results"); $m2 = _("Search BackLinks only"); $m3 = _("Case-sensitive searching"); $msg = _("Go"); $bchecked = !empty($DBInfo->use_backlinks) ? 'checked="checked"' : ''; $form = <<<EOF <form method='get' action='{$url}'> <input type='hidden' name='action' value='fullsearch' /> <input name='value' size='30' value="{$fneedle}" /> <span class='button'><input type='submit' class='button' value='{$msg}' /></span><br /> <input type='checkbox' name='backlinks' value='1' {$bchecked} />{$m2}<br /> <input type='checkbox' name='context' value='20' />{$m1}<br /> <input type='checkbox' name='case' value='1' />{$m3}<br /> </form> EOF; if (!isset($needle[0]) or !empty($opts['form'])) { # or blah blah $opts['msg'] = _("No search text"); return $form; } $opts['form'] = $form; # XXX $excl = array(); $incl = array(); if (!empty($opts['noexpr'])) { $tmp = preg_split("/\\s+/", $needle); $needle = $value = join('|', $tmp); $raw_needle = implode(' ', $tmp); $needle = preg_quote($needle); } else { if (empty($opts['backlinks'])) { $terms = preg_split('/((?<!\\S)[-+]?"[^"]+?"(?!\\S)|\\S+)/s', $needle, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $common_words = array('the', 'that', 'where', 'what', 'who', 'how', 'too', 'are'); $common = array(); foreach ($terms as $term) { if (trim($term) == '') { continue; } if (preg_match('/^([-+]?)("?)([^\\2]+?)\\2$/', $term, $match)) { $word = str_replace(array('\\', '.', '*'), '', $match[3]); $len = strlen($word); if (!$match[1] and $match[2] != '"') { if ($len < $tooshort or in_array($word, $common_words)) { $common[] = $word; continue; } } if ($match[1] == '-') { $excl[] = $word; } else { $incl[] = $word; } } } $needle = implode('|', $incl); $needle = _preg_search_escape($needle); $raw_needle = implode(' ', $incl); $test = validate_needle($needle); if ($test === false) { // invalid regex $tmp = array_map('preg_quote', $incl); $needle = implode('|', $tmp); } $excl_needle = implode('|', $excl); $test = validate_needle($excl_needle); if ($test2 === false) { // invalid regex $tmp = array_map('preg_quote', $excl); $excl_needle = implode('|', $tmp); } } else { $cneedle = _preg_search_escape($needle); $test = validate_needle($cneedle); if ($test === false) { $needle = preg_quote($needle); } else { $needle = $cneedle; } } } $test3 = trim($needle); if (!isset($test3[0])) { $opts['msg'] = _("Empty expression"); return $form; } # set arena and sid if (!empty($opts['backlinks'])) { $arena = 'backlinks'; } else { if (!empty($opts['keywords'])) { $arena = 'keywords'; } else { $arena = 'fullsearch'; } } if ($arena == 'fullsearch') { $sid = md5($value . 'v' . $offset); } else { $sid = $value; } $delay = !empty($DBInfo->default_delaytime) ? $DBInfo->default_delaytime : 0; # retrieve cache $fc = new Cache_text($arena); if (!$formatter->refresh and $fc->exists($sid)) { $data = $fc->fetch($sid); if (!empty($opts['backlinks'])) { // backlinks are not needed to check it. $hits = $data; // also fetch redirects $r = new Cache_Text('redirects'); $redirects = $r->fetch($sid); } else { if (is_array($data)) { # check cache mtime $cmt = $fc->mtime($sid); # check update or not $dmt = $DBInfo->mtime(); if ($dmt > $cmt + $delay) { # XXX crude method $data = array(); } else { # XXX smart but incomplete method if (isset($data['hits'])) { $hits =& $data['hits']; } else { $hits =& $data; } foreach ($hits as $p => $c) { $mp = $DBInfo->getPage($p); $mt = $mp->mtime(); if ($mt > $cmt + $delay) { $data = array(); break; } } } if (isset($data['searched'])) { extract($data); } else { if (!empty($data)) { $hits = $data; } } } } } $pattern = '/' . $needle . '/'; if (!empty($excl_needle)) { $excl_pattern = '/' . $excl_needle . '/'; } if (!empty($opts['case'])) { $pattern .= "i"; $excl_pattern .= "i"; } if (isset($hits)) { if (in_array($arena, array('backlinks', 'keywords'))) { $test = key($hits); if (is_int($test) and $hits[$test] != -1) { // fix compatible issue for keywords, backlinks $hits = array_flip($hits); foreach ($hits as $k => $v) { $hits[$k] = -1; } reset($hits); } // check invert redirect index if (!empty($redirects)) { $redirects = array_flip($redirects); ksort($redirects); foreach ($redirects as $k => $v) { $hits[$k] = -2; } reset($hits); } } //continue; } else { $hits = array(); set_time_limit(0); if (!empty($opts['backlinks']) and empty($DBInfo->use_backlink_search)) { $hits = array(); } else { if (!empty($opts['keywords']) and empty($DBInfo->use_keyword_search)) { $hits = array(); } else { if (!empty($opts['backlinks'])) { $pages = $DBInfo->getPageLists(); #$opts['context']=-1; # turn off context-matching $cache = new Cache_text("pagelinks"); foreach ($pages as $page_name) { $links = $cache->fetch($page_name); if (is_array($links)) { if (in_array($value, $links)) { $hits[$page_name] = -1; } // ignore count if < 0 } } } else { if (!empty($opts['keywords'])) { $pages = $DBInfo->getPageLists(); $opts['context'] = -1; # turn off context-matching $cache = new Cache_text("keyword"); foreach ($pages as $page_name) { $links = $cache->fetch($page_name); // XXX if (is_array($links)) { if (stristr(implode(' ', $links), $needle)) { $hits[$page_name] = -1; } // ignore count if < 0 } } } else { $params = array(); $ret = array(); $params['ret'] =& $ret; $params['offset'] = $offset; $params['search'] = 1; $params['incl'] = $incl; $params['excl'] = $excl; $pages = $DBInfo->getPageLists($params); // set time_limit $mt = explode(' ', microtime()); $timestamp = $mt[0] + $mt[1]; $j = 0; $time_limit = isset($DBInfo->process_time_limit) ? $DBInfo->process_time_limit : 3; // default 3-seconds $j = 0; while (list($_, $page_name) = each($pages)) { // check time_limit if ($time_limit and $j % 30 == 0) { $mt = explode(' ', microtime()); $now = $mt[0] + $mt[1]; if ($now - $timestamp > $time_limit) { break; } } $j++; $p = new WikiPage($page_name); if (!$p->exists()) { continue; } $body = $p->_get_raw_body(); #$count = count(preg_split($pattern, $body))-1; $count = preg_match_all($pattern, $body, $matches); if ($count) { foreach ($excl as $ex) { if (stristr($body, $ex)) { continue; } } foreach ($incl as $in) { if (!stristr($body, $in)) { continue; } } $hits[$page_name] = $count; } } $searched = $j > 0 ? $j : 0; $offset = !empty($offset) ? $offset + $j : $j; } } } } #krsort($hits); #ksort($hits); $name = array_keys($hits); array_multisort($hits, SORT_DESC, $name, SORT_ASC); if (in_array($arena, array('backlinks', 'keywords'))) { $fc->update($sid, $name); } else { $fc->update($sid, array('hits' => $hits, 'offset' => $offset, 'searched' => $searched)); } } $opts['hits'] = $hits; $opts['hit'] = count($hits); $opts['all'] = $DBInfo->getCounter(); if ($opts['all'] > $searched) { $opts['next'] = $offset; $opts['searched'] = $searched; } if (!empty($opts['call'])) { return $hits; } $out = "<!-- RESULT LIST START -->"; // for search plugin $out .= "<ul class='fullsearchResult'>"; $idx = 1; $checkbox = ''; while (list($page_name, $count) = each($hits)) { $pgname = _html_escape($page_name); if (!empty($opts['checkbox'])) { $checkbox = "<input type='checkbox' name='pagenames[]' value=\"{$pgname}\" />"; } $out .= '<!-- RESULT ITEM START -->'; // for search plugin $out .= '<li>' . $checkbox . $formatter->link_tag(_rawurlencode($page_name), '?action=highlight&value=' . _urlencode($value), $pgname, 'tabindex="' . $idx . '"'); if ($count > 0) { $out .= ' . . . . ' . sprintf($count == 1 ? _("%d match") : _("%d matches"), $count); } else { if ($count == -2) { $out .= " <span class='redirectIcon'><span>" . _("Redirect page") . "</span></span>\n"; } } if (!empty($opts['context']) and $opts['context'] > 0) { # search matching contexts $p = new WikiPage($page_name); if ($p->exists()) { $body = $p->_get_raw_body(); $out .= find_needle($body, $needle, $excl_needle, $opts['context']); } } $out .= "</li>\n"; $out .= '<!-- RESULT ITEM END -->'; // for search plugin $idx++; #if ($idx > 50) break; } $out .= "</ul>\n"; $out .= "<!-- RESULT LIST END -->"; // for search plugin return $out; }
function macro_UploadedFiles($formatter, $value = "", $options = "") { global $DBInfo; $use_preview = $DBInfo->use_preview_uploads ? $DBInfo->use_preview_uploads : 0; $preview_width = 64; #$use_preview=0; $use_admin = 1; $use_fileinfo = 1; $js_tag = 0; $js_script = ''; $uploader = ''; // get user id if (empty($formatter->preview) && empty($options)) { $options = array(); $options['id'] = $DBInfo->user->id; } if (isset($DBInfo->members) and !in_array($options['id'], $DBInfo->members)) { $use_admin = 0; } $iconset = 'gnome'; $icon_dir = $DBInfo->imgs_dir . '/plugin/UploadedFiles/' . $iconset; $args = !empty($DBInfo->uploadedfiles_options) ? explode(',', $DBInfo->uploadedfiles_options) : array(); $nargs = explode(',', $value); if (!empty($nargs)) { $args = array_merge($args, $nargs); } $value = ''; $default_column = 8; $col = (!empty($options['col']) and $options['col'] > 0) ? (int) $options['col'] : $default_column; if (!empty($formatter->preview)) { $js_tag = 1; $use_preview = 1; $uploader = 'UploadForm'; $use_admin = 0; $use_fileinfo = 0; $col = 10000; } else { if (!empty($options['preview'])) { $use_preview = 1; $use_admin = 0; $use_fileinfo = 0; } } if (!empty($options['tag'])) { # javascript tag mode $js_tag = 1; $use_preview = 1; $use_admin = 0; $use_fileinfo = 0; $col = 10000; } if ($use_fileinfo) { $col = 1; } $href_attr = ''; $attr = ''; if (!empty($DBInfo->use_lightbox) and !$js_tag) { $href_attr = ' rel="lightbox[upload]" '; } $nodir = 0; foreach ($args as $arg) { $arg = trim($arg); if (($p = strpos($arg, '=')) !== false) { $k = substr($arg, 0, $p); $v = substr($arg, $p + 1); if ($k == 'preview') { $use_preview = $v; } else { if ($k == 'nodir') { $nodir = $v; } else { if ($k == 'tag') { $js_tag = 1; $use_preview = 1; } } } } else { $value = $arg; } } if (!isset($options['nodir'])) { $options['nodir'] = $nodir; } if (!empty($options['page'])) { $value = $options['page']; } // avoid to set the pagename of the "page,name" as "name" if ($js_tag) { $form = 'editform'; $js_script = <<<EOS <script language="javascript" type="text/javascript"> /*<![CDATA[*/ // based on wikibits.js in the MediaWiki // small fix to use opener in the dokuwiki. function insertTags(tagOpen,tagClose,myText,replaced) { var is_ie = document.selection && document.all; if (document.{$form}) { var txtarea = document.{$form}.savetext; } else { // some alternate form? take the first one we can find var areas = document.getElementsByTagName('textarea'); if (areas.length > 0) { var txtarea = areas[0]; } else if (opener) { // WikiWyg support if (opener.document.{$form} && opener.document.{$form}.savetext) { txtarea = opener.document.{$form}.savetext; } else { txtarea = opener.document.getElementsByTagName('textarea')[0]; } var my=opener.document.getElementById('editor_area'); while (my == null || my.style.display == 'none') { // wikiwyg hack txtarea = opener.document.getElementById('wikiwyg_wikitext_textarea'); // get iframe and check visibility. var myframe = opener.document.getElementsByTagName('iframe')[0]; if (myframe.style.display == 'none' || myframe.parentNode.style.display == 'none') break; var postdata = 'action=markup/ajax&value=' + encodeURIComponent(tagOpen + myText + tagClose); var myhtml=''; myhtml= HTTPPost(self.location, postdata); var mnew = myhtml.replace(/^<div>/i,''); // strip div tag mnew = mnew.replace(/<\\/div>\\s*\$/i,''); // strip div tag if (is_ie) { var range = myframe.contentWindow.document.selection.createRange(); if (range.boundingTop == 2 && range.boundingLeft == 2) return; range.pasteHTML(html); range.collapse(false); range.select(); } else { myframe.contentWindow.document.execCommand('inserthtml', false, mnew + ' '); } return; } } else { return; // XXX } } if(is_ie) { var theSelection = document.selection.createRange().text; txtarea.focus(); if(theSelection.charAt(theSelection.length - 1) == " "){ // exclude ending space char, if any theSelection = theSelection.substring(0, theSelection.length - 1); document.selection.createRange().text = theSelection + tagOpen + myText + tagClose + " "; } else { document.selection.createRange().text = theSelection + tagOpen + myText + tagClose + " "; } } // Mozilla else if(txtarea.selectionStart || txtarea.selectionStart == '0') { \t\t//var replaced = false; \t\tvar startPos = txtarea.selectionStart; \t\tvar endPos = txtarea.selectionEnd; \t\tif (!replaced && endPos-startPos) \t\t\treplaced = true; \t\tvar scrollTop = txtarea.scrollTop; \t\tif (myText.charAt(myText.length - 1) == " ") { // exclude ending space char, if any \t\t\tsubst = tagOpen + myText.substring(0, (myText.length - 1)) + tagClose + " "; \t\t} else { \t\t\tsubst = tagOpen + myText + tagClose; \t\t} \t\ttxtarea.value = txtarea.value.substring(0, startPos) + subst + \t\t\ttxtarea.value.substring(endPos, txtarea.value.length); \t\ttxtarea.focus(); \t\t//set new selection \t\tif (replaced) { \t\t\tvar cPos = startPos+(tagOpen.length+myText.length+tagClose.length); \t\t\ttxtarea.selectionStart = cPos; \t\t\ttxtarea.selectionEnd = cPos; \t\t} else { \t\t\ttxtarea.selectionStart = startPos+tagOpen.length; \t\t\ttxtarea.selectionEnd = startPos+tagOpen.length+myText.length; \t\t}\t \t\ttxtarea.scrollTop = scrollTop; } else { // All others txtarea.value += tagOpen + myText + tagClose + " "; txtarea.focus(); } } /*]]>*/ </script> EOS; } if (!empty($DBInfo->download_action)) { $mydownload = $DBInfo->download_action; } else { $mydownload = 'download'; } $checkbox = 'checkbox'; $needle = "//"; if (!empty($options['download']) || !empty($DBInfo->force_download)) { $force_download = 1; if (!empty($options['download'])) { $mydownload = $options['download']; } } if (!empty($options['needle'])) { $needle = '@' . $options['needle'] . '@i'; } if (!empty($options['checkbox'])) { $checkbox = $options['checkbox']; } if (!in_array('UploadFile', $formatter->actions)) { $formatter->actions[] = 'UploadFile'; } if ($value and $value != 'UploadFile') { $key = $DBInfo->pageToKeyname($value); //if ($force_download or $key != $value) $down_prefix = $formatter->link_url(_rawurlencode($value), "?action={$mydownload}&value="); $dir = $DBInfo->upload_dir . "/{$key}"; } else { $value = $formatter->page->urlname; $key = $DBInfo->pageToKeyname($formatter->page->name); //if ($force_download or $key != $formatter->page->name) $down_prefix = $formatter->link_url($formatter->page->urlname, "?action={$mydownload}&value="); $dir = $DBInfo->upload_dir . "/{$key}"; } // support hashed upload_dir if (!is_dir($dir) and !empty($DBInfo->use_hashed_upload_dir)) { $dir = $DBInfo->upload_dir . '/' . get_hashed_prefix($key) . $key; } if (!empty($force_download) or $key != $value) { $prefix = $down_prefix; } if (!empty($formatter->preview) and $formatter->page->name == $value) { $opener = ''; } else { $opener = $value . ':'; } if ($value != 'UploadFile' and file_exists($dir)) { $handle = opendir($dir); } else { $key = ''; $value = 'UploadFile'; if (!$force_download) { $prefix .= $prefix ? '/' : ''; } $dir = $DBInfo->upload_dir; $handle = opendir($dir); $opener = '/'; } $upfiles = array(); $dirs = array(); $per = !empty($DBInfo->uploadedfiles_per_page) ? $DBInfo->uploadedfiles_per_page : 100; // set nodir option to show only files if (!empty($options['needle']) && !isset($options['nodir'])) { $options['nodir'] = true; } else { if (!isset($options['nodir'])) { $options['nodir'] = false; } } // count files/dirs $count_files = 0; $count_dirs = 0; $uf = new Cache_text('settings'); if (($info = $uf->fetch('uploadedfiles')) !== false) { $count_files = $info['files']; $count_dirs = $info['dirs']; } else { while (($file = readdir($handle)) !== false) { if ($file[0] == '.') { continue; } if (is_dir($dir . "/" . $file)) { $count_dirs++; } else { $count_files++; } } rewinddir($handle); // TTL = 1 day $uf->update('uploadedfiles', array('files' => $count_files, 'dirs' => $count_dirs), 60 * 60 * 24); } // XXX $plink = ''; if (!empty($options['p'])) { $p = $options['p'] ? (int) $options['p'] : 1; } else { $p = 1; } $pfrom = ($p - 1) * $per; $pto = $pfrom + $per; $count = 0; while (($file = readdir($handle)) !== false) { if ($file[0] == '.') { continue; } if ($count >= $pfrom) { if (is_dir($dir . "/" . $file)) { if ($options['nodir']) { continue; } if ($value == 'UploadFile') { $dirs[] = $DBInfo->keyToPagename($file); } } else { if (preg_match($needle, $file) and $count >= $pfrom) { if ($count < $pto) { $upfiles[] = _p_filename($file); } } } } $count++; if ($count >= $pto) { $plink = 1; break; } } closedir($handle); if (!$upfiles and !$dirs) { return "<h3>" . _("No files found") . "</h3>"; } sort($upfiles); sort($dirs); $link = $formatter->link_url($formatter->page->urlname); $out = "<form method='post' action='{$link}'>"; $out .= "<p><input type='hidden' name='action' value='DeleteFile' />\n"; if ($key) { $out .= "<input type='hidden' name='value' value=\"{$value}\" />\n"; } $out .= "</p><table style='border:0px' cellpadding='2' class='info'>\n"; // set colspan to show file informations $c = 1; if ($use_admin) { $c = 2; } if ($c) { $colspan = ' colspan="' . $c . '"'; } if ($use_fileinfo) { $mname = _("File name"); $msize = _("Size"); $mdate = _("Date"); $out .= "<tr><th{$colspan}>{$mname}</th><th>{$msize}</th><th>{$mdate}</th></tr>\n"; $c += 2; } // set colspan again if ($c > 1) { $colspan = ' colspan="' . $c . '"'; } $idx = 1; if ($js_tag) { #$attr=' target="_blank"'; $extra = '&popup=1&tag=1'; } else { $attr = ''; $extra = ''; } // support hashed upload_dir if (!empty($DBInfo->use_hashed_upload_dir)) { $ndirs = array(); foreach ($dirs as $d0) { if (strlen($d0) != 1) { $ndirs[] = $d0; continue; } $handle = opendir($DBInfo->upload_dir . '/' . $d0); if (!is_resource($handle)) { continue; } $pre = $DBInfo->upload_dir . '/' . $d0; while (($d = readdir($handle)) !== false) { if (!is_dir($pre . '/' . $d)) { $ndirs[] = $d0; break; } if ($d[0] == $d0[0]) { $hd = opendir($pre . '/' . $d); if (!is_resource($hd)) { continue; } $pre1 = $pre . '/' . $d; while (($d1 = readdir($hd)) !== false) { if ($d1[0] == '.') { continue; } if (is_dir($pre1 . '/' . $d1)) { $ndirs[] = $d1; } } closedir($hd); } } closedir($handle); } $dirs = $ndirs; sort($dirs); } // count dirs $didx = 0; if (count($dirs)) { $out .= "<tr>"; $didx++; } foreach ($dirs as $file) { $link = $formatter->link_url($file, "?action=uploadedfiles{$extra}", $file, $attr); $key = $DBInfo->pageToKeyname($file); // support hashed upload_dir $pre = ''; if (!empty($DBInfo->use_hashed_upload_dir)) { $pre = get_hashed_prefix($key); if (!is_dir($dir . '/' . $pre . $key)) { $pre = ''; } } $dirname = $dir . '/' . $pre . $key; $date = date("Y-m-d", filemtime($dirname)); $file = _html_escape($file); if ($use_admin) { $out .= "<td class='wiki'><input type='{$checkbox}' name='files[{$idx}]' value=\"{$file}\" /></td>"; } $out .= "<td class='wiki'><a href='{$link}'>{$file}/</a></td>"; if ($use_fileinfo) { $out .= "<td align='right' class='wiki'> </td><td class='wiki'>{$date}</td>"; } if ($didx % $col == 0) { $out .= "</tr>\n<tr>\n"; } $idx++; $didx++; } if (isset($value[0]) and $value != 'UploadFile') { if ($js_tag) { #$attr=' target="_blank"'; $extra = '&popup=1&tag=1'; } if (!empty($options['needle'])) { $extra .= '&q=' . $options['needle']; } $link = $formatter->link_tag('UploadFile', "?action=uploadedfiles&value=top{$extra}", "<img src='" . $icon_dir . "/32/up.png' style='border:0' class='upper' alt='..' />", $attr); $out .= "<tr>"; if ($use_admin) { $out .= "<td class='wiki'> </td>"; } $out .= "<td class='wiki'>{$link}</td>"; if ($use_fileinfo) { $date = date("Y-m-d", filemtime($dir . "/..")); $out .= "<td align='right' class='wiki'> </td><td class='wiki'>{$date}</td>"; } if ($didx % $col == 0) { $out .= "</tr>\n<tr>\n"; } $didx++; } if (!empty($options['needle'])) { $extra .= '&q=' . $options['needle']; } if (isset($options['nodir'])) { $extra .= '&nodir=' . $options['nodir']; } if ($plink) { $plink = $formatter->link_tag('', "?action=uploadedfiles{$extra}&p=" . ($p + 1), _("Next page »"), $attr); } else { if ($p > 1) { $plink = $formatter->link_tag('', "?action=uploadedfiles{$extra}", _("« First page"), $attr); } } if (empty($prefix)) { $prefix = str_replace($DBInfo->upload_dir, $DBInfo->upload_dir_url, $dir) . '/'; } $unit = array('Bytes', 'KB', 'MB', 'GB', 'TB'); $down_mode = strpos($prefix, ';value=') !== false; $mywidth = $preview_width; if (empty($didx)) { // no dirs found. $out .= '<tr>'; } $iidx = $didx; // file index foreach ($upfiles as $file) { $_l_file = _l_filename($file); // force download with some extensions. XXX if ($down_mode or preg_match('/\\.(pl|cgi|py|php.?)$/', $file)) { $link = str_replace(";value=", ";value=" . rawurlencode($file), $down_prefix); } else { $link = $prefix . rawurlencode($file); } // XXX $previewlink = $link; $size = filesize($dir . '/' . $_l_file); if (!empty($use_preview)) { preg_match("/\\.(.{1,4})\$/", $file, $m); $ext = isset($m[1]) ? strtolower($m[1]) : ''; if ($use_preview > 1 and $ext and stristr('gif,png,jpeg,jpg', $ext)) { list($w, $h) = getimagesize($dir . '/' . $file); if ($w <= $preview_width) { $mywidth = $w; } else { $mywidth = $preview_width; } if (file_exists($dir . "/thumbnails/" . $_l_file)) { if ($down_mode) { $previewlink = str_replace('value=', 'value=thumbnails/', $previewlink); } else { $previewlink = $prefix . 'thumbnails/' . rawurlencode($file); } } } } if (!empty($use_fileinfo)) { $i = 0; for (; $i < 4; $i++) { if ($size <= 1024) { #$size= round($size,2).' '.$unit[$i]; break; } $size = $size / 1024; } $size = round($size, 2) . ' ' . $unit[$i]; } $date = date('Y-m-d', filemtime($dir . '/' . $_l_file)); $fname = $file; if ($use_preview or $js_tag) { $tag_open = 'attachment:'; $tag_close = ''; if ($opener != $value) { $tag_open .= $opener; } $alt = "alt='{$tag_open}{$file}{$tag_close}' title='{$file}'"; if ($ext and stristr('gif,png,jpeg,jpg', $ext)) { $fname = "<img src='{$previewlink}' class='icon' width='{$mywidth}' {$alt} />"; $attr .= $href_attr; } else { if (preg_match('/^(wmv|avi|mpeg|mpg|swf|wav|mp3|ogg|midi|mid|mov)$/', $ext)) { $tag_open = '[[Media('; $tag_close = ')]]'; $alt = "{$tag_open}{$file}{$tag_close}"; } else { if (!preg_match('/^(bmp|c|h|java|py|bak|diff|doc|css|php|xml|html|mod|' . 'rpm|deb|pdf|ppt|xls|tgz|gz|bz2|zip)$/', $ext)) { $ext = 'unknown'; } } $fname = "<img src='{$icon_dir}/{$ext}.png' class='icon' {$alt} /><span>{$file}</span>"; } if ($js_tag) { //if (strpos($file,' ')) $tag = "insertTags('{$tag_open}','{$tag_close}','{$file}',true)"; $link = "javascript:{$tag}"; } } $file = _html_escape($file); if ($use_admin) { $out .= "<td class='wiki'><input type='{$checkbox}' name='files[{$idx}]' value=\"{$file}\" /></td>"; } $out .= "<td class='wiki'><a href=\"{$link}\"{$attr}>{$fname}</a></td>"; if ($use_fileinfo) { $out .= "<td align='right' class='wiki'>{$size}</td><td class='wiki'>{$date}</td>"; } if ($iidx % $col == 0) { $out .= "</tr>\n<tr>\n"; } if ($use_admin && $use_fileinfo) { $out .= "<td> </td><td{$colspan}>"; if ($use_admin) { $out .= $dir . '/'; } $out .= "{$file}</td>\n"; $out .= "</tr>\n<tr>"; } $idx++; $iidx++; } $kidx = $iidx - 1; $k = 0; // setup colspan to fill up <tr> with colspaned <td> while ($kidx % $col != 0) { $k += $c; $kidx++; } if ($k > 0) { // fill tr $out .= '<td colspan="' . $k . '"> </td>'; } if (substr($out, -4) == '<tr>') { $out = substr($out, 0, -4); } else { $out .= "</tr>\n"; } $idx--; $msg = sprintf(_("%d files"), $idx); if (count($dirs)) { $msg .= ' / ' . sprintf(_("Total %d files"), $count_files); $msg .= ' / ' . sprintf(_("%d dirs"), $count_dirs); } // colspan for multi column case. if ($col > 1) { $colspan = ' colspan="' . $col * $c . '"'; } $out .= "<tr>"; if ($use_admin && $c > 1) { $out .= "<td> </td>"; } // fill checkbox column $out .= "<th {$colspan}>{$msg}</th></tr>\n"; if ($plink) { $out .= "<tr><th {$colspan}>{$plink}</th></tr>\n"; } $out .= "</table>\n"; if ($use_admin) { if ($DBInfo->security->is_protected("deletefile", $options)) { $out .= '<p>' . _("Password") . ": <input type='password' name='passwd' size='10' /></p>\n"; } $out .= "<p><input type='submit' value='" . _("Delete selected files") . "' /></p>"; } $out .= "</form>\n"; if (!$value and !in_array('UploadFile', $formatter->actions)) { $formatter->actions[] = 'UploadFile'; } if ($uploader and !in_array('UploadedFiles', $formatter->actions)) { $out .= $formatter->macro_repl($uploader); } if ($use_preview) { $class = ' class="fileList preview"'; return $js_script . "<div{$class}>" . $out . "</div>\n"; } return $js_script . $out; }
function macro_Fetch($formatter, $url = '', $params = array()) { global $DBInfo; if (empty($url)) { $params['retval']['error'] = _("Empty URL"); return false; } // check valid url if (!preg_match('@^((ftp|https?)://[^/]+)/@', $url, $m)) { return false; } $siteurl = $m[1]; require_once "lib/HTTPClient.php"; $sz = 0; $allowed = 'png|jpeg|jpg|gif'; if (!empty($DBInfo->fetch_exts)) { $allowed = $DBInfo->fetch_exts; } // urlencode() $url = _urlencode($url); // set default params $maxage = !empty($DBInfo->fetch_maxage) ? (int) $DBInfo->fetch_maxage : 60 * 60 * 24 * 7; $timeout = !empty($DBInfo->fetch_timeout) ? (int) $DBInfo->fetch_timeout : 15; $vartmp_dir = $DBInfo->vartmp_dir; $buffer_size = 2048 * 1024; // default buffer size if (!empty($DBInfo->fetch_buffer_size) and $DBInfo->fetch_buffer_size > 2048 * 1024) { $buffer_size = $DBInfo->fetch_buffer_size; } // set referrer $referer = ''; if (!empty($DBInfo->fetch_referer_re)) { foreach ($DBInfo->fetch_referer_re as $re => $ref) { if (preg_match($re, $url)) { $referer = $ref; break; } } } // default referrer if (empty($referer) and !empty($DBInfo->fetch_referer)) { $referer = $DBInfo->fetch_referer; } // check site available $si = new Cache_text('siteinfo'); if ($si->exists($siteurl)) { if (!empty($params['refresh'])) { $si->remove($siteurl); } else { if (empty($params['refresh']) && ($check = $si->fetch($siteurl)) !== false) { $params['retval']['status'] = $check['status']; $params['retval']['error'] = $check['error']; return false; } } } $sc = new Cache_text('fetchinfo'); $error = null; if (empty($params['refresh']) and $sc->exists($url) and $sc->mtime($url) < time() + $maxage) { $info = $sc->fetch($url); $sz = $info['size']; $mimetype = $info['mimetype']; $error = !empty($info['error']) ? $info['error'] : null; // already retrived and found some error if (empty($params['refresh']) and !empty($error)) { $params['retval']['status'] = $info['status']; $params['retval']['error'] = $error; $params['retval']['mimetype'] = $mimetype; $params['retval']['size'] = $sz; return false; } } else { // check connection $http = new HTTPClient(); // get file header $http->nobody = true; $http->referer = $referer; $http->sendRequest($url, array(), 'GET'); //if ($http->status == 301 || $http->status == 302 ) { // //} if ($http->status != 200) { if ($http->status == 404) { $params['retval']['error'] = '404 File Not Found'; } else { $params['retval']['error'] = !empty($http->error) ? $http->error : sprintf(_("Invalid Status %d"), $http->status); } $params['retval']['status'] = $http->status; // check alive site if ($http->status == -210) { $si->update($siteurl, array('status' => $http->status, 'error' => $params['retval']['error']), 60 * 60 * 24); return false; } $sc->update($url, array('size' => -1, 'mimetype' => '', 'error' => $params['retval']['error'], 'status' => $params['retval']['status']), 60 * 60 * 24 * 3); return false; } if (isset($http->resp_headers['content-length'])) { $sz = $http->resp_headers['content-length']; } if (isset($http->resp_headers['content-type'])) { $mimetype = $http->resp_headers['content-type']; } else { $mimetype = 'application/octet-stream'; } $sc->update($url, array('size' => $sz, 'mimetype' => $mimetype)); } // size info if (is_numeric($sz)) { $unit = array('Bytes', 'KB', 'MB', 'GB'); $tmp = $sz; for ($i = 0; $i < 4; $i++) { if ($tmp <= 1024) { break; } $tmp = $tmp / 1024; } $hsz = round($tmp, 2) . ' ' . $unit[$i]; if (empty($buffer_size) && !empty($DBInfo->fetch_max_size) and $sz > $DBInfo->fetch_max_size) { $params['retval']['error'] = sprintf(_("Too big file size (%s). Please contact WikiMasters to increase \$fetch_max_size"), $hsz); $params['retval']['mimetype'] = $mimetype; return false; } } else { $params['retval']['error'] = _("Can't get file size info"); $params['retval']['mimetype'] = $mimetype; return false; } $is_image = false; if (preg_match('/^image\\/(jpe?g|gif|png)$/', $mimetype, $m)) { $ext = isset($m[1]) ? '.' . $m[1] : ''; $is_image = true; } else { $ext = '.' . get_extension('data/mime.types', $mimetype); } if (!empty($DBInfo->fetch_images_only) and !$is_image) { // always check the content-type $params['retval']['error'] = sprintf(_("Invalid mime-type %s"), $mimetype); $params['retval']['mimetype'] = $mimetype; return false; } if (empty($params['call'])) { if ($is_image) { $img_url = $formatter->link_url('', '?action=fetch&url=' . $url); return '<div class="externalImage"><div><img src="' . $img_url . '">' . '<div><a href="' . $url . '"><span>[' . strtoupper($m[1]) . ' ' . _("external image") . ' (' . $hsz . ')' . ']</span></a></div></div>'; } return $formatter->link_to('?action=fetch&url=' . $url, $mimetype . ' (' . $hsz . ')'); } // cache dir/filename/cache url if (!empty($DBInfo->cache_public_dir) and !empty($DBInfo->cache_public_url)) { $fc = new Cache_text('fetchfile', array('dir' => $DBInfo->cache_public_dir)); $fetchname = $fc->getKey($url); $fetchfile = $DBInfo->cache_public_dir . '/' . $fetchname . $ext; $fetch_url = $DBInfo->cache_public_url . '/' . $fetchname . $ext; } else { $fc = new Cache_text('fetchfile'); $fetchname = $fc->getKey($url); $fetchfile = $fc->cache_dir . '/' . $fetchname; $fetch_url = null; } // real fetch job. if (!empty($params['refresh']) or !file_exists($fetchfile)) { $fp = fopen($fetchfile, 'w'); if (!is_resource($fp)) { $params['retval']['error'] = sprintf(_("Fail to open %s"), $fetchfile); return false; } // retry to get all info $http = new HTTPClient(); if (!empty($buffer_size)) { $http->max_buffer_size = $buffer_size; } $http->vartmp_dir = $vartmp_dir; $save = ini_get('max_execution_time'); set_time_limit(0); $http->timeout = $timeout; $http->referer = $referer; $http->sendRequest($url, array(), 'GET'); set_time_limit($save); if ($http->status != 200) { fclose($fp); unlink($fetchfile); // Error found! save error status to the info cache $params['retval']['status'] = $http->status; $params['retval']['error'] = $http->error; $params['retval']['mimetype'] = $mimetype; $params['retval']['size'] = $sz; $sc->update($url, array('size' => $sz, 'mimetype' => $mimetype, 'error' => $http->error, 'status' => $params['retval']['status'])); return false; } if (!empty($http->resp_body)) { fwrite($fp, $http->resp_body); fclose($fp); } else { fclose($fp); if (!empty($http->resp_body_file) && file_exists($http->resp_body_file)) { copy($http->resp_body_file, $fetchfile); unlink($http->resp_body_file); } } // update error status. if (!empty($error)) { $sc->update($url, array('size' => $sz, 'mimetype' => $mimetype)); } } if (!empty($fetch_url) and !empty($DBInfo->fetch_use_cache_url)) { $formatter->send_header(array('Status: 302', 'Location: ' . $fetch_url)); return null; } if (!empty($params['thumbwidth'])) { // check allowed thumb widths. $thumb_widths = isset($DBInfo->thumb_widths) ? $DBInfo->thumb_widths : array('120', '240', '320', '480', '600', '800', '1024'); $width = 320; // default if (!empty($DBInfo->default_thumb_width)) { $width = $DBInfo->default_thumb_width; } if (!empty($thumb_widths)) { if (in_array($params['thumbwidth'], $thumb_widths)) { $width = $params['thumbwidth']; } else { header("HTTP/1.1 404 Not Found"); echo "Invalid thumbnail width", "<br />", "valid thumb widths are ", implode(', ', $thumb_widths); return; } } else { $width = $params['thumbwidth']; } $thumb_width = $width; $force_thumb = true; } else { // automatically generate thumb images to support low-bandwidth mobile version if (is_mobile()) { $force_thumb = (!isset($params['m']) or $params['m'] == 1); } } // generate thumb file to support low-bandwidth mobile version $thumbfile = ''; while ((!empty($params['thumb']) or $force_thumb) and preg_match('/^image\\/(jpe?g|gif|png)$/', $mimetype)) { if (empty($thumb_width)) { $thumb_width = 320; // default if (!empty($DBInfo->fetch_thumb_width)) { $thumb_width = $DBInfo->fetch_thumb_width; } } $thumbfile = preg_replace('@' . $ext . '$@', '.w' . $thumb_width . $ext, $fetchfile); if (empty($params['refresh']) && file_exists($thumbfile)) { break; } list($w, $h) = getimagesize($fetchfile); if ($w <= $thumb_width) { $thumbfile = $fetchfile; break; } require_once 'lib/mediautils.php'; // generate thumbnail using the gd func or the ImageMagick(convert) resize_image($ext, $fetchfile, $thumbfile, $w, $h, $thumb_width); break; } $down_mode = 'inline'; if (!empty($thumbfile)) { $fetchfile = $thumbfile; } header("Content-Type: {$mimetype}\r\n"); header("Content-Length: " . filesize($fetchfile)); //header("Content-Disposition: $down_mode; ".$fname ); header("Content-Description: MoniWiki PHP Fetch Downloader"); $mtime = filemtime($fetchfile); $lastmod = gmdate("D, d M Y H:i:s", $mtime) . ' GMT'; $etag = md5($lastmod . $url . $thumbfile); header("Last-Modified: " . $lastmod); header('ETag: "' . $etag . '"'); header("Pragma:"); header('Cache-Control: public, max-age=' . $maxage); $need = http_need_cond_request($mtime, $lastmod, $etag); if (!$need) { header('X-Cache-Debug: Cached OK'); header('HTTP/1.0 304 Not Modified'); @ob_end_clean(); return null; } @ob_clean(); $ret = readfile($fetchfile); return null; }
function macro_Play($formatter, $value, $params = array()) { global $DBInfo; static $autoplay = 1; $max_width = 600; $max_height = 400; $default_width = 320; $default_height = 240; // get the macro alias name $macro = 'play'; if (!empty($params['macro_name']) and $params['macro_name'] != 'play') { $macro = $params['macro_name']; } // use alias macro name as [[Youtube()]], [[Vimeo()]] # $media = array(); # preg_match("/^(([^,]+\\s*,?\\s*)+)\$/", $value, $match); if (!$match) { return '[[Play(error!! ' . $value . ')]]'; } $align = ''; // parse arguments height, width, align if (($p = strpos($match[1], ',')) !== false) { $my = explode(',', $match[1]); $my = array_map('trim', $my); for ($i = 0, $sz = count($my); $i < $sz; $i++) { if (strpos($my[$i], '=')) { list($key, $val) = explode('=', $my[$i], 2); $val = trim($val, '"\''); $val = trim($val); if ($key == 'width' and $val > 1) { $width = intval($val); } else { if ($key == 'height' and $val > 1) { $height = intval($val); } else { if ($key == 'align') { if (in_array($val, array('left', 'center', 'right'))) { $align = ' obj' . ucfirst($val); } } else { $media[] = $my[$i]; } } } } else { // multiple files $media[] = $my[$i]; } } } else { $media[] = trim($match[1]); } # set embeded object size $mywidth = !empty($width) ? min($width, $max_width) : null; $myheight = !empty($height) ? min($height, $max_height) : null; $width = !empty($width) ? min($width, $max_width) : $default_width; $height = !empty($height) ? min($height, $max_height) : $default_height; $url = array(); $my_check = 1; for ($i = 0, $sz = count($media); $i < $sz; $i++) { if (!preg_match("/^((https?|ftp|mms|rtsp):)?\\/\\//", $media[$i])) { if ($macro != 'play') { // will be parsed later $url[] = $media[$i]; continue; } $fname = $formatter->macro_repl('Attachment', $media[$i], array('link' => 1)); if ($my_check and !file_exists($fname)) { return $formatter->macro_repl('Attachment', $value); } $my_check = 1; // check only first file. $fname = str_replace($DBInfo->upload_dir, $DBInfo->upload_dir_url, $fname); $url[] = qualifiedUrl(_urlencode($fname)); } else { $url[] = $media[$i]; } } if ($autoplay == 1) { $play = "true"; } else { $play = "false"; } # $use_flashplayer_ok = 0; if ($DBInfo->use_jwmediaplayer) { $use_flashplayer_ok = 1; for ($i = 0, $sz = count($media); $i < $sz; $i++) { // check type of all files if (!preg_match("/(flv|mp3|mp4|swf)\$/i", $media[$i])) { $use_flashplayer_ok = 0; break; } } } if ($use_flashplayer_ok) { # set embed flash size if (($sz = count($media)) == 1 and preg_match("/(ogg|wav|mp3)\$/i", $media[0])) { // only one and a sound file $height = 20; // override the hegiht of the JW MediaPlayer } $swfobject_num = !empty($GLOBALS['swfobject_num']) ? $GLOBALS['swfobject_num'] : 0; $swfobject_script = ''; if (!$swfobject_num) { $swfobject_script = "<script type=\"text/javascript\" src=\"{$DBInfo->url_prefix}/local/js/swfobject.js\"></script>\n"; $num = 1; } else { $num = ++$swfobject_num; } $GLOBALS['swfobject_num'] = $num; if (!$DBInfo->jwmediaplayer_prefix) { $_swf_prefix = qualifiedUrl("{$DBInfo->url_prefix}/local/JWPlayers"); // FIXME } else { $_swf_prefix = $DBInfo->jwmediaplayer_prefix; } $addparam = ''; if ($sz > 1) { $md5sum = md5(implode(':', $media)); if ($DBInfo->cache_public_dir) { $fc = new Cache_text('jwmediaplayer', array('dir' => $DBInfo->cache_public_dir)); $fname = $fc->getKey($md5sum, false); $basename = $DBInfo->cache_public_dir . '/' . $fname; $urlbase = $DBInfo->cache_public_url ? $DBInfo->cache_public_url . '/' . $fname : $DBInfo->url_prefix . '/' . $basename; $playfile = $basename . '.xml'; } else { $cache_dir = $DBInfo->upload_dir . "/VisualTour"; $cache_url = $DBInfo->upload_url ? $DBInfo->upload_url . '/VisualTour' : $DBInfo->url_prefix . '/' . $cache_dir; $basename = $cache_dir . '/' . $md5sum; $urlbase = $cache_url . '/' . $md5sum; $playfile = $basename . '.xml'; } $playlist = $urlbase . '.xml'; $list = array(); for ($i = 0; $i < $sz; $i++) { if (!preg_match("/^((https?|ftp):)?\\/\\//", $url[$i])) { $url = qualifiedUrl($url); } $ext = substr($media[$i], -3, 3); // XXX $list[] = '<title>' . $media[$i] . '</title>' . "\n" . '<location>' . $url[$i] . '</location>' . "\n"; } $tracks = "<track>\n" . implode("</track>\n<track>\n", $list) . "</track>\n"; // UTF-8 FIXME $xml = <<<XML <?xml version="1.0" encoding="UTF-8"?> <playlist version="1" xmlns="http://xspf.org/ns/0/"> <title>XSPF Playlist</title> <info>XSPF Playlist</info> <trackList> {$tracks} </trackList> </playlist> XML; # check cache dir exists or not and make it if (!is_dir(dirname($playfile))) { $om = umask(00); _mkdir_p(dirname($playfile), 0777); umask($om); } if ($formatter->refresh or !file_exists($playfile)) { $fp = fopen($playfile, "w"); fwrite($fp, $xml); fclose($fp); } $displayheight = $height; $height += $sz * 40; // XXX $addparam = "displayheight: '{$displayheight}'"; $filelist = qualifiedUrl($playlist); } else { $filelist = $url[0]; } $jw_script = <<<EOS <p id="mediaplayer{$num}"></p> <script type="text/javascript"> (function() { var params = { allowfullscreen: "true" }; var flashvars = { width: "{$width}", height: "{$height}", // image: "preview.jpg", {$addparam} file: "{$filelist}" }; swfobject.embedSWF("{$_swf_prefix}/mediaplayer.swf","mediaplayer{$num}","{$width}","{$height}","0.0.9", "expressInstall.swf",flashvars,params); })(); </script> EOS; return <<<EOS {$swfobject_script}{$jw_script} EOS; } else { $out = ''; $mysize = ''; if (!empty($mywidth)) { $mysize .= 'width="' . $mywidth . 'px" '; } if (!empty($myheight)) { $mysize .= ' height="' . $myheight . 'px" '; } for ($i = 0, $sz = count($media); $i < $sz; $i++) { $mediainfo = 'External object'; $classid = ''; $objclass = ''; $iframe = ''; $custom = ''; $object_prefered = false; // http://code.google.com/p/google-code-project-hosting-gadgets/source/browse/trunk/video/video.js if ($macro == 'youtube' && preg_match("@^([a-zA-Z0-9_-]+)(?:\\?.*)?\$@", $media[$i], $m) || preg_match("@(?:https?:)?//(?:[a-z-]+[.])?(?:youtube(?:[.][a-z-]+)+|youtu\\.be)/(?:watch[?].*v=|v/|embed/)?([a-z0-9_-]+)\$@i", $media[$i], $m)) { if ($object_prefered) { $movie = "http://www.youtube.com/v/" . $m[1]; $type = 'type="application/x-shockwave-flash"'; $attr = $mysize . 'allowfullscreen="true" allowScriptAccess="always"'; $attr .= ' data="' . $movie . '?version=3' . '"'; $url[$i] = $movie; $params = "<param name='movie' value='{$movie}?version=3'>\n" . "<param name='allowScriptAccess' value='always'>\n" . "<param name='allowFullScreen' value='true'>\n"; } else { $iframe = '//www.youtube.com/embed/' . $m[1]; $attr = 'frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen'; if (empty($mysize)) { $attr .= ' width="500px" height="281px"'; } else { $attr .= ' ' . $mysize; } } $mediainfo = 'Youtube movie'; $objclass = ' youtube'; } else { if (preg_match('@^https?://(?:videofarm|tvpot)\\.daum\\.net/(?:.*?(?:clipid=|vid=|v/))?([a-zA-Z0-9%$]+)@i', $media[$i], $m)) { // like as http://tvpot.daum.net/v/GCpMeZtuBnk%24 if (preg_match('@[0-9]+$@', $m[1])) { // clipid case $aurl = $media[$i]; $clipid = $m[1]; require_once "lib/HTTPClient.php"; // fetch tvpot.daum.net $sc = new Cache_text('daumtvpot'); $maxage = 60 * 60; if (empty($params['refresh']) and $sc->exists($aurl) and $sc->mtime($aurl) < time() + $maxage) { $info = $sc->fetch($aurl); } else { // no cached info found. if ($formatter->_macrocache and empty($params['call'])) { return $formatter->macro_cache_repl('Play', $value); } if (empty($params['call'])) { $formatter->_dynamic_macros['@Play'] = 1; } // try to fetch tvpot.daum.net $http = new HTTPClient(); $save = ini_get('max_execution_time'); set_time_limit(0); $http->timeout = 15; // support proxy if (!empty($DBInfo->proxy_host)) { $http->proxy_host = $DBInfo->proxy_host; if (!empty($DBInfo->proxy_port)) { $http->proxy_port = $DBInfo->proxy_port; } } $http->sendRequest($aurl, array(), 'GET'); set_time_limit($save); if ($http->status != 200) { return '[[Media(' . $aurl . ')]]'; } if (!empty($http->resp_body)) { // search Open Graph url info if (preg_match('@og:url"\\s+content="http://tvpot\\.daum\\.net/v/([^"]+)"@', $http->resp_body, $match)) { $info = array('vid' => $match[1], 'clipid' => $clipid); $sc->update($aurl, $info); } } else { return '[[Media(' . $aurl . ')]]'; } } $m[1] = $info['vid']; } if ($object_prefered) { $classid = "classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000'"; $movie = "http://videofarm.daum.net/controller/player/VodPlayer.swf"; $type = 'type="application/x-shockwave-flash"'; $attr = 'allowfullscreen="true" allowScriptAccess="always" flashvars="vid=' . $m[2] . '&playLoc=undefined"'; if (empty($mysize)) { $attr .= ' width="500px" height="281px"'; } $url[$i] = $movie; $params = "<param name='movie' value='{$movie}'>\n" . "<param name='flashvars' value='vid=" . $m[1] . "&playLoc=undefined'>\n" . "<param name='allowScriptAccess' value='always'>\n" . "<param name='allowFullScreen' value='true'>\n"; } else { $iframe = '//videofarm.daum.net/controller/video/viewer/Video.html?play_loc=tvpot' . '&jsCallback=false&wmode=transparent&vid=' . $m[1] . '&autoplay=false&permitWideScreen=true'; $attr = 'frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen'; if (empty($mysize)) { $attr .= ' width="500px" height="281px"'; } else { $attr .= ' ' . $mysize; } } $mediainfo = 'Daum movie'; $objclass = ' daum'; } else { if ($macro == 'vimeo' && preg_match("@^(\\d+)\$@", $media[$i], $m) || preg_match("@(?:https?:)?//(?:player\\.)?vimeo\\.com\\/(?:video/)?(.*)\$@i", $media[$i], $m)) { if ($object_prefered) { $movie = "https://secure-a.vimeocdn.com/p/flash/moogaloop/5.2.55/moogaloop.swf?v=1.0.0"; $type = 'type="application/x-shockwave-flash"'; $attr = 'allowfullscreen="true" allowScriptAccess="always" flashvars="clip_id=' . $m[1] . '"'; if (empty($mysize)) { $attr .= ' width="500px" height="281px"'; } $url[$i] = $movie; $params = "<param name='movie' value='{$movie}'>\n" . "<param name='flashvars' value='clip_id=" . $m[1] . "'>\n" . "<param name='allowScriptAccess' value='always'>\n" . "<param name='allowFullScreen' value='true'>\n"; } else { $iframe = '//player.vimeo.com/video/' . $m[1] . '?portrait=0&color=333'; $attr = 'frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen'; if (empty($mysize)) { $attr .= ' width="500px" height="281px"'; } else { $attr .= ' ' . $mysize; } } $mediainfo = 'Vimeo movie'; $objclass = ' vimeo'; } else { if (($macro == 'niconico' || $macro == 'nicovideo') && preg_match("@((?:sm|nm)?\\d+)\$@i", $media[$i], $m) || preg_match("@(?:https?://(?:www|dic)\\.(?:nicovideo|nicozon)\\.(?:jp|net)/(?:v|watch)/)?((?:sm|nm)?\\d+)\$@i", $media[$i], $m)) { $custom = '<script type="text/javascript" src="http://ext.nicovideo.jp/thumb_watch/' . $m[1]; $size = ''; $qprefix = '?'; if ($mywidth > 0) { $size .= '?w=' . intval($mywidth); $qprefix = '&'; } if ($myheight > 0) { $size .= $qprefix . 'h=' . intval($myheight); } $custom .= $size; $custom .= '"></script>'; $attr = 'frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen'; $mediainfo = 'Niconico'; $objclass = ' niconico'; } else { if (preg_match("/(wmv|mpeg4|mp4|avi|asf)\$/", $media[$i], $m)) { $classid = "classid='clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95'"; $type = 'type="application/x-mplayer2"'; $attr = $mysize . 'autoplay="' . $play . '"'; $params = "<param name='FileName' value='" . $url[$i] . "' />\n" . "<param name='AutoStart' value='False' />\n" . "<param name='ShowControls' value='True' />"; $mediainfo = strtoupper($m[1]) . ' movie'; } else { if (preg_match("/(wav|mp3|ogg)\$/", $media[$i], $m)) { $classid = "classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B'"; $type = ''; $attr = 'codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="30"'; $attr .= ' autoplay="' . $play . '"'; $params = "<param name='src' value='" . $url[$i] . "'>\n" . "<param name='AutoStart' value='{$play}' />"; $mediainfo = strtoupper($m[1]) . ' sound'; } else { if (preg_match("/swf\$/", $media[$i])) { $type = 'type="application/x-shockwave-flash"'; $classid = "classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'"; $attr = 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0"'; $attr .= ' autoplay="' . $play . '"'; $params = "<param name='movie' value='" . $url[$i] . "' />\n" . "<param name='AutoStart' value='{$play}' />"; } else { if (preg_match("/\\.xap/", $media[$i])) { $type = 'type="application/x-silverlight-2"'; $attr = $mysize . 'data="data:application/x-silverlight,"'; $params = "<param name='source' value='" . $url[$i] . "' />\n"; } } } } } } } } $autoplay = 0; $play = 'false'; if ($iframe) { $out .= <<<IFRAME <div class='externalObject{$objclass}{$align}'><div> <iframe class='external' src="{$iframe}" {$attr}></iframe> <div><a alt='{$myurl}' onclick='javascript:openExternal(this, "inline-block"); return false;'><span>[{$mediainfo}]</span></a></div></div></div> IFRAME; } else { if (isset($custom[0])) { $out .= <<<OBJECT <div class='externalObject{$objclass}'><div> {$custom} <div><a alt='{$myurl}' onclick='javascript:openExternal(this, "inline-block"); return false;'><span>[{$mediainfo}]</span></a></div></div></div> OBJECT; } else { $myurl = $url[$i]; $out .= <<<OBJECT <div class='externalObject{$objclass}'><div> <object class='external' {$classid} {$type} {$attr}> {$params} <param name="AutoRewind" value="True"> <embed {$type} src="{$myurl}" {$attr}></embed> </object> <div><a alt='{$myurl}' onclick='javascript:openExternal(this, "inline-block"); return false;'><span>[{$mediainfo}]</span></a></div></div></div> OBJECT; } } } } if (empty($GLOBALS['js_macro_play'])) { $js = <<<JS <script type='text/javascript'> /*<![CDATA[*/ function openExternal(obj, display) { var el; (el = obj.parentNode.parentNode.firstElementChild) && (el.style.display = display); } /*]]>*/ </script> JS; $formatter->register_javascripts($js); $GLOBALS['js_macro_play'] = 1; } return $out; }
function do_admin($formatter, $options) { global $DBInfo; if (is_array($DBInfo->owners) and in_array($options['id'], $DBInfo->owners) and (is_array($options['pl']) or is_array($options['pr']))) { $formatter->send_header('', $options); $cp = new Cache_text('settings'); $cpl = $cp->fetch('plugins'); $cpr = $cp->fetch('processors'); $out = ''; if (is_array($options['pl']) and is_array($cpl)) { $ad = array_diff($options['pl'], $cpl); $de = array_diff($cpl, $options['pl']); $cp->update('plugins', $options['pl']); $out .= !empty($ad) ? '<h2>' . _("Enabled plugins") . '</h2><ul><li>' . implode("</li>\n<li>", $ad) . '</li></ul>' : ''; $out .= !empty($de) ? '<h2>' . _("Disabled plugins") . '</h2><ul><li>' . implode("</li>\n<li>", $de) . '</li></ul>' : ''; } if (is_array($options['pr']) and is_array($cpr)) { $ad = array_diff($options['pr'], $cpr); $de = array_diff($cpr, $options['pr']); $cp->update('processors', $options['pr']); $out .= !empty($ad) ? '<h2>' . _("Enabled processors") . '</h2><ul><li>' . implode("</li>\n<li>", $ad) . '</li></ul>' : ''; $out .= !empty($de) ? '<h2>' . _("Disabled processors") . '</h2><ul><li>' . implode("</li>\n<li>", $de) . '</li></ul>' : ''; } $options['title'] = _("Plugin/Processor settings are updated"); $formatter->send_title('', '', $options); print $out; $formatter->send_footer('', $options); return; } $options['title'] = _("Enable/disable plugins and processors"); $formatter->send_header('', $options); $formatter->send_title('', '', $options); echo macro_admin($formatter, $options['value'], $options); $formatter->send_footer('', $options); return; }
function processor_xsltproc($formatter, $value) { global $DBInfo; $xsltproc = "xsltproc "; if ($value[0] == '#' and $value[1] == '!') { list($line, $value) = explode("\n", $value, 2); # get parameters list($tag, $args) = explode(" ", $line, 2); } $pagename = $formatter->page->name; $vartmp_dir =& $DBInfo->vartmp_dir; $cache = new Cache_text("docbook"); if (empty($formatter->preview) and empty($formatter->refresh) and $cache->exists($pagename) and $cache->mtime($pagename) > $formatter->page->mtime()) { return $cache->fetch($pagename); } list($line, $body) = explode("\n", $value, 2); $buff = ""; while ($line[0] == '<' and $line[1] == '?' or !$line) { preg_match("/^<\\?xml-stylesheet\\s+href=\"([^\"]+)\"/", $line, $match); if ($match) { if ($DBInfo->hasPage($match[1])) { $line = '<?xml-stylesheet href="' . getcwd() . '/' . $DBInfo->text_dir . '/' . $match[1] . '" type="text/xml"?>'; } $flag = 1; } $buff .= $line . "\n"; list($line, $body) = explode("\n", $body, 2); if (!empty($flag)) { break; } } $src = $buff . $line . "\n" . $body; $tmpf = tempnam($vartmp_dir, "XSLT"); $fp = fopen($tmpf, "w"); fwrite($fp, $src); fclose($fp); $cmd = "{$xsltproc} --xinclude {$tmpf}"; $fp = popen($cmd . $formatter->NULL, "r"); #fwrite($fp,$src); $html = ''; if (is_resource($fp)) { while ($s = fgets($fp, 1024)) { $html .= $s; } pclose($fp); } unlink($tmpf); if (empty($html)) { $src = str_replace("<", "<", $value); $cache->remove($pagename); return "<pre class='code'>{$src}\n</pre>\n"; } if (function_exists("iconv") and strtoupper($DBInfo->charset) != 'UTF-8') { $new = iconv('UTF-8', $DBInfo->charset, $html); if ($new) { $html = $new; } } if (empty($formatter->preview)) { $cache->update($pagename, $html); } return $html; }
function send_header($header = "", $options = array()) { global $DBInfo; $plain = 0; $media = 'media="screen"'; if (isset($options['action'][0]) and $options['action'] == 'print') { $media = ''; } if (empty($options['is_robot']) && isset($this->pi['#redirect'][0]) && !empty($options['pi'])) { $options['value'] = $this->pi['#redirect']; $options['redirect'] = 1; $this->pi['#redirect'] = ''; do_goto($this, $options); return true; } $header = !empty($header) ? $header : (!empty($options['header']) ? $options['header'] : null); if (!empty($header)) { foreach ((array) $header as $head) { $this->header($head); if (preg_match("/^content\\-type: text\\//i", $head)) { $plain = 1; } } } $mtime = isset($options['mtime']) ? $options['mtime'] : $this->page->mtime(); if ($mtime > 0) { $modified = $mtime > 0 ? gmdate('Y-m-d\\TH:i:s', $mtime) . '+00:00' : null; $lastmod = gmdate('D, d M Y H:i:s', $mtime) . ' GMT'; $meta_lastmod = '<meta http-equiv="last-modified" content="' . $lastmod . '" />' . "\n"; } if (is_static_action($options) or !empty($DBInfo->use_conditional_get) and !empty($mtime) and empty($options['nolastmod']) and $this->page->is_static) { $this->header('Last-Modified: ' . $lastmod); $etag = $this->page->etag($options); if (!empty($options['etag'])) { $this->header('ETag: "' . $options['etag'] . '"'); } else { $this->header('ETag: "' . $etag . '"'); } } // custom headers if (!empty($DBInfo->site_headers)) { foreach ((array) $DBInfo->site_headers as $head) { $this->header($head); } } $content_type = isset($DBInfo->content_type[0]) ? $DBInfo->content_type : 'text/html'; $force_charset = ''; if (!empty($DBInfo->force_charset)) { $force_charset = '; charset=' . $DBInfo->charset; } if (!$plain) { $this->header('Content-type: ' . $content_type . $force_charset); } if (!empty($options['action_mode']) and $options['action_mode'] == 'ajax') { return true; } # disabled #$this->header("Vary: Accept-Encoding, Cookie"); #if (strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') and function_exists('ob_gzhandler')) { # ob_start('ob_gzhandler'); # $etag.= '.gzip'; #} if (!empty($options['metatags'])) { $metatags = $options['metatags']; } else { $metatags = $DBInfo->metatags; } if (!empty($options['noindex']) || !empty($this->pi['#noindex']) || (!empty($mtime) and !empty($DBInfo->delayindex) and time() - $mtime < $DBInfo->delayindex)) { // delay indexing like as dokuwiki if (preg_match("/<meta\\s+name=('|\")?robots\\1[^>]+>/i", $metatags)) { $metatags = preg_replace("/<meta\\s+name=('|\")?robots\\1[^>]+>/i", '<meta name="robots" content="noindex,nofollow" />', $metatags); } else { $metatags .= '<meta name="robots" content="noindex,nofollow" />' . "\n"; } } if (isset($DBInfo->metatags_extra)) { $metatags .= $DBInfo->metatags_extra; } $js = !empty($DBInfo->js) ? $DBInfo->js : ''; if (!$plain) { if (isset($options['trail'])) { $this->set_trailer($options['trail'], $this->page->name); } else { if ($DBInfo->origin) { $this->set_origin($this->page->name); } } # find upper page $up_separator = '/'; if (!empty($this->use_namespace)) { $up_separator .= '|\\:'; } $pos = 0; preg_match('@(' . $up_separator . ')@', $this->page->name, $sep); # NameSpace/SubPage or NameSpace:SubNameSpacePage if (isset($sep[1])) { $pos = strrpos($this->page->name, $sep[1]); } if ($pos > 0) { $upper = substr($this->page->urlname, 0, $pos); } else { if ($this->group) { $upper = _urlencode(substr($this->page->name, strlen($this->group))); } } // setup keywords $keywords = ''; if (!empty($this->pi['#keywords'])) { $keywords = _html_escape($this->pi['#keywords']); } else { $keys = array(); $dummy = strip_tags($this->page->title); $keys = explode(' ', $dummy); $keys[] = $dummy; $keys = array_unique($keys); $keywords = implode(', ', $keys); } // add redirects as keywords if (!empty($DBInfo->use_redirects_as_keywords)) { $r = new Cache_Text('redirects'); $redirects = $r->fetch($this->page->name); if ($redirects !== false) { sort($redirects); $keywords .= ', ' . _html_escape(implode(', ', $redirects)); } } // add site specific keywords if (!empty($DBInfo->site_keywords)) { $keywords .= ', ' . $DBInfo->site_keywords; } $keywords = "<meta name=\"keywords\" content=\"{$keywords}\" />\n"; # find sub pages if (empty($options['action']) and !empty($DBInfo->use_subindex)) { $scache = new Cache_text('subpages'); if (!($subs = $scache->exists($this->page->name))) { if (($p = strrpos($this->page->name, '/')) !== false) { $rule = _preg_search_escape(substr($this->page->name, 0, $p)); } else { $rule = _preg_search_escape($this->page->name); } $subs = $DBInfo->getLikePages('^' . $rule . '\\/', 1); if ($subs) { $scache->update($this->page->name, 1); } } if (!empty($subs)) { $subindices = ''; if (empty($DBInfo->use_ajax)) { $subindices = '<div>' . $this->macro_repl('PageList', '', array('subdir' => 1)) . '</div>'; $btncls = 'class="close"'; } else { $btncls = ''; } $this->subindex = "<fieldset id='wikiSubIndex'>" . "<legend title='[+]' {$btncls} onclick='javascript:toggleSubIndex(\"wikiSubIndex\")'></legend>" . $subindices . "</fieldset>\n"; } } if (!empty($options['.title'])) { $options['title'] = $options['.title']; } else { if (empty($options['title'])) { $options['title'] = !empty($this->pi['#title']) ? $this->pi['#title'] : $this->page->title; $options['title'] = _html_escape($options['title']); } else { $options['title'] = strip_tags($options['title']); } } $theme_type = !empty($this->_newtheme) ? $this->_newtheme : ''; if (empty($options['css_url'])) { $options['css_url'] = $DBInfo->css_url; } if (empty($this->pi['#nodtd']) and !isset($options['retstr']) and $theme_type != 2) { if (!empty($this->html5)) { if (is_string($this->html5)) { echo $this->html5; } else { echo '<!DOCTYPE html>', "\n", '<html xmlns="http://www.w3.org/1999/xhtml">', "\n"; } } else { echo $DBInfo->doctype; } } if ($theme_type == 2 or isset($options['retstr'])) { ob_start(); } else { echo "<head>\n"; } echo '<meta http-equiv="Content-Type" content="' . $content_type . ';charset=' . $DBInfo->charset . "\" />\n"; echo <<<JSHEAD <script type="text/javascript"> /*<![CDATA[*/ _url_prefix="{$DBInfo->url_prefix}"; /*]]>*/ </script> JSHEAD; echo $metatags, $js, "\n"; echo $this->get_javascripts(); echo $keywords; if (!empty($meta_lastmod)) { echo $meta_lastmod; } $sitename = !empty($DBInfo->title_sitename) ? $DBInfo->title_sitename : $DBInfo->sitename; if (!empty($DBInfo->title_msgstr)) { $site_title = sprintf($DBInfo->title_msgstr, $sitename, $options['title']); } else { $site_title = $options['title'] . ' - ' . $sitename; } // set OpenGraph information $act = !empty($options['action']) ? strtolower($options['action']) : 'show'; $is_show = $act == 'show'; $is_frontpage = $this->page->name == get_frontpage($DBInfo->lang); if (!$is_frontpage && !empty($DBInfo->frontpages) && in_array($this->page->name, $DBInfo->frontpages)) { $is_frontpage = true; } if (!empty($DBInfo->canonical_url)) { if (($p = strpos($DBInfo->canonical_url, '%s')) !== false) { $page_url = sprintf($DBInfo->canonical_url, $this->page->urlname); } else { $page_url = $DBInfo->canonical_url . $this->page->urlname; } } else { $page_url = qualifiedUrl($this->link_url($this->page->urlname)); } if ($is_show && $this->page->exists()) { $oc = new Cache_text('opengraph'); if ($this->refresh || ($val = $oc->fetch($this->page->name, $this->page->mtime())) === false) { $val = array('description' => '', 'image' => ''); if (!empty($this->pi['#redirect'])) { $desc = '#redirect ' . $this->pi['#redirect']; } else { $raw = $this->page->_get_raw_body(); if (!empty($this->pi['#description'])) { $desc = $this->pi['#description']; } else { $cut_size = 2000; if (!empty($DBInfo->get_description_cut_size)) { $cut_size = $DBInfo->get_description_cut_size; } $cut = mb_strcut($raw, 0, $cut_size, $DBInfo->charset); $desc = get_description($cut); if ($desc !== false) { $desc = mb_strcut($desc, 0, 200, $DBInfo->charset) . '...'; } else { $desc = $this->page->name; } } } $val['description'] = _html_escape($desc); if (!empty($this->pi['#image'])) { if (preg_match('@^(ftp|https?)://@', $this->pi['#image'])) { $page_image = $this->pi['#image']; } else { if (preg_match('@^attachment:("[^"]+"|[^\\s]+)@/', $this->pi['#image'], $m)) { $image = $this->macro_repl('attachment', $m[1], array('link_url' => 1)); if ($image[0] != 'a') { $page_image = $image; } } } } if (empty($page_image)) { // extract the first image $punct = '<>"\'}\\]\\|\\!'; if (preg_match_all('@(?<=\\b)((?:attachment:(?:"[^' . $punct . ']+"|[^\\s' . $punct . '?]+)|' . '(?:https?|ftp)://(?:[^\\s' . $punct . ']+)\\.(?:png|jpe?g|gif)))@', $raw, $m)) { foreach ($m[1] as $img) { if ($img[0] == 'a') { $img = substr($img, 11); // strip attachment: $image = $this->macro_repl('attachment', $img, array('link_url' => 1)); if ($image[0] != 'a' && preg_match('@\\.(png|jpe?g|gif)$@i', $image)) { $page_image = $image; break; } } else { $page_image = $img; break; } } } } if (empty($page_image) && $is_frontpage) { $val['image'] = qualifiedUrl($DBInfo->logo_img); } else { if (!empty($page_image)) { $val['image'] = $page_image; } } $oc->update($this->page->name, $val, time()); } if (empty($this->no_ogp)) { // for OpenGraph echo '<meta property="og:url" content="' . $page_url . '" />', "\n"; echo '<meta property="og:site_name" content="' . $sitename . '" />', "\n"; echo '<meta property="og:title" content="' . $options['title'] . '" />', "\n"; if ($is_frontpage) { echo '<meta property="og:type" content="website" />', "\n"; } else { echo '<meta property="og:type" content="article" />', "\n"; } if (!empty($val['image'])) { echo '<meta property="og:image" content="', $val['image'], '" />', "\n"; } if (!empty($val['description'])) { echo '<meta property="og:description" content="' . $val['description'] . '" />', "\n"; } } // twitter card echo '<meta name="twitter:card" content="summary" />', "\n"; if (!empty($DBInfo->twitter_id)) { echo '<meta name="twitter:site" content="', $DBInfo->twitter_id, '">', "\n"; } echo '<meta name="twitter:domain" content="', $sitename, '" />', "\n"; echo '<meta name="twitter:title" content="', $options['title'], '">', "\n"; echo '<meta name="twitter:url" content="', $page_url, '">', "\n"; if (!empty($val['description'])) { echo '<meta name="twitter:description" content="' . $val['description'] . '" />', "\n"; } if (!empty($val['image'])) { echo '<meta name="twitter:image:src" content="', $val['image'], '" />', "\n"; } // support google sitelinks serachbox if (!empty($DBInfo->use_google_sitelinks)) { if ($is_frontpage) { if (!empty($DBInfo->canonical_url)) { $site_url = $DBInfo->canonical_url; } else { $site_url = qualifiedUrl($this->link_url('')); } echo <<<SITELINK <script type='application/ld+json'> {"@context":"http://schema.org", "@type":"WebSite", "url":"{$site_url}", "name":"{$sitename}", "potentialAction":{ "@type":"SearchAction", "target":"{$site_url}?goto={search_term}", "query-input":"required name=search_term" } } </script> SITELINK; } } echo <<<SCHEMA <script type='application/ld+json'> {"@context":"http://schema.org", "@type":"WebPage", "url":"{$page_url}", "dateModified":"{$modified}", "name":"{$options['title']}" } </script> SCHEMA; if (!empty($val['description'])) { echo '<meta name="description" content="' . $val['description'] . '" />', "\n"; } } echo ' <title>', $site_title, "</title>\n"; echo ' <link rel="canonical" href="', $page_url, '" />', "\n"; # echo '<meta property="og:title" content="'.$options['title'].'" />',"\n"; if (!empty($upper)) { echo ' <link rel="Up" href="', $this->link_url($upper), "\" />\n"; } $raw_url = $this->link_url($this->page->urlname, "?action=raw"); $print_url = $this->link_url($this->page->urlname, "?action=print"); echo ' <link rel="Alternate" title="Wiki Markup" href="', $raw_url, "\" />\n"; echo ' <link rel="Alternate" media="print" title="Print View" href="', $print_url, "\" />\n"; $css_html = ''; if ($options['css_url']) { $stamp = '?' . filemtime(__FILE__); $css_url = _html_escape($options['css_url']); $css_html = ' <link rel="stylesheet" type="text/css" ' . $media . ' href="' . $css_url . "\" />\n"; if (!empty($DBInfo->custom_css) && file_exists($DBInfo->custom_css)) { $css_html .= ' <link rel="stylesheet" media="screen" type="text/css" href="' . $DBInfo->url_prefix . '/' . $DBInfo->custom_css . "{$stamp}\" />\n"; } else { if (file_exists('./css/_user.css')) { $css_html .= ' <link rel="stylesheet" media="screen" type="text/css" href="' . $DBInfo->url_prefix . "/css/_user.css{$stamp}\" />\n"; } } } echo kbd_handler(!empty($options['prefix']) ? $options['prefix'] : ''); if (isset($this->_newtheme) and $this->_newtheme == 2 or isset($options['retstr'])) { $ret = ob_get_contents(); ob_end_clean(); if (isset($options['retstr'])) { $options['retstr'] = $ret; } $this->header_html = $ret; $this->css_html = $css_html; } else { echo $css_html; echo "</head>\n"; } } return true; }
/** * default abuse filter * * @author Won-Kyu Park <*****@*****.**> * @action string action name * @params array parameters */ function abusefilter_default($action, $params = array()) { global $Config, $DBInfo; $members = $DBInfo->members; $user = $DBInfo->user; // ID or IP $id = $params['id']; // do not use abuse filter for members $ismember = $user->is_member; // do not use abuse filter check for $no_abusefilter_groups groups if (!$ismember && !empty($user->groups) && !empty($DBInfo->no_abusefilter_groups)) { foreach ($user->groups as $g) { if (in_array($g, $DBInfo->no_abusefilter_groups)) { return true; } } } if ($ismember) { return true; } // default abusing check paramters // users can edit 10 times within 5-minutes etc. $edit = array('ttl' => 60 * 5, 'create' => 2, 'delete' => 1, 'revert' => 2, 'save' => 10, 'edit' => 10); if (is_array($Config['abusefilter_settings'])) { $edit = array_merge($edit, $Config['abusefilter_settings']); } if (is_integer($Config['abusefilter_settings'])) { // TTL minutes $edit['ttl'] = $Config['abusefilter_settings'] * 60; } $act = strtolower($action); $ec = new Cache_text('abusefilter'); // get editinfo $editinfo = array('add_lines' => 0, 'del_lines' => 0, 'add_chars' => 0, 'del_chars' => 0); if (is_array($params['editinfo'])) { $editinfo = $params['editinfo']; } $info = array('create' => 0, 'delete' => 0, 'revert' => 0, 'save' => 0, 'edit' => 0, 'add_lines' => 0, 'del_lines' => 0, 'add_chars' => 0, 'del_chars' => 0); // prepare to return $ret = array(); $retval = array(); $ret['retval'] =& $retval; if ($ec->exists($id) and ($info = $ec->fetch($id, 0, $ret)) !== false) { if (isset($info['suspended']) and $info['suspended']) { $params['retval']['msg'] = sprintf(_("Abusing detected! You are suspended or blocked.")); return false; } $info['id'] = $id; $info['ip'] = $params['ip']; if ($act == 'save') { $info['add_lines'] += $editinfo['add_lines']; $info['del_lines'] += $editinfo['del_lines']; $info['add_chars'] += $editinfo['add_chars']; $info['del_chars'] += $editinfo['del_chars']; } // check edit count if ($info['edit'] > $edit['edit'] || $info[$act] > $edit[$act]) { $info['suspended'] = true; if ($info[$act] > $edit[$act]) { $myact = $act; } else { $myact = 'edit'; } if ($user->id == 'Anonymous') { $user->info['remote'] = $id; } // save abusing information if (empty($user->info['strike'])) { $user->info['strike'] = 0; } if (empty($user->info['strike_total'])) { $user->info['strike_total'] = 0; } if (empty($user->info['strikeout'])) { $user->info['strikeout'] = 0; } if (empty($user->info['strikeout_total'])) { $user->info['strikeout_total'] = 0; } $user->info['strike_total']++; $user->info['strike']++; if ($user->info['strike'] % 3 == 0) { $user->info['strikeout_total']++; $user->info['strikeout']++; $user->info['strike'] = 0; } // default maxage is 30 mimute $default_maxage = isset($Config['abusefilter_maxage']) ? $Config['abusefilter_maxage'] : 60 * 30; $maxage = $user->info['strike_total'] * $default_maxage; if ($user->info['strikeout'] >= 1) { // 3, 4, 5, 12, 14, 16 days $maxage = $user->info['strike_total'] * $user->info['strikeout'] * $default_maxage * 48; } // 1days if ($user->info['strikeout'] >= 3) { $maxage = $user->info['strike_total'] * $user->info['strikeout'] * $default_maxage * 48 * 2; } // 2days $user->info['addr'] = $id; $DBInfo->udb->saveUser($user); $ec->update($id, $info, $maxage); $y = intval($maxage / (365 * 24 * 60 * 60)); $d = intval($maxage % 3153600 / (24 * 60 * 60)); $h = intval($maxage % 86400 / (60 * 60)); $m = intval($maxage % 3600 / 60); $str = array(); if (!empty($y)) { $str[] = sprintf(_("%s years"), $y); } if (!empty($d)) { $str[] = sprintf(_("%s days"), $d); } if (!empty($h)) { $str[] = sprintf(_("%s houers"), $h); } if (!empty($m)) { $str[] = sprintf(_("%s minutes"), $m); } $params['retval']['msg'] = sprintf(_("Abusing detected! You are blocked to edit pages until %s."), implode(' ', $str)); return false; } $left_ttl = $retval['ttl'] - (time() - $retval['mtime']); $edit['ttl'] = $left_ttl; $info[$act]++; $info['edit']++; } else { $info['id'] = $id; $info['ip'] = $params['ip']; if ($act == 'save') { $info['add_lines'] += $editinfo['add_lines']; $info['del_lines'] += $editinfo['del_lines']; $info['add_chars'] += $editinfo['add_chars']; $info['del_chars'] += $editinfo['del_chars']; } $info[$act]++; $info['edit']++; } $ec->update($id, $info, $edit['ttl']); return true; }
function processor_jade($formatter, $value, $options = array()) { global $DBInfo; $methods = array('html'); # 'jade ' + # "-V %%root-filename%%='%s-x0' " % tmpfile + # "-V %%html-prefix%%='%s-' " % tmpfile + # "-V '(define %use-id-as-filename% #f)' " + # '-t sgml -i html -d %s#html ' % (DEFAULT_DSL) + # ' ' + tmpfile + '.sgml') $pagename = $formatter->page->name; $vartmp_dir =& $DBInfo->vartmp_dir; $cache = new Cache_text("jade"); if (!$formatter->refresh and !$formatter->preview and $cache->exists($pagename) and $cache->mtime($pagename) > $formatter->page->mtime()) { return $cache->fetch($pagename); } $method = "#html"; if ($options and in_array($options['method'], $methods)) { $method = "#" . $options['method']; } $jade = "jade"; # $args= "-V %%root-filename%%='$tmpfile-x0' ". # "-V %%html-prefix%%='$tmpfile-' ". $args = "-V '(define %use-id-as-filename% #f)' " . "-t sgml -i html " . "-V nochunks -o /dev/stdout "; # jade -V nochunks -t sgml -i html vim.sgml -o /dev/stdout if ($value[0] == '#' and $value[1] == '!') { list($line, $value) = explode("\n", $value, 2); # get parameters list($tag, $dummy) = explode(" ", $line, 2); } list($line, $body) = explode("\n", $value, 2); $buff = ""; $dsssl_flag = false; while ($line[0] == '<' or !$line) { preg_match("/^<\\?stylesheet\\s+href=\"([^\"]+)\"/", $line, $match); if ($match) { if ($DBInfo->hasPage($match[1])) { $line = '<?stylesheet href="' . getcwd() . '/' . $DBInfo->text_dir . '/' . $match[1] . $method . '" type="text/dsssl"?>'; } $dsssl_flag = true; break; } $buff .= $line . "\n"; list($line, $body) = explode("\n", $body, 2); } $src = $buff . $line . "\n" . $body; if (!$dsssl_flag and $DBInfo->default_dsssl) { $args .= " -d {$DBInfo->default_dsssl}"; } if (strtolower($DBInfo->charset) == 'utf-8') { if ($DBInfo->docbook_xmldcl) { $args .= ' ' . $DBInfo->docbook_xmldcl; } else { $args .= ' xml.dcl'; } $sp_encoding = 'SP_ENCODING=utf-8 '; #putenv('SP_ENCODING=utf-8'); } $tmpf = tempnam($vartmp_dir, "JADE"); $fp = fopen($tmpf, "w"); fwrite($fp, $src); fclose($fp); $cmd = $sp_encoding . "{$jade} {$args} {$tmpf}"; $formatter->errlog(); $fp = popen($cmd . $formatter->LOG, "r"); if (is_resource($fp)) { $html = ''; while ($s = fgets($fp, 1024)) { $html .= $s; } pclose($fp); } unlink($tmpf); $err = $formatter->get_errlog(); if ($err) { $err = '<pre class="errlog">' . $err . '</pre>'; } if (!$html) { $src = str_replace("<", "<", $value); return "<pre class='code'>{$src}\n</pre>\n"; } if (!$formatter->preview) { $cache->update($pagename, $html); } return $err . $html; }
function macro_foaf($formatter, $value) { global $DBInfo; $xml_parser = xml_parser_create(); preg_match("/([^,]+)?(?:\\s*,\\s*)?(.*)?\$/", $value, $match); if ($match) { $value = $match[1]; $key = _rawurlencode($match[1]); $args = explode(",", str_replace(" ", "", $match[2])); if (in_array("project", $args)) { $options['project'] = 1; } if (in_array("picture", $args)) { $options['picture'] = 1; } if (in_array("homepage", $args)) { $options['homepage'] = 1; } if (in_array("comment", $args)) { $options['comment'] = 1; } } $info = array(); // XXX $rss_parser = new FoafParser($info); xml_set_object($xml_parser, $rss_parser); xml_set_element_handler($xml_parser, "startElement", "endElement"); xml_set_character_data_handler($xml_parser, "characterData"); $cache = new Cache_text("foaf"); if (!empty($_GET['update']) or !$cache->exists($key)) { $fp = @fopen("{$value}", "r"); if (!$fp) { return "[[FOAF(ERR: not a valid URL! {$value})]]"; } while ($data = fread($fp, 4096)) { $xml_data .= $data; } fclose($fp); $cache->update($key, $xml_data); } else { $xml_data = $cache->fetch($key); } $ret = xml_parse($xml_parser, $xml_data); if (!$ret) { return sprintf("[[FOAF(XML error: %s at line %d)]]", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)); } xml_parser_free($xml_parser); ## $out = "<a href='" . $DBInfo->interwiki['FOAF'] . "{$value}'><img align='middle' border='0' alt='FOAF:' title='FOAF:' src='{$DBInfo->imgs_url_interwiki}" . "foaf-16.png'>"; if ($options['homepage']) { $out .= "</a><a href='{$info['homepage']}'>{$info['name']}</a>"; } else { $out .= "{$info['name']}</a>"; } $br = " "; if ($options['picture']) { $out .= "<br /><img src='{$info['picture']}' />"; $br = "<br />"; } if ($options['homepage']) { $out .= "{$br}<a href='{$info['homepage']}'>{$info['homepage']}</a>"; } if (strtoupper($DBInfo->charset) != 'UTF-8') { $out = iconv('utf-8', $DBInfo->charset, $out); } return $out; }
function get_cached_temporary_blacklist($all = false) { $pc = new Cache_text('persist', array('depth' => 0)); $bc = new Cache_text('ipblock'); $blocked = $pc->fetch('blacklist', $bc->mtime()); if ($blocked === false) { $blocked = get_temporary_blacklist($all); $pc->update('blacklist', $blocked); } return $blocked; }
function processor_linuxdoc($formatter, $value) { global $DBInfo; # $langs=array('en','de','nl','fr','es','da','no','se','pt','ca','it','ro'); $langs = array('en', 'de', 'nl', 'fr', 'es', 'da', 'no', 'se', 'pt', 'ca', 'it', 'ro', 'ko', 'ja'); $toutf = array('ko' => 'UHC', 'ja' => 'nippon'); $pagename = $formatter->page->name; $vartmp_dir =& $DBInfo->vartmp_dir; $cache = new Cache_text("linuxdoc"); if (!$formatter->refresh and !$formatter->preview and $cache->exists($pagename) and $cache->mtime($pagename) > $formatter->page->mtime()) { return $cache->fetch($pagename); } $sgml2html = "sgml2html"; $lang = strtok($DBInfo->lang, "_"); $lang = in_array($lang, $langs) ? $lang : 'en'; $args = "--language={$lang} " . "--split=0 "; if ($value[0] == '#' and $value[1] == '!') { list($line, $value) = explode("\n", $value, 2); # get parameters list($tag, $args) = explode(" ", $line, 2); } $converted = 0; $tmpf = tempnam($vartmp_dir, "SGML2HTML"); $fp = fopen($tmpf . ".sgml", "w"); if (strtoupper($DBInfo->charset) == 'UTF-8' and isset($toutf[$lang])) { if (function_exists('iconv') and $new = iconv('UTF-8', $toutf[$lang], $value)) { $value = $new; $converted = 1; } } fwrite($fp, $value); fclose($fp); $cmd = "{$sgml2html} {$args} {$tmpf}" . ".sgml"; $cwd = getcwd(); chdir($vartmp_dir); $log = ''; $fp = popen($cmd . $formatter->NULL, 'r'); while ($s = fgets($fp, 1024)) { $log .= $s; } pclose($fp); $tmpfh = $tmpf . '.html'; $fp = fopen($tmpfh, 'r'); $html = fread($fp, filesize($tmpfh)); fclose($fp); unlink($tmpf . ".sgml"); unlink($tmpf); // XXX unlink($tmpfh); chdir($cwd); if (!$html) { $src = str_replace("<", "<", $value); return "<pre class='code'>{$src}\n</pre>\n"; } if ($converted) { $new = iconv($toutf[$lang], 'UTF-8', $html); if ($new) { $html = $new; } } if (!$formatter->preview) { $cache->update($pagename, $html); } return $log . $html; }
function macro_WordIndex($formatter, $value, $params = array()) { global $DBInfo; $pagelinks = $formatter->pagelinks; // save $save = $formatter->sister_on; $formatter->sister_on = 0; if (!empty($DBInfo->use_titlecache)) { $cache = new Cache_text('title'); } $word_limit = 50; $start = 0; $prev = 0; if (!empty($params['start']) and is_numeric($params['start'])) { $start = $params['start']; } if (!empty($params['prev']) and is_numeric($params['prev'])) { $prev = $params['prev']; } $value = strval($value); if ($value == '' or $value == 'all') { $sel = ''; } else { $sel = $value; } if (@preg_match('/' . $sel . '/i', '') === false) { $sel = ''; } $keys = array(); $dict = array(); // cache wordindex $wc = new Cache_text('wordindex'); $delay = !empty($DBInfo->default_delaytime) ? $DBInfo->default_delaytime : 0; $lock_file = _fake_lock_file($DBInfo->vartmp_dir, 'wordindex'); $locked = _fake_locked($lock_file, $DBInfo->mtime()); if ($locked or $wc->exists('key') and $DBInfo->checkUpdated($wc->mtime('key'), $delay)) { if ($formatter->group) { $keys = $wc->fetch('key.' . $formatter->group); $dict = $wc->fetch('wordindex.' . $formatter->group); } else { $keys = $wc->fetch('key'); $dict = $wc->fetch('wordindex'); } if (empty($dict) and $locked) { // no cache found return _("Please wait..."); } } if (empty($keys) or empty($dict)) { _fake_lock($lock_file); $all_pages = array(); if ($formatter->group) { $group_pages = $DBInfo->getLikePages($formatter->group); foreach ($group_pages as $page) { $all_pages[] = str_replace($formatter->group, '', $page); } } else { $all_pages = $DBInfo->getPageLists(); } foreach ($all_pages as $page) { if (!empty($DBInfo->use_titlecache) and $cache->exists($page)) { $title = $cache->fetch($page); } else { $title = $page; } $tmp = preg_replace("/[\\?!\$%\\.\\^;&\\*()_\\+\\|\\[\\]<>\"' \\-~\\/:]/", " ", $title); $tmp = preg_replace("/((?<=[A-Za-z0-9])[A-Z][a-z0-9])/", " \\1", ucwords($tmp)); $words = preg_split("/\\s+/", $tmp); foreach ($words as $word) { $word = ltrim($word); if (!$word) { continue; } $key = get_key($word); $keys[$key] = $key; if (!empty($dict[$key][$word])) { $dict[$key][$word][] = $page; } else { if (empty($dict[$key])) { $dict[$key] = array(); } $dict[$key][$word] = array($page); } } } sort($keys); foreach ($keys as $k) { #ksort($dict[$k]); #ksort($dict[$k], SORT_STRING); #uksort($dict[$k], "strnatcasecmp"); uksort($dict[$k], "strcasecmp"); } if ($formatter->group) { $wc->update('key.' . $formatter->group, $keys); $wc->update('wordindex.' . $formatter->group, $dict); } else { $wc->update('key', $keys); $wc->update('wordindex', $dict); } _fake_lock($lock_file, LOCK_UN); } if (isset($sel[0]) and isset($dict[$sel])) { $selected = array($sel); } else { $selected =& $keys; } $out = ''; $key = -1; $count = 0; $idx = 0; foreach ($selected as $k) { $words = array_keys($dict[$k]); $sz = count($words); for ($idx = $start; $idx < $sz; $idx++) { $word = $words[$idx]; $pages =& $dict[$k][$word]; $pkey = $k; if ($key != $pkey) { $key = $pkey; if (!empty($sel) and !preg_match('/^' . $sel . '/i', $pkey)) { continue; } if (!empty($out)) { $out .= "</ul>"; } $ukey = urlencode($key); $out .= "<a name='{$ukey}'></a><h3><a href='#top'>{$key}</a></h3>\n"; } if (!empty($sel) and !preg_match('/^' . $sel . '/i', $pkey)) { continue; } $out .= "<h4>{$word}</h4>\n"; $out .= "<ul>\n"; foreach ($pages as $page) { $out .= '<li>' . $formatter->word_repl('"' . $page . '"') . "</li>\n"; } $out .= "</ul>\n"; $count++; if ($count >= $word_limit) { break; } } } if (isset($sel[0])) { $last = count($dict[$sel]); $offset = $idx + 1; $pager = array(); if ($start > 0) { // get previous start offset. $count = 0; $idx -= $word_limit - 1; if ($idx < 0) { $idx = 0; } $link = $formatter->link_url($formatter->page->name, '?action=wordindex&sec=' . $sel . '&start=' . $idx); $pager[] = "<a href='{$link}'>" . _("« Prev") . '</a>'; } if ($offset < $last) { $link = $formatter->link_url($formatter->page->name, '?action=wordindex&sec=' . $sel . '&start=' . $offset); $pager[] = "<a href='{$link}'>" . _("Next »") . '</a>'; } if (!empty($pager)) { $out .= implode(' | ', $pager) . "<br />\n"; } } $index = array(); $tlink = ''; if (isset($sel[0])) { $tlink = $formatter->link_url($formatter->page->name, '?action=wordindex&sec='); } foreach ($keys as $key) { $name = strval($key); if ($key == 'Others') { $name = _("Others"); } $ukey = urlencode($key); $link = !empty($tlink) ? preg_replace('/sec=/', 'sec=' . _urlencode($key), $tlink) : ''; $index[] = "<a href='{$link}#{$ukey}'>{$name}</a>"; } $str = implode(' | ', $index); $formatter->pagelinks = $pagelinks; // restore $formatter->sister_on = $save; return "<center><a name='top'></a>{$str}</center>\n{$out}"; }
function processor_tpl_(&$formatter, $source, $params = array()) { global $Config; #if (!$Config['use_tpl']) return $source; $cache = new Cache_text("tpl_"); if (!empty($source)) { $id = md5($source); $mtime = $formatter->page->mtime(); } else { if ($params['path']) { $id = md5_file($params['path']); $mtime = filemtime($params['path']); } } $params['uniq'] = $id; $params['formatter'] =& $formatter; $params['cache_head'] = '/* Template_ ' . __TEMPLATE_UNDERSCORE_VER__ . ' ' . $id . (!empty($params['path']) ? ' ' . $params['path'] : '') . ' */'; $TPL_VAR =& $formatter->_vars; if (empty($formatter->preview) and $cache->exists($id) and $cache->mtime($id) > $mtime) { $params['_vars'] =& $formatter->_vars; $ret = $cache->fetch($id, $mtime, $params); if ($ret === true) { return ''; } if (!empty($params['print'])) { return eval('?' . '>' . $ret . '<' . '?php '); } if (!empty($params['raw'])) { return $ret; } ob_start(); eval('?' . '>' . $ret . '<' . '?php '); $fetch = ob_get_contents(); ob_end_clean(); return $fetch; } $formatter->plugin_dir = 'plugin'; # $formatter->safe_mode = 1; # XXX $compiler = new Template_Compiler_(); if ($source[0] == '#' and $source[1] == '!') { list($line, $source) = explode("\n", $source, 2); } //if (!empty($line)) list($tag,$args)=explode(' ',$line,2); $out = $compiler->_compile_template($formatter, $source, $params); if (!$formatter->preview) { $cache->update($id, $out, 0, array('type' => 'php')); } if (!empty($params['print'])) { return eval('?' . '>' . $out . '<' . '?php '); } if (!empty($params['raw'])) { return $out; } #print '<pre>'.(preg_replace('/</','<',$out)).'</pre>'; ob_start(); eval('?' . '>' . $out . '<' . '?php '); $fetch = ob_get_contents(); ob_end_clean(); return $fetch; }
function macro_FastSearch($formatter, $value = "", &$opts) { global $DBInfo; $default_limit = isset($DBInfo->fastsearch_limit) ? $DBInfo->fastsearch_limit : 30; if ($value === true) { $needle = $value = $formatter->page->name; } else { # for MoinMoin compatibility with [[FullSearch("blah blah")]] $needle = $value = preg_replace("/^('|\")([^\\1]*)\\1/", "\\2", $value); } $needle = _preg_search_escape($needle); $pattern = '/' . $needle . '/i'; $fneedle = str_replace('"', """, $needle); # XXX $url = $formatter->link_url($formatter->page->urlname); $arena = 'fullsearch'; $check1 = 'checked="checked"'; $check2 = $check3 = ''; if (in_array($opts['arena'], array('titlesearch', 'fullsearch', 'pagelinks'))) { $check1 = ''; $arena = $opts['arena']; if ($arena == 'fullsearch') { $check1 = 'checked="checked"'; } else { if ($arena == 'titlesearch') { $check2 = 'checked="checked"'; } else { $check3 = 'checked="checked"'; } } } if (!empty($opts['backlinks'])) { $arena = 'pagelinks'; $check1 = ''; $check3 = 'checked="checked"'; } $msg = _("Fast search"); $msg2 = _("Display context of search results"); $msg3 = _("Full text search"); $msg4 = _("Title search"); $msg5 = _("Link search"); $form = <<<EOF <form method='get' action='{$url}'> <input type='hidden' name='action' value='fastsearch' /> <input name='value' size='30' value='{$fneedle}' /> <span class='button'><input type='submit' class='button' value='{$msg}' /></span><br /> <input type='checkbox' name='context' value='20' />{$msg2}<br /> <input type='radio' name='arena' value='fullsearch' {$check1} />{$msg3} <input type='radio' name='arena' value='titlesearch' {$check2} />{$msg4} <input type='radio' name='arena' value='pagelinks' {$check3} />{$msg5}<br /> </form> EOF; if (!isset($needle[0]) or !empty($opts['form'])) { # or blah blah $opts['msg'] = _("No search text"); return $form; } else { if (validate_needle($needle) === false) { $opts['msg'] = sprintf(_("Invalid search expression \"%s\""), $needle); return $form; } } $DB = new Indexer_dba($arena, "r", $DBInfo->dba_type); if ($DB->db == null) { $opts['msg'] = _("Couldn't open search database, sorry."); $opts['hits'] = array(); $opts['hit'] = 0; $opts['all'] = 0; return ''; } $opts['form'] = $form; $sc = new Cache_text("searchkey"); if ($arena == "pagelinks") { $words = array($value); } else { $words = getTokens($value); } // $words=explode(' ', strtolower($value)); $idx = array(); $new_words = array(); foreach ($words as $word) { if ($sc->exists($word)) { $searchkeys = $sc->fetch($word); } else { $searchkeys = $DB->_search($word); $sc->update($word, $searchkeys); } $new_words = array_merge($new_words, $searchkeys); $new_words = array_merge($idx, $DB->_search($word)); } $words = array_merge($words, $new_words); // $word = array_shift($words); $idx = $DB->_fetchValues($word); foreach ($words as $word) { $ids = $DB->_fetchValues($word); // FIXME foreach ($ids as $id) { $idx[] = $id; } } $init_hits = array_count_values($idx); // initial hits $idx = array_keys($init_hits); //arsort($idx); $all_count = $DBInfo->getCounter(); $pages = array(); $hits = array(); foreach ($idx as $id) { $key = $DB->_fetch($id); $pages[$id] = $key; $hits['_' . $key] = $init_hits[$id]; // HACK. prefix '_' to numerical named pages } $DB->close(); if (!empty($_GET['q']) and isset($_GET['q'][0])) { return $pages; } $context = !empty($opts['context']) ? $opts['context'] : 0; $limit = isset($opts['limit'][0]) ? $opts['limit'] : $default_limit; $contexts = array(); if ($arena == 'fullsearch' || $arena == 'pagelinks') { $idx = 1; foreach ($pages as $page_name) { if (!empty($limit) and $idx > $limit) { break; } $p = new WikiPage($page_name); if (!$p->exists()) { continue; } $body = $p->_get_raw_body(); $count = preg_match_all($pattern, $body, $matches); // more precisely count matches if ($context) { # search matching contexts $contexts[$page_name] = find_needle($body, $needle, '', $context); } $hits['_' . $page_name] = $count; // XXX hack for numerical named pages $idx++; } } //uasort($hits, 'strcasecmp'); //$order = 0; //uasort($hits, create_function('$a, $b', 'return ' . ($order ? '' : '-') . '(strcasecmp($a, $b));')); $name = array_keys($hits); array_multisort($hits, SORT_DESC, $name, SORT_ASC); $opts['hits'] = $hits; $opts['hit'] = count($hits); $opts['all'] = $all_count; if (!empty($opts['call'])) { return $hits; } $out = "<!-- RESULT LIST START -->"; // for search plugin $out .= "<ul>"; $idx = 1; while (list($page_name, $count) = each($hits)) { $page_name = substr($page_name, 1); $out .= '<!-- RESULT ITEM START -->'; // for search plugin $out .= '<li>' . $formatter->link_tag(_rawurlencode($page_name), "?action=highlight&value=" . _urlencode($needle), $page_name, "tabindex='{$idx}'"); if ($count > 1) { $out .= ' . . . . ' . sprintf($count == 1 ? _("%d match") : _("%d matches"), $count); if (!empty($contexts[$page_name])) { $out .= $contexts[$page_name]; } } $out .= "</li>\n"; $out .= '<!-- RESULT ITEM END -->'; // for search plugin $idx++; if (!empty($limit) and $idx > $limit) { break; } } $out .= "</ul>\n"; $out .= "<!-- RESULT LIST END -->"; // for search plugin return $out; }
function macro_Rss($formatter, $value) { global $DBInfo; $rsscache = new Cache_text('rsscache'); $key = _rawurlencode($value); // rss TTL = 7200 sec (60*60*2) if (!$formatter->refresh && $rsscache->exists($key) && time() < $rsscache->mtime($key) + 7200) { return $rsscache->fetch($key); } if ($rsscache->exists($key . '.lock')) { return ''; } $args = explode(',', $value); // first arg assumed to be a date fmt arg $date_fmt = ''; $title_width = 0; if (count($args) > 1) { if (preg_match("/^[\\s\\/\\-:aABdDFgGhHiIjmMOrSTY\\[\\]]+\$/", $args[0])) { $date_fmt = array_shift($args); } if (is_numeric($args[0])) { $title_width = array_shift($args); // too small or too big if ($title_width < 10 || $title_width > 40) { $title_width = 0; } } $value = implode(',', $args); } $cache = new Cache_text("rssxml"); # reflash rss each 7200 second (60*60*2) if (!$cache->exists($key) or time() > $cache->mtime($key) + 7200) { $fp = @fopen("{$value}", "r"); if (!$fp) { return "[[RSS(ERR: not a valid URL! {$value})]]"; } while ($data = fread($fp, 4096)) { $xml_data .= $data; } fclose($fp); $cache->update($key, $xml_data); } else { $xml_data = $cache->fetch($key); } // detect charset $charset = 'UTF-8'; list($line, $dummy) = explode("\n", $xml_data, 2); preg_match("/\\sencoding=?(\"|')([^'\"]+)/", $line, $match); if ($match) { $charset = strtoupper($match[2]); } // override $charset for php5 if ((int) phpversion() >= 5) { $charset = 'UTF-8'; } $xml_parser = xml_parser_create(); $rss_parser = new WikiRSSParser($charset); if (!empty($date_fmt)) { $rss_parser->setDateFormat($date_fmt); } if (!empty($title_width)) { $rss_parser->setTitleWidth($title_width); } xml_set_object($xml_parser, $rss_parser); xml_set_element_handler($xml_parser, "startElement", "endElement"); xml_set_character_data_handler($xml_parser, "characterData"); ob_start(); $ret = xml_parse($xml_parser, $xml_data); if (!$ret) { return sprintf("[[RSS(XML error: %s at line %d)]]", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)); } $out = ob_get_contents(); ob_end_clean(); xml_parser_free($xml_parser); $out = '<ul class="rss">' . $out . '</ul>'; # if (strtolower(str_replace("-","",$options['oe'])) == 'euckr') if (function_exists('iconv') and strtoupper($DBInfo->charset) != $charset) { $new = iconv($charset, $DBInfo->charset, $out); if ($new !== false) { return $new; } } $rsscache->remove($key . '.lock'); $rsscache->update($key, $out); return $out; }
$Config = getConfig('config.php', array('init' => 1)); require_once "wikilib.php"; require_once "lib/win32fix.php"; require_once "lib/wikiconfig.php"; require_once "lib/cache.text.php"; require_once "lib/timer.php"; $options = array(); if (class_exists('Timer')) { $timing = new Timer(); $options['timer'] =& $timing; $options['timer']->Check("load"); } $ccache = new Cache_text('settings', array('depth' => 0)); if (!($conf = $ccache->fetch('config'))) { $Config = wikiConfig($Config); $ccache->update('config', $Config, 0, array('deps' => array('config.php', 'lib/wikiconfig.php'))); } else { $Config =& $conf; } $DBInfo = new WikiDB($Config); if (isset($options['timer']) and is_object($options['timer'])) { $options['timer']->Check("load"); } $lang = set_locale($DBInfo->lang, $DBInfo->charset); init_locale($lang); init_requests($options); if (!isset($options['pagename'][0])) { $options['pagename'] = get_frontpage($lang); } $DBInfo->lang = $lang; $DBInfo->query_prefix = '/';
function macro_TitleIndex($formatter, $value, $options = array()) { global $DBInfo; $pc = !empty($DBInfo->titleindex_pagecount) ? intval($DBInfo->titleindex_pagecount) : 100; if ($pc < 1) { $pc = 100; } $pg = empty($options['p']) ? 1 : intval($options['p']); if ($pg < 1) { $pg = 1; } $group = $formatter->group; $key = -1; $keys = array(); if ($value == '' or $value == 'all') { $sel = ''; } else { $sel = ucfirst($value); } // get all keys $all_keys = get_keys(); if (isset($sel[0])) { if (!isset($all_keys[$sel])) { $sel = key($all_keys); } // default } if (@preg_match('/' . $sel . '/i', '') === false) { $sel = ''; } $titleindex = array(); // cache titleindex $kc = new Cache_text('titleindex'); $delay = !empty($DBInfo->default_delaytime) ? $DBInfo->default_delaytime : 0; $uid = ''; if (function_exists('posix_getuid')) { $uid = '.' . posix_getuid(); } $lock_file = _fake_lock_file($DBInfo->vartmp_dir, 'titleindex' . $uid); $locked = _fake_locked($lock_file, $DBInfo->mtime()); if ($locked or $kc->exists('key') and $DBInfo->checkUpdated($kc->mtime('key'), $delay)) { if (!empty($formatter->use_group) and $formatter->group) { $keys = $kc->fetch('key.' . $formatter->group); $titleindex = $kc->fetch('titleindex.' . $formatter->group); } else { $keys = $kc->fetch('key'); $titleindex = $kc->fetch('titleindex' . $sel); } if (isset($sel[0]) and isset($titleindex[$sel])) { $all_pages = $titleindex[$sel]; } if (empty($titleindex) and $locked) { // no cache found return _("Please wait..."); } } if (empty($all_pages)) { $all_pages = array(); $indexer = $DBInfo->lazyLoad('titleindexer'); if (!empty($formatter->use_group) and $formatter->group) { $group_pages = $indexer->getLikePages('^' . $formatter->group); foreach ($group_pages as $page) { $all_pages[] = str_replace($formatter->group, '', $page); } } else { $all_pages = $indexer->getLikePages('^' . $all_keys[$sel], 0); } #natcasesort($all_pages); #sort($all_pages,SORT_STRING); //usort($all_pages, 'strcasecmp'); $pages = array_flip($all_pages); if (!empty($formatter->use_group)) { array_walk($pages, '_setpagekey'); } else { array_walk($pages, create_function('&$p, $k', '$p = $k;')); } $all_pages = array_flip($pages); uksort($all_pages, 'strcasecmp'); } if (empty($keys) or empty($titleindex)) { _fake_lock($lock_file); foreach ($all_pages as $page => $rpage) { $p = ltrim($page); $pkey = get_key("{$p}"); if ($key != $pkey) { $key = $pkey; //$keys[] = $pkey; if (!isset($titleindex[$pkey])) { $titleindex[$pkey] = array(); } } $titleindex[$pkey][$page] = $rpage; } $keys = array_keys($all_keys); if (!empty($tlink)) { $keys[] = 'all'; } if (!empty($formatter->use_group) and $formatter->group) { $kc->update('key.' . $formatter->group, $keys); $kc->update('titleindex.' . $formatter->group, $titleindex); } else { $kc->update('key', $keys); $kc->update('titleindex' . $sel, $titleindex); } if (isset($sel[0]) and isset($titleindex[$sel])) { $all_pages = $titleindex[$sel]; } _fake_lock($lock_file, LOCK_UN); } $pnut = null; if (isset($sel[0]) and count($all_pages) > $pc) { $pages_number = intval(count($all_pages) / $pc); if (count($all_pages) % $pc) { $pages_number++; } $pages = array_keys($all_pages); $pages = array_splice($pages, ($pg - 1) * $pc, $pc); $selected = array(); foreach ($pages as $p) { $selected[$p] = $all_pages[$p]; } $pages = $selected; $pnut = get_pagelist($formatter, $pages_number, '?action=titleindex&sec=' . $sel . '&p=', !empty($pg) ? $pg : 1); } else { $pages =& $all_pages; } //print count($all_pages); //exit; $out = ''; # if ($DBInfo->use_titlecache) # $cache=new Cache_text('title'); $key = ''; foreach ($pages as $page => $rpage) { $p = ltrim($page); $pkey = get_key("{$p}"); if ($key != $pkey) { $key = $pkey; if (isset($sel[0]) and !preg_match('/^' . $sel . '/i', $pkey)) { continue; } if (!empty($out)) { $out .= "</ul>"; } $out .= "<a name='{$key}'></a><h3><a href='#top'>{$key}</a></h3>\n"; $out .= "<ul>"; } if (isset($sel[0]) and !preg_match('/^' . $sel . '/i', $pkey)) { continue; } # # if ($DBInfo->use_titlecache and $cache->exists($page)) # $title=$cache->fetch($page); # else $title = get_title($rpage, $page); #$out.= '<li>' . $formatter->word_repl('"'.$page.'"',$title,'',0,0); $urlname = _urlencode($group . $rpage); $out .= '<li>' . $formatter->link_tag($urlname, '', _html_escape($title)); $keyname = $DBInfo->pageToKeyname(urldecode($rpage)); if (is_dir($DBInfo->upload_dir . "/{$keyname}") or !empty($DBInfo->use_hashed_upload_dir) and is_dir($DBInfo->upload_dir . '/' . get_hashed_prefix($keyname) . $keyname)) { $out .= ' ' . $formatter->link_tag($urlname, "?action=uploadedfiles", $formatter->icon['attach']); } $out .= "</li>\n"; } if (!empty($pnut)) { $out .= '<li style="list-style:none">' . $pnut . '</li>' . "\n"; } $out .= "</ul>\n"; $index = ''; $tlink = ''; if (isset($sel[0])) { $tlink = $formatter->link_url($formatter->page->urlname, '?action=titleindex&sec='); } $index = array(); foreach ($keys as $key) { $name = strval($key); $tag = '#' . $key; $link = !empty($tlink) ? preg_replace('/sec=/', 'sec=' . _urlencode($key), $tlink) : ''; if ($name == 'Others') { $name = _("Others"); } else { if ($name == 'all') { $name = _("Show all"); } } $index[] = "<a href='{$link}{$tag}'>{$name}</a>"; } $str = implode(' | ', $index); return "<center><a name='top'></a>{$str}</center>\n{$out}"; }
function macro_RecentChanges($formatter, $value = '', $options = '') { global $DBInfo, $Config; // get members to hide log $members = $DBInfo->members; $checknew = 1; $checkchange = 0; $template_bra = ""; $template = '"$icon $title$updated $date . . . . $user $count$diff $extra<br />\\n"'; $template_cat = ""; $use_day = 1; $users = array(); $target = ''; if (!empty($options['target'])) { $target = "target='{$options['target']}'"; } $bookmark_action = empty($options['bookmark_action']) ? '?action=bookmark' : '?action=' . $options['bookmark_action']; // $date_fmt='D d M Y'; $date_fmt = $DBInfo->date_fmt_rc; $days = !empty($DBInfo->rc_days) ? $DBInfo->rc_days : RC_DEFAULT_DAYS; $perma_icon = $formatter->perma_icon; $changed_time_fmt = $DBInfo->changed_time_fmt; $args = explode(',', $value); // first arg assumed to be a date fmt arg if (preg_match("/^[\\s\\/\\-:aABdDFgGhHiIjmMOrSTY\\[\\]]+\$/", $args[0])) { $my_date_fmt = $args[0]; } $strimwidth = isset($DBInfo->rc_strimwidth) ? $DBInfo->rc_strimwidth : 20; // use javascript $use_js = 0; // show last edit entry only $last_entry_only = 1; $last_entry_check = 60 * 60 * 24; // show last editor only $last_editor_only = 1; // show editrange like as MoinMoin $use_editrange = 0; // avatar $use_avatar = 0; $avatar_type = 'identicon'; if (!empty($DBInfo->use_avatar)) { $use_avatar = 1; if (is_string($DBInfo->use_avatar)) { $avatar_type = $DBInfo->use_avatar; } } // RC cache delay // $rc_cache_delay <= $rc_delay $cache_delay = isset($DBInfo->rc_cache_delay) ? $DBInfo->rc_cache_delay : 0; $avatarlink = $formatter->link_url('', '?action=' . $avatar_type . '&seed='); $ipicon = '<img src="' . $DBInfo->imgs_dir . '/misc/ip.png" />'; $trash = 0; $rctype = ''; $opts = array(); $bra = ''; $cat = ''; $cat0 = ''; $rctitle = "<h2>" . _("Recent Changes") . "</h2>"; foreach ($args as $arg) { $arg = trim($arg); if (($p = strpos($arg, '=')) !== false) { $k = trim(substr($arg, 0, $p)); $v = trim(substr($arg, $p + 1)); if ($k == 'item' or $k == 'items') { $opts['items'] = min((int) $v, RC_MAX_ITEMS); } else { if ($k == 'days') { $days = min(abs($v), RC_MAX_DAYS); } else { if ($k == "datefmt") { $my_date_fmt = $v; } else { if ($k == 'ago') { if (is_numeric($v) and $v == abs($v)) { $opts['ago'] = abs($v); } else { $opts['from'] = $v; } } else { if ($k == "new") { $checknew = $v; } else { if ($k == "delay") { $cache_delay = intval($v); } else { if ($k == 'strimwidth' and is_numeric($v) and (abs($v) > 15 or $v == 0)) { $strimwidth = abs($v); } } } } } } } } else { if ($arg == "quick") { $opts['quick'] = 1; } else { if ($arg == "nonew") { $checknew = 0; } else { if ($arg == "change") { $checkchange = 1; } else { if ($arg == "showhost") { $showhost = 1; } else { if ($arg == "comment") { $comment = 1; } else { if ($arg == "comments") { $comment = 1; } else { if ($arg == "nobookmark") { $nobookmark = 1; } else { if ($arg == "noperma") { $perma_icon = ''; } else { if ($arg == "button") { $button = 1; } else { if ($arg == "timesago") { $timesago = 1; } else { if ($arg == "notitle") { $rctitle = ''; } else { if ($arg == "hits") { $use_hits = 1; } else { if ($arg == "daysago") { $use_daysago = 1; } else { if ($arg == "trash") { $trash = 1; } else { if ($arg == "editrange") { $use_editrange = 1; } else { if ($arg == "allauthors") { $last_editor_only = 0; } else { if ($arg == "allusers") { $last_editor_only = 0; } else { if ($arg == "allentries") { $last_entry_only = 0; } else { if ($arg == "avatar") { $use_avatar = 1; } else { if ($arg == "noavatar") { $use_avatar = 0; } else { if ($arg == "js") { $use_js = 1; } else { if ($arg == "diffwidth") { $use_diffwidth = 1; } else { if (in_array($arg, array('simple', 'moztab', 'board', 'table', 'list'))) { $rctype = $arg; } } } } } } } } } } } } } } } } } } } } } } } } } ksort($opts); if (!empty($nobookmark)) { $use_js = 0; } // set as dynamic macro or not. if ($formatter->_macrocache and empty($options['call']) and empty($use_js) || $rctype != 'list') { return $formatter->macro_cache_repl('RecentChanges', $value); } if (empty($options['call'])) { $formatter->_dynamic_macros['@RecentChanges'] = 1; } if (empty($DBInfo->interwiki)) { $formatter->macro_repl('InterWiki', '', array('init' => 1)); } // reset some conflict params if (empty($DBInfo->use_counter)) { $use_hits = 0; } if (empty($DBInfo->show_hosts)) { $showhost = 0; } if (!empty($rctype)) { if ($rctype == "simple") { $checkchange = 0; $use_day = 0; if ($showhost) { $template = '"$icon $title @ $day $date by $user $count $extra<br />\\n"'; } else { $template = '"$icon $title @ $day $date $count $extra<br />\\n"'; } } else { if ($rctype == "list") { $rctitle = ''; $changed_time_fmt = !empty($my_date_fmt) ? $my_date_fmt : '[H:i]'; $checkchange = 0; $use_day = 0; $template = '"<li>$date $title</li>\\n"'; $template_bra = "<ul>\n"; $template_cat = "</ul>\n"; } else { if ($rctype == "moztab") { $use_day = 1; $template = '"<li>$title $date</li>\\n"'; } else { if ($rctype == "table") { $bra = "<table border='0' cellpadding='0' cellspacing='0' width='100%'>"; $template = '"<tr><td style=\'white-space:nowrap;width:2%\'>$icon</td><td style=\'width:40%\'>$title$updated</td><td class=\'date\' style=\'width:15%\'>$date</td><td>$user $count$diff $extra</td></tr>\\n"'; $cat = "</table>"; $cat0 = ""; } else { if ($rctype == "board") { $changed_time_fmt = !empty($my_date_fmt) ? $my_date_fmt : 'm-d [H:i]'; $use_day = 0; $template_bra = "<table border='0' cellpadding='0' cellspacing='0' width='100%'>"; if (empty($nobookmark)) { $cols = 3; } else { $cols = 2; } $template_bra .= "<thead><tr><th colspan='{$cols}' class='title'>" . _("Title") . "</th>"; if (!empty($showhost)) { $template_bra .= "<th class='author'>" . _("Editor") . '</th>'; } $template_bra .= "<th class='editinfo'>" . _("Changes") . '</th>'; if (!empty($use_hits)) { $template_bra .= "<th class='hits'>" . _("Hits") . "</th>"; } $template_bra .= "<th class='date'>" . _("Change Date") . '</th>'; $template_bra .= "</tr></thead>\n<tbody>\n"; $template = '"<tr$alt><td style=\'white-space:nowrap;width:2%\'>$icon</td><td class=\'title\' style=\'width:40%\'>$title$updated</td>'; if (empty($nobookmark)) { $template .= '<td>$bmark</td>'; } if (!empty($showhost)) { $template .= '<td class=\'author\'>$user</td>'; } $template .= '<td class=\'editinfo\'>$count'; if (!empty($checkchange) or !empty($checknew)) { $template .= ' $diff'; } $template .= '</td>'; if (!empty($use_hits)) { $template .= '<td class=\'hits\'>$hits</td>'; } $template .= '<td class=\'date\'>$date</td>'; $template_extra = $template . '</tr>\\n<tr class=\'log\'$style><td colspan=\'6\'><div>$extra</div></td></tr>\\n"'; $template .= '</tr>\\n"'; $template_cat = "</tbody></table>"; $cat0 = ""; } } } } } } // override days $days = !empty($_GET['days']) ? min(abs($_GET['days']), RC_MAX_DAYS) : $days; // override ago empty($opts['ago']) ? $opts['ago'] = 0 : null; if (!empty($_GET['ago']) and is_numeric($_GET['ago'])) { $opts['ago'] = abs($_GET['ago']); } else { $opts['from'] = $_GET['ago']; } // override times // accept both 'item' or 'items' $tmp = isset($_GET['item']) ? $_GET['item'] : (isset($_GET['items']) ? $_GET['items'] : null); !empty($tmp) ? $opts['items'] = min(abs($tmp), RC_MAX_ITEMS) : null; unset($tmp); // daysago $daysago = '&days=' . $days; $daysago = $opts['ago'] ? $daysago . '&ago=' . $opts['ago'] : $daysago; $u = $DBInfo->user; # retrive user info // check member $ismember = $u->is_member; // use uniq avatar ? $uniq_avatar = 0; if (!empty($DBInfo->use_uniq_avatar)) { $uniq_avatar = $DBInfo->use_uniq_avatar; } if ($ismember) { $uniq_avatar = 'Y'; } // change avatar after year :> if ($u->id != 'Anonymous') { $bookmark = !empty($u->info['bookmark']) ? $u->info['bookmark'] : ''; } else { $bookmark = $u->bookmark; } $tz_offset = $formatter->tz_offset; if (!$bookmark or !empty($nobookmark)) { if (!empty($checknew) and preg_match('/^\\d+(\\s*\\*\\s*\\d+)*$/', $checknew)) { $checknew = eval('return ' . $checknew . ';'); } if ($checknew > 1) { $bookmark = strtotime(date('Y-m-d', time() - $checknew) . ' 00:00:00'); } } if (!$bookmark) { $bookmark = time(); } // set search query if (isset($_GET['q'][0])) { $query = _preg_search_escape(trim($_GET['q'])); if (@preg_match('/' . $query . '/', '') === false) { unset($query); } } // make rclog uniq key $locals = get_defined_vars(); unset($locals['bookmark']); unset($locals['formatter']); unset($locals['options']); unset($locals['DBInfo']); unset($locals['Config']); unset($locals['args']); unset($locals['arg']); unset($locals['u']); unset($locals['k']); unset($locals['v']); unset($locals['p']); unset($locals['value']); unset($locals['tz_offset']); unset($locals['members']); $rckey = md5(serialize($locals)); $rckey2 = $rckey; $rclog = '<!-- rckey = ' . $rckey . ', cache delay = ' . $cache_delay . ' -->'; if ($use_js) { unset($locals['use_js']); $rckey2 = md5(serialize($locals)); // rckey without js option } unset($locals); // check RC cache $lc = new Cache_text('rccache'); $mtime = $lc->mtime($rckey); if (empty($formatter->refresh)) { if (($val = $lc->fetch($rckey)) !== false and $DBInfo->checkUpdated($mtime, $cache_delay)) { return $val . '<!-- cached at ' . date('Y-m-d H:i:s', $mtime) . ' -->'; } else { if (!empty($options['ajax']) && $rctype == 'list' && $rckey != $rckey2) { // rctype == list with ajax option does not depend on "use_js" option. $mtime = $lc->mtime($rckey2); if (($val = $lc->fetch($rckey2)) !== false and $DBInfo->checkUpdated($mtime, $cache_delay)) { return $val . '<!-- cached at ' . date('Y-m-d H:i:s', $mtime) . ' -->'; } } } // need to update cache if ($val !== false and $lc->exists($rckey . '.lock')) { return $val . '<!-- cached at ' . date('Y-m-d H:i:s', $mtime) . ' -->'; } $lc->update($rckey . '.lock', array('lock'), 5); // 5s lock } else { $lc->update($rckey . '.lock', array('lock'), 5); // 5s lock } // $uniq_avatar is numeric case: change avatar icon after 24 hours if (is_numeric($uniq_avatar)) { $uniq_avatar = $rckey . date('mdH', time()); } else { if (is_string($uniq_avatar) and preg_match('/^[YmdHi]+$/', $uniq_avatar)) { // date format string case: change avatar icon after 'Ymd' etc period $uniq_avatar = $rckey . date($uniq_avatar, time()); } } $time_current = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time(); $secs_per_day = 60 * 60 * 24; //$time_cutoff= $time_current - ($days * $secs_per_day); $lines = $DBInfo->editlog_raw_lines($days, $opts); // make a daysago button $btnlist = ''; if (!empty($use_daysago) or !empty($_GET['ago'])) { $msg[0] = _("Show changes for "); $agolist = array(-$days, $days, 2 * $days, 3 * $days); $btn = array(); $arg = 'days=' . $days . '&ago'; $msg[1] = _("days ago"); foreach ($agolist as $d) { $d += $opts['ago']; if ($d <= 0) { continue; } $link = $formatter->link_tag($formatter->page_urlname, "?{$arg}=" . $d, $d); $btn[] = $link; } #if (sizeof($lines)==0) $btn=array_slice($btn,0,1); $btn[] = $formatter->link_tag($formatter->page_urlname, "?{$arg}=...", '...', 'onClick="return daysago(this)"'); $script = "<script type='text/javascript' src='{$DBInfo->url_prefix}/local/rc.js' ></script>"; $btnlist = $msg[0] . ' <ul><li>' . implode("</li>\n<li>", $btn) . '</li></ul> ' . $msg[1]; $btnlist = $script . "<div class='rc-button'>\n" . $btnlist . "</div>\n"; } $rc = new Cache_text('rclogs'); $ratchet_day = FALSE; $editors = array(); $editcount = array(); $rc_delay = isset($DBInfo->rc_delay) ? $DBInfo->rc_delay : $rc_cache_delay; $rctimestamp = 0; $needupdate = false; $use_val = false; while (($val = $rc->fetch($rckey)) !== false) { $use_val = true; if (!empty($formatter->refresh) or !$DBInfo->checkUpdated($rc->mtime($rckey), $rc_delay)) { $use_val = $rc->exists($rckey . '.lock'); } if (!$use_val) { break; } $editors = $val['editors']; $editcount = $val['editcount']; $lastmod = $val['lastmod']; $rclastline = $val['lastline']; $rctimestamp = $val['timestamp']; $users = $val['users']; break; } // no cache available if (!$use_val) { $rc->update($rckey . '.lock', array('lock'), 5); } // 5s lock $lastline = $lines[0]; $tmp = explode("\t", $lastline, 6); $timestamp = $tmp[2]; unset($tmp); $updatemod = array(); $needupdate = $rctimestamp < $timestamp or $lastline != $rclastline; if ($needupdate) { foreach ($lines as $line) { $parts = explode("\t", $line, 6); if ($lastline == $rclastline) { break; } $page_key = $parts[0]; $ed_time = $parts[2]; $user = $parts[4]; $addr = $parts[1]; if ($user == 'Anonymous') { $user = '******' . $addr; } else { $user = $user . "\t" . $addr; } $day = gmdate('Ymd', $ed_time + $tz_offset); //if ($day != $ratchet_day) { // $ratchet_day = $day; //} if ($last_entry_only and !empty($last_entry_check)) { if (!empty($lastmod[$page_key]) and $lastmod[$page_key] < $ed_time + $last_entry_check) { $edit_day = gmdate('Ymd', $lastmod[$page_key] + $tz_offset); $editors[$page_key][$edit_day][] = $user; $editcount[$page_key][$edit_day]++; if ($needupdate and empty($updatemod[$page_key])) { $updatemod[$page_key] = $ed_time; } continue; } } else { if (!empty($editcount[$page_key][$day])) { $editors[$page_key][$day][] = $user; $editcount[$page_key][$day]++; if ($needupdate and empty($updatemod[$page_key])) { $updatemod[$page_key] = $ed_time; } continue; } } if (empty($editcount[$page_key])) { $editcount[$page_key] = array(); $editors[$page_key] = array(); } $editcount[$page_key][$day] = 1; $editors[$page_key][$day] = array(); $editors[$page_key][$day][] = $user; $lastmod[$page_key] = $ed_time; if ($needupdate) { $updatemod[$page_key] = $ed_time; } } } if (!empty($lastmod)) { $lastmod = array_merge($lastmod, $updatemod); } // search query if (isset($query[0])) { $lines = preg_grep("/{$query}/i", $lines); } // setup hidelog rule $hiderule = null; if (!$ismember && !empty($Config['ruleset']['hiderule'])) { $rule = implode('|', $Config['ruleset']['hiderule']); if (preg_match('@' . $rule . '@', null) !== false) { $hiderule = '@' . $rule . '@'; } } $out = ""; $ratchet_day = FALSE; $br = ""; $ii = 0; $rc_list = array(); $list = array(); foreach ($lines as $line) { $parts = explode("\t", $line); $page_key = $parts[0]; $ed_time = $parts[2]; $day = gmdate('Ymd', $ed_time + $tz_offset); // show last edit only if (!empty($last_entry_only) and !empty($logs[$page_key])) { continue; } else { if (!empty($logs[$page_key][$day])) { continue; } } $page_name = $DBInfo->keyToPagename($parts[0]); if (!empty($hiderule)) { if (preg_match($hiderule, $page_name)) { continue; } } // show trashed pages only if ($trash and $DBInfo->hasPage($page_name)) { continue; } $addr = $parts[1]; $user = $parts[4]; $log = _stripslashes($parts[5]); $act = rtrim($parts[6]); $via_proxy = false; if (($p = strpos($addr, ',')) !== false) { // user via Proxy $via_proxy = true; $real_ip = substr($addr, 0, $p); $log_proxy = '<span class="via-proxy">' . $real_ip . '</span>'; $log = isset($log[0]) ? $log_proxy . ' ' . $log : $log_proxy; $dum = explode(',', $addr); $addr = array_pop($dum); } // if ($ed_time < $time_cutoff) // break; $group = ''; if ($formatter->group) { if (!preg_match("/^({$formatter->group})(.*)\$/", $page_name, $match)) { continue; } $title = $match[2]; } else { if (!empty($formatter->use_group) and ($p = strpos($page_name, '~')) !== false) { $title = substr($page_name, $p + 1); $group = ' (' . substr($page_name, 0, $p) . ')'; } else { $title = $page_name; } } if (!empty($changed_time_fmt)) { if (empty($timesago)) { $date = gmdate($changed_time_fmt, $ed_time + $tz_offset); } else { $date = _timesago($ed_time, 'Y-m-d', $tz_offset); } } $pageurl = _rawurlencode($page_name); // get title $title0 = get_title($title) . $group; $title0 = _html_escape($title0); if ($rctype == 'list') { $attr = ''; } else { $attr = " id='title-{$ii}'"; } if (!empty($strimwidth) and strlen(get_title($title)) > $strimwidth and function_exists('mb_strimwidth')) { $title0 = mb_strimwidth($title0, 0, $strimwidth, '...', $DBInfo->charset); } $attr .= ' title="' . $title0 . '"'; $title = $formatter->link_tag($pageurl, "", $title0, $target . $attr); // simple list format if ($rctype == 'list') { if (empty($logs[$page_key])) { $logs[$page_key] = array(); } $logs[$page_key][$day] = 1; if (!$DBInfo->hasPage($page_name)) { $act = 'DELETE'; $title = '<strike>' . $title . '</strike>'; } $list[$page_name] = array($title, $date, $ed_time, $act); continue; } // print $ed_time."/".$bookmark."//"; $diff = ''; $updated = ''; if ($act == 'UPLOAD') { $icon = $formatter->link_tag($pageurl, "?action=uploadedfiles", $formatter->icon['attach']); } else { if (!$DBInfo->hasPage($page_name)) { $icon = $formatter->link_tag($pageurl, "?action=info", $formatter->icon['del']); if (!empty($use_js)) { $rc_list[] = $page_name; } } else { $icon = $formatter->link_tag($pageurl, "?action=diff", $formatter->icon['diff'], " id='icon-{$ii}'"); if (empty($use_js) and $ed_time > $bookmark) { $icon = $formatter->link_tag($pageurl, "?action=diff&date={$bookmark}", $formatter->icon['diff']); $updated = ' ' . $formatter->link_tag($pageurl, "?action=diff&date={$bookmark}", $formatter->icon['updated'], 'class="updated"'); $add = 0; $del = 0; if ($checknew or $checkchange) { $p = new WikiPage($page_name); $v = $p->get_rev($bookmark); if (empty($v)) { $icon = $formatter->link_tag($pageurl, "?action=info", $formatter->icon['show']); $updated = ' ' . $formatter->link_tag($pageurl, "?action=info", $formatter->icon['new'], 'class="new"'); $add += $p->lines(); } } if ($checkchange) { if (empty($v)) { // new $infos = array(); } else { $infos = $p->get_info('>' . $bookmark); } foreach ($infos as $inf) { $tmp = explode(' ', trim($inf[1])); if (isset($tmp[1])) { $add += $tmp[0]; $del += $tmp[1]; } } } if (!empty($add)) { $diff .= '<span class="diff-added"><span>+' . $add . '</span></span>'; } if (!empty($del)) { $diff .= '<span class="diff-removed"><span>' . $del . '</span></span>'; } } else { if (!empty($use_js)) { $diff = '<span id="diff-' . $ii . '"></span>'; $rc_list[] = $page_name; } } } } if (!empty($use_hits)) { $hits = $DBInfo->counter->pageCounter($page_name); } if (!empty($showhost)) { if ($last_editor_only) { // show last editor only $editor = $editors[$page_key][$day]; if (is_array($editor)) { $editor = $editor[0]; } } else { // all show all authors // count edit number // make range list if ($use_editrange) { // MoinMoin like edit range $editor_list = array(); if ($editors[$page_key][$day]) { foreach ($editors[$page_key][$day] as $idx => $name) { if (empty($editor_list[$name])) { $editor_list[$name] = array(); } $editor_list[$name][] = $idx + 1; } } $editor_counts = array(); foreach ($editor_list as $name => $edits) { $range = ','; if (isset($edits[1])) { $edits[] = 999999; // MoinMoin method for ($i = 0, $sz = count($edits) - 1; $i < $sz; $i++) { if (substr($range, -1) == ',') { $range .= $edits[$i]; if ($edits[$i] + 1 == $edits[$i + 1]) { $range .= '-'; } else { $range .= ','; } } else { if ($edits[$i] + 1 != $edits[$i + 1]) { $range .= $edits[$i] . ','; } } } $range = trim($range, ',-'); $editor_counts[$name] = $range; } else { $editor_counts[$name] = $edits[0]; } } } else { $editor_counts = array_count_values($editors[$page_key][$day]); } $editor = array_keys($editor_counts); } $all_user = array(); foreach ((array) $editor as $user) { if (!$last_editor_only and isset($editor[1]) and isset($editor_counts[$user])) { $count = " <span class='range'>[" . $editor_counts[$user] . "]</span>"; } else { $count = ''; } if (!empty($showhost) && substr($user, 0, 9) == 'Anonymous') { $ouser = $user; if (isset($users[$ouser])) { $user = $users[$ouser]; } else { $checkaddr = null; $addr = null; $tmp = $user; if (strpos($user, "\t") !== false) { list($tmp, $addr) = explode("\t", $user); } $checkaddr = substr($tmp, 10); // Anonymous-127.0.0.1 or Anonymous-email@foo.bar if (($p = strpos($checkaddr, ',')) !== false) { $dum = explode(',', $checkaddr); $checkaddr = array_pop($dum); // last address is the REMOTE_ADDR } $user = $addr = $addr ? $addr : $checkaddr; if (!is_numeric($checkaddr[0]) and preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $user)) { $user = $checkaddr; if (!empty($DBInfo->hide_emails)) { $user = substr(md5($user), 0, 8); } else { $user = email_guard($user); } } else { if (isset($DBInfo->interwiki['Whois'])) { $wip = "<a href='" . $DBInfo->interwiki['Whois'] . "{$addr}' target='_blank'>{$ipicon}</a>"; } else { $wip = "<a href='?action=whois&q=" . $addr . "' target='_blank'>{$ipicon}</a>"; } if ($ismember) { if (in_array($user, $members)) { $wip = ''; } if (!empty($DBInfo->use_admin_user_url)) { $user = '******' . $DBInfo->use_admin_user_url . $user . '">' . $user . '</a>' . $wip; } else { $user = $user . $wip; } } else { if (!empty($DBInfo->mask_hostname)) { $user = _mask_hostname($addr, intval($DBInfo->mask_hostname)); } } } $avatar = ''; if (!empty($use_avatar)) { if (!empty($uniq_avatar)) { $key = $addr . $uniq_avatar; } else { $key = $addr . $rckey; } $crypted = md5($key); $mylnk = preg_replace('/seed=/', 'seed=' . $crypted, $avatarlink); $avatar = '<img src="' . $mylnk . '" class="avatar" alt="avatar" />'; } $user = $avatar . $user; $users[$ouser] = $user; } } else { list($user, $addr) = explode("\t", $user); $ouser = $user; if (!isset($users[$ouser])) { if (isset($DBInfo->interwiki['Whois'])) { $wip = "<a href='" . $DBInfo->interwiki['Whois'] . "{$addr}' target='_blank'>{$ipicon}</a>"; } else { $wip = "<a href='?action=whois&q=" . $addr . "' target='_blank'>{$ipicon}</a>"; } $avatar = ''; if (!empty($use_avatar)) { if (!empty($uniq_avatar)) { $key = $addr . $uniq_avatar; } else { $key = $addr . $rckey; } if (!$ismember) { $key .= $user; } // not a member: show different avatar for login user $crypted = md5($key); $mylnk = preg_replace('/seed=/', 'seed=' . $crypted, $avatarlink); if ($ouser != 'Anonymous') { $mylnk .= '&user='******'<img src="' . $mylnk . '" class="avatar" alt="avatar" />'; } } if (isset($users[$ouser])) { $user = $users[$ouser]; } else { if ($ismember) { if (in_array($user, $members)) { $wip = ''; } if (!empty($DBInfo->use_admin_user_url)) { $user = $avatar . '<a href="' . $DBInfo->use_admin_user_url . $user . '">' . $user . '</a>' . $wip; } else { $user = $avatar . $user . $wip; } $users[$ouser] = $user; } else { if (!empty($DBInfo->use_nick)) { $uid = $user; if (($p = strpos($uid, ' ')) !== false) { $uid = substr($uid, 0, $p); } $u = $DBInfo->udb->getUser($uid); if (!empty($u->info)) { if (!empty($DBInfo->interwiki['User'])) { $user = $formatter->link_repl('[wiki:User:'******' ' . $u->info['nick'] . ']'); } else { if (!empty($u->info['home'])) { $user = $formatter->link_repl('[' . $u->info['home'] . ' ' . $u->info['nick'] . ']'); } else { if (!empty($u->info['nick'])) { $user = $formatter->link_repl('[wiki:' . $uid . ' ' . $u->info['nick'] . ']'); } } } } $user = $avatar . $user; $users[$ouser] = $user; } else { if (strpos($user, ' ') !== false) { $user = $avatar . $formatter->link_repl($user); $users[$ouser] = $user; } else { if (empty($DBInfo->no_wikihomepage) and $DBInfo->hasPage($user)) { $user = $formatter->link_tag(_rawurlencode($user), "", $user); $user = $avatar . $user; $users[$ouser] = $user; } else { if (substr($user, 0, 9) == 'Anonymous') { $addr = substr($user, 10); $user = _('Anonymous'); } $uid = $user; if (preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $user)) { if (!empty($DBInfo->hide_emails)) { $user = substr(md5($user), 0, 8); } else { $user = email_guard($user); } } $user = $avatar . $user; $users[$ouser] = $user; } } } } } } $all_user[] = $user . $count; } if (isset($editor[1])) { $user = '******' . implode("</span> <span class='editor'>", $all_user) . "</span></span>\n"; } else { $user = '******' . $all_user[0] . "</span>\n"; } } else { $user = '******'; } $jsattr = ''; if (!empty($use_js)) { $jsattr = ' onclick="update_bookmark(' . $ed_time . ');return false;"'; } $bmark = ''; if ($day != $ratchet_day) { $ratchet_day = $day; if (!empty($use_day)) { $tag = str_replace('-', '', $day); $perma = "<a name='{$tag}'></a><a class='perma' href='#{$tag}'>{$perma_icon}</a>"; $out .= $cat0; $rcdate = gmdate($date_fmt, $ed_time + $tz_offset); $out .= sprintf("%s<span class='rc-date' style='font-size:large'>%s ", $br, $rcdate); if (empty($nobookmark)) { $out .= "<span class='rc-bookmark' style='font-size:small'>[" . $formatter->link_tag($formatter->page->urlname, $bookmark_action . "&time={$ed_time}" . $daysago, _("set bookmark"), $jsattr) . "]</span>\n"; } $br = "<br />"; $out .= '</span>' . $perma . '<br />' . $bra; $cat0 = $cat; } else { $bmark = $formatter->link_to($bookmark_action . "&time={$ed_time}" . $daysago, _("Bookmark"), $jsattr . ' class="button-small"'); } } //if (empty($use_day) and empty($nobookmark)) { if (empty($nobookmark)) { $date = $formatter->link_to($bookmark_action . "&time={$ed_time}" . $daysago, $date, ' id="time-' . $ii . '" ' . $jsattr); } $count = ""; $extra = ""; if ($editcount[$page_key][$day] > 1) { $count = '<span id="change-' . $ii . '">' . sprintf(_("%s changes"), " <span class='num'>" . $editcount[$page_key][$day] . "</span>") . '</span>'; } else { $count = '<span id="change-' . $ii . '"></span>'; } if (!empty($comment) && !empty($log)) { $extra = " <small name='word-break'>{$log}</small>"; } $alt = $ii % 2 == 0 ? ' class="alt"' : ''; if ($extra and isset($template_extra)) { if ($rctype == 'board' and !empty($use_js)) { $style = ' style="display:none"'; } else { $style = ''; } if (!empty($use_js)) { $title = '<button onclick="toggle_log(this);return false;"><span>+</span></button>' . $title; } $out .= eval('return ' . $template_extra . ';'); } else { $out .= eval('return ' . $template . ';'); } if (empty($logs[$page_key])) { $logs[$page_key] = array(); } $logs[$page_key][$day] = 1; ++$ii; } if ($needupdate) { $rc->update($rckey, array('editors' => $editors, 'editcount' => $editcount, 'lastmod' => $lastmod, 'lastline' => $lastline, 'timestamp' => $timestamp, 'users' => $users)); } $js = ''; if (!empty($rc_list)) { require_once 'lib/JSON.php'; $json = new Services_JSON(); $icon_new = $formatter->icon['new']; $icon_updated = $formatter->icon['updated']; $icon_show = $formatter->icon['show']; $icon_diff = $formatter->icon['diff']; $js = "<script type='text/javascript'>\n/*<![CDATA[*/\nvar rclist ="; $ext = array(); if (!empty($checknew)) { $ext[] = 'new=1'; } if (!empty($checkchange)) { $ext[] = 'change=1'; } $arg = implode('&', $ext); //$url = qualifiedURL($formatter->link_url('RecentChanges')); // FIXME //$url = preg_replace('/^https?:/', '', $url); $url = $formatter->link_url('RecentChanges'); $postdata = "action=recentchanges/ajax" . ($arg ? '&' . $arg : ''); $js .= $json->encode($rc_list) . ";\n"; if ($use_diffwidth) { $js .= "var use_diffwidth = true;\n"; } else { $js .= "var use_diffwidth = false;\n"; } $js .= <<<EOF function diff_width(size) { if (size < 0) size = -size; if (size < 5) return ''; else if (size < 10) return 'display:inline-block;width:25px'; else return 'display:inline-block;width:' + ~~(25 + 2*Math.sqrt(size)) + 'px'; } function update_bookmark(time) { var url = "{$url}"; if (rclist.length) { var timetag; if (typeof time == 'undefined') timetag = ''; else timetag = '&time=' + time; var data = "{$postdata}"; data += timetag + '&value=' + encodeURIComponent(json_encode(rclist)); var txt = HTTPPost(url, data); var ret; if (txt == null) return; var icon_new = "{$icon_new}"; var icon_updated = "{$icon_updated}"; var icon_show = "{$icon_show}"; var icon_diff = "{$icon_diff}"; ret = window["eval"]("(" + txt + ")"); var bookmark = ret['__-_-bookmark-_-__']; var jj = 0; for (var ii = 0; ii < rclist.length; ii++) { // update time var time = document.getElementById('time-' + ii); var tstr = time.firstChild.innerText; var d0 = Date.parse(tstr); // test if (isNaN(d0)) { // recalc time string var timestamp = time.href.match(/time=(\\d+)/); tstr = timesago(timestamp[1], "{$date_fmt}", {$tz_offset}); if (tstr != null) time.firstChild.innerText = tstr; } var item = document.getElementById('title-' + ii); var title = item.getAttribute('title'); if (rclist[jj] != title) { var re = new RegExp("^.*" + url_prefix + '/'); title = decodeURIComponent(item.href.replace(re, '')); } if (ret[title] && ret[title]['state'] == 'deleted') { jj++; continue; } if (rclist[jj] == title && ret[title]) { var icon = document.getElementById('icon-' + ii); var state = document.createElement('SPAN'); if (ret[title]['state'] == 'new') { state.innerHTML = icon_new; state.setAttribute('class', 'new'); icon.href = icon.href.replace(/action=(diff|info)((?:&|&)date=\\d+)?/, 'action=info'); icon.innerHTML = icon_show; } else { state.innerHTML = icon_updated; state.setAttribute('class', 'updated'); icon.href = icon.href.replace(/action=(diff|info)((?:&|&)date=\\d+)?/, 'action=diff&date=' + bookmark); icon.innerHTML = icon_diff; } // remove previous icon if (item.firstChild.nextSibling) item.removeChild(item.firstChild.nextSibling); item.appendChild(state); // add updated / new icon var change = document.getElementById('change-' + ii); if (!change) continue; var diff = document.getElementById('diff-' + ii); var nodiff = !diff; // remove previous diff info if (change.lastChild && change.lastChild.tagName == 'SPAN') change.removeChild(change.lastChild); else if (diff && diff.lastChild) diff.removeChild(diff.lastChild); // add diff info var diff0 = document.createElement('SPAN'); if (ret[title]['add']) { var add = document.createElement('SPAN'); var add2 = document.createElement('SPAN'); add.setAttribute('class', 'diff-added'); var txt = document.createTextNode('+' + ret[title]['add']); add2.appendChild(txt); add.appendChild(add2); diff0.appendChild(add); if (use_diffwidth) add.style.cssText = diff_width(ret[title]['add']); } if (ret[title]['del']) { var del = document.createElement('SPAN'); var del2 = document.createElement('SPAN'); del.setAttribute('class', 'diff-removed'); var txt = document.createTextNode(ret[title]['del']); del2.appendChild(txt); del.appendChild(del2); diff0.appendChild(del); if (use_diffwidth) del.style.cssText = diff_width(ret[title]['del']); } if (nodiff) change.appendChild(diff0); else diff.appendChild(diff0); jj++; } else { if (item.firstChild.nextSibling) item.removeChild(item.firstChild.nextSibling); var change = document.getElementById('change-' + ii); if (!change) continue; var diff = document.getElementById('diff-' + ii); // remove diff info if (change.lastChild && change.lastChild.tagName == 'SPAN') change.removeChild(change.lastChild); else if (diff && diff.lastChild) diff.removeChild(diff.lastChild); // recover diff icon and link var icon = document.getElementById('icon-' + ii); if (icon && icon.firstChild) { var alt = icon.firstChild.getAttribute('alt'); if (alt != 'D' && alt != '@') { icon.innerHTML = icon_diff; } // recover link icon.href = icon.href.replace(/action=(diff|info)(&date=\\d+)?/, 'action=diff'); } } } } } if(window.addEventListener)window.addEventListener("load",update_bookmark,false); else if(window.attachEvent)window.attachEvent("onload",update_bookmark); /*]]>*/ </script> EOF; } else { if (!empty($list)) { $out = ''; foreach ($list as $k => $v) { $out .= '<li><span data-timestamp="' . $v[2] . '" class="date">' . $v[1] . '</span> ' . $v[0] . '</li>' . "\n"; } //if (!empty($options['ajax'])) { // return '<ul>'.$out.'</ul>'; //} } } if (in_array($rctype, array('list', 'simple')) and $use_js) { static $rc_id = 1; $rcid = ' id="rc' . $rc_id . '"'; $extra = ''; if (!empty($opts['items'])) { $extra .= '&item=' . $opts['items']; } if (!empty($my_date_fmt)) { $extra .= '&datefmt=' . $my_date_fmt; } $url = $formatter->link_url('RecentChanges', "?action=recentchanges/ajax&type={$rctype}" . $extra); $js = <<<JS <script type='text/javascript'> /*<![CDATA[*/ (function() { var url = "{$url}"; var txt = HTTPGet(url); var rc = document.getElementById("rc{$rc_id}"); if (txt.substring(0,5) != 'false') { var m = null; if (m = txt.match(/<ul>[\\s\\S]*<\\/ul>/)) { rc.innerHTML = m[0]; } } })(); /*]]>*/ </script> JS; $rc_id++; } else { if ($use_js and $rctype == 'board') { $js .= <<<JS <script type='text/javascript'> /*<![CDATA[*/ function toggle_log(el) { var item = el.parentNode.parentNode; // container var log = item.nextSibling; if (log.tagName == undefined) log = log.nextSibling; // for IE6 if (log.style.display == "none") { el.className = "close"; log.style.display = ""; } else { el.className = "open"; log.style.display = "none"; } } /*]]>*/ </script> JS; } } $out = $btnlist . '<div class="recentChanges"' . $rcid . '>' . $rctitle . $template_bra . $out . $template_cat . $cat0 . '</div>' . $js . $rclog; $lc->update($rckey, $out); $lc->remove($rckey . '.lock'); // unlock $rc->remove($rckey . '.lock'); // unlock return $out; }
function macro_ImageFileSize($formatter, $value = '', $params = array()) { global $Config; if (empty($value)) { return ''; } $sz = 0; // check if it is valid or not while (preg_match('/^((?:https?|ftp):\\/\\/.*(\\.(?:jpg|jpeg|gif|png)))(?:\\?|&)?/i', $value, $m)) { $value = $m[1]; // check the file size saved by the fetch plugin $si = new Cache_text('fetchinfo'); if ($si->exists($value) && ($info = $si->fetch($value)) !== false) { $sz = $info['size']; break; } $sc = new Cache_text('imagefilesize'); if (empty($params['.refresh']) and $sc->exists($value) and $sc->mtime($value) < time() + 60 * 60 * 24 * 20) { $sz = $sc->fetch($value); } else { // dynamic macro if ($formatter->_macrocache and empty($params['call'])) { return $formatter->macro_cache_repl('ImageFileSize', $value); } if (empty($params['call'])) { $formatter->_dynamic_macros['@ImageFileSize'] = 1; } // do not fetch the size of image right now. just fetch the cached info by the fetch plugin if (empty($params['call']) and !empty($Config['fetch_imagesize']) and $Config['fetch_imagesize'] == 2) { return _("Unknown"); } require_once dirname(__FILE__) . '/../lib/HTTPClient.php'; $http = new HTTPClient(); // support proxy if (!empty($Config['proxy_host'])) { $http->proxy_host = $Config['proxy_host']; if (!empty($Config['proxy_port'])) { $http->proxy_port = $Config['proxy_port']; } } // set referrer $referer = ''; if (!empty($Config['fetch_referer_re'])) { foreach ($Config['fetch_referer_re'] as $re => $ref) { if (preg_match($re, $value)) { $referer = $ref; break; } } } // default referrer if (empty($referer) and !empty($Config['fetch_referer'])) { $referer = $Config['fetch_referer']; } if (empty($referer)) { $referer = qualifiedUrl($formatter->link_url($formatter->page->urlname)); } $http->nobody = true; $http->referer = $referer; // check HEAD support for the internal fetch plugin $method = 'GET'; if (!empty($Config['fetch_imagesize_head']) && strstr($value, $Config['fetch_action'])) { $method = 'HEAD'; } $http->sendRequest($value, array(), $method); if ($http->status != 200) { return _("Unknown"); } if (isset($http->resp_headers['content-length'])) { $sz = $http->resp_headers['content-length']; } $sc->update($value, $sz); } break; } if ($sz > 0) { $unit = array('Bytes', 'KB', 'MB', 'GB'); for ($i = 0; $i < 4; $i++) { if ($sz <= 1024) { break; } $sz = $sz / 1024; } return round($sz, 2) . ' ' . $unit[$i]; } // set as dynamic macro or not. if ($formatter->_macrocache and empty($options['call'])) { return $formatter->macro_cache_repl('ImageFileSize', $value); } if (empty($options['call'])) { $formatter->_dynamic_macros['@ImageFileSize'] = 1; } return _("Unknown"); }
function macro_ISBN($formatter, $value = "") { global $DBInfo; // http://www.isbn-international.org/en/identifiers/allidentifiers.html $default_map = array('89' => 'Aladdin'); $ISBN_MAP = "IsbnMap"; $DEFAULT = <<<EOS Amazon http://www.amazon.com/exec/obidos/ISBN= http://images.amazon.com/images/P/\$ISBN.01.MZZZZZZZ.gif Aladdin http://www.aladdin.co.kr/shop/wproduct.aspx?ISBN= http://image.aladdin.co.kr/cover/cover/\$ISBN_1.gif @(http://image\\..*/cover/(?:[^\\s_/]*\$ISBN_\\d\\.(?:jpe?g|gif)))@ Gang http://kangcom.com/common/qsearch/search.asp?s_flag=T&s_text= http://kangcom.com/l_pic/\$ISBN.jpg @bookinfo\\.asp\\?sku=(\\d+)"@ EOS; $DEFAULT_ISBN = "Amazon"; $re_isbn = "/^([0-9\\-]+[xX]?)(?:,\\s*)?(([A-Z][A-Za-z]*)?(?:,)?(.*))?/x"; if ($value != '') { $test = preg_match($re_isbn, $value, $match); if ($test === false) { return "<p><strong class=\"error\">Invalid ISBN \"%value\"</strong></p>"; } } $list = $DEFAULT; $map = new WikiPage($ISBN_MAP); if ($map->exists()) { $list .= $map->get_raw_body(); } $lists = explode("\n", $list); $ISBN_list = array(); foreach ($lists as $line) { if (!$line or !preg_match("/^[A-Z]/", $line[0])) { continue; } $dum = explode(" ", rtrim($line)); $re = ''; $sz = sizeof($dum); if (!preg_match('/^(http|ftp)/', $dum[1])) { continue; } if ($sz == 2) { $dum[] = $ISBN_list[$DEFAULT_ISBN][1]; } else { if ($sz != 3) { if ($sz == 4) { if (($p = strpos(substr($dum[3], 1), $dum[3][0])) !== false) { $retest = substr($dum[3], 0, $p + 2); } else { $retest = $dum[3]; } if (preg_match($retest, '') !== false) { $re = $dum[3]; } } else { continue; } } } $ISBN_list[$dum[0]] = array($dum[1], $dum[2], $re); } if ($value == '') { $out = "<ul>"; foreach ($ISBN_list as $interwiki => $v) { $href = $ISBN_list[$interwiki][0]; if (strpos($href, '$ISBN') === false) { $url = $href . '0738206679'; } else { $url = str_replace('$ISBN', '0738206679', $href); } $icon = $DBInfo->imgs_url_interwiki . strtolower($interwiki) . '-16.png'; $sx = 16; $sy = 16; if ($DBInfo->intericon[$interwiki]) { $icon = $DBInfo->intericon[$interwiki][2]; $sx = $DBInfo->intericon[$interwiki][0]; $sy = $DBInfo->intericon[$interwiki][1]; } $out .= "<li><img src='{$icon}' width='{$sx}' height='{$sy}' " . "align='middle' alt='{$interwiki}:' /><a href='{$url}'>{$interwiki}</a>: " . "<tt class='link'>{$href}</tt></li>"; } $out .= "</ul>\n"; return $out; } $isbn2 = $match[1]; $isbn = str_replace('-', '', $isbn2); #print_r($match); if ($match[3]) { if (strtolower($match[2][0]) == 'k') { $lang = 'Aladdin'; } else { $lang = $match[3]; } } else { $cl = strlen($isbn); if ($cl == 13) { $lang_code = substr($isbn, 3, 2); } else { $lang_code = substr($isbn, 0, 2); } // 89 if (!empty($default_map[$lang_code])) { $lang = $default_map[$lang_code]; } else { $lang = $DEFAULT_ISBN; } } $attr = ''; $ext = ''; if ($match[2]) { $args = explode(',', $match[2]); foreach ($args as $arg) { $arg = trim($arg); if ($arg == 'noimg') { $noimg = 1; } else { if (strtolower($arg) == 'k') { $lang = 'Aladdin'; } else { $name = strtok($arg, '='); $val = strtok(' '); if ($val) { $attr .= $name . '="' . $val . '" '; } #XXX if ($name == 'align') { $attr .= 'class="img' . ucfirst($val) . '" '; } if ($name == 'img') { $ext = $val; } } } } } if ($ISBN_list[$lang]) { $booklink = $ISBN_list[$lang][0]; $imglink = $ISBN_list[$lang][1]; $imgre = $ISBN_list[$lang][2]; } else { $booklink = $ISBN_list[$DEFAULT_ISBN][0]; $imglink = $ISBN_list[$DEFAULT_ISBN][1]; } if (strpos($booklink, '$ISBN') === false) { $booklink .= $isbn; } else { if (strpos($booklink, '$ISBN2') === false) { $booklink = str_replace('$ISBN', $isbn, $booklink); } else { $booklink = str_replace('$ISBN2', $isbn2, $booklink); } } if (empty($noimg) and $imgre and get_cfg_var('allow_url_fopen')) { if (($p = strpos(substr($imgre, 1), $imgre[0])) !== false) { $imgrepl = substr($imgre, $p + 2); $imgre = substr($imgre, 0, $p + 2); if ($imgrepl == '@') { $imgrepl = ''; } $imgre = str_replace('$ISBN', $isbn, $imgre); } $md5sum = md5($booklink); // check cache $bcache = new Cache_text('isbn'); if (empty($formatter->refresh) and $bcache->exists($md5sum)) { $imgname = trim($bcache->fetch($md5sum)); $fetch_ok = 1; } else { // fetch the bookinfo page and grep the imagname of the book. $fd = fopen($booklink, 'r'); if (is_resource($fd)) { while (!feof($fd)) { $line = fgets($fd, 1024); preg_match($imgre, $line, $match); if (!empty($match[1])) { $bcache->update($md5sum, $match[1]); $imgname = $match[1]; $fetch_ok = 1; break; } } fclose($fd); } } if ($fetch_ok) { if ($imgrepl) { $imglink = preg_replace('@' . $imgrepl . '@', $imgname, $imglink); } else { if (!preg_match('/^https?:/', $imgname)) { $imglink = str_replace('$ISBN', $imgname, $imglink); } else { $imglink = $imgname; } } } if (!empty($fetch_ok) and !empty($DBInfo->isbn_img_download)) { # some sites such as the IMDB check the referer and # do not permit to show any of its images # the $isbn_img_download option is needed to show such images preg_match('/^(.*)\\.(jpeg|jpg|gif|png)$/i', $imglink, $m); if (!empty($m[1]) and isset($m[2])) { $myimglink = md5($m[1]) . '.' . $m[2]; } if (isset($m[2])) { # skip XXX } else { if (file_exists($DBInfo->upload_dir . '/isbn/' . $myimglink)) { $mlink = $formatter->macro_repl('attachment', 'isbn:' . $myimglink, 1); $imglink = qualifiedUrl($DBInfo->url_prefix . '/' . $mlink); } else { $fd = fopen($imglink, 'r'); if (is_resource($fd)) { $myimg = ''; while (!feof($fd)) { $myimg .= fread($fd, 1024); } fclose($fd); if (!is_dir($DBInfo->upload_dir . '/isbn/')) { umask(00); mkdir($DBInfo->upload_dir . '/isbn/', 0777); umask($DBInfo->umask); } $fd = fopen($DBInfo->upload_dir . '/isbn/' . $myimglink, 'w'); if (is_resource($fd)) { fwrite($fd, $myimg); fclose($fd); } } } } } } if (empty($fetch_ok)) { if (strpos($imglink, '$ISBN') === false) { $imglink .= $isbn; } else { if (strpos($imglink, '$ISBN2') === false) { $imglink = str_replace('$ISBN', $isbn, $imglink); } else { $imglink = str_replace('$ISBN2', $isbn2, $imglink); } if ($ext) { $imglink = preg_replace('/\\.(gif|jpeg|jpg|png|bmp)$/i', $ext, $imglink); } } } if (!empty($noimg)) { $icon = $DBInfo->imgs_url_interwiki . strtolower($lang) . '-16.png'; $sx = 16; $sy = 16; if (!empty($DBInfo->intericon[$lang])) { $icon = $DBInfo->intericon[$lang][2]; $sx = $DBInfo->intericon[$lang][0]; $sy = $DBInfo->intericon[$lang][1]; } return "<img src='{$icon}' alt='{$lang}:' align='middle' width='{$sx}' height='{$sy}' title='{$lang}' />" . "[<a href='{$booklink}'>ISBN-{$isbn2}</a>]"; } else { return "<a href='{$booklink}'><img src='{$imglink}' border='1' title='{$lang}" . ":ISBN-{$isbn}' alt='[ISBN-{$isbn2}]' class='isbn' {$attr} /></a>"; } }
function do_keywords($formatter, $options) { global $DBInfo; $supported_lang = array('ko'); $page = $formatter->page->name; if (empty($options['update']) and !empty($options['value'])) { $page = $options['value']; } if (!$DBInfo->hasPage($page)) { $options['err'] = _("You are not able to add keywords."); $options['title'] = _("Page does not exists"); do_invalid($formatter, $options); return; } if (!empty($options['update']) or !empty($options['refresh'])) { $lk = $DBInfo->getPage(LOCAL_KEYWORDS); $force_charset = ''; if ($DBInfo->force_charset) { $force_charset = '; charset=' . $DBInfo->charset; } $formatter->send_header("Content-type: text/plain" . $force_charset); if (!$lk->exists()) { print sprintf(_("%s is not found."), LOCAL_KEYWORDS); return; } $raw = $lk->get_raw_body(); # update keylinks of LocalKeywords $kc = new Cache_text('keylinks'); $lines = explode("\n", $raw); $all_keys = array(); foreach ($lines as $l) { $l = trim($l); if ($l[0] == '#' or !$l) { continue; } $ws = preg_split('/((?<!\\S)(["\'])[^\\2]+?\\2(?!\\S)|\\S+)/', $l, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $ws = array_flip(array_unique($ws)); unset($ws['"']); // delete delims unset($ws["'"]); unset($ws[' ']); $ws = array_flip($ws); $ws = array_map(create_function('$a', 'return preg_replace("/^([\\"\'])(.*)\\\\1$/","\\\\2",$a);'), $ws); // delete ",' $ws = array_unique($ws); $all_keys = array_merge($all_keys, $ws); foreach ($ws as $k) { $rels = array_diff($ws, array($k)); $krels = $kc->fetch($k); if (is_array($krels)) { if ($nrels = array_diff($rels, $krels)) { $rs = array_unique(array_merge($nrels, $krels)); $kc->update($k, $rs); print "***** updated {$k}\n"; } } else { if (sizeof($rels) > 1 and is_array($rels)) { $kc->update($k, $rels); print "***** save {$k}\n"; } } } } print_r($all_keys); print "OK"; return; } $args = array(); $formatter->send_header('', $options); if (empty($options['suggest']) and (!empty($options['key']) and is_array($options['key']) or !empty($options['keywords']))) { if (!empty($options['keywords'])) { // following keyword list are acceptable separated with spaces. // Chemistry "Physical Chemistry" "Bio Chemistry" ... $keywords = _stripslashes($options['keywords']); $ws = preg_split('/((?<!\\S)(["\'])[^\\2]+?\\2(?!\\S)|\\S+)/', $keywords, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $ws = array_flip(array_unique($ws)); unset($ws['"']); // delete delims unset($ws["'"]); unset($ws[' ']); $ws = array_flip($ws); $ws = array_map(create_function('$a', 'return preg_replace("/^([\\"\'])(.*)\\\\1$/","\\\\2",$a);'), $ws); // delete ",' if (!is_array($options['key'])) { $options['key'] = array(); } $options['key'] = array_merge($options['key'], $ws); } if (!empty($options['common'])) { $raw = "#format plain"; $lang = $formatter->pi['#language'] ? $formatter->pi['#language'] : ''; $lang = $options['lang'] ? $options['lang'] : $lang; if (in_array($lang, $supported_lang)) { $common_word_page = LOCAL_KEYWORDS . '/CommonWords' . ucfirst($lang); } else { $common_word_page = LOCAL_KEYWORDS . '/CommonWords'; } if ($DBInfo->hasPage($common_word_page)) { $p = $DBInfo->getPage($common_word_page); if (!$p->exists()) { $dict = array(); } else { $raw = $p->get_raw_body(); $raw = rtrim($raw); $lines = explode("\n", $raw); $body = ''; foreach ($lines as $line) { if ($line[0] == '#' or $line == '') { continue; } $body .= $line . "\n"; } $body = rtrim($body); $dict = explode("\n", $body); } $commons = array_diff(array_values($options['key']), $dict); } else { $p = $DBInfo->getPage($common_word_page); $commons = $options['key']; } if (!empty($commons)) { sort($commons); $raw .= "\n" . implode("\n", $commons); $p->write($raw); $DBInfo->savePage($p, "Common words are added", $options); } $formatter->send_title(sprintf(_("Common words are updated"), $options['page']), '', $options); $formatter->send_footer($args, $options); return; } $cache = new Cache_text('keyword'); $keys = $options['key']; $keys = array_flip($keys); unset($keys['']); $cache->update($page, array_keys($keys)); # update 'keylinks' caches #$kc=new Cache_text('keylinks'); #foreach ($options['key'] as $k) { # // XXX # $kv=unserialize($kc->fetch($k)); # if (!in_array($page,$kv)) { # $kv[]=$page; # $kc->update($k,serialize($kv)); # } #} $raw = "#format plain"; $lk = $DBInfo->getPage(LOCAL_KEYWORDS); if (!$lk->exists()) { $dict = array(); } else { $raw = $lk->get_raw_body(); $raw = rtrim($raw); $lines = explode("\n", $raw); $body = ''; foreach ($lines as $line) { if ($line[0] == '#' or $line == '') { continue; } $body .= $line . "\n"; } $body = rtrim($body); } if (!empty($options['key'])) { // XXX $ks = array_map(create_function('$a', 'return (strpos($a," ") !== false) ? "\\"$a\\"":$a;'), $options['key']); $raw .= "\n" . implode(' ', $ks) . "\n"; $lk->write($raw); $DBInfo->savePage($lk, "Keywords are added", $options); } $formatter->send_title(sprintf(_("Keywords for %s are updated"), $page), '', $options); $ret = ''; foreach ($keys as $key => $val) { $ret .= $key . ','; } $ret = substr($ret, 0, strlen($ret) - 1); print "<tt>#keywords {$ret}</tt>\n"; if (!empty($DBInfo->use_keywords) or !empty($options['update'])) { # auto update the page with selected keywords. $body = $formatter->page->get_raw_body(); $pi = $formatter->page->get_instructions($dum); if (!empty($pi['#keywords'])) { $tag = preg_quote($pi['#keywords']); $nbody = preg_replace('/^#keywords\\s+' . $tag . '/', '#keywords ' . $ret, $body, 1); if ($nbody != $body) { $ok = 1; } } else { $nbody = '#keywords ' . $ret . "\n" . $body; $ok = 2; } if (!empty($ok)) { if ($ok == 1) { $comment = "Keywords are updated"; } else { $comment = "Keywords are added"; } $formatter->page->write($nbody); $DBInfo->savePage($formatter->page, $comment, $options); print "<h2>" . _("Keywords are updated") . "</h2>"; } else { print "<h2>" . _("There are no changes found") . "</h2>"; } } else { # user confirmation $link = $formatter->link_url(_rawurlencode($page), ''); $keys = explode(',', $ret); $ret = ''; foreach ($keys as $key) { if ($key and strpos($key, ' ') !== false) { $key = '"' . $key . '"'; } $ret .= $key . ' '; } $btn = _("Update with these Keywords"); $form = "<form method='post' action='{$link}'>"; $form .= '<input type="hidden" name="action" value="keywords" />'; $form .= '<input type="hidden" name="update" value="1" />'; $form .= '<input type="hidden" name="keywords" value=\'' . $ret . '\' />'; $form .= "<input type='submit' value='{$btn}' />\n"; $form .= "</form>"; print $form; } $formatter->send_footer($args, $options); return; } if (!empty($options['all']) or !empty($options['tour'])) { if (!empty($optiopns['sort']) and $options['sort'] == 'freq') { $sort = 'freq'; } $formatter->send_title('', '', $options); $myq = '?' . $_SERVER['QUERY_STRING']; $myq = preg_replace('/&sort=[^&]+/i', '', $myq); if ($sort != 'freq') { $myq .= '&sort=freq'; $txt = _("alphabetically"); $ltxt = _("by frequency"); } else { $txt = _("by size"); $ltxt = _("alphabetically"); } $link = $formatter->link_tag(_rawurlencode($page), $myq, $ltxt); print "<h2>"; print sprintf(_("Keywords list %s (or %s)"), $txt, $link); print "</h2>\n"; if (!$options['limit']) { $options['limit'] = 0; } } else { $formatter->send_title(sprintf(_("Select keywords for %s"), $options['page']), '', $options); $options['merge'] = 1; $options['add'] = 1; } print macro_KeyWords($formatter, $options['page'], $options); //$args['editable']=1; $formatter->send_footer($args, $options); }
function do_sitemap($formatter, $options) { global $DBInfo, $Config; $tc = new Cache_text('persist', array('depth' => 0)); $extra = ''; if (!empty($formater->group)) { $extra = '.' . $formatter->group; } if (!empty($formatter->prefix)) { $extra .= qualifiedUrl($formatter->prefix); } // all pages $mtime = $DBInfo->mtime(); $lastmod = gmdate('D, d M Y H:i:s \\G\\M\\T', $mtime); $etag = md5($mtime . $DBInfo->etag_seed . $extra); $options['etag'] = $etag; $options['mtime'] = $mtime; // set the s-maxage for proxy $date = gmdate('Y-m-d-H-i-s', $mtime); $proxy_maxage = !empty($Config['proxy_maxage']) ? ', s-maxage=' . $Config['proxy_maxage'] : ''; // only xml format supported $format = 'text/xml'; if (isset($options['format']) and in_array($options['format'], array('text/xml'))) { $format = $options['format']; } $header[] = 'Content-Type: ' . $format; $header[] = 'Cache-Control: public' . $proxy_maxage . ', max-age=0, must-revalidate'; $need = http_need_cond_request($mtime, $lastmod, $etag); if (!$need) { $header[] = 'HTTP/1.0 304 Not Modified'; } else { $header[] = 'Content-Disposition: attachment; filename="sitemap-' . $date . '.xml"'; } $formatter->send_header($header, $options); if (!$need) { @ob_end_clean(); return; } if (!$formatter->refresh && ($ret = $tc->fetch('sitemap' . $extra . '.mtime')) !== false) { if (($ret = $tc->fetch('sitemap' . $extra, 0, array('print' => 1))) !== false) { return; } } // set sitemap public cache $ext = $format == 'text/xml' ? 'xml' : 'txt'; $sc = new Cache_text('sitemap', array('dir' => $DBInfo->cache_public_dir, 'ext' => $ext, 'depth' => 0)); # get page list set_time_limit(0); if ($formater->group) { $group_pages = $DBInfo->getLikePages($formater->group); foreach ($group_pages as $page) { $all_pages[] = str_replace($formatter->group, '', $page); } usort($all_pages, 'strcasecmp'); } else { if (!empty($Config['sitemap_sortby'])) { // call PageSort macro. $opts = array(); $opts['sortby'] = $Config['sitemap_sortby']; // date or size $opts['.call'] = 1; $ret = $formatter->macro_repl('PageSort', '', $opts); $all_pages = array(); if (!empty($ret['count'])) { $tc->fetch('pagedate.raw'); $rawfile = $tc->cache_path . '/' . $tc->getKey('pagedate.raw'); $fp = fopen($rawfile, 'r'); if (is_resource($fp)) { while (($line = fgets($fp, 1024)) != false) { $tmp = explode("\t", $line); $all_pages[] = $tmp[0]; } fclose($fp); } } } else { $args = array('all' => 1); $all_pages = $DBInfo->getPageLists($args); usort($all_pages, 'strcasecmp'); } } $count = sizeof($all_pages); $map = ''; $zone = '+00:00'; $ttl = !empty($DBInfo->sitemap_ttl) ? $DBInfo->sitemap_ttl : 60 * 60 * 24 * 7; if ($count > 50000) { $map = <<<HEAD <?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> HEAD; $date = gmdate("Y-m-d\\TH:i:s", time()) . $zone; // W3C datetime format $total = intval($count / 50000) + ($count % 50000 > 0 ? 1 : 0); for ($i = 0; $i < $total; $i++) { $mapname = $sc->getKey(sprintf('sitemap' . $extra . '%03d', $i)); $map .= "<sitemap>\n<loc>\n" . qualifiedUrl($DBInfo->cache_public_url . '/' . $mapname) . '</loc>' . "\n"; $map .= '<lastmod>' . $date . "</lastmod>\n</sitemap>\n"; } $map .= "</sitemapindex>\n"; $tc->update('sitemap' . $extra, $map); $tc->update('sitemap' . $extra . '.mtime', array('dummy' => 1), $ttl); } # charset if ($options['oe'] and strtolower($options['oe']) != $DBInfo->charset) { $charset = $options['oe']; } else { $charset = $DBInfo->charset; } $head = <<<HEAD <?xml version="1.0" encoding="{$charset}"?> <urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9" url="http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> HEAD; $foot = <<<FOOT </urlset> FOOT; # process page list $i = 0; $ii = 0; $items = array(); foreach ($all_pages as $page) { $ii++; $url = qualifiedUrl($formatter->link_url(_rawurlencode($page))); $p = new WikiPage($page); $t = $p->mtime(); $date = gmdate("Y-m-d\\TH:i:s", $t) . $zone; // W3C datetime format $item = "<url>\n"; $item .= " <loc>" . $url . "</loc>\n"; $item .= " <lastmod>" . $date . "</lastmod>\n"; $item .= "</url>"; $items[] = $item; if ($ii >= 50000) { $ii = 0; // process output $out = implode("\n", $items); if ($options['oe'] and strtolower($options['oe']) != $DBInfo->charset) { $charset = $options['oe']; if (function_exists('iconv')) { $new = iconv($DBInfo->charset, $charset, $items); if (!$new) { $charset = $DBInfo->charset; } if ($new) { $out = $new; } } } $sc->update(sprintf('sitemap' . $extra . '%03d', $i), $head . $out . $foot); $i++; $items = array(); } } $sc->update('sitemap' . $extra . '.mtime', array('dummy' => 1), $ttl); // process output if ($count > 50000) { if (count($items)) { $out = implode("\n", $items); if ($options['oe'] and strtolower($options['oe']) != $DBInfo->charset) { $charset = $options['oe']; if (function_exists('iconv')) { $new = iconv($DBInfo->charset, $charset, $items); if (!$new) { $charset = $DBInfo->charset; } if ($new) { $out = $new; } } } $sc->update(sprintf('sitemap' . $extra . '%03d', $i), $head . $out . $foot); } } else { $out = implode("\n", $items); if ($options['oe'] and strtolower($options['oe']) != $DBInfo->charset) { $charset = $options['oe']; if (function_exists('iconv')) { $new = iconv($DBInfo->charset, $charset, $items); if (!$new) { $charset = $DBInfo->charset; } if ($new) { $out = $new; } } } $map = $head . $out . $foot; $tc->update('sitemap' . $extra, $map); $tc->update('sitemap' . $extra, array('dummy' => 1), $ttl); } echo $map; }