Ejemplo n.º 1
0
 public function handle_ajax_call()
 {
     global $INPUT;
     header('Content-Type: text/plain');
     $langCode = $INPUT->str('lang');
     $text = $INPUT->str('text');
     $dir = DOKU_CONF . 'lang/' . $langCode;
     $file = $dir . '/register.txt';
     // make sure the directory exists
     if (!file_exists($dir)) {
         if (mkdir($dir, 0755) === false) {
             echo $this->getLang('makeDirError');
             return;
         }
     }
     // save the file
     if (file_put_contents($file, $text) === false) {
         echo $this->getLang('saveFileError');
         return;
     }
     // set file permissions
     chmod($file, 0644);
     // log the change
     $timestamp = time();
     $id = $langCode . ':register';
     addLogEntry($timestamp, $id);
     // save this revision in the attic
     $atticFile = wikiFN($id, $timestamp, true);
     io_saveFile($atticFile, $text, false);
     // send OK to the browser
     echo 'OK';
 }
Ejemplo n.º 2
0
 /**
  * @param Doku_Event $event  event object by reference
  * @param mixed      $param  [the parameters passed as fifth argument to register_hook() when this
  *                           handler was registered]
  * @return void
  */
 public function handle_ajax_call_unknown(Doku_Event &$event, $param)
 {
     if ($event->data !== 'door43_register_edit') {
         return;
     }
     //no other action handlers needed
     $event->stopPropagation();
     $event->preventDefault();
     global $INPUT;
     header('Content-Type: text/plain');
     $langCode = $INPUT->str('lang');
     $text = $INPUT->str('text');
     $dir = DOKU_CONF . 'lang/' . $langCode;
     $file = $dir . '/register.txt';
     // make sure the directory exists
     if (!file_exists($dir)) {
         if (mkdir($dir, 0755) === false) {
             echo $this->getLang('makeDirError');
             return;
         }
     }
     // save the file
     if (file_put_contents($file, $text) === false) {
         echo $this->getLang('saveFileError');
         return;
     }
     // set file permissions
     chmod($file, 0644);
     // log the change
     $timestamp = time();
     $id = $langCode . ':register';
     addLogEntry($timestamp, $id);
     // save this revision in the attic
     $atticFile = wikiFN($id, $timestamp, true);
     io_saveFile($atticFile, $text, false);
     // send OK to the browser
     echo 'OK';
 }
Ejemplo n.º 3
0
/**
 * Handles features defined in config.inc.php
 *
 * @since 1.2
 * @package facileManager
 */
function handleHiddenFlags()
{
    global $fm_name;
    /** Recover authentication in case of lockout */
    if (defined('FM_NO_AUTH') && FM_NO_AUTH) {
        setOption('auth_method', 0);
        @addLogEntry(_('Manually reset authentication method.'), $fm_name);
    }
}
Ejemplo n.º 4
0
/**
 * Saves a wikitext by calling io_writeWikiPage.
 * Also directs changelog and attic updates.
 *
 * @author Andreas Gohr <*****@*****.**>
 * @author Ben Coburn <*****@*****.**>
 */
function saveWikiText($id, $text, $summary, $minor = false)
{
    /* Note to developers:
         This code is subtle and delicate. Test the behavior of
         the attic and changelog with dokuwiki and external edits
         after any changes. External edits change the wiki page
         directly without using php or dokuwiki.
      */
    global $conf;
    global $lang;
    global $REV;
    // ignore if no changes were made
    if ($text == rawWiki($id, '')) {
        return;
    }
    $file = wikiFN($id);
    $old = @filemtime($file);
    // from page
    $wasRemoved = empty($text);
    $wasCreated = !@file_exists($file);
    $wasReverted = $REV == true;
    $newRev = false;
    $oldRev = getRevisions($id, -1, 1, 1024);
    // from changelog
    $oldRev = (int) (empty($oldRev) ? 0 : $oldRev[0]);
    if (!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old >= $oldRev) {
        // add old revision to the attic if missing
        saveOldRevision($id);
        // add a changelog entry if this edit came from outside dokuwiki
        if ($old > $oldRev) {
            addLogEntry($old, $id);
            // send notify mails
            notify($id, 'admin', $oldRev, '', false);
            notify($id, 'subscribers', $oldRev, '', false);
            // remove soon to be stale instructions
            $cache = new cache_instructions($id, $file);
            $cache->removeCache();
        }
    }
    if ($wasRemoved) {
        // pre-save deleted revision
        @touch($file);
        clearstatcache();
        $newRev = saveOldRevision($id);
        // remove empty file
        @unlink($file);
        // remove old meta info...
        $mfiles = metaFiles($id);
        $changelog = metaFN($id, '.changes');
        foreach ($mfiles as $mfile) {
            // but keep per-page changelog to preserve page history
            if (@file_exists($mfile) && $mfile !== $changelog) {
                @unlink($mfile);
            }
        }
        $del = true;
        // autoset summary on deletion
        if (empty($summary)) {
            $summary = $lang['deleted'];
        }
        // remove empty namespaces
        io_sweepNS($id, 'datadir');
        io_sweepNS($id, 'mediadir');
    } else {
        // save file (namespace dir is created in io_writeWikiPage)
        io_writeWikiPage($file, $text, $id);
        // pre-save the revision, to keep the attic in sync
        $newRev = saveOldRevision($id);
        $del = false;
    }
    // select changelog line type
    $extra = '';
    $type = 'E';
    if ($wasReverted) {
        $type = 'R';
        $extra = $REV;
    } else {
        if ($wasCreated) {
            $type = 'C';
        } else {
            if ($wasRemoved) {
                $type = 'D';
            } else {
                if ($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) {
                    $type = 'e';
                }
            }
        }
    }
    //minor edits only for logged in users
    addLogEntry($newRev, $id, $type, $summary, $extra);
    // send notify mails
    notify($id, 'admin', $old, $summary, $minor);
    notify($id, 'subscribers', $old, $summary, $minor);
    // update the purgefile (timestamp of the last time anything within the wiki was changed)
    io_saveFile($conf['cachedir'] . '/purgefile', time());
}
Ejemplo n.º 5
0
/**
 * Saves a wikitext by calling io_writeWikiPage.
 * Also directs changelog and attic updates.
 *
 * @author Andreas Gohr <*****@*****.**>
 * @author Ben Coburn <*****@*****.**>
 *
 * @param string $id       page id
 * @param string $text     wikitext being saved
 * @param string $summary  summary of text update
 * @param bool   $minor    mark this saved version as minor update
 */
function saveWikiText($id, $text, $summary, $minor = false)
{
    /* Note to developers:
         This code is subtle and delicate. Test the behavior of
         the attic and changelog with dokuwiki and external edits
         after any changes. External edits change the wiki page
         directly without using php or dokuwiki.
       */
    global $conf;
    global $lang;
    global $REV;
    /* @var Input $INPUT */
    global $INPUT;
    // prepare data for event
    $svdta = array();
    $svdta['id'] = $id;
    $svdta['file'] = wikiFN($id);
    $svdta['revertFrom'] = $REV;
    $svdta['oldRevision'] = @filemtime($svdta['file']);
    $svdta['newRevision'] = 0;
    $svdta['newContent'] = $text;
    $svdta['oldContent'] = rawWiki($id);
    $svdta['summary'] = $summary;
    $svdta['contentChanged'] = $svdta['newContent'] != $svdta['oldContent'];
    $svdta['changeInfo'] = '';
    $svdta['changeType'] = DOKU_CHANGE_TYPE_EDIT;
    $svdta['sizechange'] = null;
    // select changelog line type
    if ($REV) {
        $svdta['changeType'] = DOKU_CHANGE_TYPE_REVERT;
        $svdta['changeInfo'] = $REV;
    } else {
        if (!file_exists($svdta['file'])) {
            $svdta['changeType'] = DOKU_CHANGE_TYPE_CREATE;
        } else {
            if (trim($text) == '') {
                // empty or whitespace only content deletes
                $svdta['changeType'] = DOKU_CHANGE_TYPE_DELETE;
                // autoset summary on deletion
                if (blank($svdta['summary'])) {
                    $svdta['summary'] = $lang['deleted'];
                }
            } else {
                if ($minor && $conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
                    //minor edits only for logged in users
                    $svdta['changeType'] = DOKU_CHANGE_TYPE_MINOR_EDIT;
                }
            }
        }
    }
    $event = new Doku_Event('COMMON_WIKIPAGE_SAVE', $svdta);
    if (!$event->advise_before()) {
        return;
    }
    // if the content has not been changed, no save happens (plugins may override this)
    if (!$svdta['contentChanged']) {
        return;
    }
    detectExternalEdit($id);
    if ($svdta['changeType'] == DOKU_CHANGE_TYPE_CREATE || $svdta['changeType'] == DOKU_CHANGE_TYPE_REVERT && !file_exists($svdta['file'])) {
        $filesize_old = 0;
    } else {
        $filesize_old = filesize($svdta['file']);
    }
    if ($svdta['changeType'] == DOKU_CHANGE_TYPE_DELETE) {
        // Send "update" event with empty data, so plugins can react to page deletion
        $data = array(array($svdta['file'], '', false), getNS($id), noNS($id), false);
        trigger_event('IO_WIKIPAGE_WRITE', $data);
        // pre-save deleted revision
        @touch($svdta['file']);
        clearstatcache();
        $data['newRevision'] = saveOldRevision($id);
        // remove empty file
        @unlink($svdta['file']);
        $filesize_new = 0;
        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
        // purge non-persistant meta data
        p_purge_metadata($id);
        // remove empty namespaces
        io_sweepNS($id, 'datadir');
        io_sweepNS($id, 'mediadir');
    } else {
        // save file (namespace dir is created in io_writeWikiPage)
        io_writeWikiPage($svdta['file'], $svdta['newContent'], $id);
        // pre-save the revision, to keep the attic in sync
        $svdta['newRevision'] = saveOldRevision($id);
        $filesize_new = filesize($svdta['file']);
    }
    $svdta['sizechange'] = $filesize_new - $filesize_old;
    $event->advise_after();
    addLogEntry($svdta['newRevision'], $svdta['id'], $svdta['changeType'], $svdta['summary'], $svdta['changeInfo'], null, $svdta['sizechange']);
    // send notify mails
    notify($svdta['id'], 'admin', $svdta['oldRevision'], $svdta['summary'], $minor);
    notify($svdta['id'], 'subscribers', $svdta['oldRevision'], $svdta['summary'], $minor);
    // update the purgefile (timestamp of the last time anything within the wiki was changed)
    io_saveFile($conf['cachedir'] . '/purgefile', time());
    // if useheading is enabled, purge the cache of all linking pages
    if (useHeading('content')) {
        $pages = ft_backlinks($id, true);
        foreach ($pages as $page) {
            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
            $cache->removeCache();
        }
    }
}
Ejemplo n.º 6
0
 /**
  * Backs up the database
  *
  * @since 1.0
  * @package facileManager
  */
 function backupDatabase()
 {
     global $__FM_CONFIG, $fm_name;
     if (!currentUserCan('run_tools')) {
         return sprintf('<p class="error">%s</p>', _('You are not authorized to run these tools.'));
     }
     /** Temporary fix for MySQL 5.6 warnings */
     $exclude_warnings = array('Warning: Using a password on the command line interface can be insecure.' . "\n");
     $curdate = date("Y-m-d_H.i.s");
     $sql_file = sys_get_temp_dir() . '/' . $__FM_CONFIG['db']['name'] . '_' . $curdate . '.sql';
     $error_log = str_replace('.sql', '.err', $sql_file);
     $mysqldump = findProgram('mysqldump');
     if (!$mysqldump) {
         return sprintf('<p class="error">' . _('mysqldump is not found on %s.') . '</p>', php_uname('n'));
     }
     $command_string = "{$mysqldump} --opt -Q -h {$__FM_CONFIG['db']['host']} -u {$__FM_CONFIG['db']['user']} -p{$__FM_CONFIG['db']['pass']} {$__FM_CONFIG['db']['name']} > " . sys_get_temp_dir() . "/{$__FM_CONFIG['db']['name']}_{$curdate}.sql 2>{$error_log}";
     @system($command_string, $retval);
     $retarr = @file_get_contents($error_log);
     if ($retval) {
         @unlink($error_log);
         @unlink($sql_file);
         return '<p class="error">' . nl2br(str_replace($exclude_warnings, '', $retarr)) . '</p>';
     }
     compressFile($sql_file, @file_get_contents($sql_file));
     @unlink($error_log);
     @unlink($sql_file);
     addLogEntry(_('Backed up the database.'), $fm_name);
     sendFileToBrowser($sql_file . '.gz');
 }
Ejemplo n.º 7
0
 /**
  *  test editor entry and external edit
  */
 function test_editor_and_externaledits()
 {
     global $ID, $conf;
     $ID = 'wiki:syntax';
     $filename = $conf['datadir'] . '/wiki/syntax.txt';
     $rev = filemtime($filename);
     $info = $this->_get_expected_pageinfo();
     $info['id'] = 'wiki:syntax';
     $info['namespace'] = 'wiki';
     $info['filepath'] = $filename;
     $info['exists'] = true;
     $info['lastmod'] = $rev;
     $info['currentrev'] = $rev;
     $info['meta'] = p_get_metadata($ID);
     // need $INFO set correctly for addLogEntry()
     global $INFO;
     $INFO = $info;
     // add an editor for the current version of $ID
     addLogEntry($rev, $ID);
     $info['meta'] = p_get_metadata($ID);
     $info['editor'] = $_SERVER['REMOTE_USER'];
     $info['user'] = $_SERVER['REMOTE_USER'];
     $info['ip'] = $_SERVER['REMOTE_ADDR'];
     $info['sum'] = '';
     // with an editor ...
     $this->assertEquals($info, pageinfo());
     // clear the meta['last_change'] value, pageinfo should restore it
     p_set_metadata($ID, array('last_change' => false));
     $this->assertEquals($info, pageinfo());
     $this->assertEquals($info['meta']['last_change'], p_get_metadata($ID, 'last_change'));
     // fake an external edit, pageinfo should clear the last change from meta data
     // and not return any editor data
     $now = time() + 10;
     touch($filename, $now);
     $info['lastmod'] = $now;
     $info['currentrev'] = $now;
     $info['meta']['last_change'] = false;
     $info['ip'] = null;
     $info['user'] = null;
     $info['sum'] = null;
     $info['editor'] = null;
     $this->assertEquals($info, pageinfo());
     $this->assertEquals($info['meta'], p_get_metadata($ID));
     // check metadata has been updated correctly
 }
Ejemplo n.º 8
0
    include ABSPATH . 'fm-modules' . DIRECTORY_SEPARATOR . $fm_name . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'class_users.php';
    switch ($_POST['action']) {
        case 'delete':
            if (isset($id)) {
                $delete_status = $fm_users->delete(sanitize($id), substr(sanitize($_POST['item_sub_type']), 0, -1));
                if ($delete_status !== true) {
                    echo $delete_status;
                } else {
                    exit('Success');
                }
            }
            break;
        case 'edit':
            if (isset($_POST['item_status'])) {
                if (!updateStatus('fm_users', $id, 'user_', sanitize($_POST['item_status']), 'user_id')) {
                    exit(sprintf(_('This user could not be set to %s.') . "\n", $_POST['item_status']));
                } else {
                    $tmp_name = getNameFromID($id, 'fm_users', 'user_', 'user_id', 'user_login');
                    addLogEntry(sprintf(_('Set user (%s) status to %s.'), $tmp_name, sanitize($_POST['item_status'])));
                    exit('Success');
                }
            }
            break;
    }
    /** Handle everything else */
} elseif (isset($_SESSION['module']) && $_SESSION['module'] != $fm_name) {
    $include_file = ABSPATH . 'fm-modules' . DIRECTORY_SEPARATOR . $_SESSION['module'] . DIRECTORY_SEPARATOR . 'ajax' . DIRECTORY_SEPARATOR . 'processPost.php';
    if (file_exists($include_file)) {
        include $include_file;
    }
}
Ejemplo n.º 9
0
 /**
  * Deletes the selected logging channel/category
  */
 function delete($id, $server_serial_no = 0, $type)
 {
     global $fmdb, $__FM_CONFIG;
     /** Check if channel is currently associated with category */
     if ($type == 'channel' && is_array($this->getAssocCategories($id))) {
         return sprintf(__('This %s could not be deleted because it is associated with one or more categories.'), $type);
     }
     $tmp_name = getNameFromID($id, 'fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'config', 'cfg_', 'cfg_id', 'cfg_data');
     /** Delete associated children */
     $query = "UPDATE `fm_{$__FM_CONFIG['fmDNS']['prefix']}config` SET `cfg_status`='deleted' WHERE `cfg_parent`={$id}";
     $fmdb->query($query);
     /** Delete item */
     if (updateStatus('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'config', $id, 'cfg_', 'deleted', 'cfg_id') === false) {
         return sprintf(__('This %s could not be deleted because a database error occurred.'), $type);
     } else {
         setBuildUpdateConfigFlag($server_serial_no, 'yes', 'build');
         addLogEntry(sprintf(__("Logging %s '%s' was deleted."), $type, $tmp_name));
         return true;
     }
 }
Ejemplo n.º 10
0
/**
 * Logs and outputs error messages
 *
 * @since 2.0
 * @package facileManager
 * @subpackage fmDNS
 *
 * @param string $last_line Output from previously run command
 * @return boolean
 */
function processReloadFailure($last_line)
{
    if ($debug) {
        echo fM($last_line);
    }
    addLogEntry($last_line);
    $message = "There was an error reloading the server - please check the logs for details\n";
    if ($debug) {
        echo fM($message);
    }
    addLogEntry($message);
    return false;
}
Ejemplo n.º 11
0
function addRequest($forimaging = 0, $revisionid = array(), $checkuser = 1)
{
    global $requestInfo, $user, $uniqid, $mysql_link_vcl;
    $startstamp = unixToDatetime($requestInfo["start"]);
    $endstamp = unixToDatetime($requestInfo["end"]);
    $now = time();
    if ($requestInfo["start"] <= $now) {
        $start = unixToDatetime($now);
        $nowfuture = "now";
    } else {
        $start = $startstamp;
        $nowfuture = "future";
    }
    addLogEntry($nowfuture, $start, $endstamp, 1, $requestInfo["imageid"]);
    $qh = doQuery("SELECT LAST_INSERT_ID() FROM log", 131);
    if (!($row = mysql_fetch_row($qh))) {
        abort(132);
    }
    $logid = $row[0];
    # add single entry to request table
    $query = "INSERT INTO request " . "(stateid, " . "userid, " . "laststateid, " . "logid, " . "forimaging, " . "start, " . "end, " . "daterequested, " . "checkuser) " . "VALUES " . "(13, " . "{$user['id']}, " . "13, " . "{$logid}, " . "{$forimaging}, " . "'{$startstamp}', " . "'{$endstamp}', " . "NOW(), " . "{$checkuser})";
    $qh = doQuery($query, 136);
    $qh = doQuery("SELECT LAST_INSERT_ID() FROM request", 134);
    if (!($row = mysql_fetch_row($qh))) {
        abort(135);
    }
    $requestid = $row[0];
    # add requestid to log entry
    $query = "UPDATE log " . "SET requestid = {$requestid} " . "WHERE id = {$logid}";
    doQuery($query, 101);
    # add an entry to the reservation table for each image
    # NOTE: make sure parent image is the first entry we add
    #   so that it has the lowest reservationid
    foreach ($requestInfo["images"] as $key => $imageid) {
        if (array_key_exists($imageid, $revisionid) && !empty($revisionid[$imageid])) {
            $imagerevisionid = array_shift($revisionid[$imageid]);
        } else {
            $imagerevisionid = getProductionRevisionid($imageid);
        }
        $computerid = $requestInfo["computers"][$key];
        $mgmtnodeid = $requestInfo['mgmtnodes'][$key];
        $fromblock = $requestInfo['fromblock'][$key];
        if ($fromblock) {
            $blockdata = $requestInfo['blockdata'][$key];
        } else {
            $blockdata = array();
        }
        addSublogEntry($logid, $imageid, $imagerevisionid, $computerid, $mgmtnodeid, $fromblock, $blockdata);
    }
    $query = "INSERT INTO reservation " . "(requestid, " . "computerid, " . "imageid, " . "imagerevisionid, " . "managementnodeid) " . "SELECT {$requestid}, " . "computerid, " . "imageid, " . "imagerevisionid, " . "managementnodeid " . "FROM semaphore " . "WHERE expires > NOW() AND " . "procid = '{$uniqid}'";
    doQuery($query);
    $cnt = mysql_affected_rows($mysql_link_vcl);
    if ($cnt == 0) {
        # reached this point SEMTIMEOUT seconds after getting semaphore, clean up and abort
        $query = "DELETE FROM request WHERE id = {$requestid}";
        doQuery($query);
        $query = "UPDATE log SET wasavailable = 0 WHERE id = {$logid}";
        doQuery($query);
        $query = "DELETE FROM sublog WHERE logid = {$logid}";
        doQuery($query);
        abort(400);
    } else {
        $query = "INSERT INTO changelog " . "(logid, " . "start, " . "end, " . "timestamp) " . "VALUES " . "({$logid}, " . "'{$start}', " . "'{$endstamp}', " . "NOW())";
        doQuery($query, 136);
    }
    // release semaphore lock
    cleanSemaphore();
    return $requestid;
}
Ejemplo n.º 12
0
/**
 * Updates the database with the db version number.
 *
 * @since 1.0
 * @package facileManager
 * @subpackage Upgrader
 */
function upgradeConfig($field, $value, $logit = true)
{
    global $fmdb;
    $query = "UPDATE `fm_options` SET option_value='{$value}' WHERE option_name='{$field}'";
    $fmdb->query($query);
    if ($fmdb->last_error) {
        echo $fmdb->last_error;
        return false;
    }
    session_id($_COOKIE['myid']);
    @session_start();
    unset($_SESSION['user']['fm_perms']);
    if ($logit) {
        include ABSPATH . 'fm-includes/version.php';
        include ABSPATH . 'fm-modules/facileManager/variables.inc.php';
        addLogEntry(sprintf(_('%s was upgraded to %s.'), $fm_name, $fm_version), $fm_name);
    }
    return true;
}
Ejemplo n.º 13
0
/**
 * Deletes specified file and directory contents
 *
 * @since 2.0.1
 * @package facileManager
 *
 * @param string $file Filename to delete
 * @param boolean $debug Debug mode or not
 * @param boolean $dryrun Whether it's a dry-run or not
 * @return boolean
 */
function deleteFile($file, $debug = false, $dryrun = false)
{
    if (is_dir($file)) {
        if ($file == '/') {
            return false;
        }
        foreach (scandir($file) as $item) {
            if (in_array($item, array('.', '..'))) {
                continue;
            }
            $full_path_file = $file . DIRECTORY_SEPARATOR . $item;
            deleteFile($full_path_file, $debug, $dryrun);
        }
    } else {
        $message = "Deleting {$file}.\n";
        if ($debug) {
            echo fM($message);
        }
        if (!$dryrun) {
            addLogEntry($message);
            unlink($file);
        }
    }
    return true;
}
Ejemplo n.º 14
0
 /**
  * Deletes the selected user
  *
  * @since 1.0
  * @package facileManager
  */
 function delete($id)
 {
     global $fm_name;
     /** Ensure user is not current LDAP template user */
     if (getOption('auth_method') == 2) {
         $template_user_id = getOption('ldap_user_template');
         if ($id == $template_user_id) {
             return _('This user is the LDAP user template and cannot be deleted at this time.');
         }
     }
     $tmp_name = getNameFromID($id, 'fm_users', 'user_', 'user_id', 'user_login');
     if (!updateStatus('fm_users', $id, 'user_', 'deleted', 'user_id')) {
         return _('This user could not be deleted.') . "\n";
     } else {
         addLogEntry(sprintf(_("Deleted user '%s'."), $tmp_name), $fm_name);
         return true;
     }
 }
Ejemplo n.º 15
0
function buildConf($url, $data)
{
    global $proto, $debug;
    if ($data['dryrun'] && $debug) {
        echo fM("Dryrun mode (nothing will be written to disk)\n\n");
    }
    $raw_data = getPostData($url, $data);
    $raw_data = $data['compress'] ? @unserialize(gzuncompress($raw_data)) : @unserialize($raw_data);
    if (!is_array($raw_data)) {
        if ($debug) {
            echo fM($raw_data);
        }
        addLogEntry($raw_data);
        exit(1);
    }
    if ($debug) {
        foreach ($raw_data['files'] as $filename => $contents) {
            echo str_repeat('=', 50) . "\n";
            echo $filename . ":\n";
            echo str_repeat('=', 50) . "\n";
            echo $contents . "\n\n";
        }
    }
    extract($raw_data, EXTR_SKIP);
    $runas = 'root';
    $chown_files = array($server_root_dir);
    /** Install the new files */
    installFiles($runas, $chown_files, $files, $data['dryrun']);
    $message = "Reloading the server\n";
    if ($debug) {
        echo fM($message);
    }
    $rc_script = str_replace('__FILE__', $server_config_file, getStartupScript($server_type));
    $message = "{$rc_script}\n";
    if ($debug) {
        echo fM($message);
    }
    if (!$data['dryrun']) {
        addLogEntry($message);
        $rc_script = str_replace('__FILE__', $server_config_file, getStartupScript($server_type));
        if ($rc_script === false) {
            $last_line = "Cannot locate the start script\n";
            if ($debug) {
                echo fM($last_line);
            }
            addLogEntry($last_line);
            $retval = true;
        } else {
            $last_line = system($rc_script . ' 2>&1', $retval);
            addLogEntry($last_line);
        }
        if ($retval) {
            $message = "There was an error reloading the firewall - please check the logs for details\n";
            if ($debug) {
                echo fM($message);
            }
            addLogEntry($message);
            return false;
        } else {
            /** Update the server with a successful reload */
            $data['action'] = 'update';
            $raw_update = getPostData($url, $data);
            $raw_update = $data['compress'] ? @unserialize(gzuncompress($raw_update)) : @unserialize($raw_update);
        }
    }
    return true;
}
Ejemplo n.º 16
0
 /**
  * Deletes the selected group
  */
 function delete($id)
 {
     global $fmdb, $__FM_CONFIG;
     // Delete group
     $tmp_name = getNameFromID($id, 'fm_' . $__FM_CONFIG['fmSQLPass']['prefix'] . 'groups', 'group_', 'group_id', 'group_name');
     if (!updateStatus('fm_' . $__FM_CONFIG['fmSQLPass']['prefix'] . 'groups', $id, 'group_', 'deleted', 'group_id')) {
         return __('This server group could not be deleted.') . "\n";
     } else {
         addLogEntry("Deleted server group '{$tmp_name}'.");
         return true;
     }
 }
Ejemplo n.º 17
0
            $response = $fm_users->update($_POST);
            if ($response !== true) {
                $form_data = $_POST;
            } else {
                header('Location: ' . $GLOBALS['basename']);
            }
        }
        if (isset($_GET['status'])) {
            if ($_GET['id'] == 1) {
                $_GET['id'] = 0;
            }
            $user_info = getUserInfo($_GET['id']);
            if ($user_info) {
                if ($user_info['user_template_only'] == 'no') {
                    if (updateStatus('fm_users', $_GET['id'], 'user_', $_GET['status'], 'user_id')) {
                        addLogEntry(sprintf(_("Set user '%s' status to %s."), $user_info['user_login'], $_GET['status']), $fm_name);
                        header('Location: ' . $GLOBALS['basename']);
                    }
                }
            }
            $response = sprintf(_('This user could not be set to %s.') . "\n", $_GET['status']);
        }
}
printHeader();
@printMenu();
echo printPageHeader($response, null, currentUserCan('manage_users'));
$sort_field = 'user_login';
$sort_direction = null;
if (isset($_SESSION[$_SESSION['module']][$GLOBALS['path_parts']['filename']])) {
    extract($_SESSION[$_SESSION['module']][$GLOBALS['path_parts']['filename']], EXTR_OVERWRITE);
}
Ejemplo n.º 18
0
function addRequest($forimaging = 0, $revisionid = array())
{
    global $requestInfo, $user;
    $startstamp = unixToDatetime($requestInfo["start"]);
    $endstamp = unixToDatetime($requestInfo["end"]);
    $now = time();
    if ($requestInfo["start"] <= $now) {
        $start = unixToDatetime($now);
        $nowfuture = "now";
    } else {
        $start = $startstamp;
        $nowfuture = "future";
    }
    addLogEntry($nowfuture, $start, $endstamp, 1, $requestInfo["imageid"]);
    $qh = doQuery("SELECT LAST_INSERT_ID() FROM log", 131);
    if (!($row = mysql_fetch_row($qh))) {
        abort(132);
    }
    $logid = $row[0];
    $query = "INSERT INTO changelog " . "(logid, " . "start, " . "end, " . "timestamp) " . "VALUES " . "({$logid}, " . "'{$start}', " . "'{$endstamp}', " . "NOW())";
    doQuery($query, 136);
    # add single entry to request table
    $query = "INSERT INTO request " . "(stateid, " . "userid, " . "laststateid, " . "logid, " . "forimaging, " . "start, " . "end, " . "daterequested) " . "VALUES " . "(13, " . "{$user['id']}, " . "13, " . "{$logid}, " . "{$forimaging}, " . "'{$startstamp}', " . "'{$endstamp}', " . "NOW())";
    $qh = doQuery($query, 136);
    $qh = doQuery("SELECT LAST_INSERT_ID() FROM request", 134);
    if (!($row = mysql_fetch_row($qh))) {
        abort(135);
    }
    $requestid = $row[0];
    # add requestid to log entry
    $query = "UPDATE log " . "SET requestid = {$requestid} " . "WHERE id = {$logid}";
    doQuery($query, 101);
    # add an entry to the reservation table for each image
    # NOTE: make sure parent image is the first entry we add
    #   so that it has the lowest reservationid
    foreach ($requestInfo["images"] as $key => $imageid) {
        if (array_key_exists($imageid, $revisionid) && !empty($revisionid[$imageid])) {
            $imagerevisionid = $revisionid[$imageid];
        } else {
            $imagerevisionid = getProductionRevisionid($imageid);
        }
        $computerid = $requestInfo["computers"][$key];
        $mgmtnodeid = $requestInfo['mgmtnodes'][$key];
        $query = "INSERT INTO reservation " . "(requestid, " . "computerid, " . "imageid, " . "imagerevisionid, " . "managementnodeid) " . "VALUES " . "({$requestid}, " . "{$computerid}, " . "{$imageid}, " . "{$imagerevisionid}, " . "{$mgmtnodeid})";
        doQuery($query, 133);
        addSublogEntry($logid, $imageid, $imagerevisionid, $computerid, $mgmtnodeid);
    }
    // release semaphore lock
    semUnlock();
    return $requestid;
}
Ejemplo n.º 19
0
 /**
  * Deletes the selected option
  */
 function delete($id, $server_serial_no = 0)
 {
     global $fmdb, $__FM_CONFIG;
     $tmp_name = getNameFromID($id, 'fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'config', 'cfg_', 'cfg_id', 'cfg_name');
     $tmp_server_name = $server_serial_no ? getNameFromID($server_serial_no, 'fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'servers', 'server_', 'server_serial_no', 'server_name') : 'All Servers';
     if (updateStatus('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'config', $id, 'cfg_', 'deleted', 'cfg_id') === false) {
         return __('This option could not be deleted because a database error occurred.');
     } else {
         setBuildUpdateConfigFlag($server_serial_no, 'yes', 'build');
         addLogEntry(sprintf(__("Option '%s' for %s was deleted."), $tmp_name, $tmp_server_name));
         return true;
     }
 }
Ejemplo n.º 20
0
function submitRequest()
{
    global $submitErr, $user, $viewmode, $HTMLheader, $mode, $printedHTMLheader;
    if ($mode == 'submitTestProd') {
        $data = getContinuationVar();
        $data["revisionid"] = processInputVar("revisionid", ARG_MULTINUMERIC);
        # TODO check for valid revisionids for each image
        if (!empty($data["revisionid"])) {
            foreach ($data['revisionid'] as $key => $val) {
                if (!is_numeric($val) || $val < 0) {
                    unset($data['revisionid']);
                }
            }
        }
    } else {
        $data = processRequestInput(1);
    }
    if ($submitErr) {
        $printedHTMLheader = 1;
        print $HTMLheader;
        print "<H2>New Reservation</H2>\n";
        newReservation();
        print getFooter();
        return;
    }
    // FIXME hack to make sure user didn't submit a request for an image he
    // doesn't have access to
    $resources = getUserResources(array("imageAdmin", "imageCheckOut"));
    $validImageids = array_keys($resources['image']);
    if (!in_array($data['imageid'], $validImageids)) {
        $data['imageid'] = array_shift($validImageids);
    }
    $showrevisions = 0;
    $subimages = 0;
    $images = getImages();
    $revcount = count($images[$data['imageid']]['imagerevision']);
    if ($revcount > 1) {
        $showrevisions = 1;
    }
    if ($images[$data['imageid']]['imagemetaid'] != NULL && count($images[$data['imageid']]['subimages'])) {
        $subimages = 1;
        foreach ($images[$data['imageid']]['subimages'] as $subimage) {
            $revcount = count($images[$subimage]['imagerevision']);
            if ($revcount > 1) {
                $showrevisions = 1;
            }
        }
    }
    if ($data["time"] == "now") {
        $nowArr = getdate();
        if ($nowArr["minutes"] == 0) {
            $subtract = 0;
            $add = 0;
        } elseif ($nowArr["minutes"] < 15) {
            $subtract = $nowArr["minutes"] * 60;
            $add = 900;
        } elseif ($nowArr["minutes"] < 30) {
            $subtract = ($nowArr["minutes"] - 15) * 60;
            $add = 900;
        } elseif ($nowArr["minutes"] < 45) {
            $subtract = ($nowArr["minutes"] - 30) * 60;
            $add = 900;
        } elseif ($nowArr["minutes"] < 60) {
            $subtract = ($nowArr["minutes"] - 45) * 60;
            $add = 900;
        }
        $start = time() - $subtract;
        $start -= $start % 60;
        $nowfuture = "now";
    } else {
        $add = 0;
        $hour = $data["hour"];
        if ($data["hour"] == 12) {
            if ($data["meridian"] == "am") {
                $hour = 0;
            }
        } elseif ($data["meridian"] == "pm") {
            $hour = $data["hour"] + 12;
        }
        $tmp = explode('/', $data["day"]);
        $start = mktime($hour, $data["minute"], "0", $tmp[0], $tmp[1], $tmp[2]);
        if ($start < time()) {
            $printedHTMLheader = 1;
            print $HTMLheader;
            print "<H2>New Reservation</H2>\n";
            print "<font color=\"#ff0000\">The time you requested is in the past.";
            print " Please select \"Now\" or use a time in the future.</font><br>\n";
            $submitErr = 1;
            newReservation();
            print getFooter();
            return;
        }
        $nowfuture = "future";
    }
    if ($data["ending"] == "length") {
        $end = $start + $data["length"] * 60 + $add;
    } else {
        $end = datetimeToUnix($data["enddate"]);
        if ($end % (15 * 60)) {
            $end = unixFloor15($end) + 15 * 60;
        }
    }
    // get semaphore lock
    if (!semLock()) {
        abort(3);
    }
    $availablerc = isAvailable($images, $data["imageid"], $start, $end, $data["os"]);
    $max = getMaxOverlap($user['id']);
    if ($availablerc != 0 && checkOverlap($start, $end, $max)) {
        $printedHTMLheader = 1;
        print $HTMLheader;
        print "<H2>New Reservation</H2>\n";
        if ($max == 0) {
            print "<font color=\"#ff0000\">The time you requested overlaps with ";
            print "another reservation you currently have.  You are only allowed ";
            print "to have a single reservation at any given time. Please select ";
            print "another time to use the application. If you are finished with ";
            print "an active reservation, click \"Current Reservations\", ";
            print "then click the \"End\" button of your active reservation.";
            print "</font><br><br>\n";
        } else {
            print "<font color=\"#ff0000\">The time you requested overlaps with ";
            print "another reservation you currently have.  You are allowed ";
            print "to have {$max} overlapping reservations at any given time. ";
            print "Please select another time to use the application. If you are ";
            print "finished with an active reservation, click \"Current ";
            print "Reservations\", then click the \"End\" button of your active ";
            print "reservation.</font><br><br>\n";
        }
        $submitErr = 1;
        newReservation();
        print getFooter();
        return;
    }
    // if user is owner of the image and there is a test version of the image
    #   available, ask user if production or test image desired
    if ($mode != "submitTestProd" && $showrevisions && $images[$data["imageid"]]["ownerid"] == $user["id"]) {
        #unset($data["testprod"]);
        $printedHTMLheader = 1;
        print $HTMLheader;
        print "<H2>New Reservation</H2>\n";
        if ($subimages) {
            print "This is a cluster environment. At least one image in the ";
            print "cluster has more than one version available. Please select ";
            print "the version you desire for each image listed below:<br>\n";
        } else {
            print "There are multiple versions of this environment available.  Please ";
            print "select the version you would like to check out:<br>\n";
        }
        print "<FORM action=\"" . BASEURL . SCRIPT . "\" method=post><br>\n";
        if (!array_key_exists('subimages', $images[$data['imageid']])) {
            $images[$data['imageid']]['subimages'] = array();
        }
        array_unshift($images[$data['imageid']]['subimages'], $data['imageid']);
        foreach ($images[$data['imageid']]['subimages'] as $subimage) {
            print "{$images[$subimage]['prettyname']}:<br>\n";
            print "<table summary=\"lists versions of the selected environment, one must be selected to continue\">\n";
            print "  <TR>\n";
            print "    <TD></TD>\n";
            print "    <TH>Version</TH>\n";
            print "    <TH>Creator</TH>\n";
            print "    <TH>Created</TH>\n";
            print "    <TH>Currently in Production</TH>\n";
            print "  </TR>\n";
            foreach ($images[$subimage]['imagerevision'] as $revision) {
                print "  <TR>\n";
                if (array_key_exists($subimage, $data['revisionid']) && $data['revisionid'][$subimage] == $revision['id']) {
                    print "    <TD align=center><INPUT type=radio name=revisionid[{$subimage}] value={$revision['id']} checked></TD>\n";
                } elseif ($revision['production']) {
                    print "    <TD align=center><INPUT type=radio name=revisionid[{$subimage}] value={$revision['id']} checked></TD>\n";
                } else {
                    print "    <TD align=center><INPUT type=radio name=revisionid[{$subimage}] value={$revision['id']}></TD>\n";
                }
                print "    <TD align=center>{$revision['revision']}</TD>\n";
                print "    <TD align=center>{$revision['user']}</TD>\n";
                print "    <TD align=center>{$revision['prettydate']}</TD>\n";
                if ($revision['production']) {
                    print "    <TD align=center>Yes</TD>\n";
                } else {
                    print "    <TD align=center>No</TD>\n";
                }
                print "  </TR>\n";
            }
            print "</table>\n";
        }
        $cont = addContinuationsEntry('submitTestProd', $data);
        print "<br><INPUT type=hidden name=continuation value=\"{$cont}\">\n";
        print "<INPUT type=submit value=\"Create Reservation\">\n";
        print "</FORM>\n";
        print getFooter();
        return;
    }
    if ($availablerc == -1) {
        $printedHTMLheader = 1;
        print $HTMLheader;
        print "<H2>New Reservation</H2>\n";
        print "You have requested an environment that is limited in the number ";
        print "of concurrent reservations that can be made. No further ";
        print "reservations for the environment can be made for the time you ";
        print "have selected. Please select another time to use the ";
        print "environment.<br>";
        addLogEntry($nowfuture, unixToDatetime($start), unixToDatetime($end), 0, $data["imageid"]);
        print getFooter();
    } elseif ($availablerc > 0) {
        $requestid = addRequest(0, $data["revisionid"]);
        $time = prettyLength($data["length"]);
        if ($data["time"] == "now") {
            $cdata = array('lengthchanged' => $data['lengthchanged']);
            $cont = addContinuationsEntry('viewRequests', $cdata);
            header("Location: " . BASEURL . SCRIPT . "?continuation={$cont}");
            dbDisconnect();
            exit;
        } else {
            if ($data["minute"] == 0) {
                $data["minute"] = "00";
            }
            $printedHTMLheader = 1;
            print $HTMLheader;
            print "<H2>New Reservation</H2>\n";
            if ($data["ending"] == "length") {
                if ($data['testjavascript'] == 0 && $data['lengthchanged']) {
                    print "<font color=red>NOTE: The maximum allowed reservation ";
                    print "length for this environment is {$time}, and the length of ";
                    print "this reservation has been adjusted accordingly.</font>\n";
                    print "<br><br>\n";
                }
                print "Your request to use <b>" . $images[$data["imageid"]]["prettyname"];
                print "</b> on " . prettyDatetime($start) . " for {$time} has been ";
                print "accepted.<br><br>\n";
            } else {
                print "Your request to use <b>" . $images[$data["imageid"]]["prettyname"];
                print "</b> starting " . prettyDatetime($start) . " and ending ";
                print prettyDatetime($end) . " has been accepted.<br><br>\n";
            }
            print "When your reservation time has been reached, the <strong>";
            print "Current Reservations</strong> page will have further ";
            print "instructions on connecting to the reserved computer.  If you ";
            print "would like to modify your reservation, you can do that from ";
            print "the <b>Current Reservations</b> page as well.<br>\n";
            print getFooter();
        }
    } else {
        $cdata = array('imageid' => $data['imageid'], 'length' => $data['length'], 'showmessage' => 1);
        $cont = addContinuationsEntry('selectTimeTable', $cdata);
        addLogEntry($nowfuture, unixToDatetime($start), unixToDatetime($end), 0, $data["imageid"]);
        header("Location: " . BASEURL . SCRIPT . "?continuation={$cont}");
        /*print "<H2>New Reservation</H2>\n";
        		print "The reservation you have requested is not available. You may ";
        		print "<a href=\"" . BASEURL . SCRIPT . "?continuation=$cont\">";
        		print "view a timetable</a> of free and reserved times to find ";
        		print "a time that will work for you.<br>\n";*/
    }
}
Ejemplo n.º 21
0
 /**
  * Purges the fM logs table
  *
  * @since 2.1
  * @package facileManager
  *
  * @return string
  */
 function purgeLogs()
 {
     global $fmdb, $fm_name;
     if (!currentUserCan('do_everything')) {
         return sprintf('<p class="error">%s</p>', _('You are not authorized to run these tools.'));
     }
     $query = "TRUNCATE fm_logs";
     $fmdb->query($query);
     if ($fmdb->sql_errors) {
         return $fmdb->last_error;
     }
     addLogEntry(_('Purged all logs from the database.'), $fm_name);
     return _('Purged all logs from the database.');
 }
Ejemplo n.º 22
0
/**
 * Processes account creation.
 *
 * @since 1.0
 * @package facileManager
 * @subpackage Installer
 */
function processAccountSetup($link, $database)
{
    global $fm_name;
    if (!function_exists('sanitize')) {
        require_once ABSPATH . '/fm-modules/facileManager/functions.php';
    }
    extract($_POST);
    $user = sanitize($user_login);
    $pass = sanitize($user_password);
    $email = sanitize($user_email);
    /** Ensure username and password are defined */
    if (empty($user) || empty($pass)) {
        printHeader(_('Installation'), 'install');
        exit(displayAccountSetup(_('Username and password cannot be empty.')));
    }
    $query = "INSERT INTO {$database}.fm_users (user_login, user_password, user_email, user_caps, user_ipaddr, user_status) VALUES('{$user}', password('{$pass}'), '{$email}', '" . serialize(array($fm_name => array('do_everything' => 1))) . "', '{$_SERVER['REMOTE_ADDR']}', 'active')";
    $result = mysql_query($query, $link) or die(mysql_error());
    addLogEntry(sprintf(_("Installer created user '%s'"), $user), $fm_name, $link);
}
Ejemplo n.º 23
0
 /**
  * Deletes the selected policy
  */
 function delete($policy_id, $server_serial_no)
 {
     global $fmdb, $__FM_CONFIG;
     /** Does the policy_id exist for this account? */
     basicGet('fm_' . $__FM_CONFIG[$_SESSION['module']]['prefix'] . 'policies', $policy_id, 'policy_', 'policy_id');
     if ($fmdb->num_rows) {
         /** Delete service */
         if (updateStatus('fm_' . $__FM_CONFIG[$_SESSION['module']]['prefix'] . 'policies', $policy_id, 'policy_', 'deleted', 'policy_id')) {
             setBuildUpdateConfigFlag($_REQUEST['server_serial_no'], 'yes', 'build');
             addLogEntry('Deleted policy from ' . getNameFromID($server_serial_no, 'fm_' . $__FM_CONFIG[$_SESSION['module']]['prefix'] . 'servers', 'server_', 'server_serial_no', 'server_name') . '.');
             return true;
         }
     }
     return __('This policy could not be deleted.');
 }
Ejemplo n.º 24
0
                }
            }
            break;
        case 'delete':
            if (isset($id)) {
                exit(parseAjaxOutput($post_class->delete(sanitize($id), $type, $server_serial_no)));
            }
            break;
        case 'edit':
            if (isset($_POST['item_status'])) {
                if (!updateStatus('fm_' . $table, $id, $prefix, sanitize($_POST['item_status']), $prefix . 'id')) {
                    exit(sprintf(__('This item could not be set to %s.') . "\n", $_POST['item_status']));
                } else {
                    setBuildUpdateConfigFlag($server_serial_no, 'yes', 'build');
                    $tmp_name = getNameFromID($id, 'fm_' . $table, $prefix, $prefix . 'id', $field_data);
                    addLogEntry(sprintf(__('Set %s (%s) status to %s.'), $object, $tmp_name, sanitize($_POST['item_status'])));
                    exit('Success');
                }
            }
            break;
    }
    exit;
}
echo $unpriv_message;
/**
 * Processes the array of domain ids for reload
 *
 * @since 2.0
 * @package facileManager
 * @subpackage fmDNS
 *
Ejemplo n.º 25
0
function eventoUsuarios($param, $accion)
{
    $msg = eventToMsg($accion, $param);
    addLogEntry($msg);
}
Ejemplo n.º 26
0
 /**
  * Deletes the selected object
  */
 function delete($object_id)
 {
     global $fmdb, $__FM_CONFIG;
     /** Does the object_id exist for this account? */
     basicGet('fm_' . $__FM_CONFIG[$_SESSION['module']]['prefix'] . 'objects', $object_id, 'object_', 'object_id');
     if ($fmdb->num_rows) {
         /** Is the object_id present in a policy? */
         if (isItemInPolicy($object_id, 'object')) {
             return __('This object could not be deleted because it is associated with one or more policies.');
         }
         /** Delete object */
         $tmp_name = getNameFromID($object_id, 'fm_' . $__FM_CONFIG[$_SESSION['module']]['prefix'] . 'objects', 'object_', 'object_id', 'object_name');
         if (updateStatus('fm_' . $__FM_CONFIG[$_SESSION['module']]['prefix'] . 'objects', $object_id, 'object_', 'deleted', 'object_id')) {
             addLogEntry(sprintf(__('Object (%s) was deleted.'), $tmp_name));
             return true;
         }
     }
     return __('This object could not be deleted.');
 }
Ejemplo n.º 27
0
/**
 * Saves a wikitext by calling io_writeWikiPage.
 * Also directs changelog and attic updates.
 *
 * @author Andreas Gohr <*****@*****.**>
 * @author Ben Coburn <*****@*****.**>
 */
function saveWikiText($id, $text, $summary, $minor = false)
{
    /* Note to developers:
         This code is subtle and delicate. Test the behavior of
         the attic and changelog with dokuwiki and external edits
         after any changes. External edits change the wiki page
         directly without using php or dokuwiki.
       */
    global $conf;
    global $lang;
    global $REV;
    // ignore if no changes were made
    if ($text == rawWiki($id, '')) {
        return;
    }
    $file = wikiFN($id);
    $old = @filemtime($file);
    // from page
    $wasRemoved = trim($text) == '';
    // check for empty or whitespace only
    $wasCreated = !@file_exists($file);
    $wasReverted = $REV == true;
    $newRev = false;
    $oldRev = getRevisions($id, -1, 1, 1024);
    // from changelog
    $oldRev = (int) (empty($oldRev) ? 0 : $oldRev[0]);
    if (!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old >= $oldRev) {
        // add old revision to the attic if missing
        saveOldRevision($id);
        // add a changelog entry if this edit came from outside dokuwiki
        if ($old > $oldRev) {
            addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit' => true));
            // remove soon to be stale instructions
            $cache = new cache_instructions($id, $file);
            $cache->removeCache();
        }
    }
    if ($wasRemoved) {
        // Send "update" event with empty data, so plugins can react to page deletion
        $data = array(array($file, '', false), getNS($id), noNS($id), false);
        trigger_event('IO_WIKIPAGE_WRITE', $data);
        // pre-save deleted revision
        @touch($file);
        clearstatcache();
        $newRev = saveOldRevision($id);
        // remove empty file
        @unlink($file);
        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
        // purge non-persistant meta data
        p_purge_metadata($id);
        $del = true;
        // autoset summary on deletion
        if (empty($summary)) {
            $summary = $lang['deleted'];
        }
        // remove empty namespaces
        io_sweepNS($id, 'datadir');
        io_sweepNS($id, 'mediadir');
    } else {
        // save file (namespace dir is created in io_writeWikiPage)
        io_writeWikiPage($file, $text, $id);
        // pre-save the revision, to keep the attic in sync
        $newRev = saveOldRevision($id);
        $del = false;
    }
    // select changelog line type
    $extra = '';
    $type = DOKU_CHANGE_TYPE_EDIT;
    if ($wasReverted) {
        $type = DOKU_CHANGE_TYPE_REVERT;
        $extra = $REV;
    } else {
        if ($wasCreated) {
            $type = DOKU_CHANGE_TYPE_CREATE;
        } else {
            if ($wasRemoved) {
                $type = DOKU_CHANGE_TYPE_DELETE;
            } else {
                if ($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) {
                    $type = DOKU_CHANGE_TYPE_MINOR_EDIT;
                }
            }
        }
    }
    //minor edits only for logged in users
    addLogEntry($newRev, $id, $type, $summary, $extra);
    // send notify mails
    notify($id, 'admin', $old, $summary, $minor);
    notify($id, 'subscribers', $old, $summary, $minor);
    // update the purgefile (timestamp of the last time anything within the wiki was changed)
    io_saveFile($conf['cachedir'] . '/purgefile', time());
    // if useheading is enabled, purge the cache of all linking pages
    if (useHeading('content')) {
        $pages = ft_backlinks($id);
        foreach ($pages as $page) {
            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
            $cache->removeCache();
        }
    }
}
Ejemplo n.º 28
0
 /**
  * Upgrades the client sotware
  *
  * @since 1.1
  * @package facileManager
  */
 function doClientUpgrade($serial_no)
 {
     global $fmdb, $__FM_CONFIG, $fm_name;
     /** Check permissions */
     if (!currentUserCan('manage_servers', $_SESSION['module'])) {
         echo buildPopup('header', _('Error'));
         printf('<p>%s</p>', _('You do not have permission to manage servers.'));
         echo buildPopup('footer', _('OK'), array('cancel_button' => 'cancel'));
         exit;
     }
     /** Process server group */
     if ($serial_no[0] == 'g') {
         $group_servers = $this->getGroupServers(substr($serial_no, 1));
         if (!is_array($group_servers)) {
             return $group_servers;
         }
         $response = null;
         foreach ($group_servers as $serial_no) {
             if (is_numeric($serial_no)) {
                 $response .= $this->doClientUpgrade($serial_no) . "\n";
             }
         }
         return $response;
     }
     /** Check serial number */
     basicGet('fm_' . $__FM_CONFIG[$_SESSION['module']]['prefix'] . 'servers', sanitize($serial_no), 'server_', 'server_serial_no');
     if (!$fmdb->num_rows) {
         return sprintf(_('%d is not a valid serial number.'), $serial_no);
     }
     $server_details = $fmdb->last_result;
     extract(get_object_vars($server_details[0]), EXTR_SKIP);
     $response[] = $server_name;
     if ($server_installed != 'yes') {
         $response[] = ' --> ' . _('Failed: Client is not installed.') . "\n";
     }
     if (count($response) == 1) {
         switch ($server_update_method) {
             case 'cron':
                 /* Servers updated via cron require manual upgrades */
                 $response[] = ' --> ' . _('This server needs to be upgraded manually with the following command:');
                 $response[] = " --> sudo php /usr/local/{$fm_name}/{$_SESSION['module']}/\$(ls /usr/local/{$fm_name}/{$_SESSION['module']} | grep php | grep -v functions) upgrade";
                 addLogEntry(sprintf(_('Upgraded client scripts on %s.'), $server_name));
                 break;
             case 'http':
             case 'https':
                 /** Test the port first */
                 if (!socketTest($server_name, $server_update_port, 10)) {
                     $response[] = ' --> ' . sprintf(_('Failed: could not access %s using %s (tcp/%d).'), $server_name, $server_update_method, $server_update_port);
                     break;
                 }
                 /** Remote URL to use */
                 $url = $server_update_method . '://' . $server_name . ':' . $server_update_port . '/' . $_SESSION['module'] . '/reload.php';
                 /** Data to post to $url */
                 $post_data = array('action' => 'upgrade', 'serial_no' => $server_serial_no);
                 $post_result = @unserialize(getPostData($url, $post_data));
                 if (!is_array($post_result)) {
                     /** Something went wrong */
                     if (empty($post_result)) {
                         $response[] = ' --> ' . sprintf(_('It appears %s does not have php configured properly within httpd or httpd is not running.'), $server_name);
                         break;
                     }
                 } else {
                     if (count($post_result) > 1) {
                         /** Loop through and format the output */
                         foreach ($post_result as $line) {
                             if (strlen(trim($line))) {
                                 $response[] = " --> {$line}";
                             }
                         }
                     } else {
                         $response[] = " --> " . $post_result[0];
                     }
                     addLogEntry(sprintf(_('Upgraded client scripts on %s.'), $server_name));
                 }
                 break;
             case 'ssh':
                 /** Test the port first */
                 if (!socketTest($server_name, $server_update_port, 10)) {
                     $response[] = ' --> ' . sprintf(_('Failed: could not access %s using %s (tcp/%d).'), $server_name, $server_update_method, $server_update_port);
                     break;
                 }
                 /** Get SSH key */
                 $ssh_key = getOption('ssh_key_priv', $_SESSION['user']['account_id']);
                 if (!$ssh_key) {
                     $response[] = ' --> ' . sprintf(_('Failed: SSH key is not %sdefined</a>.'), '<a href="' . getMenuURL(_('General')) . '">');
                     break;
                 }
                 $temp_ssh_key = sys_get_temp_dir() . '/fm_id_rsa';
                 if (file_exists($temp_ssh_key)) {
                     @unlink($temp_ssh_key);
                 }
                 if (@file_put_contents($temp_ssh_key, $ssh_key) === false) {
                     $response[] = ' --> ' . sprintf(_('Failed: could not load SSH key into %s.'), $temp_ssh_key);
                     break;
                 }
                 @chmod($temp_ssh_key, 0400);
                 $ssh_user = getOption('ssh_user', $_SESSION['user']['account_id']);
                 if (!$ssh_user) {
                     return sprintf('<p class="error">%s</p>' . "\n", sprintf(_('Failed: SSH user is not <a href="%s">defined</a>.'), getMenuURL(_('General'))));
                 }
                 unset($post_result);
                 exec(findProgram('ssh') . " -t -i {$temp_ssh_key} -o 'StrictHostKeyChecking no' -p {$server_update_port} -l {$ssh_user} {$server_name} 'sudo php /usr/local/{$fm_name}/{$_SESSION['module']}/\$(ls /usr/local/{$fm_name}/{$_SESSION['module']} | grep php | grep -v functions) upgrade 2>&1'", $post_result, $retval);
                 @unlink($temp_ssh_key);
                 if ($retval) {
                     /** Something went wrong */
                     $post_result[] = _('Client upgrade failed.');
                 } else {
                     if (!count($post_result)) {
                         $post_result[] = _('Config build was successful.');
                         addLogEntry(sprintf(_('Upgraded client scripts on %s.'), $server_name));
                     }
                 }
                 if (count($post_result) > 1) {
                     /** Loop through and format the output */
                     foreach ($post_result as $line) {
                         if (strlen(trim($line))) {
                             $response[] = " --> {$line}";
                         }
                     }
                 } else {
                     $response[] = " --> " . $post_result[0];
                 }
                 break;
         }
         $response[] = null;
     }
     return implode("\n", $response);
 }
Ejemplo n.º 29
0
 function buildServerConfig($serial_no)
 {
     global $fmdb, $__FM_CONFIG, $fm_name;
     /** Check serial number */
     basicGet('fm_' . $__FM_CONFIG[$_SESSION['module']]['prefix'] . 'servers', sanitize($serial_no), 'server_', 'server_serial_no');
     if (!$fmdb->num_rows) {
         return sprintf('<p class="error">%s</p>', __('This server is not found.'));
     }
     $server_details = $fmdb->last_result;
     extract(get_object_vars($server_details[0]), EXTR_SKIP);
     $response = null;
     switch ($server_update_method) {
         case 'cron':
             if ($action == 'buildconf') {
                 /* set the server_update_config flag */
                 setBuildUpdateConfigFlag($serial_no, 'conf', 'update');
                 $response = sprintf('<p>%s</p>' . "\n", __('This server will be updated on the next cron run.'));
             } else {
                 $response = sprintf('<p>%s</p>' . "\n", __('This server receives updates via cron - please manage the server manually.'));
             }
             break;
         case 'http':
         case 'https':
             /** Test the port first */
             if (!socketTest($server_name, $server_update_port, 10)) {
                 return sprintf('<p class="error">%s</p>' . "\n", sprintf(__('Failed: could not access %s using %s (tcp/%d).'), $server_name, $server_update_method, $server_update_port));
             }
             /** Remote URL to use */
             $url = $server_update_method . '://' . $server_name . ':' . $server_update_port . '/' . $_SESSION['module'] . '/reload.php';
             /** Data to post to $url */
             $post_data = array('action' => 'buildconf', 'serial_no' => $server_serial_no);
             $post_result = @unserialize(getPostData($url, $post_data));
             if (!is_array($post_result)) {
                 /** Something went wrong */
                 if (empty($post_result)) {
                     return sprintf('<p class="error">%s</p>', sprintf(__('It appears %s does not have php configured properly within httpd or httpd is not running.'), $server_name));
                 }
                 return $response . '<p class="error">' . $post_result . '</p>' . "\n";
             } else {
                 if (count($post_result) > 1) {
                     $response .= '<textarea rows="7" cols="100">';
                     /** Loop through and format the output */
                     foreach ($post_result as $line) {
                         $response .= "[{$server_name}] {$line}\n";
                     }
                     $response .= "</textarea>\n";
                 } else {
                     $response .= "<p>[{$server_name}] " . $post_result[0] . '</p>';
                 }
             }
             break;
         case 'ssh':
             /** Test the port first */
             if (!socketTest($server_name, $server_update_port, 10)) {
                 return sprintf('<p class="error">%s</p>' . "\n", sprintf(__('Failed: could not access %s using %s (tcp/%d).'), $server_name, $server_update_method, $server_update_port));
             }
             /** Get SSH key */
             $ssh_key = getOption('ssh_key_priv', $_SESSION['user']['account_id']);
             if (!$ssh_key) {
                 return sprintf('<p class="error">%s</p>' . "\n", sprintf(__('Failed: SSH key is not <a href="%s">defined</a>.'), getMenuURL(_('General'))));
             }
             $temp_ssh_key = sys_get_temp_dir() . '/fm_id_rsa';
             if (file_exists($temp_ssh_key)) {
                 @unlink($temp_ssh_key);
             }
             if (@file_put_contents($temp_ssh_key, $ssh_key) === false) {
                 return sprintf('<p class="error">%s</p>' . "\n", sprintf(__('Failed: could not load SSH key into %s.'), $temp_ssh_key));
             }
             @chmod($temp_ssh_key, 0400);
             $ssh_user = getOption('ssh_user', $_SESSION['user']['account_id']);
             if (!$ssh_user) {
                 return sprintf('<p class="error">%s</p>' . "\n", sprintf(__('Failed: SSH user is not <a href="%s">defined</a>.'), getMenuURL(_('General'))));
             }
             /** Test SSH authentication */
             exec(findProgram('ssh') . " -t -i {$temp_ssh_key} -o 'StrictHostKeyChecking no' -p {$server_update_port} -l {$ssh_user} {$server_name} 'ls /usr/local/{$fm_name}/{$_SESSION['module']}/fw.php'", $post_result, $retval);
             if ($retval) {
                 /** Something went wrong */
                 @unlink($temp_ssh_key);
                 return sprintf('<p class="error">%s</p>' . "\n", __('Could not login via SSH.'));
             }
             unset($post_result);
             /** Run build */
             exec(findProgram('ssh') . " -t -i {$temp_ssh_key} -o 'StrictHostKeyChecking no' -p {$server_update_port} -l {$ssh_user} {$server_name} 'sudo php /usr/local/{$fm_name}/{$_SESSION['module']}/fw.php {$action} " . implode(' ', $options) . "'", $post_result, $retval);
             @unlink($temp_ssh_key);
             if ($retval) {
                 /** Something went wrong */
                 return '<p class="error">' . ucfirst($friendly_action) . ' failed.</p>' . "\n";
             } else {
                 if (!count($post_result)) {
                     $post_result[] = ucfirst($friendly_action) . ' was successful.';
                 }
                 if (count($post_result) > 1) {
                     $response .= '<textarea rows="4" cols="100">';
                     /** Loop through and format the output */
                     foreach ($post_result as $line) {
                         $response .= "[{$server_name}] {$line}\n";
                     }
                     $response .= "</textarea>\n";
                 } else {
                     $response .= "<p>[{$server_name}] " . $post_result[0] . '</p>';
                 }
             }
             break;
     }
     /* reset the server_build_config flag */
     if (!strpos($response, strtolower('failed'))) {
         setBuildUpdateConfigFlag($serial_no, 'no', 'build');
     }
     $tmp_name = getNameFromID($serial_no, 'fm_' . $__FM_CONFIG[$_SESSION['module']]['prefix'] . 'servers', 'server_', 'server_serial_no', 'server_name');
     addLogEntry(ucfirst($friendly_action) . " was performed on server '{$tmp_name}'.");
     return $response;
 }
Ejemplo n.º 30
0
/**
 * Changes a MySQL user password
 *
 * @since 1.0
 * @package facileManager
 * @subpackage fmSQLPass
 *
 * @param string $server_name Hostname of the database server
 * @param integer $server_port Server port to connect to
 * @param string $admin_user User to login with
 * @param string $admin_pass User password to login with
 * @param string $user Database user to change
 * @param string $user_password New password
 * @param string $server_group Server group to process
 * @return string
 */
function changeMySQLUserPassword($server_name, $server_port, $admin_user, $admin_pass, $user, $user_password, $server_group)
{
    global $__FM_CONFIG;
    /** Connect to remote server */
    $verbose_output = ' --> Connecting to MySQL ';
    if (!socketTest($server_name, $server_port, 5)) {
        return $verbose_output . "[failed] - Could not connect to {$server_name} on tcp/{$server_port}\n";
    }
    $remote_connection = @new mysqli($server_name, $admin_user, $admin_pass, null, $server_port);
    if (!$remote_connection->connect_error) {
        $verbose_output .= "[ok]\n";
    } else {
        $verbose_output .= '[failed] - ' . $remote_connection->connect_error . "\n";
        return $verbose_output;
    }
    /** Ensure database user exists before changing the password */
    $verbose_output .= " --> Verifying {$user} exists ";
    list($user_login, $user_host) = explode('@', $user);
    $user_host_query = !empty($user_host) ? "AND Host='{$user_host}'" : null;
    if ($result = $remote_connection->query("SELECT User FROM mysql.user WHERE User='******' {$user_host_query}")) {
        if ($result->num_rows) {
            $verbose_output .= "[ok]\n --> Updating the password for {$user} ";
            $remote_connection->query("UPDATE mysql.user SET Password=PASSWORD('{$user_password}') WHERE User='******' {$user_host_query}");
            if ($remote_connection->affected_rows > 0) {
                $verbose_output .= "[ok]\n";
                /** Update last changed */
                basicUpdate('fm_' . $__FM_CONFIG['fmSQLPass']['prefix'] . 'groups', $server_group, 'group_pwd_change', time(), 'group_id');
                /** Flush privileges */
                $verbose_output .= ' --> Flushing privileges ';
                $remote_connection->query('FLUSH PRIVILEGES');
                $verbose_output .= $remote_connection->error ? '[failed] - ' . $remote_connection->error . "\n" : "[ok]\n";
                /** Log entry */
                addLogEntry("Updated MySQL Account ({$server_name} : {$user}).");
            } else {
                $verbose_output .= '[failed] - ';
                $verbose_output .= $remote_connection->error ? $remote_connection->error . "\n" : "Password for {$user} was not different.\n";
            }
        } else {
            $verbose_output .= "[failed] - User account ({$user}) does not exist.\n";
        }
    } else {
        $verbose_output .= '[failed] - ' . $remote_connection->error . "\n";
    }
    $remote_connection->close();
    return $verbose_output;
}