Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]

   1  <?php
   2  ///////////////////////////////////////////////////////////////////////////
   3  //                                                                       //
   4  // NOTICE OF COPYRIGHT                                                   //
   5  //                                                                       //
   6  // Moodle - Modular Object-Oriented Dynamic Learning Environment         //
   7  //          http://moodle.org                                            //
   8  //                                                                       //
   9  // Copyright (C) 1999-onwards Moodle Pty Ltd  http://moodle.com          //
  10  //                                                                       //
  11  // This program is free software; you can redistribute it and/or modify  //
  12  // it under the terms of the GNU General Public License as published by  //
  13  // the Free Software Foundation; either version 2 of the License, or     //
  14  // (at your option) any later version.                                   //
  15  //                                                                       //
  16  // This program is distributed in the hope that it will be useful,       //
  17  // but WITHOUT ANY WARRANTY; without even the implied warranty of        //
  18  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         //
  19  // GNU General Public License for more details:                          //
  20  //                                                                       //
  21  //          http://www.gnu.org/copyleft/gpl.html                         //
  22  //                                                                       //
  23  ///////////////////////////////////////////////////////////////////////////
  24  
  25  class data_field_checkbox extends data_field_base {
  26  
  27      var $type = 'checkbox';
  28      /**
  29       * priority for globalsearch indexing
  30       *
  31       * @var int
  32       */
  33      protected static $priority = self::LOW_PRIORITY;
  34  
  35      public function supports_preview(): bool {
  36          return true;
  37      }
  38  
  39      public function get_data_content_preview(int $recordid): stdClass {
  40          $options = explode("\n", $this->field->param1);
  41          $options = array_map('trim', $options);
  42          $selected = $options[$recordid % count($options)];
  43          return (object)[
  44              'id' => 0,
  45              'fieldid' => $this->field->id,
  46              'recordid' => $recordid,
  47              'content' => $selected,
  48              'content1' => null,
  49              'content2' => null,
  50              'content3' => null,
  51              'content4' => null,
  52          ];
  53      }
  54  
  55      function display_add_field($recordid = 0, $formdata = null) {
  56          global $CFG, $DB, $OUTPUT;
  57  
  58          $content = array();
  59  
  60          if ($formdata) {
  61              $fieldname = 'field_' . $this->field->id;
  62              $content = $formdata->$fieldname;
  63          } else if ($recordid) {
  64              $content = $DB->get_field('data_content', 'content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid));
  65              $content = explode('##', $content);
  66          } else {
  67              $content = array();
  68          }
  69  
  70          $str = '<div title="' . s($this->field->description) . '">';
  71          $str .= '<fieldset><legend><span class="accesshide">'.$this->field->name;
  72          if ($this->field->required) {
  73              $str .= '$nbsp;' . get_string('requiredelement', 'form');
  74              $str .= '</span></legend>';
  75              $image = $OUTPUT->pix_icon('req', get_string('requiredelement', 'form'));
  76              $str .= html_writer::div($image, 'inline-req');
  77          } else {
  78              $str .= '</span></legend>';
  79          }
  80  
  81          $i = 0;
  82          foreach (explode("\n", $this->field->param1) as $checkbox) {
  83              $checkbox = trim($checkbox);
  84              if ($checkbox === '') {
  85                  continue; // skip empty lines
  86              }
  87              $str .= '<input type="hidden" name="field_' . $this->field->id . '[]" value="" />';
  88              $str .= '<input type="checkbox" id="field_'.$this->field->id.'_'.$i.'" name="field_' . $this->field->id . '[]" ';
  89              $str .= 'value="' . s($checkbox) . '" class="mod-data-input mr-1" ';
  90  
  91              if (array_search($checkbox, $content) !== false) {
  92                  $str .= 'checked />';
  93              } else {
  94                  $str .= '/>';
  95              }
  96              $str .= '<label for="field_'.$this->field->id.'_'.$i.'">'.$checkbox.'</label><br />';
  97              $i++;
  98          }
  99          $str .= '</fieldset>';
 100          $str .= '</div>';
 101          return $str;
 102      }
 103  
 104      function display_search_field($value='') {
 105          global $CFG, $DB;
 106  
 107          if (is_array($value)) {
 108              $content = $value['checked'];
 109              $allrequired = $value['allrequired'] ? true : false;
 110          } else {
 111              $content = array();
 112              $allrequired = false;
 113          }
 114  
 115          $str = '';
 116          $found = false;
 117          $marginclass = ['class' => 'mr-1'];
 118          foreach (explode("\n",$this->field->param1) as $checkbox) {
 119              $checkbox = trim($checkbox);
 120              if (in_array($checkbox, $content)) {
 121                  $str .= html_writer::checkbox('f_'.$this->field->id.'[]', s($checkbox), true, $checkbox, $marginclass);
 122              } else {
 123                  $str .= html_writer::checkbox('f_'.$this->field->id.'[]', s($checkbox), false, $checkbox, $marginclass);
 124              }
 125              $str .= html_writer::empty_tag('br');
 126              $found = true;
 127          }
 128          if (!$found) {
 129              return '';
 130          }
 131  
 132          $requiredstr = get_string('selectedrequired', 'data');
 133          $str .= html_writer::checkbox('f_'.$this->field->id.'_allreq', null, $allrequired, $requiredstr, $marginclass);
 134          return $str;
 135      }
 136  
 137      public function parse_search_field($defaults = null) {
 138          $paramselected = 'f_'.$this->field->id;
 139          $paramallrequired = 'f_'.$this->field->id.'_allreq';
 140  
 141          if (empty($defaults[$paramselected])) { // One empty means the other ones are empty too.
 142              $defaults = array($paramselected => array(), $paramallrequired => 0);
 143          }
 144  
 145          $selected    = optional_param_array($paramselected, $defaults[$paramselected], PARAM_NOTAGS);
 146          $allrequired = optional_param($paramallrequired, $defaults[$paramallrequired], PARAM_BOOL);
 147  
 148          if (empty($selected)) {
 149              // no searching
 150              return '';
 151          }
 152          return array('checked'=>$selected, 'allrequired'=>$allrequired);
 153      }
 154  
 155      function generate_sql($tablealias, $value) {
 156          global $DB;
 157  
 158          static $i=0;
 159          $i++;
 160          $name = "df_checkbox_{$i}_";
 161          $params = array();
 162          $varcharcontent = $DB->sql_compare_text("{$tablealias}.content", 255);
 163  
 164          $allrequired = $value['allrequired'];
 165          $selected    = $value['checked'];
 166  
 167          if ($selected) {
 168              $conditions = array();
 169              $j=0;
 170              foreach ($selected as $sel) {
 171                  $j++;
 172                  $xname = $name.$j;
 173                  $likesel = str_replace('%', '\%', $sel);
 174                  $likeselsel = str_replace('_', '\_', $likesel);
 175                  $conditions[] = "({$tablealias}.fieldid = {$this->field->id} AND ({$varcharcontent} = :{$xname}a
 176                                                                                 OR {$tablealias}.content LIKE :{$xname}b
 177                                                                                 OR {$tablealias}.content LIKE :{$xname}c
 178                                                                                 OR {$tablealias}.content LIKE :{$xname}d))";
 179                  $params[$xname.'a'] = $sel;
 180                  $params[$xname.'b'] = "$likesel##%";
 181                  $params[$xname.'c'] = "%##$likesel";
 182                  $params[$xname.'d'] = "%##$likesel##%";
 183              }
 184              if ($allrequired) {
 185                  return array(" (".implode(" AND ", $conditions).") ", $params);
 186              } else {
 187                  return array(" (".implode(" OR ", $conditions).") ", $params);
 188              }
 189          } else {
 190              return array(" ", array());
 191          }
 192      }
 193  
 194      function update_content($recordid, $value, $name='') {
 195          global $DB;
 196  
 197          $content = new stdClass();
 198          $content->fieldid = $this->field->id;
 199          $content->recordid = $recordid;
 200          $content->content = $this->format_data_field_checkbox_content($value);
 201  
 202          if ($oldcontent = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
 203              $content->id = $oldcontent->id;
 204              return $DB->update_record('data_content', $content);
 205          } else {
 206              return $DB->insert_record('data_content', $content);
 207          }
 208      }
 209  
 210      function display_browse_field($recordid, $template) {
 211          $content = $this->get_data_content($recordid);
 212          if (!$content || empty($content->content)) {
 213              return '';
 214          }
 215  
 216          $options = explode("\n", $this->field->param1);
 217          $options = array_map('trim', $options);
 218  
 219          $contentarray = explode('##', $content->content);
 220          $str = '';
 221          foreach ($contentarray as $line) {
 222              if (!in_array($line, $options)) {
 223                  // Hmm, looks like somebody edited the field definition.
 224                  continue;
 225              }
 226              $str .= $line . "<br />\n";
 227          }
 228          return $str;
 229      }
 230  
 231      function format_data_field_checkbox_content($content) {
 232          if (!is_array($content)) {
 233              return NULL;
 234          }
 235          $options = explode("\n", $this->field->param1);
 236          $options = array_map('trim', $options);
 237  
 238          $vals = array();
 239          foreach ($content as $key=>$val) {
 240              if ($key === 'xxx') {
 241                  continue;
 242              }
 243              if (!in_array($val, $options)) {
 244                  continue;
 245  
 246              }
 247              $vals[] = $val;
 248          }
 249  
 250          if (empty($vals)) {
 251              return NULL;
 252          }
 253  
 254          return implode('##', $vals);
 255      }
 256  
 257      /**
 258       * Check whether any boxes in the checkbox where checked.
 259       *
 260       * @param mixed $value The submitted values
 261       * @param mixed $name
 262       * @return bool
 263       */
 264      function notemptyfield($value, $name) {
 265          $found = false;
 266          foreach ($value as $checkboxitem) {
 267              if (strval($checkboxitem) !== '') {
 268                  $found = true;
 269                  break;
 270              }
 271          }
 272          return $found;
 273      }
 274  
 275      /**
 276       * Returns the presentable string value for a field content.
 277       *
 278       * The returned string should be plain text.
 279       *
 280       * @param stdClass $content
 281       * @return string
 282       */
 283      public static function get_content_value($content) {
 284          $arr = explode('##', $content->content);
 285  
 286          $strvalue = '';
 287          foreach ($arr as $a) {
 288              $strvalue .= $a . ' ';
 289          }
 290  
 291          return trim($strvalue, "\r\n ");
 292      }
 293  
 294      /**
 295       * Return the plugin configs for external functions.
 296       *
 297       * @return array the list of config parameters
 298       * @since Moodle 3.3
 299       */
 300      public function get_config_for_external() {
 301          // Return all the config parameters.
 302          $configs = [];
 303          for ($i = 1; $i <= 10; $i++) {
 304              $configs["param$i"] = $this->field->{"param$i"};
 305          }
 306          return $configs;
 307      }
 308  }