function macro_PageLinks($formatter, $options = "") { global $DBInfo; $pages = $DBInfo->getPageLists(); $pagelinks = $formatter->pagelinks; // save $save = $formatter->sister_on; $formatter->sister_on = 0; $out = "<ul>\n"; $cache = new Cache_text("pagelinks"); foreach ($pages as $page) { $lnks = $cache->fetch($page); if ($lnks !== false) { $out .= "<li>" . $formatter->link_tag($page, '', htmlspecialchars($page)) . ": "; $links = implode(' ', $lnks); $links = preg_replace_callback("/(" . $formatter->wordrule . ")/", array(&$formatter, 'link_repl'), $links); $out .= $links . "</li>\n"; } } $out .= "</ul>\n"; $formatter->pagelinks = $pagelinks; // restore $formatter->sister_on = $save; return $out; }
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 processor_pic($formatter, $value = "") { global $DBInfo; $GROFF = "groff -e -p -ms -Tps "; $CONVERT = "convert -transparent white -density 120x120 -crop 0x0 -trim "; $vartmp_dir =& $DBInfo->vartmp_dir; if (getenv("OS") == "Windows_NT") { $NULL = 'NUL'; $vartmp_dir = getenv('TEMP'); #$convert="wconvert"; } $cache_dir = $DBInfo->upload_dir . "/PIC"; $cache_url = !empty($DBInfo->upload_url) ? $DBInfo->upload_url . '/PIC' : $DBInfo->url_prefix . '/' . $cache_dir; if ($value[0] == '#' and $value[1] == '!') { list($line, $value) = explode("\n", $value, 2); } $pic_script = $value; # print "<pre>$pic_script</pre>"; $uniq = md5($pic_script); if ($DBInfo->cache_public_dir) { $fc = new Cache_text('pic', array('ext' => 'png', 'dir' => $DBInfo->cache_public_dir)); $pngname = $fc->getKey($uniq, false); $outpath_png = $DBInfo->cache_public_dir . '/' . $pngname; $png_url = $DBInfo->cache_public_url ? $DBInfo->cache_public_url . '/' . $pngname : $DBInfo->url_prefix . '/' . $outpath_png; } else { $outpath_png = $cache_dir . '/' . $uniq . '.png'; $png_url = $cache_url . '/' . $uniq . '.png'; } $outpath_pic = "{$vartmp_dir}/{$uniq}.pic"; $outpath_ps = "{$vartmp_dir}/{$uniq}.ps"; if (!file_exists(dirname($outpath_png))) { umask(00); _mkdir_p(dirname($outpath_png), 0777); umask(022); } if ($formatter->refresh || !file_exists($outpath_png)) { # write to pic script file $ifp = fopen("{$outpath_pic}", "w"); fwrite($ifp, $pic_script); fclose($ifp); # convert processing $fp = popen("{$GROFF} {$outpath_pic} >{$outpath_ps}" . $formatter->NULL, 'r'); pclose($fp); $fp = popen("{$CONVERT} {$outpath_ps} {$outpath_png}" . $formatter->NULL, 'r'); pclose($fp); # delete temporary files unlink($outpath_ps); unlink($outpath_pic); } return "<img class='tex' src='{$png_url}' alt='pic' />"; }
function do_qr($formatter, $params = array()) { global $Config; if (isset($params['value']) && isset($params['value'][0])) { $value = $params['value']; } else { $encoded = _urlencode(strtr($formatter->page->name, ' ', '_')); $value = qualifiedUrl($formatter->link_url($encoded)); } if (!empty($Config['cache_public_dir']) and !empty($Config['cache_public_url'])) { $fc = new Cache_text('qr', array('ext' => 'png', 'dir' => $Config['cache_public_dir'])); $pngname = $fc->getKey($value); $pngfile = $Config['cache_public_dir'] . '/' . $pngname; $png_url = !empty($Config['cache_public_url']) ? $Config['cache_public_url'] . '/' . $pngname : $Config['url_prefix'] . '/' . $pngfile; } else { $uniq = md5($value); $pngfile = $cache_dir . '/' . $uniq . '.png'; $png_url = $cache_url . '/' . $uniq . '.png'; } $img_exists = file_exists($pngfile); if (!$img_exists || $formatter->refresh) { require_once dirname(__FILE__) . '/../lib/phpqrcode.php'; QRcode::png($value, $pngfile, 'l', 3, 1); } if (!empty($Config['use_cache_url'])) { header("Pragma: no-cache"); header('Cache-Control: public, max-age=0, s-maxage=0'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Cache-Control: no-store, no-cache, must-revalidate', false); $formatter->send_header(array('Status: 302', 'Location: ' . $png_url)); return null; } $down_mode = 'inline'; header("Content-Type: image/png\r\n"); $mtime = filemtime($pngfile); $lastmod = gmdate('D, d M Y H:i:s', $mtime) . ' GMT'; $etag = md5($lastmod . $key); header('Last-Modified: ' . $lastmod); header('ETag: "' . $etag . '"'); $maxage = 60 * 60 * 24 * 30; header('Cache-Control: public, max-age=' . $maxage); $need = http_need_cond_request($mtime, $lastmod, $etag); if (!$need) { header('HTTP/1.0 304 Not Modified'); @ob_end_clean(); return null; } @ob_clean(); $ret = readfile($pngfile); return null; }
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_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 processor_blog($formatter, $value = "", $options) { static $date_anchor = ''; global $DBInfo; #static $tackback_list=array(); if ($value[0] == '#' and $value[1] == '!') { list($line, $value) = explode("\n", $value, 2); } $datetag = ''; if ($date_anchor == '' and $DBInfo->use_trackback) { #read trackbacks and set entry counter $cache = new Cache_text('trackback'); if ($cache->exists($formatter->page->name)) { $trackback_raw = $cache->fetch($formatter->page->name); $trackbacks = explode("\n", $trackback_raw); foreach ($trackbacks as $trackback) { list($dummy, $entry, $extra) = explode("\t", $trackback); if ($entry) { if ($formatter->trackback_list[$entry]) { $formatter->trackback_list[$entry]++; } else { $formatter->trackback_list[$entry] = 1; } } } } } #print($date_anchor);print_r($trackback_list); if ($line) { # get parameters list($tag, $user, $date, $title) = explode(" ", $line, 4); if (preg_match('/^[\\d\\.]+$/', $user)) { if (!$DBInfo->mask_hostname and $DBInfo->interwiki['Whois']) { #$user=_("Anonymous")."[<a href='".$DBInfo->interwiki['Whois']."$user'>$user</a>]"; $user = "******" . $DBInfo->interwiki['Whois'] . "{$user}'>" . _("Anonymous") . "</a>"; } else { $user = _("Anonymous"); } } else { if ($DBInfo->hasPage($user)) { $user = $formatter->link_tag($user); } } if ($date && $date[10] == 'T') { $date[10] = ' '; $time = strtotime($date . " GMT"); $date = gmdate("m-d [h:i a]", $time + $formatter->tz_offset); $pagename = $formatter->page->name; $p = strrpos($pagename, '/'); if ($p and preg_match('/(\\d{4})(-\\d{1,2})?(-\\d{1,2})?/', substr($pagename, $p), $match)) { if ($match[3]) { $anchor = ''; } else { if ($match[2]) { $anchor = gmdate("d", $time); } else { if ($match[1]) { $anchor = gmdate("md", $time); } } } } else { $anchor = gmdate("Ymd", $time); } if ($date_anchor != $anchor) { $anchor_date_fmt = $DBInfo->date_fmt_blog; $datetag = "<div class='blog-date'>" . date($anchor_date_fmt, $time) . " <a name='{$anchor}'></a><a class='perma' href='#{$anchor}'>{$formatter->perma_icon}</a></div>"; $date_anchor = $anchor; } } $md5sum = md5(substr($line, 7)); } $src = rtrim($value); if (!empty($src)) { $options['nosisters'] = 1; $options['nojavascript'] = 1; $tmp = explode("----\n", $src, 2); $src = $tmp[0]; if (!empty($tmp[1])) { $comments = $tmp[1]; } $add_button = _("Add comment"); if (!empty($comments)) { $count = sizeof(explode("----\n", $comments)); if (!empty($options['noaction']) or !empty($DBInfo->blog_comments)) { $comments = preg_replace("/----\n/", "[[HTML(</div></div><div class='separator'><hr /></div><div class='blog-comment'><div>)]]", $comments); } else { $comments = ''; $add_button = $count == 1 ? _("%s comment") : _("%s comments"); $count_tag = '<span class="count">' . $count . '</span>'; $add_button = sprintf($add_button, $count_tag); } } if (!empty($formatter->trackback_list[$md5sum])) { $counter = ' (' . $formatter->trackback_list[$md5sum] . ')'; } else { $counter = ''; } if (empty($options['noaction']) and $md5sum) { $action = $formatter->link_tag($formatter->page->urlname, "?action=blog&value={$md5sum}#BlogComment", $add_button); if (getPlugin('SendPing')) { $action .= ' | ' . $formatter->link_tag($formatter->page->urlname, "?action=trackback&value={$md5sum}", _("track back") . $counter); } if (!empty($DBInfo->use_rawblog)) { $action .= ' | ' . $formatter->link_tag($formatter->page->urlname, "?action=rawblog&value={$md5sum}", _("raw")); } } if (!empty($action)) { $action = "<div class='blog-action'><span class='bullet'>»</span> " . $action . "</div>\n"; } else { $action = ''; } $save = !empty($formatter->preview) ? $formatter->preview : ''; $formatter->preview = 1; ob_start(); $formatter->send_page($src, $options); $msg = ob_get_contents(); ob_end_clean(); if (!empty($comments)) { ob_start(); $formatter->send_page($comments, $options); $comments = "<div class='blog-comments'><div class='blog-comment'>" . ob_get_contents() . "</div></div>"; ob_end_clean(); } else { $comments = ""; } !empty($save) ? $formatter->preview = $save : null; } $out = "{$datetag}<div class='blog'>"; if (!empty($title)) { #$tag=normalize($title); $tag = $md5sum; if ($tag[0] == '%') { $tag = "n" . $tag; } $perma = "<a class='perma' href='#{$tag}'>{$formatter->perma_icon}</a>"; $title = preg_replace_callback("/(" . $formatter->wordrule . ")/", array(&$formatter, 'link_repl'), $title); $out .= "<div class='blog-title'><a name='{$tag}'></a>{$title} {$perma}</div>\n"; } $info = sprintf(_("Submitted by %s @ %s"), $user, $date); $out .= "<div class='blog-user'>{$info}</div>\n" . "<div class='blog-content'>{$msg}</div>{$comments}{$action}\n" . "</div>\n"; return $out; }
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_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; }
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 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 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 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 processor_geshi($formatter, $value, $options) { global $DBInfo; if (!defined('GESHI_VERSION')) { return $formatter->processor_repl('vim', $value, $options); } $syntax = array('actionscript', 'ada', 'apache', 'asm', 'asp', 'bash', 'c', 'c_mac', 'caddcl', 'cadlisp', 'cpp', 'csharp', 'css-gen', 'css', 'delphi', 'html4strict', 'java', 'javascript', 'lisp', 'lua', 'nsis', 'objc', 'oobas', 'oracle8', 'pascal', 'perl', 'php-brief', 'php', 'python', 'qbasic', 'smarty', 'sql', 'vb', 'vbnet', 'visualfoxpro', 'xml'); if ($value[0] == '#' and $value[1] == '!') { list($line, $value) = explode("\n", $value, 2); } # get parameters if ($line) { $line = substr($line, 2); $tag = strtok($line, ' '); $type = strtok(' '); $extra = strtok(''); if ($tag != 'vim') { $extra = $type; $type = $tag; } } $src = rtrim($value); // XXX if (!$type) { $type = 'nosyntax'; } $uniq = md5($extra . $value); if ($DBInfo->cache_public_dir) { $fc = new Cache_text('geshi', array('ext' => 'html', 'dir' => $DBInfo->cache_public_dir)); $htmlname = $fc->getKey($uniq, false); $html = $DBInfo->cache_public_dir . '/' . $htmlname; } else { $cache_dir = $DBInfo->upload_dir . "/GeshiProcessor"; $html = $cache_dir . '/' . $uniq . '.html'; } if (!is_dir(dirname($html))) { $om = umask(00); _mkdir_p(dirname($html), 0777); umask($om); } if (file_exists($html) && !$formatter->refresh) { $out = ""; $fp = fopen($html, "r"); while (!feof($fp)) { $out .= fread($fp, 1024); } return $out; } # comment out the following two lines to freely use any syntaxes. if (!in_array($type, $syntax)) { return "<pre class='code'>\n{$line}\n" . htmlspecialchars($src) . "\n</pre>\n"; } $geshi = new GeSHi($src, $type, dirname(__FILE__) . "/../../lib/geshi/geshi"); if ($extra == "number") { $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS); } if ($extra == "fancy") { $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS); } else { $geshi->enable_line_numbers(GESHI_NO_LINE_NUMBERS); } $out = ''; $geshi->set_comments_style(1, 'font-style: normal;'); $geshi->set_header_type(GESHI_HEADER_DIV); #$geshi->set_header_type(GESHI_HEADER_PRE); #$out = '<style type="text/css"><!--'.$geshi->get_stylesheet().'--></style>'; #$geshi->enable_classes(); $out .= $geshi->parse_code(); $fp = fopen($html, "w"); fwrite($fp, $out); fclose($fp); return $out; }
define('INC_MONIWIKI', 1); # Start Main require_once "wiki.php"; $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);
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_Play($formatter, $value) { global $DBInfo; static $autoplay = 1; $max_width = 600; $max_height = 400; $default_width = 320; $default_height = 240; # $media = array(); # preg_match("/^(([^,]+\\s*,?\\s*)+)\$/", $value, $match); if (!$match) { return '[[Play(error!! ' . $value . ')]]'; } if (($p = strpos($match[1], ',')) !== false) { $my = explode(',', $match[1]); for ($i = 0, $sz = count($my); $i < $sz; $i++) { if (strpos($my[$i], '=')) { list($key, $val) = explode('=', $my[$i]); $val = trim($val, '"\''); if ($key == 'width' and $val > 1) { $width = $val; } else { if ($key == 'height' and $val > 1) { $height = $val; } } } else { // multiple files $media[] = $my[$i]; } } } else { $media[] = $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("/^(http|ftp|mms|rtsp):\\/\\//", $media[$i])) { $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("/^(http|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 = ''; $object_prefered = false; // http://code.google.com/p/google-code-project-hosting-gadgets/source/browse/trunk/video/video.js if (preg_match("@https?://(?:[a-z-]+[.])?(?:youtube(?:[.][a-z-]+)+|youtu\\.be)/(?:watch[?].*v=|v/|embed/)?([a-z0-9_-]+)\$@i", $media[$i], $m)) { $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"; $mediainfo = 'Youtube movie'; $objclass = ' youtube'; } else { if (preg_match("@https?://tvpot\\.daum\\.net\\/v\\/(.*)\$@i", $media[$i], $m)) { $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[1] . '&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"; $mediainfo = 'Daum movie'; $objclass = ' daum'; } else { if (preg_match("@https?://vimeo\\.com\\/(.*)\$@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 = 'http://player.vimeo.com/video/' . $m[1] . '?portrait=0&color=333'; $attr = 'frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen'; if (empty($mysize)) { $attr .= ' width="500px" height="281px"'; } } $mediainfo = 'Vimeo movie'; $objclass = ' vimeo'; } 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}'><div> <iframe 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 { $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 processor_metapost($formatter, $value = "") { global $DBInfo; # site spesific variables $mpost = "mpost"; $dvips = "dvips"; $convert = "convert -transparent white -crop 0x0 -density 120x120"; $vartmp_dir =& $DBInfo->vartmp_dir; $cache_dir = $DBInfo->upload_dir . "/MetaPost"; $option = '-T -interaction=batchmode '; if ($value[0] == '#' and $value[1] == '!') { list($line, $value) = explode("\n", $value, 2); } if (!$value) { return; } if (preg_match('/beginfig\\(/', $value)) { $out = '<font color=red>Don\'t use beginfig()!</font>'; $out .= "<pre>\n"; $out .= $value; $out .= "</pre>\n"; return $out; } $mp = $value; $uniq = md5($mp); if (!empty($DBInfo->cache_public_dir)) { $fc = new Cache_text('metapost', array('dir' => $DBInfo->cache_public_dir)); $basename = $fc->getKey($mp); $png = $DBInfo->cache_public_dir . '/' . $basename . '.png'; $ps = $DBInfo->cache_public_dir . '/' . $basename . '.ps'; $png_url = $DBInfo->cache_public_url . '/' . $basename . '.png'; $ps_url = $DBInfo->cache_public_url . '/' . $basename . '.ps'; } else { $png = $cache_dir . '/' . $uniq . '.png'; $ps = $cache_dir . '/' . $uniq . '.png'; $png_url = $DBInfo->url_prefix . '/' . $png; $ps_url = $DBInfo->url_prefix . '/' . $ps; if (!file_exists($cache_dir)) { umask(00); mkdir($cache_dir, 0777); umask(022); } } $vartmp_basename = $vartmp_dir . '/' . $uniq; $src = "beginfig(1);\n{$mp}\nendfig;\n"; if ($formatter->refresh || !file_exists($png)) { $fp = fopen($vartmp_dir . "/{$uniq}.mp", "w"); fwrite($fp, $src); fclose($fp); $outpath = $png; # Unix specific FIXME $dir = getcwd(); chdir($vartmp_dir); $cmd = "{$mpost} {$option} {$uniq} >/dev/null"; $fp = popen($cmd . $formatter->NULL, 'r'); pclose($fp); chdir($dir); $cmd = "{$convert} {$vartmp_basename}.1 {$outpath}"; $fp = popen($cmd . $formatter->NULL, 'r'); pclose($fp); @copy("{$vartmp_basename}.1", $ps); unlink("{$vartmp_basename}.1"); unlink("{$vartmp_basename}.mp"); unlink("{$vartmp_basename}.log"); } return "<a href='{$ps_url}'><img class='tex' border='0' src='{$png_url}' alt='mp'" . "title=\"{$mp}\" /></a>"; }
function macro_IpInfo($formatter, $value = '', $params = array()) { global $Config; $list = ''; if ($value == 'static') { $cache = new Cache_text('settings', array('depth' => 0)); if (($ips = $cache->fetch('blacklist')) !== false) { $list = _ip_table($ips); } } else { $retval = array(); $ret = array('retval' => &$retval); $infos = array(); if (!empty($params['info'])) { $infos[] = $params['info']; } else { if ($value == 'range') { $range = true; } else { $range = false; } $infos = get_temporary_blocked_info(!$range); } $list = '<table class="wiki editinfo">'; $list .= '<tr><th>' . _("IP or IP range") . '</th><th>' . _("Last updated") . '</th>' . '<th>' . _("Status") . '</th><th>' . _("Expire or Elapsed") . '</th><th>' . _("actions") . '</th></tr>'; foreach ($infos as $info) { $ttl = $info['ttl'] - (time() - $info['mtime']); $tmp = $ttl; if ($ttl < 0) { $tmp = time() - $info['mtime']; } $d = intval($tmp / 60 / 60 / 24); $tmp -= $d * 60 * 60 * 24; $h = intval($tmp / 60 / 60); $tmp -= $h * 60 * 60; $m = intval($tmp / 60); $tmp -= $m * 60; $s = $tmp % 60; $ttl_time = ''; if (!empty($d)) { $ttl_time = $d . ' ' . _("days") . ' '; } $ttl_time .= sprintf("%02d:%02d:%02d", $h, $m, $s); if ($ttl <= 0) { $ttl_time = '<span style="color:gray">Permenent: ' . $ttl_time . '</span>'; } else { $ttl_time = $ttl_time; } $anchor = 'a-' . substr(md5($info['id']), 0, 7); $list .= '<tr><td>'; $list .= '<a name="' . $anchor . '"></a>'; $list .= '<a href="?action=ipinfo&q=' . $info['id'] . '"><span>' . $info['id'] . '</span></a></td>'; $list .= '<td>' . date('Y-m-d H:i:s', $info['mtime']) . '</td>'; $list .= '<th>' . ($info['suspended'] ? '<span style="color:red">S</span>' : '') . '</th>'; $list .= '<th>' . $ttl_time . '</th>'; $list .= '<td><a class="button-small" href="?action=ipinfo&q=' . $info['id'] . '"><span>' . _("Edit") . '</span></a>'; $list .= ' <a class="button-small" href="?action=ipinfo&toggle=1&q=' . $info['id'] . '"><span>' . _("Toggle") . '</span></a>'; $list .= '</td></tr>'; if (!empty($info['comment'])) { $comments = explode("\n", $info['comment']); $comment = '<ul>'; foreach ($comments as $c) { list($date, $by, $log) = explode("\t", $c); $comment .= '<li>[' . $date . '] ' . $log . ' --' . $by . '</li>' . "\n"; } $comment .= '</ul>'; $list .= '<tr><td> </td><td colspan="7"><div class="msgboard">' . $comment . '</div></td></tr>'; } } $list .= '</table>'; } return $list; }
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_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_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 macro_BBS($formatter, $value, $options = array()) { global $DBInfo; # set defaults $ncount = 20; # default $bname = $formatter->page->name; $nid = ''; # check options $args = preg_split('/\\s*,\\s*/', $value); foreach ($args as $arg) { $arg = trim($arg); if ($arg == '') { continue; } if (($p = strpos($arg, '=')) !== false) { $k = substr($arg, 0, $p); $v = substr($arg, $p + 1); if ($k == 'no') { $nid = $v; } else { if ($k == 'mode') { $options['mode'] = $v; } } } else { if ($arg == 'mode') { } else { if ($arg == (int) $arg . "") { $ncount = $arg; } else { $bname = $arg; } } } } $bpage = _rawurlencode($bname); $nid = $nid ? $nid : $_GET['no']; $nids = array(); if ($nid) { $nids = preg_split('/\\s+/', $nid); rsort($nids); } $options['p'] = $_GET['p'] > 0 ? $_GET['p'] : 1; $options['c'] = $ncount != 20 ? $ncount : ''; $options['p'] = intval($options['p']); # is it exists ? if (!$DBInfo->hasPage($bname)) { return _("This bbs does not exists yet. Please save this page first"); } # load a config file $conf0 = array(); if (file_exists('config/bbs.' . $bname . '.php')) { $confname = 'bbs.' . $bname . '.php'; $conf0 = _load_php_vars('config/bbs.default.php'); } else { $confname = 'bbs.default.php'; } $conf = _load_php_vars('config/' . $confname); $conf = array_merge($conf0, $conf); $conf['data_dir'] = $DBInfo->data_dir; $conf['dba_type'] = $DBInfo->dba_type; if (!$DBInfo->use_bbs) { return '[[BBS]]'; } #if ($DBInfo->use_bbs == 1); #if ($DBInfo->use_bbs == 2); $MyBBS = new BBS_text($bname, $conf); // XXX if ($options['new'] and $MyBBS) { return $MyBBS; } if (!$MyBBS) { return '[[BBS]]'; } $msg = ''; $btn = array(); # read messages # $formatter->baserule[] = "/^((-=)+-?\$)/"; $formatter->baserule[] = "/ comment #(\\d+)\\b/"; $formatter->baserule[] = "/\\[reply (\\d+)\\]/"; $formatter->baserepl[] = "<hr />\n"; $formatter->baserepl[] = " comment [#c\\1 #\\1]"; $formatter->baserepl[] = "<script type='text/javascript'><!--\n" . " addReplyLink(\\1); //--></script>"; $msg = ''; $narticle = sizeof($nids); $js = ''; if ($nid and $narticle == 1 and $options['mode'] == 'simple') { $nid = $nids[0]; if (!$nid or !$MyBBS->hasPage($nid)) { return '[[BBS(error)]]'; } include_once 'lib/metadata.php'; $body = $MyBBS->getPage($nid); list($metas, $body) = _get_metadata($body); $img = ''; if ($MyBBS->use_attach) { $cache = new Cache_text('attachments'); $attachs = $cache->fetch($MyBBS->bbsname . ':' . $nid); if (preg_match('/^attachment:([^\\?]+)(\\?.*)?$/', $attachs[0], $m)) { $img = $formatter->macro_repl('Attachment', $m[1] . '?thumbwidth=100'); } $subject = $formatter->link_tag($bpage, "?no={$nid}", $metas['Subject']); } $out = "<div class='simpleView'><table>\n" . "<tr><td class='img'>" . $img . "</td><td class='subject'>" . $subject . '</td></tr>' . "<tr><td colspan='2'></td>\n</tr></table></div>"; return $out; } foreach ($nids as $nid) { if (!$nid or !$MyBBS->hasPage($nid)) { continue; } $fields = array('Name', 'Subject', 'Date', 'Email', 'HomePage', 'IP', 'Keywords'); include_once 'lib/metadata.php'; #Name: wkpark #Subject: Oh well #Date: 2006-04-29 42:04:39 #Email: wkpark@gmail.com #HomePage: #IP: 2xx.xxx.xxx.x $body = $MyBBS->getPage($nid); if ($body != null) { $options['nosisters'] = 1; $MyBBS->counter->incCounter($nid, $options); list($metas, $body) = _get_metadata($body); $boundary = strtoupper(md5("COMMENT")); # XXX $copy = $body; list($comment, $copy) = explode("----" . $boundary . "\n", $copy, 2); while (!empty($comment)) { list($comment, $copy) = explode("----" . $boundary . "\n", $copy, 2); if (preg_match('/^Comment-Id:\\s*(\\d+)/i', $comment, $m)) { list($myhead, $my) = explode("\n\n", $comment, 2); $hidden .= '<pre style="display:none;" id="comment_text_' . $m[1] . '">' . _html_escape($my) . '</pre>'; } } ob_start(); # add some basic rule/repl for bts $rule = "/-{4}(?:" . $boundary . ")?\nComment-Id:\\s*(\\d+)\n" . "From:\\s*([^\n]+)\nDate:\\s*([^\n]+)\n\n/im"; $repl = "----\n'''Comment-Id:''' [#c\\1][#c\\1 #\\1] by \\2 on [[DateTime(\\3)]] [reply \\1]\n\n"; $body = preg_replace($rule, $repl, $body); $formatter->quote_style = 'bbs-comment'; $options['usemeta'] = 1; # $q_save = $formatter->self_query; $query = '?no=' . $nid . '&p=' . $options['p']; $formatter->self_query = $query; $save = $formatter->preview; $formatter->preview = 1; $save_markup = $formatter->format; ob_start(); if ($conf['default_markup']) { $formatter->pi['#format'] = $conf['default_markup']; } $formatter->send_page($body, $options); $body = ob_get_contents(); ob_end_clean(); $formatter->pi['#format'] = $save_markup; $formatter->self_query = $q_save; $msg .= "<div class='bbsArticle'>" . '<div class="head"><h2>' . _("No") . ' ' . $nid . ': ' . $metas['Subject'] . '</h2></div>' . '<div class="body">' . '<div class="extra"> @ ' . $metas['Date'] . ' (' . _mask_hostname($metas['IP'], 3) . ')</div>' . '<div class="user"><h3>' . $metas['Name'] . '</h3></div>' . '<div class="article">' . $body . "</div>\n</div>\n" . '<div class="foot"><div></div></div>' . "</div>\n"; $snid = $nid; $btn['edit'] = $formatter->link_tag($bpage, "?action=bbs&mode=edit&no=" . $nid, '<span>' . _("Edit") . '</span>', 'class="button"'); $btn['delete'] = $formatter->link_tag($bpage, "?action=bbs&mode=delete&no=" . $nid, '<span>' . _("Delete") . '</span>', 'class="button"'); if ($narticle == 1 and $conf['use_comment']) { $opts['action'] = 'bbs'; $opts['no'] = $nid; $opts['p'] = $options['p']; $opts['mode'] = 'comment'; $opts['nopreview'] = 1; $p = new WikiPage($bname . ':' . $opts['no'], $options); $opts['datestamp'] = $p->mtime(); $comment = $formatter->macro_repl('Comment', 'usemeta', $opts); unset($opts['no']); # XXX } $msg .= '<div class="bbsComment">' . $comment . '</div><div class="bbsArticleBtn">' . implode(" ", $btn) . '</div>'; unset($btn['delete']); unset($btn['edit']); $title = str_replace('"', '\\"', $metas['Subject']); $js .= <<<JS <script type="text/javascript"> /*<![CDATA[*/ document.title+=" [" + {$snid} + "] - " + "{$title}"; /*]]>*/ </script> JS; } } if (!empty($msg) and !$_GET['p']) { return $msg; } if (1) { # XXX $nochk = _("Please check article numbers."); $js .= <<<JS <script type='text/javascript'> /*<![CDATA[*/ function send_list(obj,mode) { var tmp=""; var i, chk=false; form=obj.parentNode.parentNode; for(i=0;i< form.length;i++) { if(form[i].type!="checkbox") continue; if(form[i].checked) { tmp+=form[i].value+" "; chk=true; } } if(chk==true) { form.no.value = tmp.substr(0,tmp.length-1); if (mode!=undefined) { form.elements.action.value = 'bbs'; form.elements.mode.value = mode; } else { form.removeChild(form.elements.mode); form.removeChild(form.elements.action); } form.submit(); return false; } alert ("{$nochk}"); return false; } /*]]>*/ </script> JS; } # get list $options['perpage'] = $ncount; $list = $MyBBS->getList($ncount, $options); # get total number of articles $tot = $MyBBS->getCount(); $pages = intval($tot / $ncount); if ($tot % $ncount) { $pages++; } if ($options['mode'] == 'rss') { $rss = '<' . '?xml version="1.0" encoding="utf-8"?>' . "\n" . '<rss version="2.0">' . "\n"; $rss .= "<channel>\n<title>" . $DBInfo->sitename . ": </title>\n"; $rss .= "<link>" . qualifiedUrl($formatter->link_url($bpage)) . "</link>\n"; $rss .= "<description></description>\n"; $rss .= "<pubDate>" . gmdate('D, j M Y H:i:s', time()) . " +0000</pubDate>\n"; foreach ($list as $l) { $item = "<item>\n"; $item .= "<title><![CDATA[" . $l[7] . "]]></title>\n"; $item .= "<link>" . qualifiedUrl($formatter->link_url($bpage, "?no={$l['0']}")) . "</link>\n"; $item .= "<author><![CDATA[" . $l[3] . "]]></author>\n"; $item .= "<description><![CDATA[" . $l[3] . "]]></description>\n"; $item .= "<pubDate>" . gmdate('D, j M Y H:i:s', $l[2]) . " +0000</pubDate>\n</item>\n"; $rss .= $item; } $rss .= "</channel>\n</rss>\n"; return $rss; } else { if ($options['mode'] == 'simple') { $simple = "<div class='bbsSimple'><table class='bbsSimple'>\n"; foreach ($list as $l) { $date = date("Y-m-d", $l[2]); $my = $l[7]; $title = ''; if (function_exists('mb_strimwidth') and strlen($l[7]) > 60) { $title = 'title="' . $l[7] . '"'; $my = mb_strimwidth($l[7], 0, 40, '...', $DBInfo->charset); } $simple .= "<tr><td class='date'>[" . $date . "]</td><td>" . $formatter->link_tag($bpage, "?no={$l['0']}" . $extra, $my, $title) . '</td></tr>'; } $simple .= "<tr><td colspan='2' class='more'>" . $formatter->link_tag($bpage, "", _("More") . '»') . "</td>\n</tr>\n"; $simple .= "</table>"; return $simple; } } if ($pages > 1) { $pnut = _get_pagelist($formatter, $pages, '?' . $extra . ($extra ? '&p=' : 'p='), $options['p'], $ncount); } else { $pnut = "<div class='clear'></div>"; } $extra = $options['p'] ? '&p=' . $options['p'] : ''; #$head=array(_("no"),'C',_("Title"),_("Name"),_("Date"),_("Hit")); #$out.="<col width='3%' class='num' /><col width='1%' class='check' /><col width='63%' class='title' /><col width='14%' /><col width='13%' /><col width='7%' class='hit' />\n"; #$out.='<thead><tr><th>'.implode("</th><th>",$head)."</th></tr><thead>\n"; #$out.="<tbody>\n"; $item = array(); foreach ($list as $l) { $nid =& $l[0]; $ip =& $l[1]; $date = date("Y-m-d", $l[2]); $user = $l[3]; $subject = $formatter->link_tag($bpage, "?no={$nid}" . $extra, $l[7]); $hit = $MyBBS->counter->pageCounter($nid); $chk = '<input type="checkbox" value="' . $nid . '">'; #$item=array(in_array($nid,$nids) ? '<strong>»</strong>':$nid,$chk,$subject,$user,$date,$hit); $item[] = array('num' => in_array($nid, $nids) ? '<strong>»</strong>' : $nid, 'check' => $chk, 'subject' => $subject, 'name' => $user, 'date' => $date, 'hit' => $hit); ##$tmp='<tr><td>'.implode("</td><td>",$item)."</td></tr>\n"; #$tmp="<tr><td class='no'>$item[0]</td><td class='check'>$item[1]</td>". # "<td class='title'>$item[2]</td><td class='name'>$item[3]</td>". # "<td class='date'>$item[4]</td><td class='hit'>$item[5]</td>". # "</tr>\n"; #$out.=$tmp; } $formatter->_vars['item'] =& $item; $out .= $formatter->include_theme('plugin/BBS/default', 'list', array()); #$out.= $formatter->include_theme('plugin/BBS/default_tpl','list',array()); #$out.= $formatter->processor_repl('tpl_','',array('path'=>'theme/plugin/BBS/blue_tpl/list.tpl')); #$out.="</tbody>\n"; $btn['new'] = $formatter->link_tag($bpage, "?action=bbs&mode=edit", '<span>' . _("New") . '</span>', 'class="button"'); unset($btn['edit']); $bn['view'] = $formatter->link_tag($bpage, "", '<span>' . _("Read") . '</span>', 'onclick="return send_list(this)" onfocus="blur()" class="button"'); $bn['delete'] = $formatter->link_tag($bpage, "", '<span>' . _("Delete") . '</span>', 'onclick="return send_list(this,\'delete\')" onfocus="blur()" class="button"'); $del = "<div class='bbsAdminBtn'>" . implode(" ", $bn) . "</div>\n"; $btns = "<div class='bbsBtn'>" . implode(" ", $btn) . "</div>\n"; $lnk = $formatter->link_url($bpage, '?action=bbs'); $form0 = "<form method='get' action='{$lnk}'>\n"; $form1 = '<input type="hidden" name="no" />'; if ($options['p']) { $form1 .= '<input type="hidden" name="p" value="' . $options['p'] . "\" />\n"; } $form1 .= '<input type="hidden" name="mode" />' . '<input type="hidden" name="action" />'; $form1 .= "</form>\n"; $pnut = "<div class='pnut'>{$pnut}</div>"; $info = '<div class="bbsRSS">' . sprintf(_("Total %s articles."), '<strong>' . $tot . '</strong>') . ' ' . $formatter->link_tag($bpage, '?action=bbs&mode=rss', $formatter->icon['rss']) . '</div>'; return $info . $pnut . $msg . $js . $form0 . $out . $del . $form1 . $pnut . $btns; }
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_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_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 processor_latex(&$formatter, $value = "", $options = array()) { global $DBInfo; if (empty($formatter->latex_uniq)) { $formatter->latex_all = ''; $formatter->latex_uniq = array(); } $latex_convert_options = !empty($DBInfo->latex_convert_options) ? $DBInfo->latex_convert_options : "-trim -crop 0x0 -density 120x120"; $raw_mode = isset($options['retval']) ? 1 : 0; # site spesific variables $latex = "latex"; $dvicmd = "dvipng"; $dviopt = '-D 120 -gamma 1.3'; $convert = "convert"; $mogrify = "mogrify"; $vartmp_dir =& $DBInfo->vartmp_dir; $cache_dir = $DBInfo->upload_dir . "/LaTeX"; $cache_url = !empty($DBInfo->upload_url) ? $DBInfo->upload_url . '/LaTeX' : $DBInfo->url_prefix . '/' . $cache_dir; $option = '-interaction=batchmode '; $mask = ''; $options['dpi'] = intval($options['dpi']); if (preg_match('/ps$/', $dvicmd)) { $tmpext = 'ps'; $dviopt = '-D 300'; if (!empty($options['dpi'])) { $latex_convert_options .= ' -density ' . $options['dpi'] . 'x' . $options['dpi']; } } else { $tmpext = 'png'; $mask = '-%d'; if (!empty($options['dpi'])) { $dviopt = preg_replace('/-D 120/', '', $dviopt); $dviopt .= ' -D ' . $options['dpi']; } } if ($value[0] == '#' and $value[1] == '!') { list($line, $value) = explode("\n", $value, 2); } if (!$value) { if (empty($DBInfo->latex_allinone)) { return ''; } } $tex = $value; if (!empty($DBInfo->latex_renumbering)) { $GLOBALS['_latex_eq_num'] = !empty($formatter->latex_num) ? $formatter->latex_num : 0; // renumbering // just remove numbers and use \\tag{num} $ntex = preg_replace_callback('/\\\\begin\\{\\s*(equation)\\s*\\}((.|\\n)+)\\\\end\\{\\s*\\1\\s*\\}/', '_latex_renumber', $tex); #print '<pre>'.$ntex.'</pre>'; if ($tex != $ntex) { $tex = $ntex; } $formatter->latex_num = $GLOBALS['_latex_eq_num']; // save } else { if (!$raw_mode and !empty($DBInfo->latex_allinone)) { $chunks = preg_split('/(\\\\begin\\{\\s*(?:equation)\\s*\\}(?:(?:.|\\n)+)\\\\end\\{\\s*\\1\\s*\\})/', $tex, -1, PREG_SPLIT_DELIM_CAPTURE); if (($sz = count($chunks)) > 0) { $ntex = ''; for ($i = 1; $i < $sz; $i += 2) { $ntex .= $chunks[$i - 1]; preg_match('/\\\\begin\\{\\s*(equation)\\s*\\}((.|\\n)+)\\\\end\\{\\s*\\1\\s*\\}/', $chunks[$i], $m); $ntex .= _latex_renumber(array('', $m[1], $m[2]), "\n%%"); } $tex = $ntex; } #print '<pre>'.$ntex.'</pre>'; } } if (!empty($DBInfo->latex_template) and file_exists($DBInfo->data_dir . '/' . $DBInfo->latex_template)) { $templ = implode('', file($DBInfo->data_dir . '/' . $DBInfo->latex_template)); } else { $head = !empty($DBInfo->latex_header) ? $DBInfo->latex_header : ''; $templ = "\\documentclass[10pt,notitlepage]{article}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{amsfonts}{$head}\n%%\\usepackage[all]{xy}\n\\pagestyle{empty}\n\\begin{document}\n@TEX@\n\\end{document}\n%%{$dviopt}\n%%{$latex_convert_options}\n"; } $src = str_replace('@TEX@', $tex, $templ); $uniq = $tex ? md5($src) : $formatter->latex_uniq[sizeof($formatter->latex_uniq) - 1]; // check image file exists if (empty($raw_mode) and !empty($DBInfo->latex_allinone) and $tex) { $formatter->latex_uniq[] = $uniq; $formatter->latex_all .= $tex . "\n\\pagebreak\n\n"; #print '<pre>'.$tex.'</pre>'; } if (!empty($DBInfo->cache_public_dir)) { $fc = new Cache_text('latex', array('ext' => 'png', 'dir' => $DBInfo->cache_public_dir)); $pngname = $fc->getKey($uniq, false); $png = $DBInfo->cache_public_dir . '/' . $pngname; $png_url = !empty($DBInfo->cache_public_url) ? $DBInfo->cache_public_url . '/' . $pngname : $DBInfo->url_prefix . '/' . $png; } else { $png = $cache_dir . '/' . $uniq . '.png'; $png_url = $cache_url . '/' . $uniq . '.png'; } if (!is_dir(dirname($png))) { $om = umask(00); _mkdir_p(dirname($png), 0777); umask($om); } $NULL = '/dev/null'; if (getenv("OS") == "Windows_NT") { $NULL = 'NUL'; $vartmp_dir = getenv('TEMP'); #$convert="wconvert"; } $bra = ''; $ket = ''; if (!empty($formatter->preview) and empty($DBInfo->latex_allinone)) { $bra = '<span class="previewTex"><input type="checkbox" class="previewTex" name="_tex_' . $uniq . '" />'; $ket = '</span>'; } $img_exists = file_exists($png); $log = ''; while (!empty($formatter->preview) || !empty($formatter->refresh) || !$img_exists) { //if ($options['_tex_'.$uniq] || $formatter->refresh || !file_exists($png)) { if (empty($raw_mode) and !empty($DBInfo->latex_allinone)) { if (empty($value)) { #$js= '<script type="text/javascript" src="'.$DBInfo->url_prefix.'/local/latex.js"></script>'; if ($formatter->register_javascripts('latex.js')) { } $src = str_replace('@TEX@', $formatter->latex_all, $templ); #print '<pre>'.$src.'</pre>'; $uniq = md5($src); } else { $formatter->postamble['latex'] = 'processor:latex:'; break; } } $fp = fopen($vartmp_dir . "/{$uniq}.tex", "w"); fwrite($fp, $src); fclose($fp); $outpath =& $png; # Unix specific FIXME $cwd = getcwd(); chdir($vartmp_dir); $formatter->errlog('Dum', $uniq . '.log'); $cmd = "{$latex} {$option} {$uniq}.tex >{$NULL}"; $fp = popen($cmd . $formatter->NULL, 'r'); pclose($fp); $log = $formatter->get_errlog(1, 1); if ($log) { #list($dum,$log,$dum2)=preg_split('/\n!/',$log,3); if (($p = strpos($log, "\n!")) !== FALSE) { $log = substr($log, $p); $log = "<pre class='errlog'>" . $log . "</pre>\n"; } else { $log = ''; } } if (!file_exists($uniq . ".dvi")) { if (!$image_mode) { $log .= "<pre class='errlog'><font color='red'>ERROR:</font> LaTeX does not work properly.</pre>"; trigger_error($log, E_USER_WARNING); } chdir($cwd); return ''; } #$formatter->errlog('DVIPS'); $cmd = "{$dvicmd} {$dviopt} {$uniq}.dvi -o {$uniq}{$mask}.{$tmpext}"; $formatter->errlog('DVI', $uniq . '.log'); $fp = popen($cmd . $formatter->NULL, 'r'); pclose($fp); $log2 = $formatter->get_errlog(); if ($log2 and !$raw_mode) { trigger_error($log2, E_USER_NOTICE); } chdir($cwd); chdir(dirname($outpath)); # XXX :( if ($tmpext == 'ps') { $cmd = "{$convert} -transparent white {$latex_convert_options} {$vartmp_dir}/{$uniq}.{$tmpext} " . basename($outpath); } else { if (!$raw_mode and !empty($DBInfo->latex_allinone)) { $outpath = "{$vartmp_dir}/{$uniq}.{$tmpext}"; } $cmd = "{$mogrify} -transparent white {$latex_convert_options} {$vartmp_dir}/{$uniq}*.{$tmpext}"; } # ImageMagick of the RedHat AS 4.x do not support -trim option correctly # http://kldp.net/forum/message.php?msg_id=12024 #$cmd= "$convert -transparent white -trim -crop 0x0 -density 120x120 $vartmp_dir/$uniq.ps $outpath"; $formatter->errlog('CNV', $uniq . '.log'); $fp = popen($cmd . $formatter->LOG, 'r'); pclose($fp); $log2 = $formatter->get_errlog(1, 1); if (!$raw_mode and $log2) { trigger_error($log2, E_USER_WARNING); } chdir($cwd); if ($raw_mode or $tmpext == 'png' and empty($DBInfo->latex_allinone)) { rename("{$vartmp_dir}/{$uniq}-1.{$tmpext}", $outpath); } else { if ($DBInfo->latex_allinone) { $sz = sizeof($formatter->latex_uniq); if ($tmpext == 'png') { $soutpath = preg_replace('/\\.png/', '', $outpath); if (file_exists($outpath . '.0')) { # old convert behavior $soutpath = "{$soutpath}.png.%d"; } else { $soutpath = "{$soutpath}-%d.png"; } # new behavior :( } for ($i = 0; $i < $sz; $i++) { $id = $formatter->latex_uniq[$i]; if ($DBInfo->cache_public_dir) { $pngname = $fc->getKey($id, false); $img = $DBInfo->cache_public_dir . '/' . $pngname; } else { $img = $cache_dir . '/' . $id . '.png'; } if ($tmpext == 'ps' and $sz == 1) { rename($outpath, $img); } else { $ii = $i; if ($tmpext == 'png') { $ii++; } rename(sprintf($soutpath, $ii), $img); } } $formatter->latex_all = ''; $formatter->latex_uniq = array(); $formatter->postamble['latex'] = ''; } } @unlink($vartmp_dir . "/{$uniq}.log"); @unlink($vartmp_dir . "/{$uniq}.aux"); @unlink($vartmp_dir . "/{$uniq}.tex"); @unlink($vartmp_dir . "/{$uniq}.dvi"); @unlink($vartmp_dir . "/{$uniq}.bib"); @unlink($vartmp_dir . "/{$uniq}.ps"); $img_exists = true; break; } if (!$raw_mode and !$value) { return $js; } $alt = str_replace("'", "'", $value); $title = $alt; if (!$raw_mode and !$img_exists) { $title = $png_url; if ($DBInfo->latex_allinone == 1 && empty($formatter->wikimarkup)) { $png_url = $DBInfo->imgs_dir . '/loading.gif'; } } if (!$raw_mode) { return $log . $bra . "<img class='tex' src='{$png_url}' rel='{$uniq}' alt='{$alt}' " . "title='{$title}' />" . $ket; } $retval =& $options['retval']; $retval = $png; return $png_url; }
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 processor_gnuplot($formatter = "", $value = "") { global $DBInfo; $convert = "convert"; if (getenv("OS") == "Windows_NT") { $gnuplot = "wgnuplot"; } else { $gnuplot = "gnuplot"; } $vartmp_dir =& $DBInfo->vartmp_dir; if ($value[0] == '#' and $value[1] == '!') { list($line, $value) = explode("\n", $value, 2); } if (strpos($line, ' ') !== false) { list($dum, $szarg) = explode(' ', $line); $args = explode('x', $szarg, 2); if (count($args) > 2) { $xsize = max(intval($args[0]), 50); $ysize = max(intval($args[1]), 50); } $value = '#' . $line . "\n" . $value; } #$term='dumb'; // for w3m,lynx $term = 'png'; if ($term == 'png') { $ext = 'png'; } else { if ($term == 'dumb') { $ext = 'txt'; } } $default_size = "set size 0.5,0.6"; $body = $plt = $value; while ($body and $body[0] == '#') { # extract first line list($line, $body) = explode("\n", $body, 2); # skip comments (lines with two hash marks) if ($line[1] == '#') { continue; } # parse the PI list($verb, $arg) = explode(' ', $line, 2); $verb = strtolower($verb); $arg = rtrim($arg); if (in_array($verb, array('#size'))) { $args = explode('x', $arg, 2); $xsize = intval($args[0]); $ysize = intval($args[1]); } } if (!empty($xsize)) { if ($xsize > 640 or $xsize < 100) { $xscale = 0.5; } if ($xscale and ($ysize > 480 or $ysize < 100)) { $yscale = 0.6; } $xscale = $xsize / 640.0; if (empty($yscale)) { $yscale = $xscale / 0.5 * 0.6; } $size = 'set size ' . $xscale . ',' . $yscale; } else { $size = $default_size; } # a sample for testing # $plt=' #set term gif #! ls #plot sin(x) #'; # normalize plt $plt = str_replace("\r\n", "\n", $plt); $plt = "\n" . $plt . "\n"; $plt = preg_replace("/\n\\s*![^\n]+\n/", "\n", $plt); # strip shell commands $plt = preg_replace("/[ ]+/", " ", $plt); preg_match("/\nset?\\s+(t|te|ter|term)\\s(.*)\n/", $plt, $tmatch); $plt = preg_replace("/\nset?\\s+(t|o|si).*\n/", "\n", $plt); $plt = preg_replace("/system/", "", $plt); # strip system() function # $plt = preg_replace("/('|\")<(\\s*)/", "\\1\\2", $plt); # strip all redirection mark #print "<pre>$plt</pre>"; if ($tmatch) { if (preg_match('/^postscript\\s*(enhanced|color)?/', $tmatch[2])) { // XXX $term = $tmatch[2]; $ext = 'ps'; $size = '#set term ' . $term; } else { if (preg_match('/^svg/', $tmatch[2])) { $term = $tmatch[2]; $ext = 'svg'; $size = "set size 1.0,1.0\n#set term " . $term; } } } if ($term != 'dumb') { $plt = "\n" . $size . "\n" . $plt; } $uniq = md5($plt); if ($DBInfo->cache_public_dir) { $fc = new Cache_text('gnuplot', array('ext' => $ext, 'dir' => $DBInfo->cache_public_dir)); $pngname = $fc->getKey($uniq, false); $png = $DBInfo->cache_public_dir . '/' . $pngname; $png_url = $DBInfo->cache_public_url ? $DBInfo->cache_public_url . '/' . $pngname : $DBInfo->url_prefix . '/' . $png; $cache_dir = $DBInfo->cache_public_dir; } else { $cache_dir = $DBInfo->upload_dir . "/GnuPlot"; $cache_url = $DBInfo->upload_url ? $DBInfo->upload_url . '/GnuPlot' : $DBInfo->url_prefix . '/' . $cache_dir; $png = $cache_dir . '/' . $uniq . ".{$ext}"; $png_url = $cache_url . '/' . $uniq . ".{$ext}"; } $outpath =& $png; $src = "\nset term {$term}\nset out '{$outpath}'\n{$plt}\n"; if (!is_dir(dirname($png))) { $om = umask(00); _mkdir_p(dirname($png), 0777); umask($om); } $log = ''; if ($formatter->refresh || !file_exists($outpath)) { $flog = tempnam($vartmp_dir, "GNUPLOT"); # # for Win32 wgnuplot.exe # if (getenv("OS") == "Windows_NT") { $finp = tempnam($vartmp_dir, "GNUPLOT"); $ifp = fopen($finp, "w"); fwrite($ifp, $src); fclose($ifp); $cmd = "{$gnuplot} \"{$finp}\" > {$flog}"; $fp = system($cmd); $log = join(file($flog), ""); if (file_exists($outpath)) { unlink($flog); unlink($finp); } else { print "<font color='red'>ERROR:</font> Gnuplot does not work correctly"; } } else { # # Unix # $cmd = $gnuplot; $formatter->errlog('GnuPlot'); $fp = popen($cmd . $formatter->LOG, "w"); if (is_resource($fp)) { fwrite($fp, $src); pclose($fp); } $log = $formatter->get_errlog(); if (filesize($outpath) == 0) { $log .= "\n<font color='red'>ERROR:</font> Gnuplot does not work correctly"; unlink($outpath); } } if ($log) { $log = "<pre class='errlog'>{$log}</pre>\n"; } } $rext = $ext; $rpng_url = $png_url; if ($ext == 'ps' and file_exists($outpath)) { $routpath = preg_replace('/\\.' . $ext . '$/', '.png', $outpath); if ($formatter->refresh || !file_exists($routpath)) { $cmd = "{$convert} -rotate 90 {$outpath} {$routpath}"; $fp = popen($cmd . $formatter->NULL, 'r'); pclose($fp); } $rpng_url = preg_replace('/\\.' . $ext . '$/', '.png', $png_url); $rext = 'png'; } else { if ($ext == 'svg') { $fp = fopen($outpath, 'r'); if ($fp) { $svg = fread($fp, filesize($outpath)); fclose($fp); $svg = preg_replace('/<svg [^>]+>/', '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">', $svg); $fp = fopen($outpath, 'w'); if ($fp) { fwrite($fp, $svg); fclose($fp); } } } } $bra = ''; $ket = ''; if ($ext == 'ps') { $bra = '<a href="' . $png_url . '" />'; $ket = '</a>'; } if (!file_exists($outpath)) { return $log; } if ($rext == 'png') { return $log . $bra . "<img src='{$rpng_url}' alt='gnuplot' style='border:0' />" . $ket; } if ($rext == 'svg') { return $log . $bra . "<embed src='{$rpng_url}' alt='gnuplot' width='640' height='480' />" . $ket; } if ($rext == 'txt') { return $log . '<pre class="gnuplot">' . implode('', file("{$cache_dir}/{$pngname}")) . '</pre>'; } }