public static function add($cmd, $type, $data = array(), $customer_id = null) { /* Kijken of het typen een day of month is (die worden ondersteund). */ if ($type == 'day' || $type == 'month') { /* Maak van de data array een JSON string en escape deze. */ $json = Database::escape(json_encode($data)); /* Escape $cmd tegen mysql injecties. */ $cmd = Database::escape($cmd); /* Escape $customer_id tegen mysql injecties. */ $customer_id = Database::escape($customer_id); /* Uitzoeken in welke tabel de actie moet. */ if ($type == 'day') { /* Insert het commando. */ $insert = Database::query("INSERT INTO queue_day (customer_id, create_date, action, `data`) VALUES (" . $customer_id . ", NOW(), '" . $cmd . "', '" . $json . "')"); } else { /* Insert het commando. */ $insert = Database::query("INSERT INTO queue_month (customer_id, create_date, action, `data`) VALUES (" . $customer_id . ", NOW(), '" . $cmd . "', '" . $json . "')"); } /* Controleren of de insert query is gelukt. */ if ($insert) { /* Query gelukt, return het ID van het veld. */ return Database::insert_id(); } else { /* Query is mislukt. */ throw new Exception('Er ging wat fout in de database tijdens het importeren van de taak.<br />' . Database::error()); } } else { /* Onbekende type mee gekregen. */ throw new Exception('De type \'' . $type . '\' wordt niet ondersteund.'); } }
/** * This functions stores the note in the database * * @param array $values * @return bool * @author Christian Fasanando <*****@*****.**> * @author Patrick Cool <*****@*****.**>, Ghent University, Belgium * @version januari 2009, dokeos 1.8.6 * */ static function save_note($values) { if (!is_array($values) or empty($values['note_title'])) { return false; } // Database table definition $t_notebook = Database :: get_course_table(TABLE_NOTEBOOK); $course_id = api_get_course_int_id(); $sql = "INSERT INTO $t_notebook (c_id, user_id, course, session_id, title, description, creation_date,update_date,status) VALUES( $course_id, '" . api_get_user_id() . "', '" . Database::escape_string(api_get_course_id()) . "', '" . intval($_SESSION['id_session']) . "', '" . Database::escape_string($values['note_title']) . "', '" . Database::escape_string($values['note_comment']) . "', '" . Database::escape_string(date('Y-m-d H:i:s')) . "', '" . Database::escape_string(date('Y-m-d H:i:s')) . "', '0')"; $result = Database::query($sql); $id = Database::insert_id(); if ($id > 0) { //insert into item_property api_item_property_update(api_get_course_info(), TOOL_NOTEBOOK, $id, 'NotebookAdded', api_get_user_id()); } $affected_rows = Database::affected_rows(); if (!empty($affected_rows)) { return $id; } }
public static function insert($inputData = array()) { // End addons $totalArgs = count($inputData); $addMultiAgrs = ''; if (isset($inputData[0]['foldername'])) { foreach ($inputData as $theRow) { $keyNames = array_keys($theRow); $insertKeys = implode(',', $keyNames); $keyValues = array_values($theRow); $insertValues = "'" . implode("','", $keyValues) . "'"; $addMultiAgrs .= "({$insertValues}), "; } $addMultiAgrs = substr($addMultiAgrs, 0, strlen($addMultiAgrs) - 2); } else { $keyNames = array_keys($inputData); $insertKeys = implode(',', $keyNames); $keyValues = array_values($inputData); $insertValues = "'" . implode("','", $keyValues) . "'"; $addMultiAgrs = "({$insertValues})"; } Database::query("insert into plugins_meta({$insertKeys}) values" . $addMultiAgrs); if (!($error = Database::hasError())) { $id = Database::insert_id(); return $id; } return false; }
/** * add Testcategory in the database if name doesn't already exists */ public function addCategoryInBDD() { $t_cattable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY); $v_name = $this->name; $v_name = Database::escape_string($v_name); $v_description = $this->description; $v_description = Database::escape_string($v_description); // check if name already exists $sql = "SELECT count(*) AS nb FROM {$t_cattable}\n WHERE title = '{$v_name}' AND c_id=" . api_get_course_int_id(); $result_verif = Database::query($sql); $data_verif = Database::fetch_array($result_verif); // lets add in BDD if not the same name if ($data_verif['nb'] <= 0) { $c_id = api_get_course_int_id(); $sql = "INSERT INTO {$t_cattable} VALUES ('{$c_id}', '', '{$v_name}', '{$v_description}')"; Database::query($sql); $new_id = Database::insert_id(); // add test_category in item_property table $course_code = api_get_course_id(); $course_info = api_get_course_info($course_code); api_item_property_update($course_info, TOOL_TEST_CATEGORY, $new_id, 'TestCategoryAdded', api_get_user_id()); return $new_id; } else { return false; } }
public static function insert($inputData = array()) { // End addons // $totalArgs=count($inputData); $addMultiAgrs = ''; if (isset($inputData[0]['userid'])) { foreach ($inputData as $theRow) { $keyNames = array_keys($theRow); $insertKeys = implode(',', $keyNames); $keyValues = array_values($theRow); $insertValues = "'" . implode("','", $keyValues) . "'"; $addMultiAgrs .= "({$insertValues}), "; } $addMultiAgrs = substr($addMultiAgrs, 0, strlen($addMultiAgrs) - 2); } else { $keyNames = array_keys($inputData); $insertKeys = implode(',', $keyNames); $keyValues = array_values($inputData); $insertValues = "'" . implode("','", $keyValues) . "'"; $addMultiAgrs = "({$insertValues})"; } Database::query("insert into " . Database::getPrefix() . "address({$insertKeys}) values" . $addMultiAgrs); DBCache::removeDir('system/address'); if (!($error = Database::hasError())) { $id = Database::insert_id(); return $id; } return false; }
/** * Creates a new group * * @author Julio Montoya <*****@*****.**>, * * @param string The URL of the site * @param string The description of the site * @param int is active or not * @param int the user_id of the owner * @return boolean if success */ public static function add($name, $description, $url, $visibility, $picture = '') { $now = api_get_utc_datetime(); $table = Database::get_main_table(TABLE_MAIN_GROUP); $sql = "INSERT INTO {$table}\n SET name \t= '" . Database::escape_string($name) . "',\n description = '" . Database::escape_string($description) . "',\n picture_uri = '" . Database::escape_string($picture) . "',\n url \t\t= '" . Database::escape_string($url) . "',\n visibility \t= '" . Database::escape_string($visibility) . "',\n created_on = '" . $now . "',\n updated_on = '" . $now . "'"; Database::query($sql); $return = Database::insert_id(); return $return; }
/** * Creates a new group * * @author Julio Montoya <*****@*****.**>, * * @param string $name The URL of the site * @param string $description The description of the site * @param string $url * @param int $visibility is active or not * @param string $picture * * @return boolean if success */ public static function add($name, $description, $url, $visibility, $picture = '') { $now = api_get_utc_datetime(); $table = Database::get_main_table(TABLE_MAIN_GROUP); $sql = "INSERT INTO {$table}\n SET name \t= '" . Database::escape_string($name) . "',\n description = '" . Database::escape_string($description) . "',\n picture_uri = '" . Database::escape_string($picture) . "',\n url \t\t= '" . Database::escape_string($url) . "',\n visibility \t= '" . Database::escape_string($visibility) . "',\n created_on = '" . $now . "',\n updated_on = '" . $now . "'"; Database::query($sql); $id = Database::insert_id(); if ($id) { Event::addEvent(LOG_GROUP_PORTAL_CREATED, LOG_GROUP_PORTAL_ID, $id); return $id; } return false; }
/** * Ingresa datos en tabla * @param string $tabla * @param array $parametros * @return int identificador del nuevo registro */ public function insert($parametros) { $campos_tabla = ""; $valores_tabla = ""; $coma = ""; foreach ($parametros as $campo => $valor) { $campos_tabla .= $coma . $campo; $valores_tabla .= $coma . "?"; $coma = ","; } $sql = "INSERT INTO " . $this->_table . "(" . $campos_tabla . ") VALUES(" . $valores_tabla . ")"; $this->_db->query($sql, array_values($parametros)); return $this->_db->insert_id(); }
/** * Add sub-language * @param string Original language name (Occitan, Wallon, Vlaams) * @param string English language name (occitan, wallon, flanders) * @param string ISO code (fr_FR, ...) * @param int Whether the sublanguage is published (0=unpublished, 1=published) * @param int ID del idioma padre * @return int New sub language ID or false on error */ function add_sub_language($original_name, $english_name, $isocode, $sublanguage_available, $parent_id) { $tbl_admin_languages = Database::get_main_table(TABLE_MAIN_LANGUAGE); $original_name = Database::escape_string($original_name); $english_name = Database::escape_string($english_name); $isocode = Database::escape_string($isocode); $sublanguage_available = Database::escape_string($sublanguage_available); $parent_id = Database::escape_string($parent_id); $sql = 'INSERT INTO ' . $tbl_admin_languages . '(original_name,english_name,isocode,dokeos_folder,available,parent_id) VALUES ("' . $original_name . '","' . $english_name . '","' . $isocode . '","' . $english_name . '","' . $sublanguage_available . '","' . $parent_id . '")'; $res = Database::query($sql); if ($res === false) { return false; } return Database::insert_id(); }
public static function register($username, $password, $verifypassword, $email) { $query = "SELECT * FROM " . self::$tUsers . " WHERE username = ? OR email = ?"; $query = Database::query($query, [$username, $email]); if (Database::num_rows($query)) { throw new Exception('Username or Email already exists!'); } if ($password != $verifypassword) { throw new Exception('Passwords do not match!'); } $password = password_hash($password, PASSWORD_BCRYPT); $data = ['username' => $username, 'password' => $password, 'email' => $email]; $query = Database::query("INSERT INTO " . self::$tUsers . "(username,password,email)VALUES(?,?,?)", [$username, $password, $email]); $id = Database::insert_id(); return $id; }
public static function InsertOnSubmit($listFieldInsert = '') { // $freshConnnect=$this->fieldList['dbConnect']; $fieldList = $this->fieldList; $tableName = $fieldList['tableName']; unset($fieldList['dbConnect'], $fieldList['hasConnected'], $fieldList['tableName'], $fieldList['dbType'], $fieldList['error']); if (is_array($listFieldInsert)) { $fieldList = $listFieldInsert; } $listFieldNames = array_keys($fieldList); $listFieldValues = array_values($fieldList); $mergeField = implode(',', $listFieldNames); $mergeValue = "'" . implode("','", $listFieldValues) . "'"; $queryStr = "INSERT INTO {$tableName}({$mergeField}) VALUES({$mergeValue})"; Database::query($queryStr); $insert_id = Database::insert_id(); return $insert_id; }
public function new_invoice($cid = null, $type = null) { /* Controleren of ייn van de twee input niet null is. */ if ($cid != null && is_numeric($cid) || $type != null) { /* Insert query */ $insert = Database::query("INSERT INTO invoice (customer_id, create_date, type_customer) VALUES (" . ($cid != null ? Database::escape($cid) : 'NULL') . ", NOW(), " . ($type != null ? "'" . Database::escape($type) . "'" : 'NULL') . ")"); /* Controleren of de query is gelukt. */ if ($insert) { /* Haal invoice ID op, en sla deze op in het object. */ $this->id = Database::insert_id(); /* Return het invoice ID. */ return Database::escape($this->id); } else { /* MySQL Foutmelding. */ throw new Exception('Er ging wat fout tijdens het aanmaken van een nieuw factuur.<br />' . Database::error()); } } else { /* Er moet minimaal 1 van de twee types opgegeven worden. */ throw new Exception('Er is geen geldig klant ID of klant type op gegeven.'); } }
/** * Add a specific field * @param string $name specific field name */ function add_specific_field($name) { $table_sf = Database::get_main_table(TABLE_MAIN_SPECIFIC_FIELD); $name = trim($name); if (empty($name)) { return false; } $sql = 'INSERT INTO %s(id, code, name) VALUES(NULL, \'%s\', \'%s\')'; $_safe_name = Database::escape_string($name); $_safe_code = substr($_safe_name, 0, 1); $_safe_code = get_specific_field_code_from_name($_safe_code); if ($_safe_code === false) { return false; } $sql = sprintf($sql, $table_sf, $_safe_code, $_safe_name); $result = Database::query($sql); if ($result) { return Database::insert_id(); } else { return false; } }
/** * Creates a new url access * * @author Julio Montoya <*****@*****.**>, * * @param string The URL of the site * @param string The description of the site * @param int is active or not * @param int the user_id of the owner * @param int The type of URL (1=multiple-access-url, 2=sincro-server, 3=sincro-client) * @param array If the type is different than 1, then there might be extra URL parameters to take into account * @return boolean if success */ public static function add($url, $description, $active, $type = 1, $extra_params) { $tms = time(); $type = intval($type); $table_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL); $u = api_get_user_id(); if ($u == 0) { $u = api_get_anonymous_id(); } if ($type > 1) { $active = 0; } $sql = "INSERT INTO {$table_access_url} " . " SET url \t= '" . Database::escape_string($url) . "', " . " description = '" . Database::escape_string($description) . "', " . " active \t\t= {$active}, " . " created_by \t= {$u}, " . " url_type = {$type}, " . " tms = FROM_UNIXTIME(" . $tms . ")"; $result = Database::query($sql); $id = Database::insert_id(); if ($result !== false && $type == 3 && count($extra_params) > 0) { // Register extra parameters in the branch_sync table $t = Database::get_main_table(TABLE_BRANCH_SYNC); $sql = "INSERT INTO {$t} SET " . " access_url_id = {$id} " . (!empty($extra_params['ip']) ? ", branch_ip = '" . Database::escape_string($extra_params['ip']) . "'" : "") . (!empty($extra_params['name']) ? ", branch_name = '" . Database::escape_string($extra_params['name']) . "'" : "") . (!empty($extra_params['last_sync']) ? ", last_sync_trans_id = '" . Database::escape_string($extra_params['last_sync']) . "'" : "") . (!empty($extra_params['dwn_speed']) ? ", dwn_speed = '" . Database::escape_string($extra_params['dwn_speed']) . "'" : "") . (!empty($extra_params['up_speed']) ? ", up_speed = '" . Database::escape_string($extra_params['up_speed']) . "'" : "") . (!empty($extra_params['delay']) ? ", delay = '" . Database::escape_string($extra_params['delay']) . "'" : "") . (!empty($extra_params['admin_mail']) ? ", admin_mail = '" . Database::escape_string($extra_params['admin_mail']) . "'" : "") . (!empty($extra_params['admin_name']) ? ", admin_name = '" . Database::escape_string($extra_params['admin_name']) . "'" : "") . (!empty($extra_params['admin_phone']) ? ", admin_phone = '" . Database::escape_string($extra_params['admin_phone']) . "'" : "") . (!empty($extra_params['latitude']) ? ", latitude = '" . Database::escape_string($extra_params['latitude']) . "'" : "") . (!empty($extra_params['longitude']) ? ", longitude = '" . Database::escape_string($extra_params['longitude']) . "'" : "") . ", last_sync_trans_date = '" . api_get_utc_datetime() . "'"; $result = $result && Database::query($sql); } return $result; }
function insert_id() { parent::insert_id($id); return mysql_insert_id($this->link_id); }
/** * Create group category * @param string $title The title of the new category * @param string $description The description of the new category * @param bool $self_registration_allowed * @param bool $self_unregistration_allowed * @param int $max_number_of_students * @param int $groups_per_user */ public static function create_category($title, $description, $doc_state, $work_state, $calendar_state, $announcements_state, $forum_state, $wiki_state, $chat_state = 1, $self_registration_allowed = 0, $self_unregistration_allowed = 0, $maximum_number_of_students = 8, $groups_per_user = 0) { if (empty($title)) { return false; } $table_group_category = Database::get_course_table(TABLE_GROUP_CATEGORY); $course_id = api_get_course_int_id(); $sql = "SELECT MAX(display_order)+1 as new_order FROM {$table_group_category} WHERE c_id = {$course_id} "; $res = Database::query($sql); $obj = Database::fetch_object($res); if (!isset($obj->new_order)) { $obj->new_order = 1; } $sql = "INSERT INTO " . $table_group_category . " SET\n c_id = {$course_id} ,\n title='" . Database::escape_string($title) . "',\n display_order ='" . $obj->new_order . "',\n description='" . Database::escape_string($description) . "',\n doc_state = '" . Database::escape_string($doc_state) . "',\n work_state = '" . Database::escape_string($work_state) . "',\n calendar_state = '" . Database::escape_string($calendar_state) . "',\n announcements_state = '" . Database::escape_string($announcements_state) . "',\n forum_state = '" . Database::escape_string($forum_state) . "',\n wiki_state = '" . Database::escape_string($wiki_state) . "',\n chat_state = '" . Database::escape_string($chat_state) . "',\n groups_per_user = '******',\n self_reg_allowed = '" . Database::escape_string($self_registration_allowed) . "',\n self_unreg_allowed = '" . Database::escape_string($self_unregistration_allowed) . "',\n max_student = '" . Database::escape_string($maximum_number_of_students) . "' "; Database::query($sql); $categoryId = Database::insert_id(); if ($categoryId == self::VIRTUAL_COURSE_CATEGORY) { $sql = "UPDATE " . $table_group_category . " SET id = " . ($categoryId + 1) . " WHERE c_id = {$course_id} AND id = {$categoryId}"; Database::query($sql); return $categoryId + 1; } return $categoryId; }
$result_message[$TBL_STUDENT_PUBLICATION_ASSIGNMENT]++; } } $doc_url = $data['url']; $new_url = str_replace($parent_data['url'], $created_dir, $doc_url); if ($update_database) { //Creating a new work $sql_add_publication = "INSERT INTO " . $TBL_STUDENT_PUBLICATION . " SET " . "url = '" . $new_url . "',\n c_id = {$course_id},\n title = '" . $data['title'] . "',\n description = '" . $data['description'] . " file moved',\n author = '" . $data['author'] . "',\n active = '" . $data['active'] . "',\n accepted = '" . $data['accepted'] . "',\n post_group_id = " . $data['post_group_id'] . ",\n sent_date = '" . $data['sent_date'] . "',\n parent_id = " . $new_parent_id . " ,\n session_id = " . $new_session_id; if ($debug) { echo $sql_add_publication; } $rest_insert = Database::query($sql_add_publication); if ($debug) { var_dump($rest_insert); } $id = Database::insert_id(); api_item_property_update($course_info, 'work', $id, 'DocumentAdded', $user_id); $result_message[$TBL_STUDENT_PUBLICATION]++; $full_file_name = $course_dir . '/' . $doc_url; $new_file = $course_dir . '/' . $new_url; if (file_exists($full_file_name)) { //deleting old assignment $result = copy($full_file_name, $new_file); if ($result) { unlink($full_file_name); $sql = "DELETE FROM {$TBL_STUDENT_PUBLICATION} WHERE id= " . $data['id']; if ($debug) { var_dump($sql); } $result_delete = Database::query($sql); api_item_property_update($course_info, 'work', $data['id'], 'DocumentDeleted', api_get_user_id());
/** * Add a relation between question and category in table c_quiz_question_rel_category * @param int $categoryId * @param int $questionId * @param int $courseId * * @return int */ public static function add_category_for_question_id($categoryId, $questionId, $courseId) { $table = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY); // if question doesn't have a category // @todo change for 1.10 when a question can have several categories if (TestCategory::getCategoryForQuestion($questionId, $courseId) == 0 && $questionId > 0 && $courseId > 0) { $sql = "INSERT INTO {$table} (c_id, question_id, category_id)\n VALUES (" . intval($courseId) . ", " . intval($questionId) . ", " . intval($categoryId) . ")"; Database::query($sql); $id = Database::insert_id(); return $id; } return false; }
/** * CSV file import functions * @author René Haentjens , Ghent University */ public static function put_link($url, $cat, $title, $description, $on_homepage, $hidden) { $tbl_link = Database::get_course_table(TABLE_LINK); $course_id = api_get_course_int_id(); $urleq = "url='" . Database::escape_string($url) . "'"; $cateq = "category_id=" . intval($cat); $result = Database::query("SELECT id FROM {$tbl_link}\n WHERE c_id = {$course_id} AND " . $urleq . ' AND ' . $cateq); if (Database::num_rows($result) >= 1 && ($row = Database::fetch_array($result))) { Database::query("UPDATE {$tbl_link} set title='" . Database::escape_string($title) . "', description='" . Database::escape_string($description) . "'\n WHERE c_id = {$course_id} AND id='" . Database::escape_string($row['id']) . "'"); $ipu = 'LinkUpdated'; $rv = 1; // 1 = upd } else { // Add new link $result = Database::query("SELECT MAX(display_order) FROM {$tbl_link}\n WHERE c_id = {$course_id} AND category_id='" . intval($cat) . "'"); list($max_order) = Database::fetch_row($result); Database::query("INSERT INTO {$tbl_link} (c_id, url, title, description, category_id, display_order, on_homepage)\n VALUES (" . api_get_course_int_id() . ",\n '" . Database::escape_string($url) . "',\n '" . Database::escape_string($title) . "',\n '" . Database::escape_string($description) . "',\n '" . intval($cat) . "','" . (intval($max_order) + 1) . "',\n '" . intval($on_homepage) . "')"); $id = Database::insert_id(); $ipu = 'LinkAdded'; $rv = 2; // 2 = new } global $_course, $nameTools, $_user; api_item_property_update($_course, TOOL_LINK, $id, $ipu, $_user['user_id']); if ($hidden && $ipu == 'LinkAdded') { api_item_property_update($_course, TOOL_LINK, $id, 'invisible', $_user['user_id']); } return $rv; }
public static function insert($inputData = array()) { // End addons // $totalArgs=count($inputData); $addMultiAgrs = ''; if (isset($inputData[0]['postid'])) { foreach ($inputData as $theRow) { $theRow['date_added'] = date('Y-m-d H:i:s'); if (isset($theRow['fullname'])) { $theRow['fullname'] = String::encode(strip_tags($theRow['fullname'])); } if (isset($theRow['content'])) { // $theRow['content']=Shortcode::toBBCode($theRow['content']); $theRow['content'] = String::encode($theRow['content']); } $keyNames = array_keys($theRow); $insertKeys = implode(',', $keyNames); $keyValues = array_values($theRow); $insertValues = "'" . implode("','", $keyValues) . "'"; $addMultiAgrs .= "({$insertValues}), "; } $addMultiAgrs = substr($addMultiAgrs, 0, strlen($addMultiAgrs) - 2); } else { $inputData['date_added'] = date('Y-m-d H:i:s'); if (isset($inputData['fullname'])) { $inputData['fullname'] = String::encode(strip_tags($inputData['fullname'])); } if (isset($inputData['content'])) { // $inputData['content']=Shortcode::toBBCode($inputData['content']); $inputData['content'] = String::encode($inputData['content']); } $keyNames = array_keys($inputData); $insertKeys = implode(',', $keyNames); $keyValues = array_values($inputData); $insertValues = "'" . implode("','", $keyValues) . "'"; $addMultiAgrs = "({$insertValues})"; } Database::query("insert into " . Database::getPrefix() . "comments({$insertKeys}) values" . $addMultiAgrs); DBCache::removeDir('system/comment'); if (!($error = Database::hasError())) { $id = Database::insert_id(); return $id; } return false; }
/** * Create a group * @param string $name The name for this group * @param int $category_id * @param int $tutor The user-id of the group's tutor * @param int $places How many people can subscribe to the new group */ public static function create_group($name, $category_id, $tutor, $places) { $_course = api_get_course_info(); $session_id = api_get_session_id(); $course_id = $_course['real_id']; $currentCourseRepository = $_course['path']; $category = self::get_category($category_id); $places = intval($places); if ($category) { if ($places == 0) { //if the amount of users per group is not filled in, use the setting from the category $places = $category['max_student']; } else { if ($places > $category['max_student'] && $category['max_student'] != 0) { $places = $category['max_student']; } } $docState = $category['doc_state']; $calendarState = $category['calendar_state']; $workState = $category['work_state']; $anonuncementState = $category['announcements_state']; $forumState = $category['forum_state']; $wikiState = $category['wiki_state']; $chatState = $category['chat_state']; $selfRegAllowed = $category['self_reg_allowed']; $selfUnregAllwoed = $category['self_unreg_allowed']; } else { $docState = self::TOOL_PRIVATE; $calendarState = self::TOOL_PRIVATE; $workState = self::TOOL_PRIVATE; $anonuncementState = self::TOOL_PRIVATE; $forumState = self::TOOL_PRIVATE; $wikiState = self::TOOL_PRIVATE; $chatState = self::TOOL_PRIVATE; $selfRegAllowed = 0; $selfUnregAllwoed = 0; } $table_group = Database::get_course_table(TABLE_GROUP); $sql = "INSERT INTO " . $table_group . " SET\n c_id = {$course_id},\n status = 1,\n category_id='" . Database::escape_string($category_id) . "',\n max_student = '" . $places . "',\n doc_state = '" . $docState . "',\n calendar_state = '" . $calendarState . "',\n work_state = '" . $workState . "',\n announcements_state = '" . $anonuncementState . "',\n forum_state = '" . $forumState . "',\n wiki_state = '" . $wikiState . "',\n chat_state = '" . $chatState . "',\n self_registration_allowed = '" . $selfRegAllowed . "',\n self_unregistration_allowed = '" . $selfUnregAllwoed . "',\n session_id='" . intval($session_id) . "'"; Database::query($sql); $lastId = Database::insert_id(); if ($lastId) { $sql = "UPDATE {$table_group} SET id = iid WHERE iid = {$lastId}"; Database::query($sql); $desired_dir_name = '/' . api_replace_dangerous_char($name) . '_groupdocs'; $my_path = api_get_path(SYS_COURSE_PATH) . $currentCourseRepository . '/document'; $newFolderData = create_unexisting_directory($_course, api_get_user_id(), $session_id, $lastId, null, $my_path, $desired_dir_name, null, 1); $unique_name = $newFolderData['path']; /* Stores the directory path into the group table */ $sql = "UPDATE " . $table_group . " SET\n name = '" . Database::escape_string($name) . "',\n secret_directory = '" . $unique_name . "'\n WHERE c_id = {$course_id} AND id ='" . $lastId . "'"; Database::query($sql); // create a forum if needed if ($forumState >= 0) { require_once api_get_path(SYS_CODE_PATH) . 'forum/forumconfig.inc.php'; require_once api_get_path(SYS_CODE_PATH) . 'forum/forumfunction.inc.php'; $forum_categories = get_forum_categories(); $values = array(); $values['forum_title'] = $name; $values['group_id'] = $lastId; $counter = 0; foreach ($forum_categories as $key => $value) { if ($counter == 0) { $forum_category_id = $key; } $counter++; } // A sanity check. if (empty($forum_category_id)) { $forum_category_id = 0; } $values['forum_category'] = $forum_category_id; $values['allow_anonymous_group']['allow_anonymous'] = 0; $values['students_can_edit_group']['students_can_edit'] = 0; $values['approval_direct_group']['approval_direct'] = 0; $values['allow_attachments_group']['allow_attachments'] = 1; $values['allow_new_threads_group']['allow_new_threads'] = 1; $values['default_view_type_group']['default_view_type'] = api_get_setting('forum.default_forum_view'); $values['group_forum'] = $lastId; if ($forumState == '1') { $values['public_private_group_forum_group']['public_private_group_forum'] = 'public'; } elseif ($forumState == '2') { $values['public_private_group_forum_group']['public_private_group_forum'] = 'private'; } elseif ($forumState == '0') { $values['public_private_group_forum_group']['public_private_group_forum'] = 'unavailable'; } store_forum($values); } } return $lastId; }
/** * Insert this evaluation into the database */ public function add() { if (isset($this->name) && isset($this->user_id) && isset($this->weight) && isset($this->eval_max) && isset($this->visible)) { $tbl_grade_evaluations = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION); $sql = 'INSERT INTO ' . $tbl_grade_evaluations . ' (name, user_id, weight, max, visible'; if (isset($this->description)) { $sql .= ',description'; } if (isset($this->course_code)) { $sql .= ', course_code'; } if (isset($this->category)) { $sql .= ', category_id'; } $sql .= ', created_at'; $sql .= ',type'; $sql .= ") VALUES ('" . Database::escape_string($this->get_name()) . "'" . ',' . intval($this->get_user_id()) . ',' . floatval($this->get_weight()) . ',' . intval($this->get_max()) . ',' . intval($this->is_visible()); if (isset($this->description)) { $sql .= ",'" . Database::escape_string($this->get_description()) . "'"; } if (isset($this->course_code)) { $sql .= ",'" . Database::escape_string($this->get_course_code()) . "'"; } if (isset($this->category)) { $sql .= ',' . intval($this->get_category_id()); } if (empty($this->type)) { $this->type = 'evaluation'; } $sql .= ", '" . api_get_utc_datetime() . "'"; $sql .= ',\'' . Database::escape_string($this->type) . '\''; $sql .= ")"; Database::query($sql); $this->set_id(Database::insert_id()); } else { die('Error in Evaluation add: required field empty'); } }
private function login_log($id, $success, $two_way = 0) { /* Wanneer het aantal login_log over de 30 komt, moet alles wat daarna komt verwijderd worden. Onderstaande query doet dit. */ Database::query("DELETE FROM login_log WHERE id NOT IN (SELECT id FROM (SELECT id FROM login_log WHERE customer_id = " . $id . " ORDER BY id DESC LIMIT 29) foo)"); /* En hier wordt de nieuwste login_log aangemaakt. */ Database::query("INSERT INTO login_log (customer_id, log_date, accepted, two_way, ip) VALUES (" . $id . ", NOW(), " . ($success ? 1 : 0) . ", " . Database::escape($two_way) . ", '" . Database::escape($_SERVER['REMOTE_ADDR']) . "')"); /* Return de ID van het laatst geinserte row (dus de log van hierboven. */ return Database::insert_id(); }
function WSCreateUserPasswordCrypted($params) { global $_user, $_configuration, $debug; $debug = 1; 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); $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 = isset($params['official_code']) ? $params['official_code'] : ''; $language = ''; $phone = $params['phone']; $picture_uri = ''; $auth_source = PLATFORM_AUTH_SOURCE; $expiration_date = ''; $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 = isset($params['extra']) ? $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}\n 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. 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 = '" . Database::escape_string($official_code) . "',\n picture_uri = '" . Database::escape_string($picture_uri) . "',\n creator_id = '" . 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(); $sql = "UPDATE {$table_user} SET user_id = id WHERE id = {$return}"; Database::query($sql); $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. 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' UserManager::update_extra_field_value($return, $extra_field_name, $extra_field_value); } } } else { return 0; } return $return; }
/** * Restart the whole learnpath. Return the URL of the first element. * Make sure the results are saved with anoter method. This method should probably be * redefined in children classes. * To use a similar method statically, use the create_new_attempt() method * @return string URL to load in the viewer */ function restart() { if ($this->debug > 0) { error_log('New LP - In learnpath::restart()', 0); } //TODO //call autosave method to save the current progress //$this->index = 0; $lp_view_table = Database::get_course_table(TABLE_LP_VIEW); $sql = "INSERT INTO {$lp_view_table} (lp_id, user_id, view_count) " . "VALUES (" . $this->lp_id . "," . $this->get_user_id() . "," . ($this->attempt + 1) . ")"; if ($this->debug > 2) { error_log('New LP - Inserting new lp_view for restart: ' . $sql, 0); } $res = Database::query($sql, __FILE__, __LINE__); if ($view_id = Database::insert_id($res)) { $this->lp_view_id = $view_id; $this->attempt = $this->attempt + 1; } else { $this->error = 'Could not insert into item_view table...'; return false; } $this->autocomplete_parents($this->current); foreach ($this->items as $index => $dummy) { $this->items[$index]->restart(); $this->items[$index]->set_lp_view($this->lp_view_id); } $this->first(); return true; }
/** * Subscribes a user to a given blog * @author Toon Keppens * * @param Integer $blog_id * @param Integer $user_id */ public static function set_user_subscribed($blog_id, $user_id) { // Init $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER); $tbl_user_permissions = Database::get_course_table(TABLE_PERMISSION_USER); $course_id = api_get_course_int_id(); // Subscribe the user $sql = "INSERT INTO {$tbl_blogs_rel_user} (c_id, blog_id, user_id )\n\t\t VALUES ({$course_id}, '" . (int) $blog_id . "', '" . (int) $user_id . "');"; $result = Database::query($sql); // Give this user basic rights $sql = "INSERT INTO {$tbl_user_permissions} (c_id, user_id,tool,action)\n\t\t VALUES ({$course_id}, '" . (int) $user_id . "','BLOG_" . (int) $blog_id . "','article_add')"; $result = Database::query($sql); $id = Database::insert_id(); if ($id) { $sql = "UPDATE {$tbl_user_permissions} SET id = iid WHERE iid = {$id}"; Database::query($sql); } $sql = "INSERT INTO {$tbl_user_permissions} (c_id, user_id,tool,action)\n\t\t VALUES ({$course_id}, '" . (int) $user_id . "','BLOG_" . (int) $blog_id . "','article_comments_add')"; $result = Database::query($sql); $id = Database::insert_id(); if ($id) { $sql = "UPDATE {$tbl_user_permissions} SET id = iid WHERE iid = {$id}"; Database::query($sql); } }
/** * Creates a new course request within the database. * @param string $wanted_code The code for the created in the future course. * @param string $title * @param string $description * @param string $category_code * @param string $course_language * @param string $objetives * @param string $target_audience * @param int/string $user_id * @return int/bool The database id of the newly created course request or FALSE on failure. */ public static function create_course_request($wanted_code, $title, $description, $category_code, $course_language, $objetives, $target_audience, $user_id, $exemplary_content) { $wanted_code = trim($wanted_code); $user_id = (int) $user_id; $exemplary_content = (bool) $exemplary_content ? 1 : 0; if ($wanted_code == '') { return false; } if (self::course_code_exists($wanted_code)) { return false; } if ($user_id <= 0) { return false; } $user_info = api_get_user_info($user_id); if (!is_array($user_info)) { return false; } $tutor_name = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, null, $course_language); $request_date = api_get_utc_datetime(); $status = COURSE_REQUEST_PENDING; $info = 0; $keys = AddCourse::define_course_keys($wanted_code, ''); if (!count($keys)) { return false; } $visual_code = $keys['currentCourseCode']; $code = $keys['currentCourseId']; $db_name = isset($keys['currentCourseDbName']) ? $keys['currentCourseDbName'] : null; $directory = $keys['currentCourseRepository']; $sql = sprintf('INSERT INTO %s ( code, user_id, directory, db_name, course_language, title, description, category_code, tutor_name, visual_code, request_date, objetives, target_audience, status, info, exemplary_content) VALUES ( "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s");', Database::get_main_table(TABLE_MAIN_COURSE_REQUEST), Database::escape_string($code), Database::escape_string($user_id), Database::escape_string($directory), Database::escape_string($db_name), Database::escape_string($course_language), Database::escape_string($title), Database::escape_string($description), Database::escape_string($category_code), Database::escape_string($tutor_name), Database::escape_string($visual_code), Database::escape_string($request_date), Database::escape_string($objetives), Database::escape_string($target_audience), Database::escape_string($status), Database::escape_string($info), Database::escape_string($exemplary_content)); $result_sql = Database::query($sql); if (!$result_sql) { return false; } $last_insert_id = Database::insert_id(); // E-mail notifications. // E-mail language: The platform language seems to be the best choice. $email_language = api_get_setting('platformLanguage'); $email_subject = sprintf(get_lang('CourseRequestEmailSubject', null, $email_language), '[' . api_get_setting('siteName') . ']', $code); $email_body = get_lang('CourseRequestMailOpening', null, $email_language) . "\n\n"; $email_body .= get_lang('CourseName', null, $email_language) . ': ' . $title . "\n"; $email_body .= get_lang('Fac', null, $email_language) . ': ' . $category_code . "\n"; $email_body .= get_lang('CourseCode', null, $email_language) . ': ' . $code . "\n"; $email_body .= get_lang('Professor', null, $email_language) . ': ' . api_get_person_name($user_info['firstname'], $user_info['lastname'], null, null, $email_language) . "\n"; $email_body .= get_lang('Email', null, $email_language) . ': ' . $user_info['mail'] . "\n"; $email_body .= get_lang('Description', null, $email_language) . ': ' . $description . "\n"; $email_body .= get_lang('Objectives', null, $email_language) . ': ' . $objetives . "\n"; $email_body .= get_lang('TargetAudience', null, $email_language) . ': ' . $target_audience . "\n"; $email_body .= get_lang('Ln', null, $email_language) . ': ' . $course_language . "\n"; $email_body .= get_lang('FillWithExemplaryContent', null, $email_language) . ': ' . ($exemplary_content ? get_lang('Yes', null, $email_language) : get_lang('No', null, $email_language)) . "\n"; // Sending an e-mail to the platform administrator. $email_body_admin = $email_body; $email_body_admin .= "\n" . get_lang('CourseRequestPageForApproval', null, $email_language) . ' ' . api_get_path(WEB_CODE_PATH) . 'admin/course_request_edit.php?id=' . $last_insert_id . "\n"; $email_body_admin .= "\n" . get_lang('CourseRequestLegalNote', null, $email_language) . "\n"; $sender_name_teacher = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS); $sender_email_teacher = $user_info['mail']; $recipient_name_admin = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS); $recipient_email_admin = api_get_setting('emailAdministrator'); $userInfo = api_get_user_info($user_id); $additionalParameters = array('smsType' => SmsPlugin::NEW_COURSE_SUGGESTED_TEACHER, 'userId' => $user_id, 'userUsername' => $userInfo['username']); api_mail_html($recipient_name_admin, $recipient_email_admin, $email_subject, $email_body_admin, $sender_name_teacher, $sender_email_teacher, null, null, null, $additionalParameters); // Sending an e-mail to the requestor. $email_body_teacher = get_lang('Dear', null, $email_language) . ' '; $email_body_teacher .= api_get_person_name($user_info['firstname'], $user_info['lastname'], null, null, $email_language) . ",\n\n"; $email_body_teacher .= $email_body; $email_body_teacher .= "\n" . get_lang('Formula', null, $email_language) . "\n"; $email_body_teacher .= api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, null, $email_language) . "\n"; $email_body_teacher .= get_lang('Manager', null, $email_language) . ' ' . api_get_setting('siteName') . "\n"; $email_body_teacher .= get_lang('Phone', null, $email_language) . ': ' . api_get_setting('administratorTelephone') . "\n"; $email_body_teacher .= get_lang('Email', null, $email_language) . ': ' . api_get_setting('emailAdministrator', null, $email_language) . "\n"; $email_body_teacher .= "\n" . get_lang('CourseRequestLegalNote', null, $email_language) . "\n"; // Swap the sender and the recipient. $sender_name_admin = $recipient_name_admin; $sender_email_admin = $recipient_email_admin; $recipient_name_teacher = $sender_name_teacher; $recipient_email_teacher = $sender_email_teacher; $additionalParameters = array('smsType' => SmsPlugin::COURSE_OPENING_REQUEST_CODE_REGISTERED, 'userId' => $user_info['user_id'], 'courseCode' => $wanted_code); api_mail_html($recipient_name_teacher, $recipient_email_teacher, $email_subject, $email_body_teacher, $sender_name_admin, $sender_email_admin, null, null, null, $additionalParameters); return $last_insert_id; }
function restore_wiki($session_id = 0) { if ($this->course->has_resources(RESOURCE_WIKI)) { // wiki table of the target course $table_wiki = Database::get_course_table('wiki'); $table_wiki_conf = Database::get_course_table('wiki_conf'); // storing all the resources that have to be copied in an array $resources = $this->course->resources; foreach ($resources[RESOURCE_WIKI] as $id => $wiki) { //$wiki = new Wiki($obj->page_id, $obj->reflink, $obj->title, $obj->content, $obj->user_id, $obj->group_id, $obj->dtime); // the sql statement to insert the groups from the old course to the new course // check resources inside html from fckeditor tool and copy correct urls into recipient course $wiki->content = DocumentManager::replace_urls_inside_content_html_from_copy_course($wiki->content, $this->course->code, $this->course->destination_path, $this->course->backup_path, $this->course->info['path']); $sql = "INSERT INTO {$table_wiki} (c_id, page_id, reflink, title, content, user_id, group_id, dtime, progress, version, session_id) VALUES (\n\t\t\t\t\t\t\t" . $this->destination_course_id . " ,\n\t\t\t\t\t\t\t'" . self::DBUTF8escapestring($wiki->page_id) . "',\n\t\t\t\t\t\t\t'" . self::DBUTF8escapestring($wiki->reflink) . "',\n\t\t\t\t\t\t\t'" . self::DBUTF8escapestring($wiki->title) . "',\n\t\t\t\t\t\t\t'" . self::DBUTF8escapestring($wiki->content) . "',\n\t\t\t\t\t\t\t'" . intval($wiki->user_id) . "',\n\t\t\t\t\t\t\t'" . intval($wiki->group_id) . "',\n\t\t\t\t\t\t\t'" . self::DBUTF8escapestring($wiki->dtime) . "',\n\t\t\t\t\t\t\t'" . self::DBUTF8escapestring($wiki->progress) . "',\n\t\t\t\t\t\t\t'" . intval($wiki->version) . "',\n\t\t\t\t\t\t\t'" . (!empty($session_id) ? intval($session_id) : 0) . "')"; $rs2 = Database::query($sql); $new_id = Database::insert_id(); $this->course->resources[RESOURCE_WIKI][$id]->destination_id = $new_id; $sql = "UPDATE {$table_wiki} set page_id = '{$new_id}' WHERE c_id = " . $this->destination_course_id . " AND id = '{$new_id}'"; Database::query($sql); // we also add an entry in wiki_conf $sql = "INSERT INTO {$table_wiki_conf} (c_id, page_id, task, feedback1, feedback2, feedback3, fprogress1, fprogress2, fprogress3, max_size, max_text, max_version, startdate_assig, enddate_assig, delayedsubmit) VALUES\n\t\t\t\t\t\t(" . $this->destination_course_id . " , '" . intval($new_id) . "', '', '', '', '', '', '', '', NULL, 0, 0, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0)"; $rs1 = Database::query($sql); } } }
/** * Create a question from a set of parameters * @param int Quiz ID * @param string Question name * @param int Maximum result for the question * @param int Type of question (see constants at beginning of question.class.php) * @param int Question level/category */ public function create_question($quiz_id, $question_name, $max_score = 0, $type = 1, $level = 1) { $course_id = api_get_course_int_id(); $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION); $tbl_quiz_rel_question = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION); $quiz_id = intval($quiz_id); $max_score = (double) $max_score; $type = intval($type); $level = intval($level); // Get the max position $sql = "SELECT max(position) as max_position" . " FROM {$tbl_quiz_question} q INNER JOIN {$tbl_quiz_rel_question} r" . " ON q.iid = r.question_id" . " AND exercice_id = {$quiz_id} AND q.c_id = {$course_id} AND r.c_id = {$course_id}"; $rs_max = Database::query($sql); $row_max = Database::fetch_object($rs_max); $max_position = $row_max->max_position + 1; // Insert the new question $sql = "INSERT INTO {$tbl_quiz_question} (c_id, question, ponderation, position, type, level)\n VALUES ({$course_id}, '" . Database::escape_string($question_name) . "', '{$max_score}', {$max_position}, {$type}, {$level})"; Database::query($sql); // Get the question ID $question_id = Database::insert_id(); // Get the max question_order $sql = "SELECT max(question_order) as max_order FROM {$tbl_quiz_rel_question}\n WHERE c_id = {$course_id} AND exercice_id = {$quiz_id} "; $rs_max_order = Database::query($sql); $row_max_order = Database::fetch_object($rs_max_order); $max_order = $row_max_order->max_order + 1; // Attach questions to quiz $sql = "INSERT INTO {$tbl_quiz_rel_question} (c_id, question_id, exercice_id, question_order)\n VALUES ({$course_id}, {$question_id}, {$quiz_id}, {$max_order})"; Database::query($sql); return $question_id; }
/** * update users' attendance results * @param array $user_ids registered users inside current course * @param int $attendance_id * @return void */ public function update_users_results($user_ids, $attendance_id) { $tbl_attendance_sheet = Database::get_course_table(TABLE_ATTENDANCE_SHEET); $tbl_attendance_result = Database::get_course_table(TABLE_ATTENDANCE_RESULT); $tbl_attendance = Database::get_course_table(TABLE_ATTENDANCE); $course_id = api_get_course_int_id(); $attendance_id = intval($attendance_id); // fill results about presence of students $attendance_calendar = $this->get_attendance_calendar($attendance_id, 'all', null, null, true); $calendar_ids = array(); // get all dates from calendar by current attendance foreach ($attendance_calendar as $cal) { $calendar_ids[] = $cal['id']; } // get count of presences by users inside current attendance and save like results if (count($user_ids) > 0) { foreach ($user_ids as $uid) { $count_presences = 0; if (count($calendar_ids) > 0) { $sql = "SELECT count(presence) as count_presences\n\t\t\t\t\t\t\tFROM {$tbl_attendance_sheet}\n\t\t\t\t\t WHERE\n\t\t\t\t\t \tc_id = {$course_id} AND\n\t\t\t\t\t \tuser_id = '{$uid}' AND\n\t\t\t\t\t \tattendance_calendar_id IN (" . implode(',', $calendar_ids) . ") AND\n\t\t\t\t\t \tpresence = 1"; $rs_count = Database::query($sql); $row_count = Database::fetch_array($rs_count); $count_presences = $row_count['count_presences']; } // save results $sql = "SELECT id FROM {$tbl_attendance_result}\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\tc_id = {$course_id} AND\n\t\t\t\t\t\t\tuser_id = '{$uid}' AND\n\t\t\t\t\t\t\tattendance_id = '{$attendance_id}' "; $rs_check_result = Database::query($sql); if (Database::num_rows($rs_check_result) > 0) { // update result $sql = "UPDATE {$tbl_attendance_result} SET\n\t\t\t\t\t\t\tscore = '{$count_presences}'\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tc_id = {$course_id} AND\n\t\t\t\t\t\t\t\tuser_id='{$uid}' AND\n\t\t\t\t\t\t\t\tattendance_id='{$attendance_id}'"; Database::query($sql); } else { // insert new result $sql = "INSERT INTO {$tbl_attendance_result} SET\n\t\t\t\t\t\t\tc_id = {$course_id} ,\n\t\t\t\t\t\t\tuser_id\t\t\t= '{$uid}',\n\t\t\t\t\t\t\tattendance_id \t= '{$attendance_id}',\n\t\t\t\t\t\t\tscore\t\t\t= '{$count_presences}'"; Database::query($sql); $insertId = Database::insert_id(); if ($insertId) { $sql = "UPDATE {$tbl_attendance_result} SET id = iid WHERE iid = {$insertId}"; Database::query($sql); } } } } // update attendance qualify max $count_done_calendar = self::get_done_attendance_calendar($attendance_id); $sql = "UPDATE {$tbl_attendance} SET\n\t\t\t\tattendance_qualify_max = '{$count_done_calendar}'\n\t\t\t\tWHERE c_id = {$course_id} AND id = '{$attendance_id}'"; Database::query($sql); }