当前位置: 首页>>代码示例>>PHP>>正文


PHP begin_sql函数代码示例

本文整理汇总了PHP中begin_sql函数的典型用法代码示例。如果您正苦于以下问题:PHP begin_sql函数的具体用法?PHP begin_sql怎么用?PHP begin_sql使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了begin_sql函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: start_transaction

 /**
  * Begins a (possibly nested) transaction. The forum uses transactions
  * where possible and where supported by the underlying Moodle function,
  * which does not cope with nesting.
  */
 static function start_transaction()
 {
     if (self::$transactions == 0) {
         begin_sql();
     }
     self::$transactions++;
 }
开发者ID:hmatulis,项目名称:RTL-BIDI-Hebrew-Moodle-Plugins,代码行数:12,代码来源:forum_utils.php

示例2: cleanup_contexts

/**
 * Remove stale context records
 *
 * @return bool
 */
function cleanup_contexts()
{
    global $CFG;
    $sql = "  SELECT c.contextlevel,\n                     c.instanceid AS instanceid\n              FROM {$CFG->prefix}context c\n              LEFT OUTER JOIN {$CFG->prefix}course_categories t\n                ON c.instanceid = t.id\n              WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSECAT . "\n            UNION\n              SELECT c.contextlevel,\n                     c.instanceid\n              FROM {$CFG->prefix}context c\n              LEFT OUTER JOIN {$CFG->prefix}course t\n                ON c.instanceid = t.id\n              WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSE . "\n            UNION\n              SELECT c.contextlevel,\n                     c.instanceid\n              FROM {$CFG->prefix}context c\n              LEFT OUTER JOIN {$CFG->prefix}course_modules t\n                ON c.instanceid = t.id\n              WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_MODULE . "\n            UNION\n              SELECT c.contextlevel,\n                     c.instanceid\n              FROM {$CFG->prefix}context c\n              LEFT OUTER JOIN {$CFG->prefix}user t\n                ON c.instanceid = t.id\n              WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_USER . "\n            UNION\n              SELECT c.contextlevel,\n                     c.instanceid\n              FROM {$CFG->prefix}context c\n              LEFT OUTER JOIN {$CFG->prefix}block_instance t\n                ON c.instanceid = t.id\n              WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_BLOCK . "\n           ";
    if ($rs = get_recordset_sql($sql)) {
        begin_sql();
        $tx = true;
        while ($tx && ($ctx = rs_fetch_next_record($rs))) {
            $tx = $tx && delete_context($ctx->contextlevel, $ctx->instanceid);
        }
        rs_close($rs);
        if ($tx) {
            commit_sql();
            return true;
        }
        rollback_sql();
        return false;
        rs_close($rs);
    }
    return true;
}
开发者ID:edwinphillips,项目名称:moodle-485cb39,代码行数:26,代码来源:accesslib.php

示例3: dialogue_cron


//.........这里部分代码省略.........
    $rs = get_recordset_select('dialogue_conversations', 'grouping != 0 AND grouping IS NOT NULL', 'dialogueid, grouping');
    $dialogueid = 0;
    $grouping = 0;
    $groupid = null;
    $inconversation = array();
    $newusers = array();
    while ($conversation = rs_fetch_next_record($rs)) {
        if ($dialogueid != $conversation->dialogueid || $groupid != $conversation->groupid || $grouping != $conversation->grouping) {
            if ($dialogueid == 0 || $groupid === null) {
                $dialogueid = $conversation->dialogueid;
                $groupid = $conversation->groupid;
            }
            $cm = get_coursemodule_from_instance('dialogue', $dialogueid);
            $context = get_context_instance(CONTEXT_MODULE, $cm->id);
            $users = (array) get_users_by_capability($context, 'mod/dialogue:participate', 'u.id, u.firstname, u.lastname', null, null, null, empty($groupid) ? null : $groupid, null, null, null, false);
            $managers = (array) get_users_by_capability($context, 'mod/dialogue:manage', 'u.id, u.firstname, u.lastname', null, null, null, null, null, null, null, false);
            $dialogueid = $conversation->dialogueid;
            $groupid = $conversation->groupid;
        }
        if ($grouping != $conversation->grouping) {
            if ($grouping) {
                if ($userdiff = array_diff_key($users, $inconversation, $managers)) {
                    foreach ($userdiff as $userid => $value) {
                        $newusers[$userid . ',' . $grouping] = array('userid' => $userid, 'courseid' => $cm->course, 'grouping' => $grouping);
                    }
                }
            }
            $inconversation = array();
            $grouping = $conversation->grouping;
        }
        $inconversation[$conversation->recipientid] = true;
    }
    if (!empty($dialogueid)) {
        // Finish of any remaing users
        $cm = get_coursemodule_from_instance('dialogue', $dialogueid);
        $context = get_context_instance(CONTEXT_MODULE, $cm->id);
        $users = (array) get_users_by_capability($context, 'mod/dialogue:participate', 'u.id, u.firstname, u.lastname', null, null, null, empty($groupid) ? null : $groupid, null, null, null, false);
        $managers = (array) get_users_by_capability($context, 'mod/dialogue:manage', 'u.id, u.firstname, u.lastname', null, null, null, null, null, null, null, false);
        if ($userdiff = array_diff_key($users, $inconversation, $managers)) {
            foreach ($userdiff as $userid => $value) {
                $newusers[$userid . ',' . $grouping] = array('userid' => $userid, 'courseid' => $cm->course, 'grouping' => $grouping);
            }
        }
    }
    rs_close($rs);
    if (!empty($newusers)) {
        foreach ($newusers as $key => $newuser) {
            begin_sql();
            course_setup($newuser['courseid']);
            if ($conversations = get_records('dialogue_conversations', 'grouping', $newuser['grouping'], 'id', '*', 0, 1)) {
                $conversation = array_pop($conversations);
                // we only need one to get the common field values
                if ($entry = get_records('dialogue_entries', 'conversationid', $conversation->id, 'id', '*', 0, 1)) {
                    unset($conversation->id);
                    $conversation->recipientid = $newuser['userid'];
                    $conversation->lastrecipientid = $newuser['userid'];
                    $conversation->timemodified = time();
                    $conversation->seenon = false;
                    $conversation->closed = 0;
                    $conversation = addslashes_object($conversation);
                    if (!($conversationid = insert_record('dialogue_conversations', $conversation))) {
                        rollback_sql();
                        continue;
                    }
                    $entry = array_pop($entry);
                    $srcentry = clone $entry;
                    unset($entry->id);
                    $entry->conversationid = $conversationid;
                    $entry->timecreated = $conversation->timemodified;
                    $entry->recipientid = $conversation->recipientid;
                    $entry->mailed = false;
                    $entry = addslashes_object($entry);
                    if (!($entry->id = insert_record('dialogue_entries', $entry))) {
                        rollback_sql();
                        continue;
                    }
                    $read = new stdClass();
                    $lastread = time();
                    $read->conversationid = $conversationid;
                    $read->entryid = $entry->id;
                    $read->userid = $conversation->userid;
                    $read->firstread = $lastread;
                    $read->lastread = $lastread;
                    insert_record('dialogue_read', $read);
                    if ($entry->attachment) {
                        $srcdir = dialogue_file_area($srcentry);
                        $dstdir = dialogue_file_area($entry);
                        copy($srcdir . '/' . $entry->attachment, $dstdir . '/' . $entry->attachment);
                    }
                } else {
                    mtrace('Failed to find entry for conversation: ' . $conversation->id);
                }
            } else {
                mtrace('Failed to find conversation: ' . $conversation->id);
            }
            commit_sql();
        }
    }
    return true;
}
开发者ID:netspotau,项目名称:moodle-mod_dialogue,代码行数:101,代码来源:lib.php

示例4: fix_coursecategory_orphans

/**
 * Ensure all courses have a valid course category
 * useful if a category has been removed manually
 **/
function fix_coursecategory_orphans()
{
    global $CFG;
    // Note: the handling of sortorder here is arguably
    // open to race conditions. Hard to fix here, unlikely
    // to hit anyone in production.
    $sql = "SELECT c.id, c.category, c.shortname\n            FROM {$CFG->prefix}course c\n            LEFT OUTER JOIN {$CFG->prefix}course_categories cc ON c.category=cc.id\n            WHERE cc.id IS NULL AND c.id != " . SITEID;
    $rs = get_recordset_sql($sql);
    if (!rs_EOF($rs)) {
        // we have some orphans
        // the "default" category is the lowest numbered...
        $default = get_field_sql("SELECT MIN(id)\n                                    FROM {$CFG->prefix}course_categories");
        $sortorder = get_field_sql("SELECT MAX(sortorder)\n                                    FROM {$CFG->prefix}course\n                                    WHERE category={$default}");
        begin_sql();
        $tx = true;
        while ($tx && ($course = rs_fetch_next_record($rs))) {
            $tx = $tx && set_field('course', 'category', $default, 'id', $course->id);
            $tx = $tx && set_field('course', 'sortorder', ++$sortorder, 'id', $course->id);
        }
        if ($tx) {
            commit_sql();
        } else {
            rollback_sql();
        }
    }
    rs_close($rs);
}
开发者ID:r007,项目名称:PMoodle,代码行数:31,代码来源:datalib.php

示例5: restore

 /**
  * Restores the data in the question
  *
  * This is used in question/restorelib.php
  */
 function restore($old_question_id, $new_question_id, $info, $restore)
 {
     $status = begin_sql();
     $minfo = $info['#']['MATRIX'];
     $newmatrix = (object) array('questionid' => $new_question_id, 'grademethod' => backup_todb($minfo[0]['#']['GRADEMETHOD']['0']['#']), 'multiple' => backup_todb($minfo[0]['#']['MULTIPLE']['0']['#']), 'renderer' => backup_todb($minfo[0]['#']['RENDERER']['0']['#']));
     $newmatrix->id = insert_record('question_matrix', $newmatrix);
     $rows = $minfo[0]['#']['ROWS'][0]['#']['ROW'];
     // why does this get eaten?!
     $rowmapping = array();
     foreach ($rows as $row) {
         $row = $row['#'];
         // more nonsense
         $newrow = (object) array('matrixid' => $newmatrix->id, 'shorttext' => backup_todb($row['SHORTTEXT']['0']['#']), 'description' => backup_todb($row['DESCRIPTION']['0']['#']), 'feedback' => backup_todb($row['FEEDBACK']['0']['#']));
         $status = $status && ($rowmapping[backup_todb($row['ID']['0']['#'])] = insert_record('question_matrix_rows', $newrow));
     }
     $cols = $minfo[0]['#']['COLS'][0]['#']['COL'];
     // why does this get eaten?!
     $colmapping = array();
     foreach ($cols as $col) {
         $col = $col['#'];
         // more nonsense
         $newcol = (object) array('matrixid' => $newmatrix->id, 'shorttext' => backup_todb($col['SHORTTEXT']['0']['#']), 'description' => backup_todb($col['DESCRIPTION']['0']['#']));
         $status = $status && ($colmapping[backup_todb($col['ID']['0']['#'])] = insert_record('question_matrix_cols', $newcol));
     }
     $weights = $minfo[0]['#']['WEIGHTS'][0]['#']['WEIGHT'];
     foreach ($weights as $weight) {
         $weight = $weight['#'];
         $newweight = (object) array('rowid' => $rowmapping[backup_todb($weight['ROWID'][0]['#'])], 'colid' => $colmapping[backup_todb($weight['COLID'][0]['#'])], 'weight' => backup_todb($weight['WEIGHT'][0]['#']));
         $status = $status && insert_record('question_matrix_weights', $newweight);
     }
     return $status && commit_sql();
 }
开发者ID:sunilwebaccess,项目名称:moodle-question-matrix,代码行数:37,代码来源:questiontype.php

示例6: update

 /**
  * Adds a new document or updates an existing one. The necessary set_ 
  * methods must already have been called.
  * @param string $title Document title (plain text)
  * @param string $content Document content (XHTML)
  * @param int $timemodified Optional modified time (defaults to now)
  * @param int $timeexpires Optional expiry time (defaults to none); if
  *   expiry time is included then module must provide a 
  *   modulename_ousearch_update($document=null) function
  * @param mixed $extrastrings An array of additional strings which are
  *   searchable, but not included as part of the document content (for
  *   display to users etc). This can be used for keywords and the like
  * @return True for success, false for failure
  */
 function update($title, $content, $timemodified = null, $timeexpires = null, $extrastrings = null)
 {
     global $OUSEARCH_NO_TRANSACTIONS;
     if (empty($OUSEARCH_NO_TRANSACTIONS)) {
         begin_sql();
     }
     // Find document ID, creating document if needed
     if (!$this->find()) {
         // Arse around with slashes so we can insert it safely
         // but the data is corrected again later.
         if (!empty($this->stringref)) {
             $beforestringref = $this->stringref;
             $this->stringref = addslashes($this->stringref);
         }
         $beforeplugin = $this->plugin;
         $this->plugin = addslashes($this->plugin);
         $ok = insert_record('block_ousearch_documents', $this);
         if (!empty($beforestringref)) {
             $this->stringref = $beforestringref;
         }
         $this->plugin = $beforeplugin;
         if (!$ok) {
             debugging('Failed to add ousearch document');
             if (empty($OUSEARCH_NO_TRANSACTIONS)) {
                 rollback_sql();
             }
             return false;
         }
         $this->id = $ok;
     }
     // Update document record if needed
     if ($timemodified || $timeexpires) {
         $update = new StdClass();
         $update->id = $this->id;
         if ($timemodified) {
             $update->timemodified = $timemodified;
         }
         if ($timeexpires) {
             $update->timeexpires = $timeexpires;
         }
         if (!update_record('block_ousearch_documents', $update)) {
             debugging('Failed to update document record');
             if (empty($OUSEARCH_NO_TRANSACTIONS)) {
                 rollback_sql();
             }
             return false;
         }
     }
     // Delete existing words
     if (!delete_records('block_ousearch_occurrences', 'documentid', $this->id)) {
         debugging('Failed to delete occurrences for ousearch document ' . $this->id);
         if (empty($OUSEARCH_NO_TRANSACTIONS)) {
             rollback_sql();
         }
         return false;
     }
     // Extra strings are just counted as more content in the database
     if ($extrastrings) {
         foreach ($extrastrings as $string) {
             $content .= ' ' . $string;
         }
     }
     // Add new words
     $result = $this->internal_add_words($title, $content);
     if (empty($OUSEARCH_NO_TRANSACTIONS)) {
         commit_sql();
     }
     return $result;
 }
开发者ID:hmatulis,项目名称:RTL-BIDI-Hebrew-Moodle-Plugins,代码行数:83,代码来源:searchlib.php

示例7: optional_param

$id_ejercicio = optional_param('id_ejercicio', 0, PARAM_INT);
$tipo_origen = optional_param('tipo_origen', 0, PARAM_INT);
$tipo_respuesta = optional_param('tr', 0, PARAM_INT);
$tipo_creacion = optional_param('tipocreacion', 0, PARAM_INT);
echo "MODIFICANDO";
$mform = new mod_ejercicios_mostrar_ejercicio_asociacion_multiple($id_curso, $id_ejercicio, $tipo_origen, $tipo_respuesta, $tipo_creacion);
$mform->mostrar_ejercicio_asociacion_multiple($id_curso, $id_ejercicio, 0, $tipo_origen, $tipo_respuesta, $tipo_creacion);
$numeropreguntas = optional_param('num_preg', 0, PARAM_INT);
echo "El numero de pregunas es" . $numeropreguntas;
$ejercicio_general = new Ejercicios_general();
$miejercicio = $ejercicio_general->obtener_uno($id_ejercicio);
$miejercicio->set_numpregunta($numeropreguntas);
$fuentes = optional_param('fuentes', PARAM_TEXT);
$miejercicio->set_fuentes($fuentes);
$miejercicio->alterar();
begin_sql();
if ($tipo_origen == 1) {
    //la pregunta es un texto
    if ($tipo_respuesta == 1) {
        //Es un texto
        //obtengo los id de las preguntas del ejercicio
        //$id_preguntas = array();
        $mis_preguntas = new Ejercicios_texto_texto_preg();
        $id_preguntas = $mis_preguntas->obtener_todas_preguntas_ejercicicio($id_ejercicio);
        //borro las respuestas
        for ($s = 0; $s < sizeof($id_preguntas); $s++) {
            delete_records('ejercicios_texto_texto_resp', 'id_pregunta', $id_preguntas[$s]->get('id'));
        }
    } else {
        if ($tipo_respuesta == 2) {
            //la respuesta es un audio
开发者ID:cagmi,项目名称:ejerciciosVIP,代码行数:31,代码来源:ejercicios_modificar_asociacion_multiple.php

示例8: delete_user

/**
 * Marks user deleted in internal user database and notifies the auth plugin.
 * Also unenrols user from all roles and does other cleanup.
 * @param object $user       Userobject before delete    (without system magic quotes)
 * @return boolean success
 */
function delete_user($user)
{
    global $CFG;
    require_once $CFG->libdir . '/grouplib.php';
    require_once $CFG->libdir . '/gradelib.php';
    require_once $CFG->dirroot . '/message/lib.php';
    begin_sql();
    // delete all grades - backup is kept in grade_grades_history table
    if ($grades = grade_grade::fetch_all(array('userid' => $user->id))) {
        foreach ($grades as $grade) {
            $grade->delete('userdelete');
        }
    }
    //move unread messages from this user to read
    message_move_userfrom_unread2read($user->id);
    // remove from all groups
    delete_records('groups_members', 'userid', $user->id);
    // unenrol from all roles in all contexts
    role_unassign(0, $user->id);
    // this might be slow but it is really needed - modules might do some extra cleanup!
    // now do a final accesslib cleanup - removes all role assingments in user context and context itself
    delete_context(CONTEXT_USER, $user->id);
    require_once $CFG->dirroot . '/tag/lib.php';
    tag_set('user', $user->id, array());
    // workaround for bulk deletes of users with the same email address
    $delname = addslashes("{$user->email}." . time());
    while (record_exists('user', 'username', $delname)) {
        // no need to use mnethostid here
        $delname++;
    }
    // mark internal user record as "deleted"
    $updateuser = new object();
    $updateuser->id = $user->id;
    $updateuser->deleted = 1;
    $updateuser->username = $delname;
    // Remember it just in case
    $updateuser->email = md5($user->username);
    // Store hash of username, useful importing/restoring users
    $updateuser->idnumber = '';
    // Clear this field to free it up
    $updateuser->timemodified = time();
    if (update_record('user', $updateuser)) {
        commit_sql();
        // notify auth plugin - do not block the delete even when plugin fails
        $authplugin = get_auth_plugin($user->auth);
        $authplugin->user_delete($user);
        events_trigger('user_deleted', $user);
        return true;
    } else {
        rollback_sql();
        return false;
    }
}
开发者ID:nadavkav,项目名称:rtlMoodle,代码行数:59,代码来源:moodlelib.php

示例9: sync_users

 /**
  * syncronizes user fron external db to moodle user table
  *
  * Sync is now using username attribute.
  *
  * Syncing users removes or suspends users that dont exists anymore in external db.
  * Creates new users and updates coursecreator status of users.
  *
  * @param int $bulk_insert_records will insert $bulkinsert_records per insert statement
  *                         valid only with $unsafe. increase to a couple thousand for
  *                         blinding fast inserts -- but test it: you may hit mysqld's
  *                         max_allowed_packet limit.
  * @param bool $do_updates will do pull in data updates from ldap if relevant
  */
 function sync_users($bulk_insert_records = 1000, $do_updates = true)
 {
     global $CFG;
     $textlib = textlib_get_instance();
     $droptablesql = array();
     /// sql commands to drop the table (because session scope could be a problem for
     /// some persistent drivers like ODBTP (mssql) or if this function is invoked
     /// from within a PHP application using persistent connections
     $temptable = $CFG->prefix . 'extuser';
     $createtemptablesql = '';
     // configure a temp table
     print "Configuring temp table\n";
     switch (strtolower($CFG->dbfamily)) {
         case 'mysql':
             $droptablesql[] = 'DROP TEMPORARY TABLE ' . $temptable;
             // sql command to drop the table (because session scope could be a problem)
             $createtemptablesql = 'CREATE TEMPORARY TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username)) TYPE=MyISAM';
             break;
         case 'postgres':
             $droptablesql[] = 'DROP TABLE ' . $temptable;
             // sql command to drop the table (because session scope could be a problem)
             $bulk_insert_records = 1;
             // no support for multiple sets of values
             $createtemptablesql = 'CREATE TEMPORARY TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))';
             break;
         case 'mssql':
             $temptable = '#' . $temptable;
             /// MSSQL temp tables begin with #
             $droptablesql[] = 'DROP TABLE ' . $temptable;
             // sql command to drop the table (because session scope could be a problem)
             $bulk_insert_records = 1;
             // no support for multiple sets of values
             $createtemptablesql = 'CREATE TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))';
             break;
         case 'oracle':
             $droptablesql[] = 'TRUNCATE TABLE ' . $temptable;
             // oracle requires truncate before being able to drop a temp table
             $droptablesql[] = 'DROP TABLE ' . $temptable;
             // sql command to drop the table (because session scope could be a problem)
             $bulk_insert_records = 1;
             // no support for multiple sets of values
             $createtemptablesql = 'CREATE GLOBAL TEMPORARY TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username)) ON COMMIT PRESERVE ROWS';
             break;
     }
     execute_sql_arr($droptablesql, true, false);
     /// Drop temp table to avoid persistence problems later
     echo "Creating temp table {$temptable}\n";
     if (!execute_sql($createtemptablesql, false)) {
         print "Failed to create temporary users table - aborting\n";
         exit;
     }
     print "Connecting to ldap...\n";
     $ldapconnection = $this->ldap_connect();
     if (!$ldapconnection) {
         $this->ldap_close();
         print get_string('auth_ldap_noconnect', 'auth', $this->config->host_url);
         exit;
     }
     ////
     //// get user's list from ldap to sql in a scalable fashion
     ////
     // prepare some data we'll need
     $filter = '(&(' . $this->config->user_attribute . '=*)' . $this->config->objectclass . ')';
     $contexts = explode(";", $this->config->contexts);
     if (!empty($this->config->create_context)) {
         array_push($contexts, $this->config->create_context);
     }
     $fresult = array();
     foreach ($contexts as $context) {
         $context = trim($context);
         if (empty($context)) {
             continue;
         }
         begin_sql();
         if ($this->config->search_sub) {
             //use ldap_search to find first user from subtree
             $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute));
         } else {
             //search only in this context
             $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute));
         }
         if ($entry = ldap_first_entry($ldapconnection, $ldap_result)) {
             do {
                 $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
                 $value = $textlib->convert($value[0], $this->config->ldapencoding, 'utf-8');
                 // usernames are __always__ lowercase.
//.........这里部分代码省略.........
开发者ID:arshanam,项目名称:Moodle-ITScholars-LMS,代码行数:101,代码来源:auth.php

示例10: stats_upgrade_for_roles_wrapper

function stats_upgrade_for_roles_wrapper()
{
    global $CFG;
    if (!empty($CFG->statsrolesupgraded)) {
        return true;
    }
    $result = begin_sql();
    $result = $result && stats_upgrade_user_table_for_roles('daily');
    $result = $result && stats_upgrade_user_table_for_roles('weekly');
    $result = $result && stats_upgrade_user_table_for_roles('monthly');
    $result = $result && stats_upgrade_table_for_roles('daily');
    $result = $result && stats_upgrade_table_for_roles('weekly');
    $result = $result && stats_upgrade_table_for_roles('monthly');
    $result = $result && commit_sql();
    if (!empty($result)) {
        set_config('statsrolesupgraded', time());
    }
    // finally upgade totals, no big deal if it fails
    stats_upgrade_totals();
    return $result;
}
开发者ID:r007,项目名称:PMoodle,代码行数:21,代码来源:statslib.php

示例11: quiz_delete_userdata

/**
 * Actual implementation of the rest coures functionality, delete all the
 * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
 * set and true.
 *
 * Also, move the quiz open and close dates, if the course start date is changing.
 *
 * @param $data the data submitted from the reset course forum.
 * @param $showfeedback whether to output progress information as the reset
 *      progresses.
 */
function quiz_delete_userdata($data, $showfeedback = true)
{
    global $CFG;
    /// Delete attempts.
    if (!empty($data->reset_quiz_attempts)) {
        $conditiononquizids = 'quiz IN (SELECT id FROM ' . $CFG->prefix . 'quiz q WHERE q.course = ' . $data->courseid . ')';
        $attemptids = get_records_select('quiz_attempts', $conditiononquizids, '', 'id, uniqueid');
        if ($attemptids) {
            if ($showfeedback) {
                echo '<div class="notifysuccess">', get_string('deletingquestionattempts', 'quiz');
                $divider = ': ';
            }
            foreach ($attemptids as $attemptid) {
                delete_attempt($attemptid->uniqueid);
                if ($showfeedback) {
                    echo $divider, $attemptid->uniqueid;
                    $divider = ', ';
                }
            }
            if ($showfeedback) {
                echo "</div><br />\n";
            }
        }
        if (delete_records_select('quiz_grades', $conditiononquizids) && $showfeedback) {
            notify(get_string('gradesdeleted', 'quiz'), 'notifysuccess');
        }
        if (delete_records_select('quiz_attempts', $conditiononquizids) && $showfeedback) {
            notify(get_string('attemptsdeleted', 'quiz'), 'notifysuccess');
        }
    }
    /// Update open and close dates
    if (!empty($data->reset_start_date)) {
        /// Work out offset.
        $olddate = get_field('course', 'startdate', 'id', $data->courseid);
        $olddate = usergetmidnight($olddate);
        // time part of $olddate should be zero
        $newdate = make_timestamp($data->startyear, $data->startmonth, $data->startday);
        $interval = $newdate - $olddate;
        /// Apply it to quizzes with an open or close date.
        $success = true;
        begin_sql();
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz\n                    SET timeopen = timeopen + {$interval}\n                    WHERE course = {$data->courseid} AND timeopen <> 0", false);
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz\n                    SET timeclose = timeclose + {$interval}\n                    WHERE course = {$data->courseid} AND timeclose <> 0", false);
        if ($success) {
            commit_sql();
            if ($showfeedback) {
                notify(get_string('openclosedatesupdated', 'quiz'), 'notifysuccess');
            }
        } else {
            rollback_sql();
        }
    }
}
开发者ID:BackupTheBerlios,项目名称:samouk-svn,代码行数:64,代码来源:lib.php

示例12: sync_users


//.........这里部分代码省略.........
     }
     print "Staring LDAP URL SSO Cron Sync - " . date(DATE_RFC822) . "\n";
     execute_sql_arr($droptablesql, true, false);
     /// Drop temp table to avoid persistence problems later
     echo "Creating temp table {$temptable}\n";
     if (!execute_sql($createtemptablesql, false)) {
         print "Failed to create temporary users table - aborting\n";
         exit;
     }
     print "Connecting to ldap...\n";
     $ldapconnection = $this->ldap_connect();
     if (!$ldapconnection) {
         @ldap_close($ldapconnection);
         print get_string('auth_ldap_noconnect', 'auth', $this->config->host_url);
         exit;
     }
     ////
     //// get user's list from ldap to sql in a scalable fashion
     ////
     // prepare some data we'll need
     $filter = '(&(' . $this->config->user_attribute . '=*) (' . $this->config->objectclass . '))';
     echo "filter: " . $filter . "\n";
     $contexts = explode(";", $this->config->contexts);
     if (!empty($this->config->create_context)) {
         array_push($contexts, $this->config->create_context);
     }
     $fresult = array();
     foreach ($contexts as $context) {
         $context = trim($context);
         if (empty($context)) {
             continue;
         }
         echo "Searching Context: " . $context . "\n";
         begin_sql();
         if ($this->config->search_sub) {
             //use ldap_search to find first user from subtree
             $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute));
         } else {
             //search only in this context
             $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute));
         }
         if ($entry = ldap_first_entry($ldapconnection, $ldap_result)) {
             do {
                 $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
                 $value = $textlib->convert($value[0], $this->config->ldapencoding, 'utf-8');
                 // usernames are __always__ lowercase.
                 if (strpos($value[0], '$') && $this->config->user_type == 'ad') {
                     // Eliminiate AD Service Accounts
                     continue;
                 }
                 // Skip AD Service Account Entries
                 array_push($fresult, moodle_strtolower($value));
                 if (count($fresult) >= $bulk_insert_records) {
                     $this->ldap_bulk_insert($fresult, $temptable);
                     $fresult = array();
                 }
             } while ($entry = ldap_next_entry($ldapconnection, $entry));
         }
         unset($ldap_result);
         // free mem
         // insert any remaining users and release mem
         if (count($fresult)) {
             $this->ldap_bulk_insert($fresult, $temptable);
             $fresult = array();
         }
         commit_sql();
开发者ID:kai707,项目名称:ITSA-backup,代码行数:67,代码来源:auth.php

示例13: dialogue_delete_conversation

function dialogue_delete_conversation($dialogueid, $conversationid)
{
    //echo "<div style=\"text-align:center;\">deleting dialogue $dialogueid and conversation $conversationid</div>";
    begin_sql();
    //$tx = true; // transaction sanity
    $tx = delete_records("dialogue_conversations", "id", $conversationid, "dialogueid", $dialogueid);
    $tx = $tx && delete_records("dialogue_entries", "conversationid", $conversationid, "dialogueid", $dialogueid);
    if ($tx) {
        commit_sql();
    } else {
        rollback_sql();
        error("oups...error deleting conversation");
        return false;
    }
    return true;
}
开发者ID:hmatulis,项目名称:RTL-BIDI-Hebrew-Moodle-Plugins,代码行数:16,代码来源:lib.php

示例14: register_scannedjob

/**
 * Process Job's results logged in a text file.
 * 
 * @param array $scan from table blended_scans
 */
function register_scannedjob($scan)
{
    global $CFG;
    global $scansfoldername;
    $jobid = $scan->id;
    $fieldspath = blended_getOMRFieldsetDir($scan);
    $logfile = blended_getOMRInputLogFilePath($scan);
    try {
        if ($logfile != 'null') {
            $logelements = read_log_file($logfile);
        }
        if (!isset($logelements) || count($logelements) == 0) {
            throw new OMRError("Log file is empty", OMRError::LOG_FILE_IS_EMPTY);
        }
    } catch (OMRError $e) {
        throw $e;
    }
    // open a transaction
    begin_sql();
    foreach ($logelements as $logelement) {
        try {
            //cada elemento es un registro de blended_images.
            $image_result = parse_log_elements($logelement);
            $image_result->jobid = $jobid;
            register_image($image_result);
            $acode = $image_result->activitycode;
            if ($acode != null) {
                if ($acode == 'Undetected') {
                    mtrace("Undetected activity code for result:" . $logelement);
                } else {
                    mtrace('<br>REGISTERING FIELDS...');
                    register_template_fields($image_result, $fieldspath);
                    mtrace('<br>REGISTERING RESULTS...');
                    register_result_files($image_result, $fieldspath);
                    mtrace('<br>CHECKING VALIDITY...');
                    check_invalid_results($image_result);
                }
            }
        } catch (Exception $e) {
            mtrace('OMRError: ' . $e->getMessage());
            register_exception($e, $jobid);
            $errorcode = $e->getCode();
            if ($errorcode == 5 or $errorcode == 6) {
                //print_object($e);
                //throw $e;
                continue;
                // process next result
            }
        }
    }
    mtrace('<br>UPDATING SCANJOB QUEUE...');
    update_record('blended_scans', $scan);
    // End the transaction
    commit_sql();
    return;
}
开发者ID:juacas,项目名称:moodle-mod_blended,代码行数:61,代码来源:processinglib.php

示例15: quiz_upgrade


//.........这里部分代码省略.........
    if ($success && $oldversion < 2005012700) {
        $success = $success && table_column('quiz_grades', 'grade', 'grade', 'real', 2, '');
    }
    if ($success && $oldversion < 2005021400) {
        $success = $success && table_column("quiz", "", "decimalpoints", "integer", "4", "", "2", "not null", "grademethod");
    }
    if ($success && $oldversion < 2005022800) {
        $success = $success && table_column('quiz_questions', '', 'hidden', 'integer', '1', 'unsigned', '0', 'not null', 'version');
        $success = $success && table_column('quiz_responses', '', 'originalquestion', 'integer', '10', 'unsigned', '0', 'not null', 'question');
        $success = $success && modify_database('', "CREATE TABLE prefix_quiz_question_version (\n                              id SERIAL PRIMARY KEY,\n                              quiz integer NOT NULL default '0',\n                              oldquestion integer NOT NULL default '0',\n                              newquestion integer NOT NULL default '0',\n                              userid integer NOT NULL default '0',\n                              timestamp integer NOT NULL default '0');");
    }
    if ($success && $oldversion < 2005032000) {
        $success = $success && execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('quiz', 'editquestions', 'quiz', 'name') ");
    }
    if ($success && $oldversion < 2005032300) {
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_question_version RENAME TO prefix_quiz_question_versions;');
    }
    if ($success && $oldversion < 2005041200) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        $sql = "select course from {$CFG->prefix}quiz_categories, {$CFG->prefix}quiz_questions ";
        $sql .= "where {$CFG->prefix}quiz_category.id = {$CFG->prefix}quiz_questions.category ";
        $sql .= "and {$CFG->prefix}quiz_questions.id = ";
        $wtm->update('quiz_questions', 'questiontext', 'questiontextformat', $sql);
    }
    if ($success && $oldversion < 2005041300) {
        $success = $success && modify_database('', "UPDATE prefix_quiz_questions SET hidden = '1' WHERE qtype ='" . RANDOM . "';");
    }
    if ($success && $oldversion < 2005042002) {
        $success = $success && table_column('quiz_answers', 'answer', 'answer', 'text', '', '', '', 'not null', '');
    }
    if ($success && $oldversion < 2005042400) {
        begin_sql();
        // Changes to quiz table
        // The bits of the optionflags field will hold various option flags
        $success = $success && table_column('quiz', '', 'optionflags', 'integer', '10', 'unsigned', '0', 'not null', 'timeclose');
        // The penalty scheme
        $success = $success && table_column('quiz', '', 'penaltyscheme', 'integer', '4', 'unsigned', '0', 'not null', 'optionflags');
        // The review options are now all stored in the bits of the review field
        $success = $success && table_column('quiz', 'review', 'review', 'integer', 10, 'unsigned', 0, 'not null', '');
        /// Changes to quiz_attempts table
        // The preview flag marks teacher previews
        $success = $success && table_column('quiz_attempts', '', 'preview', 'tinyint', '2', 'unsigned', '0', 'not null', 'timemodified');
        // The layout is the list of questions with inserted page breaks.
        $success = $success && table_column('quiz_attempts', '', 'layout', 'text', '', '', '', 'not null', 'timemodified');
        // For old quiz attempts we will set this to the repaginated question list from $quiz->questions
        /// The following updates of field values require a loop through all quizzes
        // This is because earlier versions of mysql don't allow joins in UPDATE
        if ($quizzes = get_records('quiz')) {
            // turn reporting off temporarily to avoid one line output per set_field
            $olddebug = $db->debug;
            $db->debug = false;
            foreach ($quizzes as $quiz) {
                // repaginate
                $quiz->questions = $quiz->questionsperpage ? quiz_repaginate($quiz->questions, $quiz->questionsperpage) : $quiz->questions;
                if ($quiz->questionsperpage) {
                    $quiz->questions = quiz_repaginate($quiz->questions, $quiz->questionsperpage);
                    $success = $success && set_field('quiz', 'questions', $quiz->questions, 'id', $quiz->id);
                }
                set_field('quiz_attempts', 'layout', $quiz->questions, 'quiz', $quiz->id);
                // set preview flag
                if ($teachers = get_course_teachers($quiz->course)) {
                    $teacherids = implode(',', array_keys($teachers));
                    $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_attempts SET preview = 1 WHERE userid IN ({$teacherids})");
                }
开发者ID:BackupTheBerlios,项目名称:samouk-svn,代码行数:67,代码来源:postgres7.php


注:本文中的begin_sql函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。