Ejemplo n.º 1
0
function ewiki_auth_userdb_xprofile($username, $password)
{
    global $ewiki_author;
    #-- already logged in
    if ($_SESSION["xprofile"]) {
        $ewiki_author = $_SESSION["ewiki_author"];
        return $true;
    }
    #-- fetch profile
    $xpro = new xprofile($username);
    // URL or email-like shortcut
    if ($xpro->control) {
        #-- validate
        if ($xpro->login()) {
            #-- save data
            $_SESSION["ewiki_author"] = $ewiki_author = $xpro->info["nickname"];
            $_SESSION["xprofile"] = $xpro->url;
            return true;
        } else {
            // misuse (already logged by XProfile manager)
            ewiki_log("userdb_xprofile: wrong password '...' for remote account on '{$username}'", 1);
        }
    }
    return false;
}
Ejemplo n.º 2
0
function ewiki_trigger_spam_watchonly($id, &$data, &$action, $pf_i)
{
    #-- fetch list of tracked pages
    if ($d = ewiki_db::GET("WatchSpam")) {
        (array) ($ewiki_config["watchspam"] += explode("\n", trim($d["refs"])));
    }
    #-- disable all bot-blocking plugins?
    if (!ewiki_in_array($id, $ewiki_config["watchspam"])) {
        $GLOBALS["ewiki_no_bot"] = 1;
    } elseif ($action == "edit") {
        ewiki_log("someone is {$action}ing specifically watched page '{$id}'", 2);
    }
}
Ejemplo n.º 3
0
function ewiki_edit_patch($id, &$data)
{
    $r = false;
    $base = ewiki_database("GET", array("id" => $id, "version" => $_REQUEST["version"]));
    if (!$base) {
        return false;
    }
    $fn_base = EWIKI_TMP . "/ewiki.base." . md5($base["content"]);
    $fn_requ = EWIKI_TMP . "/ewiki..requ." . md5($_REQUEST["content"]);
    $fn_patch = EWIKI_TMP . "/ewiki.patch." . md5($base["content"]) . "-" . md5($_REQUEST["content"]);
    $fn_curr = EWIKI_TMP . "/ewiki.curr." . md5($data["content"]);
    if ($f = fopen($fn_base, "w")) {
        fwrite($f, $base["content"]);
        fclose($f);
    } else {
        return false;
    }
    if ($f = fopen($fn_requ, "w")) {
        fwrite($f, $_REQUEST["content"]);
        fclose($f);
    } else {
        unlink($fn_base);
        return false;
    }
    if ($f = fopen($fn_curr, "w")) {
        fwrite($f, $data["content"]);
        fclose($f);
    } else {
        unlink($fn_base);
        unlink($fn_requ);
        return false;
    }
    exec("diff -c {$fn_base} {$fn_requ} > {$fn_patch}", $output, $retval);
    if ($retval) {
        exec("patch {$fn_curr} {$fn_patch}", $output, $retval);
        if (!$retval) {
            $_REQUEST["version"] = $curr["version"];
            $_REQUEST["content"] = implode("", file($fn_curr));
            $r = true;
        }
    }
    unlink($fn_base);
    unlink($fn_requ);
    unlink($fn_patch);
    unlink($fn_curr);
    ewiki_log("patchsaving of {$id}[{$data[version]}] was " . ($r ? "" : "un") . "successful", 2);
    return $r;
}
Ejemplo n.º 4
0
function ewiki_action_image_append($id, $data, $action)
{
    #-- invalid $id value
    if (empty($data) || !$data["version"] || EWIKI_DB_F_TEXT != ($data["flags"] & EWIKI_DB_F_TYPE)) {
        $o = ewiki_t("CANNOTCHANGEPAGE");
    } elseif ($fa = $_FILES["imagefile"]) {
        #-- guess HTTP meta data
        $meta = array("X-Content-Type" => $fa["type"]);
        if ($s = $fa["name"]) {
            $meta["Content-Location"] = $s;
            $p = 0 or $p = strrpos($s, "/") and $p++ or $p = strrpos($s, '\\') and $p++;
            $meta["Content-Disposition"] = 'inline; filename="' . urlencode(substr($s, $p)) . '"';
        }
        #-- proceed an image (reject binary, resize if too large)
        $result = ewiki_binary_save_image($fa["tmp_name"], "", "RETURN", $meta, 0, 1);
        #-- database rejected file
        if (!$result) {
            $o = ewiki_t("BIN_NOIMG");
        } else {
            $loop = 3;
            while ($loop--) {
                $data = ewiki_db::GET($id);
                $data["version"]++;
                $data["content"] = rtrim($data["content"], "\n") . "\n\n" . "[\"AppendedPicture\"{$result}]\n\n\n";
                $result = ewiki_db::WRITE($data);
                if ($result) {
                    break;
                }
            }
            if ($result) {
                $o = ewiki_page("view/{$id}");
                ewiki_log("image appended to '{$id}'");
            } else {
                $o .= ewiki_t("NO_IMAGEAPPEND");
            }
        }
    } else {
        $o .= ewiki_t("BIN_NOIMG");
        #"You did not select an image, or something went really wrong during tansmission. Plase go back to the previous page.";
    }
    return $o;
}
Ejemplo n.º 5
0
function ewiki_binary_store_file(&$filename, &$id, &$meta, $ext = ".bin")
{
    if ($meta["size"] >= EWIKI_DB_STORE_MINSIZE && $meta["size"] <= EWIKI_DB_STORE_MAXSIZE) {
        #-- generate internal://md5sum
        if (empty($id)) {
            $md5sum = md5_file($filename);
            $id = EWIKI_IDF_INTERNAL . $md5sum . ".{$ext}";
            ewiki_log("generated md5sum '{$md5sum}' from file content");
        }
        #-- move file to dest. location
        $dbfname = EWIKI_DB_STORE_DIRECTORY . "/" . rawurlencode($id);
        if (@rename($filename, $dbfname) || copy($filename, $dbfname) && unlink($filename)) {
            $filename = "";
            $meta["binary_store"] = 1;
            return true;
        } else {
            ewiki_log("file store error with '{$dbfname}'", 0);
        }
    }
    return false;
}
Ejemplo n.º 6
0
function ewiki_input_truncate()
{
    global $ewiki_input_limits, $ewiki_plugins;
    //get and trim current page id
    $id = substr(ewiki_id(), 0, $ewiki_input_limits['_AllPages']['id']);
    if ($delim = strpos($id, EWIKI_ACTION_SEP_CHAR)) {
        $action = substr($id, 0, $delim);
        $id = substr($id, $delim + 1);
    }
    foreach ($_REQUEST as $key => $value) {
        //loop through the $_REQUEST variable
        $input_value = trim($value);
        //trim value
        $ewiki_input_key = $key;
        $ewiki_input_id = ewiki_check_input($id, $ewiki_input_key, $action);
        if (!strlen($ewiki_input_id)) {
            $ewiki_input_key = ewiki_reset_key($id, $key);
            $ewiki_input_id = ewiki_check_input($id, $ewiki_input_key, $action);
        }
        if (!strlen($ewiki_input_id)) {
            ewiki_log('Unhandled submit: Page: "' . $id . '" Key: "' . $key . '" Value: "' . $value . '" \\n', 1);
            ewiki_set_globals($key);
        }
        if (is_array($input_value)) {
            //loop through the input array
            foreach ($input_value as $array_input_key => $array_input_value) {
                $input_value = trim($array_input_value);
                //redefine input_value with the array value
                //check to see if its longer than allowed
                if (strlen($input_value) > $ewiki_input_limits[$ewiki_input_id][$ewiki_input_key]) {
                    //its too long truncate it...
                    ewiki_set_globals($key, substr($input_value, 0, $ewiki_input_limits[$ewiki_input_id][$ewiki_input_key]), $array_input_key);
                }
            }
        } elseif (strlen($input_value) > $ewiki_input_limits[$ewiki_input_id][$ewiki_input_key] && isset($ewiki_input_limits[$ewiki_input_id][$ewiki_input_key])) {
            ewiki_log("Trimming: Key: {$ewiki_input_key} Id: {$ewiki_input_id} to length: " . $ewiki_input_limits[$ewiki_input_id][$ewiki_input_key]);
            ewiki_set_globals($key, substr($input_value, 0, $ewiki_input_limits[$ewiki_input_id][$ewiki_input_key]));
        }
    }
}
Ejemplo n.º 7
0
function ewiki_cache_generated_pages($id, &$data, $action)
{
    global $ewiki_plugins, $ewiki_ring;
    $o = ewiki_make_title($id, $id, 1);
    if (empty($_REQUEST["generate_cache"])) {
        $o .= "Use this page plugin/tool to generate text database entries for\nall generated ('internal' or 'static') pages available, so those can later\nbe found using the search functions.<br /><br />";
        $o .= '<form action="' . ewiki_script("", $id) . '" method="POST" enctype="text/html">' . '<input type="hidden" name="id" value="' . $id . '">' . '<input type="submit" value="generate cache" name="generate_cache">' . '</form>';
    } elseif (!ewiki_auth($id, $data, $action, $ring = 0, "_FORCE_AUTH=1") || !isset($ewiki_ring) || $ewiki_ring > 0) {
        if (is_array($data)) {
            $data = "You'll need to be admin. See ewiki_auth() and _PROTECTED_MODE in the README.";
        }
        $o .= $data;
    } else {
        unset($_REQUEST["generate_cache"]);
        $o .= "generating cache versions from:<ul>\n";
        foreach ($ewiki_plugins["page"] as $pid => $pf) {
            #echo "$pid:";
            $d = ewiki_db::GET($pid);
            if (empty($d) || empty($d["content"])) {
                $d = array("id" => $pid, "version" => 1, "flags" => EWIKI_DB_F_TEXT, "created" => time(), "content" => "", "meta" => "", "hits" => 0, "refs" => "");
            }
            $d["last_modified"] = time();
            $d["hits"]++;
            $d["content"] = $pf($pid, $d, "view");
            //@ADD - transform <html> back to wikimarkup
            //       here?
            if (ewiki_db::WRITE($d, true)) {
                $o .= "<li>{$pid}</li>\n";
            }
            unset($d);
        }
        $o .= "</ul>";
        ewiki_log("page search cache was updated", 2);
    }
    return $o;
}
Ejemplo n.º 8
0
function ewiki_page_fileupload($id, $data, $action, $def_sec = "")
{
    global $ewiki_upload_sections, $ewiki_plugins;
    $o = ewiki_make_title($id, $id, 2);
    $upload_file = $_FILES[EWIKI_UP_UPLOAD];
    if (empty($upload_file)) {
        $o .= ewiki_t("UPLOAD0");
        $o .= '<div class="upload">' . '<form action="' . ewiki_script($action != "view" ? $action : "", $id) . '" method="POST" enctype="multipart/form-data">' . '<b>' . ewiki_t("file") . '</b><br /><input type="file" name="' . EWIKI_UP_UPLOAD . '"><br /><br />' . '<input type="submit" value="' . EWIKI_PAGE_UPLOAD . '"><br /><br />';
        $o .= '<b>' . ewiki_t("comment") . '</b><br /><textarea name="comment" cols="35" rows="3"></textarea><br /><br />';
        if (empty($ewiki_upload_sections[$def_sec])) {
            $ewiki_upload_sections[$def_sec] = $def_sec;
        }
        if (count($ewiki_upload_sections) > 1) {
            if (empty($def_sec)) {
                $def_sec = $_REQUEST["section"];
            }
            $o .= '<b>' . ewiki_t("UPL_INSECT") . '</b><br /><select name="section">';
            foreach ($ewiki_upload_sections as $id => $title) {
                $o .= '<option value="' . $id . '"' . ($id == $def_sec ? ' selected' : '') . '>' . $title . '</option>';
            }
            $o .= '</select><br /><br />';
        }
        $o .= '<b>' . ewiki_t("UPL_NEWNAM") . '</b><br /><input type="text" name="new_filename" size="20"><br /><br />';
        $o .= '</form></div>';
    } elseif ($upload_file["size"] > EWIKI_UPLOAD_MAXSIZE) {
        $o .= ewiki_t("UPL_TOOLARGE");
    } else {
        $meta = array("X-Content-Type" => $upload_file["type"], "Cache-control" => "private");
        if (($s = $upload_file["name"]) && strlen($s) >= 3 || ($s = substr(md5(time() + microtime()), 0, 8) . ".dat")) {
            if (strlen($uu = trim($_REQUEST["new_filename"])) >= 3) {
                if ($uu != $s) {
                    $meta["Original-Filename"] = $s;
                }
                $s = $uu;
            }
            $meta["Content-Location"] = $s;
            $p = 0 or $p = strrpos($s, "/") and $p++ or $p = strrpos($s, '\\') and $p++;
            $meta["Content-Disposition"] = 'attachment; filename="' . urlencode(substr($s, $p)) . '"';
        }
        if (strlen($sect = $_REQUEST["section"])) {
            if ($ewiki_upload_sections[$sect] || $action == EWIKI_ACTION_ATTACHMENTS && $data["content"] && strlen($ewiki_plugins["action"][EWIKI_ACTION_ATTACHMENTS])) {
                $meta["section"] = $sect;
            } else {
                $o .= ewiki_t("UPL_REJSECT", array('sect' => $sect));
                return $o;
            }
        }
        if (strlen($s = trim($_REQUEST["comment"]))) {
            $meta["comment"] = $s;
        }
        $result = ewiki_binary_save_image($upload_file["tmp_name"], "", "RETURN", $meta, "ACCEPT_ALL", $care_for_images = 0);
        if ($result) {
            $o .= ewiki_t("UPL_OK", array('$script' => ewiki_script(EWIKI_PAGE_DOWNLOAD)));
            ewiki_log("file uploaded to section '{$sect}'");
        } else {
            $o .= ewiki_t("UPL_ERROR");
        }
    }
    return $o;
}
Ejemplo n.º 9
0
function resizeImage(&$filename, &$mime, $return = 0)
{
    //start timing
    $time_start = getmicrotime();
    /*** this disallows Win32 ***/
    if (DIRECTORY_SEPARATOR != "/" && !EWIKI_IMAGERESIZE_WIN || strpos($mime, "image/") !== 0) {
        return false;
    }
    if (!isMemoryFriendly($filename)) {
        return false;
    }
    if (isCandyCane($filename)) {
        return false;
    }
    $rescaled_filename = $filename;
    $type = getTypeFromMIME($mime);
    $orig_image = getImageStream($rescaled_filename, $type);
    if (!isset($orig_image)) {
        return false;
    }
    getXY($orig_image, $orig_x, $orig_y);
    if (!isResizeNeeded($orig_x, $filename)) {
        return true;
    }
    getInitialResize($orig_image, $new_x, $new_y);
    $orig_image = doResize($orig_image, $new_x, $new_y, $type);
    $rescaled_filename = tempnam(EWIKI_TMP, "ewiki.img_resize_gd.tmp.");
    doSave($orig_image, $rescaled_filename, $type);
    if (isResizeNeeded($new_x, $rescaled_filename)) {
        ewiki_log("Resize beyond initial resize is needed.  Carrying through.", 3);
        //set starting points for binary search
        $x_max = EWIKI_IMAGE_MAX_X - 1;
        $x_min = EWIKI_IMAGE_MIN_X;
        //set failsafe break to max number of iterations through the loop
        $failsafe = (int) (log($orig_x) + 1);
        while ($x_min <= $x_max && !isImageTolerable($rescaled_filename)) {
            ewiki_log("While loop initiated", 3);
            //somehow made it to an infinite loop, so get out
            if ($failsafe < 0) {
                return false;
            }
            //take a guess at the correct width
            $x_guess = (int) (($x_max + $x_min) / 2);
            if ($filename == $rescaled_filename) {
                $rescaled_filename = tempnam(EWIKI_TMP, "ewiki.img_resize_gd.tmp.");
            }
            #-- sizes
            $new_x = (int) $x_guess;
            $new_y = (int) ($x_guess * $orig_y / $orig_x);
            $new_image = doResize($orig_image, $new_x, $new_y, $type);
            doSave($new_image, $rescaled_filename, $type);
            #-- prepare next run
            imagedestroy($new_image);
            clearstatcache();
            $failsafe--;
            $ftmp = filesize($rescaled_filename);
            ewiki_log("xguess: {$x_guess}, xmin: {$x_min}, xmax: {$x_max}, filesize: {$ftmp}", 3);
            if (filesize($rescaled_filename) < EWIKI_IMAGE_TOLERANCE) {
                $x_min = $x_guess + 1;
            } else {
                if (filesize($rescaled_filename) > EWIKI_IMAGE_MAXSIZE) {
                    $x_max = $x_guess - 1;
                }
            }
        }
        ewiki_log("While loop ended", 3);
    }
    #-- stop
    imagedestroy($orig_image);
    clearstatcache();
    #-- security check filesizes, abort
    if (!filesize($filename) || !filesize($rescaled_filename) || filesize($rescaled_filename) > EWIKI_IMAGE_MAXSIZE) {
        unlink($rescaled_filename);
        return $false;
    }
    #-- set $mime, as it may have changed (.gif)
    $mime = strtok($mime, "/") . "/" . $type;
    if (!strstr($filename, ".{$type}")) {
        unlink($filename);
        $filename .= ".{$type}";
    }
    #-- move tmp file to old name
    copy($rescaled_filename, $filename);
    unlink($rescaled_filename);
    //end timing
    $time_end = getmicrotime();
    $time = $time_end - $time_start;
    ewiki_log("{$time} seconds to perform resizing", 3);
    return true;
}
Ejemplo n.º 10
0
function ewiki_action_control_page($id, &$data, $action)
{
    global $ewiki_ring, $ewiki_config, $ewiki_plugins;
    $a_flagnames = array("_TEXT", "_BINARY", "_DISABLED", "_HTML", "_READONLY", "_WRITEABLE", "_APPENDONLY", "_SYSTEM", "_PART", "_MINOR", "_HIDDEN", "_ARCHIVE", "_UU12", "_UU13", "_UU14", "_UU15", "_UU16", "_EXEC", "_UU18", "_UU19");
    $o = ewiki_make_title($id, "control {$id}", 2);
    #-- admin requ. ---------------------------------------------------------
    if (!ewiki_auth($id, $data, $action, $ring = 0, "_FORCE_LOGIN=1") || !isset($ewiki_ring) || $ewiki_ring > 1) {
        if (is_array($data)) {
            $data = "You'll need to be admin. See ewiki_auth() and _PROTECTED_MODE in the README.";
        }
        $o .= $data;
    } elseif (@$_REQUEST["pgc_setflags"]) {
        #-- setted new flags
        $new_f = 0;
        foreach ($_REQUEST["sflag"] as $n => $b) {
            if ($b) {
                $new_f |= 1 << $n;
            }
        }
        #-- administrator may change all flags
        if ($ewiki_ring == 0) {
            $data["flags"] = $new_f;
        } else {
            $data["flags"] = $data["flags"] & ~EWIKI_DB_F_MODERATORFLAGS | $new_f & EWIKI_DB_F_MODERATORFLAGS;
        }
        $data["lastmodified"] = time();
        $data["version"]++;
        if (ewiki_db::WRITE($data)) {
            $o .= "Page flags were updated correctly.";
            ewiki_log("page flags of '{$id}' were set to {$data['flags']}");
        } else {
            $o .= "A database error occoured.";
        }
    } elseif (@$_REQUEST["pgc_rename"] && strlen($new_id = $_REQUEST["mv_to"])) {
        $old_id = $id;
        $report = "";
        $preg_id = "/" . addcslashes($old_id, ".+*?|/\\()\$[]^#") . "/" . ($_REQUEST["mv_cr1"] ? "i" : "");
        #-- check if new name does not already exist in database
        $exists = ewiki_db::GET($new_id);
        if ($exists || !empty($exists)) {
            return $o .= "Cannot overwrite an existing database entry.";
        }
        #-- copy from old name to new name
        $max_ver = $data["version"];
        $data = array();
        for ($v = 1; $v <= $max_ver; $v++) {
            $row = ewiki_db::GET($old_id, $v);
            $row["id"] = $new_id;
            $row["lastmodified"] = time();
            $row["content"] = preg_replace($preg_id, $new_id, $row["content"]);
            ewiki_scan_wikiwords($row["content"], $links, "_STRIP_EMAIL=1");
            $row["refs"] = "\n\n" . implode("\n", array_keys($links)) . "\n\n";
            $row["author"] = ewiki_author("control/");
            if (!ewiki_db::WRITE($row)) {
                $report .= "error while copying version {$v},<br />\n";
            }
        }
        #-- proceed if previous actions error_free
        if (empty($report)) {
            #-- deleting old versions
            for ($v = 1; $v <= $max_ver; $v++) {
                ewiki_db::DELETE($old_id, $v);
            }
            #-- adjust links/references to old page name
            if ($_REQUEST["mv_cr0"]) {
                $result = ewiki_db::SEARCH("refs", $old_id);
                while ($result && ($row = $result->get())) {
                    $row = ewiki_db::GET($row["id"]);
                    if (preg_match($preg_id, $row["content"], $uu)) {
                        $row["content"] = preg_replace($preg_id, $new_id, $row["content"]);
                        $row["lastmodified"] = time();
                        $row["version"]++;
                        ewiki_scan_wikiwords($row["content"], $links, "_STRIP_EMAIL=1");
                        $row["refs"] = "\n\n" . implode("\n", array_keys($links)) . "\n\n";
                        $row["author"] = ewiki_author("control/");
                        if (!ewiki_db::WRITE($row)) {
                            $report .= "could not update references in " . $row['id'] . ",<br />\n";
                        } else {
                            $report .= "updated references in " . $row['id'] . ",<br />\n";
                        }
                    }
                }
            }
            $o .= "This page was correctly renamed from '{$old_id}' to '{$new_id}'.<br /><br />\n{$report}";
            ewiki_log("page renamed from '{$old_id}' to '{$new_id}'", 2);
        } else {
            $o .= "Some problems occoured while processing your request, therefor the old page still exists:<br />\n" . $report;
        }
    } elseif (@$_REQUEST["pgc_setmeta"] && $ewiki_ring == 0 && ($set = explode("\n", $_REQUEST["pgc_meta"]))) {
        $new_meta = array();
        foreach ($set as $line) {
            if (($line = trim($line)) && ($key = trim(strtok($line, ":"))) && ($value = trim(strtok("")))) {
                $new_meta[$key] = $value;
            }
        }
        $data["meta"] = $new_meta;
        $data["lastmodified"] = time();
        $data["version"]++;
        if (ewiki_db::WRITE($data)) {
            $o .= "The {meta} field was updated.";
        } else {
            $o .= "A database error occoured.";
        }
    } elseif (@$_REQUEST["pgc_purge"] && $_REQUEST["pgc_purge1"]) {
        $loop = 3;
        do {
            $verZ = $data["version"];
            while ($verZ > 0) {
                ewiki_db::DELETE($id, $verZ);
                $verZ--;
            }
        } while ($loop-- && ($data = ewiki_db::GET($id)));
        if (empty($data)) {
            $o .= "Page completely removed from database.";
            ewiki_log("page '{$id}' was deleted from db", 2);
        } else {
            $o .= "Page still here.";
        }
    } else {
        $o .= '<form action="' . ewiki_script("{$action}", $id) . '" method="POST" enctype="text/html">' . '<input type="hidden" name="id" value="' . "{$action}/{$id}" . '">';
        #-- flags
        $o .= '<div class="flags">';
        $o .= "<h4>page flags</h4>\n";
        foreach ($a_flagnames as $n => $s) {
            $disabled = $ewiki_ring == 1 && !(1 << $n & EWIKI_DB_F_MODERATORFLAGS) ? ' disabled="disabled"' : "";
            $checked = $data["flags"] & 1 << $n ? ' checked="checked"' : "";
            $a[$n] = '<input type="checkbox" name="sflag[' . $n . ']" value="1"' . $checked . $disabled . '> ' . $s;
        }
        $o .= '<table border="0" class="list">' . "\n";
        for ($n = 0; $n < count($a_flagnames); $n++) {
            $y = $n >> 2;
            $x = $n & 0x3;
            if ($x == 0) {
                $o .= "<tr>";
            }
            $o .= "<td>" . $a[4 * $y + $x] . "</td>";
            if ($x == 3) {
                $o .= "</tr>\n";
            }
        }
        $o .= '</table>';
        $o .= '<input type="submit" name="pgc_setflags" value="chmod">';
        $o .= "\n<br /><br /><hr></div>\n";
        #-- rename
        $o .= '<div class="rename">';
        $o .= "<h4>rename page</h4>\n";
        $o .= 'new page name: <input type="text" size="30" name="mv_to" value="' . htmlentities($id) . '">' . '<br />' . '<input type="checkbox" name="mv_cr0" value="1" checked> also try to change all references from other pages accordingly ' . '(<input type="checkbox" name="mv_cr1" value="1" checked> and act case-insensitive when doing so) ';
        $o .= '<br /><input type="submit" name="pgc_rename" value="mv">';
        $o .= "\n<br /><br /><hr></div>\n";
        #-- meta
        if (isset($ewiki_ring) && $ewiki_ring == 0) {
            $o .= '<div class="meta">';
            $o .= "<h4>meta data</h4>\n";
            $o .= '<textarea cols="40" rows="6" name="pgc_meta">';
            if (($uu = @$data["meta"]) && is_array($uu)) {
                foreach ($uu as $key => $value) {
                    if (is_array($value)) {
                        $value = serialize($array);
                    }
                    $o .= htmlentities($key . ": " . trim($value)) . "\n";
                }
            }
            $o .= "</textarea>\n";
            $o .= '<br /><input type="submit" name="pgc_setmeta" value="set">';
            $o .= "\n<br /><br /><hr></div>\n";
        }
        #-- delete
        $o .= '<div class="delete">';
        $o .= "<h4>delete page</h4>\n";
        $o .= '<input type="checkbox" name="pgc_purge1" value="1"> I\'m sure';
        $o .= '<br /><input type="submit" name="pgc_purge" value="rm">';
        $o .= "\n<br /><br /><hr></div>\n";
        $o .= '</form>';
    }
    return $o;
}
Ejemplo n.º 11
0
function ewiki_xpi_plugin_control_centre()
{
    ewiki_xpi_load_registry($registry, $registry_hash);
    #-- title
    $o = '<div class="xpi-settings"><h4>plugin control</h4>';
    #-- delete plugins
    if ($access && ($uu = $_REQUEST["xpi_rm"])) {
        foreach ($uu as $id => $del) {
            if ($del) {
                $id = rawurldecode($id);
                $dat = ewiki_db::GET($id);
                $vZ = $dat["version"];
                for ($v = 1; $v <= $vZ; $v++) {
                    ewiki_db::DELETE($id, $v);
                }
                unset($registry[$id]);
                $vZ += 0;
                $o .= "<b>i</b>: Purged {$vZ} versions of '{$id}' and removed xpi registry entry.<br /><br />";
                ewiki_log("uninstalled .xpi/.jpi plugin '{$id}'", 0);
            }
        }
        $_REQUEST["setup_xpi"] = 1;
    }
    #-- update config settings
    if ($_REQUEST["setup_xpi"]) {
        if ($access) {
            foreach ($registry as $id => $uu) {
                $registry[$id]["state"] = $_REQUEST["xpi_set"][rawurlencode($id)] ? 1 : 0;
            }
            $registry_hash["content"] = serialize($registry);
            ewiki_data_update($registry_hash);
            $registry_hash["version"]++;
            ewiki_db::WRITE($registry_hash);
        } else {
            $o .= "You have no privileges to change the status of installed .xpi plugins.<br />\n";
        }
    }
    #-- enable/disable checkboxes
    $o .= '<table border="0" cellspacing="1" cellpadding="2">';
    foreach ($registry as $dat) {
        $enabled = $dat["state"] == 1;
        $hard = $dat["type"] == "page";
        $title = $hard ? ewiki_link($dat["id"]) : $dat["id"];
        $o .= '<tr>' . '<td><tt>' . $dat["type"] . '</tt></td>' . '<td class="xs-check"><input type="checkbox" name="xpi_set[' . rawurlencode($dat["id"]) . ']" value="1"' . ($enabled ? " checked" : "") . ($hard ? " disabled" : "") . '></td>' . '<td class="xs-id">' . $title . '</td>' . '<td><small>' . htmlentities($dat["description"]) . '</small></td>' . '<td>' . $dat["author"] . ", " . $dat["license"] . '</td>' . '<td class="xs-check"><input type="submit" name="xpi_rm[' . rawurlencode($dat["id"]) . ']" value="rm" title="uninstall plugin"' . ($access ? "" : " disabled") . '></td>' . '</tr>';
    }
    $o .= '</table>';
    $o .= '<br /><input type="submit" name="setup_xpi" value="configure"' . ($access ? "" : " disabled") . '>';
    $o .= '</form></div>';
    return $o;
}
Ejemplo n.º 12
0
/**
 * admin gui for modifying user accounts.
 *
 * @param string id
 * @param mixed data
 * @param string action
 * @return string page output response
 */
function ewiki_page_liveuser_admin_users($id, $data, $action)
{
    global $liveuserAuthAdmin, $liveuserPermAdmin, $ewiki_plugins;
    ob_start();
    echo ewiki_make_title($id, $id, 2);
    // handle posted deletes or updates
    if (isset($_POST['submit_deleteusers']) || isset($_POST['submit_changeusers']) || isset($_POST['submit_adduserstogroup']) || isset($_POST['submit_removeusersfromgroup']) || isset($_POST['submit_changegroups'])) {
        foreach ($_POST as $key => $value) {
            list($prefix, $id) = explode('_', $key, 2);
            //get password status of current $id
            $username = $_POST['origname_' . $id];
            $pwdstatus = ewiki_get_uservar("passwdstatus", NULL, $username);
            // Remove a user
            if ($prefix == 'chk' && is_numeric($id) && $value == 'on' && isset($_POST['submit_deleteusers'])) {
                if (liveuser_removeEntity('user_id', $id)) {
                    echo '<p>User ' . $id . ' was successfully removed.</p>';
                } else {
                    echo '<p>Removal of user ' . $id . ' failed.</p>';
                }
            }
            // Add a user to a group
            if ($prefix == 'chk' && is_numeric($id) && $value == 'on' && isset($_POST['submit_adduserstogroup'])) {
                if (($group_id = liveuser_checkEntity('group', $_POST['grouplist'])) !== false) {
                    if (liveuser_checkGroupUser($group_id, $id) === false) {
                        if ($liveuserPermAdmin->addUserToGroup($id, $group_id)) {
                            echo '<p>User ' . $id . ' was successfully added to group ' . $_POST['grouplist'] . '.</p>';
                        } else {
                            echo '<p>Addition of user ' . $id . ' to group ' . $_POST['grouplist'] . ' failed.</p>';
                        }
                    } else {
                        echo '<p>User ' . $id . ' is already a member of group ' . $_POST['grouplist'] . '.</p>';
                    }
                } else {
                    echo '<p>Group ' . $_POST['grouplist'] . ' does not exist.</p>';
                }
            }
            // Remove a user from a group
            if ($prefix == 'chk' && is_numeric($id) && $value == 'on' && isset($_POST['submit_removeusersfromgroup'])) {
                if (($group_id = liveuser_checkEntity('group', $_POST['grouplist'])) !== false) {
                    if ($liveuserPermAdmin->removeUserFromGroup($id, liveuser_checkEntity('group', $_POST['grouplist']))) {
                        echo '<p>User ' . $id . ' was successfully removed from group ' . $_POST['grouplist'] . '.</p>';
                    } else {
                        echo '<p>Removal of user ' . $id . ' from group ' . $_POST['grouplist'] . ' failed.</p>';
                    }
                } else {
                    echo '<p>Group ' . $_POST['grouplist'] . ' does not exist.</p>';
                }
            }
            // Change the user name
            if ($prefix == 'chname' && is_numeric($id) && !empty($value) && $_POST['origname_' . $id] != $value && isset($_POST['submit_changeusers'])) {
                $event_log = '';
                if (liveuser_checkEntity('user', $value) === false) {
                    if ($liveuserAuthAdmin->updateUser($id, $value)) {
                        $event_log .= '<p>User ' . $value . ' was successfully updated.</p>';
                        if (isset($ewiki_plugins['uservars_store'][0])) {
                            if ($ewiki_plugins['uservars_store'][0]($ewiki_plugins['uservars_retrieve'][0]($_POST['origname_' . $id]), $value)) {
                                $event_log .= '<p>User data copied to ' . $value;
                                if ($ewiki_plugins['uservars_store'][0](array(), $_POST['origname_' . $id])) {
                                    $event_log .= ' and deleted from ' . $_POST['origname_' . $id];
                                } else {
                                    $event_log .= ' but not deleted from ' . $_POST['origname_' . $id];
                                }
                                $event_log .= '.</p>';
                            } else {
                                $event_log .= '<p>User data copy failed.</p>';
                            }
                        }
                    } else {
                        $event_log .= '<p>Update of user ' . $value . ' failed.</p>';
                    }
                } else {
                    $event_log .= '<p>Another user with the name ' . $value . ' already exists in the database. No change has been made.</p>';
                }
                echo $event_log;
                ewiki_log("Attempted to rename " . $_POST['origname_' . $id] . " to {$value}." . $event_log, 1);
            }
            // Change user variable
            if ($prefix == 'chuvar' && is_numeric($id) && !empty($value) && $_POST['origchuvar_' . $id] != $value && isset($_POST['submit_changeusers'])) {
                if (ewiki_set_uservar($_POST['uvar_fieldname'], $value, $username)) {
                    echo "<p>UserVar " . $_POST['uvar_fieldname'] . " successfully updated for {$username}</p>";
                } else {
                    echo "<p>Update of UserVar " . $_POST['uvar_fieldname'] . " for {$username} failed.</p>";
                }
            }
            if ($prefix == "radpw" && is_numeric($id) && !empty($value) && isset($_POST['submit_changeusers'])) {
                if ($value == "expire" && ($pwdstatus == 'good' || is_null($pwdstatus))) {
                    ewiki_set_uservar("passwdexpiredate", time(), $username);
                    ewiki_set_uservar("passwdstatus", 'expired', $username);
                } elseif ($value == "good" && ($pwdstatus == 'expired' || is_null($pwdstatus))) {
                    ewiki_set_uservar("passwdexpiredate", time() + 60 * 60 * 24 * EWIKI_PASSWD_LIFETIME, $username);
                    ewiki_set_uservar("passwdstatus", 'good', $username);
                }
            }
            if ($prefix == 'chkrandpw' && is_numeric($id) && !empty($value) && isset($_POST['submit_changeusers'])) {
                $password = liveuser_generate_password();
                if ($liveuserAuthAdmin->updateUser($id, $_POST['chname_' . $id], $password)) {
                    ewiki_set_uservar("passwdexpiredate", time() - 60 * 60 * 24 * EWIKI_PASSWD_LIFETIME, $username);
                    ewiki_set_uservar("passwdstatus", 'expired', $username);
                    echo '<p>Password for user ' . $_POST['chname_' . $id] . " was successfully updated to \"{$password}\" and set to expire in " . EWIKI_PASSWD_LIFETIME . "days.</p>";
                } else {
                    echo '<p>Update of password for user ' . $_POST['chname_' . $id] . ' failed.</p>';
                }
            }
            // Change the user's password
            if ($prefix == 'chpw' && is_numeric($id) && !empty($value) && isset($_POST['submit_changeusers'])) {
                // check for cracklib functions and validate against them if possible
                liveuser_admin_users_cracklib_check($_POST['chname_' . $id], $value);
                if ($liveuserAuthAdmin->updateUser($id, $_POST['chname_' . $id], $value)) {
                    ewiki_set_uservar("passwdexpiredate", time() - 60 * 60 * 24 * EWIKI_PASSWD_LIFETIME, $username);
                    ewiki_set_uservar("passwdstatus", 'expired', $username);
                    echo '<p>Password for user ' . $_POST['chname_' . $id] . ' was successfully updated and set to expire in ' . EWIKI_PASSWD_LIFETIME . 'days.</p>';
                } else {
                    echo '<p>Update of password for user ' . $_POST['chname_' . $id] . ' failed.</p>';
                }
            }
            // Remove a group
            if ($prefix == 'chkgroup' && is_numeric($id) && $value == 'on' && isset($_POST['submit_changegroups'])) {
                if (liveuser_removeEntity('group_id', $id)) {
                    echo '<p>Group ' . $id . ' was successfully deleted.</p>';
                } else {
                    echo '<p>Deletion of group ' . $id . ' failed.</p>';
                }
            }
            // Change group name
            if ($prefix == 'chgroupname' && is_numeric($id) && !empty($value) && $_POST['origgroupname_' . $id] != $value && isset($_POST['submit_changegroups'])) {
                if ($liveuserPermAdmin->updateGroup($id, $value)) {
                    echo '<p>Group ' . $value . ' was successfully updated.</p>';
                } else {
                    echo 'Update of group ' . $value . ' failed.</p>';
                }
            }
        }
    }
    // Add a user
    if (!empty($_POST['username_text']) && !empty($_POST['pw_text']) && isset($_POST['submit_adduser'])) {
        if (liveuser_checkEntity('user', $_POST['username_text']) === false) {
            // check for cracklib functions and validate against them if possible
            liveuser_admin_users_cracklib_check($_POST['chname_' . $id], $value);
            if (liveuser_addEntity('user', array($_POST['username_text'], $_POST['pw_text'])) !== false) {
                echo '<p>User ' . $_POST['username_text'] . ' was successfully created.</p>';
            } else {
                echo '<p>Creation of user ' . $_POST['username_text'] . ' failed.</p>';
            }
        } else {
            echo '<p>User ' . $_POST['username_text'] . ' already exists.</p>';
        }
    }
    // Add a lot of users and add them into groups
    if (!empty($_POST['usernames_text']) && isset($_POST['submit_addusers'])) {
        $newusers = explode("\n", $_POST['usernames_text']);
        foreach ($newusers as $newuser) {
            $newuser = trim($newuser);
            if (($auth_id = liveuser_checkEntity('user', $newuser)) === false) {
                if ($_POST["pwgen_addusers"] == "on") {
                    $password = liveuser_generate_password();
                } else {
                    $password = $newuser;
                }
                if (($auth_id = liveuser_addEntity('user', array($newuser, $password))) !== false) {
                    echo "<p>User {$newuser} was successfully created with password {$password}.</p>";
                } else {
                    echo '<p>Creation of user ' . $newuser . ' failed.</p>';
                }
            } else {
                echo '<p>User ' . $newuser . ' already exists.</p>';
            }
            if ($auth_id !== false && !empty($_POST['usernames_grouplist'])) {
                if (($group_id = liveuser_checkEntity('group', $_POST['usernames_grouplist'])) !== false) {
                    if (liveuser_checkGroupUser($group_id, $auth_id) === false) {
                        if ($liveuserPermAdmin->addUserToGroup($auth_id, $group_id)) {
                            echo '<p>User ' . $newuser . ' was successfully added to group ' . $_POST['usernames_grouplist'] . '.</p>';
                        } else {
                            echo '<p>Addition of user ' . $newuser . ' to group ' . $_POST['usernames_grouplist'] . ' failed.</p>';
                        }
                    } else {
                        echo '<p>User ' . $newuser . ' is already a member of group ' . $_POST['usernames_grouplist'] . '.</p>';
                    }
                } else {
                    echo '<p>Group ' . $_POST['usernames_grouplist'] . ' does not exist.</p>';
                }
            }
        }
    }
    // Add a group
    if (!empty($_POST['groupname_text']) && isset($_POST['submit_addgroup'])) {
        $group_id = liveuser_checkEntity('group', $_POST['groupname_text']);
        if ($group_id === false) {
            $group_const = 'LU_G_' . strtoupper($_POST['groupname_text']);
            $group_id = liveuser_addEntity('group', array($group_const, $_POST['groupname_text'], null, true));
            if ($group_id !== false) {
                echo '<p>Group ' . $_POST['groupname_text'] . ' was successfully created.</p>';
            } else {
                echo '<p>Creation of group ' . $_POST['groupname_text'] . ' failed.</p>';
            }
        } else {
            echo '<p>Group ' . $_POST['groupname_text'] . ' already exists.</p>';
        }
        if (isset($_POST['addright']) && $group_id !== false) {
            $right_id = liveuser_checkEntity('right', $_POST['groupname_text']);
            if ($right_id === false) {
                $right_const = 'LU_R_' . strtoupper($_POST['groupname_text']);
                $right_id = liveuser_addEntity('right', array(LU_AREA_LIVEWEB, $right_const, $_POST['groupname_text']));
                if ($right_id !== false) {
                    echo '<p>Right ' . $_POST['groupname_text'] . ' was successfully created.</p>';
                } else {
                    echo '<p>Creation of right ' . $_POST['groupname_text'] . ' failed.</p>';
                }
            } else {
                echo '<p>Right ' . $_POST['groupname_text'] . ' already exists.</p>';
            }
            if ($right_id !== false) {
                // check if group already has the right
                if (liveuser_checkGroupRight($group_id, $right_id)) {
                    echo 'Group ' . $_POST['groupname_text'] . ' already has right ' . $_POST['groupname_text'] . '.</p>';
                } else {
                    // attempt to assign right to group
                    if ($liveuserPermAdmin->grantGroupRight($group_id, $right_id, 1) === true) {
                        echo '<p>Right ' . $_POST['groupname_text'] . ' has been assigned to group ' . $_POST['groupname_text'] . '.</p>';
                    } else {
                        echo '<p>Assignment of right ' . $_POST['groupname_text'] . ' to group ' . $_POST['groupname_text'] . ' failed.</p>';
                    }
                }
            }
        }
    }
    // Show current table listing of pages and permissions
    $users = $liveuserAuthAdmin->getUsers();
    $groups = $liveuserPermAdmin->getGroups();
    //uservars based controls
    if (isset($ewiki_plugins['uservars_search'][0])) {
        if (isset($_REQUEST['search_fieldname'])) {
            //set fieldname variable
            $fieldname = $_REQUEST['search_fieldname'];
        }
        if (strlen($_REQUEST['search_fieldvalue'])) {
            //set fieldvalue variable
            $fieldvalue = $_REQUEST['search_fieldvalue'];
        }
        if (!empty($fieldname)) {
            $userdata = ewiki_search_uservar($fieldname, $fieldvalue);
            //get data for the given fieldname/fieldvalue combination
            //Remove non-matching users
            foreach ($users as $key => $user) {
                if (!isset($userdata[$user['handle']])) {
                    unset($users[$key]);
                }
            }
        }
        //Display search form
        ?>
      <form method="post" action="">
        <table>
          <tr><td>Field Name</td><td>
			<input type="text" name="search_fieldname" value="<?php 
        echo $fieldname;
        ?>
">
			</td></tr>
          <tr><td>Value</td><td>
			<input type="text" name="search_fieldvalue" value="<?php 
        echo $fieldvalue;
        ?>
">
			</td></tr>
        </table>
        <input value="Search" type="submit" name="submit_searchaccount" />
      </form>
      
      <?php 
    }
    if (is_array($users) && !empty($users)) {
        ?>
	    <form method="post" action="">
	    <h3>Edit Users</h3>
      <input type="hidden" name="uvar_fieldname" value="<?php 
        echo $fieldname;
        ?>
">
	    <table border="1">
	    <tr><th>Select</th><th>User ID</th><th>User Name<br />Password [Random]</th><th>Password Status</th><th>Groups</th>
        <?php 
        if (!empty($fieldname)) {
            ?>

    <th><?php 
            echo $fieldname;
            ?>
 			
		<input type="hidden" name="search_fieldname" value="<?php 
            echo $fieldname;
            ?>
">
		<input type="hidden" name="search_fieldvalue" value="<?php 
            echo $fieldvalue;
            ?>
">
		</th>
	<?php 
        }
        echo '</tr>';
        foreach ($users as $user) {
            ?>
                <tr>
                    <td><input name="chk_<?php 
            echo $user['auth_user_id'];
            ?>
" type="checkbox" /></td>
                    <td><?php 
            echo $user['auth_user_id'];
            ?>
</td>
                    <td>
                        <input id="chname_<?php 
            echo $user['auth_user_id'];
            ?>
" name="chname_<?php 
            echo $user['auth_user_id'];
            ?>
" type="text" value="<?php 
            echo $user['handle'];
            ?>
" />
                        <input name="origname_<?php 
            echo $user['auth_user_id'];
            ?>
" type="hidden" value="<?php 
            echo $user['handle'];
            ?>
"><br />
                        
                        <input id="chpw_<?php 
            echo $user['auth_user_id'];
            ?>
" name="chpw_<?php 
            echo $user['auth_user_id'];
            ?>
" type="text" value="" />
                        <input name="chkrandpw_<?php 
            echo $user['auth_user_id'];
            ?>
" type="checkbox" />
                        <?php 
            echo $liveuserAuthAdmin->encryptPW($user['handle']) == $user['passwd'] ? '<div class="warning">Password == User Name</div>' : '';
            ?>
                        
                    </td>
                    <td>
                    <?php 
            $good = '<input type="radio" name="radpw_' . $user["auth_user_id"] . '" value="good" CHECKED >Good<br />' . '<input type="radio" name="radpw_' . $user["auth_user_id"] . '" value="expire">Expired<br />';
            $expired = '<input type="radio" name="radpw_' . $user["auth_user_id"] . '" value="good">Good<br />' . '<input type="radio" name="radpw_' . $user["auth_user_id"] . '" value="expire" CHECKED >Expired<br />';
            echo ewiki_get_uservar("passwdstatus", 'good', $user['handle']) == 'good' ? $good : $expired;
            echo intval((ewiki_get_uservar("passwdexpiredate", time(), $user['handle']) - time()) / (60 * 60 * 24)) . " Days<br />";
            ?>
                    </td>
                    <td>
            <?php 
            foreach ($liveuserPermAdmin->getGroups(array('where_user_id' => $user['auth_user_id'])) as $group) {
                echo $group['name'] . '<br />';
            }
            ?>
                    </td>
                
            <?php 
            if (isset($userdata[$user['handle']])) {
                echo '<input id="origchuvar_' . $user['auth_user_id'] . '" name="origchuvar_' . $user['auth_user_id'] . '" type="hidden" value="' . $userdata[$user['handle']] . '">';
                echo '<td> <input id="chuvar_' . $user['auth_user_id'] . '" name="chuvar_' . $user['auth_user_id'] . '" type="text" value="' . $userdata[$user['handle']] . '" /></td>';
            }
            echo "</tr>";
        }
        ?>
            </table>
            <input type="reset" value="Reset" />
            <input type="submit" name="submit_deleteusers" value="Delete Selected" />
            <input type="submit" name="submit_changeusers" value="Submit Changes" />
        <?php 
        if (is_array($groups) && !empty($groups)) {
            ?>
                <br /><br /><label for="grouplist">Group</label>
                <select id="grouplist" name="grouplist">
            <?php 
            foreach ($groups as $group) {
                echo '<option value="' . $group['name'] . '">' . $group['name'] . '</option>';
            }
            ?>
                </select><br />
                <input type="submit" name="submit_adduserstogroup" value="Add Selected" />
                <input type="submit" name="submit_removeusersfromgroup" value="Remove Selected" />
            <?php 
        }
        echo '</form>';
    } else {
        ?>
            <h3>Edit Users</h3>
            <p>No users were found in the database.</p>
        <?php 
    }
    // Show Add a new user section
    ?>
	<form method="post" action="">
	<h3>Add a User</h3>
	<label for="username_text">User Name</label>
	<input id="username_text" name="username_text" type="text" /><br />
	<label for="pw_text">Password</label>
	<input id="pw_text" name="pw_text" type="text" /><br />
	<input type="submit" name="submit_adduser" value="Add User" />
	</form>
    <?php 
    // Show Add multiple users section
    ?>
	<form method="post" action="">
	<h3>Add Multiple Users</h3>
        <p>Insert one user name per line. This input will be processed as a 
        batch, and each user will be created with a password identical to his 
        user name or a randomly generated password if the "Generate Passwords" 
        box is checked.</p>
	<textarea id="usernames_text" name="usernames_text" rows="10" cols="25"></textarea>    
    <?php 
    if (is_array($groups) && !empty($groups)) {
        ?>
            <label for="usernames_grouplist">Groups</label>
            <select id="usernames_grouplist" name="usernames_grouplist" />
            <option value=""></option>
        <?php 
        foreach ($groups as $group) {
            echo '<option value="' . $group['name'] . '">' . $group['name'] . '</option>';
        }
        ?>
            </select>
        <?php 
    }
    ?>
        <p><input type="checkbox" name="pwgen_addusers" checked="checked"> Generate random passwords.</p>
        <input type="submit" name="submit_addusers" value="Add Users" />    
        </form>
    <?php 
    // Groups Section
    if (is_array($groups) && !empty($groups)) {
        ?>
	    <form method="post" action="">
	    <h3>Edit Groups</h3>
	    <table border="1">
	    <tr><th>Delete</th><th>Group ID</th><th>Group Name</th></tr>
        <?php 
        foreach ($groups as $group) {
            ?>
                <tr>
                    <td><input name="chkgroup_<?php 
            echo $group['group_id'];
            ?>
" type="checkbox" /></td>
                    <td><?php 
            echo $group['group_id'];
            ?>
</td>
                    <td>
                        <input name="chgroupname_<?php 
            echo $group['group_id'];
            ?>
" type="text" value="<?php 
            echo $group['name'];
            ?>
" />
                        <input name="origgroupname_<?php 
            echo $group['group_id'];
            ?>
" type="hidden" value="<?php 
            echo $group['name'];
            ?>
" />
                    </td>
                </tr>
            <?php 
        }
        ?>
            </table>
            <input type="reset" value="Reset" />
            <input name="submit_changegroups" type="submit" value="Submit Changes">
            </form>
        <?php 
    } else {
        ?>
            <h3>Edit Groups</h3>
            <p>No groups were found in the database.</p>
        <?php 
    }
    // Show Add a new group section
    ?>
	<form method="post" action="">
	<h3>Add a Group</h3>
        <p>When creating a group, you may choose to create a right with the group, which may then be applied to user accounts via the group. If the group already exists, this form will still attempt to link a right to it. If the right already exists and is not associated with the group, it will be assigned to the group.</p>
	<label for="groupname_text">Group Name</label>
	<input id="groupname_text" name="groupname_text" type="text"><br />
	<label for="addright">Add/Link Right</label>
	<input id="addright" name="addright" type="checkbox" checked="checked"><br />
	<input type="submit" name="submit_addgroup" value="Add Group" />
	</form>
    <?php 
    $o = ob_get_contents();
    ob_end_clean();
    return $o;
}
Ejemplo n.º 13
0
function ewiki_uservars_pages_retrieve($username = NULL)
{
    global $ewiki_uservars;
    if (!isset($username)) {
        $username = $GLOBALS['ewiki_auth_user'];
    }
    if (!empty($ewiki_uservars) && $username == $GLOBALS['ewiki_auth_user']) {
        return $ewiki_uservars;
    }
    $data = ewiki_db::GET(EWIKI_USERVARS_PAGENAME_PREFIX . $username);
    //User data must be on system pages
    if ($data["flags"] & EWIKI_DB_F_SYSTEM) {
        //echo("System flag set ");
        $userdata = unserialize($data['content']);
    }
    //log and fail if no userdata found i.e. no page, no system flag, or not an array
    if (!is_array($userdata)) {
        //echo(" retrieved no user data");
        ewiki_log("No userdata for {$username} in ewiki_uservars_pages_retrieve()", 2);
        return array();
    }
    if ($username == $GLOBALS['ewiki_auth_user']) {
        $ewiki_uservars = $userdata;
    }
    return $userdata;
}
Ejemplo n.º 14
0
function ewiki_page_userregistry($id, &$data, $action)
{
    global $ewiki_plugins, $ewiki_config, $ewiki_auth_user;
    $o = ewiki_make_title($id, $id, 2, $action);
    $url = ewiki_script("", $id);
    #-- auto-login
    if ($ewiki_auth_user && empty($_REQUEST["userreg_name"])) {
        $user = $ewiki_auth_user;
        $uu = ewiki_auth_userdb_userregistry($ewiki_auth_user);
        $pw = $uu[0];
        $_REQUEST["userreg_login"] = 1;
    } else {
        $user = trim($_REQUEST["userreg_name"]);
        $pw = $_REQUEST["userreg_pw"];
    }
    #-- try to get user entry
    $ue = ewiki_auth_userdb_userregistry($user);
    #-- account creation ---------------------------------------------------
    if ($_REQUEST["userreg_register"] && empty($ue)) {
        $o .= ewiki_t(<<<END
<h4>_{New Account}</h4>
<form action="{$url}" method="POST" enctype="multipart/form-data" accept-encoding="ISO-8859-1">
_{user/login name} <input type="text" size="14" name="userreg_name" value="{$user}"> <br />
<input type="hidden" name="userreg_pw" value="">
<br />
_{password} <input type="password" name="new_pw" size="10" maxsize="12" value="{$pw}"> <br />
_{retype} <input type="password" name="new_pw2" size="10" maxsize="12" value=""> <br />
<br />
<input type="submit" name="userreg_store" value="_{create account}">
</form><br /><br />
END
);
        return $o;
        // finished here, prevent fallthrough-display of login-form
    }
    #-- check password
    if ($ue && $user && !ewiki_auth_user($user, $pw)) {
        $o .= $_REQUEST["userreg_register"] ? ewiki_t("USERNAME_ALREADY_USED") : ewiki_t("WRONG_PW") . "\n" . ewiki_t("PLEASE_RETRY");
        return $o;
    }
    #-- set fallback settings for account creation
    if (empty($ue) && $_REQUEST["userreg_store"]) {
        $ue = $_REQUEST["userreg_ue"] = array($pw, EWIKI_REGISTERED_LEVEL, "", "", "");
    }
    #-- check username
    if (preg_match("/[^" . EWIKI_CHARS_U . EWIKI_CHARS_L . "]/", $user . $pw)) {
        $o .= ewiki_t("PW_ONLY_LETTERS") . "\n" . ewiki_t("PLEASE_RETRY");
        return $o;
    } elseif ($name && strlen($user) < 3) {
        return $o . ewiki_t("USERNAME_MIN");
    }
    #-- save changes -------------------------------------------------------
    if ($_REQUEST["userreg_store"] && $user) {
        #-- new user entry
        $new_ue = $_REQUEST["userreg_ue"] or $new_ue = array();
        $new_ue[0] = $pw;
        $new_ue[1] = $ue[1] or $new_ue[1] = EWIKI_REGISTERED_LEVEL;
        if ($new_pw = $_REQUEST["new_pw"]) {
            if ($new_pw == $_REQUEST["new_pw2"]) {
                $new_ue[0] = md5($new_pw);
            } else {
                $o .= ewiki_t("RETYPE_PW") . "\n<br />";
                return $o;
            }
        }
        foreach ($new_ue as $i => $v) {
            $new_ue[$i] = preg_replace("/[^-@._ \\w\\d" . EWIKI_CHARS_L . EWIKI_CHARS_U . "]/", " ", $v);
        }
        #-- get user db page
        $data = ewiki_db::GET(EWIKI_USERDB_USERREGISTRY) or $data = array("id" => EWIKI_USERDB_USERREGISTRY, "version" => 1, flags => 0, "created" => time(), "lastmodified" => time(), "content" => "nobody:*:3::", "meta" => "", "author" => ewiki_author("{$user}@{$id}"));
        $data["flags"] |= EWIKI_DB_F_SYSTEM;
        $list = explode("\n", $data["content"]);
        #-- update entry
        ksort($new_ue);
        $new_ue = $user . ":" . implode(":", $new_ue);
        $found = 0;
        foreach ($list as $i => $line) {
            $line = trim($line);
            if (strtok($line, ":") == $user) {
                $list[$i] = $new_ue;
                $found = 1;
            }
        }
        if (!$found) {
            $list[] = $new_ue;
        }
        #-- save back
        $data["content"] = implode("\n", $list);
        $retry = 3;
        while ($retry--) {
            $data["version"]++;
            if ($ok = ewiki_db::WRITE($data)) {
                break;
            }
        }
        if ($ok) {
            $o .= ewiki_t("Data saved") . "\n<br />";
        } else {
            $o .= ewiki_t("Error saving") . "\n<br />";
            ewiki_log("_userdb_userregistry: failed to update db for user {$user}, retries={$retry}", 2);
        }
        #-- fallthru to view_settings
        $_REQUEST["userreg_login"] = 1;
        $ue = ewiki_auth_userdb_userregistry($user);
    }
    #-- view settings ----------------------------------------------------
    if ($_REQUEST["userreg_login"]) {
        #-- edit <form>
        $o .= ewiki_t(<<<END
<h4>_{Account Settings}</h4>
<form action="{$url}" method="POST" enctype="multipart/form-data" accept-encoding="ISO-8859-1">
<input type="hidden" name="userreg_name" value="{$user}">
<input type="hidden" name="userreg_pw" value="{$pw}">
<b>_{change password}</b><br />
_{new password} <input type="password" size="10" maxsize="12" name="new_pw" value=""> <br />
_{retype} <input type="password" size="10" maxsize="12" name="new_pw2" value=""> <br />
<br />
<b>_{optional infos}</b><br />
_{personal WikiPage} <input type="text" name="userreg_ue[2]" value="{$ue[2]}"><br />
_{email address} <input type="text" name="userreg_ue[3]" value="{$ue[3]}"><br />
<!--
opt string <input type="text" name="userreg_ue[4]" value="{$ue[4]}"><br />
opt string <input type="text" name="userreg_ue[5]" value="{$ue[5]}"><br />
opt string <input type="text" name="userreg_ue[6]" value="{$ue[6]}"><br />
-->
<br />
<input type="submit" name="userreg_store" value="_{save}">
</form><br /><br />
END
);
    } else {
        $url = ewiki_script("", $id);
        $o .= ewiki_t(<<<END
<form action="{$url}" method="POST" enctype="multipart/form-data" accept-encoding="ISO-8859-1">
<div class="userreg-form-settings">
<div class="userreg-form-register">
_{name} <input type="text" size="14" name="userreg_name"> &nbsp;
<input type="submit" name="userreg_register" value="_{create account}"><br />
</div>
<br />
_{password} <input type="password" size="10" maxsize="12" name="userreg_pw"><br />
<br />
<input type="submit" name="userreg_login" value="_{change settings}">
</div>
</form><br /><br />
END
);
    }
    return $o;
}
Ejemplo n.º 15
0
function ewiki_page_searchandreplace($id, $data, $action)
{
    global $ewiki_ring, $ewiki_plugins;
    $o = ewiki_make_title($id, $id, 2);
    #-- admin requ. ---------------------------------------------------------
    if (!ewiki_auth($id, $data, $action, $ring = 1, "_FORCE_LOGIN=1") || !isset($ewiki_ring) || $ewiki_ring > 1) {
        if (is_array($data)) {
            $data = "You'll need moderator/administrator privileges to use this.";
        }
        return $o .= $data;
    }
    #-- form ----------------------------------------------------------------
    if (empty($_REQUEST["snr_go"]) && empty($_REQUEST["snr_test"])) {
        $url = ewiki_script("", $id);
        $o .= ewiki_t(<<<END
Use this form to replace all occourences of a phrase in all WikiPages.
<br /><br />
<form action="{$url}" method="POST" enctype="multipart/form-data">
search for string<br />
<input type="text" name="snr_search_string" value="" size="30"><br />
<small>this text snippet always matches case-insensitive, used as
<b>first-stage</b> search string; leave it empty to use only the regular
expression matching (slower)</small><br />
look this string up only in <select name="snr_search_string_where"><option selected="selected" value="content">page content / body</option> <option value="id">page name / title</option></select><br />
<br />
<i>and/or</i> with <tt>/Perl/i</tt> regular expression<br />
<input type="text" name="snr_search_regex" value="" size="30"><br />
<small>this is <b>optional</b>, and is anyhow only used as second-stage search
pattern; if used allows to use regex backreferences in the replacement
string field</small><br />
<br />
then replace with string<br />
<input type="text" name="snr_replace" value="" size="30"><br />
<small>can contain backreferences  and \$1 if the regex search field was
used</small><br />
<br />
<input type="submit" name="snr_test" value="dry run / test regex"> &nbsp;
<input type="submit" name="snr_go" value="Replace All">
</form>
<br />
<br />
The regular expression matching is optional, you'll often only need the
simple string search field and another simple string in the replacement
field.
<br />
<br />
Please note, that this form allows to initially search for a simple string,
but you can leave this empty and only use a regex search. And as it is a
two stage searching, both patterns can be completely different.
<br />
<br />
Text replacement always happens in the WikiPages body, even if the simple
search string can be used to search for page names - if you do so, you
certainly need a second regular expression pattern for content replacement.
<br />
END
);
    } else {
        $do = $_REQUEST["snr_go"];
        #-- prepare vars
        $search_where = $_REQUEST["snr_search_string_where"];
        $search_string = $_REQUEST["snr_search_string"];
        $search_regex = $_REQUEST["snr_search_regex"];
        $replacement = $_REQUEST["snr_replace"];
        if ($search_string == "*") {
            $search_string = "";
        }
        $search_string2 = preg_quote($search_string, "/");
        $replacement2 = addcslashes($replacement, "\$");
        #-- security check in search_regex
        if (preg_match('/([\\w\\s]+)$/', $search_regex, $uu) && strstr($uu[0], "e")) {
            ewiki_log("use of regex '{$search_regex}' could be security circumvention attempt", 1);
            return $o . "wrong regex delimiter";
        }
        #-- complain
        if (empty($search_string) && empty($search_regex) || empty($replacement)) {
            return $o . "too few parameters, needs at least one search and a replacement string";
        }
        #-- initial database string search
        if (empty($search_string)) {
            $result = ewiki_db::GETALL(array("id", "version", "flags"));
        } else {
            $result = ewiki_db::SEARCH($search_where, $search_string);
        }
        #-- walk through pages
        while ($row = $result->get()) {
            #-- skip binary entries
            if (EWIKI_DB_F_TEXT != ($row["flags"] & EWIKI_DB_F_TYPE)) {
                continue;
            }
            $id = $row["id"];
            $save = false;
            $row = ewiki_db::GET($id);
            /*
               if (!ewiki_auth($id, $row, "edit", ...
               ...
            */
            if ($search_regex) {
                if (preg_match($search_regex, $row[$search_where], $uu)) {
                    $save = true;
                    $row["content"] = preg_replace($search_regex, $replacement, $row["content"]);
                }
            } elseif ($search_string) {
                if (stristr($row[$search_where], $search_string)) {
                    $save = true;
                    $row["content"] = preg_replace("/{$search_string2}/i", $replacement, $row["content"]);
                }
            }
            if ($save) {
                $o .= "· <a href=\"" . ewiki_script("", $id) . "\">" . htmlentities($id) . "</a> matched given search pattern<br />\n";
                if ($do) {
                    $row["lastmodified"] = time();
                    $row["author"] = ewiki_author("SearchAndReplace");
                    $row["version"]++;
                    if (ewiki_db::WRITE($row)) {
                        $o .= "&nbsp; changed.<br />\n";
                    } else {
                        $o .= "&nbsp; database store error<br />\n";
                        $o .= "&nbsp; " . mysql_error() . "<br />\n";
                    }
                }
            }
        }
        #-- while $result
        if ($do) {
            ewiki_log("SearchAndReplace for '{$search_strinmg}' and '{$search_regex}' to replace with '{$replacement}'");
        }
    }
    return $o;
}
Ejemplo n.º 16
0
/**
 * Allows for removal of LiveUser entities. The supplied entity name must be one
 * of the following: language, application; area; right; group; or user. These
 * types imply that the id parameter is in the form of the entity name. To
 * denote the id parameter as an entity numeric id, the suffix '_id' should be
 * appended to the names. This function expects the following global variables:
 *
 *      $liveuserAuthAdmin (of type LiveUser_Admin_Auth_Container_DB)
 *      $liveuserPermAdmin (of type LiveUser_Admin_Perm_Container_DB_Complex)
 *
 * @param string type name of entity type to remove
 * @param mixed id integer id or unique name of entity to remove depending on type
 * @return true if the entity existed and was removed, false otherwise
 */
function liveuser_removeEntity($type, $id)
{
    global $liveuserDB, $liveuserConfig, $liveuserAuthAdmin, $liveuserPermAdmin;
    switch ($type) {
        // special case, remove user to both auth and perm containers
        case 'user':
        case 'user_id':
            // log removed users with ewiki_log
            if (($auth_id = liveuser_checkEntity($type, $id)) !== false && ($perm_id = liveuser_getPermUserId('user_id', $auth_id)) !== false) {
                // fetch authTable names
                $authTable = $liveuserConfig['authContainers'][0]['authTable'];
                // backup user preferences and groups of user being removed
                $backup['prefs'] = $liveuserDB->getAll('SELECT ' . LW_PREFIX . '_prefs_fields.field_name, ' . LW_PREFIX . '_prefs_data.field_value
                        FROM ' . LW_PREFIX . '_prefs_fields, ' . LW_PREFIX . '_prefs_data
                        WHERE ' . LW_PREFIX . '_prefs_data.user_id = ? AND ' . LW_PREFIX . '_prefs_data.field_id = ' . LW_PREFIX . '_prefs_fields.field_id', array((int) $perm_id));
                // direct sql required to fetch group_define_name
                $backup['groups'] = $liveuserDB->getAll('SELECT liveuser_groups.group_define_name
                        FROM liveuser_groups, liveuser_groupusers
                        WHERE liveuser_groupusers.perm_user_id = ? AND liveuser_groupusers.group_id = liveuser_groups.group_id', array((int) $perm_id));
                // output serialized data to log file
                $handle = $liveuserDB->getOne('SELECT handle FROM ! WHERE auth_user_id = ?', array($authTable, (int) $auth_id));
                ewiki_log('liveuser: removed user: '******'|' . serialize($backup), 1);
                // remove records of user in auth/perm containers and the user's preferences
                if ($liveuserPermAdmin->removeUser($perm_id) !== true) {
                    return false;
                }
                if ($liveuserAuthAdmin->removeUser($auth_id) !== true) {
                    return false;
                }
                return $liveuserDB->query('DELETE FROM ' . LW_PREFIX . '_prefs_data WHERE ' . LW_PREFIX . '_prefs_data.user_id = ?', array((int) $perm_id)) == DB_OK;
            }
            return false;
            break;
            // common cases, fetch unique name from arguments and proceed
        // common cases, fetch unique name from arguments and proceed
        case 'language':
        case 'application':
        case 'area':
        case 'right':
        case 'group':
            if (($entityId = liveuser_checkEntity($type, $id)) !== false) {
                if (call_user_func_array(array(&$liveuserPermAdmin, 'remove' . $type), $entityId) !== true) {
                    return false;
                }
                return true;
            }
            return false;
            break;
        case 'language_id':
        case 'application_id':
        case 'area_id':
        case 'right_id':
        case 'group_id':
            if (($entityId = liveuser_checkEntity($type, $id)) !== false) {
                if (call_user_func_array(array(&$liveuserPermAdmin, 'remove' . substr($type, 0, -3)), $entityId) !== true) {
                    return false;
                }
                return true;
            }
            return false;
            break;
            // failure case, unknown type or no match for entity
        // failure case, unknown type or no match for entity
        default:
            return false;
            break;
    }
}
Ejemplo n.º 17
0
function ewiki_initialization_wizard($id, &$data, &$action)
{
    global $ewiki_plugins;
    #-- proceed only if frontpage missing or explicetely requested
    if (strtolower($id) == "wikisetupwizard" || $id == EWIKI_PAGE_INDEX && $action == "edit" && empty($data["version"]) && !$_REQUEST["abort"]) {
        if ($_REQUEST["abort"]) {
        } elseif (empty($_REQUEST["init"])) {
            $o = "<h2>WikiSetupWizard</h2>\n";
            $o .= "You don't have any pages in your Wiki yet, so we should try to read-in the default ones from <tt>init-pages/</tt> now.<br /><br />";
            $o .= '<a href="' . ewiki_script("", $id, array("init" => "now")) . '">[InitializeWikiDatabase]</a>';
            $o .= " &nbsp; ";
            $o .= '<a href="' . ewiki_script("", $id, array("abort" => "this")) . '">[NoThanks]</a>';
            $o .= "<br /><br />";
            #-- analyze and print settings and misconfigurations
            $pf_db = $ewiki_plugins["database"][0];
            $db = substr("_{$pf_db}", strrpos($pf_db, "_") + 1);
            $o .= '<table border="0" width="90%" class="diagnosis">';
            $o .= '<tr><td>DatabaseBackend</td><td>';
            $o .= "<b>" . $db . "</b><br />";
            if ($db == "files" || strstr($db, "f2")) {
                $o .= "<small>_DBFILES_DIR='</small><tt>" . EWIKI_DBFILES_DIRECTORY . "'</tt>";
                if (strpos(EWIKI_DBFILES_DIRECTORY, "tmp")) {
                    $o .= "<br /><b>Warning</b>: Storing your pages into a temporary directory is not what you want (there they would get deleted randomly), except for testing purposes of course. See the README.";
                }
            } else {
                $o .= "(looks ok)";
            }
            $o .= "</td></tr>";
            $o .= '<tr><td>WikiSoftware</td><td>ewiki ' . EWIKI_VERSION . "</td></tr>";
            $o .= "</table>";
            #-- more diagnosis
            if (ini_get("magic_quotes")) {
                $o .= "<b>Warning</b>: Your PHP interpreter has enabled the ugly and outdated '<i>magic_quotes</i>'. This will lead to problems, so please ask your provider to correct it; or fix it yourself with .htaccess settings as documented in the README. Otherwise don't forget to include() the <tt>fragments/strip_wonderful_slashes.php</tt> (it's ok to proceed for the moment).<br /><br />";
            }
            if (ini_get("register_globals")) {
                $o .= "<b>Security warning</b>: The horrible '<i>register_globals</i>' setting is enabled. Without always using <tt>fragments/strike_register_globals.php</tt> or letting your provider fix that, you could get into trouble some day.<br /><br />";
            }
            return '<div class="wiki view WikiSetupWizard">' . $o . '</div>';
        } else {
            ewiki_db::INIT();
            if ($dh = @opendir($path = EWIKI_INIT_PAGES)) {
                while ($filename = readdir($dh)) {
                    if (preg_match('/^([' . EWIKI_CHARS_U . ']+[' . EWIKI_CHARS_L . ']+\\w*)+/', $filename)) {
                        $found = ewiki_db::FIND(array($filename));
                        if (!$found[$filename]) {
                            $content = implode("", file("{$path}/{$filename}"));
                            ewiki_scan_wikiwords($content, $ewiki_links, "_STRIP_EMAIL=1");
                            $refs = "\n\n" . implode("\n", array_keys($ewiki_links)) . "\n\n";
                            $save = array("id" => "{$filename}", "version" => "1", "flags" => "1", "content" => $content, "author" => ewiki_author("ewiki_initialize"), "refs" => $refs, "lastmodified" => filemtime("{$path}/{$filename}"), "created" => filectime("{$path}/{$filename}"));
                            ewiki_db::WRITE($save);
                        }
                    }
                }
                closedir($dh);
                ewiki_log("initializing database", 0);
            } else {
                return "<b>ewiki error</b>: could not read from directory " . realpath($path) . "<br />\n";
            }
            #-- try to view/ that newly inserted page
            if ($data = ewiki_db::GET($id)) {
                $action = "view";
            }
            #-- let ewiki_page() proceed as usual
            return "";
        }
    }
}
Ejemplo n.º 18
0
function ewiki_database($action, $args, $sw1 = 0, $sw2 = 0, $pf = false)
{
    #-- normalize (fetch bad parameters)
    if ($action == "GET" && !is_array($args) && is_string($args)) {
        $args = array("id" => $args);
    }
    #-- treat special
    switch ($action) {
        case "GETALL":
            $args = array_unique(@array_merge($args, array("flags", "version")));
            $args = array_diff($args, array("id"));
            break;
        case "SEARCH":
            #         unset($args["version"]);
            #         unset($args["flags"]);
            break;
        default:
            break;
    }
    #-- handle {meta} sub array as needed
    if (is_array(@$args["meta"])) {
        $args["meta"] = serialize($args["meta"]);
    }
    #-- database plugin
    if ($pf || ($pf = @$GLOBALS["ewiki_plugins"]["database"][0])) {
        $r = $pf($action, $args, $sw1, $sw2);
    } else {
        ewiki_log("DB layer: no backend!", 0);
        $r = false;
    }
    #-- database layer generation 2 abstraction
    if (is_array($r) && ($action == "SEARCH" || $action == "GETALL")) {
        $z = new ewiki_dbquery_result(array_keys($args));
        foreach ($r as $id => $row) {
            $z->add($row);
        }
        $r = $z;
    }
    #-- extract {meta} sub array
    if (is_array($r) && !is_array(@$r["meta"]) && strlen(@$r["meta"])) {
        $r["meta"] = unserialize($r["meta"]);
    }
    return $r;
}
Ejemplo n.º 19
0
function ewiki_shutdown_referer_log($id, &$data, $action, $args = NULL)
{
    global $ewiki_config;
    $iw = $ewiki_config["interwiki"];
    #-- the referer url
    $ref = strtok($_SERVER["HTTP_REFERER"], "# ");
    $this1 = EWIKI_SERVER . $_SERVER["REQUEST_URI"];
    $this2 = ewiki_script("", $id);
    #-- pattern of ourselfs
    $host = $_SERVER["HTTP_HOST"];
    $pat = substr($host, strpos($host, ".") + 1);
    if (!strpos($pat, ".")) {
        $pat = $host;
    }
    #-- reject if self-referring
    if (strpos($ref, $host) || strpos($ref, $_SERVER["SERVER_NAME"])) {
        return false;
    }
    #-- reject search engine links
    if (strpos($ref, "?") && strpos($ref, "q=")) {
        return false;
    }
    #-- link already on page?
    $sref = trim($ref, "/");
    $sref = substr($sref, strpos($sref, ".") + 1);
    $sref = strtolower($sref);
    if (strpos(strtolower($data["refs"]), $sref)) {
        return false;
    }
    #-- forgery test 1
    if (strpos(urldecode($ref), $pat) || strpos(urldecode(urldecode($ref)), $pat)) {
        ewiki_log("forged REFERER '{$ref}' to {$this1}");
        return -1;
    }
    #-- already banned?
    if (function_exists("ewiki_banned_link") && ewiki_banned_link($ref)) {
        ewiki_log("banned REFERER '{$ref}' to {$this1}");
        return -1;
    }
    #-- special cases
    if (!strpos(trim(substr($ref, 10), "/"), "/")) {
        $likely_fake = 1;
        // link from server root dir?
    } elseif (strpos($ref, "slashdot")) {
        $from_sd = 1;
    }
    #-- decode InterWiki URLs into "prefix:PageName" representation
    if ($link = ewiki_url2wiki($ref)) {
        if (stristr($data["refs"], $link)) {
            // already in page
            return false;
        }
    } else {
        $link = $ref;
    }
    #-- retrieve page to check for link existence
    $R = ewiki_http_query("GET", $ref, NULL, array(), "cookies.txt");
    if (!stristr($R[0], $this1) && !stristr($R[0], $this2) && !strpos($R[0], EWIKI_NAME . ":{$id}")) {
        ewiki_log("faked REFERER '{$ref}' to {$this1}");
        if ($likely_fake && ($abuse = $_SERVER["HTTP_FROM"])) {
            mail($abuse, "REFERER Header Abuse", "Dear 'search-engine' maintainer,\n\nYou misused the HTTP Referer: header for marketing purposes.\nThis informational mail is meant to annoy you likewise.\n\n", "X-From: {$_SERVER['SERVER_ADMIN']}\nX-Mailer: ewiki:refererlog\n");
        }
        return -1;
    }
    #-- all tests passed, add link
    $data = ewiki_db::GET($id);
    if ($data["version"]++) {
        $data["content"] = trim($data["content"]) . "\n- {$link}\n";
        ewiki_data_update($data);
        $data["author"] = "RefererLog; " . $data["author"];
        if (!EWIKI_REFERER_NOISE) {
            $data["flags"] |= EWIKI_DB_F_MINOR;
        }
        ewiki_db::WRITE($data);
    }
}