function do_filter($formatter, $options) { if (!$options['filter']) { do_invalid($formatter, $options); return; } $body = $formatter->page->get_raw_body($options); $filters = preg_split("/(\\||,)/", $options['filter']); if ($options['raw']) { $formatter->send_header('Content-Type: text/plain'); } else { $formatter->send_header('', $options); } foreach ($filters as $ft) { $body = $formatter->filter_repl(trim($ft), $body, $options); } if ($options['raw']) { print $body; return; } $formatter->send_title('', '', $options); print '<pre>' . $body . '</pre>'; $formatter->send_footer("", $options); return; }
function do_vote($formatter, $options) { global $DBInfo; if ($options['id'] == 'Anonymous') { if (!isset($options['msg'])) { $options['msg'] = ''; } $options['msg'] .= "\n" . _("Please Login or make your ID on this Wiki ;)"); do_invalid($formatter, $options); return; } if (!$options['ticket'] and !$options['vote']) { return '<html><h1>Error</h1></html>'; } $body = $formatter->page->get_raw_body(); $lines = explode("\n", $body); $count = count($lines); for ($i = 0; $i < $count; $i++) { if ($test = preg_match_all("/\\[\\[Vote\\(([^\\]]+)\\)\\]\\]/", $lines[$i], $tickets)) { foreach ($tickets[1] as $ticket) { $tic = preg_replace($formatter->baserule, $formatter->baserepl, $ticket); if (md5($tic) == $options['ticket']) { $save = $ticket; $items = explode(",", $tic); $rawitems = explode(",", $ticket); for ($k = 0; $k < sizeof($items); $k++) { preg_match("/(^.+)\\s+(\\d+)\$/", $items[$k], $match); preg_match("/(^.+)\\s+(\\d+)\$/", $rawitems[$k], $rawmatch); $votes[$rawmatch[1]] = (int) $match[2]; if (md5($match[1]) == $options['vote']) { $votes[$rawmatch[1]]++; $voted = 1; } } if ($voted) { while (list($item, $count) = each($votes)) { $args .= "{$item} {$count},"; } $args = substr($args, 0, -1); $lines[$i] = str_replace("[[Vote({$save})]]", "[[Vote({$args})]]", $lines[$i]); break; } } } } } if ($voted) { $formatter->page->write(join("\n", $lines)); $DBInfo->savePage($formatter->page, "Vote", $options); $options[msg] = _("Voted successfully"); } $formatter->send_header("", $options); $formatter->send_title("", "", $options); $formatter->send_page(); $formatter->send_footer("", $options); return; }
function do_format($formatter, $options) { $mimes = array('text/plain' => 'html', 'text/xml' => 'text_xml'); $mimetype = $options['mimetype']; $proc = !empty($options['proc']) ? $options['proc'] : ''; if (!$mimetype) { $mimetype = 'text/plain'; } $pi = $formatter->page->get_instructions($dummy); if (!$formatter->wordrule) { $formatter->set_wordrule($pi); } if ($pi['#format'] == 'xsltproc') { $options['title'] = _("It is a XML format !"); do_invalid($formatter, $options); return; } if (!$formatter->page->exists()) { do_invalid($formatter, $options); return; } else { if (empty($proc) and array_key_exists($mimetype, $mimes)) { header("Content-type: " . $mimetype); print $formatter->processor_repl($mimes[$mimetype], $formatter->page->get_raw_body(), $options); } else { if (!empty($proc)) { #if (getProcessor($processor)) { # do_invalid($formatter,$options); # return; #} #header("Content-type: ".$mimetype); header("Content-type: text/plain"); print $formatter->processor_repl($proc, $formatter->page->get_raw_body(), $options); } else { $processor = str_replace("/.", "__", $mimetype); header("Content-type: text/plain"); if (getProcessor($processor)) { print $formatter->processor_repl($processor, $formatter->page->get_raw_body(), $options); } else { do_invalid($formatter, $options); return; } } } } return; }
function do_rcspurge($formatter, $options) { global $DBInfo; # XXX if (!$options['show'] and $DBInfo->security->is_protected("rcspurge", $options) and !$DBInfo->security->is_valid_password($options['passwd'], $options)) { $title = sprintf('Invalid password to purge "%s" !', $options['page']); $formatter->send_header("", $options); $formatter->send_title($title); $formatter->send_footer(); return; } if (!preg_match("/^[\\d:;\\.]+\$/", $options['range'])) { $options['title'] = _("Invalid rcspurge range"); do_invalid($formatter, $options); return; } $title = sprintf(_("RCS purge \"%s\""), $options['page']); $formatter->send_header("", $options); $formatter->send_title($title, "", $options); if ($options['range']) { $ranges = explode(';', $options['range']); foreach ($ranges as $range) { if (!trim($range)) { continue; } printf("<h3>range '%s' purged</h3>", $range); if ($options['show']) { print "<tt>rcs -o{$range} " . $options['page'] . "</tt><br />"; } else { #print "<b>Not enabled now</b> <tt>rcs -o$range data_dir/".$options[page]."</tt><br />"; print "<tt>rcs -o{$range} " . $options['page'] . "</tt><br />"; $fp = popen("rcs -o{$range} " . $formatter->page->filename . $formatter->NULL, 'r'); pclose($fp); } } } else { printf("<h3>No version selected to purge '%s'</h3>", $options['page']); } $args['noaction'] = 1; $formatter->send_footer($args, $options); }
function do_aclinfo($formatter, $options) { global $DBInfo; if ($DBInfo->security_class == 'acl') { list($allowed, $denied, $protected) = $DBInfo->security->get_acl('aclinfo', $options); } else { $options['msg'] = _("ACL is not enabled on this Wiki"); do_invalid($formatter, $options); return; } $formatter->send_header('', $options); $formatter->send_title('', '', $options); print '<h2>' . _("Your ACL Info") . '</h2>'; if (in_array($options['id'], $DBInfo->owners)) { print '<h4>' . _("You are wiki owner") . "</h4>\n"; } else { if (in_array($options['id'], $DBInfo->wikimasters)) { print '<h4>' . _("You are wiki master") . "</h4>\n"; } else { print '<h4>' . _("Allowed actions") . "</h4>\n"; print '<ul>'; foreach ($allowed as $k => $v) { print '<li>' . $k . ': (' . $v . ')</li>'; } print '</ul>'; print '<h4>' . _("Denied actions") . "</h4>\n"; print '<ul>'; foreach ($denied as $k => $v) { print '<li>' . $k . ': (' . $v . ')</li>'; } print '</ul>'; print '</pre>'; print '<h4>' . _("Protected actions") . "</h4>\n"; print '<ul><li>'; print implode('</li><li>', $protected); print '</li></ul>'; } } $formatter->send_footer('', $options); return; }
function do_post_jme($formatter, $options) { global $DBInfo; if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($options)) { $options['title'] = _("Page is not writable"); return do_invalid($formatter, $options); } $draw_dir = str_replace("./", '', $DBInfo->upload_dir . '/JME'); $pagename = $options['page']; !empty($options['value']) ? $name = $options['value'] : !empty($options['name']) ? $name = $options['name'] : null; if (empty($name)) { $name = time(); } if ($_SERVER['REQUEST_METHOD'] == 'POST' and $options['mol']) { $dummy = explode('/', $name); $name = $dummy[count($dummy) - 1]; $molname = $name . '.mol'; $fp = fopen($draw_dir . '/' . $molname, 'w'); if ($fp) { fwrite($fp, $options['mol']); fclose($fp); } $formatter->send_header('', $options); $formatter->send_title(_("Molecule successfully added"), '', $options); $formatter->send_footer('', $options); return; } $formatter->send_header('', $options); $formatter->send_title(_("Edit Molecule"), '', $options); $script = <<<SCRIPT <script type="text/javascript"> /*<![CDATA[*/ function setMolFile(obj) { var mol = document.JME.molFile(); obj.mol.value = mol; } function getGauFile(obj) { var mol = document.JME.molFile(); var lines = mol.split("\\n"); var i=0; var gau="%chk=\\n# ub3lyp/6-311g(d,p) OPT FREQ POP=full\\n\\n"; gau += obj.name.value + "\\n\\n0 1\\n"; while (i < lines.length) { var mat = lines[i].match(/^\\s+([^\\s]+)\\s+([^\\s]+)\\s+([^\\s]+)\\s+([A-Z]{1,2})\\s+.*/); if (mat != null) { gau += mat[4] + ' ' + mat[1] + ' ' + mat[2] + ' ' + mat[3] + "\\n"; } i++; } obj.mol.value = gau + "\\n"; } /*]]>*/ </script> SCRIPT; $pubpath = $DBInfo->url_prefix . "/applets/JMEPlugin"; print "<h2>" . _("Edit new molecule") . "</h2>\n"; $name = _html_escape($name); print <<<FORM {$script} <form method="POST" action=""> <applet code="JME.class" name="JME" codebase="{$pubpath}" archive="JME.zip" width="360" height="315"> <param name=" options" value="multipart; autoez";> You have to enable Java and JavaScritpt on your machine ! </applet><br /> <input type="hidden" name="action" value="jme" /> <input type="hidden" name="name" value="{$name}" /> <input type="submit" name="submit_button" value="Submit" onclick="setMolFile(this.form)" /> <input type="button" name="gau_button" value="Get Gaussian input" onclick="getGauFile(this.form)" /> <input type="button" value="Get Mol" onclick="setMolFile(this.form)" /> <input type="reset" value="reset" /> <div class="molecule"> <textarea cols="50" rows="20" name="mol" /></textarea></div> </form> FORM; $formatter->send_footer("", $options); return; }
function do_OeKaki($formatter, $options) { global $DBInfo; if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($options)) { $options['title'] = _("Page is not writable"); return do_invalid($formatter, $options); } $oekaki_dir = $DBInfo->upload_dir . '/OeKaki'; $pagename = $options['page']; $name = $options['value']; # $fp=fopen('php://stderr','w'); # fputs($fp,"name=$name\n"); # fputs($fp,"page=$options[page]\n"); # if ($_SERVER['REQUEST_METHOD']=='POST') { # $len = $_SERVER['CONTENT_LENGTH']; # fputs($fp,"len=$len\n"); # fputs($fp,"method=POST\n"); # } if (!$name) { $name = time(); } # XXX $pngname = 'OeKaki_' . _rawurlencode($name); $imgurl = "{$DBInfo->url_prefix}/{$oekaki_dir}/{$pngname}.png"; $imgpath = "{$oekaki_dir}/{$pngname}.png"; $dummy = 0; $backup_imgpath = $imgpath; while (file_exists($backup_imgpath)) { $dummy = $dummy + 1; $ufname = $pngname . "_" . $dummy; // rename file $upfilename = $ufname . ".png"; $backup_imgpath = "{$oekaki_dir}/{$upfilename}"; } if ($GLOBALS['HTTP_RAW_POST_DATA']) { if ($formatter->page->exists()) { $body = $formatter->page->get_raw_body(); } else { $body = ''; } if (!preg_match("/\n?\\[\\[OeKaki\\({$name}\\)\\]\\]\n?/i", $body)) { if (preg_match("/\n##Draw\n/i", $body)) { $body = preg_replace("/\n##Draw\n/", "\n##Draw\n[[OeKaki({$name})]]\n", $body); } else { $body .= "[[OeKaki({$name})]]\n"; } $log = "Oekaki drawing added"; $formatter->page->write($body); # XXX Oekaki post does not hav any information about user id. $DBInfo->savePage($formatter->page, $log, $options); } if ($backup_imgpath != $imgpath) { copy($imgpath, $backup_imgpath); } $raw = $GLOBALS['HTTP_RAW_POST_DATA']; $p = strpos($raw, "\r"); if ($p < 0) { header("Content-type: text/plain"); print "error\n\n"; } else { $img = fopen($imgpath, 'w'); if (is_resource($img)) { fwrite($img, substr($raw, $p + 2)); fclose($img); } } header("Content-type: text/plain"); print "ok\n\n"; print $imgpath; return; } if ($options['size'] and preg_match("/(\\d{3})x(\\d{3})/", $options['size'], $match)) { $sizex = $match[1]; $sizey = $match[2]; if ($sizex < 100 or $sizex > 600) { $sizex = 300; } if ($sizey < 100 or $sizey > 600) { $sizey = 300; } } else { $sizex = 300; $sizey = 300; } $extra = "<param name='image_canvas' value='{$imgurl}'>"; $formatter->send_header("", $options); $formatter->send_title(_("Create new picture"), "", $options); $prefix = $formatter->prefix; $now = time(); $urlpgname = _rawurlencode($options['page']); $imgname = _rawurlencode($name); $url_exit = $formatter->link_url($urlpgname, "?ts={$now}"); $url_save = $formatter->link_url($urlpgname, "----OeKaki----{$imgname}"); $pubpath = $DBInfo->url_prefix . "/applets/OekakiPlugin"; print "<h2>" . _("Edit Image") . "</h2>\n"; print <<<APPLET <applet code="pbbs.PaintBBS.class" archive="PaintBBS.jar" codebase="{$pubpath}" name="{$pngname}.png" width="400" height="400" align="center"> <param name="image_width" value="{$sizex}"> <param name="image_height" value="{$sizey}"> <param name="image_bkcolor" value="#ffffff"> {$extra} <param name="image_jpeg" value="true"> <param name="image_size" value="60"> <param name="compress_level" value="15"> <param name="undo" value="60"> <param name="undo_in_mg" value="15"> <param name="color_text"value="#708090"> <param name="color_bk" value="#A0A0BB"> <param name="color_bk2" value="#A0A0BB"> <param name="color_icon" value="#eeeeee"> <param name="color_bar" value="#8f93a1"> <param name="color_bar_hl" value="#ffffff"> <param name="color_bar_frame_hl" value="#eeeeee"> <param name="color_bar_frame_shadow" value="#aaaaaa"> <param name="bar_size" value="15"> <param name="url_save" value="{$url_save}"> <param name="url_exit" value="{$url_exit}"> <param name="tool_advance" value="true"> <param name="send_advance" value="true"> <param name="send_header" value=""> <param name="send_header_image_type" value="false"> <param name="poo" value="true"> <param name="thumbnail_width" value="100%%"> <param name="thumbnail_height" value="100%%"> <param name="security_click" value="0"> <param name="security_timer" value="0"> <param name="security_url" value=""> <param name="security_post" value="false"> <b>NOTE:</b> You need a Java enabled browser to edit the drawing example. </applet><br> APPLET; $formatter->send_footer("", $options); return; }
function do_ticket($formatter, $options) { global $DBInfo; $word_length = 4; if (!empty($options['__seed'])) { // check seed // check referer $passwd = getTicket($options['__seed'], $_SERVER['REMOTE_ADDR'], $word_length); } else { $options['title'] = _("Invalid use of ticket"); do_invalid($formatter, $options); return; } if (!empty($DBInfo->gdfontpath)) { putenv('GDFONTPATH=' . $DBInfo->gdfontpath); } else { // set default GDFONTPATH $old = getenv('GDFONTPATH'); $path = $DBInfo->data_dir; if ($old) { $path = $old . ':' . $new; } putenv('GDFONTPATH=' . $path); } if (function_exists('ImageTtfText')) { while (!empty($DBInfo->ticket_font)) { if (is_numeric($DBInfo->ticket_font)) { break; } $FONT = $DBInfo->ticket_font; //$FONT="/home/foobar/data/PenguinAttack.ttf"; if ($FONT[0] == '/' and !file_exists($FONT)) { $use_ttf = 0; } else { $FONT = $DBInfo->ticket_font; $use_ttf = 1; } break; } } if (!empty($use_ttf)) { $pointsize = !empty($DBInfo->ticket_font_size) ? $DBInfo->ticket_font_size : 16; $angle = 0; //$size = Imagettfbbox($pointsize, 0, $FONT, $passwd); // XXX segfault :( $margin = $pointsize / 2; $size = array(0, 0, 0, 20, 65); //$size=array(0,0,0,20,50); //$w=$size[4]+20; # margin=20 ? $w = $pointsize * $word_length + $margin; $h = $pointsize + $margin; if ($DBInfo->use_ticket & 23) { $h += $pointsize / 3; } } else { $FONT = 5; // giant if (!empty($DBInfo->ticket_gdfont)) { $FONT = $DBInfo->ticket_gdfont; } $w = imagefontwidth($FONT) * strlen($passwd) + 10; $h = imagefontheight($FONT); $pointsize = $h; $h += 10; } $im = ImageCreate($w, $h); $color = array(); if (isset($DBInfo->captcha_bgcolor) and preg_match('/^#[0-9a-fA-F]$/', $DBInfo->captcha_bgcolor)) { $r = substr($DBInfo->captcha_bgcolor, 1, 2); $g = substr($DBInfo->captcha_bgcolor, 3, 2); $b = substr($DBInfo->captcha_bgcolor, 5, 2); $color[] = ImageColorAllocate($im, hexdec($r), hexdec($g), hexdec($b)); // background } else { $color[] = ImageColorAllocate($im, 240, 240, 240); // default background } $color[] = ImageColorAllocate($im, 0, 0, 0); // black $color[] = ImageColorAllocate($im, 255, 255, 255); // white $pen = rand(3, 19); $pen1 = rand(3, 19); for ($i = 0; $i < 18; $i++) { $color[] = ImageColorAllocate($im, rand(100, 200), rand(100, 200), rand(100, 200)); } if (!empty($use_ttf)) { $sx = $margin; $sy = $margin / 2 + $pointsize; ImageTtfText($im, $pointsize, $angle, $sx, $sy + 1, $color[$pen], $FONT, $passwd); ImageTtfText($im, $pointsize, $angle, $sx + 1, $sy, $color[$pen], $FONT, $passwd); } else { ImageString($im, $FONT, 5, 3, $passwd, $color[$pen]); ImageString($im, $FONT, 4, 4, $passwd, $color[$pen]); } $grad = ''; if ($DBInfo->use_ticket & 8) { $grad = 1; } if ($DBInfo->use_ticket & 4) { _effect_distort($im, $pointsize, $grad); } else { if ($DBInfo->use_ticket & 16) { _effect_distort($im, $pointsize, $grad, 1); } } if ($DBInfo->use_ticket & 1) { _effect_blur($im, $color, 1, 1); } if ($DBInfo->use_ticket & 2) { _effect_grid($im, $color, $pen1); } if (function_exists("imagepng")) { header("Content-Type: image/png"); imagepng($im); } else { if (function_exists("imagegif")) { header("Content-Type: image/gif"); imagegif($im); } else { if (function_exists("imagejpeg")) { $jpeg_quality = 5; header("Content-Type: image/jpeg"); imagejpeg($im, null, $jpeg_quality); } } } ImageDestroy($im); }
function do_userform($formatter, $options) { global $DBInfo; $user =& $DBInfo->user; # get cookie $id = !empty($options['login_id']) ? $options['login_id'] : ''; $use_any = 0; if (!empty($DBInfo->use_textbrowsers)) { if (is_string($DBInfo->use_textbrowsers)) { $use_any = preg_match('/' . $DBInfo->use_textbrowsers . '/', $_SERVER['HTTP_USER_AGENT']) ? 1 : 0; } else { $use_any = preg_match('/Lynx|w3m|links/', $_SERVER['HTTP_USER_AGENT']) ? 1 : 0; } } $options['msg'] = ''; # e-mail conformation if (!empty($options['ticket']) and $id and $id != 'Anonymous') { $userdb =& $DBInfo->udb; $suspended = false; if ($userdb->_exists($id)) { $user = $userdb->getUser($id); } else { if ($userdb->_exists($id, 1)) { // suspended user $suspended = true; $user = $userdb->getUser($id, 1); } } if ($user->id == $id) { if ($user->info['eticket'] == $options['ticket']) { list($dummy, $email) = explode('.', $options['ticket'], 2); $user->info['email'] = $email; $user->info['eticket'] = ''; if ($suspended) { if (empty($DBInfo->register_confirm_admin)) { $userdb->activateUser($id); $userdb->saveUser($user); } else { $userdb->saveUser($user, array('suspended' => 1)); } } else { $userdb->saveUser($user); } $title = _("Successfully confirmed"); $options['msg'] = _("Your e-mail address is confirmed successfully"); if (!empty($DBInfo->register_confirm_admin)) { $options['msg'] .= "<br />" . _("Your need to wait until your ID activated by admin"); } } else { if ($user->info['nticket'] == $options['ticket']) { $title = _("Successfully confirmed"); $user->info['nticket'] = ''; $user->info['password'] = $user->info['npassword']; $user->info['npassword'] = ''; $userdb->saveUser($user); $options['msg'] = _("Your new password is confirmed successfully"); } else { $title = _("Confirmation missmatched !"); $options['msg'] = _("Please try again to register your e-mail address"); } } } else { if ($suspended) { $title = _("Please wait until your ID is confirmed by admin!"); } else { $title = _("ID does not exist !"); } $options['msg'] = _("Please try again to register your e-mail address"); } $formatter->send_header("", $options); $formatter->send_title($title, "", $options); $formatter->send_footer("", $options); return ''; } $title = ''; if ($user->id == "Anonymous" and !empty($options['emailreset'])) { setcookie('MONI_VERIFIED_EMAIL', '', time() - 3600, get_scriptname()); $options['msg'] .= '<br />' . _("Verification E-mail removed."); $options['verifyemail'] = ''; $user->verified_email = ''; } else { if ($user->id == "Anonymous" and !empty($options['login']) and !empty($options['verify_email'])) { $email = base64_decode($options['login']); $ticket = base64_encode(getTicket($_SERVER['REMOTE_ADDR'], $email, 10)); if ($ticket == $options['verify_email']) { $options['msg'] .= '<br />' . _("Your email address is successfully verified."); $user->verified_email = $email; setcookie('MONI_VERIFIED_EMAIL', $email, time() + 60 * 60 * 24 * 30, get_scriptname()); } else { $options['msg'] .= '<br />' . _("Verification missmatched."); } } else { if ($user->id == "Anonymous" and $options['verify'] == _("Verify E-mail address") and !empty($DBInfo->anonymous_friendly) and !empty($options['verifyemail'])) { if (preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $options['verifyemail'])) { if (($ret = verify_email($options['verifyemail'])) < 0) { $ret = -$ret; $options['msg'] .= '<br />' . 'ERROR Code: ' . $ret; $options['msg'] .= '<br/>' . _("Invalid email address or can't verify it."); } else { if (!empty($DBInfo->verify_email)) { if ($DBInfo->verify_email == 1) { $options['msg'] .= '<br/>' . _("Your email address is successfully verified."); setcookie('MONI_VERIFIED_EMAIL', $options['verifyemail'], time() + 60 * 60 * 24 * 30, get_scriptname()); } else { $opts = array(); $opts['subject'] = "[{$DBInfo->sitename}] " . _("Verify Email address"); $opts['email'] = $options['verifyemail']; $opts['id'] = 'nobody'; $ticket = base64_encode(getTicket($_SERVER['REMOTE_ADDR'], $opts['email'], 10)); $enc = base64_encode($opts['email']); $body = qualifiedUrl($formatter->link_url('UserPreferences', "?action=userform&login={$enc}&verify_email={$ticket}")); $body = _("Please confirm your e-mail address") . "\n" . $body . "\n"; $ret = wiki_sendmail($body, $opts); $options['msg'] .= '<br/>' . _("E-mail verification mail sent"); } } } } else { $options['msg'] .= '<br/>' . _("Your email address is not valid"); } } else { if ($user->id == "Anonymous" and !empty($options['login_id']) and isset($options['password']) and !isset($options['passwordagain'])) { if (method_exists($user, 'login')) { $user->login($formatter, $options); $params = array(); $params['value'] = $options['page']; do_goto($formatter, $params); return; } # login $userdb = $DBInfo->udb; if ($userdb->_exists($id)) { $user = $userdb->getUser($id); $login_ok = 0; if (!empty($DBInfo->use_safelogin)) { if (isset($options['challenge']) and $options['_chall'] == $options['challenge']) { #print '<pre>'; #print $options['password'].'<br />'; #print hmac($options['challenge'],$user->info['password']); #print '</pre>'; if (hmac($options['challenge'], $user->info['password']) == $options['password']) { $login_ok = 1; } } else { # with no javascript browsers $md5pw = md5($options['password']); if ($md5pw == $user->info['password']) { $login_ok = 1; } } } if ($login_ok or $user->checkPasswd($options['password']) === true) { $options['msg'] = sprintf(_("Successfully login as '%s'"), $id); $options['id'] = $user->id; if ($user->id == 'Anonymous') { // special case. login success but ID is not acceptable $options['msg'] = _("Invalid user ID. Please register again"); } else { $formatter->header($user->setCookie()); if (!isset($user->info['login_success'])) { $user->info['login_success'] = 0; } if (!isset($user->info['login_fail'])) { $user->info['login_fail'] = 0; } $user->info['login_success']++; $user->info['last_login'] = gmdate("Y/m/d H:i:s", time()); $user->info['login_fail'] = 0; // reset login $user->info['remote'] = $_SERVER['REMOTE_ADDR']; $userdb->saveUser($user); $use_refresh = 1; } $DBInfo->user = $user; } else { $title = sprintf(_("Invalid password !")); if (!isset($user->info['login_fail'])) { $user->info['login_fail'] = 0; } $user->info['login_fail']++; $user->info['remote'] = $_SERVER['REMOTE_ADDR']; $userdb->saveUser($user); $user->setID('Anonymous'); } } else { if (isset($options['login_id'][0])) { if ($userdb->_exists($id, 1)) { // suspended user $title = sprintf(_("\"%s\" is waiting for activated by admin !"), $options['login_id']); } else { $title = sprintf(_("\"%s\" does not exist on this wiki !"), $options['login_id']); } $options['login_id'] = ''; } else { $title = _("Make new ID on this wiki"); } $form = macro_UserPreferences($formatter, '', $options); } } else { if (!empty($options['logout'])) { # logout header($user->unsetCookie(), false); if (session_name() != '') { $path = get_scriptname(); // for moniwiki internal header('Set-Cookie: ' . session_name() . '=' . $user->id . '; expires=Tuesday, 01-Jan-1999 12:00:00 GMT; Path=' . $path, false); // for some user plugins $params = session_get_cookie_params(); header('Set-Cookie: ' . session_name() . '=' . $user->id . '; expires=Tuesday, 01-Jan-1999 12:00:00 GMT; Path=' . $params['path'], false); } // call logout method if (method_exists($user, 'logout')) { $user->logout($formatter, $options); } else { $options['msg'] = _("Cookie deleted !"); } $user->id = 'Anonymous'; $DBInfo->user = $user; $use_refresh = 1; } else { if (!empty($DBInfo->use_sendmail) and $options['login'] == _("E-mail new password") and $user->id == "Anonymous" and !empty($options['email']) and !empty($options['login_id'])) { # email new password $title = ''; if (!$use_any and $DBInfo->use_ticket) { if ($options['__seed'] and $options['check']) { $mycheck = getTicket($options['__seed'], $_SERVER['REMOTE_ADDR'], 4); if ($mycheck == $options['check']) { $ok_ticket = 1; } else { $title = _("Invalid ticket !"); } } else { $title = _("You need a ticket !"); } } else { $ok_ticket = 1; } $userdb =& $DBInfo->udb; if ($userdb->_exists($id)) { $user = $userdb->getUser($id); } if ($ok_ticket and $user->id != "Anonymous") { if ($options['email'] == $user->info['email'] and $user->info['eticket'] == '') { #make new password $mypass = base64_encode(getTicket(time(), $_SERVER['REMOTE_ADDR'], 10)); $mypass = substr($mypass, 0, 8); $options['password'] = $mypass; $old_passwd = $user->info['password']; if ($DBInfo->use_safelogin) { $ret = $user->setPasswd(md5($mypass), md5($mypass), 1); } else { $ret = $user->setPasswd($mypass, $mypass); } $new_passwd = $user->info['password']; $user->info['password'] = $old_passwd; $user->info['npassword'] = $new_passwd; #make ticket $ticket = md5(time() . $user->id . $options['email']); $user->info['nticket'] = $ticket . "." . $options['email']; // save join agreement if (!empty($DBInfo->use_agreement) and !empty($options['joinagreement'])) { $user->info['join_agreement'] = 'agree'; if (!empty($DBInfo->agreement_version)) { $user->info['join_agreement_version'] = $DBInfo->agreement_version; } } $userdb->saveUser($user); # XXX $opts['subject'] = "[{$DBInfo->sitename}] " . _("New password confirmation"); $opts['email'] = $options['email']; $opts['id'] = 'nobody'; $body = qualifiedUrl($formatter->link_url('', "?action=userform&login_id={$user->id}&ticket={$ticket}.{$options['email']}")); $body = _("Please confirm your new password") . "\n" . $body . "\n"; $body .= sprintf(_("Your new password is %s"), $mypass) . "\n\n"; $body .= _("Please change your password later") . "\n"; $ret = wiki_sendmail($body, $opts); if (is_array($ret)) { $title = _("Fail to e-mail notification !"); $options['msg'] = $ret['msg']; } else { $title = _("New password is sent to your e-mail !"); $options['msg'] = _("Please check your e-mail"); } } else { if ($options['email'] != $user->info['email']) { $title = _("Fail to e-mail notification !"); $options['msg'] = _("E-mail mismatch !"); } else { $title = _("Invalid request"); $options['msg'] = _("Please confirm your e-mail address first !"); } } } else { if (!$ok_ticket) { $title = _("Invalid ticket !"); } else { $title = _("ID and e-mail mismatch !"); } $options['msg'] = _("Please try again or make a new profile"); } $formatter->send_header("", $options); $formatter->send_title($title, "", $options); $formatter->send_footer("", $options); return; } else { if ($user->id == "Anonymous" and !empty($options['login_id']) and ($options['password'] and $options['passwordagain'] or $DBInfo->use_safelogin and $options['email'])) { # create profile $title = ''; if (!$use_any and !empty($DBInfo->use_ticket)) { if ($options['__seed'] and $options['check']) { $mycheck = getTicket($options['__seed'], $_SERVER['REMOTE_ADDR'], 4); if ($mycheck == $options['check']) { $ok_ticket = 1; } else { $title = _("Invalid ticket !"); } } else { $title = _("You need a ticket !"); } } else { $ok_ticket = 1; } $id = $user->getID($options['login_id']); if (preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $id)) { if (($ret = verify_email($id)) < 0) { $ret = -$ret; $options['msg'] .= '<br />' . 'ERROR Code: ' . $ret; $options['msg'] .= '<br/>' . _("Invalid email address or can't verify it."); } else { $options['email'] = $id; $user->setID($id); } } else { if (!preg_match("/\\//", $id)) { $user->setID($id); } } // protect http:// style id if (!empty($DBInfo->use_agreement) and empty($options['joinagreement'])) { $title = _("Please check join agreement."); } else { if ($ok_ticket and $user->id != "Anonymous") { if (!empty($DBInfo->use_safelogin)) { $mypass = base64_encode(getTicket(time(), $_SERVER['REMOTE_ADDR'], 10)); $mypass = substr($mypass, 0, 8); $options['password'] = $mypass; $ret = $user->setPasswd(md5($mypass), md5($mypass), 1); } else { $ret = $user->setPasswd($options['password'], $options['passwordagain']); } if (!empty($DBInfo->password_length) and strlen($options['password']) < $DBInfo->password_length) { $ret = 0; } if ($ret <= 0) { if ($ret == 0) { $title = _("too short password!"); } else { if ($ret == -1) { $title = _("mismatch password!"); } else { if ($ret == -2) { $title = _("not acceptable character found in the password!"); } } } } else { if ($ret < 8 and empty($DBInfo->use_safelogin)) { $options['msg'] = _("Your password is too simple to use as a password !"); } $udb = $DBInfo->udb; if ($options['email']) { if (preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $options['email'])) { if (($ret = verify_email($options['email'])) < 0) { $options['email'] = ''; // reset email address $ret = -$ret; $options['msg'] .= '<br />' . 'ERROR Code: ' . $ret; $options['msg'] .= '<br/>' . _("Can't verify E-mail address! Please check your email address."); } } else { $options['msg'] .= '<br/>' . _("Your email address is not valid"); } } if ($udb->isNotUser($user)) { if (!empty($DBInfo->no_register)) { $options['msg'] = _("Fail to register"); $options['err'] = _("You are not allowed to register on this wiki"); $options['err'] .= "\n" . _("Please contact WikiMasters"); do_invalid($formatter, $options); return; } $title = sprintf(_("Successfully added as '%s'"), _html_escape($user->id)); $options['id'] = $user->id; $ticket = md5(time() . $user->id . $options['email']); $user->info['eticket'] = $ticket . "." . $options['email']; if (!empty($DBInfo->use_safelogin)) { $options['msg'] = sprintf(_("Successfully added as '%s'"), $user->id); $options['msg'] .= '<br />' . _("Please check your mailbox"); } $args = array(); if ($options['email'] == $id or !empty($DBInfo->register_confirm_email)) { $args = array('suspended' => 1); } if (!empty($DBInfo->register_confirm_admin)) { $args = array('suspended' => 1); } if (!empty($DBInfo->register_confirm_admin)) { if (!empty($options['msg'])) { $options['msg'] .= '<br />'; } $options['msg'] .= _("Your need to wait until your ID activated by admin"); } // save join agreement if (!empty($DBInfo->use_agreement) and !empty($options['joinagreement'])) { $user->info['join_agreement'] = 'agree'; if (!empty($DBInfo->agreement_version)) { $user->info['join_agreement_version'] = $DBInfo->agreement_version; } } if (empty($DBInfo->use_safelogin) && empty($args['suspended'])) { $formatter->header($user->setCookie()); } $ret = $udb->addUser($user, $args); # XXX if (!empty($options['email']) and preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $options['email'])) { $options['subject'] = "[{$DBInfo->sitename}] " . _("E-mail confirmation"); $body = ''; if (!empty($DBInfo->email_register_header) and file_exists($DBInfo->email_register_header)) { $body = file_get_contents($DBInfo->email_register_header); $body = str_replace(array('@sitename@'), array($DBInfo->sitename), $body); } $body .= _("Please confirm your email address") . "\n\n"; $body .= qualifiedUrl($formatter->link_url('', "?action=userform&login_id={$user->id}&ticket={$ticket}.{$options['email']}")); $body .= "\n"; if (!empty($DBInfo->use_safelogin)) { $body .= "\n" . sprintf(_("Your initial password is %s"), $mypass) . "\n\n"; $body .= _("Please change your password later") . "\n"; } $ret = wiki_sendmail($body, $options); if (is_array($ret)) { $options['msg'] .= $ret['msg']; } else { $options['msg'] .= '<br/>' . _("Confirmation E-mail sent"); } } } else { # already exist user $user = $udb->getUser($user->id); if ($user->checkPasswd($options['password']) === true) { $options['msg'] .= sprintf(_("Successfully login as '%s'"), $id); $options['id'] = $user->id; $formatter->header($user->setCookie()); $udb->saveUser($user); # XXX } else { $title = _("Invalid password !"); } } } } else { if (empty($title)) { $title = _("Invalid username !"); } } } } else { if ($user->id != "Anonymous") { # save profile $udb =& $DBInfo->udb; $userinfo = $udb->getUser($user->id); if (!empty($options['password']) and !empty($options['passwordagain'])) { $chall = 0; if (!empty($DBInfo->use_safelogin)) { if (isset($options['_chall'])) { $chall = $options['challenge']; } else { $chall = rand(100000); $options['password'] = hmac($chall, $options['password']); } } //echo 'chall=',$chall,' ',$options['password']; if ($userinfo->checkPasswd($options['password'], $chall) === true) { if ($DBInfo->use_safelogin) { $mypass = md5($options['passwordagain']); // XXX $ret = $userinfo->setPasswd($mypass, $mypass, 1); } else { $ret = $userinfo->setPasswd($options['passwordagain']); } if ($ret <= 0) { if ($ret == 0) { $title = _("too short password!"); } else { if ($ret == -1) { $title = _("mismatch password !"); } else { if ($ret == -2) { $title = _("not acceptable character found in the password!"); } } } $options['msg'] = _("Password is not changed !"); } else { $title = _("Password is changed !"); if ($ret < 8) { $options['msg'] = _("Password is too simple to use as a password !"); } } } else { $title = _("Invalid password !"); $options['msg'] = _("Password is not changed !"); } } if (isset($options['user_css'])) { $userinfo->info['css_url'] = $options['user_css']; } if (isset($options['timezone'])) { list($hour, $min) = explode(':', $options['timezone']); $min = $min * 60; $min = $hour < 0 ? -1 * $min : $min; $tz_offset = $hour * 3600 + $min; $userinfo->info['tz_offset'] = $tz_offset; } if (!empty($DBInfo->use_agreement) and !empty($options['joinagreement'])) { $userinfo->info['join_agreement'] = 'agree'; if (!empty($DBInfo->agreement_version)) { $userinfo->info['join_agreement_version'] = $DBInfo->agreement_version; } } $button_check_email_again = !empty($options['button_check_email_again']) ? 1 : 0; if ($button_check_email_again and !empty($userinfo->info['eticket'])) { list($dummy, $email) = explode('.', $userinfo->info['eticket'], 2); if (!empty($email)) { $options['email'] = $email; } } if (!empty($options['email']) and $options['email'] != $userinfo->info['email']) { if (preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $options['email'])) { if (($ret = verify_email($options['email'])) < 0) { $ret = -$ret; $options['msg'] .= '<br />' . 'ERROR Code: ' . $ret; $options['msg'] .= '<br />' . _("Invalid email address or can't verify it."); } else { $ticket = md5(time() . $userinfo->info['id'] . $options['email']); $userinfo->info['eticket'] = $ticket . "." . $options['email']; $options['subject'] = "[{$DBInfo->sitename}] " . _("E-mail confirmation"); $body = qualifiedUrl($formatter->link_url('', "?action=userform&login_id={$user->id}&ticket={$ticket}.{$options['email']}")); $body = _("Please confirm your email address") . "\n" . $body; $ret = wiki_sendmail($body, $options); if (is_array($ret)) { $options['msg'] = $ret['msg']; } else { $options['msg'] = _("E-mail confirmation mail sent"); } } } else { $options['msg'] = _("Your email address is not valid"); } } if (!empty($userinfo->info['idtype']) and $userinfo->info['idtype'] == 'openid' and isset($options['nick']) and $options['nick'] != $userinfo->info['nick']) { $nick = $userinfo->getID($options['nick']); // nickname check XXX if (!$udb->_exists($nick)) { $userinfo->info['nick'] = $nick; } else { $options['msg'] = _("Your Nickname already used as ID in this wiki"); } } $udb->saveUser($userinfo); #$options['css_url']=$options['user_css']; if (!isset($options['msg'])) { $options['msg'] = _("Profiles are saved successfully !"); } } else { if ($user->id == "Anonymous" and isset($options['openid_url'])) { # login with openid include_once 'lib/openid.php'; session_start(); $process_url = qualifiedUrl($formatter->link_url("UserPreferences", "?action=userform")); $trust_root = qualifiedUrl($formatter->link_url("")); $openid = new SimpleOpenID(); $openid->SetIdentity($options['openid_url']); $openid->SetTrustRoot($trust_root); $openid->SetRequiredFields(array('nickname', 'email', 'fullname')); $openid->SetOptionalFields(array('language', 'timezone')); if ($openid->GetOpenIDServer()) { $openid->SetApprovedURL($process_url); // Send Response from OpenID server to this script $openid->Redirect(); // This will redirect user to OpenID Server return; } else { $error = $openid->GetError(); #echo "ERROR CODE: " . $error['code'] . "<br>"; #echo "ERROR DESCRIPTION: " . $error['description'] . "<br>"; $options["msg"] = sprintf(_("Authentication request was failed: %s"), $error['description']); } } else { if (!empty($options['openid_mode']) and $options['openid_mode'] == 'id_res') { // OpenID result include_once 'lib/openid.php'; if (!preg_match('/utf-?8/i', $DBInfo->charset)) { $options['openid_sreg_nickname'] = iconv('utf-8', $DBInfo->charset, $options['openid_sreg_nickname']); $options['openid_sreg_fullname'] = iconv('utf-8', $DBInfo->charset, $options['openid_sreg_fullname']); } $openid = new SimpleOpenID(); $openid->SetIdentity($options['openid_identity']); $openid_validation_result = $openid->ValidateWithServer(); if ($openid_validation_result == true) { // OK HERE KEY IS VALID $userdb =& $DBInfo->udb; // XXX $user->setID($options['openid_identity']); // XXX if (!empty($options['openid_language'])) { $user->info['language'] = strtolower($options['openid_sreg_language']); } //$user->info['tz_offset']=$options['openid_timezone']; if ($userdb->_exists($options['openid_identity'])) { $user = $userdb->getUser($options['openid_identity']); $user->info['idtype'] = 'openid'; $options['msg'] .= sprintf(_("Successfully login as '%s' via OpenID."), $options['openid_identity']); $formatter->header($user->setCookie()); $userdb->saveUser($user); // always save } else { if (!empty($DBInfo->no_register) and $DBInfo->no_register == 1) { $options['msg'] = _("Fail to register"); $options['err'] = _("You are not allowed to register on this wiki"); $options['err'] .= "\n" . _("Please contact WikiMasters"); do_invalid($formatter, $options); return; } if ($options['openid_sreg_nickname']) { $nick = $user->getID($options['openid_sreg_nickname']); if (!$userdb->_exists($nick)) { $user->info['nick'] = $nick; } else { $options['msg'] = sprintf(_("Your Nickname %s already used as ID in this Wiki."), $nick); } } $user->info['email'] = $options['openid_sreg_email']; $user->info['idtype'] = 'openid'; $userdb->addUser($user); $formatter->header($user->setCookie()); $userdb->saveUser($user); $options["msg"] .= sprintf(_("OpenID Authentication successful and saved as %s."), $options['openid_identity']); } $options['id'] = $user->id; } else { if ($openid->IsError() == true) { // ON THE WAY, WE GOT SOME ERROR $error = $openid->GetError(); $options["msg"] = sprintf(_("Authentication request was failed: %s"), $error['description']); } else { // Signature Verification Failed $options["msg"] = _("Invalid OpenID Authentication request"); echo "INVALID AUTHORIZATION"; } } } else { if (!empty($DBInfo->use_agreement) and $options['login'] == _("Make profile")) { $options['agreement'] = 1; $form = macro_UserPreferences($formatter, '', $options); } else { $options["msg"] = _("Invalid request"); } } } } } } } } } } } $myrefresh = ''; if (!empty($DBInfo->use_refresh) and !empty($use_refresh)) { $sec = $DBInfo->use_refresh - 1; if (!empty($options['return_url'])) { $lnk = $options['return_url']; } else { $lnk = $formatter->link_url($formatter->page->urlname, '?action=show'); } $myrefresh = 'Refresh: ' . $sec . '; url=' . qualifiedURL($lnk); } $formatter->send_header($myrefresh, $options); $formatter->send_title($title, "", $options); if (!$title && (empty($DBInfo->control_read) or $DBInfo->security->is_allowed('read', $options))) { $lnk = $formatter->link_to('?action=show'); if (empty($form)) { echo sprintf(_("return to %s"), $lnk); } else { echo $form; } } else { if (!empty($form)) { print $form; } # else $formatter->send_page("Goto UserPreferences"); } $formatter->send_footer("", $options); }
function do_theme($formatter, $options = array()) { global $DBInfo; if (!empty($DBInfo->theme_css)) { $options['title'] = _("Theme disabled !"); $options['msg'] = _("Please contact WikiMasters"); do_invalid($formatter, $options); return _("Theme disabled !"); } $theme = ''; if (preg_match('/^[a-zA-Z0-9_-]+$/', $options['value'])) { $theme = $options['value']; } else { if (preg_match('/^[a-zA-Z0-9_-]+$/', $options['theme'])) { $theme = $options['theme']; } } $themes = macro_Theme($formatter, '', array('call' => 1)); if (!in_array($theme, $themes)) { $title = _("Invalid Theme"); $theme = null; } else { if ($options['id'] == 'Anonymous') { if ($theme == $_COOKIE['MONI_THEME']) { $theme = null; } } else { if ($theme == $DBInfo->user->info['theme']) { $theme = null; } else { if (empty($DBInfo->user->info['theme']) && $theme == $DBInfo->theme) { $theme = null; } } } } if ($options['clear']) { if ($options['id'] == 'Anonymous') { #header("Set-Cookie: MONI_THEME=dummy; expires=Tuesday, 01-Jan-1999 12:00:00 GMT; Path=".get_scriptname()); #header("Set-Cookie: MONI_CSS=dummy; expires=Tuesday, 01-Jan-1999 12:00:00 GMT; Path=".get_scriptname()); setcookie('MONI_THEME', 'dummy', time() - 60 * 60 * 24 * 30, get_scriptname()); setcookie('MONI_CSS', 'dummy', time() - 60 * 60 * 24 * 30, get_scriptname()); $cleared = 1; //$options['css_url']=''; //$options['theme']=''; } else { # save profile $udb = $DBInfo->udb; $userinfo = $udb->getUser($options['id']); $userinfo->info['theme'] = ""; $userinfo->info['css_url'] = ""; $udb->saveUser($userinfo); } $msg = '<h2>' . _("Theme cleared.") . ' ' . sprintf(_("Goto %s"), $formatter->link_repl("UserPreferences")) . '</h2>'; } else { if (!empty($theme)) { $themedir = $formatter->themedir; if (file_exists($themedir . "/header.php")) { # check $options['css_url'] = $formatter->themeurl . "/css/default.css"; if ($options['save'] and $options['id'] == 'Anonymous') { setcookie("MONI_THEME", $theme, time() + 60 * 60 * 24 * 30, get_scriptname()); setcookie("MONI_CSS", $options['css_url'], time() + 60 * 60 * 24 * 30, get_scriptname()); $title = _("Theme is changed"); $msg = "Goto " . $formatter->link_repl("UserPreferences"); } else { if ($options['save'] and $options['id'] != 'Anonymous') { # save profile $udb = $DBInfo->udb; $userinfo = $udb->getUser($options['id']); $userinfo->info['theme'] = $theme; $userinfo->info['css_url'] = $options['css_url']; $udb->saveUser($userinfo); $msg = "Goto " . $formatter->link_repl("UserPreferences"); } else { $title = ""; $want = _("Do you want to apply this theme ?"); $btn = _("OK"); $msg = <<<FORM <form method='post'> <input type='hidden' name='action' value='theme' /> <input type='hidden' name='theme' value="{$theme}" /> {$want} <input type='submit' name='save' value='{$btn}' /> </form> FORM; } } $formatter->send_header("", $options); $formatter->send_title($title, "", $options); print $msg; $formatter->send_footer("", $options); return; } } else { $title = _("Please select a theme"); } } $formatter->send_header("", $options); $formatter->send_title($title, '', $options); if (empty($msg)) { echo macro_Theme($formatter); } else { echo $msg; } $formatter->send_footer("", $options); return; }
function do_rating($formatter, $options) { global $DBInfo; if (!$DBInfo->security->writable($options)) { $options['title'] = _("Page is not writable"); return do_invalid($formatter, $options); } if ($options['id'] == 'Anonymous') { $options['msg'] .= "\n" . _("Please Login or make your ID on this Wiki ;)"); do_invalid($formatter, $options); return; } $formatter->send_header('', $options); $oraw = $formatter->page->get_raw_body(); list($nth, $dum, $v) = explode(',', base64_decode($options['mid']), 3); $val = explode(',', $v); if (sizeof($val) >= 2) { $total = $val[0]; $count = $val[1]; } else { $total = $val[0]; } if (isset($count)) { $count = max(1, $count); } else { $count = 1; } $value = $total / $count; // averaged value if ($total == 0 and $count == 1) { $count = 0; } $value = (!empty($value) and 0 < $value and 6 > $value) ? $value : 0; ++$count; $check = '[[' . $dum . '(' . $v . ')]]'; $rating = $options['rating'] ? (int) $options['rating'] : 1; $rating = min(5, max(0, $rating)); $total += $rating; // increase total rating if (is_numeric($nth)) { $raw = str_replace("\n", "", $oraw); $chunk = preg_split("/({{{.+}}})/U", $raw, -1, PREG_SPLIT_DELIM_CAPTURE); #print '<pre>'; #print_r($chunk); #print '</pre>'; $nc = ''; $k = 1; $i = 1; foreach ($chunk as $c) { if ($k % 2) { $nc .= $c; } else { $nc .= "" . $i . ""; $blocks[$i] = str_replace("", "\n", $c); ++$i; } $k++; } $nc = str_replace("", "\n", $nc); $chunk = preg_split('/((?!\\!)\\[\\[.+\\]\\])/U', $nc, -1, PREG_SPLIT_DELIM_CAPTURE); $nnc = ''; $ii = 1; $matched = 0; for ($j = 0, $sz = sizeof($chunk); $j < $sz; ++$j) { if (($j + 1) % 2) { $nnc .= $chunk[$j]; } else { if ($nth == $ii) { $new = '[[Rating(' . $total . ',' . $count . ')]]'; if ($check != $chunk[$j]) { break; } $nnc .= $new; $matched = 1; } else { $nnc .= $chunk[$j]; } ++$ii; } } if (!empty($blocks)) { $formatter->_array_callback($blocks, true); $nnc = preg_replace_callback("/(\\d+)/", array(&$formatter, '_array_callback'), $nnc); } } if (empty($matched)) { if (!empty($DBInfo->use_rating)) { $dum = ''; $pi = $formatter->page->get_instructions($dum); $old = !empty($pi['#rating']) ? $pi['#rating'] : ''; $new = '#rating ' . $total . ',' . $count; if ($old) { list($ts, $cnt) = explode(',', $old); $raw = preg_replace('/^#rating\\s+.*$/m', $new, $oraw, 1); } else { if (!$formatter->pi) { $raw = $new . "\n" . $oraw; } else { $body = $oraw; $head = ''; while (true) { list($line, $body) = explode("\n", $body, 2); if ($line[0] == '#') { $head .= $line . "\n"; } else { $body = $line . "\n" . $body; break; } } $raw = $head . $new . "\n" . $body; } } #print "<pre>".$raw."</pre>"; $nnc =& $raw; } else { $options['title'] = _("Invalid rating request !"); $formatter->send_title('', '', $options); $formatter->send_footer('', $options); return; } } $formatter->page->write($nnc); $DBInfo->savePage($formatter->page, "Rating", $options); #print "<pre>"; #print_r($options); #print "</pre>"; #print $check; $options['title'] = _("Rating successfully !"); $formatter->send_title('', '', $options); $formatter->send_page('', $options); $formatter->send_footer('', $options); return; }
function do_post_fixbacklinks($formatter, $options = array()) { global $DBInfo; if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($options)) { $options['title'] = _("Page is not writable"); return do_invalid($formatter, $options); } $options['name'] = trim($options['name']); $new = $options['name']; if (!empty($DBInfo->use_namespace) and $new[0] == '~' and ($p = strpos($new, '/')) !== false) { // Namespace renaming ~foo/bar -> foo~bar $dummy = substr($new, 1, $p - 1); $dummy2 = substr($new, $p + 1); $options['name'] = $dummy . '~' . $dummy2; } if (isset($options['name'][0]) and $options['name']) { if ($DBInfo->hasPage($options['name'])) { $formatter->send_header('', $options); $new_encodedname = _rawurlencode($options['name']); $fixed = 0; $msg = ''; $title = sprintf(_("backlinks of \"%s\" page are fixed !"), $options['page']); $comment = sprintf(_("Fixed \"%s\" to \"%s\""), $options['page'], $options['name']); if ($options['pagenames'] and is_array($options['pagenames'])) { $regex = preg_quote($options['page']); //$options['minor'] = 1; # disable log foreach ($options['pagenames'] as $page) { $p = new WikiPage($page); if (!$p->exists()) { continue; } $f = new Formatter($p); $body = $p->_get_raw_body(); $nbody = preg_replace("/{$regex}/m", $options['name'], $body); // FIXME if ($nbody !== false && $body != $nbody) { $f->page->write($nbody); if (!$options['show_only']) { $DBInfo->savePage($f->page, $comment, $options); } $msg .= sprintf(_("'%s' is changed"), $f->link_tag(_rawurlencode($page), "?action=highlight&value=" . $new_encodedname, _html_escape($page))) . "<br />"; $fixed++; } } } if ($fixed == 0) { $title = _("No pages are fixed!"); } $formatter->send_title($title, '', $options); if ($fixed > 0) { print $msg; print sprintf(_("'%s' links are successfully fixed as '%s'."), _html_escape($options['page']), $formatter->link_tag($new_encodedname, "?action=highlight&value=" . $new_encodedname, _html_escape($options['name']))); } $formatter->send_footer('', $options); return; } else { $title = sprintf(_("Fail to fix backlinks of \"%s\" !"), $options['page']); $options['msg'] = sprintf(_("New pagename \"%s\" is not exists!"), $options['name']); $formatter->send_header('', $options); $formatter->send_title($title, '', $options); $formatter->send_footer('', $options); return; } } $title = sprintf(_("Fix backlinks of \"%s\" ?"), $options['page']); $formatter->send_header('', $options); $formatter->send_title($title, '', $options); $obtn = _("Old name:"); $nbtn = _("New name:"); $pgname = _html_escape($options['page']); print "<form method='post'>\n <table border='0'>\n <tr><td align='right'>{$obtn} </td><td><b>{$pgname}</b></td></tr>\n <tr><td align='right'>{$nbtn} </td><td><input name='name' /></td></tr>\n"; if (!empty($options['value']) and $options['value'] == 'check_backlinks') { $button = _("Fix backlinks"); print "<tr><td colspan='2'>\n"; print check_backlinks($formatter, $options); print "</td></tr>\n"; } else { $button = _("Check backlinks"); } if ($DBInfo->security->is_protected("fixbacklinks", $options)) { print "<tr><td align='right'>" . _("Password") . ": </td><td><input type='password' name='passwd' /> " . _("Only WikiMaster can fix backlinks of this page") . "</td></tr>\n"; } if (!empty($options['value']) and $options['value'] == 'check_backlinks') { print "<tr><td colspan='2'><input type='checkbox' name='show_only' checked='checked' />" . _("show only") . "</td></tr>\n"; } print "<tr><td></td><td><input type='submit' name='button_fixbacklinks' value='{$button}' />"; print "<input type='hidden' name='value' value='check_backlinks' />"; print "</td></tr>\n"; print "\n </table>\n <input type='hidden' name='action' value='fixbacklinks' />\n </form>"; $formatter->send_footer('', $options); }
function do_post_DeletePage($formatter, $options) { global $DBInfo; if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($options)) { $options['title'] = _("Page is not writable"); return do_invalid($formatter, $options); } $page = $DBInfo->getPage($options['page']); if (!$page->exists()) { $formatter->send_header('', $options); $title = _("Page not found."); $formatter->send_title($title, '', $options); $formatter->send_footer('', $options); return; } // check full permission to edit $full_permission = true; if (!empty($DBInfo->no_full_edit_permission) or $options['id'] == 'Anonymous' && !empty($DBInfo->anonymous_no_full_edit_permission)) { $full_permission = false; } // members always have full permission to edit if (in_array($options['id'], $DBInfo->members)) { $full_permission = true; } if (!$full_permission) { $formatter->send_header('', $options); $title = _("You do not have full permission to delete this page on this wiki."); $formatter->send_title($title, '', $options); $formatter->send_footer('', $options); return; } // get the site specific hash code $ticket = $page->mtime() . getTicket($DBInfo->user->id, $_SERVER['REMOTE_ADDR']); $hash = md5($ticket); if (isset($options['name'][0])) { $options['name'] = urldecode($options['name']); } $pagename = $formatter->page->urlname; if (isset($options['name'][0]) and $options['name'] == $options['page']) { $retval = array(); $options['retval'] =& $retval; $ret = -1; // check hash if (empty($options['hash'])) { $ret = -2; } else { if ($hash == $options['hash']) { $ret = $DBInfo->deletePage($page, $options); } else { $ret = -3; } } if ($ret == -1) { if (!empty($options['retval']['msg'])) { $title = $options['retval']['msg']; } else { $title = sprintf(_("Fail to delete \"%s\""), _html_escape($page->name)); } } else { if ($ret == -2) { $title = _("Empty hash code !"); } else { if ($ret == -3) { $title = _("Incorrect hash code !"); } else { $title = sprintf(_("\"%s\" is deleted !"), _html_escape($page->name)); } } } $myrefresh = ''; if (!empty($DBInfo->use_save_refresh)) { $sec = $DBInfo->use_save_refresh - 1; $lnk = $formatter->link_url($formatter->page->urlname, "?action=show"); $myrefresh = 'Refresh: ' . $sec . '; url=' . qualifiedURL($lnk); } $formatter->send_header($myrefresh, $options); $formatter->send_title($title, "", $options); $formatter->send_footer('', $options); return; } else { if (isset($options['name'][0])) { #print $options['name']; $options['msg'] = _("Please delete this file manually."); } } $title = sprintf(_("Delete \"%s\" ?"), $page->name); $formatter->send_header("", $options); $formatter->send_title($title, "", $options); $btn = _("Summary"); print "<form method='post'>\n{$btn}: <input name='comment' size='80' value='' /><br />\n"; if (!empty($DBInfo->delete_history)) { print _("with revision history") . " <input type='checkbox' name='history' />\n"; } print "\n<input type=\"hidden\" name=\"hash\" value=\"" . $hash . "\" />\n"; $pwd = _("Password"); $btn = _("Delete Page"); $msg = _("Only WikiMaster can delete this page"); if ($DBInfo->security->is_protected("DeletePage", $options)) { print "{$pwd}: <input type='password' name='passwd' size='20' value='' />\n{$msg}<br />\n"; } print "\n <input type='hidden' name='action' value='DeletePage' />\n <input type='hidden' name='name' value='{$pagename}' />\n <span class='button'><input type='submit' class='button' value='{$btn}' /></span>\n </form>"; # $formatter->send_page(); $formatter->send_footer('', $options); }
function do_sendping($formatter, $options) { global $DBInfo, $_release; if (!$formatter->page->exists()) { $options['msg'] = _("Error: Page Not found !"); do_invalid($formatter, $options); return; } if (strtolower($DBInfo->charset) == 'utf-8') { $checked = 'checked="checked"'; } if (!$options['trackback_url']) { $url = $formatter->link_url($formatter->page->urlname); $raw_body = $formatter->page->_get_raw_body(); if ($options['value']) { $lines = explode("\n", $raw_body); $count = count($lines); # add comment for ($i = 0; $i < $count; $i++) { if (preg_match("/^({{{)?#!blog (.*)\$/", $lines[$i], $match)) { if (md5($match[2]) == $options['value']) { list($tag, $user, $date, $title) = explode(" ", $lines[$i], 4); $found = 1; if ($match[1]) { $end_tag = '}}}'; } break; } } } if ($found) { # a blog page with multiple entries $i++; if ($end_tag) { for (; $i < $count; $i++) { if (preg_match("/^}}}\$/", $lines[$i])) { break; } else { if (preg_match("/^----\$/", $lines[$i])) { break; } } $excerpt .= $lines[$i] . "\n"; } } else { # a blog page with a single entry list($dummy, $entry) = explode("\n", $raw_body, 2); list($excerpt, $comments) = explode("\n----\n", $entry, 2); } } else { $options['msg'] = _("Error: No entry found!"); do_invalid($formatter, $options); return; } } else { # a plain wiki page $excerpt = substr($raw_body, 0, 400); $title = $options['page']; } $COLS_MSIE = 80; $COLS_OTHER = 85; $cols = preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT']) ? $COLS_MSIE : $COLS_OTHER; $rows = $options['rows'] > 5 ? $options['rows'] : 8; $cols = $options['cols'] > 60 ? $options['cols'] : $cols; $formatter->send_header("", $options); $formatter->send_title(_("Send TrackBack ping"), "", $options); $msg1 = _("TrackBack Ping URL"); print "<form method='post' action='{$url}'>\n"; print "<b>{$msg1}</b>: <input name='trackback_url' size='60' maxlength='256' style='width:200' /><br />\n"; if ($options['value']) { $options['value'] = _html_escape($options['value']); print "<input type='hidden' name='value' value=\"{$options['value']}\" />\n"; } $msg2 = _("Title"); $title = _html_escape($title); print "<b>{$msg2}</b>: <input name='title' value=\"{$title}\" size='70' maxlength='70' style='width:200' /><br />\n"; if ($DBInfo->use_resizer > 1) { echo <<<JS <script type="text/javascript" src="{$DBInfo->url_prefix}/local/textarea.js"></script> JS; } print <<<FORM <div class="resizable-textarea" style='position:relative'><!-- IE hack --> <textarea class="wiki resizable" id="content" wrap="virtual" name="excerpt" rows="{$rows}" cols="{$cols}" class="wiki">{$excerpt}</textarea></div> FORM; $mb_msg = _("mb encoded"); $send_msg = _("Send ping"); $reset = _("Reset"); print <<<FORM2 <b>{$mb_msg}</b> <input type="checkbox" name="mbencode" {$checked} /> <input type="hidden" name="action" value="sendping" /> <span class="button"><input class="button" type="submit" value="{$send_msg}" /></span> <span class="button"><input class="button" type="reset" value="{$reset}" /></span> </form> FORM2; $formatter->send_footer("", $options); return; } # send Trackback ping $trackback_url = $options['trackback_url']; $title = urlencode(_stripslashes($options['title'])); $blog_name = urlencode($DBInfo->sitename . ":{$options['id']}"); $excerpt = _stripslashes($options['excerpt']); if ($options['mbencode']) { if ($checked and function_exists('iconv') and strtolower($DBInfo->charset) != 'utf-8') { $excerpt = iconv($DBInfo->charset, 'utf-8', $excerpt); } if (function_exists('mb_encode_numericentity')) { $new = mb_encode_numericentity($excerpt, $DBInfo->convmap, 'utf-8'); if ($new) { $excerpt = $new; } $new = mb_encode_numericentity($title, $DBInfo->convmap, 'utf-8'); if ($new) { $title = $new; } } else { include_once 'lib/compat.php'; $new = utf8_mb_encode($excerpt); if ($new) { $excerpt = $new; } $new = utf8_mb_encode($title); if ($new) { $title = $new; } } } $excerpt = urlencode($excerpt); $url = $formatter->link_url($options['page'], "#{$options['value']}"); $url = urlencode(qualifiedUrl($url)); $query_string = "title={$title}&url={$url}&blog_name={$blog_name}&excerpt={$excerpt}"; if (strstr($trackback_url, '?')) { $trackback_url .= "&" . $query_string; $fp = @fopen($trackback_url, 'r'); $result = @fread($fp, 4096); @fclose($fp); /* debug code $debug_file = 'trackback.log'; $fp = fopen($debug_file, 'a'); fwrite($fp, "\n*****\nTrackback URL query:\n\n$trackback_url\n\nResponse:\n\n"); fwrite($fp, $result); fwrite($fp, "\n\n"); fclose($fp); */ } else { $trackback_url = parse_url($trackback_url); $http_request = 'POST ' . $trackback_url['path'] . " HTTP/1.0\r\n"; $http_request .= 'Host: ' . $trackback_url['host'] . "\r\n"; $http_request .= 'Content-Type: application/x-www-form-urlencoded' . "\r\n"; $http_request .= 'Content-Length: ' . strlen($query_string) . "\r\n"; $http_request .= "\r\n"; $http_request .= $query_string; $fs = @fsockopen($trackback_url['host'], 80); @fputs($fs, $http_request); /* debug code $debug_file = 'trackback.log'; $fp = fopen($debug_file, 'a'); fwrite($fp, "\n*****\nRequest:\n\n$http_request\n\nResponse:\n\n"); while(!@feof($fs)) { fwrite($fp, @fgets($fs, 4096)); } fwrite($fp, "\n\n"); fclose($fp); */ @fclose($fs); } $formatter->send_header("", $options); $formatter->send_title(_("Trackback sent"), "", $options); #$formatter->send_page("Return: $result"); print "Return: {$result}"; $formatter->send_footer("", $options); return; }
function do_comment($formatter, $options = array()) { global $DBInfo; if (!$DBInfo->security->writable($options)) { $formatter->preview = 1; $options['title'] = _("Page is not writable"); return do_invalid($formatter, $options); } else { if (!$DBInfo->hasPage($options['page'])) { $options['err'] = _("You are not allowed to add a comment."); $options['title'] = _("Page does not exists"); return do_invalid($formatter, $options); } } if (!empty($options['usemeta'])) { $use_meta = 1; } $cols = get_textarea_cols(); $rows = (!empty($options['rows']) and $options['rows'] > 5) ? $options['rows'] : 8; $cols = (!empty($options['cols']) and $options['cols'] > 60) ? $options['cols'] : $cols; $url = $formatter->link_url($formatter->page->urlname); $button_preview = !empty($options['button_preview']) ? $options['button_preview'] : 0; $use_any = 0; if (!empty($DBInfo->use_textbrowsers)) { if (is_string($DBInfo->use_textbrowsers)) { $use_any = preg_match('/' . $DBInfo->use_textbrowsers . '/', $_SERVER['HTTP_USER_AGENT']) ? 1 : 0; } else { $use_any = preg_match('/Lynx|w3m|links/', $_SERVER['HTTP_USER_AGENT']) ? 1 : 0; } } $ok_ticket = 0; if (empty($use_any) and !empty($DBInfo->use_ticket) and $options['id'] == 'Anonymous') { if ($options['__seed'] and $options['check']) { $mycheck = getTicket($options['__seed'], $_SERVER['REMOTE_ADDR'], 4); if ($mycheck == $options['check']) { $ok_ticket = 1; } else { $options['msg'] = _("Invalid ticket !"); $button_preview = 1; } } else { if (!$button_preview) { $options['msg'] = _("You need a ticket !"); } $button_preview = 1; } } else { $ok_ticket = 1; } if ($options['savetext']) { $savetext = _stripslashes($options['savetext']); $savetext = str_replace("\r", "", $savetext); $savetext = rtrim($savetext); #$savetext=str_replace("<","<",$savetext); } if (!empty($savetext) and empty($button_preview) and !empty($DBInfo->spam_filter)) { $text = $savetext; $fts = preg_split('/(\\||,)/', $DBInfo->spam_filter); foreach ($fts as $ft) { $text = $formatter->filter_repl($ft, $text, $options); } if ($text != $savetext) { $button_preview = 1; $options['msg'] = _("Sorry, can not save page because some messages are blocked in this wiki."); } } if (!empty($button_preview) && !empty($options['savetext'])) { if (empty($options['action_mode']) or $options['action_mode'] != 'ajax') { $formatter->send_header("", $options); $formatter->send_title(_("Preview comment"), "", $options); $formatter->send_page($savetext . "\n----"); $options['savetext'] = $savetext; print macro_Comment($formatter, '', $options); print $formatter->macro_repl('EditHints'); $formatter->send_footer("", $options); } return false; } else { if (empty($savetext)) { if (empty($options['action_mode']) or $options['action_mode'] != 'ajax') { $formatter->send_header("", $options); $formatter->send_title(_("Add comment"), "", $options); print macro_Comment($formatter, '', $options); print $formatter->macro_repl('EditHints'); $formatter->send_footer("", $options); } return false; } } $datestamp = $options['datestamp']; if ($formatter->page->mtime() > $datestamp) { $options['msg'] = ''; if (empty($options['action_mode']) or $options['action_mode'] != 'ajax') { $formatter->send_header('', $options); $formatter->send_title(_("Error: Don't make a clone!"), '', $options); $formatter->send_footer('', $options); } return false; } $body = $formatter->page->get_raw_body(); if ($options['id'] == 'Anonymous') { $id = $options['name'] ? _stripslashes($options['name']) : $_SERVER['REMOTE_ADDR']; } else { $id = $options['id']; } if (!empty($use_meta)) { $date = gmdate('Y-m-d H:i:s') . ' GMT'; $savetext = rtrim($savetext) . "\n"; $boundary = strtoupper(md5("COMMENT")); # XXX $idx = 1; if (preg_match_all('/-{4}(?:' . $boundary . ')?\\nComment-Id:\\s*(\\d+)\\n/m', $body, $m)) { $idx = $m[1][sizeof($m[1]) - 1] + 1; } if ($options['id'] != 'Anonymous') { $id = '@USERNAME@'; } $meta = <<<META Comment-Id: {$idx} From: {$id} Date: {$date} META; $savetext = "----" . $boundary . "\n{$meta}\n\n{$savetext}\n"; } else { if (!empty($options['nosig'])) { $savetext = "----\n{$savetext}\n"; } else { if ($options['id'] == 'Anonymous') { $savetext = "----\n{$savetext} -- {$id} @DATE@\n"; } else { $savetext = "----\n{$savetext} @SIG@\n"; } } } while ($options['comment_id']) { list($nth, $dum, $v) = explode(',', base64_decode($options['comment_id']), 3); if ($v) { $check = '[[' . $dum . '(' . $v . ')]]'; } else { $check = '[[' . $dum . ']]'; } if ($v) { $check2 = '<<' . $dum . '(' . $v . ')>>'; } else { $check2 = '<<' . $dum . '>>'; } if (is_numeric($nth)) { $raw = str_replace("\n", "", $body); $chunk = preg_split("/({{{.+}}})/U", $raw, -1, PREG_SPLIT_DELIM_CAPTURE); // FIXME $nc = ''; $k = 1; $i = 1; foreach ($chunk as $c) { if ($k % 2) { $nc .= $c; } else { $nc .= "" . $i . ""; $blocks[$i] = str_replace("", "\n", $c); ++$i; } $k++; } $nc = str_replace("", "\n", $nc); if (preg_match_all('/(?!\\!)(?:\\<\\<|\\[\\[)Comment(?:.*?)(?:\\]\\]|>>)/', $nc, $m)) { if (count($m[0]) == 1) { break; } } $chunk = preg_split('/((?!\\!)(?:\\<\\<|\\[\\[).+(?:\\]\\]|>>))/U', $nc, -1, PREG_SPLIT_DELIM_CAPTURE); $nnc = ''; $ii = 1; $matched = 0; for ($j = 0, $sz = sizeof($chunk); $j < $sz; ++$j) { if (($j + 1) % 2) { $nnc .= $chunk[$j]; } else { if ($nth == $ii) { $new = $savetext . $chunk[$j]; if ($check != $chunk[$j] and $check2 != $chunk[$j]) { break; } $nnc .= $new; $matched = 1; } else { $nnc .= $chunk[$j]; } ++$ii; } } if (!empty($blocks)) { $formatter->_array_callback($blocks, true); $nnc = preg_replace_callback("/(\\d+)/", array(&$formatter, '_array_callback'), $nnc); } } if (!empty($matched)) { $body = $nnc; } break; } if (empty($matched)) { if ($options['comment_id'] and preg_match("/^((?:\\[\\[|\\<\\<)Comment\\(" . $options['comment_id'] . "\\)(?:\\]\\]|>>))/m", $body, $m)) { $str = $m[1]; $body = preg_replace('/' . preg_quote($str) . '/', $savetext . $str, $body, 1); } else { if (preg_match("/\n##Comment\n/i", $body)) { $body = preg_replace("/\n##Comment\n/i", "\n##Comment\n{$savetext}", $body, 1); } else { if (preg_match("/^((\\[\\[|\\<\\<)Comment(\\([^\\)]*\\))?(\\]\\]|>>)/m", $body)) { $body = preg_replace("/^((\\[\\[|\\<\\<)Comment(\\([^\\)]*\\))?(\\]\\]|>>))/m", $savetext . "\\1", $body, 1); } else { $body .= $savetext; } } } } $formatter->page->write($body); $DBInfo->savePage($formatter->page, "Comment added", $options); if ($options['action_mode'] == 'ajax') { return true; } $options['msg'] = sprintf(_("%s is commented successfully"), $formatter->link_tag($formatter->page->urlname, "?action=show", $options['page'])); $title = _("Comment added successfully"); $myrefresh = ''; if ($DBInfo->use_save_refresh) { $sec = $DBInfo->use_save_refresh - 1; $lnk = $formatter->link_url($formatter->page->urlname, "?action=show"); $myrefresh = 'Refresh: ' . $sec . '; url=' . qualifiedURL($lnk); } $formatter->send_header($myrefresh, $options); $formatter->send_title($title, '', $options); $opt['pagelinks'] = 1; # re-generates pagelinks $formatter->send_page('', $opt); $formatter->send_footer('', $options); return; }
function do_man_get($formatter, $options) { global $DBInfo; $supported = array('C', 'bg', 'de', 'en', 'fr', 'hu', 'ja', 'pt', 'ru', 'sr', 'cs', 'de_DE', 'es', 'fr_FR', 'id', 'ko', 'nl', 'pt_BR', 'sk', 'sv', 'da', 'el', 'fi', 'hr', 'it', 'pl', 'ro', 'sl'); if (!$options['man']) { $options['title'] = _("No manpage selected"); do_invalid($formatter, $options); return; } $LANG = ''; if ($options['lang'] and in_array($options['lang'], $supported)) { $LANG = 'LANG=' . $options['lang']; } if ($options['sec'] != intval($options['sec'])) { unset($options['sec']); } $cmd = $LANG . " man {$options['sec']} -a -w {$options['man']}"; $formatter->errlog(); $fp = popen(escapeshellcmd($cmd) . $formatter->LOG, 'r'); if (is_resource($fp)) { $fnames = array(); while ($l = fgets($fp, 1024)) { if (preg_match('/\\.gz$/', $l)) { $fnames[] = trim($l); } } pclose($fp); } $err = $formatter->get_errlog(); if ($err) { $err = '<pre class="errlog">' . $err . '</pre>'; } if (!$fnames) { $options['title'] = _("No manpage found"); $options['msg'] = $err; // XXX do_invalid($formatter, $options); return; } $sz = count($fnames); $man = array(); if ($sz >= 1) { foreach ($fnames as $fname) { $man[] = $tmp = preg_replace("/\\.gz\$/", "", basename($fname)); } $options['page'] = "ManPage/{$man['0']}"; $fname = $fnames[0]; } if ($DBInfo->hasPage($options['page'])) { $options['value'] = $options['page']; do_goto($formatter, $options); return; } if (function_exists('gzfile')) { $raw = gzfile($fname); $raw = join('', $raw); } else { exec("zcat {$fname}", $raw); $raw = join("\n", $raw); } if ($sz > 1) { $lnk = array(); foreach ($fnames as $f) { $tmp = preg_match("@/([^/]+)?/man./([^/]+).(.)\\.gz\$@", $f, $m); $lang = 'en'; if ($m) { if ($m[1] != 'man') { $lang = $m[1]; } $myman = $m[2]; $mysec = $m[3]; $tag = ''; if ($lang) { $tag = $lang == 'ko' ? '(' . $lang . ')' : ''; $lang = '&lang=' . $lang; } $lnk[] = $formatter->link_tag('ManPage/' . $myman . '.' . $mysec, '?action=man_get&man=' . $myman . '&sec=' . $mysec . $lang, $myman . '.' . $mysec) . $tag; } } if (sizeof($lnk) > 0) { $options['msgtitle'] = implode(', ', $lnk); } } if ($DBInfo->man_charset and $DBInfo->man_charset != $DBInfo->charset) { if (function_exists('iconv')) { $ignore = '//IGNORE'; // XXX $raw = iconv($DBInfo->man_charset, $DBInfo->charset . $ignore, $raw); } } if ($DBInfo->man_filter) { $raw = $formatter->filter_repl('simplere', $raw, array('page' => $DBInfo->man_filter)); } $options['savetext'] = $raw; if ($options['edit']) { $formatter->send_header("", $options); $formatter->send_title("", "", $options); print macro_EditText($formatter, $raw, $options); } else { if ($options['raw']) { $formatter->send_header("content-type: text/plain", $options); print $raw; return; } else { $formatter->send_header("", $options); $formatter->send_title("", "", $options); print $formatter->processor_repl('man', $raw, $options); $extra = ''; if ($options['sec']) { $extra = '&sec=' . $options['sec']; } if ($options['lang']) { $extra = '&lang=' . $options['lang']; } $formatter->actions[] = '?action=man_get&man=' . $options['man'] . $extra . '&edit=1 ' . _("Edit man page"); } } $formatter->send_footer('', $options); return; // vim:et:sts=4: }
function do_html2pdf($formatter, $options) { global $DBInfo, $Config; $conf = _load_php_vars("config/html2pdf.php"); $libdir = !empty($conf['tcpdf_dir']) ? $conf['tcpdf_dir'] : 'tcpdf'; $k_path_install = 'lib/' . $libdir . '/'; # required for config/tcpdf.php @(require_once 'config/tcpdf.php'); @(require_once 'lib/' . $libdir . '/config/lang/eng.php'); @(require_once 'lib/' . $libdir . '/tcpdf.php'); if (!class_exists('TCPDF')) { $options['title'] = _("The TCPDF class not found!"); return do_invalid($formatter, $options); } if (!class_exists('XTCPDF')) { class XTCPDF extends TCPDF { var $toc = array(); var $fontalias = array(); function setFontAlias($alias) { $this->fontalias = array(); foreach ($alias as $k => $v) { array_push($this->fontlist, $k); } $this->fontalias = $alias; } function AddFont($family, $style = '', $fontfile = '') { $family = trim($family); if (!empty($family) and array_key_exists($family, $this->fontalias)) { $family = strtolower($family); $fontfile = $family; $name = $this->fontalias[$family]; $fontfile = $this->fontalias[$family] . '.php'; $fontdata = parent::AddFont($family, $style, $fontfile); $key = $fontdata['fontkey']; if ($this->fonts[$key]['type'] == 'core') { $this->fonts[$key]['name'] = $this->CoreFonts[$name]; } return $fontdata; } return parent::AddFont($family, $style, $fontfile); } function getHtmlDomArray($html) { $html = preg_replace('@<title>.*</title>@', '', $html); $html = preg_replace('@<head>.*</head>@s', '', $html); $html = preg_replace('@"@', '"', $html); #$html = preg_replace('@>\s+<@',"><",$html); $html = preg_replace('@>\\n@', ">", $html); $html = preg_replace('@/\\*<\\!\\[CDATA\\[.*\\]\\]>\\*/\\n?@Us', '', $html); $html = preg_replace('@<pre[^>]*>@', '<pre style="background-color:black;color:white">', $html); $dom =& parent::getHtmlDomArray($html); $sz = count($dom); for ($i = 0; $i < $sz; $i++) { $tag =& $dom[$i]; if (!empty($tag['opening']) and $tag['value'] == 'table') { #$tag['attribute']['border']=1; #$tag['attribute']['bgcolor']=array(200,200,200); #$tag['bgcolor']=array(200,200,200); #} else if (!empty($tag['opening']) and $tag['value']=='pre') { # $tag['bgcolor']=array(0,0,0); # $tag['fgcolor']=array(255,255,255); # $tag['fontname']='courier'; #} else if (!empty($tag['opening']) and $tag['value']=='div') { # $tag['bgcolor']=array(100,100,100); } } #print "<pre>"; #print_r($dom); #print "</pre>"; return $dom; } function closeHTMLTagHandler(&$dom, $key, $cell = false) { $tag = $dom[$key]; switch ($tag['value']) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': $i = $key; $txt = ''; while ($dom[--$i]['value'] != $tag['value'] and $i > 0) { if (!isset($dom[$i]['opening'])) { $txt = $dom[$i]['value'] . $txt; } } $num = key($this->toc); $dep = count(explode('.', $num)); $this->Bookmark($num . ' ' . $this->toc[$num], $dep, $this->y); next($this->toc); } parent::closeHTMLTagHandler($dom, $key, $cell); } } } // define the share directory to create img define('X_PATH_SHARE_IMG', $DBInfo->cache_public_dir . '/html2pdf/'); if (!file_exists(X_PATH_SHARE_IMG)) { _mkdir_p(X_PATH_SHARE_IMG, 0777); } // XXX $formatter->nonexists = 'always'; $formatter->section_edit = 0; $formatter->perma_icon = ''; ob_start(); $formatter->send_header(); $formatter->send_page('', array('fixpath' => 1)); print '</body></html>'; $html = ob_get_contents(); ob_end_clean(); # begin $pdf = new XTCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, $DBInfo->charset); include_once 'function/toc.php'; $toc = function_toc($formatter); $pdf->toc = $toc; $pdf->setFontAlias(array('monospace' => 'courier')); #$pdf->setLIsymbol(chr(42)); #$pdf->setLIsymbol('a'); // set default header data // $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING); $pdf->SetHeaderData($DBInfo->logo_img, 20, $formatter->page->name); $pdf->SetTitle($formatter->page->name); # $pdf->SetAuthor('Your name'); $pdf->SetCreator('TCPDF/MoniWiki'); $pdf->SetSubject($formatter->page->name); if (!empty($formatter->pi['#keywords'])) { $pdf->SetKeywords($keywords = $formatter->pi['#keywords']); } // load default font $pdf->AddFont($conf['default_unifont']); $pdf->SetFont($conf['default_font']); // set header and footer fonts // $pdf->setHeaderFont(Array($conf['default_unifont'], '', PDF_FONT_SIZE_MAIN)); $pdf->setHeaderFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); $pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); //set margins $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); //set auto page breaks $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); //set some language-dependent strings $pdf->setLanguageArray($l); //set image scale factor //$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); # initialize document $pdf->AliasNbPages(); # add a page $pdf->AddPage(); $pdf->Bookmark($formatter->page->name, 0, 0); # $pdf->writeHTML($html, true, 0, false, false); # output $pdf->output(date("Ymd", time()) . '.pdf', 'I'); return; }
function do_uploadfile($formatter, $options) { global $DBInfo; if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($options)) { $options['title'] = _("Page is not writable"); return do_invalid($formatter, $options); } // check staff members $can_replace = false; if (isset($DBInfo->members) and in_array($options['id'], $DBInfo->members)) { $can_replace = true; } $files = array(); $title = ''; if (isset($options['data'])) { if (substr($options['data'], 0, 5) == 'data:') { $data = substr($options['data'], 5); } else { $data = $options['data']; } $err = _("Fail to parse data string"); while (preg_match('@^(image/(gif|jpe?g|png));base64,(.*)$@', $data, $match)) { $ret = base64_decode($match[3]); if ($ret === false) { $err = _("Fail to decode base64 data string."); break; } else { $name = isset($options['name'][0]) ? $options['name'] : 'unnamed'; $name .= '.' . $match[2]; $tmpfile = tempnam($DBInfo->vartmp_dir, 'DATA'); $fp = fopen($tmpfile, 'wb'); if (!is_resource($fp)) { $err = _("Fail to open file.\n"); break; } fwrite($fp, $ret); fclose($fp); $count = 1; $files['upfile']['name'][] = $name; $files['upfile']['tmp_name'][] = $tmpfile; $files['upfile']['error'][] = ''; $files['upfile']['type'][] = $match[1]; $err = ''; break; } } } if (!empty($err)) { echo $err; return; } if (isset($_FILES['upfile']) and is_array($_FILES)) { if (!empty($options['multiform']) and $options['multiform'] > 1 or is_array($_FILES['upfile']['name'])) { $options['multiform'] = !empty($options['multiform']) ? $options['multiform'] : sizeof($_FILES['upfile']['name']); $count = $options['multiform']; $files =& $_FILES; if (!isset($options['rename'])) { $options['rename'] = array(); } } else { $count = 1; $files['upfile']['name'][] =& $_FILES['upfile']['name']; $files['upfile']['tmp_name'][] =& $_FILES['upfile']['tmp_name']; $files['upfile']['error'][] =& $_FILES['upfile']['error']; $files['upfile']['type'][] =& $_FILES['upfile']['type']; $options['rename'] = array($options['rename']); $options['replace'] = array($options['replace']); } } else { if (isset($options['MYFILES']) and is_array($options['MYFILES'])) { // for SWFUpload action $count = sizeof($options['MYFILES']); $MYFILES =& $options['MYFILES']; $mysubdir = $options['mysubdir']; for ($i = 0; $i < $count; $i++) { $myname = $MYFILES[$i]; $files['upfile']['name'][] = $myname; $files['upfile']['tmp_name'][] = $DBInfo->upload_dir . '/.swfupload/' . $mysubdir . $myname; // XXX $files['rename'][] = ''; $files['replace'][] = ''; } } } // Set upload err msg func. if (!empty($DBInfo->upload_err_func) and function_exists($DBInfo->upload_err_func)) { $upload_err_func = $DBInfo->upload_err_func; } else { $upload_err_func = '_upload_err_msg'; } $msg = array(); $err_msg = array(); $upload_ok = array(); $js = ''; $uploadid = !empty($options['uploadid']) ? $options['uploadid'] : ''; if (!empty($uploadid) or !empty($options['MYFILES'])) { $js = <<<EOF <script type="text/javascript"> /*<![CDATA[*/ function delAllForm(id) { if (!opener) return; if (id == '') return; var fform = opener.document.getElementById(id); if (fform && fform.rows && fform.rows.length) { // for UploadForm for (var i=fform.rows.length;i>0;i--) { fform.deleteRow(i-1); } } else { // for SWFUpload var listing = opener.document.getElementById('mmUploadFileListing'); if (listing) { var elem = listing.getElementsByTagName("li"); listing.innerHTML=''; } else if (fform) { fform.reset(); } } } delAllForm('{$uploadid}'); /*]]>*/ </script> EOF; } $ok = 0; if ($files) { foreach ($files['upfile']['name'] as $f) { if ($f) { $ok = 1; break; } } } if (!$ok) { if (isset($options['retval'])) { return false; } // ignore #$title="No file selected"; $formatter->send_header("", $options); $formatter->send_title($title, "", $options); print macro_UploadFile($formatter, '', $options); if (!in_array('UploadedFiles', $formatter->actions)) { $formatter->actions[] = 'UploadedFiles'; } $formatter->send_footer("", $options); return false; } $key = $DBInfo->pageToKeyname($formatter->page->name); if ($formatter->page->name != 'UploadFile') { $dir = $DBInfo->upload_dir . '/' . $key; // support hashed upload_dir if (!is_dir($dir) and !empty($DBInfo->use_hashed_upload_dir)) { $prefix = get_hashed_prefix($key); $dir = $DBInfo->upload_dir . '/' . $prefix . $key; } } else { $dir = $DBInfo->upload_dir; } if (!file_exists($dir)) { umask(00); _mkdir_p($dir, 0777); umask(02); } $REMOTE_ADDR = $_SERVER['REMOTE_ADDR']; $comment = "File "; $uploaded = ''; $log_entry = ''; $protected_exts = !empty($DBInfo->pds_protected) ? $DBInfo->pds_protected : "pl|cgi|php"; $safe_exts = !empty($DBInfo->pds_safe) ? $DBInfo->pds_safe : "txt|gif|png|jpg|jpeg"; $protected = explode('|', $protected_exts); $safe = explode('|', $safe_exts); # upload file protection if (!empty($DBInfo->pds_allowed)) { $pds_exts = $DBInfo->pds_allowed; } else { $pds_exts = "png|jpg|jpeg|gif|mp3|zip|tgz|gz|txt|css|exe|pdf|hwp"; } $allowed = 0; if (isset($DBInfo->upload_masters) and in_array($options['id'], $DBInfo->upload_masters)) { // XXX WARN!! $pds_exts = '.*'; $allowed = 1; } $safe_types = array('text' => '', 'media' => '', 'image' => '', 'audio' => '', 'application' => 'bin'); for ($j = 0; $j < $count; $j++) { # replace space and ':' strtr() $upfilename = str_replace(" ", "_", $files['upfile']['name'][$j]); $upfilename = str_replace(":", "_", $upfilename); preg_match("/^(.*)\\.([a-z0-9]{1,5})\$/i", $upfilename, $fname); if (!$upfilename) { continue; } else { if ($upfilename) { $uploaded++; } } $no_ext = 0; if (empty($fname[2])) { $fname[1] = $upfilename; $fname[2] = ''; $no_ext = 1; } if (!$allowed) { if (!empty($DBInfo->use_filetype)) { $type = ''; $type = $files['upfile']['type'][$j] ? $files['upfile']['type'][$j] : 'text/plain'; list($mtype, $xtype) = explode('/', $type); if (!empty($mtype) and array_key_exists($mtype, $safe_types)) { $allowed = 1; $fname[2] = $fname[2] ? $fname[2] : $safe_types[$mtype]; } else { if ($no_ext) { $err_msg[] = sprintf(_("The %s type of %s is not allowed to upload"), $type, $upfilename); continue; } } } else { $fname[2] = $fname[2] ? $fname[2] : 'txt'; $no_ext = 0; } } $upfilename = preg_replace('/\\.$/', '', implode('.', array($fname[1], $fname[2]))); if (!$allowed) { if (!$no_ext and !preg_match("/(" . $pds_exts . ")\$/i", $fname[2])) { if ($DBInfo->use_filetype and !empty($type)) { $err_msg[] = sprintf(_("The %s type of %s is not allowed to upload"), $type, $upfilename); } else { $err_msg[] = sprintf(_("%s is not allowed to upload"), $upfilename); } continue; } else { if ($fname[2] and in_array(strtolower($fname[2]), $safe)) { $upfilename = $fname[1] . '.' . $fname[2]; } else { # check extra extentions for the mod_mime $exts = explode('.', $fname[1]); $ok = 0; for ($i = sizeof($exts); $i > 0; $i--) { if (in_array(strtolower($exts[$i - 1]), $safe)) { $ok = 1; break; } else { if (in_array(strtolower($exts[$i - 1]), $protected)) { $exts[$i] .= '.txt'; # extra check for mod_mime: append 'txt' extension: my.pl.hwp => my.pl.txt.hwp $ok = 1; break; } } } if ($ok) { $fname[1] = implode('.', $exts); $upfilename = $fname[1] . '.' . $fname[2]; } } } } $file_path = $newfile_path = $dir . "/" . $upfilename; $filename = $upfilename; if (!empty($options['rename'][$j])) { # XXX $temp = explode("/", _stripslashes($options['rename'][$j])); $upfilename = $temp[count($temp) - 1]; preg_match("/^(.*)\\.([a-z0-9]{1,5})\$/i", $upfilename, $tname); $exts = explode('.', $tname[1]); $ok = 0; for ($i = sizeof($exts); $i > 0; $i--) { if (in_array(strtolower($exts[$i - 1]), $protected)) { $exts[$i] .= '.txt'; $ok = 1; break; } } if ($ok) { $tname[1] = implode('.', $exts); $upfilename = $tname[1] . '.' . $fname[2]; } # check the extention of the new file name. $fname[1] = $tname[1]; $newfile_path = $dir . "/" . $tname[1] . ".{$fname['2']}"; if ($tname[2] != $fname[2]) { if (strtolower($tname[2]) == strtolower($fname[2])) { # change the case of the file ext. is allowed $newfile_path = $dir . "/" . $tname[1] . ".{$tname['2']}"; } else { $err_msg[] = sprintf(_("It is not allowed to change file ext. \"%s\" to \"%s\"."), $fname[2], $tname[2]); } } } # is file already exists ? $dummy = 0; $myext = $fname[2] ? '.' . $fname[2] : ''; while (@file_exists($newfile_path)) { $dummy = $dummy + 1; $ufname = $fname[1] . "_" . $dummy; // rename file $upfilename = $ufname . $myext; $newfile_path = $dir . "/" . $upfilename; } $upfile = $files['upfile']['tmp_name'][$j]; if (!empty($files['upfile']['error'][$j]) and $files['upfile']['error'][$j] != UPLOAD_ERR_OK) { $err_msg[] = _("ERROR:") . ' <tt>' . $upload_err_func($files['upfile']['error'][$j]) . ' : ' . $upfilename . '</tt>'; if ($files['upfile']['error'][$j] == UPLOAD_ERR_INI_SIZE) { $err_msg[] = "<tt>upload_max_filesize=" . ini_get('upload_max_filesize') . '</tt>'; } continue; } $_l_path = _l_filename($file_path); $new_l_path = _l_filename($newfile_path); if ($can_replace and !empty($options['replace'][$j])) { // only staff can replace // backup if ($newfile_path != $file_path) { $test = @copy($_l_path, $new_l_path); } // replace $test = @copy($upfile, $_l_path); $upfilename = $filename; } else { $test = @copy($upfile, $new_l_path); } @unlink($upfile); if (!$test) { $err_msg[] = sprintf(_("Fail to copy \"%s\" to \"%s\""), $upfilename, $file_path); if ($files['upfile']['error'][$j] == UPLOAD_ERR_INI_SIZE) { $err_msg[] = "<tt>upload_max_filesize=" . ini_get('upload_max_filesize') . '</tt>'; } continue; } chmod($new_l_path, 0644); $comment .= "'{$upfilename}' "; $title .= (!empty($title) ? "\\n" : '') . sprintf(_("File \"%s\" is uploaded successfully"), $upfilename); $fullname = _html_escape($formatter->page->name) . "/{$upfilename}"; $upname = $upfilename; if (strpos($fullname, ' ') !== false) { $fullname = '"' . $fullname . '"'; } if (strpos($upname, ' ') !== false) { $upname = '"' . $upname . '"'; } if ($formatter->page->name == 'UploadFile') { $msg[] = "<ins>attachment:/{$upname}</ins>"; $upload_ok[] = '/' . $upname; $log_entry .= " * attachment:/{$upname}?action=deletefile . . . @USERNAME@ @DATE@\n"; } else { $msg[] = "<ins>attachment:{$upname}</ins> or"; $msg[] = "<ins>attachment:{$fullname}</ins>"; $upload_ok[] = $upname; $log_entry .= " * attachment:{$fullname}?action=deletefile . . . @USERNAME@ @DATE@\n"; } } // multiple upload $comment .= "uploaded"; if (!empty($DBInfo->upload_changes)) { $p = $DBInfo->getPage($DBInfo->upload_changes); $raw_body = $p->_get_raw_body(); if ($raw_body and $raw_body[strlen($raw_body) - 1] != "\n") { $raw_body .= "\n"; } $raw_body .= $log_entry; $p->write($raw_body); $DBInfo->savePage($p, $comment, $options); } else { $DBInfo->addLogEntry($formatter->page->name, $REMOTE_ADDR, $comment, "UPLOAD"); } if (!empty($options['action_mode']) and $options['action_mode'] == 'ajax') { $err = implode("\\n", $err_msg); $err = strip_tags($err); if ($err) { $err .= "\\n"; } $formatter->header('Content-type: text/html; charset=' . $DBInfo->charset); $scr = ''; if (!empty($options['domain']) and preg_match('/^[a-z][a-z0-9]+(\\.[a-z][a-z0-9]+)*$/i', $options['domain'])) { $scr = '<script type="text/javascript">document.domain="' . $options['domain'] . '";</script>'; } echo $scr . ' {"title": "' . str_replace(array('"', '<'), array("'", '<'), $title) . '", "msg": ["' . $err . strip_tags(implode("\\n", $msg)) . '"], "uploaded":' . $uploaded . ', "files": ["' . implode("\"\n,\"", $upload_ok) . '"] }'; return true; } $msgs = implode("<br />\n", $err_msg); $msgs .= implode("<br />\n", $msg); if (isset($options['retval'])) { $retval = array('title' => $title, 'msg' => $msgs, 'uploaded' => $uploaded, 'files' => $upload_ok); $ret =& $options['retval']; $ret = $retval; return true; } $formatter->send_header("", $options); if ($uploaded < 2) { $formatter->send_title($title, "", $options); print $msgs; } else { $msg = $title . '<br />' . $msg; $title = sprintf(_("Files are uploaded successfully"), $upfilename); $formatter->send_title($title, "", $options); print $msgs; } print $js; $formatter->send_footer('', $options); if (isset($options['MYFILES']) and is_array($options['MYFILES']) and session_id() != '') { session_destroy(); } return true; }
function do_Blog($formatter, $options) { global $DBInfo; if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($options)) { $options['title'] = _("Page is not writable"); return do_invalid($formatter, $options); } $COLS_MSIE = 80; $COLS_OTHER = 85; $cols = preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT']) ? $COLS_MSIE : $COLS_OTHER; $rows = (!empty($options['rows']) and $options['rows'] > 5) ? $options['rows'] : 8; $cols = (!empty($options['cols']) and $options['cols'] > 60) ? $options['cols'] : $cols; $name = !empty($options['name']) ? $options['name'] : ''; $url = $formatter->link_url($formatter->page->urlname); $pagename = _html_escape($formatter->page->name); if (!empty($formatter->refresh) or !empty($options['button_refresh'])) { updateBlogList($formatter); $options['msg'] = sprintf(_("Blog cache of \"%s\" is refreshed"), $pagename); } $savetext = ""; if (!empty($options['savetext'])) { $savetext = _stripslashes($options['savetext']); $savetext = str_replace("\r", "", $savetext); $savetext = str_replace("----\n", "-''''''---\n", $savetext); $savetext = rtrim($savetext); #$savetext=str_replace("<","<",$savetext); } # for conflict check if (!empty($options['datestamp'])) { $datestamp = $options['datestamp']; } else { $datestamp = $formatter->page->mtime(); } if (!empty($options['title'])) { $options['title'] = _stripslashes($options['title']); } else { $options['title'] = ''; } $options['title'] = _html_escape($options['title']); $button_preview = $options['button_preview']; if (!empty($savetext)) { $ok_ticket = 0; if (empty($use_any) and !empty($DBInfo->use_ticket) and $options['id'] == 'Anonymous') { if ($options['__seed'] and $options['check']) { $mycheck = getTicket($options['__seed'], $_SERVER['REMOTE_ADDR'], 4); if ($mycheck == $options['check']) { $ok_ticket = 1; } else { $options['msg'] = _("Invalid ticket !"); $button_preview = 1; } } else { if (!$button_preview) { $options['msg'] = _("You need a ticket !"); } $button_preview = 1; } } else { $ok_ticket = 1; } } if (empty($button_preview) && !empty($savetext)) { //$savetext=preg_replace("/(?<!\\\\)}}}/","\}}}",$savetext); $url = $formatter->link_tag($formatter->page->urlname, '', $pagename); $options['msg'] = sprintf(_("\"%s\" is updated"), $url); if ($formatter->page->exists()) { $raw_body = $formatter->page->_get_raw_body(); } else { $raw_body = "#action Blog " . _("Add Blog") . "\n##Blog\n"; } $lines = explode("\n", $raw_body); $count = count($lines); if ($options['id'] == 'Anonymous') { $id = $options['name'] ? _stripslashes($options['name']) : $_SERVER['REMOTE_ADDR']; } else { $id = $options['id']; } if (!empty($options['value'])) { # add comment for ($i = 0; $i < $count; $i++) { if (preg_match("/^({{{)?#!blog (.*)\$/", $lines[$i], $match)) { if (md5($match[2]) == $options['value']) { list($tag, $user, $date, $title) = explode(" ", $lines[$i], 4); $found = 1; if ($match[1]) { $endtag = '}}}'; } break; } } } if (!empty($found)) { if (!empty($endtag)) { for (; $i < $count; $i++) { if (preg_match("/^}}}\$/", $lines[$i])) { $found = 1; break; } } } else { # XXX $lines = explode("\n", rtrim($raw_body)); $i = count($lines); } if (!empty($options['nosig'])) { $lines[$i] = "----\n{$savetext}\n{$endtag}"; } else { $lines[$i] = "----\n{$savetext} @SIG@\n{$endtag}"; } $raw_body = join("\n", $lines); } else { $formatter->send_header("", $options); $formatter->send_title(_("Error: No blog entry found!"), "", $options); $formatter->send_footer("", $options); return; } } else { # Blog entry // check timestamp if ($formatter->page->mtime() > $datestamp) { $options['msg'] = ''; if ($options['action_mode'] == 'ajax') { print "false\n"; print _("Error: Don't make a clone!"); } else { $formatter->send_title(_("Error: Don't make a clone!"), "", $options); $formatter->send_footer("", $options); } return; } $entry = "{{{#!blog {$id} @date@"; if (!empty($options['title'])) { $entry .= " " . $options['title']; } $entry .= "\n{$savetext}\n}}}\n\n"; if (preg_match("/\n##Blog\n/i", $raw_body)) { $raw_body = preg_replace("/\n##Blog\n/i", "\n##Blog\n{$entry}", $raw_body, 1); } else { $raw_body .= $entry; } } $myrefresh = ''; if (!empty($DBInfo->use_save_refresh)) { $sec = $DBInfo->use_save_refresh - 1; $lnk = $formatter->link_url($formatter->page->urlname, "?action=show"); $myrefresh = 'Refresh: ' . $sec . '; url=' . qualifiedURL($lnk); } $formatter->send_header($myrefresh, $options); if (!empty($options['value'])) { $formatter->send_title(sprintf(_("Comment added to \"%s\""), $title), "", $options); $log = "Add Comment to \"{$title}\""; } else { $formatter->send_title(sprintf(_("Blog entry added to \"%s\""), $pagename), "", $options); if (!empty($options['title'])) { $log = sprintf(_("Blog entry \"%s\" added"), $options['title']); } else { $log = _("Blog entry added"); } } $formatter->page->write($raw_body); $DBInfo->savePage($formatter->page, $log, $options); updateBlogList($formatter); if ($options['action_mode'] == 'ajax') { print "true\n"; print $options['msg']; } else { $formatter->send_page(); } } else { # add entry or comment $formatter->send_header("", $options); if (!empty($options['value'])) { $raw_body = $formatter->page->_get_raw_body(); $lines = explode("\n", $raw_body); $count = count($lines); for ($i = 0; $i < $count; $i++) { if (preg_match("/^({{{)?#!blog (.*)\$/", $lines[$i], $match)) { if (md5($match[2]) == $options['value']) { list($tag, $user, $date, $title) = explode(" ", $lines[$i], 4); $found = 1; $lines[$i] = '#!blog ' . $match[2]; break; } } } if (!empty($found)) { $quote = ''; for (; $i < $count; $i++) { if (preg_match("/^}}}\$/", $lines[$i])) { break; } $quote .= $lines[$i] . "\n"; } } if (empty($title)) { $title = $pagename; } if (empty($found)) { $formatter->send_title("Error: No entry found!", "", $options); $formatter->send_footer("", $options); return; } $formatter->send_title(sprintf(_("Add Comment to \"%s\""), $title), "", $options); } else { $formatter->send_title(sprintf(_("Add Blog entry to \"%s\""), $pagename), "", $options); } $options['noaction'] = 1; if (!empty($quote)) { $quote = str_replace('\\}}}', '}}}', $quote); print $formatter->processor_repl('blog', $quote, $options); #print $formatter->send_page($quote,$options); } $extra = ''; $btn = _("Refresh"); if ($options['id'] != 'Anonymous') { $extra = '<div style="text-align:right">' . ' <span class="button"><input type="submit" class="button" name="button_refresh" value="' . $btn . '" /></span></div>'; } if (!empty($options['value'])) { print "<a name='BlogComment'></a>"; } print '<div id="editor_area">'; print "<form method='post' action='{$url}'>\n"; $myinput = ''; if ($options['id'] == 'Anonymous') { $myinput .= '<b>' . _("Name") . "</b>: <input name='name' size='15' maxlength='15' value=\"{$name}\" />\n"; } if (empty($options['value'])) { $myinput .= '<b>' . _("Title") . "</b>: <input name='title' value=\"{$options['title']}\" size='70' maxlength='70' style='width:300px' /><br />\n"; } else { print "<input type='hidden' name='value' value='{$options['value']}' />\n"; } print '<div class="editor_area_extra">' . $myinput . "</div>\n"; $savetext = $savetext ? $savetext : 'Enter blog entry'; if (!empty($DBInfo->use_wikiwyg)) { $wysiwyg_msg = _("GUI"); $wysiwyg_btn = ' <span class="button"><input class="button" type="button" tabindex="7" value="' . $wysiwyg_msg . '" onclick="javascript:sectionEdit(null,null,null)" /></span>'; } if ($DBInfo->use_resizer > 1) { echo <<<JS <script type="text/javascript" src="{$DBInfo->url_prefix}/local/textarea.js"></script> JS; } print <<<FORM <div class="resizable-textarea" style='position:relative'><!-- IE hack --> <textarea class="wiki resizable" id="content" wrap="virtual" name="savetext" rows="{$rows}" cols="{$cols}" class="wiki">{$savetext}</textarea></div> FORM; if (!empty($options['value'])) { print "<input name='nosig' type='checkbox' />" . _("Don't add a signature") . "<br />"; } $save_msg = _("Save"); $preview_msg = _("Preview"); if (empty($use_any) and !empty($DBInfo->use_ticket) and $options['id'] == 'Anonymous') { $seed = md5(base64_encode(time())); $ticketimg = $formatter->link_url($formatter->page->urlname, '?action=ticket&__seed=' . $seed); $captcha = <<<EXTRA <div class='captcha'><span class='captchaImg'><img src="{$ticketimg}" alt="captcha" /></span><input type="text" size="10" name="check" /> <input type="hidden" name="__seed" value="{$seed}" /></div> EXTRA; } print <<<FORM2 {$captcha} <input type="hidden" name="action" value="Blog" /> <input type="hidden" name="datestamp" value="{$datestamp}" /> <span class="button"><input type="submit" class="button" value="{$save_msg}" /></span> <span class="button"><input type="submit" class="button" name="button_preview" value="{$preview_msg}" /></span> {$wysiwyg_btn}{$extra} </form> </div> FORM2; if (!empty($DBInfo->use_wikiwyg) and $DBInfo->use_wikiwyg >= 3) { print <<<JS <script type='text/javascript'> /*<![CDATA[*/ sectionEdit(null,null,null); /*]]>*/ </script> JS; } } if (empty($savetext)) { #print $formatter->macro_repl('SmileyChooser'); print macro_EditHints($formatter); print "<div class='wikiHints'>" . _("<b>horizontal rule</b> ---- is not applied on the blog mode.") . "</div>\n"; } if (!empty($options['button_preview']) && !empty($options['savetext'])) { if (!empty($options['title'])) { $formatter->send_page("== {$options['title']} ==\n"); } $formatter->send_page($savetext); } $formatter->send_footer("", $options); return; }
function do_blame($formatter, $params) { global $DBInfo; $rev = ''; $option = ''; if (!empty($params['rev'])) { if (preg_match('/^\\d\\.\\d+$/', $params['rev'])) { $rev = $params['rev']; $option = ' -r' . $rev; } } if (!$formatter->page->exists()) { $params['msg'] = _("Error: Page Not found !"); do_invalid($formatter, $params); return; } $formatter->send_header('', $params); if (isset($rev[0])) { $params['.title'] = sprintf(_("Blame r%s"), $rev); } else { $params['.title'] = sprintf(_("Blame of %s page"), _html_escape($formatter->page->name)); } $key = $DBInfo->getPageKey($formatter->page->name); // FIXME call blame $fp = popen("blame -x,v/ {$option} " . $key, 'r'); //.' '.$formatter->NULL, 'r'); $out = ''; if (is_resource($fp)) { while (!feof($fp)) { $line = fgets($fp, 2048); $out .= $line; } pclose($fp); } $formatter->send_title($title, '', $params); $lines = explode("\n", $out); $end = array_pop($lines); if ($end != '') { array_push($lines, $end); } $u =& $DBInfo->user; $is_member = $u->is_member; // members $members = $DBInfo->members; // check modified blame or not if (($p = strpos($lines[0], "\t")) !== false && $p < 23) { $sep = "@\t@"; $count = 5; } else { $sep = "@\\s+@"; $count = 4; } $ipicon = '<img src="' . $DBInfo->imgs_dir . '/misc/ip.png" />'; if (!empty($DBInfo->use_avatar)) { if (is_string($DBInfo->use_avatar)) { $type = $DBInfo->use_avatar; } else { $type = 'identicon'; } $avatarlink = qualifiedUrl($formatter->link_url('', '?action=' . $type . '&seed=')); } echo '<div class="wikiBlame"><table>'; $ov = ''; $alts = array('', ' alt'); $j = 0; $ii = 1; $blame_url = $formatter->link_url($formatter->page->urlname, '?action=blame&rev='); foreach ($lines as $line) { $tmp = preg_split($sep, $line, $count); $v = trim($tmp[0]); if ($count == 4) { $u = trim($tmp[1], '('); $t = trim($tmp[2], '):'); $l = $tmp[3]; } else { $ip = $tmp[1]; $u = $tmp[2]; $t = $tmp[3]; $l = $tmp[4]; if (!empty($DBInfo->use_avatar)) { $crypted = crypt($ip, $ip); $mylnk = preg_replace('/seed=/', 'seed=' . $crypted, $avatarlink); $avatar = '<img src="' . $mylnk . '" style="width:16px;height:16px;vertical-align:middle" alt="avatar" />'; } else { $avatar = ''; } if ($u == 'Anonymous') { if (!$is_member) { $avatar . ($u = _mask_hostname($ip, 2)); } else { if (isset($DBInfo->interwiki['Whois'])) { $wip = "<a href='" . $DBInfo->interwiki['Whois'] . "{$ip}' target='_blank'>{$ipicon}</a>"; } else { $wip = "<a href='?action=whois&q=" . $ip . "' target='_blank'>{$ipicon}</a>"; } $u = $ip; if (!empty($DBInfo->use_admin_user_url)) { $u = '<a href="' . $DBInfo->use_admin_user_url . $u . '">' . $u . '</a>'; } $u = $avatar . $u . $wip; } } else { if (isset($DBInfo->interwiki['Whois'])) { $wip = "<a href='" . $DBInfo->interwiki['Whois'] . "{$ip}' target='_blank'>{$ipicon}</a>"; } else { $wip = "<a href='?action=whois&q=" . $ip . "' target='_blank'>{$ipicon}</a>"; } if ($is_member) { if (!in_array($u, $members)) { $u = $avatar . $u . $wip; } else { $u = $avatar . $u; } } else { $u = $avatar . $u; } } $t = date('y-m-d', $t); } if ($ov != $v) { $alt = $alts[++$j % 2]; } else { $alt = ''; } $link = '<a href="' . $blame_url . $v . '">' . $v . '</a>'; echo '<tr><td class="version' . $alt . '">r' . $link, '</td> <td class="author' . $alt . '">', "{$u}", '</td> <td class="date' . $alt . '">', $t, '</td><td class="line">' . $ii . '</td><td class="src' . $alt . '">' . str_replace('<', '<', $l) . '</td></tr>'; $ov = $v; $ii++; } echo '</table></div>'; $formatter->send_footer('', $params); return; }
function do_merge($formatter, $params = array()) { global $DBInfo; if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($params)) { $params['title'] = _("Page is not writable"); return do_invalid($formatter, $params); } // check full permission to edit $full_permission = true; if (!empty($DBInfo->no_full_edit_permission) or $params['id'] == 'Anonymous' && !empty($DBInfo->anonymous_no_full_edit_permission)) { $full_permission = false; } // members always have full permission to edit if (in_array($params['id'], $DBInfo->members)) { $full_permission = true; } $is_new = !$formatter->page->exists(); if (!$is_new and !$full_permission) { $formatter->send_header('', $params); $title = _("You do not have full permission to merge this page."); $formatter->send_title($title, '', $params); $formatter->send_footer('', $params); return; } $pagename = isset($params['name'][0]) ? $params['name'] : ''; $formatter->send_header('', $params); $force = 1; if (isset($_POST['name'][0]) and $DBInfo->hasPage($_POST['name'])) { $force = 0; if ($_POST['force']) { $force = 1; } } // validate rev if (!empty($params['rev'])) { $info = $formatter->page->get_info($params['rev']); if (empty($info[0])) { unset($params['rev']); if (!empty($_POST['rev'])) { unset($_POST['rev']); } } } if (!empty($_POST['rev']) and isset($_POST['name'][0]) and $pagename !== $formatter->page->name and $DBInfo->hasPage($pagename)) { if (!empty($DBInfo->version_class)) { $REMOTE_ADDR = $_SERVER['REMOTE_ADDR']; $user =& $DBInfo->user; $comment = _stripslashes($params['comment']); $tag = '{MERGE}'; if (!empty($comment)) { $comment = $tag . ': ' . $comment . ': '; } else { $comment = $tag . ': '; } $log = $REMOTE_ADDR . ';;' . $user->id . ';;' . $comment; $version = $DBInfo->lazyLoad('version', $DBInfo); if (!method_exists($version, 'merge')) { // check merge method $formatter->send_title(_("No merge method available."), '', $params); $formatter->send_footer('', $params); return; } $params['log'] = $log; $ret = array(); $params['retval'] =& $ret; // merge RCS revisions $merged = $version->merge($pagename, $formatter->page->name, $params); if (!$force) { $fname = tempnam($DBInfo->vartmp_dir, 'MERGED'); $fp = fopen($fname . ',v', 'w'); if (is_resource($fp)) { fwrite($fp, $merged); fclose($fp); } // parse rlog require_once dirname(__FILE__) . '/Info.php'; $out = $version->rlog($fname . ',v', ''); $params['simple'] = true; $info = _parse_rlog($formatter, $out, $params); @unlink($fname); @unlink($fname . ',v'); } else { if ($merged !== false) { // $params['retval']['comment'] has merged versions information $log = $comment . $params['retval']['comment']; $DBInfo->addLogEntry($pagename, $REMOTE_ADDR, $log, 'MERGE'); $indexer = $DBInfo->lazyLoad('titleindexer'); if ($is_new) { $indexer->addPage($pagename); } else { $indexer->update($pagename); } $info = ''; } } } else { $formatter->send_title(_("No version control available."), '', $params); $formatter->send_footer('', $params); return; } $params['.title'] = _("Merge result."); $formatter->send_title(sprintf(_("%s is successfully merged."), $formatter->page->name), '', $params); if (!$force) { echo '<h3>' . _("This is a testing merge. Please confirm force option to merge it.") . '</h3>'; } echo $info; $formatter->send_footer('', $params); return; } else { if (!isset($params['name'][0]) || !$DBInfo->hasPage($params['name'])) { $title = _("Please select the original page to merge."); } else { if (empty($params['rev'])) { $title = _("Please select the revision to merge from."); } else { if ($DBInfo->hasPage($formatter->page->name)) { $title = _("Are you really want to merge this page ?"); } } } $params['.title'] = _("Merge Page history."); $formatter->send_title($title, '', $params); } $pname = _html_escape($pagename); $lab = _("Summary"); $rev = !empty($params['rev']) ? _html_escape($params['rev']) : ''; if (!empty($rev) && isset($pagename[0]) && $DBInfo->hasPage($pagename)) { $extra = '<input type="checkbox" name="force" />' . _("Force overwrite") . '<br />'; $placeholder = sprintf(_("Merge [[%s]] with [[%s]] from r%s: "), $pname, _html_escape($formatter->page->name), $rev); echo "<form method='post'>\n{$lab}: <input name='comment' size='80' value='{$comment}' placeholder='{$placeholder}' /><br />\n"; $btn = sprintf(_("Merge [[%s]] to [[%s]]:"), _html_escape($formatter->page->name), $pname); $msg = sprintf(_("Only WikiMaster can %s this page"), _("merge")); if ($DBInfo->security->is_protected("merge", $params)) { echo _("Password") . ": <input type='password' name='passwd' size='20' value='' />\n{$msg}<br />\n"; } echo <<<FORM <input type='hidden' name='name' value='{$pname}' /> <input type='hidden' name='action' value='merge' /> <input type='hidden' name='rev' value='{$rev}' /> <input type='submit' value='{$btn}' />{$extra} </form> FORM; } else { $btn = _("Select Page to Merge"); echo <<<FORM <form method='get'> <input name='name' value='{$pname}' /> <input type='hidden' name='action' value='merge' /> <input type='submit' value='{$btn}' />{$extra} </form> FORM; } if (isset($pagename[0]) && $pagename !== $formatter->page->name && $DBInfo->hasPage($pagename)) { echo macro_Merge($formatter, $pagename, $params); } $formatter->send_footer('', $params); return; }
function do_revert($formatter, $options) { global $DBInfo; if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($options)) { $options['title'] = _("Page is not writable"); return do_invalid($formatter, $options); } // check full permission to edit $full_permission = true; if (!empty($DBInfo->no_full_edit_permission) or $options['id'] == 'Anonymous' && !empty($DBInfo->anonymous_no_full_edit_permission)) { $full_permission = false; } // members always have full permission to edit if (in_array($options['id'], $DBInfo->members)) { $full_permission = true; } $is_new = false; if (!$formatter->page->exists()) { $is_new = true; } if (!$is_new and !$full_permission) { $formatter->send_header('', $options); $title = _("You do not have full permission to rollback this page on this wiki."); $formatter->send_title($title, '', $options); $formatter->send_footer('', $options); return; } $formatter->send_header('', $options); $force = 1; if (isset($_POST['name'][0]) and $DBInfo->hasPage($_POST['name'])) { $force = 0; if ($_POST['force']) { $force = 1; } } // validate rev if (!empty($options['rev'])) { $info = $formatter->page->get_info($options['rev']); if (empty($info[0])) { unset($options['rev']); if (!empty($_POST['rev'])) { unset($_POST['rev']); } } } if (!empty($_POST['rev']) and isset($_POST['name'][0]) and $force) { if (!empty($DBInfo->version_class)) { $REMOTE_ADDR = $_SERVER['REMOTE_ADDR']; $user =& $DBInfo->user; $comment = _stripslashes($options['comment']); $key = $DBInfo->getPageKey($formatter->page->name); $version = $DBInfo->lazyLoad('version', $DBInfo); if ($force) { @unlink($key); } // try to delete $ret = $version->co($formatter->page->name, $_POST['rev'], array('stdout' => 1)); chmod($key, 0666); $log = $REMOTE_ADDR . ';;' . $user->id . ';;' . $comment; $keyname = $DBInfo->_getPageKey($formatter->page->name); $DBInfo->addLogEntry($formatter->page->name, $REMOTE_ADDR, $comment, 'REVERT'); $indexer = $DBInfo->lazyLoad('titleindexer'); if ($is_new) { $indexer->addPage($formatter->page->name); } else { $indexer->update($formatter->page->name); } } else { $formatter->send_title(_("No version control available."), "", $options); $formatter->send_footer('', $options); return; } $formatter->send_title(sprintf(_("%s is successfully rollback."), $formatter->page->name), "", $options); $formatter->send_footer('', $options); return; } else { if (empty($options['rev'])) { $title = _("Please select old revision to revert."); } else { if ($DBInfo->hasPage($formatter->page->name)) { $title = _("Are you really want to overwrite this page ?"); $extra = '<input type="checkbox" name="force" />' . _("Force overwrite") . '<br />'; } else { $title = _("Are you really want to revert this page ?"); } } $formatter->send_title($title, "", $options); } $pagename = $formatter->page->name; $lab = _("Summary"); $rev = !empty($options['rev']) ? $options['rev'] : ''; if (!empty($rev)) { $comment = sprintf(_("Rollback to revision %s"), $rev); print "<form method='post'>\n{$lab}: <input name='comment' size='80' value='{$comment}' /><br />\n"; $btn = _("Revert page"); $msg = sprintf(_("Only WikiMaster can %s this page"), _("revert")); if ($DBInfo->security->is_protected("revert", $options)) { print _("Password") . ": <input type='password' name='passwd' size='20' value='' />\n{$msg}<br />\n"; } print "\n <input type='hidden' name='action' value='revert' />\n <input type='hidden' name='rev' value='{$rev}' />\n <input type='hidden' name='name' value='{$pagename}' />\n <input type='submit' value='{$btn}' />{$extra}\n </form>"; } print macro_revert($formatter, $options['value'], $options); $formatter->send_footer('', $options); return; }
function do_revoke($formatter, $options) { global $DBInfo; if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($options)) { $options['title'] = _("Page is not writable"); return do_invalid($formatter, $options); } $is_new = false; if (!$formatter->page->exists()) { $is_new = true; } if ($is_new) { $formatter->send_header('', $options); $title = _("You can't revoke already deleted page."); $formatter->send_title($title, '', $options); $formatter->send_footer('', $options); return; } // check revocable $params = array(); $retval = array(); $params['retval'] =& $retval; macro_Stat($formatter, $value, $params); $is_ok = false; if ($retval['first_author'] == $options['id'] || in_array($options['id'], $DBInfo->members)) { $is_ok = true; } // get the site specific hash code $ticket = $formatter->page->mtime() . getTicket($DBInfo->user->id, $_SERVER['REMOTE_ADDR']); $hash = md5($ticket); $formatter->send_header('', $options); if ($is_ok && $_SERVER['REQUEST_METHOD'] == 'POST' && $hash == $options['hash']) { // simple comment check $comment = _stripslashes($options['comment']); $comment = trim($comment); $default = _("Revoke"); if (isset($comment[0]) && ($p = strpos($comment, $default)) === 0) { $comment = substr($comment, strlen($default)); $comment = trim($comment); $comment = ltrim($comment, ': '); } $options['comment'] = isset($comment[0]) ? $default . ': ' . $comment : $default; $options['.revoke'] = true; $ret = $DBInfo->deletePage($formatter->page, $options); if ($ret == -1) { if (!empty($options['retval']['msg'])) { $title = $options['retval']['msg']; } else { $title = sprintf(_("Fail to revoke \"%s\""), _html_escape($formatter->page->name)); } } else { $title = sprintf(_("\"%s\" is successfully revoked !"), _html_escape($formatter->page->name)); } $formatter->send_title($title, '', $options); $formatter->send_footer('', $options); return; } $pagename = $formatter->page->name; $lab = _("Summary"); if (!$is_ok) { $title = _("You are not the first author of this page or do not have enough revoke permission"); $formatter->send_title($title, '', $options); $formatter->send_footer('', $options); return; } if ($retval['first_author'] == $options['id']) { $title = _("You are the first author of this page"); } else { $title = _("Do you want to revoke this page?"); } $formatter->send_title($title, '', $options); $comment = _("Revoke"); print "<form method='post'>\n {$lab} : <input name='comment' size='80' value='{$comment}: ' /><br />\n"; $btn = _("Revoke page"); $msg = sprintf(_("Only WikiMaster can %s this page"), _("revoke")); if ($DBInfo->security->is_protected("revoke", $options)) { print _("Password") . ": <input type='password' name='passwd' size='20' value='' />\n{$msg}<br />\n"; } print "\n <input type='hidden' name='action' value='revoke' />\n <input type='hidden' name='hash' value='{$hash}' />\n <input type='submit' value='{$btn}' />{$extra}\n </form>"; $formatter->send_footer('', $options); return; }
function wiki_main($options) { global $DBInfo, $Config; $pagename = isset($options['pagename'][0]) ? $options['pagename'] : $DBInfo->frontpage; # get primary variables if (isset($_SERVER['REQUEST_METHOD']) and $_SERVER['REQUEST_METHOD'] == 'POST') { // reset some reserved variables if (isset($_POST['retstr'])) { unset($_POST['retstr']); } if (isset($_POST['header'])) { unset($_POST['header']); } # hack for TWiki plugin $action = ''; if (!empty($_FILES['filepath']['name'])) { $action = 'draw'; } if (isset($GLOBALS['HTTP_RAW_POST_DATA'])) { # hack for Oekaki: PageName----action----filename list($pagename, $action, $value) = explode('----', $pagename, 3); $options['value'] = $value; } else { $value = !empty($_POST['value']) ? $_POST['value'] : ''; $action = !empty($_POST['action']) ? $_POST['action'] : $action; if (empty($action)) { $dum = explode('----', $pagename, 3); if (isset($dum[0][0]) && isset($dum[1][0])) { $pagename = trim($dum[0]); $action = trim($dum[1]); $value = isset($dum[2][0]) ? $dum[2] : ''; } } } $goto = !empty($_POST['goto']) ? $_POST['goto'] : ''; $popup = !empty($_POST['popup']) ? 1 : 0; // ignore invalid POST actions if (empty($goto) and empty($action)) { header('Status: 405 Not allowed'); return; } } else { // reset some reserved variables if (isset($_GET['retstr'])) { unset($_GET['retstr']); } if (isset($_GET['header'])) { unset($_GET['header']); } $action = !empty($_GET['action']) ? $_GET['action'] : ''; $value = isset($_GET['value'][0]) ? $_GET['value'] : ''; $goto = isset($_GET['goto'][0]) ? $_GET['goto'] : ''; $rev = !empty($_GET['rev']) ? $_GET['rev'] : ''; if ($options['id'] == 'Anonymous') { $refresh = 0; } else { $refresh = !empty($_GET['refresh']) ? $_GET['refresh'] : ''; } $popup = !empty($_GET['popup']) ? 1 : 0; } // parse action // action=foobar, action=foobar/macro, action=foobar/json etc. $full_action = $action; $action_mode = ''; if (($p = strpos($action, '/')) !== false) { $full_action = strtr($action, '/', '-'); $action_mode = substr($action, $p + 1); $action = substr($action, 0, $p); } $options['page'] = $pagename; $options['action'] =& $action; $reserved = array('call', 'prefix'); foreach ($reserved as $k) { unset($options[$k]); } // unset all reserved // check pagename length $key = $DBInfo->pageToKeyname($pagename); if (!empty($options['action']) && strlen($key) > 255) { $i = 252; // 252 + reserved 3 (.??) = 255 $newname = $DBInfo->keyToPagename(substr($key, 0, 252)); $j = mb_strlen($newname, $Config['charset']); $j--; do { $newname = mb_substr($pagename, 0, $j, $Config['charset']); $key = $DBInfo->pageToKeyname($newname); } while (strlen($key) > 248 && --$j > 0); $options['page'] = $newname; $options['orig_pagename'] = $pagename; // original page name $pagename = $newname; } else { $options['orig_pagename'] = ''; } if (function_exists('local_pre_check')) { local_pre_check($action, $options); } // load ruleset if (!empty($Config['config_ruleset'])) { $ruleset_file = 'config/ruleset.' . $Config['config_ruleset'] . '.php'; if (file_exists($ruleset_file)) { $ruleset = load_ruleset($ruleset_file); $Config['ruleset'] = $ruleset; } // is it robot ? if (!empty($ruleset['allowedrobot'])) { if (empty($_SERVER['HTTP_USER_AGENT'])) { $options['is_robot'] = 1; } else { $options['is_robot'] = is_allowed_robot($ruleset['allowedrobot'], $_SERVER['HTTP_USER_AGENT']); } } // setup staff members if (!empty($ruleset['staff'])) { $DBInfo->members = array_merge($DBInfo->members, $ruleset['staff']); } } $page = $DBInfo->getPage($pagename); $page->is_static = false; // FIXME $pis = array(); // get PI cache if ($page->exists()) { $page->pi = $pis = $page->get_instructions('', array('refresh' => $refresh)); // set some PIs for robot if (!empty($options['is_robot'])) { $DBInfo->use_sectionedit = 0; # disable section edit $page->is_static = true; } else { if ($_SERVER['REQUEST_METHOD'] == 'GET' or $_SERVER['REQUEST_METHOD'] == 'HEAD') { if (empty($action) and empty($refresh)) { $page->is_static = empty($pis['#nocache']) && empty($pis['#dynamic']); } } } } // HEAD support for robots if (empty($action) and !empty($_SERVER['REQUEST_METHOD']) and $_SERVER['REQUEST_METHOD'] == 'HEAD') { if (!$page->exists()) { header("HTTP/1.1 404 Not found"); header("Status: 404 Not found"); } else { if ($page->is_static or is_static_action($options)) { $mtime = $page->mtime(); $etag = $page->etag($options); $lastmod = gmdate('D, d M Y H:i:s \\G\\M\\T', $mtime); header('Last-Modified: ' . $lastmod); if (!empty($action)) { $etag = '"' . $etag . '"'; header('ETag: ' . $etag); } // checksum request if (isset($_SERVER['HTTP_X_GET_CHECKSUM'])) { header('X-Checksum: md5-' . md5($page->get_raw_body())); } } } return; } if (is_static_action($options) or !empty($DBInfo->use_conditional_get) and $page->is_static) { $mtime = $page->mtime(); $etag = $page->etag($options); $lastmod = gmdate('D, d M Y H:i:s \\G\\M\\T', $mtime); $need = http_need_cond_request($mtime, $lastmod, $etag); if (!$need) { @ob_end_clean(); $headers = array(); $headers[] = 'HTTP/1.0 304 Not Modified'; $headers[] = 'Last-Modified: ' . $lastmod; foreach ($headers as $header) { header($header); } return; } } $formatter = new Formatter($page, $options); $formatter->refresh = !empty($refresh) ? $refresh : ''; $formatter->popup = !empty($popup) ? $popup : ''; $formatter->tz_offset = $options['tz_offset']; // check blocklist/whitelist for block_actions $act = strtolower($action); while (!empty($DBInfo->block_actions) && !empty($ruleset) && in_array($act, $DBInfo->block_actions)) { require_once 'lib/checkip.php'; // check whitelist if (isset($ruleset['whitelist']) && check_ip($ruleset['whitelist'], $_SERVER['REMOTE_ADDR'])) { break; } $res = null; // check blacklist if (isset($ruleset['blacklist']) && check_ip($ruleset['blacklist'], $_SERVER['REMOTE_ADDR']) || isset($ruleset['blacklist.ranges']) && search_network($ruleset['blacklist.ranges'], $_SERVER['REMOTE_ADDR'])) { $res = true; } else { if (!empty($DBInfo->use_dynamic_blacklist)) { require_once 'plugin/ipinfo.php'; $blacklist = get_cached_temporary_blacklist(); $retval = array(); $ret = array('retval' => &$retval); $res = search_network($blacklist, $_SERVER['REMOTE_ADDR'], $ret); if ($res !== false) { // retrieve found $ac = new Cache_Text('ipblock'); $info = $ac->fetch($retval, 0, $ret); if ($info !== false) { if (!$info['suspended']) { // whitelist IP break; } $res = true; } else { $ac->remove($retval); // expired IP entry. $res = false; } } } } // show warning message if ($res) { $options['notice'] = _("Your IP is in the blacklist"); $options['msg'] = _("Please contact WikiMasters"); $options['msgtype'] = 'warn'; if (!empty($DBInfo->edit_actions) and in_array($act, $DBInfo->edit_actions)) { $options['action'] = $action = 'edit'; } else { if ($act != 'edit') { $options['action'] = $action = 'show'; } } break; } // check kiwirian if (isset($ruleset['kiwirian']) && in_array($options['id'], $ruleset['kiwirian'])) { $options['title'] = _("You are blocked in this wiki"); $options['msg'] = _("Please contact WikiMasters"); do_invalid($formatter, $options); return false; } break; } // set robot class if (!empty($options['is_robot'])) { if (!empty($DBInfo->security_class_robot)) { $class = 'Security_' . $DBInfo->security_class_robot; include_once 'plugin/security/' . $DBInfo->security_class_robot . '.php'; } else { $class = 'Security_robot'; include_once 'plugin/security/robot.php'; } $DBInfo->security = new $class($DBInfo); // is it allowed to robot ? if (!$DBInfo->security->is_allowed($action, $options)) { $action = 'show'; if (!empty($action_mode)) { return '[]'; } } $DBInfo->extra_macros = ''; } while (empty($action) or $action == 'show') { if (isset($value[0])) { # ?value=Hello $options['value'] = $value; do_goto($formatter, $options); return true; } else { if (isset($goto[0])) { # ?goto=Hello $options['value'] = $goto; do_goto($formatter, $options); return true; } } if (!$page->exists()) { if (isset($options['retstr'])) { return false; } if (!empty($DBInfo->auto_search) && $action != 'show' && ($p = getPlugin($DBInfo->auto_search))) { $action = $DBInfo->auto_search; break; } // call notfound action $action = 'notfound'; break; } # render this page if (isset($_GET['redirect']) and !empty($DBInfo->use_redirect_msg) and $action == 'show') { $redirect = $_GET['redirect']; $options['msg'] = '<h3>' . sprintf(_("Redirected from page \"%s\""), $formatter->link_tag(_rawurlencode($redirect), '?action=show', $redirect)) . "</h3>"; } if (empty($action)) { $options['pi'] = 1; } # protect a recursivly called #redirect if (!empty($DBInfo->control_read) and !$DBInfo->security->is_allowed('read', $options)) { $options['action'] = 'read'; do_invalid($formatter, $options); return; } $formatter->pi = $formatter->page->get_instructions(); if (!empty($DBInfo->body_attr)) { $options['attr'] = $DBInfo->body_attr; } $ret = $formatter->send_header('', $options); if (empty($options['is_robot'])) { if ($DBInfo->use_counter) { $DBInfo->counter->incCounter($pagename, $options); } if (!empty($DBInfo->use_referer) and isset($_SERVER['HTTP_REFERER'])) { log_referer($_SERVER['HTTP_REFERER'], $pagename); } } $formatter->send_title("", "", $options); $formatter->write("<div id='wikiContent'>\n"); if (isset($options['timer']) and is_object($options['timer'])) { $options['timer']->Check("init"); } // force #nocache for #redirect pages if (isset($formatter->pi['#redirect'][0])) { $formatter->pi['#nocache'] = 1; } $extra_out = ''; $options['pagelinks'] = 1; if (!empty($Config['cachetime']) and $Config['cachetime'] > 0 and empty($formatter->pi['#nocache'])) { $cache = new Cache_text('pages', array('ext' => 'html')); $mcache = new Cache_text('dynamic_macros'); $mtime = $cache->mtime($pagename); $now = time(); $check = $now - $mtime; $_macros = null; if ($cache->mtime($pagename) < $formatter->page->mtime()) { $formatter->refresh = 1; } // force update $valid = false; $delay = !empty($DBInfo->default_delaytime) ? $DBInfo->default_delaytime : 0; if (empty($formatter->refresh) and $DBInfo->checkUpdated($mtime, $delay) and $check < $Config['cachetime']) { if ($mcache->exists($pagename)) { $_macros = $mcache->fetch($pagename); } // FIXME TODO: check postfilters if (0 && empty($_macros)) { #$out = $cache->fetch($pagename); $valid = $cache->fetch($pagename, '', array('print' => 1)); } else { $out = $cache->fetch($pagename); $valid = $out !== false; } $mytime = gmdate("Y-m-d H:i:s", $mtime + $options['tz_offset']); $extra_out = "<!-- Cached at {$mytime} -->"; } if (!$valid) { $formatter->_macrocache = 1; ob_start(); $formatter->send_page('', $options); flush(); $out = ob_get_contents(); ob_end_clean(); $formatter->_macrocache = 0; $_macros = $formatter->_dynamic_macros; if (!empty($_macros)) { $mcache->update($pagename, $_macros); } if (isset($out[0])) { $cache->update($pagename, $out); } } if (!empty($_macros)) { $mrule = array(); $mrepl = array(); foreach ($_macros as $m => $v) { if (!is_array($v)) { continue; } $mrule[] = '@@' . $v[0] . '@@'; $options['mid'] = $v[1]; $mrepl[] = $formatter->macro_repl($m, '', $options); // XXX } echo $formatter->get_javascripts(); $out = str_replace($mrule, $mrepl, $out); // no more dynamic macros found if (empty($formatter->_dynamic_macros)) { // update contents $cache->update($pagename, $out); // remove dynamic macros cache $mcache->remove($pagename); } } if ($options['id'] != 'Anonymous') { $args['refresh'] = 1; } // add refresh menu } else { ob_start(); $formatter->send_page('', $options); flush(); $out = ob_get_contents(); ob_end_clean(); } // fixup to use site specific thumbwidth if (!empty($Config['site_thumb_width']) and $Config['site_thumb_width'] != $DBInfo->thumb_width) { $opts = array('thumb_width' => $Config['site_thumb_width']); $out = $formatter->postfilter_repl('imgs_for_mobile', $out, $opts); } echo $out, $extra_out; // automatically set #dynamic PI if (empty($formatter->pi['#dynamic']) and !empty($formatter->_dynamic_macros)) { $pis = $formatter->pi; if (empty($pis['raw'])) { // empty PIs $pis = array(); } else { if (isset($pis['#format']) and !preg_match('/#format\\s/', $pis['raw'])) { // #format not found in PIs unset($pis['#format']); } } $pis['#dynamic'] = 1; // internal instruction $pi_cache = new Cache_text('PI'); $pi_cache->update($formatter->page->name, $pis); } else { if (empty($formatter->_dynamic_macros) and !empty($formatter->pi['#dynamic'])) { $pi_cache = new Cache_text('PI'); $pi_cache->remove($formatter->page->name); // reset PI $mcache->remove($pagename); // remove macro cache if (isset($out[0])) { $cache->update($pagename, $out); } // update cache content } } if (isset($options['timer']) and is_object($options['timer'])) { $options['timer']->Check("send_page"); } $formatter->write("<!-- wikiContent --></div>\n"); if (!empty($DBInfo->extra_macros) and $formatter->pi['#format'] == $DBInfo->default_markup) { if (!empty($formatter->pi['#nocomment'])) { $options['nocomment'] = 1; $options['notoolbar'] = 1; } $options['mid'] = 'dummy'; echo '<div id="wikiExtra">' . "\n"; $mout = ''; $extra = array(); if (is_array($DBInfo->extra_macros)) { $extra = $DBInfo->extra_macros; } else { $extra[] = $DBInfo->extra_macros; } // XXX if (!empty($formatter->pi['#comment'])) { array_unshift($extra, 'Comment'); } foreach ($extra as $macro) { $mout .= $formatter->macro_repl($macro, '', $options); } echo $formatter->get_javascripts(); echo $mout; echo '</div>' . "\n"; } $args['editable'] = 1; $formatter->send_footer($args, $options); return; } $act = $action; if (!empty($DBInfo->myplugins) and array_key_exists($action, $DBInfo->myplugins)) { $act = $DBInfo->myplugins[$action]; } if ($act) { $options['noindex'] = true; $options['custom'] = ''; $options['help'] = ''; $options['value'] = $value; $a_allow = $DBInfo->security->is_allowed($act, $options); if (!empty($action_mode)) { $myopt = $options; $myopt['explicit'] = 1; $f_allow = $DBInfo->security->is_allowed($full_action, $myopt); # check if hello/ajax is defined or not if ($f_allow === false && $a_allow) { $f_allow = $a_allow; } # follow action permission if it is not defined explicitly. if (!$f_allow) { $args = array('action' => $action); $args['allowed'] = $options['allowed'] = $f_allow; if ($f_allow === false) { $title = sprintf(_("%s action is not found."), $action); } else { $title = sprintf(_("Invalid %s action."), $action_mode); } if ($action_mode == 'ajax') { $args['title'] = $title; return ajax_invalid($formatter, $args); } $options['title'] = $title; return do_invalid($formatter, $options); } } else { if (!$a_allow) { $options['allowed'] = $a_allow; if ($options['custom'] != '' and method_exists($DBInfo->security, $options['custom'])) { $options['action'] = $action; if ($action) { call_user_func(array(&$DBInfo->security, $options['custom']), $formatter, $options); } return; } return do_invalid($formatter, $options); } else { if ($_SERVER['REQUEST_METHOD'] == "POST" and $DBInfo->security->is_protected($act, $options) and !$DBInfo->security->is_valid_password($_POST['passwd'], $options)) { # protect some POST actions and check a password $title = sprintf(_("Fail to \"%s\" !"), $action); $formatter->send_header("", $options); $formatter->send_title($title, "", $options); $formatter->send_page("== " . _("Please enter the valid password") . " =="); $formatter->send_footer("", $options); return; } } } $options['action_mode'] = ''; if (!empty($action_mode) and in_array($action_mode, array('ajax', 'macro'))) { if ($_SERVER['REQUEST_METHOD'] == "POST") { $options = array_merge($_POST, $options); } else { $options = array_merge($_GET, $options); } $options['action_mode'] = $action_mode; if ($action_mode == 'ajax') { $formatter->ajax_repl($action, $options); } else { if (!empty($DBInfo->use_macro_as_action)) { # XXX echo $formatter->macro_repl($action, $options['value'], $options); } else { do_invalid($formatter, $options); } } return; } // is it valid action ? $plugin = $pn = getPlugin($action); if ($plugin === '') { // action not found $plugin = $action; } if (!function_exists("do_post_" . $plugin) and !function_exists("do_" . $plugin) and $pn) { include_once "plugin/{$pn}.php"; } if (function_exists("do_" . $plugin)) { if ($_SERVER['REQUEST_METHOD'] == "POST") { $options = array_merge($_POST, $options); } else { $options = array_merge($_GET, $options); } call_user_func("do_{$plugin}", $formatter, $options); return; } else { if (function_exists("do_post_" . $plugin)) { if ($_SERVER['REQUEST_METHOD'] == "POST") { $options = array_merge($_POST, $options); } else { # do_post_* set some primary variables as $options $options['value'] = isset($_GET['value'][0]) ? $_GET['value'] : ''; } call_user_func("do_post_{$plugin}", $formatter, $options); return; } } do_invalid($formatter, $options); return; } }
function do_reverse($formatter, $options = array()) { global $DBInfo; if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($options)) { $options['title'] = _("Page is not writable"); return do_invalid($formatter, $options); } // check full permission to edit $full_permission = true; if (!empty($DBInfo->no_full_edit_permission) or $options['id'] == 'Anonymous' && !empty($DBInfo->anonymous_no_full_edit_permission)) { $full_permission = false; } // members always have full permission to edit if (in_array($options['id'], $DBInfo->members)) { $full_permission = true; } $is_new = false; if (!$formatter->page->exists()) { $is_new = true; } if (!$is_new and !$full_permission) { $formatter->send_header('', $options); $title = _("You do not have full permission to rollback this page on this wiki."); $formatter->send_title($title, '', $options); $formatter->send_footer('', $options); return; } $pagename = $formatter->page->urlname; $force = 1; if (isset($_POST['rev'][0]) && $DBInfo->hasPage($options['page'])) { $force = 0; if ($_POST['force']) { $force = 1; } } // validate rev $rev = isset($_POST['rev'][0]) ? $_POST['rev'] : $options['rev']; if (!empty($rev)) { $info = array(); if (preg_match('/^[a-zA-Z0-9\\.]+$/', $rev)) { $info = $formatter->page->get_info($rev); } if (empty($info[0])) { // no version found unset($rev); unset($options['rev']); unset($_POST['rev']); } } // check ticket $ticket = getTicket($formatter->page->mtime() . $options['id'] . $_SERVER['REMOTE_ADDRESS']); if ($force and !empty($pagename) and !empty($_POST['rev']) and $ticket == $options['ticket']) { // simple comment check $comment = trim($options['comment']); $default = sprintf(_("Rollback to revision %s"), $rev); if (isset($comment[0]) && ($p = strpos($comment, $default)) === 0) { $comment = substr($comment, strlen($default)); $comment = trim($comment); $comment = ltrim($comment, ': '); } $comment = isset($comment[0]) ? $default . ': ' . $comment : $default; // get current revision $current_body = $formatter->page->_get_raw_body(); // get old revision $body = $formatter->page->get_raw_body($options); if ($body == $current_body) { $title = sprintf(_("No change found.")); } else { if ($body == '') { $title = sprintf(_("Empty Page!")); } else { $options['.reverted'] = 1; $formatter->page->write($body); $ret = $DBInfo->savePage($formatter->page, $comment, $options); if ($ret != -1) { $title = sprintf(_("%s is successfully rollbacked."), _html_escape($page->name)); } else { $title = sprintf(_("Failed to rollback %s page"), _html_escape($page->name)); } } } $formatter->send_header('', $options); $formatter->send_title($title, '', $options); $formatter->send_footer('', $options); return; } $extra = ''; if (empty($options['rev'])) { $title = _("Please select old revision to revert."); } else { if ($DBInfo->hasPage($formatter->page->name)) { if ($_POST['rev']) { $title = sprintf(_("Please check force overwrite to revert %s revision."), $rev); } else { $title = sprintf(_("Are you really want to overwrite %s page to %s revision ?"), $options['page'], $rev); } $extra = '<input type="checkbox" name="force" />' . _("Force overwrite") . '<br />'; } else { $title = sprintf(_("Are you really want to revert %s page to %s revision ?"), $options['page'], $rev); } } $formatter->send_header('', $options); $formatter->send_title($title, '', $options); if ($rev) { $msg = _("Summary"); $btn = _("Revert page"); $comment = sprintf(_("Rollback to revision %s"), $rev); $hidden = '<input type="hidden" name="ticket" value="' . $ticket . '" />'; echo "<form method='post'>\n", "<span>{$msg}: </span><input name='comment' size='80' maxlength='80' value='{$comment}: ' />\n", "<input type='hidden' name='action' value='reverse' />\n", "<input type='hidden' name='rev' value='" . $rev . "' />\n", $hidden, "<br /><input type='submit' value='{$btn}' />{$extra}\n", "</form>"; } $params = array(); $params['page'] = $options['page']; $params['info_actions'] = array('recall' => 'view', 'reverse' => 'revert'); $params['title'] = '<h3>' . sprintf(_("Old Revisions of the %s"), _html_escape($formatter->page->name)) . '</h3>'; echo $formatter->macro_repl('Info', '', $params); $formatter->send_footer('', $options); }
function do_SWFUpload($formatter, $options = array()) { global $DBInfo; if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($options)) { $options['title'] = _("Page is not writable"); return do_invalid($formatter, $options); } // check allowed file extensions $allowed_re = '.*'; if (!empty($DBInfo->pds_allowed)) { $allowed_re = $DBInfo->pds_allowed; } $swfupload_dir = $DBInfo->upload_dir . '/.swfupload'; $mysubdir = ''; if (!is_dir($swfupload_dir)) { $om = umask(00); mkdir($swfupload_dir, 0777); umask($om); $fp = fopen($swfupload_dir . '/.htaccess', 'w'); if ($fp) { $htaccess = <<<EOF Options -Indexes Order deny,allow deny from all EOF; fwrite($fp, $htaccess); fclose($fp); } } // check subdir if (!empty($DBInfo->swfupload_depth) and $DBInfo->swfupload_depth > 2) { $depth = $DBInfo->swfupload_depth; } else { $depth = 2; } $seed = $_SERVER['REMOTE_ADDR'] . '.' . 'MONIWIKI'; if ($DBInfo->seed) { $seed .= $DBInfo->seed; } $myid = md5($seed); // FIXME if (session_id() != '') { // ip based if (0 and $_SESSION['_swfupload']) { // XXX flash bug? $myid = $_SESSION['_swfupload']; } else { if (!empty($options['value']) and ($p = strpos($options['value'], '/')) !== false) { $tmp = explode('/', $options['value']); #list($dum,$myid,$dum2)=explode('/',$options['value'],3); $myid = $tmp[1]; } } } $prefix = substr($myid, 0, $depth); $mysubdir = $prefix . '/' . $myid . '/'; // debug //$options['_mysubdir']=$mysubdir; //$fp=fopen($swfupload_dir.'/swflog.txt','a+'); //foreach ($options as $k=>$v) { // if (is_string($v)) // fwrite($fp,sprintf("%s=>%s\n",$k,$v)); //} //foreach ($_SESSION as $k=>$v) { // if (is_string($v)) // fwrite($fp,sprintf("%s=>%s\n",$k,$v)); //} //fwrite($fp,"------------------------\n"); //fclose($fp); // set the personal subdir if (!empty($options['value']) and preg_match('/^[a-z0-9\\/]+$/i', $options['value'])) { //if ($mysubdir == $options['value']) // XXX check subdir // $mysubdir = $options['value']; list($dum, $myval, $dum2) = explode('/', $options['value'], 3); // XXX if (!is_dir($swfupload_dir . '/' . $mysubdir)) { $om = umask(00); _mkdir_p($swfupload_dir . '/' . $mysubdir, 0777); umask($om); } } //move the uploaded file if (isset($_FILES['Filedata']['tmp_name'])) { if (preg_match('/\\.(' . $allowed_re . ')$/i', $_FILES['Filedata']['name'])) { move_uploaded_file($_FILES['Filedata']['tmp_name'], $swfupload_dir . '/' . $mysubdir . $_FILES['Filedata']['name']); } echo "Success"; return; } else { if (isset($options['MYFILES']) and is_array($options['MYFILES'])) { include_once 'plugin/UploadFile.php'; $options['_pds_subdir'] = $mysubdir; // a temporary pds dir $options['_pds_remove'] = 1; // remove all files in pds dir do_UploadFile($formatter, $options); } else { $formatter->send_header("", $options); $formatter->send_title("", "", $options); $out = macro_SWFUpload($formatter, ''); print $formatter->get_javascripts(); print $out; if (!in_array('UploadedFiles', $formatter->actions)) { $formatter->actions[] = 'UploadedFiles'; } $formatter->send_footer("", $options); } } }
function do_msgfmt($formatter, $options) { global $DBInfo; if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($options)) { $options['title'] = _("Page is not writable"); return do_invalid($formatter, $options); } $po = ''; $domain = 'PoHello'; if (isset($options['msgid']) or isset($options['msgstr'])) { # just check a single msgstr header("Content-type: text/plain"); $date = date('Y-m-d h:i+0900'); $charset = strtoupper($DBInfo->charset); if (_stripslashes($options['msgid']) != '""') { $po = <<<POHEAD msgid "" msgstr "" "Project-Id-Version: {$domain} 1.1\\n" "POT-Creation-Date: {$date}\\n" "PO-Revision-Date: {$date}\\n" "Last-Translator: MoniWiki <nobody@localhost>\\n" "Language-Team: moniwiki <ko@localhost>\\n" "MIME-Version: 1.0\\n" "Content-Type: text/plain; charset={$charset}\\n" "Content-Transfer-Encoding: 8bit\\n" #: src/test.c POHEAD; } $po .= 'msgid ' . _stripslashes($options['msgid']) . "\n"; #$msg=preg_replace('/""(?!")/',"\"\n\"", # _stripslashes($options['msgstr'])); $msg = _stripslashes($options['msgstr']); $po .= 'msgstr ' . $msg . "\n"; $po .= "\n\n"; $ret = _pocheck($po, 1); if ($ret == true) { print "true\n" . $po; } return; } if ($options['po'] and $options['btn']) { $formatter->send_header('', $options); $formatter->send_title(sprintf(_("Translation of %s"), $options['page']), '', $options); $comment = $options['comment'] ? _stripslashes($options['comment']) : "Translations are updated"; $po = preg_replace("/(\r\n|\r)/", "\n", _stripslashes($options['po'])); $formatter->page->write($po); $ret = $DBInfo->savePage($formatter->page, $comment, $options); if ($ret != -1) { print "<h2>" . _("Translations are successfully updated.") . "</h2>"; } else { print "<h2>" . _("Fail to save translations.") . "</h2>"; } $formatter->send_footer('', $options); return; } $msgkeys = array_keys($options); $msgids = preg_grep('/^msgid-/', $msgkeys); $msgstrs = preg_grep('/^msgstr-/', $msgkeys); if (sizeof($msgids) != sizeof($msgstrs)) { print "Invalid request."; return; } $rawpo = $formatter->page->_get_raw_body(); $lines = explode("\n", $rawpo); $po = ''; $comment = ''; $msgid = array(); $msgstr = array(); foreach ($lines as $l) { if ($l[0] != 'm' and !preg_match('/^\\s*"/', $l)) { if ($msgstr) { $mid = implode("\n", $msgid); $id = md5($mid); $msg = preg_replace("/(\r\n|\r)/", "\n", _stripslashes($options['msgstr-' . $id])); $sid = md5(rtrim($msg)); if ($options['md5sum-' . $id] and $options['md5sum-' . $id] != $sid) { $comment = preg_replace('/#, fuzzy\\n/m', '', $comment); $comment = str_replace(', fuzzy', '', $comment); } # fix msgstr #$msg=preg_replace('/(?!<\\\\)"/','\\"',$msg); $po .= $comment; $po .= 'msgid ' . preg_replace('/(\\r\\n|\\r)/', "\n", _stripslashes($options['msgid-' . $id])) . "\n"; $po .= 'msgstr ' . $msg . "\n"; # init $msgid = array(); $msgstr = array(); $comment = ''; } if ($l[0] == '#' and $l[1] == ',') { if ($comment) { $po .= $comment; $comment = ''; } $comment .= $l . "\n"; } else { if ($comment) { $po .= $comment; $comment = ''; } $po .= $l . "\n"; continue; } } else { if (preg_match('/^(msgid|msgstr)\\s+(".*")\\s*$/', $l, $m)) { if ($m[1] == 'msgid') { $msgid[] = $m[2]; continue; } $msgstr[] = $m[2]; } else { if (preg_match('/^\\s*(".*")\\s*$/', $l, $m)) { if ($msgstr) { $msgstr[] = $m[1]; } else { $msgid[] = $m[1]; } } else { $po .= $l . "\n"; } } } } $formatter->send_header('', $options); $formatter->send_title(sprintf(_("Translation of %s"), $options['page']), '', $options); $e = _pocheck($po); #if ($e != true) return; #print $po; $url = $formatter->link_url($formatter->page->urlname); print "<form method='post' action='{$url}'>\n" . "<input type='hidden' name='action' value='msgfmt' />\n"; print "<input type='submit' name='btn' value='Save Translation ?' /> "; print "Summary:" . " <input type='text' size='60' name='comment' value='Translations are updated' />" . "<br />\n"; if ($options['patch']) { include_once 'lib/difflib.php'; $rawpo = array_map(create_function('$a', 'return $a."\\n";'), explode("\n", $rawpo)); $newpo = array_map(create_function('$a', 'return $a."\\n";'), explode("\n", $po)); $diff = new Diff($rawpo, $newpo); $f = new UnifiedDiffFormatter(); $f->trailing_cr = ""; $diffs = $f->format($diff); $sz = sizeof(explode("\n", $diffs)); print "<textarea cols='80' rows='{$sz}' style='width:80%'>"; print $diffs; print "</textarea>\n"; } $po = _html_escape($po); print "<input type='hidden' name='po' value=\"{$po}\" />\n"; print "</form>"; $formatter->send_footer('', $options); return; }
function do_diff($formatter, $options = "") { global $DBInfo; $range = !empty($options['range']) ? $options['range'] : ''; $date = !empty($options['date']) ? $options['date'] : ''; $rev = !empty($options['rev']) ? $options['rev'] : ''; $rev2 = !empty($options['rev2']) ? $options['rev2'] : ''; // check revision number if (!empty($rev) && !preg_match("/^[0-9a-f.]+\$/", $rev) || !empty($rev2) && !preg_match("/^[0-9a-f.]+\$/", $rev2)) { $options['title'] = _("Invalid revision numbers"); $options['msg'] = _("Please set correct revision numbers"); do_invalid($formatter, $options); return; } if (!empty($options['rcspurge'])) { if (!$range) { $range = array(); } $rr = ''; $dum = array(); foreach (array_keys($range) as $r) { if (!$rr) { $rr = $range[$r]; } if ($range[$r + 1]) { continue; } else { $rr .= ":" . $range[$r]; } $dum[] = $rr; $rr = ''; } $options['range'] = join(';', $dum); include_once "plugin/rcspurge.php"; do_RcsPurge($formatter, $options); return; } if (!empty($options['type']) and !in_array($options['type'], array('smart', 'fancy', 'simple'))) { $options['type'] = $DBInfo->diff_type; } else { $options['type'] = $DBInfo->diff_type; } $title = ''; if (!empty($DBInfo->use_smartdiff)) { $rev = substr($rev, 0, 5); $rev2 = substr($rev2, 0, 5); if ($rev and $rev2) { $msg = sprintf(_("Difference between r%s and r%s"), $rev, $rev2); } else { if ($rev) { $msg = sprintf(_("Difference between r%s and the current"), $rev); } else { $msg = _("latest changes"); } } $title = $msg; } $retval = array(); $options['retval'] =& $retval; if ($date) { $options['rev'] = $date; } $diff = macro_diff($formatter, '', $options); if (!empty($options['raw']) || $options['action_mode'] == 'ajax') { header('Content-Type: text/plain'); if ($retval['msg']) { echo '<h2>' . $retval['msg'] . '</h2>'; } $class = 'Diff'; if ($options['type'] == 'fancy' and !empty($options['inline'])) { $class .= 'Inline'; } if (isset($diff[0])) { echo '<div class="' . $options['type'] . $class . '">'; echo $diff; echo '</div>'; } return; } $formatter->send_header("", $options); $formatter->send_title($title, "", $options); $class = 'Diff'; if ($options['type'] == 'fancy' and !empty($options['inline'])) { $class .= 'Inline'; } if (!empty($retval['msg'])) { echo '<h2>', $retval['msg'] . '</h2>'; } echo '<div class="' . $options['type'] . $class . '">'; echo $diff; echo '</div>'; if (empty($DBInfo->diffonly) and empty($options['smart'])) { print "<br /><hr />\n"; $formatter->send_page(); } $formatter->send_footer('', $options); return; }
function do_keywords($formatter, $options) { global $DBInfo; $supported_lang = array('ko'); $page = $formatter->page->name; if (empty($options['update']) and !empty($options['value'])) { $page = $options['value']; } if (!$DBInfo->hasPage($page)) { $options['err'] = _("You are not able to add keywords."); $options['title'] = _("Page does not exists"); do_invalid($formatter, $options); return; } if (!empty($options['update']) or !empty($options['refresh'])) { $lk = $DBInfo->getPage(LOCAL_KEYWORDS); $force_charset = ''; if ($DBInfo->force_charset) { $force_charset = '; charset=' . $DBInfo->charset; } $formatter->send_header("Content-type: text/plain" . $force_charset); if (!$lk->exists()) { print sprintf(_("%s is not found."), LOCAL_KEYWORDS); return; } $raw = $lk->get_raw_body(); # update keylinks of LocalKeywords $kc = new Cache_text('keylinks'); $lines = explode("\n", $raw); $all_keys = array(); foreach ($lines as $l) { $l = trim($l); if ($l[0] == '#' or !$l) { continue; } $ws = preg_split('/((?<!\\S)(["\'])[^\\2]+?\\2(?!\\S)|\\S+)/', $l, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $ws = array_flip(array_unique($ws)); unset($ws['"']); // delete delims unset($ws["'"]); unset($ws[' ']); $ws = array_flip($ws); $ws = array_map(create_function('$a', 'return preg_replace("/^([\\"\'])(.*)\\\\1$/","\\\\2",$a);'), $ws); // delete ",' $ws = array_unique($ws); $all_keys = array_merge($all_keys, $ws); foreach ($ws as $k) { $rels = array_diff($ws, array($k)); $krels = $kc->fetch($k); if (is_array($krels)) { if ($nrels = array_diff($rels, $krels)) { $rs = array_unique(array_merge($nrels, $krels)); $kc->update($k, $rs); print "***** updated {$k}\n"; } } else { if (sizeof($rels) > 1 and is_array($rels)) { $kc->update($k, $rels); print "***** save {$k}\n"; } } } } print_r($all_keys); print "OK"; return; } $args = array(); $formatter->send_header('', $options); if (empty($options['suggest']) and (!empty($options['key']) and is_array($options['key']) or !empty($options['keywords']))) { if (!empty($options['keywords'])) { // following keyword list are acceptable separated with spaces. // Chemistry "Physical Chemistry" "Bio Chemistry" ... $keywords = _stripslashes($options['keywords']); $ws = preg_split('/((?<!\\S)(["\'])[^\\2]+?\\2(?!\\S)|\\S+)/', $keywords, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $ws = array_flip(array_unique($ws)); unset($ws['"']); // delete delims unset($ws["'"]); unset($ws[' ']); $ws = array_flip($ws); $ws = array_map(create_function('$a', 'return preg_replace("/^([\\"\'])(.*)\\\\1$/","\\\\2",$a);'), $ws); // delete ",' if (!is_array($options['key'])) { $options['key'] = array(); } $options['key'] = array_merge($options['key'], $ws); } if (!empty($options['common'])) { $raw = "#format plain"; $lang = $formatter->pi['#language'] ? $formatter->pi['#language'] : ''; $lang = $options['lang'] ? $options['lang'] : $lang; if (in_array($lang, $supported_lang)) { $common_word_page = LOCAL_KEYWORDS . '/CommonWords' . ucfirst($lang); } else { $common_word_page = LOCAL_KEYWORDS . '/CommonWords'; } if ($DBInfo->hasPage($common_word_page)) { $p = $DBInfo->getPage($common_word_page); if (!$p->exists()) { $dict = array(); } else { $raw = $p->get_raw_body(); $raw = rtrim($raw); $lines = explode("\n", $raw); $body = ''; foreach ($lines as $line) { if ($line[0] == '#' or $line == '') { continue; } $body .= $line . "\n"; } $body = rtrim($body); $dict = explode("\n", $body); } $commons = array_diff(array_values($options['key']), $dict); } else { $p = $DBInfo->getPage($common_word_page); $commons = $options['key']; } if (!empty($commons)) { sort($commons); $raw .= "\n" . implode("\n", $commons); $p->write($raw); $DBInfo->savePage($p, "Common words are added", $options); } $formatter->send_title(sprintf(_("Common words are updated"), $options['page']), '', $options); $formatter->send_footer($args, $options); return; } $cache = new Cache_text('keyword'); $keys = $options['key']; $keys = array_flip($keys); unset($keys['']); $cache->update($page, array_keys($keys)); # update 'keylinks' caches #$kc=new Cache_text('keylinks'); #foreach ($options['key'] as $k) { # // XXX # $kv=unserialize($kc->fetch($k)); # if (!in_array($page,$kv)) { # $kv[]=$page; # $kc->update($k,serialize($kv)); # } #} $raw = "#format plain"; $lk = $DBInfo->getPage(LOCAL_KEYWORDS); if (!$lk->exists()) { $dict = array(); } else { $raw = $lk->get_raw_body(); $raw = rtrim($raw); $lines = explode("\n", $raw); $body = ''; foreach ($lines as $line) { if ($line[0] == '#' or $line == '') { continue; } $body .= $line . "\n"; } $body = rtrim($body); } if (!empty($options['key'])) { // XXX $ks = array_map(create_function('$a', 'return (strpos($a," ") !== false) ? "\\"$a\\"":$a;'), $options['key']); $raw .= "\n" . implode(' ', $ks) . "\n"; $lk->write($raw); $DBInfo->savePage($lk, "Keywords are added", $options); } $formatter->send_title(sprintf(_("Keywords for %s are updated"), $page), '', $options); $ret = ''; foreach ($keys as $key => $val) { $ret .= $key . ','; } $ret = substr($ret, 0, strlen($ret) - 1); print "<tt>#keywords {$ret}</tt>\n"; if (!empty($DBInfo->use_keywords) or !empty($options['update'])) { # auto update the page with selected keywords. $body = $formatter->page->get_raw_body(); $pi = $formatter->page->get_instructions($dum); if (!empty($pi['#keywords'])) { $tag = preg_quote($pi['#keywords']); $nbody = preg_replace('/^#keywords\\s+' . $tag . '/', '#keywords ' . $ret, $body, 1); if ($nbody != $body) { $ok = 1; } } else { $nbody = '#keywords ' . $ret . "\n" . $body; $ok = 2; } if (!empty($ok)) { if ($ok == 1) { $comment = "Keywords are updated"; } else { $comment = "Keywords are added"; } $formatter->page->write($nbody); $DBInfo->savePage($formatter->page, $comment, $options); print "<h2>" . _("Keywords are updated") . "</h2>"; } else { print "<h2>" . _("There are no changes found") . "</h2>"; } } else { # user confirmation $link = $formatter->link_url(_rawurlencode($page), ''); $keys = explode(',', $ret); $ret = ''; foreach ($keys as $key) { if ($key and strpos($key, ' ') !== false) { $key = '"' . $key . '"'; } $ret .= $key . ' '; } $btn = _("Update with these Keywords"); $form = "<form method='post' action='{$link}'>"; $form .= '<input type="hidden" name="action" value="keywords" />'; $form .= '<input type="hidden" name="update" value="1" />'; $form .= '<input type="hidden" name="keywords" value=\'' . $ret . '\' />'; $form .= "<input type='submit' value='{$btn}' />\n"; $form .= "</form>"; print $form; } $formatter->send_footer($args, $options); return; } if (!empty($options['all']) or !empty($options['tour'])) { if (!empty($optiopns['sort']) and $options['sort'] == 'freq') { $sort = 'freq'; } $formatter->send_title('', '', $options); $myq = '?' . $_SERVER['QUERY_STRING']; $myq = preg_replace('/&sort=[^&]+/i', '', $myq); if ($sort != 'freq') { $myq .= '&sort=freq'; $txt = _("alphabetically"); $ltxt = _("by frequency"); } else { $txt = _("by size"); $ltxt = _("alphabetically"); } $link = $formatter->link_tag(_rawurlencode($page), $myq, $ltxt); print "<h2>"; print sprintf(_("Keywords list %s (or %s)"), $txt, $link); print "</h2>\n"; if (!$options['limit']) { $options['limit'] = 0; } } else { $formatter->send_title(sprintf(_("Select keywords for %s"), $options['page']), '', $options); $options['merge'] = 1; $options['add'] = 1; } print macro_KeyWords($formatter, $options['page'], $options); //$args['editable']=1; $formatter->send_footer($args, $options); }
function do_subscribe($formatter, $options) { global $DBInfo; if (!$DBInfo->notify and 0) { # XXX $options['title'] = _("EmailNotification is not activated"); $options['msg'] = _("If you want to subscribe this page please contact the WikiMaster to activate the e-mail notification"); do_invalid($formatter, $options); return; } if ($options['id'] != 'Anonymous') { $udb =& $DBInfo->udb; $userinfo = $udb->getUser($options['id']); $email = $userinfo->info['email']; #$subs=$udb->getPageSubscribers($options[page]); if (!$email) { $title = _("Please enter your email address first."); } } else { $title = _("Please login or make your ID."); } if ($options['id'] == 'Anonymous' or !$email) { $formatter->send_header("", $options); $formatter->send_title($title, "", $options); $formatter->send_page("== " . _("Goto UserPreferences") . " ==\n" . _("If you want to subscribe this page, just make your ID and register your email address in the UserPreferences.")); $formatter->send_footer(); return; } if (isset($options['subscribed_pages'])) { $pages = preg_replace("/\n\\s*/", "\n", $options['subscribed_pages']); $pages = preg_replace("/\\s*\n/", "\n", $pages); $pages = explode("\n", $pages); $pages = array_unique($pages); $page_list = join("\t", $pages); $userinfo->info['subscribed_pages'] = $page_list; $udb->saveUser($userinfo); $title = _("Subscribe lists updated."); $formatter->send_header("", $options); $formatter->send_title($title, "", $options); $formatter->send_page("Goto [{$options['page']}]\n"); $formatter->send_footer(); return; } $plist = _preg_search_escape($userinfo->info['subscribed_pages']); $check = 1; if (trim($plist)) { $plists = explode("\t", $plist); $prule = '^' . join("\$|^", $plists) . '$'; if (preg_match('/(' . $prule . ')/', _preg_search_escape($options['page']))) { $title = sprintf(_("\"%s\" is already subscribed."), $options['page']); $check = 0; } } $pages = explode("\t", $userinfo->info['subscribed_pages']); if ($check) { if (!in_array($options['page'], $pages)) { $pages[] = $options['page']; } $title = sprintf(_("Do you want to subscribe \"%s\" ?"), $options['page']); } $page_lists = join("\n", $pages); $formatter->send_header("", $options); $formatter->send_title($title, "", $options); $msg = _("Subscribed pages"); print "<form method='post'>\n<table border='0'><tr>\n<th>{$msg} :</th><td><textarea name='subscribed_pages' cols='30' rows='5' value='' />{$page_lists}</textarea></td></tr>\n<tr><td></td><td>\n <input type='hidden' name='action' value='subscribe' />\n <input type='submit' value='Subscribe' />\n</td></tr>\n</table>\n </form>"; # $formatter->send_page(); $formatter->send_footer("", $options); }