Exemplo n.º 1
0
 function addBook($query)
 {
     $db = new Database();
     if ($db->error()) {
         echo $db->error();
     } else {
         $db->query($query);
     }
 }
Exemplo n.º 2
0
 /**
  * @param $query
  * @param $h Database
  * @param int $resultless
  * @throws Exception
  */
 function __construct($query, &$h, $resultless = 0)
 {
     $this->parent = $h;
     $this->query = $query;
     $this->q = mysql_query($query, $this->parent->dbh);
     if (!$this->q) {
         throw new Exception($this->parent->error());
     }
 }
Exemplo n.º 3
0
 private function getUserValues($arrayUser)
 {
     $uname = $arrayUser["username"];
     $upass = $arrayUser["password"];
     $email = $arrayUser["email"];
     $time = time();
     $db = new Database();
     $query = "INSERT INTO users(user_name,user_password_hash,user_email,user_registration_datetime) VALUES('{$uname}','{$upass}','{$email}',{$time})";
     $db->query($query);
     if ($db->error()) {
         echo $db->error();
     } else {
         header("Location: /");
     }
 }
Exemplo n.º 4
0
 public function set_new_two_way($accountId, $secret)
 {
     /* Controleren of de gebruiker rechten heeft. */
     if (Permission::has('panel_account_two_way')) {
         /* Update query uitvoeren om de secret in te stellen. */
         $update = Database::query("UPDATE customer SET secret = '" . Database::escape($secret) . "' WHERE id = " . Database::escape($accountId));
         /* Kijken of de query is gelukt. */
         if ($update) {
             /* Secret instellen zodat de two-way geactiveerd is in de huidige sessie. */
             $_SESSION['login']['secret'] = true;
         } else {
             /* Query ging fout, geef foutmelding terug. */
             throw new Exception(Database::error());
         }
     }
 }
Exemplo n.º 5
0
 /**
  * Get recent posts
  *
  * Returns an array of all recent posts, given a certain posts amount.
  *
  * @param int $amount Number of posts to get (defaults to 10).
  * @param int $offset How many posts to skip.
  * @return array Array of {@link Post} instances of all recent posts.
  */
 function getRecentPosts($amount = '%', $offset = 0)
 {
     // default amount from setting
     if ($amount == '%') {
         $amount = $this->getSetting('recent_count');
     }
     // db query
     $sql = 'SELECT `postid`, `time`, `content`, `comments_count` ' . 'FROM `+posts` ' . 'WHERE 1 ' . 'ORDER BY `postid` DESC ' . 'LIMIT ' . ($offset + 0) . ',' . ($amount + 0);
     $q = $this->db->query($sql) or $this->displayError('site->getRecentPosts', $this->db->error());
     $recent = array();
     while ($postdata = $this->db->fetch_assoc($q)) {
         $post = new Post($this);
         $post->fetch_from_array($postdata);
         $recent[] = $post;
     }
     // while
     return $recent;
 }
Exemplo n.º 6
0
$stmt = "SELECT Title, Contents FROM _posts WHERE Post_ID = ?";
$types = "i";
$array_of_binds = array($post_id);
$result = $db->fetch($stmt, $types, $array_of_binds);
if ($result !== false) {
    $title = $result[0]['Title'];
    $contents = $result[0]['Contents'];
    $something_wrong = false;
}
// Form the site, according to whether one is logged or not
$navbar = "<a class='blog-nav-item' href='index.php'>Home</a>";
$navbar .= "<a class='blog-nav-item' href='addpost.php'>Add Post</a>";
$navbar .= "<a class='blog-nav-item' href='logout.php'>Logout</a>";
// Form main content
if ($something_wrong) {
    $main = $db->error();
} else {
    $main = '
		<div class="col-sm-8 blog-main">
			<form id="form-addpost" class="form-signin" action="editpost_submit.php" method="post">
				<h2 class="form-signin-heading">Edit Post</h2>
				<label for="title" class="sr-only">Title</label>
				<input value=' . $title . ' id="title" class="form-control" name="title" placeholder="Title of the post" maxlength="255" required autofocus>
				<p>The title can only contain a maximum of 255 characters.</p>
				<label for="contents" class="sr-only">Contents</label>
				<textarea id="contents" class="form-control" name="contents" placeholder="Contents of the post" required>' . $contents . '</textarea>
				<p>Github Markdown formatting is supported. Check this <a href="https://guides.github.com/features/mastering-markdown/">link</a> for details.</p>
				<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />
				<input type="hidden" name="post_id" value="<?php echo $post_id; ?>" />
				<button id="form-submit" class="btn btn-lg btn-primary btn-block" type="submit">Edit Post</button>
			</form>
Exemplo n.º 7
0
    $message = "An error has occured. Please try again.";
} else {
    $user_id = $_SESSION['user_id'];
    $title = $_POST['title'];
    $contents = $_POST['contents'];
    $db = new Database();
    $stmt = "INSERT INTO _posts (User_ID, Title, Contents) VALUES (?, ?, ?)";
    $types = "sss";
    $array_of_binds = array($user_id, $title, $contents);
    if ($db->query($stmt, $types, $array_of_binds)) {
        $something_wrong = false;
        header('refresh: 3; url = index.php');
        $message = "Post has been successfully added!";
        $message .= "<br /> <a href='index.php'>Click here if you are not redirected.</a>";
    } else {
        $message = $db->error();
    }
}
if ($something_wrong) {
    $message .= "<br /> <a href='addpost.php'>Re-add post</a>";
}
// Form the navbar
$navbar = "<a class='blog-nav-item' href='index.php'>Home</a>";
$navbar .= "<a class='blog-nav-item active' href='addpost.php'>Add Post</a>";
$navbar .= "<a class='blog-nav-item' href='logout.php'>Logout</a>";
?>

<!DOCTYPE html>
<html lang='en'>
	<head>
		<meta charset='utf-8'>
Exemplo n.º 8
0
 public static function pay_subscription($subscription_id, $month, $account_from, $finish_month = false)
 {
     /* Pak de rekeningnummer van CityPark. */
     $account_to = Config::$bank_account;
     /* Haal de maand prijs op en vermenigvuldig dit met $month. */
     $amount = $month * Settings::get('citypark_subscription_month_cost');
     /* Kijken of we de laatste paar dagen moeten berekenen. */
     if ($finish_month) {
         /* Haal totaal aantal dagen op van deze maand. */
         $days_in_month = Date('t');
         /* Bereken het resterende aantal dagen op van deze maand. */
         $days = $days_in_month - Date('j');
         /* Bereken de kosten van 1 dag deze maand. */
         $amount_one_day = $amount / $days_in_month;
         /* Bereken de kosten van de overgebleven dagen. */
         $amount_left = $amount_one_day * $days;
         /* Rond het getal af omhoog, en replace een eventuele komma met een punt. */
         $amount = str_replace(',', '.', round($amount_left, 2, PHP_ROUND_HALF_UP));
     }
     /* Kijken of de transactie is gelukt. */
     if (Bank_api::transfer($amount, $account_from, $account_to)) {
         /* Succesvol overgemaakt, update query maken. */
         $update = Database::query("UPDATE subscription SET last_paid = NOW() WHERE sub_number = " . Database::escape($subscription_id));
         /* Kijken of de query is gelukt. */
         if ($update) {
             /* Customer ID ophalen. */
             $select = Database::query("SELECT customer_id FROM subscription WHERE sub_number = " . Database::escape($subscription_id) . " LIMIT 1");
             /* Kijken of de select query gelukt is. */
             if ($select) {
                 /* Haal de customer ID op. */
                 $cid = $select->fetch_object()->customer_id;
                 /* Probeer onderstaande. */
                 try {
                     /* Nieuw invoice object aanmaken. */
                     $invoice = new Invoice();
                     /* Nieuw factuur aanmaken. */
                     $invoice_id = $invoice->new_invoice($cid);
                     /* Factuur regel aanmaken. */
                     /* $amount bevat in dit geval de prijs wat er betaald is. */
                     $invoice->add_item('Abonnement kosten', 'Van ' . Date('d-m-Y') . ' tot ' . Date('t-m-Y') . '.', '1', $amount);
                     /* Factuur als betaald instellen. */
                     $invoice->set_paid();
                 } catch (Exception $e) {
                     /* Er ging wat fout bij het aanmaken van het factuur. */
                     throw new Exception($e->getMessage());
                 }
                 /* Return een true. */
                 return true;
             } else {
                 /* Foutmelding. */
                 throw new Exception('Er ging wat fout bij het ophalen van uw gegevens voor het factuur.<br />' . Database::error());
             }
         } else {
             /* Query is gefaalt, gooi foutmelding. */
             throw new Exception('Er ging wat fout bij het updaten van de betaling in de database.<br />' . Database::error());
         }
     } else {
         /* Kon niet overmaken. */
         return false;
     }
 }
Exemplo n.º 9
0
 function error($message)
 {
     if ($this->debug) {
         $message = $this->error(pg_last_error($this->link_id));
     }
     parent::error($message);
 }
Exemplo n.º 10
0
 public static function remove_solo($id, $pid)
 {
     /* Permissie check. */
     if (Permission::has('operator_permission_edit')) {
         /* Escape ID. */
         $id = Database::escape($id);
         /* Escape permission id. */
         $pid = Database::escape($pid);
         /* Select query. */
         $select = Database::query("SELECT id FROM permission_customer_has WHERE customer_id = " . $id . " AND permission_id = " . $pid . " LIMIT 1");
         /* Kijken of query gelukt is. */
         if ($select) {
             /* Kijken of het item bestaat. */
             if ($select->num_rows != 0) {
                 /* Delete query */
                 $delete = Database::query("DELETE FROM permission_customer_has WHERE customer_id = " . $id . " AND permission_id = " . $pid . " LIMIT 1");
                 /* Delete check */
                 if (!$delete) {
                     /* Foutmelding. */
                     throw new Exception('Er ging wat fout bij het verwijderen van de recht.<Br />' . Database::error());
                 }
             } else {
                 /* Bestaat niet. */
                 throw new Exception('De recht die u wenst te verijderen bestaat niet.');
             }
         } else {
             /* Foutmelding. */
             throw new Exception('Er ging wat fout bij de controle.<br />' . Database::error());
         }
     } else {
         /* Geen rechten. */
         throw new Exception('U heeft niet de bevoegdheden om rechten toe te mogen voegen,');
     }
 }
Exemplo n.º 11
0
    /**
     * Import the aicc object (as a result from the parse_config_files function) into the database structure
     * @param	string	Unique course code
     * @return	bool	Returns -1 on error
     */
    function import_aicc($course_code) {
        $course_id = api_get_course_int_id();

        if ($this->debug > 0) { error_log('New LP - In aicc::import_aicc('.$course_code.')', 0); }
        // Get table names.
        $new_lp = 'lp';
        $new_lp_item = 'lp_item';

        // The previous method wasn't safe to get the database name, so do it manually with the course_code.
        $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." WHERE code='$course_code'";
        $res = Database::query($sql);
        if (Database::num_rows($res) < 1) { error_log('New LP - Database for '.$course_code.' not found '.__FILE__.' '.__LINE__, 0); return -1; }
        $row = Database::fetch_array($res);

        $new_lp = Database::get_course_table(TABLE_LP_MAIN);
        $new_lp_item = Database::get_course_table(TABLE_LP_ITEM);
        $get_max = "SELECT MAX(display_order) FROM $new_lp WHERE c_id = $course_id";
        $res_max = Database::query($get_max);
        if (Database::num_rows($res_max) < 1) {
            $dsp = 1;
        } else {
            $row = Database::fetch_array($res_max);
            $dsp = $row[0] + 1;
        }

        $this->config_encoding = "ISO-8859-1"; // TODO: We may apply detection for this value, see the function api_detect_encoding().

        $sql = "INSERT INTO $new_lp (c_id, lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib, content_maker,display_order)" .
                "VALUES " .
                "($course_id, 3, '".$this->course_title."', '".$this->course_id."','".$this->course_description."'," .
                "'".$this->subdir."', 0, 'embedded', '".$this->config_encoding."'," .
                "'aicc_api.php','".$this->course_creator."',$dsp)";
        if ($this->debug > 2) { error_log('New LP - In import_aicc(), inserting path: '. $sql, 0); }
        $res = Database::query($sql);
        $lp_id = Database::insert_id();
        $this->lp_id = $lp_id;
        api_item_property_update(api_get_course_info($course_code), TOOL_LEARNPATH, $this->lp_id, 'LearnpathAdded', api_get_user_id());
        api_item_property_update(api_get_course_info($course_code), TOOL_LEARNPATH, $this->lp_id, 'visible', api_get_user_id());

        $previous = 0;
        foreach ($this->aulist as $identifier => $dummy) {
            $oAu =& $this->aulist[$identifier];
            //echo "Item ".$oAu->identifier;
            $field_add = '';
            $value_add = '';
            if (!empty($oAu->masteryscore)) {
                $field_add = 'mastery_score, ';
                $value_add = $oAu->masteryscore.',';
            }
            $title = $oAu->identifier;
            if (is_object($this->deslist[$identifier])) {
                $title = $this->deslist[$identifier]->title;
            }
            $path = $oAu->path;
            //$max_score = $oAu->max_score // TODO: Check if special constraint exists for this item.
            //$min_score = $oAu->min_score // TODO: Check if special constraint exists for this item.
            $parent = 0; // TODO: Deal with the parent.
            $previous = 0;
            $prereq = $oAu->prereq_string;
            //$previous = (!empty($this->au_order_list_new_id[x]) ? $this->au_order_list_new_id[x] : 0); // TODO: Deal with the previous.
            $sql_item = "INSERT INTO $new_lp_item (c_id, lp_id,item_type,ref,title, path,min_score,max_score, $field_add parent_item_id,previous_item_id,next_item_id, prerequisite,display_order) " .
                    "VALUES " .
                    "($course_id, $lp_id, 'au','".$oAu->identifier."','".$title."'," .
                    "'$path',0,100, $value_add" .
                    "$parent, $previous, 0, " .
                    "'$prereq', 0" .
                    ")";
            $res_item = Database::query($sql_item);
            if ($this->debug > 1) { error_log('New LP - In aicc::import_aicc() - inserting item : '.$sql_item.' : '.Database::error(), 0); }
            $item_id = Database::insert_id();
            // Now update previous item to change next_item_id.
            if ($previous != 0) {
                $upd = "UPDATE $new_lp_item SET next_item_id = $item_id WHERE c_id = $course_id AND id = $previous";
                $upd_res = Database::query($upd);
                // Update the previous item id.
            }
            $previous = $item_id;
        }
    }
Exemplo n.º 12
0
/**
 * Displays step 3 - a form where the user can enter the installation settings
 * regarding the databases - login and password, names, prefixes, single
 * or multiple databases, tracking or not...
 */
function display_database_settings_form($installType, $dbHostForm, $dbUsernameForm, $dbPassForm, $dbPrefixForm, $enableTrackingForm, $singleDbForm, $dbNameForm, $dbStatsForm, $dbScormForm, $dbUserForm) {

    if ($installType == 'update') {
        global $_configuration, $update_from_version_6;

        if (in_array($_POST['old_version'], $update_from_version_6)) {
            $dbHostForm         = get_config_param('dbHost');

            $dbUsernameForm     = get_config_param('dbLogin');
            $dbPassForm         = get_config_param('dbPass');
            $dbPrefixForm       = get_config_param('dbNamePrefix');
            $enableTrackingForm = get_config_param('is_trackingEnabled');
            $singleDbForm       = get_config_param('singleDbEnabled');
            $dbHostForm         = get_config_param('mainDbName');

            $dbStatsForm        = get_config_param('statsDbName');
            $dbScormForm        = get_config_param('scormDbName');
            $dbUserForm         = get_config_param('user_personal_database');
            $dbScormExists      = true;
        } else {
            $dbHostForm         = $_configuration['db_host'];
            $dbUsernameForm     = $_configuration['db_user'];
            $dbPassForm         = $_configuration['db_password'];
            $dbPrefixForm       = $_configuration['db_prefix'];
            $enableTrackingForm = $_configuration['tracking_enabled'];
            $singleDbForm       = $_configuration['single_database'];
            $dbNameForm         = $_configuration['main_database'];
            $dbStatsForm        = $_configuration['statistics_database'];
            $dbScormForm        = $_configuration['scorm_database'];
            $dbUserForm         = $_configuration['user_personal_database'];
            $dbScormExists      = true;
        }

        if (empty($dbScormForm)) {
            if ($singleDbForm) {
                $dbScormForm = $dbNameForm;
            } else {
                $dbScormForm = $dbPrefixForm.'scorm';
                $dbScormExists = false;
            }
        }

        if (empty($dbUserForm)) {
            $dbUserForm = $singleDbForm ? $dbNameForm : $dbPrefixForm.'chamilo_user';
        }
        echo '<div class="RequirementHeading"><h2>' . display_step_sequence() .get_lang('DBSetting') . '</h2></div>';
        echo '<div class="RequirementContent">';
        echo get_lang('DBSettingUpgradeIntro');
        echo '</div>';
    } else {
        if (empty($dbPrefixForm)) { //make sure there is a default value for db prefix
            $dbPrefixForm = '';
        }
        echo '<div class="RequirementHeading"><h2>' . display_step_sequence() .get_lang('DBSetting') . '</h2></div>';
        echo '<div class="RequirementContent">';
        echo get_lang('DBSettingIntro');
        echo '</div>';
    }
    ?>
    </td>
    </tr>
    <tr>
    <td>
    <table class="data_table_no_border">
    <tr>
      <td width="40%"><?php echo get_lang('DBHost'); ?> </td>
      <?php if ($installType == 'update'): ?>
      <td width="30%"><input type="hidden" name="dbHostForm" value="<?php echo htmlentities($dbHostForm); ?>" /><?php echo $dbHostForm; ?></td>
      <td width="30%">&nbsp;</td>
      <?php else: ?>
      <td width="30%"><input type="text" size="25" maxlength="50" name="dbHostForm" value="<?php echo htmlentities($dbHostForm); ?>" /></td>
      <td width="30%"><?php echo get_lang('EG').' localhost'; ?></td>
      <?php endif; ?>
    </tr>
    <tr>
    <?php
    //database user username
    $example_login = get_lang('EG').' root';
    display_database_parameter($installType, get_lang('DBLogin'), 'dbUsernameForm', $dbUsernameForm, $example_login);

    //database user password
    $example_password = get_lang('EG').' '.api_generate_password();
    display_database_parameter($installType, get_lang('DBPassword'), 'dbPassForm', $dbPassForm, $example_password);

    echo '<input type="hidden" name="enableTrackingForm" value="1" />';

    $style = '';
    if ($installType == INSTALL_TYPE_UPDATE) {
        $style = '';
    }

    //Database Name fix replace weird chars
    if ($installType != INSTALL_TYPE_UPDATE) {
        $dbNameForm = str_replace(array('-','*', '$', ' ', '.'), '', $dbNameForm);
        $dbNameForm = replace_dangerous_char($dbNameForm);
    }

    display_database_parameter($installType, get_lang('MainDB'), 'dbNameForm',  $dbNameForm,  '&nbsp;', null, 'id="optional_param1" '.$style);

    //Only for updates we show this options
    if ($installType == INSTALL_TYPE_UPDATE) {
        display_database_parameter($installType, get_lang('StatDB'), 'dbStatsForm', $dbStatsForm, '&nbsp;', null, 'id="optional_param2" '.$style);
        if ($installType == INSTALL_TYPE_UPDATE && in_array($_POST['old_version'], $update_from_version_6)) {
            display_database_parameter($installType, get_lang('ScormDB'), 'dbScormForm', $dbScormForm, '&nbsp;', null, 'id="optional_param3" '.$style);
        }
        display_database_parameter($installType, get_lang('UserDB'), 'dbUserForm', $dbUserForm, '&nbsp;', null, 'id="optional_param4" '.$style);
    }
    ?>
    <tr>
        <td></td>
        <td>
            <button type="submit" class="btn" name="step3" value="<?php echo get_lang('CheckDatabaseConnection'); ?>" >
                <?php echo get_lang('CheckDatabaseConnection'); ?></button>
        </td>
    </tr>
    <tr>
        <td>

        <?php

        $dbConnect = test_db_connect($dbHostForm, $dbUsernameForm, $dbPassForm, $singleDbForm, $dbPrefixForm, $dbNameForm);

        $database_exists_text = '';

        if (database_exists($dbNameForm)) {
            $database_exists_text = '<div class="warning-message">'.get_lang('ADatabaseWithTheSameNameAlreadyExists').'</div>';
        } else {
            if ($dbConnect == -1) {
                 $database_exists_text = '<div class="warning-message">'.sprintf(get_lang('UserXCantHaveAccessInTheDatabaseX'), $dbUsernameForm, $dbNameForm).'</div>';
            } else {
                 //Try to create the database
                $user_can_create_databases = false;
                $multipleDbCheck = @Database::query("CREATE DATABASE ".mysql_real_escape_string($dbNameForm));
                if ($multipleDbCheck !== false) {
                    $multipleDbCheck = @Database::query("DROP DATABASE IF EXISTS ".mysql_real_escape_string($dbNameForm));
                    $user_can_create_databases = true;
                }

                if ($user_can_create_databases) {
                    $database_exists_text = '<div class="normal-message">'.sprintf(get_lang('DatabaseXWillBeCreated'), $dbNameForm, $dbUsernameForm).'</div>';
                } else {
                    $dbConnect = 0;
                    $database_exists_text = '<div class="warning-message">'.sprintf(get_lang('DatabaseXCantBeCreatedUserXDoestHaveEnoughPermissions'), $dbNameForm, $dbUsernameForm).'</div>';
                }
            }
        }

        if ($dbConnect == 1): ?>
        <td colspan="2">
            <?php echo $database_exists_text ?>
            <div id="db_status" class="confirmation-message">
                Database host: <strong><?php echo Database::get_host_info(); ?></strong><br />
                Database server version: <strong><?php echo Database::get_server_info(); ?></strong><br />
                Database client version: <strong><?php echo Database::get_client_info(); ?></strong><br />
                Database protocol version: <strong><?php echo Database::get_proto_info(); ?></strong>
                <div style="clear:both;"></div>
            </div>
        </td>
        <?php else: ?>
        <td colspan="2">
            <?php echo $database_exists_text ?>
            <div id="db_status" style="float:left;" class="error-message">
                <div style="float:left;">
                    <strong><?php echo get_lang('FailedConectionDatabase'); ?></strong><br />
                    <strong>Database error: <?php echo Database::errno(); ?></strong><br />
                    <?php echo Database::error().'<br />'; ?>
                </div>
            </div>
        </td>
        <?php endif; ?>
    </tr>
    <tr>
      <td>
          <button type="submit" name="step2" class="back" value="&lt; <?php echo get_lang('Previous'); ?>" ><?php echo get_lang('Previous'); ?></button>
      </td>
      <td>&nbsp;</td>
      <td align="right">
          <input type="hidden" name="is_executable" id="is_executable" value="-" />
           <?php if ($dbConnect == 1) { ?>
            <button type="submit"  class="btn next" name="step4" value="<?php echo get_lang('Next'); ?> &gt;" /><?php echo get_lang('Next'); ?></button>
          <?php } else { ?>
            <button disabled="disabled" type="submit" class="btn next disabled" name="step4" value="<?php echo get_lang('Next'); ?> &gt;" /><?php echo get_lang('Next'); ?></button>
          <?php } ?>
      </td>
    </tr>
    </table>
    <?php
}
Exemplo n.º 13
0
 public static function operator_show($id)
 {
     /* Permission check. */
     if (Permission::has('operator_subscription_list')) {
         /* ID Escapen. */
         $id = Database::escape($id);
         /* Select query. */
         $select = Database::query("SELECT c.username, c.email, c.secret, c.active, UNIX_TIMESTAMP(c.register_date) AS register_date, ci.* FROM customer AS c INNER JOIN customer_info AS ci ON ci.customer_id = c.id WHERE c.id = " . $id);
         /* Query controle. */
         if ($select) {
             /* Kijken of er een result is. */
             if ($select->num_rows != 0) {
                 /* Return het object. */
                 return $select->fetch_object();
             } else {
                 /* Geen rows. */
                 throw new Exception('De geselecteerde abonnee bestaat niet (meer).');
             }
         } else {
             /* Foutmelding. */
             throw new Exception('Er ging wat fout bij het ophalen van de abonnee gegevens.' . Database::error());
         }
     } else {
         /* Geen rechten. */
         throw new Exception('U heeft geen rechten om alle abonnees te mogen bekijken.');
     }
 }
Exemplo n.º 14
0
function WSCreateUserPasswordCrypted($params)
{
    global $_user, $_configuration, $debug;
    if ($debug) {
        error_log('WSCreateUserPasswordCrypted');
    }
    if ($debug) {
        error_log(print_r($params, 1));
    }
    if (!WSHelperVerifyKey($params)) {
        return return_error(WS_ERROR_SECRET_KEY);
    }
    // Database table definition.
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
    $result = array();
    $orig_user_id_value = array();
    $password = $params['password'];
    $encrypt_method = $params['encrypt_method'];
    $firstName = $params['firstname'];
    $lastName = $params['lastname'];
    $status = $params['status'];
    $email = $params['email'];
    $loginName = $params['loginname'];
    $official_code = $params['official_code'];
    $language = '';
    $phone = '';
    $picture_uri = '';
    $auth_source = PLATFORM_AUTH_SOURCE;
    $expiration_date = '0000-00-00 00:00:00';
    $active = 1;
    $hr_dept_id = 0;
    $extra = null;
    $original_user_id_name = $params['original_user_id_name'];
    $original_user_id_value = $params['original_user_id_value'];
    $orig_user_id_value[] = $params['original_user_id_value'];
    $extra_list = $params['extra'];
    if (!empty($_configuration['password_encryption'])) {
        if ($_configuration['password_encryption'] === $encrypt_method) {
            if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
                $msg = "Encryption {$encrypt_method} is invalid";
                if ($debug) {
                    error_log($msg);
                }
                return $msg;
            } else {
                if ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
                    $msg = "Encryption {$encrypt_method} is invalid";
                    if ($debug) {
                        error_log($msg);
                    }
                    return $msg;
                }
            }
        } else {
            $msg = "This encryption {$encrypt_method} is not configured";
            if ($debug) {
                error_log($msg);
            }
            return $msg;
        }
    } else {
        $msg = 'The chamilo setting $_configuration["password_encryption"] is not configured';
        if ($debug) {
            error_log($msg);
        }
        return $msg;
    }
    if (!empty($params['language'])) {
        $language = $params['language'];
    }
    if (!empty($params['phone'])) {
        $phone = $params['phone'];
    }
    if (!empty($params['expiration_date'])) {
        $expiration_date = $params['expiration_date'];
    }
    // Check whether x_user_id exists into user_field_values table.
    $user_id = UserManager::get_user_id_from_original_id($original_user_id_value, $original_user_id_name);
    if ($debug) {
        error_log('Ready to create user');
    }
    if ($user_id > 0) {
        if ($debug) {
            error_log('User found with id: ' . $user_id);
        }
        // Check whether user is not active
        //@todo why this condition exists??
        $sql = "SELECT user_id FROM {$table_user} WHERE user_id ='" . $user_id . "' AND active= '0' ";
        $resu = Database::query($sql);
        $r_check_user = Database::fetch_row($resu);
        $count_check_user = Database::num_rows($resu);
        if ($count_check_user > 0) {
            if ($debug) {
                error_log('User id: ' . $user_id . ' exists and is NOT active. Updating user and setting setting active = 1');
            }
            $sql = "UPDATE {$table_user} SET\n                    lastname='" . Database::escape_string($lastName) . "',\n                    firstname='" . Database::escape_string($firstName) . "',\n                    username='******',";
            if (!is_null($auth_source)) {
                $sql .= " auth_source='" . Database::escape_string($auth_source) . "',";
            }
            $sql .= "\n                    password='******',\n                    email='" . Database::escape_string($email) . "',\n                    status='" . Database::escape_string($status) . "',\n                    official_code='" . Database::escape_string($official_code) . "',\n                    phone='" . Database::escape_string($phone) . "',\n                    expiration_date='" . Database::escape_string($expiration_date) . "',\n                    active='1',\n                    hr_dept_id=" . intval($hr_dept_id);
            $sql .= " WHERE user_id='" . $r_check_user[0] . "'";
            if ($debug) {
                error_log($sql);
            }
            Database::query($sql);
            if (is_array($extra_list) && count($extra_list) > 0) {
                foreach ($extra_list as $extra) {
                    $extra_field_name = $extra['field_name'];
                    $extra_field_value = $extra['field_value'];
                    // Save the external system's id into user_field_value table.
                    $res = UserManager::update_extra_field_value($r_check_user[0], $extra_field_name, $extra_field_value);
                }
            }
            return $r_check_user[0];
        } else {
            if ($debug) {
                error_log('User exists but is active. Cant be updated');
            }
            return 0;
        }
    } else {
        if ($debug) {
            error_log("User not found with original_id = {$original_user_id_value} and original_name = {$original_user_id_name}");
        }
    }
    // Default language.
    if (empty($language)) {
        $language = api_get_setting('platformLanguage');
    }
    if (!empty($_user['user_id'])) {
        $creator_id = $_user['user_id'];
    } else {
        $creator_id = '';
    }
    // First check wether the login already exists
    if (!UserManager::is_username_available($loginName)) {
        if ($debug) {
            error_log("Username {$loginName} is not available");
        }
        return 0;
    }
    $sql = "INSERT INTO {$table_user} SET\n                lastname            = '" . Database::escape_string(trim($lastName)) . "',\n                firstname           = '" . Database::escape_string(trim($firstName)) . "',\n                username            = '******',\n                status              = '" . Database::escape_string($status) . "',\n                password            = '******',\n                email               = '" . Database::escape_string($email) . "',\n                official_code\t    = '" . Database::escape_string($official_code) . "',\n                picture_uri \t    = '" . Database::escape_string($picture_uri) . "',\n                creator_id  \t    = '" . Database::escape_string($creator_id) . "',\n                auth_source         = '" . Database::escape_string($auth_source) . "',\n                phone               = '" . Database::escape_string($phone) . "',\n                language            = '" . Database::escape_string($language) . "',\n                registration_date   = '" . api_get_utc_datetime() . "',\n                expiration_date     = '" . Database::escape_string($expiration_date) . "',\n                hr_dept_id          = '" . Database::escape_string($hr_dept_id) . "',\n                active              = '" . Database::escape_string($active) . "'";
    if ($debug) {
        error_log($sql);
    }
    $result = Database::query($sql);
    if ($result) {
        $return = Database::insert_id();
        //Multiple URL
        $url_id = api_get_current_access_url_id();
        UrlManager::add_user_to_url($return, $url_id);
        if ($debug) {
            error_log("Adding user_id = {$return} to URL id {$url_id} ");
        }
        // Save new fieldlabel into user_field table.
        $field_id = UserManager::create_extra_field($original_user_id_name, 1, $original_user_id_name, '');
        // Save the remote system's id into user_field_value table.
        $res = UserManager::update_extra_field_value($return, $original_user_id_name, $original_user_id_value);
        if (is_array($extra_list) && count($extra_list) > 0) {
            foreach ($extra_list as $extra) {
                $extra_field_name = $extra['field_name'];
                $extra_field_value = $extra['field_value'];
                // save new fieldlabel into user_field table
                $field_id = UserManager::create_extra_field($extra_field_name, 1, $extra_field_name, '');
                // save the external system's id into user_field_value table'
                $res = UserManager::update_extra_field_value($return, $extra_field_name, $extra_field_value);
            }
        }
    } else {
        $error = Database::error();
        if ($debug) {
            error_log($error);
        }
        return 0;
    }
    return $return;
}
Exemplo n.º 15
0
 public static function get_invoice_data()
 {
     /* Permission check. */
     if (Permission::has('operator_chart_invoice')) {
         /* Selecteer alle invoice items vanaf nu en 1 jaar terug. */
         $select = Database::query("SELECT UNIX_TIMESTAMP(i.create_date) AS create_date, i.type_customer, (SELECT SUM(price) FROM invoice_data WHERE invoice_id = i.id AND price IS NOT NULL) AS price FROM invoice AS i WHERE create_date >= DATE_SUB(NOW(), INTERVAL 1 YEAR)");
         /* Kijken of query is gelukt. */
         if ($select) {
             /* Kijken of er minimaal één result is. */
             if ($select->num_rows != 0) {
                 /* Return array .*/
                 $return = array();
                 /* Database array aanmaken. */
                 $db_array = array();
                 /* Doorloop alle items uit DB. */
                 while ($obj = $select->fetch_object()) {
                     /* Sla object in array op. */
                     $db_array[] = $obj;
                 }
                 /* Tel aantal items in db_array. */
                 $db_array_count = count($db_array);
                 /* Loop 13x (12 maanden in 1 jaar, plus 1 erbij om het huidige maand te bekijken). */
                 for ($i = 12; $i > -1; $i--) {
                     /* d-m-Y van huidige maand uit de loop. */
                     $time = Date('m-Y', strtotime("-" . $i . " month"));
                     /* Sla time op in de return array, en maak er een array van. */
                     $return[$time] = array('ad-hoc' => 0, 'subscription' => 0);
                     /* Doorloop de database array. */
                     for ($j = 0; $j < $db_array_count; $j++) {
                         /* Obj var aanmaken. */
                         $obj = $db_array[$j];
                         /* Kijken of het huidige factuur bij de huidige datum hoort. */
                         if (Date('m-Y', $obj->create_date) == $time) {
                             /* Kijken wat het type customer is. */
                             if ($obj->type_customer == 'subscription') {
                                 /* Voeg het prijs toe aan de array. */
                                 $return[$time]['subscription'] = $return[$time]['subscription'] + $obj->price;
                             } else {
                                 /* Voeg het prijs toe aan de array. */
                                 $return[$time]['ad-hoc'] = $return[$time]['ad-hoc'] + $obj->price;
                             }
                         }
                     }
                 }
                 /* Geef de array terug. */
                 return $return;
             }
         } else {
             /* Foutmelding. */
             throw new Exception('Er ging wat fout bij het opzoeken van de facturen het laatste jaar.<br />' . Database::error());
         }
     } else {
         /* Geen permissies. */
         throw new Exception('U heeft geen rechten om deze chart te mogen zien.');
     }
 }
Exemplo n.º 16
0
 public static function search_card()
 {
     /* Permission check. */
     if (Permission::has('operator_card_search')) {
         /* Kijken of de zoek gegevens ingevuld zijn. */
         if (!empty($_POST['zoek_veld']) && !empty($_POST['zoek_type'])) {
             /* Kijken of het zoek type ondersteund wordt. */
             if (in_array($_POST['zoek_type'], array('abonnee_naam', 'abonnee_nummer', 'rfid_id'))) {
                 /* Escape het zoek term. */
                 $zoek = Database::escape($_POST['zoek_veld']);
                 /* Kijken of type abonnee_naam is. */
                 if ($_POST['zoek_type'] == 'abonnee_naam') {
                     /* Maak zoek query die de customer ID ophaalt van het resultaat. */
                     $select = Database::query("SELECT rfid.*, UNIX_TIMESTAMP(rfid.blocked_date) AS blocked_date FROM customer_info AS ci INNER JOIN subscription AS s ON s.customer_id = ci.customer_id INNER JOIN rfid_card AS rfid ON rfid.subscription_id = s.id WHERE ci.firstname LIKE '%" . $zoek . "%' OR ci.inserts LIKE '%" . $zoek . "%' OR ci.lastname LIKE '%" . $zoek . "%'");
                 } else {
                     /* Zoeken op abonneenummer. */
                     if ($_POST['zoek_type'] == 'abonnee_nummer') {
                         /* Maak zoek query die de customer ID ophaalt van het resultaat. */
                         $select = Database::query("SELECT rfid.*, UNIX_TIMESTAMP(rfid.blocked_date) AS blocked_date FROM subscription AS s INNER JOIN rfid_card AS rfid ON s.id = rfid.subscription_id WHERE s.sub_number LIKE '%" . $zoek . "%'");
                     } else {
                         /* Zoeken op RFID id. */
                         if ($_POST['zoek_type'] == 'rfid_id') {
                             /* Maak zoek query die de customer ID ophaalt van het resultaat. */
                             $select = Database::query("SELECT *, UNIX_TIMESTAMP(blocked_date) AS blocked_date FROM rfid_card WHERE id LIKE '%" . $zoek . "%'");
                         }
                     }
                 }
                 /* Controleren of de select query gelukt is. */
                 if ($select) {
                     /* Return het mysql object. */
                     return $select;
                 } else {
                     /* Foutmelding. */
                     throw new Exception('Er ging wat fout bij het zoeken.<br />' . Database::error());
                 }
             } else {
                 /* Type niet ondersteund. */
                 throw new Exception('Het zoek type wordt niet ondersteund.');
             }
         } else {
             /* Gooi foutmelding. */
             throw new Exception('Niet alle zoek velden zijn ingevuld.<br />' . Database::error());
         }
     } else {
         /* Geen rechten. */
         throw new Exception('U heeft geen rechten om de parkeer passen te mogen verwijderen.');
     }
 }
Exemplo n.º 17
0
 public function escalate()
 {
     /* Permission check. */
     if (Permission::has('operator_request_reply')) {
         /* Selecteer het type uit de ticket. */
         $select = Database::query("SELECT type_ticket FROM support_ticket WHERE id = " . $this->ticket_id);
         /* Kijken of de query gelukt is. */
         if ($select) {
             /* Kijken of het verzoek bestaat. */
             if ($select->num_rows != 0) {
                 /* Haal type ticket op. */
                 $type = $select->fetch_object()->type_ticket;
                 /* Controleren of de type wel een verzoek is. */
                 if ($type == 1) {
                     /* Update het verzoek naar ticket. */
                     $update = Database::query("UPDATE support_ticket SET type_ticket = 0 WHERE id = " . $this->ticket_id);
                     /* Kijken of update gelukt is. */
                     if ($update) {
                         /* Insert query om te laten zien dat het verzoek geëcaleert is. */
                         $insert = Database::query("INSERT INTO support_ticket_message (ticket_id, customer_id, new_msg, type_msg, create_date, message) VALUES (" . $this->ticket_id . ", " . $_SESSION['login']['id'] . ", 1, 1, NOW(), 'Het verzoek is geescaleerd tot ticket.')");
                         /* Controleren of het bericht is geplaatst. */
                         if (!$insert) {
                             /* Foutmelding. */
                             throw new Exception('Verzoek is geescaleerd, maar er kon geen bericht aan toegevoegd worden.<br />' . Database::error());
                         }
                     } else {
                         /* Update gefaald. */
                         throw new Exception('Er ging wat fout bij het escaleren van het verzoek.<br />' . Database::error());
                     }
                 } else {
                     /* Geen verzoek. */
                     throw new Exception('Het geselecteerde ticket is geen verzoek.');
                 }
             } else {
                 /* Dit verzoek bestaat niet. */
                 throw new Exception('Het geselecteerde verzoek bestaat niet.');
             }
         } else {
             /* Query mislukt. */
             throw new Exception('Er ging wat fout bij het controleren van het verzoek.<br />' . Database::error());
         }
     } else {
         /* Geen permissies. */
         throw new Exception('U heeft geen rechten om dit verzoek te mogen aan passen.');
     }
 }
Exemplo n.º 18
0
 private function rate_time_insert($obj, $json)
 {
     /* Escape alle items. */
     $days = Database::escape($json->days);
     $time_from = Database::escape($json->time_from);
     $time_till = Database::escape($json->time_till);
     $cat = Database::escape($json->category);
     /* Selecteer cat. */
     $select = Database::query("SELECT id FROM rate_category WHERE category = " . $cat);
     /* Kijken of query gelukt is. */
     if ($select) {
         /* Kijken of item bestaat. */
         if ($select->num_rows != 0) {
             /* Insert query. */
             $insert = Database::query("INSERT INTO rate_time (category_id, days, time_from, time_till) VALUES (" . $cat . ", '" . $days . "', " . $time_from . ", " . $time_till . ")");
             /* Kijken of insert gelukt is. */
             if ($insert) {
                 /* Return een true. */
                 return true;
             } else {
                 /* Voeg foutmelding toe. */
                 Queue_manager::add_error($obj->id, 'Database foutmelding: ' . Database::error());
             }
         } else {
             /* Category bestaat niet, dus voer het item niet uit en stel een foutmelding in. */
             Queue_manager::add_error($obj->id, 'De gekoze category \'' . $cat . '\' bestaat niet (meer).');
         }
     }
     /* Geef false terug. */
     return false;
 }
Exemplo n.º 19
0
<?php

require_once 'config.php';
require_once 'database.php';
$db = new Database(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
$db->insert('name', array('my_first_name', 'arp19690', 'my_last_name'), array('first', 'middle', 'last'));
$db->insert('name', array('f', 'arp19690', 'l'), array('first', 'middle', 'last'));
echo $db->error();
echo $db->error();
$db->update('name', array('middle' => 'my_middle_name'), array('first', 'my_first_name'));
echo $db->error();
$db->select('name', true, '*', 'middle = "my_middle_name"');
echo $db->error();
echo "result   " . $db->getResult();
Exemplo n.º 20
0
 public static function nonQuery($queryStr = '', $objectStr = '')
 {
     switch (self::$dbType) {
         case "mysqli":
             $queryDB = self::$dbConnect->send_query($queryStr);
             // echo self::$dbConnect->error;
             self::$error = self::$dbConnect->error;
             if (is_object($objectStr)) {
                 $objectStr($queryDB);
             }
             return $queryDB;
             break;
     }
 }
Exemplo n.º 21
0
 public static function get_category_time()
 {
     /* Permission check. */
     if (Permission::has('operator_price')) {
         /* Select query. */
         $select = Database::query("SELECT rc.*, rt.* FROM rate_time AS rt INNER JOIN rate_category AS rc ON rc.id = rt.category_id ORDER BY rt.days, rt.time_from");
         /* Kijken of query is gelukt. */
         if ($select) {
             /* Geef het mysqli object terug. */
             return $select;
         } else {
             /* Foutmelding. */
             throw new Exception('Er ging wat fout tijdens het ophalen van de categorie periode gegevens.<br />' . Database::error());
         }
     } else {
         /* Geen rechten. */
         throw new Exception('U heeft geen rechten om de tijd periode te mogen bekijken.');
     }
 }
Exemplo n.º 22
0
 public static function save($name, $value)
 {
     /* Permission check. */
     if (Permission::has('operator_settings_edit')) {
         /* Kijken of de setting bestaat. */
         if (Self::get($name) != null) {
             /* Update query aanmaken. */
             $update = Database::query("UPDATE citypark_setting SET setting_value = '" . Database::escape($value) . "' WHERE setting_name = '" . Database::escape($name) . "'");
             /* Controleren of de query is mislukt. */
             if (!$update) {
                 /* Foutmelding. */
                 throw new Exception('Er ging wat fout bij het aanpassen van de instelling.<br />' . Database::error());
             }
         } else {
             /* Setting bestaat niet. */
             throw new Exception('De permissie \'' . $name . '\' bestaat niet.');
         }
     } else {
         /* Geen rechten. */
         throw new Exception('U heeft geen rechten om een instellingen te wijzigen.');
     }
 }
Exemplo n.º 23
0
/**
 * Connects to the database server.
 */
function database_server_connect()
{
    global $dbHostForm, $dbUsernameForm, $dbPassForm;
    if (($res = @Database::connect(array('server' => $dbHostForm, 'username' => $dbUsernameForm, 'password' => $dbPassForm))) === false) {
        $no = Database::errno();
        $msg = Database::error();
        echo '<hr />#' . $no . ': ' . $msg . '<hr />';
        echo translate('DBServerDoesntWorkOrLoginPassIsWrong') . '.<br /><br />' . translate('PleaseCheckTheseValues') . ' :<br /><br />' . '<strong>' . translate('DBHost') . '</strong> : ' . $dbHostForm . '<br />' . '<strong>' . translate('DBLogin') . '</strong> : ' . $dbUsernameForm . '<br />' . '<strong>' . translate('DBPassword') . '</strong> : ' . $dbPassForm . '<br /><br />' . translate('PleaseGoBackToStep') . ' ' . (defined('SYSTEM_INSTALLATION') ? '3' : '1') . '.' . '<p><button type="submit" class="back" name="step' . (defined('SYSTEM_INSTALLATION') ? '3' : '1') . '" value="&lt; ' . translate('Back') . '">' . translate('Back') . '</button></p>' . '</td></tr></table></form></body></html>';
        exit;
    }
    @Database::query("set session sql_mode='';");
    // Disabling special SQL modes (MySQL 5)
}
    $lp_ordered_items = array();
    $parent_lps = array(); //keeps a track of chapter's learnpath ids
    $my_new_lp = $db.$new_lp;
    $my_new_lp_item = $db.$new_lp_item;
    $my_new_lp_view = $db.$new_lp_view;
    $my_new_lp_item_view = $db.$new_lp_item_view;

    // Migrate learnpaths
    $sql_test = "SELECT * FROM $my_new_lp";
    $res_test = Database::query($sql_test);
    $sql_lp = "SELECT * FROM $lp_main";
    if ($loglevel > 1) { Log::notice("$sql_lp"); }
    $res_lp = Database::query($sql_lp);
    if (!$res_lp or !$res_test) {
        if ($loglevel > 1) {
            Log::error("+++Problem querying DB $lp_main+++ skipping (".Database::error().")");
            if (!$res_test) {
                Log::error("This might be due to no existing table in the destination course");
            }
        }
        continue;
    }
    $dsp_ord = 1;
    while ($row = Database::fetch_array($res_lp)) {
        //echo "Treating lp id : ".$row['learnpath_id']."<br />\n";
        $ins_lp_sql = "INSERT INTO $my_new_lp (lp_type,name,description,display_order,content_maker) " .
                "VALUES (1," .
                        "'".Database::escape_string($row['learnpath_name'])."'," .
                        "'".Database::escape_string($row['learnpath_description'])."',$dsp_ord,'Dokeos')";
        $ins_lp_res = Database::query($ins_lp_sql);
        $in_id = Database::insert_id();
Exemplo n.º 25
0
 /**
  * Import the scorm object (as a result from the parse_manifest function) into the database structure
  * @param    string    Unique course code
  * @return    bool    Returns -1 on error
  */
 function import_manifest($course_code, $use_max_score = 1)
 {
     if ($this->debug > 0) {
         error_log('New LP - Entered import_manifest(' . $course_code . ')', 0);
     }
     $course_info = api_get_course_info($course_code);
     $course_id = $course_info['real_id'];
     // Get table names.
     $new_lp = Database::get_course_table(TABLE_LP_MAIN);
     $new_lp_item = Database::get_course_table(TABLE_LP_ITEM);
     $use_max_score = intval($use_max_score);
     foreach ($this->organizations as $id => $dummy) {
         $is_session = api_get_session_id();
         $is_session != 0 ? $session_id = $is_session : ($session_id = 0);
         $oOrganization =& $this->organizations[$id];
         // Prepare and execute insert queries:
         // -for learnpath
         // -for items
         // -for views?
         $get_max = "SELECT MAX(display_order) FROM {$new_lp} WHERE c_id = {$course_id} ";
         $res_max = Database::query($get_max);
         $dsp = 1;
         if (Database::num_rows($res_max) > 0) {
             $row = Database::fetch_array($res_max);
             $dsp = $row[0] + 1;
         }
         $myname = $oOrganization->get_name();
         $myname = api_utf8_decode($myname);
         $sql = "INSERT INTO {$new_lp} (c_id, lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib,display_order, session_id, use_max_score)" . "VALUES ({$course_id} , 2,'" . $myname . "', '" . $oOrganization->get_ref() . "','','" . $this->subdir . "', 0, 'embedded', '" . $this->manifest_encoding . "', 'scorm_api.php', {$dsp}, {$session_id}, {$use_max_score})";
         if ($this->debug > 1) {
             error_log('New LP - In import_manifest(), inserting path: ' . $sql, 0);
         }
         $res = Database::query($sql);
         $lp_id = Database::insert_id();
         $this->lp_id = $lp_id;
         // Insert into item_property.
         api_item_property_update(api_get_course_info($course_code), TOOL_LEARNPATH, $this->lp_id, 'LearnpathAdded', api_get_user_id());
         api_item_property_update(api_get_course_info($course_code), TOOL_LEARNPATH, $this->lp_id, 'visible', api_get_user_id());
         // Now insert all elements from inside that learning path.
         // Make sure we also get the href and sco/asset from the resources.
         $list = $oOrganization->get_flat_items_list();
         $parents_stack = array(0);
         $parent = 0;
         $previous = 0;
         $level = 0;
         foreach ($list as $item) {
             if ($item['level'] > $level) {
                 // Push something into the parents array.
                 array_push($parents_stack, $previous);
                 $parent = $previous;
             } elseif ($item['level'] < $level) {
                 $diff = $level - $item['level'];
                 // Pop something out of the parents array.
                 for ($j = 1; $j <= $diff; $j++) {
                     $outdated_parent = array_pop($parents_stack);
                 }
                 $parent = array_pop($parents_stack);
                 // Just save that value, then add it back.
                 array_push($parents_stack, $parent);
             }
             $path = '';
             $type = 'dir';
             if (isset($this->resources[$item['identifierref']])) {
                 $oRes =& $this->resources[$item['identifierref']];
                 $path = @$oRes->get_path();
                 if (!empty($path)) {
                     $temptype = $oRes->get_scorm_type();
                     if (!empty($temptype)) {
                         $type = $temptype;
                     }
                 }
             }
             $level = $item['level'];
             $field_add = '';
             $value_add = '';
             if (!empty($item['masteryscore'])) {
                 $field_add .= 'mastery_score, ';
                 $value_add .= $item['masteryscore'] . ',';
             }
             if (!empty($item['maxtimeallowed'])) {
                 $field_add .= 'max_time_allowed, ';
                 $value_add .= "'" . $item['maxtimeallowed'] . "',";
             }
             $title = Database::escape_string($item['title']);
             $title = api_utf8_decode($title);
             $max_score = Database::escape_string($item['max_score']);
             if ($max_score == 0 || is_null($max_score) || $max_score == '') {
                 //If max score is not set The use_max_score parameter is check in order to use 100 (chamilo style) or '' (strict scorm)
                 if ($use_max_score) {
                     $max_score = "'100'";
                 } else {
                     $max_score = "NULL";
                 }
             } else {
                 //Otherwise save the max score
                 $max_score = "'{$max_score}'";
             }
             $identifier = Database::escape_string($item['identifier']);
             if (empty($title)) {
                 $title = get_lang('Untitled');
             }
             $prereq = Database::escape_string($item['prerequisites']);
             $sql_item = "INSERT INTO {$new_lp_item} (c_id, lp_id,item_type,ref,title, path,min_score,max_score, {$field_add} parent_item_id,previous_item_id,next_item_id, prerequisite,display_order,launch_data, parameters) VALUES " . "({$course_id}, {$lp_id}, '{$type}','{$identifier}', '{$title}', '{$path}' , 0, {$max_score}, {$value_add}" . "{$parent}, {$previous}, 0, " . "'{$prereq}', " . $item['rel_order'] . ", '" . $item['datafromlms'] . "'," . "'" . $item['parameters'] . "'" . ")";
             $res_item = Database::query($sql_item);
             if ($this->debug > 1) {
                 error_log('New LP - In import_manifest(), inserting item : ' . $sql_item . ' : ' . Database::error(), 0);
             }
             $item_id = Database::insert_id();
             // Now update previous item to change next_item_id.
             $upd = "UPDATE {$new_lp_item} SET next_item_id = {$item_id} WHERE c_id = {$course_id} AND id = {$previous}";
             $upd_res = Database::query($upd);
             // Update previous item id.
             $previous = $item_id;
             // Code for indexing, now only index specific fields like terms and the title.
             if (!empty($_POST['index_document'])) {
                 require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php';
                 require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
                 require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
                 $di = new ChamiloIndexer();
                 isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : ($lang = 'english');
                 $di->connectDb(null, null, $lang);
                 $ic_slide = new IndexableChunk();
                 $ic_slide->addValue('title', $title);
                 $specific_fields = get_specific_field_list();
                 $all_specific_terms = '';
                 foreach ($specific_fields as $specific_field) {
                     if (isset($_REQUEST[$specific_field['code']])) {
                         $sterms = trim($_REQUEST[$specific_field['code']]);
                         $all_specific_terms .= ' ' . $sterms;
                         if (!empty($sterms)) {
                             $sterms = explode(',', $sterms);
                             foreach ($sterms as $sterm) {
                                 $ic_slide->addTerm(trim($sterm), $specific_field['code']);
                             }
                         }
                     }
                 }
                 $body_to_index = $all_specific_terms . ' ' . $title;
                 $ic_slide->addValue("content", $body_to_index);
                 // TODO: Add a comment to say terms separated by commas.
                 $courseid = api_get_course_id();
                 $ic_slide->addCourseId($courseid);
                 $ic_slide->addToolId(TOOL_LEARNPATH);
                 $xapian_data = array(SE_COURSE_ID => $courseid, SE_TOOL_ID => TOOL_LEARNPATH, SE_DATA => array('lp_id' => $lp_id, 'lp_item' => $previous, 'document_id' => ''), SE_USER => (int) api_get_user_id());
                 $ic_slide->xapian_data = serialize($xapian_data);
                 $di->addChunk($ic_slide);
                 // Index and return search engine document id.
                 $did = $di->index();
                 if ($did) {
                     // Save it to db.
                     $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
                     $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
                             VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
                     $sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did);
                     Database::query($sql);
                 }
             }
         }
     }
 }
Exemplo n.º 26
0
 public function set_paid()
 {
     /* Controleren of er een ID geset is van een factuur om mee te werken. */
     if ($this->id != null) {
         /* Query uitvoeren. */
         $update = Database::query("UPDATE invoice SET paid = 1, paid_date = NOW() WHERE id = " . $this->id);
         /* Controleren of query is gelukt. */
         if (!$update) {
             /* Foutmelding. */
             throw new Exception('Er ging wat fout bij het op betaald zetten van het factuur.<br />' . Database::error());
         }
         /* Return een true. */
         return true;
     } else {
         /* Er is geen factuur geselecteerd. */
         throw new Exception('Er is geprobeerd een factuur regel aan te maken terwijl er geen factuur ingesteld is.');
     }
 }
Exemplo n.º 27
0
<?php

require_once "Question.php";
require_once "db.php";
@Database::connect();
if (!Database::$link) {
    Database::error();
}
if (!isset($_POST["text"]) || !isset($_POST["trueAnswer"]) || !isset($_POST["falseAnswer1"]) || !isset($_POST["falseAnswer2"])) {
    die;
}
$text = $_POST["text"];
$trueAnswer = $_POST["trueAnswer"];
$falseAnswer1 = $_POST["falseAnswer1"];
$falseAnswer2 = $_POST["falseAnswer2"];
$question = new Question($text, $trueAnswer, $falseAnswer1, $falseAnswer2);
$question->add();
header("Location: ../front-end/moviesChallenge.html");
Exemplo n.º 28
0
 /**
  * Displays the form to register users in a blog (in a course)
  * The listed users are users subcribed in the course.
  * @author Toon Keppens
  *
  * @param Integer $blog_id
  *
  * @return Html Form with sortable table with users to unsubcribe from a blog.
  */
 public static function display_form_user_unsubscribe($blog_id)
 {
     global $_user;
     $is_western_name_order = api_is_western_name_order();
     // Init
     $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
     $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
     echo '<legend>' . get_lang('UnsubscribeMembers') . '</legend>';
     $properties["width"] = "100%";
     //table column titles
     $column_header[] = array('', false, '');
     if ($is_western_name_order) {
         $column_header[] = array(get_lang('FirstName'), true, '');
         $column_header[] = array(get_lang('LastName'), true, '');
     } else {
         $column_header[] = array(get_lang('LastName'), true, '');
         $column_header[] = array(get_lang('FirstName'), true, '');
     }
     $column_header[] = array(get_lang('Email'), false, '');
     $column_header[] = array(get_lang('TaskManager'), true, '');
     $column_header[] = array(get_lang('UnRegister'), false, '');
     $course_id = api_get_course_int_id();
     $sql_query = "SELECT user.user_id, user.lastname, user.firstname, user.email, user.username\n\t\t\tFROM {$tbl_users} user INNER JOIN {$tbl_blogs_rel_user} blogs_rel_user\n\t\t\tON user.user_id = blogs_rel_user.user_id\n\t\t\tWHERE blogs_rel_user.c_id = {$course_id} AND  blogs_rel_user.blog_id = '" . (int) $blog_id . "'";
     if (!($sql_result = Database::query($sql_query))) {
         return false;
     }
     $user_data = array();
     while ($myrow = Database::fetch_array($sql_result)) {
         $row = array();
         $row[] = '<input type="checkbox" name="user[]" value="' . $myrow['user_id'] . '" ' . ($_GET['selectall'] == "unsubscribe" ? ' checked="checked" ' : '') . '/>';
         $username = api_htmlentities(sprintf(get_lang('LoginX'), $myrow["username"]), ENT_QUOTES);
         if ($is_western_name_order) {
             $row[] = $myrow["firstname"];
             $row[] = Display::tag('span', $myrow["lastname"], array('title' => $username));
         } else {
             $row[] = Display::tag('span', $myrow["lastname"], array('title' => $username));
             $row[] = $myrow["firstname"];
         }
         $row[] = Display::icon_mailto_link($myrow["email"]);
         $sql = "SELECT bt.title task\n\t\t\tFROM " . Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER) . " btu\n\t\t\tINNER JOIN " . Database::get_course_table(TABLE_BLOGS_TASKS) . " bt ON btu.task_id = bt.task_id\n\t\t\tWHERE \tbtu.c_id \t= {$course_id}  AND\n\t\t\t\t\tbt.c_id \t= {$course_id}  AND\n\t\t\t\t\tbtu.blog_id = {$blog_id} AND\n\t\t\t\t\tbtu.user_id = " . $myrow['user_id'];
         if (!($sql_res = Database::query($sql))) {
             die(Database::error());
         }
         $task = '';
         while ($r = Database::fetch_array($sql_res)) {
             $task .= stripslashes($r['task']) . ', ';
         }
         //echo $task;
         $task = api_strlen(trim($task)) != 0 ? api_substr($task, 0, api_strlen($task) - 2) : get_lang('Reader');
         $row[] = $task;
         //Link to register users
         if ($myrow["user_id"] != $_user['user_id']) {
             $row[] = "<a class=\"btn\" href=\"" . api_get_self() . "?action=manage_members&amp;blog_id={$blog_id}&amp;unregister=yes&amp;user_id=" . $myrow[user_id] . "\">" . get_lang('UnRegister') . "</a>";
         } else {
             $row[] = '';
         }
         $user_data[] = $row;
     }
     $query_vars['action'] = 'manage_members';
     $query_vars['blog_id'] = $blog_id;
     echo '<form method="post" action="blog.php?action=manage_members&amp;blog_id=' . $blog_id . '">';
     Display::display_sortable_table($column_header, $user_data, null, null, $query_vars);
     $link = '';
     $link .= isset($_GET['action']) ? 'action=' . Security::remove_XSS($_GET['action']) . '&amp;' : '';
     $link .= "blog_id={$blog_id}&amp;";
     echo '<a href="blog.php?' . $link . 'selectall=unsubscribe">' . get_lang('SelectAll') . '</a> - ';
     echo '<a href="blog.php?' . $link . '">' . get_lang('UnSelectAll') . '</a> ';
     echo get_lang('WithSelected') . ' : ';
     echo '<select name="action">';
     echo '<option value="select_unsubscribe">' . get_lang('UnRegister') . '</option>';
     echo '</select>';
     echo '<input type="hidden" name="unregister" value="true" />';
     echo '<button class="save" type="submit">' . get_lang('Ok') . '</button>';
     echo '</form>';
 }
Exemplo n.º 29
0
 public function save_information()
 {
     /* Controleren of alle vereiste velden ingevuld zijn. */
     if (!empty($_POST['firstname']) && !empty($_POST['lastname']) && !empty($_POST['street']) && !empty($_POST['house_nr']) && !empty($_POST['zipcode']) && !empty($_POST['city']) && !empty($_POST['bank_account']) && !empty($_POST['email'])) {
         /* Kijken of minimaal een van de twee telefoonnummers ingevuld is. */
         if (!empty($_POST['phone_home']) || !empty($_POST['phone_mob'])) {
             /* Controleren of het bank rekening nummer een getal is. */
             if (is_numeric($_POST['bank_account'])) {
                 /* Controleren of het huis nummer een getal is. */
                 if (is_numeric($_POST['house_nr'])) {
                     /* Controleren of het e-mailadres klopt. */
                     if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                         /* Escape de heel $_POST array, en plaats het resultaat terug in $_POST. */
                         $_POST = Database::escape_array($_POST);
                         /* Update de customer information. */
                         $update_ci = Database::query("UPDATE customer_info SET firstname = '" . $_POST['firstname'] . "', inserts = '" . $_POST['inserts'] . "', lastname = '" . $_POST['lastname'] . "', street = '" . $_POST['street'] . "', house_nr = " . $_POST['house_nr'] . ", house_nr_add = '" . $_POST['house_nr_add'] . "', city = '" . $_POST['city'] . "', zipcode = '" . $_POST['zipcode'] . "', phone_home = '" . $_POST['phone_home'] . "', phone_mob = '" . $_POST['phone_mob'] . "', bank_account = " . $_POST['bank_account'] . " WHERE customer_id = " . $_SESSION['login']['id']);
                         if ($update_ci) {
                             /* Update de customer email. */
                             $update_c = Database::query("UPDATE customer SET email = '" . $_POST['email'] . "' WHERE id = " . $_SESSION['login']['id']);
                             if (!$update_c) {
                                 /* Aanpassen van email is mislukt. */
                                 throw new Exception('Er ging wat fout tijdens het opslaan van de wijzigingen.<br />' . Database::error());
                             }
                         } else {
                             /* Customer info aanpassen is mislukt. */
                             throw new Exception('Er ging wat fout tijdens het opslaan van de wijzigingen.<br />' . Database::error());
                         }
                     } else {
                         /* E-mailadres is ongeldig. */
                         throw new Exception('Het ingevulde e-mailadres is ongeldig.');
                     }
                 } else {
                     /* Huisnummer is geen getal. */
                     throw new Exception('Het ingevulde huisnummer is ongeldig.');
                 }
             } else {
                 /* Banknummer is geen getal. */
                 throw new Exception('Het ingevulde rekeningnummer is ongeldig.');
             }
         } else {
             /* Beide telefoonnummers missen. */
             throw new Exception('Minimaal een van de telefoonnummers dient ingevuld te worden.');
         }
     } else {
         /* Niet alle verplichte velden zijn ingevuld. */
         throw new Exception('Niet alle verplichte velden zijn ingevuld.');
     }
 }
Exemplo n.º 30
0
	}	
}

$mysqlStatsDb = $mysqlMainDb;
$mysqlUserDb = $mysqlMainDb;

// This parameter is needed to run a command line install of Chamilo (needed for Phing)
if (!defined('CLI_INSTALLATION')) {
	include api_get_path(SYS_LANG_PATH).'english/create_course.inc.php';

	if ($languageForm != 'english') {
		include api_get_path(SYS_LANG_PATH).$languageForm.'/create_course.inc.php';
	}
}

Database::select_db($mysqlMainDb) or die(Database::error());

$installation_settings = array();
$installation_settings['{ORGANISATIONNAME}']                = $institutionForm;
$installation_settings['{ORGANISATIONURL}']                 = $institutionUrlForm;
$installation_settings['{CAMPUSNAME}']                      = $campusForm;
$installation_settings['{PLATFORMLANGUAGE}']                = $languageForm;
$installation_settings['{ALLOWSELFREGISTRATION}']           = true_false($allowSelfReg);
$installation_settings['{ALLOWTEACHERSELFREGISTRATION}']    = true_false($allowSelfRegProf);
$installation_settings['{ADMINLASTNAME}']                   = $adminLastName;
$installation_settings['{ADMINFIRSTNAME}']                  = $adminFirstName;
$installation_settings['{ADMINLOGIN}']                      = $loginForm;
$installation_settings['{ADMINPASSWORD}']                   = $passToStore;
$installation_settings['{ADMINEMAIL}']                      = $emailForm;
$installation_settings['{ADMINPHONE}']                      = $adminPhoneForm;
$installation_settings['{PLATFORM_AUTH_SOURCE}']            = PLATFORM_AUTH_SOURCE;