function db_error($doExit = false, $sql = '')
{
    global $settings;
    $ret = str_replace('XXX', dbi_error(), translate('Database error XXX.')) . (!empty($settings['mode']) && $settings['mode'] == 'dev' && !empty($sql) ? '<br />SQL:<br />' . $sql : '');
    if ($doExit) {
        echo $ret;
        exit;
    } else {
        return $ret;
    }
}
function save_pref($prefs, $src)
{
    global $my_theme, $prefuser;
    while (list($key, $value) = each($prefs)) {
        if ($src == 'post') {
            $setting = substr($key, 5);
            $prefix = substr($key, 0, 5);
            if ($prefix != 'pref_') {
                continue;
            }
            // validate key name.  should start with "pref_" and not include
            // any unusual characters that might cause SQL injection
            if (!preg_match('/pref_[A-Za-z0-9_]+$/', $key)) {
                die_miserable_death(str_replace('XXX', $key, translate('Invalid setting name XXX.')));
            }
        } else {
            $setting = $key;
            $prefix = 'pref_';
        }
        //echo "Setting = $setting, key = $key, prefix = $prefix<br />\n";
        if (strlen($setting) > 0 && $prefix == 'pref_') {
            if ($setting == 'THEME' && $value != 'none') {
                $my_theme = strtolower($value);
            }
            $sql = 'DELETE FROM webcal_user_pref WHERE cal_login = ? ' . 'AND cal_setting = ?';
            dbi_execute($sql, array($prefuser, $setting));
            if (strlen($value) > 0) {
                $setting = strtoupper($setting);
                $sql = 'INSERT INTO webcal_user_pref ' . '( cal_login, cal_setting, cal_value ) VALUES ' . '( ?, ?, ? )';
                if (!dbi_execute($sql, array($prefuser, $setting, $value))) {
                    $error = 'Unable to update preference: ' . dbi_error() . '<br /><br /><span class="bold">SQL:</span>' . $sql;
                    break;
                }
            }
        }
    }
}
if (!$is_admin) {
    $error = translate("You are not authorized");
}
if ($error == "") {
    while (list($key, $value) = each($HTTP_POST_VARS)) {
        $setting = substr($key, 6);
        if (strlen($setting) > 0) {
            $sql = "DELETE FROM webcal_config WHERE cal_setting = '{$setting}'";
            if (!dbi_query($sql)) {
                $error = translate("Error") . ": " . dbi_error() . "<P><B>SQL:</B> {$sql}";
                break;
            }
            if (strlen($value) > 0) {
                $sql = "INSERT INTO webcal_config " . "( cal_setting, cal_value ) VALUES " . "( '{$setting}', '{$value}' )";
                if (!dbi_query($sql)) {
                    $error = translate("Error") . ": " . dbi_error() . "<P><B>SQL:</B> {$sql}";
                    break;
                }
            }
        }
    }
}
if (empty($error)) {
    if (empty($ovrd)) {
        do_redirect("admin.php");
    } else {
        do_redirect("admin.php?ovrd={$ovrd}");
    }
}
?>
<HTML>
Example #4
0
function convert_server_to_GMT($offset = 0, $cutoffdate = '')
{
    // Default value.
    $error = translate('Conversion Successful');
    // Don't allow $offsets over 24.
    if (abs($offset) > 24) {
        $offset = 0;
    }
    // Do webcal_entry update.
    $res = dbi_execute('SELECT cal_date, cal_time, cal_id, cal_duration
    FROM webcal_entry');
    if ($res) {
        while ($row = dbi_fetch_row($res)) {
            $cal_date = $row[0];
            $cal_time = sprintf("%06d", $row[1]);
            $cal_id = $row[2];
            $cal_duration = $row[3];
            // Skip Untimed or All Day events.
            if ($cal_time == -1 || $cal_time == 0 && $cal_duration == 1440) {
                continue;
            } else {
                $sy = substr($cal_date, 0, 4);
                $sm = substr($cal_date, 4, 2);
                $sd = substr($cal_date, 6, 2);
                $sh = substr($cal_time, 0, 2);
                $si = substr($cal_time, 2, 2);
                $ss = substr($cal_time, 4, 2);
                $new_datetime = empty($offset) ? mktime($sh, $si, $ss, $sm, $sd, $sy) : gmmktime($sh + $offset, $si, $ss, $sm, $sd, $sy);
                $new_cal_date = gmdate('Ymd', $new_datetime);
                $new_cal_time = gmdate('His', $new_datetime);
                $cutoff = !empty($cutoffdate) ? ' AND cal_date <= ?' : '';
                // Now update row with new data.
                if (!dbi_execute('UPDATE webcal_entry SET cal_date = ?, cal_time = ?
          WHERE cal_id = ?' . $cutoff, array($new_cal_date, $new_cal_time, $cal_id, $cutoffdate))) {
                    return str_replace('XXX', array('webcal_entry', dbi_error()), translate('Error updating table XXX'));
                }
            }
        }
        dbi_free_result($res);
    }
    // Do webcal_entry_logs update.
    $res = dbi_execute('SELECT cal_date, cal_time, cal_log_id
    FROM webcal_entry_log');
    if ($res) {
        while ($row = dbi_fetch_row($res)) {
            $cal_date = $row[0];
            $cal_time = sprintf("%06d", $row[1]);
            $cal_log_id = $row[2];
            $sy = substr($cal_date, 0, 4);
            $sm = substr($cal_date, 4, 2);
            $sd = substr($cal_date, 6, 2);
            $sh = substr($cal_time, 0, 2);
            $si = substr($cal_time, 2, 2);
            $ss = substr($cal_time, 4, 2);
            $new_datetime = mktime($sh, $si, $ss, $sm, $sd, $sy);
            $new_cal_date = gmdate('Ymd', $new_datetime);
            $new_cal_time = gmdate('His', $new_datetime);
            // Now update row with new data
            if (!dbi_execute('UPDATE webcal_entry_log
        SET cal_date = ?, cal_time = ? WHERE cal_log_id = ?', array($new_cal_date, $new_cal_time, $cal_log_id))) {
                return str_replace('XXX', array('webcal_entry_log', dbi_error()), translate('Error updating table XXX'));
            }
        }
        dbi_free_result($res);
    }
    // Update Conversion Flag in webcal_config.
    // Delete any existing entry.
    if (!dbi_execute('DELETE FROM webcal_config
    WHERE cal_setting = \'WEBCAL_TZ_CONVERSION\'')) {
        return str_replace('XXX', dbi_error(), translate('Database error XXX.'));
    }
    if (!dbi_execute('INSERT INTO webcal_config ( cal_setting, cal_value )
    VALUES ( \'WEBCAL_TZ_CONVERSION\', \'Y\' )')) {
        return str_replace('XXX', dbi_error(), translate('Database error XXX.'));
    }
    return $error;
}
function import_data($data, $overwrite, $type)
{
    global $login, $count_con, $count_suc, $error_num, $ImportType, $LOG_CREATE;
    global $single_user, $single_user_login, $allow_conflicts;
    global $numDeleted, $errormsg;
    global $calUser, $H2COLOR, $sqlLog;
    $oldUIDs = array();
    $oldIds = array();
    $firstEventId = 0;
    $importId = 1;
    // Generate a unique import id
    $res = dbi_query("SELECT MAX(cal_import_id) FROM webcal_import");
    if ($res) {
        if ($row = dbi_fetch_row($res)) {
            $importId = $row[0] + 1;
        }
        dbi_free_result($res);
    }
    $sql = "INSERT INTO webcal_import ( cal_import_id, cal_name, " . "cal_date, cal_type, cal_login ) VALUES ( {$importId}, NULL, " . date("Ymd") . ", '{$type}', '{$login}' )";
    if (!dbi_query($sql)) {
        $errormsg = translate("Database error") . ": " . dbi_error();
        return;
    }
    foreach ($data as $Entry) {
        $priority = 2;
        $participants[0] = $calUser;
        // Some additional date/time info
        $START = $Entry['StartTime'] > 0 ? localtime($Entry['StartTime']) : 0;
        $END = $Entry['EndTime'] > 0 ? localtime($Entry['EndTime']) : 0;
        $Entry['StartMinute'] = sprintf("%02d", $START[1]);
        $Entry['StartHour'] = sprintf("%02d", $START[2]);
        $Entry['StartDay'] = sprintf("%02d", $START[3]);
        $Entry['StartMonth'] = sprintf("%02d", $START[4] + 1);
        $Entry['StartYear'] = sprintf("%04d", $START[5] + 1900);
        $Entry['EndMinute'] = sprintf("%02d", $END[1]);
        $Entry['EndHour'] = sprintf("%02d", $END[2]);
        $Entry['EndDay'] = sprintf("%02d", $END[3]);
        $Entry['EndMonth'] = sprintf("%02d", $END[4] + 1);
        $Entry['EndYear'] = sprintf("%04d", $END[5] + 1900);
        if ($overwrite && !empty($Entry['UID'])) {
            $oldUIDs[$Entry['UID']]++;
        }
        // Check for untimed
        if ($Entry['Untimed'] == 1) {
            $Entry['StartMinute'] = '';
            $Entry['StartHour'] = '';
            $Entry['EndMinute'] = '';
            $Entry['EndHour'] = '';
        }
        // first check for any schedule conflicts
        if (empty($allow_conflicts) && $Entry['Duration'] != 0) {
            $date = mktime(0, 0, 0, $Entry['StartMonth'], $Entry['StartDay'], $Entry['StartYear']);
            $endt = !empty($Entry['Repeat']['EndTime']) ? $Entry['Repeat']['EndTime'] : 'NULL';
            $dayst = !empty($Entry['Repeat']['RepeatDays']) ? $Entry['Repeat']['RepeatDays'] : "nnnnnnn";
            $ex_days = array();
            if (!empty($Entry['Repeat']['Exceptions'])) {
                foreach ($Entry['Repeat']['Exceptions'] as $ex_date) {
                    $ex_days[] = date("Ymd", $ex_date);
                }
            }
            $dates = get_all_dates($date, RepeatType($Entry['Repeat']['Interval']), $endt, $dayst, $ex_days, $Entry['Repeat']['Frequency']);
            $overlap = overlap($dates, $Entry['Duration'], $Entry['StartHour'], $Entry['StartMinute'], $participants, $login, 0);
        }
        if (empty($error) && !empty($overlap)) {
            $error = translate("The following conflicts with the suggested time") . ":<ul>{$overlap}</ul>\n";
        }
        if (empty($error)) {
            $updateMode = false;
            // See if event already is there from prior import.
            // The same UID is used for all events imported at once with iCal.
            // So, we still don't have enough info to find the exact
            // event we want to replace.  We could just delete all
            // existing events that correspond to the UID.
            /************************************************************************
              Not sure what to do with this code since I don't know how Palm and vCal
              use the UID stuff yet...
              
                  if ( ! empty ( $Entry['UID'] ) ) {
                    $res = dbi_query ( "SELECT webcal_import_data.cal_id " .
                      "FROM webcal_import_data, webcal_entry_user " .
                      "WHERE cal_import_type = 'ical' AND " .
                      "webcal_import_data.cal_id = webcal_entry_user.cal_id AND " .
                      "webcal_entry_user.cal_login = '******' AND " .
                      "cal_external_id = '$Entry[UID]'" );
                    if ( $res ) {
                      if ( $row = dbi_fetch_row ( $res ) ) {
                        if ( ! empty ( $row[0] ) ) {
                          $id = $row[0];
                          $updateMode = true;
                          // update rather than add a new event
                        }
                      }
                    }
                  }
            ************************************************************************/
            // Add the Event
            $res = dbi_query("SELECT MAX(cal_id) FROM webcal_entry");
            if ($res) {
                $row = dbi_fetch_row($res);
                $id = $row[0] + 1;
                dbi_free_result($res);
            } else {
                $id = 1;
                //$error = "Unable to select MAX cal_id: " . dbi_error () . "<br /><br />\n<b>SQL:</b> $sql";
                //break;
            }
            if ($firstEventId == 0) {
                $firstEventId = $id;
            }
            $names = array();
            $values = array();
            $names[] = 'cal_id';
            $values[] = "{$id}";
            if (!$updateMode) {
                $names[] = 'cal_create_by';
                $values[] = "'{$login}'";
            }
            $names[] = 'cal_date';
            $values[] = sprintf("%04d%02d%02d", $Entry['StartYear'], $Entry['StartMonth'], $Entry['StartDay']);
            $names[] = 'cal_time';
            $values[] = $Entry['Untimed'] == 1 ? "-1" : sprintf("%02d%02d00", $Entry['StartHour'], $Entry['StartMinute']);
            $names[] = 'cal_mod_date';
            $values[] = date("Ymd");
            $names[] = 'cal_mod_time';
            $values[] = date("Gis");
            $names[] = 'cal_duration';
            $values[] = sprintf("%d", $Entry['Duration']);
            $names[] = 'cal_priority';
            $values[] = $priority;
            $names[] = 'cal_access';
            $values[] = $Entry['Private'] == 1 ? "'R'" : "'P'";
            $names[] = 'cal_type';
            $values[] = $Entry['Repeat'] ? "'M'" : "'E'";
            if (strlen($Entry['Summary']) == 0) {
                $Entry['Summary'] = translate("Unnamed Event");
            }
            if (strlen($Entry['Description']) == 0) {
                $Entry['Description'] = $Entry['Summary'];
            }
            $Entry['Summary'] = str_replace("\\n", "\n", $Entry['Summary']);
            $Entry['Summary'] = str_replace("\\'", "'", $Entry['Summary']);
            $Entry['Summary'] = str_replace("\\\"", "\"", $Entry['Summary']);
            $Entry['Summary'] = str_replace("'", "\\'", $Entry['Summary']);
            $names[] = 'cal_name';
            $values[] = "'" . $Entry['Summary'] . "'";
            $Entry['Description'] = str_replace("\\n", "\n", $Entry['Description']);
            $Entry['Description'] = str_replace("\\'", "'", $Entry['Description']);
            $Entry['Description'] = str_replace("\\\"", "\"", $Entry['Description']);
            $Entry['Description'] = str_replace("'", "\\'", $Entry['Description']);
            // limit length to 1024 chars since we setup tables that way
            if (strlen($Entry['Description']) >= 1024) {
                $Entry['Description'] = substr($Entry['Description'], 0, 1019) . "...";
            }
            $names[] = 'cal_description';
            $values[] = "'" . $Entry['Description'] . "'";
            //echo "Summary:<p>" . nl2br ( htmlspecialchars ( $Entry['Summary'] ) ) . "</p>";
            //echo "Description:<p>" . nl2br ( htmlspecialchars ( $Entry['Description'] ) ) . "</p>"; exit;
            if ($updateMode) {
                $sql = "UPDATE webcal_entry SET ";
                for ($f = 0; $f < count($names); $f++) {
                    if ($f > 0) {
                        $sql .= ", ";
                    }
                    $sql .= $names[$f] . " = " . $values[$f];
                }
                $sql .= " WHERE cal_id = {$id}";
            } else {
                $sql = "INSERT INTO webcal_entry ( " . implode(", ", $names) . " ) VALUES ( " . implode(", ", $values) . " )";
            }
            if (empty($error)) {
                $sqlLog .= $sql . "<br />\n";
                //echo "SQL: $sql <br />\n";
                if (!dbi_query($sql)) {
                    $error .= "<p>" . translate("Database error") . ": " . dbi_error() . "</p>\n";
                    break;
                }
            }
            // log add/update
            activity_log($id, $login, $login, $updateMode ? $LOG_UPDATE : $LOG_CREATE, "Import from {$ImportType}");
            if ($single_user == "Y") {
                $participants[0] = $single_user_login;
            }
            // Now add to webcal_import_data
            if (!$updateMode) {
                if ($ImportType == "PALMDESKTOP") {
                    $sql = "INSERT INTO webcal_import_data ( cal_import_id, cal_id, " . "cal_login, cal_import_type, cal_external_id ) VALUES ( " . "{$importId}, {$id}, '{$calUser}', 'palm', '{$Entry['RecordID']}' )";
                    $sqlLog .= $sql . "<br />\n";
                    if (!dbi_query($sql)) {
                        $error = translate("Database error") . ": " . dbi_error();
                        break;
                    }
                } else {
                    if ($ImportType == "VCAL") {
                        $uid = empty($Entry['UID']) ? "null" : "'{$Entry['UID']}'";
                        if (strlen($uid) > 200) {
                            $uid = "NULL";
                        }
                        $sql = "INSERT INTO webcal_import_data ( cal_import_id, cal_id, " . "cal_login, cal_import_type, cal_external_id ) VALUES ( " . "{$importId}, {$id}, '{$calUser}', 'vcal', {$uid} )";
                        $sqlLog .= $sql . "<br />\n";
                        if (!dbi_query($sql)) {
                            $error = translate("Database error") . ": " . dbi_error();
                            break;
                        }
                    } else {
                        if ($ImportType == "ICAL") {
                            $uid = empty($Entry['UID']) ? "null" : "'{$Entry['UID']}'";
                            if (strlen($uid) > 200) {
                                $uid = "NULL";
                            }
                            $sql = "INSERT INTO webcal_import_data ( cal_import_id, cal_id, " . "cal_login, cal_import_type, cal_external_id ) VALUES ( " . "{$importId}, {$id}, '{$calUser}', 'ical', {$uid} )";
                            $sqlLog .= $sql . "<br />\n";
                            if (!dbi_query($sql)) {
                                $error = translate("Database error") . ": " . dbi_error();
                                break;
                            }
                        }
                    }
                }
            }
            // Now add participants
            if (!$updateMode) {
                $status = $login == "__public__" ? 'W' : 'A';
                if (empty($cat_id)) {
                    $cat_id = 'NULL';
                }
                $sql = "INSERT INTO webcal_entry_user " . "( cal_id, cal_login, cal_status, cal_category ) VALUES ( {$id}, '" . $participants[0] . "', '{$status}', {$cat_id} )";
                $sqlLog .= $sql . "<br />\n";
                if (!dbi_query($sql)) {
                    $error = translate("Database error") . ": " . dbi_error();
                    break;
                }
            }
            // Add repeating info
            if ($updateMode) {
                // remove old repeating info
                dbi_query("DELETE FROM webcal_entry_repeats WHERE cal_id = {$id}");
                dbi_query("DELETE FROM webcal_entry_repeats_not WHERE cal_id = {$id}");
            }
            if (!empty($Entry['Repeat']['Interval'])) {
                //while ( list($k,$v) = each ( $Entry['Repeat'] ) ) {
                //  echo "$k: $v <br />\n";
                //}
                $rpt_type = RepeatType($Entry['Repeat']['Interval']);
                $freq = $Entry['Repeat']['Frequency'] ? $Entry['Repeat']['Frequency'] : 1;
                if (strlen($Entry['Repeat']['EndTime'])) {
                    $REND = localtime($Entry['Repeat']['EndTime']);
                    $end = sprintf("%04d%02d%02d", $REND[5] + 1900, $REND[4] + 1, $REND[3]);
                } else {
                    $end = 'NULL';
                }
                $days = !empty($Entry['Repeat']['RepeatDays']) ? "'" . $Entry['Repeat']['RepeatDays'] . "'" : 'NULL';
                $sql = "INSERT INTO webcal_entry_repeats ( cal_id, " . "cal_type, cal_end, cal_days, cal_frequency ) VALUES " . "( {$id}, '{$rpt_type}', {$end}, {$days}, {$freq} )";
                $sqlLog .= $sql . "<br />\n";
                if (!dbi_query($sql)) {
                    $error = "Unable to add to webcal_entry_repeats: " . dbi_error() . "<br /><br />\n<b>SQL:</b> {$sql}";
                    break;
                }
                // Repeating Exceptions...
                if (!empty($Entry['Repeat']['Exceptions'])) {
                    foreach ($Entry['Repeat']['Exceptions'] as $ex_date) {
                        $ex_date = date("Ymd", $ex_date);
                        $sql = "INSERT INTO webcal_entry_repeats_not ( cal_id, cal_date ) VALUES ( {$id}, {$ex_date} )";
                        $sqlLog .= $sql . "<br />\n";
                        if (!dbi_query($sql)) {
                            $error = "Unable to add to webcal_entry_repeats_not: " . dbi_error() . "<br /><br />\n<b>SQL:</b> {$sql}";
                            break;
                        }
                    }
                }
            }
            // End Repeat
            // Add Alarm info -> site_extras
            if ($updateMode) {
                dbi_query("DELETE FROM webcal_site_extras WHERE cal_id = {$id}");
            }
            if ($Entry['AlarmSet'] == 1) {
                $RM = $Entry['AlarmAdvanceAmount'];
                if ($Entry['AlarmAdvanceType'] == 1) {
                    $RM = $RM * 60;
                }
                if ($Entry['AlarmAdvanceType'] == 2) {
                    $RM = $RM * 60 * 24;
                }
                $sql = "INSERT INTO webcal_site_extras ( cal_id, " . "cal_name, cal_type, cal_remind, cal_data ) VALUES " . "( {$id}, 'Reminder', 7, 1, {$RM} )";
                $sqlLog .= $sql . "<br />\n";
                if (!dbi_query($sql)) {
                    $error = translate("Database error") . ": " . dbi_error();
                }
            }
        }
        if (!empty($error) && empty($overlap)) {
            $error_num++;
            echo "<h2>" . translate("Error") . "</h2>\n<blockquote>\n";
            echo $error . "</blockquote>\n<br />\n";
        }
        // Conflicting
        if (!empty($overlap)) {
            echo "<b><h2>" . translate("Scheduling Conflict") . ": ";
            $count_con++;
            echo "</h2></b>";
            if ($Entry['Duration'] > 0) {
                $time = display_time($Entry['StartHour'] . $Entry['StartMinute'] . "00") . " - " . display_time($Entry['EndHour'] . $Entry['EndMinute'] . "00");
            }
            $dd = $Entry['StartMonth'] . "-" . $Entry['StartDay'] . "-" . $Entry['StartYear'];
            echo "<a class=\"entry\" href=\"view_entry.php?id={$id}";
            echo "\" onmouseover=\"window.status='" . translate("View this entry") . "'; return true;\" onmouseout=\"window.status=''; return true;\">";
            $Entry['Summary'] = str_replace("''", "'", $Entry['Summary']);
            $Entry['Summary'] = str_replace("'", "\\'", $Entry['Summary']);
            echo htmlspecialchars($Entry['Summary']);
            echo "</a> (" . $dd;
            $time = trim($time);
            if (!empty($time)) {
                echo "&nbsp; " . $time;
            }
            echo ")<br />\n";
            etranslate("conflicts with the following existing calendar entries");
            echo ":<ul>\n" . $overlap . "</ul>\n";
        } else {
            // No Conflict
            echo "<b><h2>" . translate("Event Imported") . ":</h2></b>\n";
            $count_suc++;
            if ($Entry['Duration'] > 0) {
                $time = display_time($Entry['StartHour'] . $Entry['StartMinute'] . "00") . " - " . display_time($Entry['EndHour'] . $Entry['EndMinute'] . "00");
            }
            $dateYmd = sprintf("%04d%02d%02d", $Entry['StartYear'], $Entry['StartMonth'], $Entry['StartDay']);
            $dd = date_to_str($dateYmd);
            echo "<a class=\"entry\" href=\"view_entry.php?id={$id}";
            echo "\" onmouseover=\"window.status='" . translate("View this entry") . "'; return true;\" onmouseout=\"window.status=''; return true;\">";
            $Entry['Summary'] = str_replace("''", "'", $Entry['Summary']);
            $Entry['Summary'] = str_replace("\\", "", $Entry['Summary']);
            echo htmlspecialchars($Entry['Summary']);
            echo "</a> (" . $dd;
            if (!empty($time)) {
                echo "&nbsp; " . $time;
            }
            echo ")<br />\n";
        }
        // Reset Variables
        $overlap = $error = $dd = $time = '';
    }
    // Mark old events from prior import as deleted.
    if ($overwrite && count($oldUIDs) > 0) {
        // We could do this with a single SQL using sub-select, but
        // I'm pretty sure MySQL does not support it.
        $old = array_keys($oldUIDs);
        for ($i = 0; $i < count($old); $i++) {
            $sql = "SELECT cal_id FROM webcal_import_data WHERE " . "cal_import_type = '{$type}' AND " . "cal_external_id = '{$old[$i]}' AND " . "cal_login = '******' AND " . "cal_id < {$firstEventId}";
            $res = dbi_query($sql);
            if ($res) {
                while ($row = dbi_fetch_row($res)) {
                    $oldIds[] = $row[0];
                }
                dbi_free_result($res);
            } else {
                echo translate("Database error") . ": " . dbi_error() . "<br />\n";
            }
        }
        for ($i = 0; $i < count($oldIds); $i++) {
            $sql = "UPDATE webcal_entry_user SET cal_status = 'D' " . "WHERE cal_id = {$oldIds[$i]}";
            $sqlLog .= $sql . "<br />\n";
            dbi_query($sql);
            $numDeleted++;
        }
    }
    //echo "<b>SQL:</b><br />\n$sqlLog\n";
}
Example #6
0
/**
 * Add a new user.
 *
 * @param string $user      User login
 * @param string $password  User password
 * @param string $firstname User first name
 * @param string $lastname  User last name
 * @param string $email     User email address
 * @param string $admin     Is the user an administrator? ('Y' or 'N')
 *
 * @return bool True on success
 *
 * @global string Error message
 */
function user_add_user($user, $password, $firstname, $lastname, $email, $admin, $enabled = 'Y')
{
    global $error;
    if ($user == '__public__') {
        $error = translate('Invalid user login', true);
        return false;
    }
    if (strlen($email)) {
        $uemail = $email;
    } else {
        $uemail = NULL;
    }
    if (strlen($firstname)) {
        $ufirstname = $firstname;
    } else {
        $ufirstname = NULL;
    }
    if (strlen($lastname)) {
        $ulastname = $lastname;
    } else {
        $ulastname = NULL;
    }
    if (strlen($password)) {
        $upassword = md5($password);
    } else {
        $upassword = NULL;
    }
    if ($admin != 'Y') {
        $admin = 'N';
    }
    $sql = 'INSERT INTO webcal_user
    ( cal_login, cal_lastname, cal_firstname,
    cal_is_admin, cal_passwd, cal_email, cal_enabled )
    VALUES ( ?, ?, ?, ?, ?, ? )';
    if (!dbi_execute($sql, array($user, $ulastname, $ufirstname, $admin, $upassword, $uemail, $enabled))) {
        $error = translate('Database error', true) . ': ' . dbi_error();
        return false;
    }
    return true;
}
Example #7
0
function dbtable_update($tablear, $tablename, $valuesar)
{
    global $error;
    $sql = "UPDATE " . $tablename . " SET";
    if (!is_array($tablear)) {
        echo "Error: dbtable_update parameter 1 is not an array!<br />\n";
        exit;
    }
    if (!is_array($valuesar)) {
        echo "Error: dbtable_update parameter 3 is not an array!<br />\n";
        exit;
    }
    $first = 1;
    for ($i = 0; $i < count($tablear); $i++) {
        if (!empty($tablear[$i]["iskey"])) {
            continue;
        }
        if ($first) {
            $first = 0;
        } else {
            $sql .= ", ";
        }
        if (empty($tablear[$i]["name"])) {
            echo "Error: dbtable_update {$tablename} field {$i} does not define name.\n";
            exit;
        }
        $sql .= " " . $tablear[$i]["name"] . " = ";
        if (empty($valuesar[$i])) {
            $sql .= "NULL";
        } else {
            if ($tablear[$i]["type"] == "int" || $tablear[$i]["type"] == "date") {
                $sql .= $valuesar[$i];
            } else {
                $sql .= "'" . $valuesar[$i] . "'";
            }
        }
    }
    $sql .= " WHERE";
    $first = 1;
    for ($i = 0; $i < count($tablear); $i++) {
        if (empty($tablear[$i]["iskey"])) {
            continue;
        }
        if ($first) {
            $first = 0;
        } else {
            $sql .= " AND";
        }
        if (empty($valuesar[$i])) {
            echo "Error: you must set field {$i} (" . $tablear[$i]["name"] . ") by hand. Cannot be empty.";
            exit;
        }
        $sql .= " " . $tablear[$i]["name"] . " = '" . $valuesar[$i] . "'";
    }
    //echo "SQL: $sql <p>\n";
    if (!dbi_query($sql)) {
        // Shouldn't happen... complain if it does.
        $error = translate("Database error") . ": " . dbi_error();
        return false;
    }
    return true;
}
Example #8
0
        $db_persistent = false;
        $db_type = getGetValue('db_type');
        $db_host = getGetValue('db_host');
        $db_database = getGetValue('db_database');
        $db_login = getGetValue('db_login');
        $db_password = getGetValue('db_password');
        echo "<html><head><title>WebCalendar: Db Connection Test</title>\n" . "</head><body style=\"background-color: #fff;\">\n";
        echo "<p><b>Connection Result:</b></p><blockquote>";
        $c = dbi_connect($db_host, $db_login, $db_password, $db_database);
        if ($c) {
            echo "<span style=\"color: #0f0;\">Success</span></blockquote>";
            $_SESSION['db_success'] = true;
            // TODO: update the text in the main window to indicate success
        } else {
            echo "<span style=\"color: #0f0;\">Failure</span</blockquote>";
            echo "<br/><br/><b>Reason:</b><blockquote>" . dbi_error() . "</blockquote>\n";
        }
        echo "<br/><br/><br/><div align=\"center\"><form><input align=\"middle\" type=\"button\" onclick=\"window.close()\" value=\"Close\" /></form></div>\n";
        echo "</p>";
        echo "<script language=\"JavaScript\" type=\"text/javascript\">\n";
        echo "<!-- <![CDATA[\n";
        echo "window.opener.show_db_status ( " . ($c ? "true" : "false") . " );\n";
        echo "//]]> -->\n</script>\n";
        echo "</body></html>\n";
    } else {
        // Not valid user
        echo "You are not authorized.";
        // etranslate ( "You are not authorized" );
    }
    exit;
}
Example #9
0
function save_pref($prefs, $src)
{
    global $error, $my_theme, $prad;
    if (!$prad) {
        global $prefuser;
    }
    $pos = $prad ? 6 : 5;
    while (list($key, $value) = each($prefs)) {
        if ($src == 'post') {
            $prefix = substr($key, 0, $pos);
            $setting = substr($key, $pos);
            if (!$prad && $prefix != 'pref_' || $prad && $key == 'currenttab') {
                continue;
            }
            // .
            // Validate key name.
            // If $prad not true, should start with "pref_"
            // else should start with "admin_",
            // and not include any unusual characters that might be an SQL injection attack.
            if (!$prad && !preg_match('/pref_[A-Za-z0-9_]+$/', $key) || $prad && !preg_match('/admin_[A-Za-z0-9_]+$/', $key)) {
                die_miserable_death(str_replace('XXX', $key, translate('Invalid setting name XXX.')));
            }
        } else {
            $prefix = $prad ? 'admin_' : 'pref_';
            $setting = $key;
        }
        if (strlen($setting) > 0 && $prefix == 'pref_' || $prefix == 'admin_') {
            if ($setting == 'THEME' && $value != 'none') {
                $my_theme = strtolower($value);
            }
            if ($prad) {
                $setting = strtoupper($setting);
                $sql = 'DELETE FROM webcal_config WHERE cal_setting = ?';
                if (!dbi_execute($sql, array($setting))) {
                    $error = db_error(false, $sql);
                    break;
                }
                if (strlen($value) > 0) {
                    $sql = 'INSERT INTO webcal_config ( cal_setting, cal_value ) VALUES ( ?, ? )';
                    if (!dbi_execute($sql, array($setting, $value))) {
                        $error = db_error(false, $sql);
                        break;
                    }
                }
            } else {
                dbi_execute('DELETE FROM webcal_user_pref WHERE cal_login = ?
          AND cal_setting = ?', array($prefuser, $setting));
                if (strlen($value) > 0) {
                    $setting = strtoupper($setting);
                    $sql = 'INSERT INTO webcal_user_pref ( cal_login, cal_setting,
            cal_value ) VALUES ( ?, ?, ? )';
                    if (!dbi_execute($sql, array($prefuser, $setting, $value))) {
                        $error = 'Unable to update preference: ' . dbi_error() . '<br /><br /><span class="bold">SQL:</span>' . $sql;
                        break;
                    }
                }
            }
        }
    }
    // Reload preferences so any CSS changes will take effect.
    load_global_settings();
    load_user_preferences();
}
}
// First, look at the passwords.  If we find and md5 hash in there,
// (it will have 32 chars instead of < 25 like in the old version),
// then we know this script was already run.
$sql = "SELECT cal_passwd FROM webcal_user";
$res = dbi_query($sql);
$doneBefore = false;
if ($res) {
    if ($row = dbi_fetch_row($res)) {
        if (strlen($row[0]) > 30) {
            $doneBefore = true;
        }
    }
    dbi_free_result($res);
} else {
    echo "Database error: " . dbi_error();
    exit;
}
if ($doneBefore) {
    echo "Passwords were already converted to md5!\n<br />\n";
    exit;
}
// See if webcal_user.cal_passwd will allow 32 characters
$sql = "DESC webcal_user";
$res = dbi_query($sql);
while ($row = dbi_fetch_row($res)) {
    if ($row[Field] == 'cal_passwd') {
        preg_match("/([0-9]+)/", $row[Type], $match);
        if ($match[1] < 32) {
            $sql = "ALTER TABLE webcal_user MODIFY cal_passwd VARCHAR(32) NULL";
            // Use the following on older MySQL versions
         $session_not_found = true;
     } else {
         // Check for cookie...
         if (!empty($webcalendar_session)) {
             $encoded_login = $webcalendar_session;
             if (empty($encoded_login)) {
                 // invalid session cookie
                 $session_not_found = true;
             } else {
                 $login_pw = split('\\|', decode_string($encoded_login));
                 $login = $login_pw[0];
                 $cryptpw = $login_pw[1];
                 // make sure we are connected to the database for password check
                 $c = dbi_connect($db_host, $db_login, $db_password, $db_database);
                 if (!$c) {
                     echo "Error connecting to database:<BLOCKQUOTE>" . dbi_error() . "</BLOCKQUOTE>\n";
                     exit;
                 }
                 if (!user_valid_crypt($login, $cryptpw)) {
                     do_debug("User not logged in; redirecting to login page");
                     if (empty($login_return_path)) {
                         do_redirect("login.php");
                     } else {
                         do_redirect("login.php?return_path={$login_return_path}");
                     }
                 }
                 do_debug("Decoded login from cookie: {$login}");
             }
         }
     }
 }
Example #12
0
// a valid login.
if ($single_user == 'Y') {
    if (empty($single_user_login)) {
        echo "<html><head><title>Setup error</title>\n" . "</head>\n<body><h2>Setup error</h2><p>" . "You have not defined <tt>single_user_login</tt> in " . "<tt>includes/settings.php</tt></p></body></html>\n";
        exit;
    }
    $res = dbi_query("SELECT COUNT(*) FROM webcal_user " . "WHERE cal_login = '******'");
    if (!$res) {
        echo "Database error: " . dbi_error();
        exit;
    }
    $row = dbi_fetch_row($res);
    if ($row[0] == 0) {
        // User specified as single_user_login does not exist
        if (!dbi_query("INSERT INTO webcal_user ( cal_login, " . "cal_passwd, cal_is_admin ) VALUES ( '{$single_user_login}', " . "'" . md5($single_user_login) . "', 'Y' )")) {
            echo "<b>Error:</b> user <tt>{$single_user_login}</tt> does not " . "exist in webcal_user table and was not able to add it for you:<br />" . dbi_error();
            exit;
        }
        // User was added... should we tell them?
    }
    dbi_free_result($res);
}
// global settings have not been loaded yet, so check for public_access now
$res = dbi_query("SELECT cal_value FROM webcal_config " . "WHERE cal_setting = 'public_access'");
$pub_acc_enabled = false;
if ($res) {
    if ($row = dbi_fetch_row($res)) {
        if ($row[0] == "Y") {
            $pub_acc_enabled = true;
        }
    }
function user_is_participant($id, $user)
{
    $ret = false;
    $rows = dbi_get_cached_rows('SELECT COUNT( cal_id ) FROM webcal_entry_user
    WHERE cal_id = ? AND cal_login = ? AND cal_status IN ( \'A\',\'W\' )', array($id, $user));
    if (!$rows) {
        die_miserable_death(str_replace('XXX', dbi_error(), translate('Database error XXX.')));
    }
    if (!empty($rows[0])) {
        $row = $rows[0];
        if (!empty($row)) {
            $ret = $row[0] > 0;
        }
    }
    return $ret;
}
Example #14
0
function dbi_query($sql)
{
    if (strcmp($GLOBALS["db_type"], "mysql") == 0) {
        $res = mysql_query($sql);
        if (!$res) {
            dbi_fatal_error("Error executing query: " . dbi_error() . "\n\n<P>\n" . $sql);
        }
        return $res;
    } else {
        if (strcmp($GLOBALS["db_type"], "oracle") == 0) {
            $GLOBALS["oracle_statement"] = OCIParse($GLOBALS["oracle_connection"], $sql);
            return OCIExecute($GLOBALS["oracle_statement"], OCI_COMMIT_ON_SUCCESS);
        } else {
            if (strcmp($GLOBALS["db_type"], "postgresql") == 0) {
                $GLOBALS["postgresql_row"] = 0;
                $GLOBALS["postgresql_row"] = 0;
                $res = pg_exec($GLOBALS["postgresql_connection"], $sql);
                if (!$res) {
                    dbi_fatal_error("Error executing query: " . dbi_error() . "\n\n<P>\n" . $sql);
                }
                $GLOBALS["postgresql_numrows"] = pg_numrows($res);
                return $res;
            } else {
                if (strcmp($GLOBALS["db_type"], "odbc") == 0) {
                    return odbc_exec($GLOBALS["odbc_connection"], $sql);
                } else {
                    if (strcmp($GLOBALS["db_type"], "ibase") == 0) {
                        $res = ibase_query($sql);
                        if (!$res) {
                            dbi_fatal_error("Error executing query: " . dbi_error() . "\n\n<P>\n" . $sql);
                        }
                        return $res;
                    } else {
                        dbi_fatal_error("dbi_query(): db_type not defined.");
                    }
                }
            }
        }
    }
}
Example #15
0
/**
 * Check to see if a given login/crypted password is valid.
 *
 * If invalid, the error message will be placed in $error.
 *
 * @param string $login          User login
 * @param string $crypt_password Encrypted user password
 *
 * @return bool True on success
 *
 * @global string Error message
 */
function user_valid_crypt($login, $crypt_password)
{
    global $error;
    $ret = false;
    $sql = 'SELECT cal_login, cal_passwd FROM webcal_user WHERE cal_login = ?';
    $res = dbi_execute($sql, array($login));
    if ($res) {
        $row = dbi_fetch_row($res);
        if ($row && $row[0] != '') {
            // MySQL seems to do case insensitive matching, so double-check
            // the login.
            // also check if password matches
            if ($row[0] == $login && crypt($row[1], $crypt_password) == $crypt_password) {
                $ret = true;
            } else {
                $error = 'Invalid login';
            }
        } else {
            $error = 'Invalid login';
        }
        dbi_free_result($res);
    } else {
        $error = 'Database error: ' . dbi_error();
    }
    return $ret;
}
Example #16
0
                 if (strlen($ext_emails[$ext_count]) && empty($ext_names[$ext_count])) {
                     $ext_names[$ext_count] = $ext_emails[$ext_count];
                 }
                 $ext_count++;
             }
         }
     }
 }
 // Send notification if enabled.
 if (is_array($ext_names) && is_array($ext_emails)) {
     $ext_namescnt = count($ext_names);
     for ($i = 0; $i < $ext_namescnt; $i++) {
         if (strlen($ext_names[$i])) {
             if (!dbi_execute('INSERT INTO webcal_entry_ext_user
       ( cal_id, cal_fullname, cal_email ) VALUES ( ?, ?, ? )', array($id, $ext_names[$i], strlen($ext_emails[$i]) ? $ext_emails[$i] : null))) {
                 $error = $dberror . dbi_error();
             }
             // Send mail notification if enabled.
             // TODO:  Move this code into a function...
             if ($EXTERNAL_NOTIFICATIONS == 'Y' && $SEND_EMAIL != 'N' && strlen($ext_emails[$i]) > 0) {
                 if (!$newevent && isset($EXTERNAL_UPDATES) && $EXTERNAL_UPDATES == 'Y' || $newevent) {
                     $fmtdate = $timetype == 'T' ? date('Ymd', $eventstart) : gmdate('Ymd', $eventstart);
                     // Strip [\d] from duplicate Names before emailing.
                     $ext_names[$i] = trim(preg_replace('/\\[[\\d]]/', '', $ext_names[$i]));
                     $msg = str_replace('XXX', $ext_names[$i], $helloStr) . "\n\n" . str_replace('XXX', $login_fullname, $newevent ? $newAppStr : $updAppStr) . "\n" . str_replace('XXX', $name, $subjStr) . "\n\n" . str_replace('XXX', $description, $descStr) . "\n\n" . str_replace('XXX', date_to_str($fmtdate), $dateStr) . "\n" . ($timetype == 'T' ? str_replace('XXX', display_time('', !empty($GENERAL_USE_GMT) && $GENERAL_USE_GMT == 'Y' ? 3 : 6, $eventstart), $timeStr) : '') . $extra_email_data;
                     // Don't send HTML to external adresses.
                     // Always attach iCalendar file to external users
                     $mail->WC_Send($login_fullname, $ext_emails[$i], $ext_names[$i], $name, $msg, 'N', $from, $id);
                 }
             }
         }
Example #17
0
        $setting = substr($key, 6);
        // validate key name.  should start with "admin_" and not include
        // any unusual characters that might cause SQL injection
        if (!preg_match('/admin_[A-Za-z0-9_]+$/', $key)) {
            die_miserable_death('Invalid admin setting name "' . $key . '"');
        }
        if (strlen($setting) > 0) {
            $sql = "DELETE FROM webcal_config WHERE cal_setting = '{$setting}'";
            if (!dbi_query($sql)) {
                $error = translate("Error") . ": " . dbi_error() . "<br /><br /><span style=\"font-weight:bold;\">SQL:</span> {$sql}";
                break;
            }
            if (strlen($value) > 0) {
                $sql = "INSERT INTO webcal_config " . "( cal_setting, cal_value ) VALUES " . "( '{$setting}', '{$value}' )";
                if (!dbi_query($sql)) {
                    $error = translate("Error") . ": " . dbi_error() . "<br /><br /><span style=\"font-weight:bold;\">SQL:</span> {$sql}";
                    break;
                }
            }
        }
    }
}
if (empty($error)) {
    if (empty($ovrd)) {
        do_redirect("admin.php");
    } else {
        do_redirect("admin.php?ovrd={$ovrd}");
    }
}
print_header();
?>
Example #18
0
// If we are in single user mode, make sure that the login selected is
// a valid login.
if ($single_user == 'Y') {
    if (empty($single_user_login)) {
        die_miserable_death("You have not defined <tt>single_user_login</tt> in " . "<tt>includes/settings.php</tt>");
    }
    $res = dbi_query("SELECT COUNT(*) FROM webcal_user " . "WHERE cal_login = '******'");
    if (!$res) {
        echo "Database error: " . dbi_error();
        exit;
    }
    $row = dbi_fetch_row($res);
    if ($row[0] == 0) {
        // User specified as single_user_login does not exist
        if (!dbi_query("INSERT INTO webcal_user ( cal_login, " . "cal_passwd, cal_is_admin ) VALUES ( '{$single_user_login}', " . "'" . md5($single_user_login) . "', 'Y' )")) {
            die_miserable_death("User <tt>{$single_user_login}</tt> does not " . "exist in <tt>webcal_user</tt> table and was not able to add " . "it for you:<br /><blockquote>" . dbi_error() . "</blockquote>");
        }
        // User was added... should we tell them?
    }
    dbi_free_result($res);
}
// global settings have not been loaded yet, so check for public_access now
$res = dbi_query("SELECT cal_value FROM webcal_config " . "WHERE cal_setting = 'public_access'");
$pub_acc_enabled = false;
if ($res) {
    if ($row = dbi_fetch_row($res)) {
        if ($row[0] == "Y") {
            $pub_acc_enabled = true;
        }
    }
    dbi_free_result($res);
Example #19
0
} else {
    $app_user = $is_assistant || $is_nonuser_admin ? $user : $login;
}
if (empty($error) && $id > 0) {
    if (!dbi_query("UPDATE webcal_entry_user SET cal_status = 'R' " . "WHERE cal_login = '******' AND cal_id = {$id}")) {
        $error = translate("Error approving event") . ": " . dbi_error();
    } else {
        activity_log($id, $login, $app_user, $LOG_REJECT, "");
    }
    // Update any extension events related to this one.
    $res = dbi_query("SELECT cal_id FROM webcal_entry " . "WHERE cal_ext_for_id = {$id}");
    if ($res) {
        if ($row = dbi_fetch_row($res)) {
            $ext_id = $row[0];
            if (!dbi_query("UPDATE webcal_entry_user SET cal_status = 'R' " . "WHERE cal_login = '******' AND cal_id = {$ext_id}")) {
                $error = translate("Error approving event") . ": " . dbi_error();
            }
        }
        dbi_free_result($res);
    }
    // Email participants to notify that it was rejected.
    // Get list of participants
    $sql = "SELECT cal_login FROM webcal_entry_user WHERE cal_id = {$id} and cal_status = 'A'";
    //echo $sql."<br />";
    $res = dbi_query($sql);
    if ($res) {
        while ($row = dbi_fetch_row($res)) {
            $partlogin[] = $row[0];
        }
        dbi_free_result($res);
    }
Example #20
0
}
$updating_public = false;
if ($is_admin && !empty($public) && $public_access == "Y") {
    $updating_public = true;
    $layer_user = "******";
    $url = 'layers.php?public=1';
} else {
    $layer_user = $login;
    $url = 'layers.php';
}
$sql = "DELETE FROM webcal_user_pref WHERE cal_login = '******' " . "AND cal_setting = 'LAYERS_STATUS'";
dbi_query($sql);
$value = $status == "off" ? "N" : "Y";
$sql = "INSERT INTO webcal_user_pref " . "( cal_login, cal_setting, cal_value ) VALUES " . "( '{$layer_user}', 'LAYERS_STATUS', '{$value}' )";
if (!dbi_query($sql)) {
    $error = "Unable to update preference: " . dbi_error() . "<br /><br /><span style=\"font-weight:bold;\">SQL:</span> {$sql}";
    break;
}
if (empty($error)) {
    do_redirect($url);
}
print_header();
?>

<h2><?php 
etranslate("Error");
?>
</h2>

<?php 
etranslate("The following error occurred");
Example #21
0
function user_update_user_password($user, $password)
{
    global $error;
    $sql = "UPDATE webcal_user SET cal_passwd = '" . md5($password) . "' " . "WHERE cal_login = '******'";
    if (!dbi_query($sql)) {
        $error = translate("Database error") . ": " . dbi_error();
        return false;
    }
    return true;
}
function check_for_conflicts($dates, $duration, $hour, $minute, $participants, $login, $id)
{
    global $single_user_login, $single_user;
    global $repeated_events, $limit_appts, $limit_appts_number;
    if (!count($dates)) {
        return false;
    }
    $evtcnt = array();
    $sql = "SELECT distinct webcal_entry_user.cal_login, webcal_entry.cal_time," . "webcal_entry.cal_duration, webcal_entry.cal_name, " . "webcal_entry.cal_id, webcal_entry.cal_ext_for_id, " . "webcal_entry.cal_access, " . "webcal_entry_user.cal_status, webcal_entry.cal_date " . "FROM webcal_entry, webcal_entry_user " . "WHERE webcal_entry.cal_id = webcal_entry_user.cal_id " . "AND (";
    for ($x = 0; $x < count($dates); $x++) {
        if ($x != 0) {
            $sql .= " OR ";
        }
        $sql .= "webcal_entry.cal_date = " . date("Ymd", $dates[$x]);
    }
    $sql .= ") AND webcal_entry.cal_time >= 0 " . "AND webcal_entry_user.cal_status IN ('A','W') AND ( ";
    if ($single_user == "Y") {
        $participants[0] = $single_user_login;
    } else {
        if (strlen($participants[0]) == 0) {
            // likely called from a form with 1 user
            $participants[0] = $login;
        }
    }
    for ($i = 0; $i < count($participants); $i++) {
        if ($i > 0) {
            $sql .= " OR ";
        }
        $sql .= " webcal_entry_user.cal_login = '******'";
    }
    $sql .= " )";
    // make sure we don't get something past the end date of the
    // event we are saving.
    //echo "SQL: $sql<P>";
    $conflicts = "";
    $res = dbi_query($sql);
    $found = array();
    $count = 0;
    if ($res) {
        $time1 = sprintf("%d%02d00", $hour, $minute);
        $duration1 = sprintf("%d", $duration);
        while ($row = dbi_fetch_row($res)) {
            //Add to an array to see if it has been found already for the next part.
            $found[$count++] = $row[4];
            // see if either event overlaps one another
            if ($row[4] != $id && (empty($row[5]) || $row[5] != $id)) {
                $time2 = $row[1];
                $duration2 = $row[2];
                $cntkey = $user . "-" . $row[8];
                $evtcnt[$cntkey]++;
                $over_limit = 0;
                if ($limit_appts == "Y" && $limit_appts_number > 0 && $evtcnt[$cntkey] >= $limit_appts_number) {
                    $over_limit = 1;
                }
                if ($over_limit || times_overlap($time1, $duration1, $time2, $duration2)) {
                    $conflicts .= "<LI>";
                    if ($single_user == "Y") {
                        $conflicts .= "{$row['0']}: ";
                    }
                    if ($row[6] == 'R' && $row[0] != $login) {
                        $conflicts .= "(" . translate("Private") . ")";
                    } else {
                        $conflicts .= "<A HREF=\"view_entry.php?id={$row['4']}";
                        if ($user != $login) {
                            $conflicts .= "&user={$user}";
                        }
                        $conflicts .= "\">{$row['3']}</A>";
                    }
                    if ($duration2 == 24 * 60) {
                        $conflicts .= " (" . translate("All day event") . ")";
                    } else {
                        $conflicts .= " (" . display_time($time2);
                        if ($duration2 > 0) {
                            $conflicts .= "-" . display_time(add_duration($time2, $duration2));
                        }
                        $conflicts .= ")";
                    }
                    $conflicts .= " on " . date_to_str($row[8]);
                    if ($over_limit) {
                        $tmp = translate("exceeds limit of XXX events per day");
                        $tmp = str_replace("XXX", $limit_appts_number, $tmp);
                        $conflicts .= " (" . $tmp . ")";
                    }
                }
            }
        }
        dbi_free_result($res);
    } else {
        echo translate("Database error") . ": " . dbi_error();
        exit;
    }
    //echo "<br>hello";
    for ($q = 0; $q < count($participants); $q++) {
        $time1 = sprintf("%d%02d00", $hour, $minute);
        $duration1 = sprintf("%d", $duration);
        //This date filter is not necessary for functional reasons, but it eliminates some of the
        //events that couldn't possibly match.  This could be made much more complex to put more
        //of the searching work onto the database server, or it could be dropped all together to put
        //the searching work onto the client.
        $date_filter = "AND (webcal_entry.cal_date <= " . date("Ymd", $dates[count($dates) - 1]);
        $date_filter .= " AND (webcal_entry_repeats.cal_end IS NULL OR webcal_entry_repeats.cal_end >= " . date("Ymd", $dates[0]) . "))";
        //Read repeated events for the participants only once for a participant for
        //for performance reasons.
        $repeated_events = query_events($participants[$q], true, $date_filter);
        //for ($dd=0; $dd<count($repeated_events); $dd++) {
        //  echo $repeated_events[$dd]['cal_id'] . "<BR>";
        //}
        for ($i = 0; $i < count($dates); $i++) {
            $dateYmd = date("Ymd", $dates[$i]);
            $list = get_repeating_entries($participants[$q], $dateYmd);
            $thisyear = substr($dateYmd, 0, 4);
            $thismonth = substr($dateYmd, 4, 2);
            for ($j = 0; $j < count($list); $j++) {
                //okay we've narrowed it down to a day, now I just gotta check the time...
                //I hope this is right...
                $row = $list[$j];
                if ($row['cal_id'] != $id && $row['cal_ext_for_id'] != $id) {
                    $time2 = $row['cal_time'];
                    $duration2 = $row['cal_duration'];
                    if (times_overlap($time1, $duration1, $time2, $duration2)) {
                        $conflicts .= "<LI>";
                        if ($single_user != "Y") {
                            $conflicts .= $row['cal_login'] . ": ";
                        }
                        if ($row['cal_access'] == 'R' && $row['cal_login'] != $login) {
                            $conflicts .= "(" . translate("Private") . ")";
                        } else {
                            $conflicts .= "<A HREF=\"view_entry.php?id=" . $row['cal_id'];
                            if ($user != $login) {
                                $conflicts .= "&user={$user}";
                            }
                            $conflicts .= "\">" . $row['cal_name'] . "</A>";
                        }
                        $conflicts .= " (" . display_time($time2);
                        if ($duration2 > 0) {
                            $conflicts .= "-" . display_time(add_duration($time2, $duration2));
                        }
                        $conflicts .= ")";
                        $conflicts .= " on " . date("l, F j, Y", $dates[$i]);
                    }
                }
            }
        }
    }
    return $conflicts;
}
Example #23
0
// points to the base WebCalendar directory relative to
// current working directory
$includedir = "../includes";
include "{$includedir}/config.php";
include "{$includedir}/php-dbi.php";
include "{$includedir}/functions.php";
include "{$includedir}/{$user_inc}";
include "{$includedir}/site_extras.php";
$debug = false;
// set to true to print debug info...
$only_testing = false;
// act like we're sending, but don't send -- for debugging
// Establish a database connection.
$c = dbi_connect($db_host, $db_login, $db_password, $db_database);
if (!$c) {
    echo "Error connecting to database: " . dbi_error();
    exit;
}
load_global_settings();
include "{$includedir}/translate.php";
if ($debug) {
    echo "<br />\n";
}
// Get a list of people who have asked not to receive email
$res = dbi_query("SELECT cal_login FROM webcal_user_pref " . "WHERE cal_setting = 'EMAIL_REMINDER' " . "AND cal_value = 'N'");
$noemail = array();
if ($res) {
    while ($row = dbi_fetch_row($res)) {
        $user = $row[0];
        $noemail[$user] = 1;
        if ($debug) {
Example #24
0
/**
 * Executes a SQL query.
 *
 * <b>Note:</b> Use the {@link dbi_error()} function to get error information
 * if the connection fails.
 *
 * @param string $sql          SQL of query to execute
 * @param bool   $fatalOnError Abort execution if there is a database error?
 * @param bool   $showError    Display error to user (including possibly the
 *                             SQL) if there is a database error?
 *
 * @return mixed The query result resource on queries (which can then be
 *               passed to the {@link dbi_fetch_row()} function to obtain the
 *               results), or true/false on insert or delete queries.
 */
function dbi_query($sql, $fatalOnError = true, $showError = true)
{
    global $phpdbiVerbose;
    if (strcmp($GLOBALS["db_type"], "mysql") == 0) {
        $res = mysql_query($sql);
        if (!$res) {
            dbi_fatal_error("Error executing query." . $phpdbiVerbose ? dbi_error() . "\n\n<br />\n" . $sql : "" . "", $fatalOnError, $showError);
        }
        return $res;
    } else {
        if (strcmp($GLOBALS["db_type"], "mysqli") == 0) {
            $res = mysqli_query($GLOBALS["db_connection"], $sql);
            if (!$res) {
                dbi_fatal_error("Error executing query." . $phpdbiVerbose ? dbi_error() . "\n\n<br />\n" . $sql : "" . "", $fatalOnError, $showError);
            }
            return $res;
        } else {
            if (strcmp($GLOBALS["db_type"], "mssql") == 0) {
                $res = mssql_query($sql);
                if (!$res) {
                    dbi_fatal_error("Error executing query." . $phpdbiVerbose ? dbi_error() . "\n\n<br />\n" . $sql : "" . "", $fatalOnError, $showError);
                }
                return $res;
            } else {
                if (strcmp($GLOBALS["db_type"], "oracle") == 0) {
                    $GLOBALS["oracle_statement"] = OCIParse($GLOBALS["oracle_connection"], $sql);
                    return OCIExecute($GLOBALS["oracle_statement"], OCI_COMMIT_ON_SUCCESS);
                } else {
                    if (strcmp($GLOBALS["db_type"], "postgresql") == 0) {
                        @($GLOBALS["postgresql_row[\"{$res}\"]"] = 0);
                        $res = pg_exec($GLOBALS["postgresql_connection"], $sql);
                        if (!$res) {
                            dbi_fatal_error("Error executing query." . $phpdbiVerbose ? dbi_error() . "\n\n<br />\n" . $sql : "" . "", $fatalOnError, $showError);
                        }
                        $GLOBALS["postgresql_numrows[\"{$res}\"]"] = pg_numrows($res);
                        return $res;
                    } else {
                        if (strcmp($GLOBALS["db_type"], "odbc") == 0) {
                            return odbc_exec($GLOBALS["odbc_connection"], $sql);
                        } else {
                            if (strcmp($GLOBALS["db_type"], "ibm_db2") == 0) {
                                $res = db2_exec($GLOBALS["ibm_db2_connection"], $sql);
                                if (!$res) {
                                    dbi_fatal_error("Error executing query." . $phpdbiVerbose ? dbi_error() . "\n\n<br />\n" . $sql : "" . "", $fatalOnError, $showError);
                                }
                                return $res;
                            } else {
                                if (strcmp($GLOBALS["db_type"], "ibase") == 0) {
                                    $res = ibase_query($sql);
                                    if (!$res) {
                                        dbi_fatal_error("Error executing query." . $phpdbiVerbose ? dbi_error() . "\n\n<br />\n" . $sql : "" . "", $fatalOnError, $showError);
                                    }
                                    return $res;
                                } else {
                                    dbi_fatal_error("dbi_query(): db_type not defined.");
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
Example #25
0
        if ($row[0] == $id) {
            $is_my_event = true;
            echo "Event # " . $id . " is already on your calendar.";
            exit;
        }
        dbi_free_result($res);
    }
    // Now lets make sure the user is allowed to add the event (not private)
    $sql = "SELECT cal_access FROM webcal_entry WHERE cal_id = " . $id;
    $res = dbi_query($sql);
    if (!$res) {
        echo translate("Invalid entry id") . ": {$id}";
        exit;
    }
    $row = dbi_fetch_row($res);
    if ($row[0] == "R" && !$is_my_event) {
        $is_private = true;
        etranslate("This is a private event and may not be added to your calendar.");
        exit;
    } else {
        $is_private = false;
    }
    // add the event
    if ($readonly == "N" && !$is_my_event && !$is_private) {
        if (!dbi_query("INSERT INTO webcal_entry_user ( cal_id, cal_login, cal_status ) VALUES ( {$id}, '{$login}', 'A' )")) {
            $error = translate("Error adding event") . ": " . dbi_error();
        }
    }
}
send_to_preferred_view();
exit;
Example #26
0
                 $login = $login_pw[0];
                 $cryptpw = $login_pw[1];
                 // Security fix.  Don't allow certain types of characters in
                 // the login.  WebCalendar does not escape the login name in
                 // SQL requests.  So, if the user were able to set the login
                 // name to be "x';drop table u;",
                 // they may be able to affect the database.
                 if (!empty($login)) {
                     if ($login != addslashes($login)) {
                         die_miserable_death("Illegal characters in login " . "<tt>" . htmlentities($login) . "</tt>");
                     }
                 }
                 // make sure we are connected to the database for password check
                 $c = @dbi_connect($db_host, $db_login, $db_password, $db_database);
                 if (!$c) {
                     die_miserable_death("Error connecting to database:<blockquote>" . dbi_error() . "</blockquote>\n");
                 }
                 doDbSanityCheck();
                 if (!user_valid_crypt($login, $cryptpw)) {
                     do_debug("User not logged in; redirecting to login page");
                     if (empty($login_return_path)) {
                         do_redirect("login.php");
                     } else {
                         do_redirect("login.php?return_path={$login_return_path}");
                     }
                 }
                 do_debug("Decoded login from cookie: {$login}");
             }
         }
     }
 }
Example #27
0
include_once 'includes/init.php';
load_user_layers();
$status = getValue('status', '(on|off)', true);
$public = getValue('public');
if ($ALLOW_VIEW_OTHER != 'Y') {
    print_header();
    echo print_not_auth(7) . print_trailer();
    exit;
}
$updating_public = false;
$url = 'layers.php';
if ($is_admin && !empty($public) && $PUBLIC_ACCESS == 'Y') {
    $updating_public = true;
    $layer_user = '******';
    $url .= '?public=1';
} else {
    $layer_user = $login;
}
dbi_execute('DELETE FROM webcal_user_pref WHERE cal_login = ?
  AND cal_setting = \'LAYERS_STATUS\'', array($layer_user));
$sql = 'INSERT INTO webcal_user_pref ( cal_login, cal_setting, cal_value )
  VALUES ( ?, \'LAYERS_STATUS\', ? )';
if (!dbi_execute($sql, array($layer_user, $status == 'off' ? 'N' : 'Y'))) {
    $error = translate('Unable to update preference') . ': ' . dbi_error() . '<br /><br /><span class="bold">SQL:</span> ' . $sql;
    break;
}
if (empty($error)) {
    do_redirect($url);
}
print_header();
echo print_error($error, true) . print_trailer();
             }
             if ($row[1] == 'A') {
                 $approved[$num_app++] = $pname;
             } else {
                 if ($row[1] == 'W') {
                     $waiting[$num_wait++] = $pname;
                 } else {
                     if ($row[1] == 'R') {
                         $rejected[$num_rej++] = $pname;
                     }
                 }
             }
         }
         dbi_free_result($res);
     } else {
         echo translate("Database error") . ": " . dbi_error() . "<br />\n";
     }
 }
 for ($i = 0; $i < $num_app; $i++) {
     user_load_variables($approved[$i], "temp");
     if (strlen($tempemail)) {
         echo "<a href=\"mailto:" . $tempemail . "?subject={$subject}\">" . $tempfullname . "</a><br />\n";
         $allmails[] = $tempemail;
     } else {
         echo $tempfullname . "<br />\n";
     }
 }
 // show external users here...
 if (!empty($allow_external_users) && $allow_external_users == "Y") {
     $external_users = event_get_external_users($id, 1);
     $ext_users = explode("\n", $external_users);
            $sql .= " cal_lastname = '{$nlastname}', ";
        }
        if ($nfirstname) {
            $sql .= " cal_firstname = '{$nfirstname}', ";
        }
        $sql .= "cal_admin = '{$nadmin}' WHERE cal_login = '******'";
        if (!dbi_query($sql)) {
            $error = translate("Database error") . ": " . dbi_error();
        }
    } else {
        // Adding
        if (preg_match("/^[\\w]+\$/", $nid)) {
            $nid = $NONUSER_PREFIX . $nid;
            $sql = "INSERT INTO webcal_nonuser_cals " . "( cal_login, cal_firstname, cal_lastname, cal_admin ) " . "VALUES ( '{$nid}', '{$nfirstname}', '{$nlastname}', '{$nadmin}' )";
            if (!dbi_query($sql)) {
                $error = translate("Database error") . ": " . dbi_error();
            }
        } else {
            $error = translate("Calendar ID") . " " . translate("word characters only") . ".";
        }
    }
}
if (!empty($error)) {
    print_header('', '', '', true);
    ?>

<h2><?php 
    etranslate("Error");
    ?>
</h2>
Example #30
0
<!-- in if -->';
    $cnt = 0;
    while (($row = dbi_fetch_row($res)) && $cnt < $num) {
        $out .= '
<!-- in while type: $row[2] -->
  <log>
    <login>' . ws_escape_xml($row[0]) . '</login>
    <calendar>' . ws_escape_xml($row[1]) . '</calendar>
    <type>' . ws_escape_xml($row[2]) . '</type>
    <date>' . ws_escape_xml($row[3]) . '</date>
    <time>' . ws_escape_xml($row[4]) . '</time>
    <action>' . ws_escape_xml($row[5]) . '</action>
    <id>' . ws_escape_xml($row[6]) . '</id>
  </log>
';
        $cnt++;
    }
    dbi_free_result($res);
} else {
    $out .= '
  <error>' . ws_escape_xml(dbi_error()) . '</error>';
}
$out .= '
</activitylog>
';
// If web servic debugging is on...
if (!empty($WS_DEBUG) && $WS_DEBUG) {
    ws_log_message($out);
}
// Send output now...
echo $out;