function diff_compute($text1, $text2) { $text1 = explode("\n", "\n" . $text1); $text2 = explode("\n", "\n" . $text2); $diff = new Diff($text1, $text2); $formatter = new UnifiedDiffFormatter(); return $formatter->format($diff); }
public function test1() { $x1 = "din hatt har en kant\nDin med!\n"; $x2 = "min hatt har en kant\nDin med!\n"; $df = new Diff($x1, $x2); //$form = new TableDiffFormatter(); $form = new UnifiedDiffFormatter(); $expected = "@@ -1,3 +1,3 @@\n" . "- din hatt har en kant\n" . "+ min hatt har en kant\n" . " Din med!\n" . " \n"; $this->assertEquals($expected, $form->format($df)); }
protected function showDiff($str1, $str2) { $diff = new Diff(explode("\n", $str1), explode("\n", $str2)); if ($diff->isEmpty()) { $this->fail("No difference ???"); } else { $fmt = new UnifiedDiffFormatter(); $this->fail($fmt->format($diff)); } }
function paintDiff($stringA, $stringB) { $diff = new Diff(explode("\n", $stringA), explode("\n", $stringB)); if ($diff->isEmpty()) { $this->_response->addContent('<p>Erreur diff : bizarre, aucune différence d\'aprés la difflib...</p>'); } else { $fmt = new UnifiedDiffFormatter(); $this->_response->addContent($fmt->format($diff)); } }
function git_diff($proj, $from, $from_name, $to, $to_name) { $fromdata = $from ? $proj->GetObject($from)->data : ""; $todata = $to ? $proj->GetObject($to)->data : ""; $fromdata = str_replace("\r\n", "\n", $fromdata); $todata = str_replace("\r\n", "\n", $todata); $diff = new Diff(explode("\n", $fromdata), explode("\n", $todata)); $diffFormatter = new UnifiedDiffFormatter(); $diffFormatter->leading_context_lines = 3; $diffFormatter->trailing_context_lines = 3; $out = "--- {$from_name}\n+++ {$to_name}\n" . $diffFormatter->format($diff); return $out; }
/** * Generates a diff txt * @param Title $title * @return string */ function generateDiffBodyTxt( $title ) { $revision = Revision::newFromTitle( $title, 0 ); $diff = new DifferenceEngine( $title, $revision->getId(), 'prev' ); // The getDiffBody() method generates html, so let's generate the txt diff manualy: global $wgContLang; $diff->loadText(); $otext = str_replace( "\r\n", "\n", $diff->mOldtext ); $ntext = str_replace( "\r\n", "\n", $diff->mNewtext ); $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) ); $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) ); // We use here the php diff engine included in MediaWiki $diffs = new Diff( $ota, $nta ); // And we ask for a txt formatted diff $formatter = new UnifiedDiffFormatter(); $diff_text = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ); return $diff_text; }
/** * Send udiff for a changed page to multiple users. * See rename and remove methods also */ function sendPageChangeNotification(&$wikitext, $version, &$meta) { global $request; if (@is_array($request->_deferredPageChangeNotification)) { // collapse multiple changes (loaddir) into one email $request->_deferredPageChangeNotification[] = array($this->pagename, $this->emails, $this->userids); return; } $backend =& $request->_dbi->_backend; $subject = _("Page change") . ' ' . $this->pagename; $previous = $backend->get_previous_version($this->pagename, $version); if (!isset($meta['mtime'])) { $meta['mtime'] = time(); } if ($previous) { $difflink = WikiURL($this->pagename, array('action' => 'diff'), true); $cache =& $request->_dbi->_cache; $this_content = explode("\n", $wikitext); $prevdata = $cache->get_versiondata($this->pagename, $previous, true); if (empty($prevdata['%content'])) { $prevdata = $backend->get_versiondata($this->pagename, $previous, true); } $other_content = explode("\n", $prevdata['%content']); include_once "lib/difflib.php"; $diff2 = new Diff($other_content, $this_content); //$context_lines = max(4, count($other_content) + 1, // count($this_content) + 1); $fmt = new UnifiedDiffFormatter(); $content = $this->pagename . " " . $previous . " " . Iso8601DateTime($prevdata['mtime']) . "\n"; $content .= $this->pagename . " " . $version . " " . Iso8601DateTime($meta['mtime']) . "\n"; $content .= $fmt->format($diff2); } else { $difflink = WikiURL($this->pagename, array(), true); $content = $this->pagename . " " . $version . " " . Iso8601DateTime($meta['mtime']) . "\n"; $content .= _("New page"); $content .= "\n\n"; $content .= $wikitext; } $editedby = sprintf(_("Edited by: %s"), $this->from); $summary = sprintf(_("Summary: %s"), $meta['summary']); $this->sendMail($subject, $editedby . "\n" . $summary . "\n" . $difflink . "\n\n" . $content); }
/** * Send udiff for a changed page to multiple users. * See rename and remove methods also */ function sendPageChangeNotification(&$wikitext, $version, $meta, $emails, $userids) { global $request; if (@is_array($request->_deferredPageChangeNotification)) { // collapse multiple changes (loaddir) into one email $request->_deferredPageChangeNotification[] = array($this->_pagename, $emails, $userids); return; } $backend =& $this->_wikidb->_backend; //$backend = &$request->_dbi->_backend; $subject = _("Page change") . ' ' . $this->_pagename; $previous = $backend->get_previous_version($this->_pagename, $version); if (!isset($meta['mtime'])) { $meta['mtime'] = time(); } if ($previous) { $difflink = WikiURL($this->_pagename, array('action' => 'diff'), true); $difflink .= "&versions%5b%5d=" . $previous . "&versions%5b%5d=" . $version; $cache =& $this->_wikidb->_cache; //$cache = &$request->_dbi->_cache; $this_content = explode("\n", $wikitext); $prevdata = $cache->get_versiondata($this->_pagename, $previous, true); if (empty($prevdata['%content'])) { $prevdata = $backend->get_versiondata($this->_pagename, $previous, true); } $other_content = explode("\n", $prevdata['%content']); include_once "lib/difflib.php"; $diff2 = new Diff($other_content, $this_content); //$context_lines = max(4, count($other_content) + 1, // count($this_content) + 1); $fmt = new UnifiedDiffFormatter(); $content = $this->_pagename . " " . $previous . " " . Iso8601DateTime($prevdata['mtime']) . "\n"; $content .= $this->_pagename . " " . $version . " " . Iso8601DateTime($meta['mtime']) . "\n"; $content .= $fmt->format($diff2); } else { $difflink = WikiURL($this->_pagename, array(), true); $content = $this->_pagename . " " . $version . " " . Iso8601DateTime($meta['mtime']) . "\n"; $content .= _("New page"); } // Codendi specific $from = user_getemail(user_getid()); $body = $subject . "\n" . sprintf(_("Edited by: %s"), $from) . "\n" . $difflink; $m = new Mail(); $m->setFrom($from); $m->setSubject("[" . WIKI_NAME . "] " . $subject); $m->setBcc(join(',', $emails)); $m->setBody($body); if ($m->send()) { trigger_error(sprintf(_("PageChange Notification of %s sent to %s"), $this->_pagename, join(',', $userids)), E_USER_NOTICE); } else { trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"), $this->_pagename, join(',', $userids)), E_USER_WARNING); } }
/** * Send udiff for a changed page to multiple users. * See rename and remove methods also */ function sendPageChangeNotification(&$wikitext, $version, $meta, $emails, $userids) { global $request; if (@is_array($request->_deferredPageChangeNotification)) { // collapse multiple changes (loaddir) into one email $request->_deferredPageChangeNotification[] = array($this->_pagename, $emails, $userids); return; } $backend =& $this->_wikidb->_backend; //$backend = &$request->_dbi->_backend; $subject = _("Page change") . ' ' . urlencode($this->_pagename); $previous = $backend->get_previous_version($this->_pagename, $version); if (!isset($meta['mtime'])) { $meta['mtime'] = time(); } if ($previous) { $difflink = WikiURL($this->_pagename, array('action' => 'diff'), true); $cache =& $this->_wikidb->_cache; //$cache = &$request->_dbi->_cache; $this_content = explode("\n", $wikitext); $prevdata = $cache->get_versiondata($this->_pagename, $previous, true); if (empty($prevdata['%content'])) { $prevdata = $backend->get_versiondata($this->_pagename, $previous, true); } $other_content = explode("\n", $prevdata['%content']); include_once "lib/difflib.php"; $diff2 = new Diff($other_content, $this_content); //$context_lines = max(4, count($other_content) + 1, // count($this_content) + 1); $fmt = new UnifiedDiffFormatter(); $content = $this->_pagename . " " . $previous . " " . Iso8601DateTime($prevdata['mtime']) . "\n"; $content .= $this->_pagename . " " . $version . " " . Iso8601DateTime($meta['mtime']) . "\n"; $content .= $fmt->format($diff2); } else { $difflink = WikiURL($this->_pagename, array(), true); $content = $this->_pagename . " " . $version . " " . Iso8601DateTime($meta['mtime']) . "\n"; $content .= _("New page"); } $from = $request->_user->getId(); $editedby = sprintf(_("Edited by: %s"), $from); $emails = join(',', $emails); $headers = "From: {$from} <nobody>\r\n" . "Bcc: {$emails}\r\n" . "MIME-Version: 1.0\r\n" . "Content-Type: text/plain; charset=" . CHARSET . "; format=flowed\r\n" . "Content-Transfer-Encoding: 8bit"; if (mail("<undisclosed-recipients>", "[" . WIKI_NAME . "] " . $subject, $subject . "\n" . $editedby . "\n" . $difflink . "\n\n" . $content, $headers)) { trigger_error(sprintf(_("PageChange Notification of %s sent to %s"), $this->_pagename, join(',', $userids)), E_USER_NOTICE); } else { trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"), $this->_pagename, join(',', $userids)), E_USER_WARNING); } }
/** * Send the diff for some page change * * @param string $subscriber_mail The target mail address * @param string $template Mail template ('subscr_digest', 'subscr_single', 'mailtext', ...) * @param string $id Page for which the notification is * @param int|null $rev Old revision if any * @param string $summary Change summary if any * @return bool true if successfully sent */ public function send_diff($subscriber_mail, $template, $id, $rev = null, $summary = '') { global $DIFF_INLINESTYLES; // prepare replacements (keys not set in hrep will be taken from trep) $trep = array('PAGE' => $id, 'NEWPAGE' => wl($id, '', true, '&'), 'SUMMARY' => $summary, 'SUBSCRIBE' => wl($id, array('do' => 'subscribe'), true, '&')); $hrep = array(); if ($rev) { $subject = 'changed'; $trep['OLDPAGE'] = wl($id, "rev={$rev}", true, '&'); $old_content = rawWiki($id, $rev); $new_content = rawWiki($id); $df = new Diff(explode("\n", $old_content), explode("\n", $new_content)); $dformat = new UnifiedDiffFormatter(); $tdiff = $dformat->format($df); $DIFF_INLINESTYLES = true; $df = new Diff(explode("\n", $old_content), explode("\n", $new_content)); $dformat = new InlineDiffFormatter(); $hdiff = $dformat->format($df); $hdiff = '<table>' . $hdiff . '</table>'; $DIFF_INLINESTYLES = false; } else { $subject = 'newpage'; $trep['OLDPAGE'] = '---'; $tdiff = rawWiki($id); $hdiff = nl2br(hsc($tdiff)); } $trep['DIFF'] = $tdiff; $hrep['DIFF'] = $hdiff; $headers = array('Message-Id' => $this->getMessageID($id)); if ($rev) { $headers['In-Reply-To'] = $this->getMessageID($id, $rev); } return $this->send($subscriber_mail, $subject, $id, $template, $trep, $hrep, $headers); }
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; }
/** * Sends a notify mail on page change * * @param string $id The changed page * @param string $who Who to notify (admin|subscribers) * @param int $rev Old page revision * @param string $summary What changed * @param boolean $minor Is this a minor edit? * @param array $replace Additional string substitutions, @KEY@ to be replaced by value * * @author Andreas Gohr <*****@*****.**> */ function notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) { global $lang; global $conf; // decide if there is something to do if ($who == 'admin') { if (empty($conf['notify'])) { return; } //notify enabled? $text = rawLocale('mailtext'); $to = $conf['notify']; $bcc = ''; } elseif ($who == 'subscribers') { if (!$conf['subscribers']) { return; } //subscribers enabled? if ($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) { return; } //skip minors $bcc = subscriber_addresslist($id); if (empty($bcc)) { return; } $to = ''; $text = rawLocale('subscribermail'); } elseif ($who == 'register') { if (empty($conf['registernotify'])) { return; } $text = rawLocale('registermail'); $to = $conf['registernotify']; $bcc = ''; } else { return; //just to be safe } $text = str_replace('@DATE@', date($conf['dformat']), $text); $text = str_replace('@BROWSER@', $_SERVER['HTTP_USER_AGENT'], $text); $text = str_replace('@IPADDRESS@', $_SERVER['REMOTE_ADDR'], $text); $text = str_replace('@HOSTNAME@', gethostbyaddr($_SERVER['REMOTE_ADDR']), $text); $text = str_replace('@NEWPAGE@', wl($id, '', true), $text); $text = str_replace('@PAGE@', $id, $text); $text = str_replace('@TITLE@', $conf['title'], $text); $text = str_replace('@DOKUWIKIURL@', DOKU_URL, $text); $text = str_replace('@SUMMARY@', $summary, $text); $text = str_replace('@USER@', $_SERVER['REMOTE_USER'], $text); foreach ($replace as $key => $substitution) { $text = str_replace('@' . strtoupper($key) . '@', $substitution, $text); } if ($who == 'register') { $subject = $lang['mail_new_user'] . ' ' . $summary; } elseif ($rev) { $subject = $lang['mail_changed'] . ' ' . $id; $text = str_replace('@OLDPAGE@', wl($id, "rev={$rev}", true), $text); require_once DOKU_INC . 'inc/DifferenceEngine.php'; $df = new Diff(split("\n", rawWiki($id, $rev)), split("\n", rawWiki($id))); $dformat = new UnifiedDiffFormatter(); $diff = $dformat->format($df); } else { $subject = $lang['mail_newpage'] . ' ' . $id; $text = str_replace('@OLDPAGE@', 'none', $text); $diff = rawWiki($id); } $text = str_replace('@DIFF@', $diff, $text); $subject = '[' . $conf['title'] . '] ' . $subject; mail_send($to, $subject, $text, $conf['mailfrom'], '', $bcc); }
/** * Add recent changed pages to a feed object * * @author Andreas Gohr <*****@*****.**> * @param FeedCreator $rss the FeedCreator Object * @param array $data the items to add * @param array $opt the feed options */ function rss_buildItems(&$rss, &$data, $opt) { global $conf; global $lang; /* @var auth_basic $auth */ global $auth; $eventData = array('rss' => &$rss, 'data' => &$data, 'opt' => &$opt); $event = new Doku_Event('FEED_DATA_PROCESS', $eventData); if ($event->advise_before(false)) { foreach ($data as $ditem) { if (!is_array($ditem)) { // not an array? then only a list of IDs was given $ditem = array('id' => $ditem); } $item = new FeedItem(); $id = $ditem['id']; if (!$ditem['media']) { $meta = p_get_metadata($id); } else { $meta = array(); } // add date if ($ditem['date']) { $date = $ditem['date']; } elseif ($ditem['media']) { $date = @filemtime(mediaFN($id)); } elseif (@file_exists(wikiFN($id))) { $date = @filemtime(wikiFN($id)); } elseif ($meta['date']['modified']) { $date = $meta['date']['modified']; } else { $date = 0; } if ($date) { $item->date = date('r', $date); } // add title if ($conf['useheading'] && $meta['title']) { $item->title = $meta['title']; } else { $item->title = $ditem['id']; } if ($conf['rss_show_summary'] && !empty($ditem['sum'])) { $item->title .= ' - ' . strip_tags($ditem['sum']); } // add item link switch ($opt['link_to']) { case 'page': if ($ditem['media']) { $item->link = media_managerURL(array('image' => $id, 'ns' => getNS($id), 'rev' => $date), '&', true); } else { $item->link = wl($id, 'rev=' . $date, true, '&'); } break; case 'rev': if ($ditem['media']) { $item->link = media_managerURL(array('image' => $id, 'ns' => getNS($id), 'rev' => $date, 'tab_details' => 'history'), '&', true); } else { $item->link = wl($id, 'do=revisions&rev=' . $date, true, '&'); } break; case 'current': if ($ditem['media']) { $item->link = media_managerURL(array('image' => $id, 'ns' => getNS($id)), '&', true); } else { $item->link = wl($id, '', true, '&'); } break; case 'diff': default: if ($ditem['media']) { $item->link = media_managerURL(array('image' => $id, 'ns' => getNS($id), 'rev' => $date, 'tab_details' => 'history', 'mediado' => 'diff'), '&', true); } else { $item->link = wl($id, 'rev=' . $date . '&do=diff', true, '&'); } } // add item content switch ($opt['item_content']) { case 'diff': case 'htmldiff': if ($ditem['media']) { $revs = getRevisions($id, 0, 1, 8192, true); $rev = $revs[0]; $src_r = ''; $src_l = ''; if ($size = media_image_preview_size($id, false, new JpegMeta(mediaFN($id)), 300)) { $more = 'w=' . $size[0] . '&h=' . $size[1] . 't=' . @filemtime(mediaFN($id)); $src_r = ml($id, $more); } if ($rev && ($size = media_image_preview_size($id, $rev, new JpegMeta(mediaFN($id, $rev)), 300))) { $more = 'rev=' . $rev . '&w=' . $size[0] . '&h=' . $size[1]; $src_l = ml($id, $more); } $content = ''; if ($src_r) { $content = '<table>'; $content .= '<tr><th width="50%">' . $rev . '</th>'; $content .= '<th width="50%">' . $lang['current'] . '</th></tr>'; $content .= '<tr align="center"><td><img src="' . $src_l . '" alt="" /></td><td>'; $content .= '<img src="' . $src_r . '" alt="' . $id . '" /></td></tr>'; $content .= '</table>'; } } else { require_once DOKU_INC . 'inc/DifferenceEngine.php'; $revs = getRevisions($id, 0, 1); $rev = $revs[0]; if ($rev) { $df = new Diff(explode("\n", rawWiki($id, $rev)), explode("\n", rawWiki($id, ''))); } else { $df = new Diff(array(''), explode("\n", rawWiki($id, ''))); } if ($opt['item_content'] == 'htmldiff') { // note: no need to escape diff output, TableDiffFormatter provides 'safe' html $tdf = new TableDiffFormatter(); $content = '<table>'; $content .= '<tr><th colspan="2" width="50%">' . $rev . '</th>'; $content .= '<th colspan="2" width="50%">' . $lang['current'] . '</th></tr>'; $content .= $tdf->format($df); $content .= '</table>'; } else { // note: diff output must be escaped, UnifiedDiffFormatter provides plain text $udf = new UnifiedDiffFormatter(); $content = "<pre>\n" . hsc($udf->format($df)) . "\n</pre>"; } } break; case 'html': if ($ditem['media']) { if ($size = media_image_preview_size($id, false, new JpegMeta(mediaFN($id)))) { $more = 'w=' . $size[0] . '&h=' . $size[1] . 't=' . @filemtime(mediaFN($id)); $src = ml($id, $more); $content = '<img src="' . $src . '" alt="' . $id . '" />'; } else { $content = ''; } } else { if (@filemtime(wikiFN($id)) === $date) { $content = p_wiki_xhtml($id, '', false); } else { $content = p_wiki_xhtml($id, $date, false); } // no TOC in feeds $content = preg_replace('/(<!-- TOC START -->).*(<!-- TOC END -->)/s', '', $content); // add alignment for images $content = preg_replace('/(<img .*?class="medialeft")/s', '\\1 align="left"', $content); $content = preg_replace('/(<img .*?class="mediaright")/s', '\\1 align="right"', $content); // make URLs work when canonical is not set, regexp instead of rerendering! if (!$conf['canonical']) { $base = preg_quote(DOKU_REL, '/'); $content = preg_replace('/(<a href|<img src)="(' . $base . ')/s', '$1="' . DOKU_URL, $content); } } break; case 'abstract': default: if ($ditem['media']) { if ($size = media_image_preview_size($id, false, new JpegMeta(mediaFN($id)))) { $more = 'w=' . $size[0] . '&h=' . $size[1] . 't=' . @filemtime(mediaFN($id)); $src = ml($id, $more); $content = '<img src="' . $src . '" alt="' . $id . '" />'; } else { $content = ''; } } else { $content = $meta['description']['abstract']; } } $item->description = $content; //FIXME a plugin hook here could be senseful // add user # FIXME should the user be pulled from metadata as well? $user = @$ditem['user']; // the @ spares time repeating lookup $item->author = ''; if ($user && $conf['useacl'] && $auth) { $userInfo = $auth->getUserData($user); if ($userInfo) { switch ($conf['showuseras']) { case 'username': $item->author = $userInfo['name']; break; default: $item->author = $user; break; } } else { $item->author = $user; } if ($userInfo && !$opt['guardmail']) { $item->authorEmail = $userInfo['mail']; } else { //cannot obfuscate because some RSS readers may check validity $item->authorEmail = $user . '@' . $ditem['ip']; } } elseif ($user) { // this happens when no ACL but some Apache auth is used $item->author = $user; $item->authorEmail = $user . '@' . $ditem['ip']; } else { $item->authorEmail = 'anonymous@' . $ditem['ip']; } // add category if (isset($meta['subject'])) { $item->category = $meta['subject']; } else { $cat = getNS($id); if ($cat) { $item->category = $cat; } } // finally add the item to the feed object, after handing it to registered plugins $evdata = array('item' => &$item, 'opt' => &$opt, 'ditem' => &$ditem, 'rss' => &$rss); $evt = new Doku_Event('FEED_ITEM_ADD', $evdata); if ($evt->advise_before()) { $rss->addItem($item); } $evt->advise_after(); // for completeness } } $event->advise_after(); }
function get_diff($text, $rev = '') { global $DBInfo; if (!isset($text[0])) { $text = "\n"; } if (!empty($DBInfo->use_external_diff)) { $tmpf2 = tempnam($DBInfo->vartmp_dir, 'DIFF_NEW'); $fp = fopen($tmpf2, 'w'); if (!is_resource($fp)) { return ''; } // ignore fwrite($fp, $text); fclose($fp); $fp = popen('diff -u ' . $this->page->filename . ' ' . $tmpf2 . $this->NULL, 'r'); if (!is_resource($fp)) { unlink($tmpf2); return ''; } $out = ''; while (!feof($fp)) { $line = fgets($fp, 1024); $out .= $line; } pclose($fp); unlink($tmpf2); } else { require_once 'lib/difflib.php'; $orig = $this->page->_get_raw_body(); $olines = explode("\n", $orig); $tmp = array_pop($olines); if ($tmp != '') { $olines[] = $tmp; } $nlines = explode("\n", $text); $tmp = array_pop($nlines); if ($tmp != '') { $nlines[] = $tmp; } $diff = new Diff($olines, $nlines); $unified = new UnifiedDiffFormatter(); $unified->trailing_cr = " \n"; // hack to see inserted empty lines $out .= $unified->format($diff); } return $out; }
function _approval_form(&$request, $args, $moderation, $pass = '******') { $header = HTML::h3(_("Please approve or reject this request:")); $loader = new WikiPluginLoader(); $BackendInfo = $loader->getPlugin("_BackendInfo"); $table = HTML::table(array('border' => 1, 'cellpadding' => 2, 'cellspacing' => 0)); $content = $table; $diff = ''; if ($moderation['args']['action'] == 'edit') { $pagename = $moderation['args']['pagename']; $p = $request->_dbi->getPage($pagename); $rev = $p->getCurrentRevision(true); $curr_content = $rev->getPackedContent(); $new_content = $moderation['args']['edit']['content']; include_once "lib/difflib.php"; $diff2 = new Diff($curr_content, $new_content); $fmt = new UnifiedDiffFormatter(); $diff = $pagename . " Current Version " . Iso8601DateTime($p->get('mtime')) . "\n"; $diff .= $pagename . " Edited Version " . Iso8601DateTime($moderation['timestamp']) . "\n"; $diff .= $fmt->format($diff2); } $content->pushContent($BackendInfo->_showhash("Request", array('User' => $moderation['userid'], 'When' => CTime($moderation['timestamp']), 'Pagename' => $pagename, 'Action' => $moderation['args']['action'], 'Diff' => HTML::pre($diff)))); $content_dbg = $table; $myargs = $args; $BackendInfo->_fixupData($myargs); $content_dbg->pushContent($BackendInfo->_showhash("raw request args", $myargs)); $BackendInfo->_fixupData($moderation); $content_dbg->pushContent($BackendInfo->_showhash("raw moderation data", $moderation)); $reason = HTML::div(_("Reason: "), HTML::textarea(array('name' => 'reason'))); $approve = Button('submit:ModeratedPage[approve]', _("Approve"), $pass == 'approve' ? 'wikiadmin' : 'button'); $reject = Button('submit:ModeratedPage[reject]', _("Reject"), $pass == 'reject' ? 'wikiadmin' : 'button'); $args['action'] = _("ModeratedPage"); return HTML::form(array('action' => $request->getPostURL(), 'method' => 'post'), $header, $content, HTML::p(""), $content_dbg, $reason, ENABLE_PAGEPERM ? '' : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN)), HiddenInputs($args), $pass == 'approve' ? HTML::p($approve, $reject) : HTML::p($reject, $approve)); }
/** * Send a digest mail * * Sends a digest mail showing a bunch of changes. * * @param string $subscriber_mail The target mail address * @param array $id The ID * @param int $lastupdate Time of the last notification * * @author Adrian Lang <*****@*****.**> */ function subscription_send_digest($subscriber_mail, $id, $lastupdate) { $n = 0; do { $rev = getRevisions($id, $n++, 1); $rev = count($rev) > 0 ? $rev[0] : null; } while (!is_null($rev) && $rev > $lastupdate); $replaces = array('NEWPAGE' => wl($id, '', true, '&'), 'SUBSCRIBE' => wl($id, array('do' => 'subscribe'), true, '&')); if (!is_null($rev)) { $subject = 'changed'; $replaces['OLDPAGE'] = wl($id, "rev={$rev}", true, '&'); $df = new Diff(explode("\n", rawWiki($id, $rev)), explode("\n", rawWiki($id))); $dformat = new UnifiedDiffFormatter(); $replaces['DIFF'] = $dformat->format($df); } else { $subject = 'newpage'; $replaces['OLDPAGE'] = 'none'; $replaces['DIFF'] = rawWiki($id); } subscription_send($subscriber_mail, $replaces, $subject, $id, 'subscr_digest'); }
/** * Add recent changed pages to a feed object * * @author Andreas Gohr <*****@*****.**> * @param object $rss - the FeedCreator Object * @param array $data - the items to add * @param array $opt - the feed options */ function rss_buildItems(&$rss, &$data, $opt) { global $conf; global $lang; global $auth; $eventData = array('rss' => &$rss, 'data' => &$data, 'opt' => &$opt); $event = new Doku_Event('FEED_DATA_PROCESS', $eventData); if ($event->advise_before(false)) { foreach ($data as $ditem) { if (!is_array($ditem)) { // not an array? then only a list of IDs was given $ditem = array('id' => $ditem); } $item = new FeedItem(); $id = $ditem['id']; $meta = p_get_metadata($id); // add date if ($ditem['date']) { $date = $ditem['date']; } elseif ($meta['date']['modified']) { $date = $meta['date']['modified']; } else { $date = @filemtime(wikiFN($id)); } if ($date) { $item->date = date('r', $date); } // add title if ($conf['useheading'] && $meta['title']) { $item->title = $meta['title']; } else { $item->title = $ditem['id']; } if ($conf['rss_show_summary'] && !empty($ditem['sum'])) { $item->title .= ' - ' . strip_tags($ditem['sum']); } // add item link switch ($opt['link_to']) { case 'page': $item->link = wl($id, 'rev=' . $date, true, '&'); break; case 'rev': $item->link = wl($id, 'do=revisions&rev=' . $date, true, '&'); break; case 'current': $item->link = wl($id, '', true, '&'); break; case 'diff': default: $item->link = wl($id, 'rev=' . $date . '&do=diff', true, '&'); } // add item content switch ($opt['item_content']) { case 'diff': case 'htmldiff': require_once DOKU_INC . 'inc/DifferenceEngine.php'; $revs = getRevisions($id, 0, 1); $rev = $revs[0]; if ($rev) { $df = new Diff(explode("\n", htmlspecialchars(rawWiki($id, $rev))), explode("\n", htmlspecialchars(rawWiki($id, '')))); } else { $df = new Diff(array(''), explode("\n", htmlspecialchars(rawWiki($id, '')))); } if ($opt['item_content'] == 'htmldiff') { $tdf = new TableDiffFormatter(); $content = '<table>'; $content .= '<tr><th colspan="2" width="50%">' . $rev . '</th>'; $content .= '<th colspan="2" width="50%">' . $lang['current'] . '</th></tr>'; $content .= $tdf->format($df); $content .= '</table>'; } else { $udf = new UnifiedDiffFormatter(); $content = "<pre>\n" . $udf->format($df) . "\n</pre>"; } break; case 'html': $content = p_wiki_xhtml($id, $date, false); // no TOC in feeds $content = preg_replace('/(<!-- TOC START -->).*(<!-- TOC END -->)/s', '', $content); // make URLs work when canonical is not set, regexp instead of rerendering! if (!$conf['canonical']) { $base = preg_quote(DOKU_REL, '/'); $content = preg_replace('/(<a href|<img src)="(' . $base . ')/s', '$1="' . DOKU_URL, $content); } break; case 'abstract': default: $content = $meta['description']['abstract']; } $item->description = $content; //FIXME a plugin hook here could be senseful // add user # FIXME should the user be pulled from metadata as well? $user = null; $user = @$ditem['user']; // the @ spares time repeating lookup $item->author = ''; if ($user && $conf['useacl'] && $auth) { $userInfo = $auth->getUserData($user); $item->author = $userInfo['name']; if ($userInfo && !$opt['guardmail']) { $item->authorEmail = $userInfo['mail']; } else { //cannot obfuscate because some RSS readers may check validity $item->authorEmail = $user . '@' . $ditem['ip']; } } elseif ($user) { // this happens when no ACL but some Apache auth is used $item->author = $user; $item->authorEmail = $user . '@' . $ditem['ip']; } else { $item->authorEmail = 'anonymous@' . $ditem['ip']; } // add category if ($meta['subject']) { $item->category = $meta['subject']; } else { $cat = getNS($id); if ($cat) { $item->category = $cat; } } // finally add the item to the feed object, after handing it to registered plugins $evdata = array('item' => &$item, 'opt' => &$opt, 'ditem' => &$ditem, 'rss' => &$rss); $evt = new Doku_Event('FEED_ITEM_ADD', $evdata); if ($evt->advise_before()) { $rss->addItem($item); } $evt->advise_after(); // for completeness } } $event->advise_after(); }
/** * show diff * * @author Matt Pascoe <*****@*****.**> * Requires DifferenceEngine.php from dokuwiki. * * Input: two strings * Output: unified text diff */ function text_diff($old, $new) { global $conf; $html = ''; if (!($old and $new)) { return 'ERROR => Insufficient parameters passed to text_diff()!'; } // Load diff code require_once $conf['inc_diff']; $df = new Diff(explode("\n", $old), explode("\n", $new)); $tdf = new UnifiedDiffFormatter(); $text .= $tdf->format($df); return $text; }
/** * Sends a notify mail on page change or registration * * @param string $id The changed page * @param string $who Who to notify (admin|subscribers|register) * @param int|string $rev Old page revision * @param string $summary What changed * @param boolean $minor Is this a minor edit? * @param array $replace Additional string substitutions, @KEY@ to be replaced by value * * @return bool * @author Andreas Gohr <*****@*****.**> */ function notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) { global $lang; global $conf; global $INFO; global $DIFF_INLINESTYLES; // decide if there is something to do, eg. whom to mail if ($who == 'admin') { if (empty($conf['notify'])) { return false; } //notify enabled? $text = rawLocale('mailtext'); $to = $conf['notify']; $bcc = ''; } elseif ($who == 'subscribers') { if (!$conf['subscribers']) { return false; } //subscribers enabled? if ($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) { return false; } //skip minors $data = array('id' => $id, 'addresslist' => '', 'self' => false); trigger_event('COMMON_NOTIFY_ADDRESSLIST', $data, 'subscription_addresslist'); $bcc = $data['addresslist']; if (empty($bcc)) { return false; } $to = ''; $text = rawLocale('subscr_single'); } elseif ($who == 'register') { if (empty($conf['registernotify'])) { return false; } $text = rawLocale('registermail'); $to = $conf['registernotify']; $bcc = ''; } else { return false; //just to be safe } // prepare replacements (keys not set in hrep will be taken from trep) $trep = array('NEWPAGE' => wl($id, '', true, '&'), 'PAGE' => $id, 'SUMMARY' => $summary); $trep = array_merge($trep, $replace); $hrep = array(); // prepare content if ($who == 'register') { $subject = $lang['mail_new_user'] . ' ' . $summary; } elseif ($rev) { $subject = $lang['mail_changed'] . ' ' . $id; $trep['OLDPAGE'] = wl($id, "rev={$rev}", true, '&'); $df = new Diff(explode("\n", rawWiki($id, $rev)), explode("\n", rawWiki($id))); $dformat = new UnifiedDiffFormatter(); $tdiff = $dformat->format($df); $DIFF_INLINESTYLES = true; $dformat = new InlineDiffFormatter(); $hdiff = $dformat->format($df); $hdiff = '<table>' . $hdiff . '</table>'; $DIFF_INLINESTYLES = false; } else { $subject = $lang['mail_newpage'] . ' ' . $id; $trep['OLDPAGE'] = '---'; $tdiff = rawWiki($id); $hdiff = nl2br(hsc($tdiff)); } $trep['DIFF'] = $tdiff; $hrep['DIFF'] = $hdiff; // send mail $mail = new Mailer(); $mail->to($to); $mail->bcc($bcc); $mail->subject($subject); $mail->setBody($text, $trep, $hrep); if ($who == 'subscribers') { $mail->setHeader('List-Unsubscribe', '<' . wl($id, array('do' => 'subscribe'), true, '&') . '>', false); } return $mail->send(); }
/** * Sends a notify mail on page change or registration * * @param string $id The changed page * @param string $who Who to notify (admin|subscribers|register) * @param int $rev Old page revision * @param string $summary What changed * @param boolean $minor Is this a minor edit? * @param array $replace Additional string substitutions, @KEY@ to be replaced by value * * @author Andreas Gohr <*****@*****.**> */ function notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) { global $lang; global $conf; global $INFO; // decide if there is something to do if ($who == 'admin') { if (empty($conf['notify'])) { return; } //notify enabled? $text = rawLocale('mailtext'); $to = $conf['notify']; $bcc = ''; } elseif ($who == 'subscribers') { if (!$conf['subscribers']) { return; } //subscribers enabled? if ($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) { return; } //skip minors $data = array('id' => $id, 'addresslist' => '', 'self' => false); trigger_event('COMMON_NOTIFY_ADDRESSLIST', $data, 'subscription_addresslist'); $bcc = $data['addresslist']; if (empty($bcc)) { return; } $to = ''; $text = rawLocale('subscr_single'); } elseif ($who == 'register') { if (empty($conf['registernotify'])) { return; } $text = rawLocale('registermail'); $to = $conf['registernotify']; $bcc = ''; } else { return; //just to be safe } $ip = clientIP(); $text = str_replace('@DATE@', dformat(), $text); $text = str_replace('@BROWSER@', $_SERVER['HTTP_USER_AGENT'], $text); $text = str_replace('@IPADDRESS@', $ip, $text); $text = str_replace('@HOSTNAME@', gethostsbyaddrs($ip), $text); $text = str_replace('@NEWPAGE@', wl($id, '', true, '&'), $text); $text = str_replace('@PAGE@', $id, $text); $text = str_replace('@TITLE@', $conf['title'], $text); $text = str_replace('@DOKUWIKIURL@', DOKU_URL, $text); $text = str_replace('@SUMMARY@', $summary, $text); $text = str_replace('@USER@', $_SERVER['REMOTE_USER'], $text); $text = str_replace('@NAME@', $INFO['userinfo']['name'], $text); $text = str_replace('@MAIL@', $INFO['userinfo']['mail'], $text); foreach ($replace as $key => $substitution) { $text = str_replace('@' . strtoupper($key) . '@', $substitution, $text); } if ($who == 'register') { $subject = $lang['mail_new_user'] . ' ' . $summary; } elseif ($rev) { $subject = $lang['mail_changed'] . ' ' . $id; $text = str_replace('@OLDPAGE@', wl($id, "rev={$rev}", true, '&'), $text); $df = new Diff(explode("\n", rawWiki($id, $rev)), explode("\n", rawWiki($id))); $dformat = new UnifiedDiffFormatter(); $diff = $dformat->format($df); } else { $subject = $lang['mail_newpage'] . ' ' . $id; $text = str_replace('@OLDPAGE@', 'none', $text); $diff = rawWiki($id); } $text = str_replace('@DIFF@', $diff, $text); if (utf8_strlen($conf['title']) < 20) { $subject = '[' . $conf['title'] . '] ' . $subject; } else { $subject = '[' . utf8_substr($conf['title'], 0, 20) . '...] ' . $subject; } mail_send($to, $subject, $text, $conf['mailfrom'], '', $bcc); }
function __construct($context_lines = 4) { parent::__construct($context_lines); }
function paintDiff($stringA, $stringB) { $diff = new Diff(explode("\n", $stringA), explode("\n", $stringB)); if ($diff->isEmpty()) { $this->_response->content .= '<p>Diff Error : weird, no difference said difflib...</p>'; } else { $fmt = new UnifiedDiffFormatter(); $this->_response->content .= $fmt->format($diff); } }
/** * Returns unified plain-text diff of two texts. * "Useful" for machine processing of diffs. * * @deprecated since 1.25, use DiffEngine/UnifiedDiffFormatter directly * * @param string $before The text before the changes. * @param string $after The text after the changes. * @param string $params Command-line options for the diff command. * @return string Unified diff of $before and $after */ function wfDiff($before, $after, $params = '-u') { if ($before == $after) { return ''; } global $wgDiff; MediaWiki\suppressWarnings(); $haveDiff = $wgDiff && file_exists($wgDiff); MediaWiki\restoreWarnings(); # This check may also protect against code injection in # case of broken installations. if (!$haveDiff) { wfDebug("diff executable not found\n"); $diffs = new Diff(explode("\n", $before), explode("\n", $after)); $format = new UnifiedDiffFormatter(); return $format->format($diffs); } # Make temporary files $td = wfTempDir(); $oldtextFile = fopen($oldtextName = tempnam($td, 'merge-old-'), 'w'); $newtextFile = fopen($newtextName = tempnam($td, 'merge-your-'), 'w'); fwrite($oldtextFile, $before); fclose($oldtextFile); fwrite($newtextFile, $after); fclose($newtextFile); // Get the diff of the two files $cmd = "{$wgDiff} " . $params . ' ' . wfEscapeShellArg($oldtextName, $newtextName); $h = popen($cmd, 'r'); if (!$h) { unlink($oldtextName); unlink($newtextName); throw new Exception(__METHOD__ . '(): popen() failed'); } $diff = ''; do { $data = fread($h, 8192); if (strlen($data) == 0) { break; } $diff .= $data; } while (true); // Clean up pclose($h); unlink($oldtextName); unlink($newtextName); // Kill the --- and +++ lines. They're not useful. $diff_lines = explode("\n", $diff); if (isset($diff_lines[0]) && strpos($diff_lines[0], '---') === 0) { unset($diff_lines[0]); } if (isset($diff_lines[1]) && strpos($diff_lines[1], '+++') === 0) { unset($diff_lines[1]); } $diff = implode("\n", $diff_lines); return $diff; }
function get_diff($old, $new, $params = array()) { include_once dirname(__FILE__) . "/../lib/difflib.php"; $olines = explode("\n", $old); $tmp = array_pop($olines); if ($tmp != '') { $olines[] = $tmp; } $nlines = explode("\n", $new); $tmp = array_pop($nlines); if ($tmp != '') { $nlines[] = $tmp; } $diff = new Diff($olines, $nlines); $unified = new UnifiedDiffFormatter(); //$unified->trailing_cr = " \n"; // hack to see inserted empty lines $unified->trailing_cr = "\n"; // hack to see inserted empty lines return $unified->format($diff); }