コード例 #1
0
ファイル: tag.php プロジェクト: alanaipe2015/moodle
 /**
  * Export this data so it can be used as the context for a mustache template.
  *
  * @param renderer_base $output
  * @return stdClass
  */
 public function export_for_template(renderer_base $output)
 {
     global $CFG;
     require_once $CFG->libdir . '/externallib.php';
     $r = new stdClass();
     $r->id = (int) $this->record->id;
     $r->rawname = clean_param($this->record->rawname, PARAM_TAG);
     $r->name = clean_param($this->record->name, PARAM_TAG);
     $format = clean_param($this->record->descriptionformat, PARAM_INT);
     list($r->description, $r->descriptionformat) = external_format_text($this->record->description, $format, \context_system::instance()->id, 'core', 'tag', $r->id);
     $r->flag = clean_param($this->record->flag, PARAM_INT);
     if (isset($this->record->official)) {
         $r->official = clean_param($this->record->official, PARAM_INT);
     } else {
         $r->official = $this->record->tagtype === 'official' ? 1 : 0;
     }
     $url = new moodle_url('/tag/index.php', array('id' => $this->record->id));
     $r->viewurl = $url->out(false);
     $manageurl = new moodle_url('/tag/manage.php', array('sesskey' => sesskey(), 'tagid' => $this->record->id));
     $url = new moodle_url($manageurl);
     $url->param('action', 'changetype');
     $url->param('tagtype', $r->official ? 'default' : 'official');
     $r->changetypeurl = $url->out(false);
     $url = new moodle_url($manageurl);
     $url->param('action', $this->record->flag ? 'resetflag' : 'setflag');
     $r->changeflagurl = $url->out(false);
     return $r;
 }
コード例 #2
0
ファイル: lock_config.php プロジェクト: evltuma/moodle
 /**
  * Get an instance of the currently configured locking subclass.
  *
  * @param string $type - Unique namespace for the locks generated by this factory. e.g. core_cron
  * @return \core\lock\lock_factory
  * @throws \coding_exception
  */
 public static function get_lock_factory($type)
 {
     global $CFG, $DB;
     $lockfactory = null;
     if (isset($CFG->lock_factory) && $CFG->lock_factory != 'auto') {
         if (!class_exists($CFG->lock_factory)) {
             // In this case I guess it is not safe to continue. Different cluster nodes could end up using different locking
             // types because of an installation error.
             throw new \coding_exception('Lock factory set in $CFG does not exist: ' . $CFG->lock_factory);
         }
         $lockfactoryclass = $CFG->lock_factory;
         $lockfactory = new $lockfactoryclass($type);
     } else {
         $dbtype = clean_param($DB->get_dbfamily(), PARAM_ALPHA);
         // DB Specific lock factory is preferred - should support auto-release.
         $lockfactoryclass = "\\core\\lock\\{$dbtype}_lock_factory";
         if (!class_exists($lockfactoryclass)) {
             $lockfactoryclass = '\\core\\lock\\file_lock_factory';
         }
         /* @var lock_factory $lockfactory */
         $lockfactory = new $lockfactoryclass($type);
         if (!$lockfactory->is_available()) {
             // Final fallback - DB row locking.
             $lockfactory = new \core\lock\db_record_lock_factory($type);
         }
     }
     return $lockfactory;
 }
コード例 #3
0
 /**
  * fix_js_StartUp
  *
  * @param xxx $str (passed by reference)
  * @param xxx $start
  * @param xxx $length
  * @return xxx
  */
 function fix_js_StartUp(&$str, $start, $length)
 {
     global $CFG;
     $substr = substr($str, $start, $length);
     $append = '';
     if ($pos = strrpos($substr, '}')) {
         if ($this->use_DropDownList()) {
             $gaptype = 'select';
         } else {
             $gaptype = 'input';
         }
         $insert = "\n" . "\tvar ClozeBody = null;\n" . "\twindow.CurrentListItem = 0;\n" . "\twindow.ListItems = new Array();\n" . "\tvar div = document.getElementsByTagName('div');\n" . "\tif (div) {\n" . "\t\tvar d_max = div.length;\n" . "\t\tfor (var d=0; d<d_max; d++) {\n" . "\t\t\tif (div[d].className=='ClozeBody') {\n" . "\t\t\t\tListItems = div[d].getElementsByTagName('li');\n" . "\t\t\t\tClozeBody = div[d];\n" . "\t\t\t\tbreak;\n" . "\t\t\t}\n" . "\t\t}\n" . "\t}\n" . "\tdiv = null;\n" . "\tvar i_max = ListItems.length;\n" . "\tvar gapid = new RegExp('^Gap[0-9]+\$');\n" . "\tfor (var i=0; i<i_max; i++) {\n" . "\t\tListItems[i].id = 'Q_' + i;\n" . "\t\tif (i==CurrentListItem) {\n" . "\t\t\tListItems[i].style.display = '';\n" . "\t\t} else {\n" . "\t\t\tListItems[i].style.display = 'none';\n" . "\t\t}\n" . "\t\tListItems[i].gaps = new Array();\n" . "\t\tvar gap = ListItems[i].getElementsByTagName('{$gaptype}');\n" . "\t\tif (gap) {\n" . "\t\t\tvar g_max = gap.length;\n" . "\t\t\tfor (var g=0; g<g_max; g++) {\n" . "\t\t\t\tif (gapid.test(gap[g].id)) {\n" . "\t\t\t\t\tListItems[i].gaps.push(gap[g]);\n" . "\t\t\t\t}\n" . "\t\t\t}\n" . "\t\t\tListItems[i].score = -1;\n" . "\t\t\tListItems[i].AnsweredCorrectly = false;\n" . "\t\t} else {\n" . "\t\t\tListItems[i].score = 0;\n" . "\t\t\tListItems[i].AnsweredCorrectly = true;\n" . "\t\t}\n" . "\t\tgap = null;\n" . "\t}\n" . "\tgapid = null;\n";
         $dots = 'squares';
         // default
         if ($param = clean_param($this->expand_UserDefined1(), PARAM_ALPHANUM)) {
             if (is_dir($CFG->dirroot . "/mod/hotpot/pix/autoadvance/{$param}")) {
                 $dots = $param;
             }
         }
         if ($dots) {
             $insert .= '' . "\tif (ClozeBody) {\n" . "\t\tvar ProgressBar = document.createElement('div');\n" . "\t\tProgressBar.setAttribute('id', 'ProgressBar');\n" . "\t\tProgressBar.setAttribute(AA_className(), 'ProgressBar');\n" . "\n" . "\t\t// add feedback boxes and progess dots for each question\n" . "\t\tfor (var i=0; i<ListItems.length; i++){\n" . "\n" . "\t\t\tif (ProgressBar.childNodes.length) {\n" . "\t\t\t\t// add arrow between progress dots\n" . "\t\t\t\tProgressBar.appendChild(document.createTextNode(' '));\n" . "\t\t\t\tProgressBar.appendChild(AA_ProgressArrow());\n" . "\t\t\t\tProgressBar.appendChild(document.createTextNode(' '));\n" . "\t\t\t}\n" . "\t\t\tProgressBar.appendChild(AA_ProgressDot(i));\n" . "\n" . "\t\t\t// AA_Add_FeedbackBox(i);\n" . "\t\t}\n" . "\t\tClozeBody.parentNode.insertBefore(ProgressBar, ClozeBody);\n" . "\t\tAA_SetProgressBar();\n" . "\t}\n";
             $append = "\n" . "function AA_isNonStandardIE() {\n" . "\tif (typeof(window.isNonStandardIE)=='undefined') {\n" . "\t\tif (navigator.appName=='Microsoft Internet Explorer' && (document.documentMode==null || document.documentMode<8)) {\n" . "\t\t\t// either IE8+ (in compatability mode) or IE7, IE6, IE5 ...\n" . "\t\t\twindow.isNonStandardIE = true;\n" . "\t\t} else {\n" . "\t\t\t// Firefox, Safari, Opera, IE8+\n" . "\t\t\twindow.isNonStandardIE = false;\n" . "\t\t}\n" . "\t}\n" . "\treturn window.isNonStandardIE;\n" . "}\n" . "function AA_className() {\n" . "\tif (AA_isNonStandardIE()){\n" . "\t\treturn 'className';\n" . "\t} else {\n" . "\t\treturn 'class';\n" . "\t}\n" . "}\n" . "function AA_onclickAttribute(fn) {\n" . "\tif (AA_isNonStandardIE()){\n" . "\t\treturn new Function(fn);\n" . "\t} else {\n" . "\t\treturn fn; // just return the string\n" . "\t}\n" . "}\n" . "function AA_images() {\n" . "\treturn 'pix/autoadvance/{$dots}';\n" . "}\n" . "function AA_ProgressArrow() {\n" . "\tvar img = document.createElement('img');\n" . "\tvar src = 'ProgressDotArrow.gif';\n" . "\timg.setAttribute('src', AA_images() + '/' + src);\n" . "\timg.setAttribute('alt', src);\n" . "\timg.setAttribute('title', src);\n" . "\t//img.setAttribute('height', 18);\n" . "\t//img.setAttribute('width', 18);\n" . "\timg.setAttribute(AA_className(), 'ProgressDotArrow');\n" . "\treturn img;\n" . "}\n" . "function AA_ProgressDot(i) {\n" . "\t// i is either an index on ListItems \n" . "\t// or a string to be used as an id for an HTML element\n" . "\tif (typeof(i)=='string') {\n" . "\t\tvar id = i;\n" . "\t\tvar add_link = false;\n" . "\t} else if (ListItems[i]) {\n" . "\t\tvar id = ListItems[i].id;\n" . "\t\tvar add_link = true;\n" . "\t} else {\n" . "\t\treturn false;\n" . "\t}\n" . "\t// id should now be: 'Q_' + q ...\n" . "\t// where q is an index on the State array\n" . "\tvar src = 'ProgressDotEmpty.gif';\n" . "\tvar img = document.createElement('img');\n" . "\timg.setAttribute('id', id + '_ProgressDotImg');\n" . "\timg.setAttribute('src', AA_images() + '/' + src);\n" . "\timg.setAttribute('alt', src);\n" . "\timg.setAttribute('title', src);\n" . "\t//img.setAttribute('height', 18);\n" . "\t//img.setAttribute('width', 18);\n" . "\timg.setAttribute(AA_className(), 'ProgressDotEmpty');\n" . "\tif (add_link) {\n" . "\t\tvar link = document.createElement('a');\n" . "\t\tlink.setAttribute('id', id + '_ProgressDotLink');\n" . "\t\tlink.setAttribute(AA_className(), 'ProgressDotLink');\n" . "\t\tlink.setAttribute('title', 'go to question '+(i+1));\n" . "\t\tvar fn = 'AA_ChangeListItem('+i+');return false;';\n" . "\t\tlink.setAttribute('onclick', AA_onclickAttribute(fn));\n" . "\t\tlink.appendChild(img);\n" . "\t}\n" . "\tvar span = document.createElement('span');\n" . "\tspan.setAttribute('id', id + '_ProgressDot');\n" . "\tspan.setAttribute(AA_className(), 'ProgressDot');\n" . "\tif (add_link) {\n" . "\t\tspan.appendChild(link);\n" . "\t} else {\n" . "\t\tspan.appendChild(img);\n" . "\t}\n" . "\treturn span;\n" . "}\n" . "function AA_SetProgressDot(i, next_i) {\n" . "\tvar img = document.getElementById('Q_'+i+'_ProgressDotImg');\n" . "\tif (! img) {\n" . "\t\treturn;\n" . "\t}\n" . "\tvar src = '';\n" . "\tif (ListItems[i].score >= 0) {\n" . "\t\tvar score = Math.max(0, ListItems[i].score);\n" . "\t\tif (score >= 99) {\n" . "\t\t\tsrc = 'ProgressDotCorrect99Plus'+'.gif';\n" . "\t\t} else if (score >= 80) {\n" . "\t\t\tsrc = 'ProgressDotCorrect80Plus'+'.gif';\n" . "\t\t} else if (score >= 60) {\n" . "\t\t\tsrc = 'ProgressDotCorrect60Plus'+'.gif';\n" . "\t\t} else if (score >= 40) {\n" . "\t\t\tsrc = 'ProgressDotCorrect40Plus'+'.gif';\n" . "\t\t} else if (score >= 20) {\n" . "\t\t\tsrc = 'ProgressDotCorrect20Plus'+'.gif';\n" . "\t\t} else if (score >= 0) {\n" . "\t\t\tsrc = 'ProgressDotCorrect00Plus'+'.gif';\n" . "\t\t} else {\n" . "\t\t\t// this question has negative score, which means it has not yet been correctly answered\n" . "\t\t\tsrc = 'ProgressDotWrong'+'.gif';\n" . "\t\t}\n" . "\t} else {\n" . "\t\t// this question has not been completed\n" . "\t\tif (typeof(next_i)=='number' && i==next_i) {\n" . "\t\t\t// this question will be attempted next\n" . "\t\t\tsrc = 'ProgressDotCurrent'+'.gif';\n" . "\t\t} else {\n" . "\t\t\tsrc = 'ProgressDotEmpty'+'.gif';\n" . "\t\t}\n" . "\t}\n" . "\tvar full_src = AA_images() + '/' + src;\n" . "\tif (img.src != full_src) {\n" . "\t\timg.setAttribute('src', full_src);\n" . "\t}\n" . "}\n" . "function AA_ChangeListItem(i) {\n" . "\tListItems[CurrentListItem].style.display = 'none';\n" . "\tvar obj = ListItems[i].parentNode;\n" . "\twhile (obj) {\n" . "\t\tif (obj.tagName=='OL') {\n" . "\t\t\tobj.start = (i+1);\n" . "\t\t\tobj = null;\n" . "\t\t} else {\n" . "\t\t\t// workaround for IE7\n" . "\t\t\tobj = obj.parentNode;\n" . "\t\t}\n" . "\t}\n" . "\tListItems[i].style.display = '';\n" . "\tAA_SetProgressBar(i);\n" . "\tCurrentListItem = i;\n" . "}\n" . "function AA_SetProgressBar(next_i) {\n" . "\tif (typeof(next_i)=='undefined') {\n" . "\t\tnext_i = CurrentListItem;\n" . "\t}\n" . "\tfor (var i=0; i<ListItems.length; i++) {\n" . "\t\tAA_SetProgressDot(i, next_i);\n" . "\t}\n" . "}\n";
         }
         $insert .= "\tClozeBody = null;\n";
         $substr = substr_replace($substr, $insert, $pos, 0);
     }
     parent::fix_js_StartUp($substr, 0, strlen($substr));
     $substr .= $append;
     $str = substr_replace($str, $substr, $start, $length);
 }
コード例 #4
0
 public function process_form($data)
 {
     $locks = array();
     // Process the edit_form() section
     if (!empty($data->grade)) {
         foreach ($data->grade as $itemid => $info) {
             if (!isset($info['delete'])) {
                 if ($item = $this->get_grade_item($itemid)) {
                     $grades = explode(':', $info['grade']);
                     foreach ($grades as $key => $grade) {
                         $grade = clean_param($grade, PARAM_NUMBER);
                         if ($grade < 0) {
                             $grade = 0;
                         } else {
                             if ($grade > $item->grademax) {
                                 $grade = clean_param($item->grademax, PARAM_NUMBER);
                             }
                         }
                         $grades[$key] = $grade;
                     }
                     if (count($grades) == 2 and $grades[0] >= $grades[1]) {
                         $grades = array($grades[1]);
                     }
                     $grade = implode(':', $grades);
                     $locks[] = array('type' => 'grade', 'id' => $item->id, 'grade' => $grade);
                 }
             }
         }
     }
     // Process the add_form() section
     if (!empty($data->addgradeditem)) {
         $locks[] = array('type' => 'grade', 'id' => $data->addgradeditem, 'grade' => 0);
     }
     return $locks;
 }
コード例 #5
0
 /**
  * Performs custom validation for us.
  *
  * @param array $data An array of data sent to the form.
  * @param array $files An array of files sent to the form.
  * @return array An array of errors.
  */
 protected function configuration_validation($data, $files)
 {
     $errors = array();
     if (!array_key_exists('prefix', $data)) {
         $prefix = '';
     } else {
         $prefix = clean_param($data['prefix'], PARAM_ALPHANUM);
     }
     $factory = cache_factory::instance();
     $config = $factory->create_config_instance();
     foreach ($config->get_all_stores() as $store) {
         if ($store['plugin'] !== 'xcache') {
             continue;
         }
         if (empty($store['configuration']['prefix'])) {
             $storeprefix = '';
         } else {
             $storeprefix = $store['configuration']['prefix'];
         }
         if ($storeprefix === $prefix) {
             $errors['prefix'] = get_string('erroruniqueprefix');
         }
     }
     return $errors;
 }
コード例 #6
0
    /**
     * Processes the message (sends by email).
     * @param object $eventdata the event data submitted by the message sender plus $eventdata->savedmessageid
     */
    function send_message($eventdata) {
        global $CFG;

        if (!empty($CFG->noemailever)) {
            // hidden setting for development sites, set in config.php if needed
            debugging('$CFG->noemailever active, no email message sent.', DEBUG_MINIMAL);
            return true;
        }

        // skip any messaging suspended and deleted users
        if ($eventdata->userto->auth === 'nologin' or $eventdata->userto->suspended or $eventdata->userto->deleted) {
            return true;
        }

        //the user the email is going to
        $recipient = null;

        //check if the recipient has a different email address specified in their messaging preferences Vs their user profile
        $emailmessagingpreference = get_user_preferences('message_processor_email_email', null, $eventdata->userto);
        $emailmessagingpreference = clean_param($emailmessagingpreference, PARAM_EMAIL);

        // If the recipient has set an email address in their preferences use that instead of the one in their profile
        // but only if overriding the notification email address is allowed
        if (!empty($emailmessagingpreference) && !empty($CFG->messagingallowemailoverride)) {
            //clone to avoid altering the actual user object
            $recipient = clone($eventdata->userto);
            $recipient->email = $emailmessagingpreference;
        } else {
            $recipient = $eventdata->userto;
        }
        $result = email_to_user($recipient, $eventdata->userfrom, $eventdata->subject, $eventdata->fullmessage, $eventdata->fullmessagehtml);

        return $result;
    }
コード例 #7
0
 function execute($finalelements, $data)
 {
     $filter_fuserfield = optional_param('filter_fuserfield_' . $data->field, 0, PARAM_RAW);
     if ($filter_fuserfield) {
         // addslashes is done in clean param
         $filter = clean_param(base64_decode($filter_fuserfield), PARAM_CLEAN);
         if (strpos($data->field, 'profile_') === 0) {
             if ($fieldid = get_field('user_info_field', 'id', 'shortname', str_replace('profile_', '', $data->field))) {
                 $sql = "fieldid = {$fieldid} AND data = '{$filter}' AND userid IN(" . implode(',', $finalelements) . ")";
                 if ($infodata = get_records_select('user_info_data', $sql)) {
                     $finalusersid = array();
                     foreach ($infodata as $d) {
                         $finalusersid[] = $d->userid;
                     }
                     return $finalusersid;
                 }
             }
         } else {
             $sql = "{$data->field} = '{$filter}' AND id IN(" . implode(',', $finalelements) . ")";
             if ($elements = get_records_select('user', $sql)) {
                 $finalelements = array_keys($elements);
             }
         }
     }
     return $finalelements;
 }
コード例 #8
0
ファイル: tag.php プロジェクト: rushi963/moodle
 /**
  * Export this data so it can be used as the context for a mustache template.
  *
  * @param renderer_base $output
  * @return stdClass
  */
 public function export_for_template(renderer_base $output)
 {
     global $CFG;
     require_once $CFG->libdir . '/externallib.php';
     $r = new stdClass();
     $r->id = (int) $this->record->id;
     $r->tagcollid = clean_param($this->record->tagcollid, PARAM_INT);
     $r->rawname = clean_param($this->record->rawname, PARAM_TAG);
     $r->name = clean_param($this->record->name, PARAM_TAG);
     $format = clean_param($this->record->descriptionformat, PARAM_INT);
     list($r->description, $r->descriptionformat) = external_format_text($this->record->description, $format, \context_system::instance()->id, 'core', 'tag', $r->id);
     $r->flag = clean_param($this->record->flag, PARAM_INT);
     if (isset($this->record->isstandard)) {
         $r->isstandard = clean_param($this->record->isstandard, PARAM_INT) ? 1 : 0;
     }
     $r->official = $r->isstandard;
     // For backwards compatibility.
     $url = core_tag_tag::make_url($r->tagcollid, $r->rawname);
     $r->viewurl = $url->out(false);
     $manageurl = new moodle_url('/tag/manage.php', array('sesskey' => sesskey(), 'tagid' => $this->record->id));
     $url = new moodle_url($manageurl);
     $url->param('action', 'changetype');
     $url->param('isstandard', $r->isstandard ? 0 : 1);
     $r->changetypeurl = $url->out(false);
     $url = new moodle_url($manageurl);
     $url->param('action', $this->record->flag ? 'resetflag' : 'setflag');
     $r->changeflagurl = $url->out(false);
     return $r;
 }
コード例 #9
0
function block_exabis_eportfolio_print_extern_item($item, $access)
{
    global $CFG;
    print_heading(format_string($item->name));
    $box_content = '';
    if ($item->type == 'link') {
        $link = clean_param($item->url, PARAM_URL);
        $link_js = str_replace('http://', '', $link);
        if ($link) {
            $box_content .= '<p><a href="#" onclick="window.open(\'http://' . addslashes_js($link_js) . '\',\'validate\',\'width=620,height=450,scrollbars=yes,status=yes,resizable=yes,menubar=yes,location=yes\');return true;">' . $link . '</a></p>';
        }
    } elseif ($item->type == 'file') {
        if ($item->attachment) {
            $type = mimeinfo("type", $item->attachment);
            $ffurl = "{$CFG->wwwroot}/blocks/exabis_eportfolio/portfoliofile.php?access=" . $access . "&itemid=" . $item->id;
            if (in_array($type, array('image/gif', 'image/jpeg', 'image/png'))) {
                // Image attachments don't get printed as links
                $box_content .= "<img width=\"100%\" src=\"{$ffurl}\" alt=\"" . format_string($item->name) . "\" /><br/>";
            } else {
                $box_content .= "<p>" . link_to_popup_window("{$ffurl}", 'popup', "{$ffurl}", $height = 400, $width = 500, format_string($item->name), 'none', true) . "</p>";
            }
        }
    }
    $box_content .= format_text($item->intro, FORMAT_HTML);
    print_box($box_content);
}
コード例 #10
0
ファイル: behat_mod_quiz.php プロジェクト: adonm/learning
 /**
  * Put the specified questions on the specified pages of a given quiz.
  *
  * Give the question name in the first column, and that page number in the
  * second column. You may optionally give the desired maximum mark for each
  * question in a third column.
  *
  * @param string $quizname the name of the quiz to add questions to.
  * @param TableNode $data information about the questions to add.
  *
  * @Given /^quiz "([^"]*)" contains the following questions:$/
  */
 public function quiz_contains_the_following_questions($quizname, TableNode $data)
 {
     global $DB;
     $quiz = $DB->get_record('quiz', array('name' => $quizname), '*', MUST_EXIST);
     // The action depends on the field type.
     foreach ($data->getRows() as $questiondata) {
         if (count($questiondata) < 2 || count($questiondata) > 3) {
             throw new ExpectationException('When adding questions to a quiz, you should give 2 or three 3 things: ' . ' the question name, the page number, and optionally a the maxiumum mark. ' . count($questiondata) . ' values passed.', $this->getSession());
         }
         list($questionname, $rawpage) = $questiondata;
         if (!isset($questiondata[2]) || $questiondata[2] === '') {
             $maxmark = null;
         } else {
             $maxmark = clean_param($questiondata[2], PARAM_FLOAT);
             if (!is_numeric($questiondata[2]) || $maxmark < 0) {
                 throw new ExpectationException('When adding questions to a quiz, the max mark must be a positive number.', $this->getSession());
             }
         }
         $page = clean_param($rawpage, PARAM_INT);
         if ($page <= 0 || (string) $page !== $rawpage) {
             throw new ExpectationException('When adding questions to a quiz, the page number must be a positive integer.', $this->getSession());
         }
         $questionid = $DB->get_field('question', 'id', array('name' => $questionname), MUST_EXIST);
         quiz_add_quiz_question($questionid, $quiz, $page, $maxmark);
     }
     quiz_update_sumgrades($quiz);
 }
コード例 #11
0
ファイル: url.php プロジェクト: parksandwildlife/learning
 /**
  *
  */
 protected function format_content($entry, array $values = null)
 {
     $fieldid = $this->id;
     $oldcontents = array();
     $contents = array();
     // Old contents.
     if (isset($entry->{"c{$fieldid}_content"})) {
         $oldcontents[] = isset($entry->{"c{$fieldid}" . '_content'}) ? $entry->{"c{$fieldid}" . '_content'} : null;
         $oldcontents[] = isset($entry->{"c{$fieldid}" . '_content1'}) ? $entry->{"c{$fieldid}" . '_content1'} : null;
     }
     // New contents.
     $url = $alttext = null;
     if (!empty($values)) {
         foreach ($values as $name => $value) {
             switch ($name) {
                 case '':
                     if ($value and $value != 'http://') {
                         $url = clean_param($value, PARAM_URL);
                     }
                     break;
                 case 'alt':
                     $alttext = clean_param($value, PARAM_NOTAGS);
                     break;
             }
         }
     }
     if (!is_null($url)) {
         $contents[] = $url;
         $contents[] = $alttext;
     }
     return array($contents, $oldcontents);
 }
コード例 #12
0
 private function execute_users($finalelements, $data)
 {
     global $remotedb, $CFG;
     $filter_fuserfield = optional_param('filter_fuserfield_' . $data->field, 0, PARAM_RAW);
     if ($filter_fuserfield) {
         // addslashes is done in clean param
         $filter = clean_param(base64_decode($filter_fuserfield), PARAM_CLEAN);
         if (strpos($data->field, 'profile_') === 0) {
             if ($fieldid = $remotedb->get_field('user_info_field', 'id', array('shortname' => str_replace('profile_', '', $data->field)))) {
                 list($usql, $params) = $remotedb->get_in_or_equal($finalelements);
                 $sql = "fieldid = ? AND data LIKE ? AND userid {$usql}";
                 $params = array_merge(array($fieldid, "%{$filter}%"), $params);
                 if ($infodata = $remotedb->get_records_select('user_info_data', $sql, $params)) {
                     $finalusersid = array();
                     foreach ($infodata as $d) {
                         $finalusersid[] = $d->userid;
                     }
                     return $finalusersid;
                 }
             }
         } else {
             list($usql, $params) = $remotedb->get_in_or_equal($finalelements);
             $sql = "{$data->field} LIKE ? AND id {$usql}";
             $params = array_merge(array("%{$filter}%"), $params);
             if ($elements = $remotedb->get_records_select('user', $sql, $params)) {
                 $finalelements = array_keys($elements);
             }
         }
     }
     return $finalelements;
 }
コード例 #13
0
 function refresh_key()
 {
     global $CFG;
     // set up an RPC request
     require_once $CFG->dirroot . '/mnet/xmlrpc/client.php';
     $mnetrequest = new mnet_xmlrpc_client();
     // Use any method - listServices is pretty lightweight.
     $mnetrequest->set_method('system/listServices');
     // Do RPC call and store response
     if ($mnetrequest->send($this) === true) {
         // Ok - we actually don't care about the result
         $temp = new mnet_peer();
         $temp->set_id($this->id);
         if ($this->public_key != $temp->public_key) {
             $newkey = clean_param($temp->public_key, PARAM_PEM);
             if (!empty($newkey)) {
                 $this->public_key = $newkey;
                 $this->updateparams->public_key = $newkey;
                 $this->commit();
                 return true;
             }
         }
     }
     return false;
 }
コード例 #14
0
ファイル: lib.php プロジェクト: nmicha/moodle
 /**
  * Get file listing
  *
  * @param string $encodedpath
  * @return mixed
  */
 public function get_listing($encodedpath = '', $page = '')
 {
     global $CFG, $USER, $OUTPUT;
     $ret = array();
     $ret['dynload'] = true;
     $ret['nosearch'] = true;
     $ret['nologin'] = true;
     $list = array();
     if (!empty($encodedpath)) {
         $params = unserialize(base64_decode($encodedpath));
         if (is_array($params)) {
             $component = is_null($params['component']) ? NULL : clean_param($params['component'], PARAM_COMPONENT);
             $filearea = is_null($params['filearea']) ? NULL : clean_param($params['filearea'], PARAM_AREA);
             $itemid = is_null($params['itemid']) ? NULL : clean_param($params['itemid'], PARAM_INT);
             $filepath = is_null($params['filepath']) ? NULL : clean_param($params['filepath'], PARAM_PATH);
             $filename = is_null($params['filename']) ? NULL : clean_param($params['filename'], PARAM_FILE);
             $context = get_context_instance_by_id(clean_param($params['contextid'], PARAM_INT));
         }
     } else {
         $itemid = null;
         $filename = null;
         $filearea = null;
         $filepath = null;
         $component = null;
         if (!empty($this->context)) {
             list($context, $course, $cm) = get_context_info_array($this->context->id);
             if (is_object($course)) {
                 $context = get_context_instance(CONTEXT_COURSE, $course->id);
             } else {
                 $context = get_system_context();
             }
         } else {
             $context = get_system_context();
         }
     }
     $browser = get_file_browser();
     $list = array();
     if ($fileinfo = $browser->get_file_info($context, $component, $filearea, $itemid, $filepath, $filename)) {
         // build file tree
         $element = repository_local_file::retrieve_file_info($fileinfo, $this);
         $nonemptychildren = $element->get_non_empty_children();
         foreach ($nonemptychildren as $child) {
             $list[] = (array) $child->get_node();
         }
     } else {
         // if file doesn't exist, build path nodes root of current context
         $fileinfo = $browser->get_file_info($context, null, null, null, null, null);
     }
     // build path navigation
     $ret['path'] = array();
     $element = repository_local_file::retrieve_file_info($fileinfo, $this);
     for ($level = $element; $level; $level = $level->get_parent()) {
         if ($level == $element || !$level->can_skip()) {
             array_unshift($ret['path'], $level->get_node_path());
         }
     }
     $ret['list'] = array_filter($list, array($this, 'filter'));
     return $ret;
 }
コード例 #15
0
ファイル: upgradelib.php プロジェクト: richheath/moodle
/**
 * Migrates physical scorm package files to proper new file area files
 * @param stdClass $context
 * @param string $base
 * @param string $path
 * @return void
 */
function scorm_migrate_moddata_subdir($context, $base, $path)
{
    global $OUTPUT;
    $fullpathname = $base . $path;
    $fs = get_file_storage();
    $filearea = 'content';
    $items = new DirectoryIterator($fullpathname);
    foreach ($items as $item) {
        if ($item->isDot()) {
            unset($item);
            // release file handle
            continue;
        }
        if ($item->isLink()) {
            // do not follow symlinks - they were never supported in moddata, sorry
            unset($item);
            // release file handle
            continue;
        }
        if ($item->isFile()) {
            if (!$item->isReadable()) {
                echo $OUTPUT->notification(" File not readable, skipping: " . $fullpathname . $item->getFilename());
                unset($item);
                // release file handle
                continue;
            }
            $filepath = clean_param($path, PARAM_PATH);
            $filename = clean_param($item->getFilename(), PARAM_FILE);
            $oldpathname = $fullpathname . $item->getFilename();
            if ($filename === '') {
                continue;
                unset($item);
                // release file handle
            }
            if (!$fs->file_exists($context->id, 'mod_scorm', $filearea, '0', $filepath, $filename)) {
                $file_record = array('contextid' => $context->id, 'component' => 'mod_scorm', 'filearea' => $filearea, 'itemid' => 0, 'filepath' => $filepath, 'filename' => $filename, 'timecreated' => $item->getCTime(), 'timemodified' => $item->getMTime());
                unset($item);
                // release file handle
                if ($fs->create_file_from_pathname($file_record, $oldpathname)) {
                    @unlink($oldpathname);
                }
            } else {
                unset($item);
                // release file handle
            }
        } else {
            //migrate recursively all subdirectories
            $oldpathname = $fullpathname . $item->getFilename() . '/';
            $subpath = $path . $item->getFilename() . '/';
            unset($item);
            // release file handle
            scorm_migrate_moddata_subdir($context, $base, $subpath);
            @rmdir($oldpathname);
            // deletes dir if empty
        }
    }
    unset($items);
    //release file handles
}
コード例 #16
0
ファイル: tagisstandard.php プロジェクト: evltuma/moodle
 /**
  * Updates the value in database and returns itself, called from inplace_editable callback
  *
  * @param int $itemid
  * @param mixed $newvalue
  * @return \self
  */
 public static function update($itemid, $newvalue)
 {
     require_capability('moodle/tag:manage', context_system::instance());
     $tag = core_tag_tag::get($itemid, '*', MUST_EXIST);
     $newvalue = (int) clean_param($newvalue, PARAM_BOOL);
     $tag->update(array('isstandard' => $newvalue));
     return new self($tag);
 }
コード例 #17
0
ファイル: lib.php プロジェクト: kai707/ITSA-backup
/**
 * Given an object containing all the necessary data, 
 * (defined by the form in mod.html) this function 
 * will update an existing instance with new data.
 *
 * @param object $instance An object from the form in mod.html
 * @return boolean Success/Fail
 **/
function nanogong_update_instance($nanogong)
{
    $nanogong->timemodified = time();
    $nanogong->id = $nanogong->instance;
    $nanogong->maxmessages = clean_param($nanogong->maxmessages, PARAM_INT);
    $nanogong->maxscore = clean_param($nanogong->maxscore, PARAM_INT);
    return update_record("nanogong", $nanogong);
}
コード例 #18
0
 /**
  * Processes the message (sends by email).
  * @param object $eventdata the event data submitted by the message sender plus $eventdata->savedmessageid
  */
 function send_message($eventdata)
 {
     global $CFG;
     // Ignore $CFG->noemailever here because we want to test this code,
     // the message sending fails later in email_to_user().
     // skip any messaging suspended and deleted users
     if ($eventdata->userto->auth === 'nologin' or $eventdata->userto->suspended or $eventdata->userto->deleted) {
         return true;
     }
     //the user the email is going to
     $recipient = null;
     //check if the recipient has a different email address specified in their messaging preferences Vs their user profile
     $emailmessagingpreference = get_user_preferences('message_processor_email_email', null, $eventdata->userto);
     $emailmessagingpreference = clean_param($emailmessagingpreference, PARAM_EMAIL);
     // If the recipient has set an email address in their preferences use that instead of the one in their profile
     // but only if overriding the notification email address is allowed
     if (!empty($emailmessagingpreference) && !empty($CFG->messagingallowemailoverride)) {
         //clone to avoid altering the actual user object
         $recipient = clone $eventdata->userto;
         $recipient->email = $emailmessagingpreference;
     } else {
         $recipient = $eventdata->userto;
     }
     // Check if we have attachments to send.
     $attachment = '';
     $attachname = '';
     if (!empty($CFG->allowattachments) && !empty($eventdata->attachment)) {
         if (empty($eventdata->attachname)) {
             // Attachment needs a file name.
             debugging('Attachments should have a file name. No attachments have been sent.', DEBUG_DEVELOPER);
         } else {
             if (!$eventdata->attachment instanceof stored_file) {
                 // Attachment should be of a type stored_file.
                 debugging('Attachments should be of type stored_file. No attachments have been sent.', DEBUG_DEVELOPER);
             } else {
                 // Copy attachment file to a temporary directory and get the file path.
                 $attachment = $eventdata->attachment->copy_content_to_temp();
                 // Get attachment file name.
                 $attachname = clean_filename($eventdata->attachname);
             }
         }
     }
     // Configure mail replies - this is used for incoming mail replies.
     $replyto = '';
     $replytoname = '';
     if (isset($eventdata->replyto)) {
         $replyto = $eventdata->replyto;
         if (isset($eventdata->replytoname)) {
             $replytoname = $eventdata->replytoname;
         }
     }
     $result = email_to_user($recipient, $eventdata->userfrom, $eventdata->subject, $eventdata->fullmessage, $eventdata->fullmessagehtml, $attachment, $attachname, true, $replyto, $replytoname);
     // Remove an attachment file if any.
     if (!empty($attachment) && file_exists($attachment)) {
         unlink($attachment);
     }
     return $result;
 }
コード例 #19
0
 /**
  * Get file listing
  *
  * @param string $encodedpath
  * @return mixed
  */
 public function get_listing($encodedpath = '')
 {
     global $CFG, $USER, $OUTPUT;
     $ret = array();
     $ret['dynload'] = true;
     $ret['nosearch'] = true;
     $ret['nologin'] = true;
     $list = array();
     if (!empty($encodedpath)) {
         $params = unserialize(base64_decode($encodedpath));
         if (is_array($params)) {
             $filepath = clean_param($params['filepath'], PARAM_PATH);
             $filename = clean_param($params['filename'], PARAM_FILE);
         }
     } else {
         $itemid = 0;
         $filepath = '/';
         $filename = null;
     }
     $filearea = 'private';
     $component = 'user';
     $itemid = 0;
     $context = get_context_instance(CONTEXT_USER, $USER->id);
     try {
         $browser = get_file_browser();
         if ($fileinfo = $browser->get_file_info($context, $component, $filearea, $itemid, $filepath, $filename)) {
             $pathnodes = array();
             $level = $fileinfo;
             $params = $fileinfo->get_params();
             while ($level && $params['component'] == 'user' && $params['filearea'] == 'private') {
                 $encodedpath = base64_encode(serialize($level->get_params()));
                 $pathnodes[] = array('name' => $level->get_visible_name(), 'path' => $encodedpath);
                 $level = $level->get_parent();
                 $params = $level->get_params();
             }
             $ret['path'] = array_reverse($pathnodes);
             // build file tree
             $children = $fileinfo->get_children();
             foreach ($children as $child) {
                 if ($child->is_directory()) {
                     $encodedpath = base64_encode(serialize($child->get_params()));
                     $node = array('title' => $child->get_visible_name(), 'size' => 0, 'date' => '', 'path' => $encodedpath, 'children' => array(), 'thumbnail' => $OUTPUT->pix_url('f/folder-32')->out(false));
                     $list[] = $node;
                 } else {
                     $encodedpath = base64_encode(serialize($child->get_params()));
                     $node = array('title' => $child->get_visible_name(), 'size' => 0, 'date' => '', 'source' => $encodedpath, 'thumbnail' => $OUTPUT->pix_url(file_extension_icon($child->get_visible_name(), 32))->out(false));
                     $list[] = $node;
                 }
             }
         }
     } catch (Exception $e) {
         throw new repository_exception('emptyfilelist', 'repository_user');
     }
     $ret['list'] = $list;
     $ret['list'] = array_filter($list, array($this, 'filter'));
     return $ret;
 }
コード例 #20
0
 /**
  * Returns an instance of parser for the given format of data
  *
  * @param string $format format of data like 'php', 'xml', 'csv' etc (alphanumerical only)
  * @return instance of a class implementing {@see mlang_parser} interface
  */
 public static function get_parser($format)
 {
     $format = clean_param($format, PARAM_ALPHANUM);
     $classname = 'mlang_' . $format . '_parser';
     if (class_exists($classname)) {
         return call_user_func("{$classname}::get_instance");
     } else {
         throw new coding_error('No such parser implemented');
     }
 }
コード例 #21
0
ファイル: onedrive.php プロジェクト: eugeneventer/o365-moodle
 /**
  * Validate that a given url is a valid OneDrive for Business SharePoint URL.
  *
  * @param string $resource Uncleaned, unvalidated URL to check.
  * @param \local_o365\oauth2\clientdata $clientdata oAuth2 Credentials
  * @param \local_o365\httpclientinterface $httpclient An HttpClient to use for transport.
  * @return bool Whether the received resource is valid or not.
  */
 public static function validate_resource($resource, \local_o365\oauth2\clientdata $clientdata, \local_o365\httpclientinterface $httpclient)
 {
     $cleanresource = clean_param($resource, PARAM_URL);
     if ($cleanresource !== $resource) {
         return false;
     }
     $fullcleanresource = 'https://' . $cleanresource;
     $token = \local_o365\oauth2\systemtoken::get_for_new_resource(null, $fullcleanresource, $clientdata, $httpclient);
     return !empty($token) ? true : false;
 }
コード例 #22
0
 public function test_create()
 {
     global $DB;
     $this->resetAfterTest(true);
     $generator = $this->getDataGenerator();
     $count = $DB->count_records('user');
     $user = $generator->create_user();
     $this->assertEquals($count + 1, $DB->count_records('user'));
     $this->assertSame($user->username, clean_param($user->username, PARAM_USERNAME));
     $this->assertSame($user->email, clean_param($user->email, PARAM_EMAIL));
     $user = $generator->create_user(array('firstname' => 'Žluťoučký', 'lastname' => 'Koníček'));
     $this->assertSame($user->username, clean_param($user->username, PARAM_USERNAME));
     $this->assertSame($user->email, clean_param($user->email, PARAM_EMAIL));
     $count = $DB->count_records('course_categories');
     $category = $generator->create_category();
     $this->assertEquals($count + 1, $DB->count_records('course_categories'));
     $this->assertRegExp('/^Course category \\d/', $category->name);
     $this->assertSame('', $category->idnumber);
     $this->assertRegExp('/^Test course category \\d/', $category->description);
     $this->assertSame(FORMAT_MOODLE, $category->descriptionformat);
     $count = $DB->count_records('cohort');
     $cohort = $generator->create_cohort();
     $this->assertEquals($count + 1, $DB->count_records('cohort'));
     $this->assertEquals(context_system::instance()->id, $cohort->contextid);
     $this->assertRegExp('/^Cohort \\d/', $cohort->name);
     $this->assertSame('', $cohort->idnumber);
     $this->assertRegExp('/^Test cohort \\d/', $cohort->description);
     $this->assertSame(FORMAT_MOODLE, $cohort->descriptionformat);
     $this->assertSame('', $cohort->component);
     $this->assertLessThanOrEqual(time(), $cohort->timecreated);
     $this->assertSame($cohort->timecreated, $cohort->timemodified);
     $count = $DB->count_records('course');
     $course = $generator->create_course();
     $this->assertEquals($count + 1, $DB->count_records('course'));
     $this->assertRegExp('/^Test course \\d/', $course->fullname);
     $this->assertRegExp('/^tc_\\d/', $course->shortname);
     $this->assertSame('', $course->idnumber);
     $this->assertSame('topics', $course->format);
     $this->assertEquals(0, $course->newsitems);
     $this->assertEquals(5, $course->numsections);
     $this->assertRegExp('/^Test course \\d/', $course->summary);
     $this->assertSame(FORMAT_MOODLE, $course->summaryformat);
     $section = $generator->create_course_section(array('course' => $course->id, 'section' => 3));
     $this->assertEquals($course->id, $section->course);
     $scale = $generator->create_scale();
     $this->assertNotEmpty($scale);
     // Note we only count grade cats with depth > 1 because the course grade category
     // is lazily created.
     $count = $DB->count_records_select('grade_categories', 'depth <> 1');
     $gradecategory = $generator->create_grade_category(array('courseid' => $course->id));
     $this->assertEquals($count + 1, $DB->count_records_select('grade_categories', 'depth <> 1'));
     $this->assertEquals(2, $gradecategory->depth);
     $this->assertEquals($course->id, $gradecategory->courseid);
     $this->assertEquals('Grade category 1', $gradecategory->fullname);
 }
コード例 #23
0
 public function optional_param($name, $default = NULL, $type = PARAM_CLEAN)
 {
     if ($this->params !== false) {
         if (isset($this->params[$name])) {
             return clean_param($this->params[$name], $type);
         } else {
             return $default;
         }
     } else {
         return optional_param($name, $default, $type);
     }
 }
コード例 #24
0
ファイル: player_native.php プロジェクト: lucaboesch/moodle
 /**
  * Extracts a value for an attribute
  *
  * @param string $tag html tag which properties are extracted, for example "<video ...>....</video>"
  * @param string $attrname name of the attribute we are looking for
  * @param string $type one of PARAM_* constants to clean the attribute value
  * @return string|null
  */
 public static function get_attribute($tag, $attrname, $type = PARAM_RAW)
 {
     if (preg_match('/^<[^>]*\\b' . $attrname . '="(.*?)"/is', $tag, $matches)) {
         return clean_param(htmlspecialchars_decode($matches[1]), $type);
     } else {
         if (preg_match('~^<[^>]*\\b' . $attrname . '[ />]"~is', $tag, $matches)) {
             // Some attributes may not have value, for example this is valid: <video controls>.
             return clean_param("true", $type);
         }
     }
     return null;
 }
コード例 #25
0
ファイル: abstract.php プロジェクト: bgao-ca/moodle-local_mr
 /**
  * Constructor
  *
  * @param mr_server_abstract $server The current server model
  * @param string $serviceclass The web service class
  */
 public function __construct($server, $serviceclass)
 {
     $this->server = $server;
     $this->serviceclass = $serviceclass;
     $method = $this->server->get_request()->getParam('method', '');
     $method = clean_param($method, PARAM_ALPHAEXT);
     if (empty($method)) {
         $method = 'unknown';
     }
     $this->servicemethod = $method;
     $this->init();
 }
コード例 #26
0
ファイル: radio.php プロジェクト: alanaipe2015/moodle
 function _generateId()
 {
     // Override the standard implementation, since you can have multiple
     // check-boxes with the same name on a form. Therefore, add the
     // (cleaned up) value to the id.
     if ($this->getAttribute('id')) {
         return;
     }
     parent::_generateId();
     $id = $this->getAttribute('id') . '_' . clean_param($this->getValue(), PARAM_ALPHANUMEXT);
     $this->updateAttributes(array('id' => $id));
 }
コード例 #27
0
ファイル: tagflag.php プロジェクト: evltuma/moodle
 /**
  * Updates the value in database and returns itself, called from inplace_editable callback
  *
  * @param int $itemid
  * @param mixed $newvalue
  * @return \self
  */
 public static function update($itemid, $newvalue)
 {
     require_capability('moodle/tag:manage', context_system::instance());
     $tag = core_tag_tag::get($itemid, '*', MUST_EXIST);
     $newvalue = (int) clean_param($newvalue, PARAM_BOOL);
     if ($newvalue) {
         $tag->flag();
     } else {
         $tag->reset_flag();
     }
     return new self($tag);
 }
コード例 #28
0
 /**
  * Updates the value in database and returns itself, called from inplace_editable callback
  *
  * @param int $itemid
  * @param mixed $newvalue
  * @return \self
  */
 public static function update($itemid, $newvalue)
 {
     global $DB;
     require_capability('moodle/tag:manage', context_system::instance());
     $tagarea = $DB->get_record('tag_area', array('id' => $itemid), '*', MUST_EXIST);
     $newvalue = clean_param($newvalue, PARAM_INT);
     $data = array('showstandard' => $newvalue);
     core_tag_area::update($tagarea, $data);
     $tagarea->showstandard = $newvalue;
     $tmpl = new self($tagarea);
     return $tmpl;
 }
コード例 #29
0
ファイル: lib.php プロジェクト: MoodleMetaData/MoodleMetaData
/**
 * This is method serves up files to the user.  The files used in this course are just images,
 * but they are sent largely the same way.
 *
 */
function block_nurs_navigation_pluginfile($course, $birecord, $context, $filearea, $args, $forcedownload)
{
    require_once 'lib/filelib.php';
    $fs = get_file_storage();
    $entryid = clean_param(array_shift($args), PARAM_INT);
    $file = array_shift($args);
    if (!($file = $fs->get_file($context->id, 'block_nurs_navigation', $filearea, $entryid, '/', $file))) {
        send_file_not_found();
        return;
    }
    send_stored_file($file, 10 * 60, 0, true);
}
コード例 #30
0
 protected function action($message, $level, $options = null)
 {
     $columns = $this->columns;
     if ($this->datecol) {
         $columns[$this->datecol] = time();
     }
     if ($this->levelcol) {
         $columns[$this->levelcol] = $level;
     }
     $columns[$this->messagecol] = clean_param($message, PARAM_NOTAGS);
     return $this->insert_log_record($this->logtable, $columns);
 }