Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 311 and 401] [Versions 311 and 402] [Versions 311 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_latlong extends data_field_base {
  26      var $type = 'latlong';
  27  
  28      // This is an array of URL schemes for linking out to services, using the float values of lat and long.
  29      // In each scheme, the special markers @lat@ and @long@ will be replaced by the float values.
  30      // The config options for the field store each service name that should be displayed, in a comma-separated
  31      // field. Therefore please DO NOT include commas in the service names if you are adding extra services.
  32  
  33      // Parameter data used:
  34      // "param1" is a comma-separated list of the linkout service names that are enabled for this instance
  35      // "param2" indicates the label that will be used in generating Google Earth KML files: -1 for item #, -2 for lat/long, positive number for the (text) field to use.
  36  
  37      var $linkoutservices = array(
  38            "Google Maps" => "http://maps.google.com/maps?q=@lat@,+@long@&iwloc=A&hl=en",
  39            "Google Earth" => "@wwwroot@/mod/data/field/latlong/kml.php?d=@dataid@&fieldid=@fieldid@&rid=@recordid@",
  40            "Geabios" => "http://www.geabios.com/html/services/maps/PublicMap.htm?lat=@lat@&lon=@long@&fov=0.3&title=Moodle%20data%20item",
  41            "OpenStreetMap" => "http://www.openstreetmap.org/index.html?lat=@lat@&lon=@long@&zoom=11",
  42            "Multimap" => "http://www.multimap.com/map/browse.cgi?scale=200000&lon=@long@&lat=@lat@&icon=x"
  43      );
  44      // Other map sources listed at http://kvaleberg.com/extensions/mapsources/index.php?params=51_30.4167_N_0_7.65_W_region:earth
  45  
  46      function display_add_field($recordid = 0, $formdata = null) {
  47          global $CFG, $DB, $OUTPUT;
  48  
  49          $lat = '';
  50          $long = '';
  51          if ($formdata) {
  52              $fieldname = 'field_' . $this->field->id . '_0';
  53              $lat = $formdata->$fieldname;
  54              $fieldname = 'field_' . $this->field->id . '_1';
  55              $long = $formdata->$fieldname;
  56          } else if ($recordid) {
  57              if ($content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
  58                  $lat  = $content->content;
  59                  $long = $content->content1;
  60              }
  61          }
  62          $str = '<div title="'.s($this->field->description).'">';
  63          $str .= '<fieldset><legend><span class="accesshide">'.$this->field->name.'</span></legend>';
  64          $str .= '<table class="form-inline"><tr><td align="right">';
  65          $classes = 'mod-data-input form-control-static';
  66          $str .= '<label for="field_'.$this->field->id.'_0" class="' . $classes . '">' . get_string('latitude', 'data');
  67          if ($this->field->required) {
  68              $str .= $OUTPUT->pix_icon('req', get_string('requiredelement', 'form'));
  69          }
  70          $classes = 'form-control mx-1';
  71          $str .= '</label></td><td>';
  72          $str .= '<input class="' . $classes . '" type="text" name="field_'.$this->field->id.'_0" ';
  73          $str .= ' id="field_'.$this->field->id.'_0" value="';
  74          $str .= s($lat).'" size="10" />°N</td></tr>';
  75          $classes = 'mod-data-input form-control-static';
  76          $str .= '<tr><td align="right"><label for="field_'.$this->field->id.'_1" class="' . $classes . '">';
  77          $str .= get_string('longitude', 'data');
  78          if ($this->field->required) {
  79              $str .= $OUTPUT->pix_icon('req', get_string('requiredelement', 'form'));
  80          }
  81          $classes = 'form-control mx-1';
  82          $str .= '</label></td><td><input class="' . $classes . '" type="text" ';
  83          $str .= 'name="field_'.$this->field->id.'_1" id="field_'.$this->field->id.'_1" value="';
  84          $str .= s($long).'" size="10" />°E</td>';
  85          $str .= '</tr>';
  86          $str .= '</table>';
  87          $str .= '</fieldset>';
  88          $str .= '</div>';
  89          return $str;
  90      }
  91  
  92      function display_search_field($value = '') {
  93          global $CFG, $DB;
  94  
  95          $varcharlat = $DB->sql_compare_text('content');
  96          $varcharlong= $DB->sql_compare_text('content1');
  97          $latlongsrs = $DB->get_recordset_sql(
  98              "SELECT DISTINCT $varcharlat AS la, $varcharlong AS lo
  99                 FROM {data_content}
 100                WHERE fieldid = ?
 101               ORDER BY $varcharlat, $varcharlong", array($this->field->id));
 102  
 103          $options = array();
 104          foreach ($latlongsrs as $latlong) {
 105              $latitude = format_float($latlong->la, 4);
 106              $longitude = format_float($latlong->lo, 4);
 107              if ($latitude && $longitude) {
 108                  $options[$latlong->la . ',' . $latlong->lo] = $latitude . ' ' . $longitude;
 109              }
 110          }
 111          $latlongsrs->close();
 112  
 113          $classes = array('class' => 'accesshide');
 114          $return = html_writer::label(get_string('latlong', 'data'), 'menuf_'.$this->field->id, false, $classes);
 115          $classes = array('class' => 'custom-select');
 116          $return .= html_writer::select($options, 'f_'.$this->field->id, $value, array('' => get_string('menuchoose', 'data')),
 117              $classes);
 118         return $return;
 119      }
 120  
 121      public function parse_search_field($defaults = null) {
 122          $param = 'f_'.$this->field->id;
 123          if (empty($defaults[$param])) {
 124              $defaults = array($param => '');
 125          }
 126          return optional_param($param, $defaults[$param], PARAM_NOTAGS);
 127      }
 128  
 129      function generate_sql($tablealias, $value) {
 130          global $DB;
 131  
 132          static $i=0;
 133          $i++;
 134          $name1 = "df_latlong1_$i";
 135          $name2 = "df_latlong2_$i";
 136          $varcharlat = $DB->sql_compare_text("{$tablealias}.content");
 137          $varcharlong= $DB->sql_compare_text("{$tablealias}.content1");
 138  
 139  
 140          $latlong[0] = '';
 141          $latlong[1] = '';
 142          $latlong = explode (',', $value, 2);
 143          return array(" ({$tablealias}.fieldid = {$this->field->id} AND $varcharlat = :$name1 AND $varcharlong = :$name2) ",
 144                       array($name1=>$latlong[0], $name2=>$latlong[1]));
 145      }
 146  
 147      function display_browse_field($recordid, $template) {
 148          global $CFG, $DB;
 149          if ($content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
 150              $lat = $content->content;
 151              if (strlen($lat) < 1) {
 152                  return false;
 153              }
 154              $long = $content->content1;
 155              if (strlen($long) < 1) {
 156                  return false;
 157              }
 158              // We use format_float to display in the regional format.
 159              if($lat < 0) {
 160                  $compasslat = format_float(-$lat, 4) . '°S';
 161              } else {
 162                  $compasslat = format_float($lat, 4) . '°N';
 163              }
 164              if($long < 0) {
 165                  $compasslong = format_float(-$long, 4) . '°W';
 166              } else {
 167                  $compasslong = format_float($long, 4) . '°E';
 168              }
 169  
 170              // Now let's create the jump-to-services link
 171              $servicesshown = explode(',', $this->field->param1);
 172  
 173              // These are the different things that can be magically inserted into URL schemes
 174              $urlreplacements = array(
 175                  '@lat@'=> $lat,
 176                  '@long@'=> $long,
 177                  '@wwwroot@'=> $CFG->wwwroot,
 178                  '@contentid@'=> $content->id,
 179                  '@dataid@'=> $this->data->id,
 180                  '@courseid@'=> $this->data->course,
 181                  '@fieldid@'=> $content->fieldid,
 182                  '@recordid@'=> $content->recordid,
 183              );
 184  
 185              if(sizeof($servicesshown)==1 && $servicesshown[0]) {
 186                  $str = " <a href='"
 187                            . str_replace(array_keys($urlreplacements), array_values($urlreplacements), $this->linkoutservices[$servicesshown[0]])
 188                            ."' title='$servicesshown[0]'>$compasslat $compasslong</a>";
 189              } elseif (sizeof($servicesshown)>1) {
 190                  $str = '<form id="latlongfieldbrowse">';
 191                  $str .= "$compasslat, $compasslong\n";
 192                  $str .= "<label class='accesshide' for='jumpto'>". get_string('jumpto') ."</label>";
 193                  $str .= '<select id="jumpto" name="jumpto" class="custom-select">';
 194                  foreach($servicesshown as $servicename){
 195                      // Add a link to a service
 196                      $str .= "\n  <option value='"
 197                                 . str_replace(array_keys($urlreplacements), array_values($urlreplacements), $this->linkoutservices[$servicename])
 198                                 . "'>".htmlspecialchars($servicename)."</option>";
 199                  }
 200                  // NB! If you are editing this, make sure you don't break the javascript reference "previousSibling"
 201                  //   which allows the "Go" button to refer to the drop-down selector.
 202                  $str .= '\n</select><input type="button" class="btn ml-1 btn-secondary" value="' . get_string('go');
 203                  $str .= '" onclick="if(previousSibling.value){self.location=previousSibling.value}"/>';
 204                  $str .= '</form>';
 205              } else {
 206                  $str = "$compasslat, $compasslong";
 207              }
 208  
 209              return $str;
 210          }
 211          return false;
 212      }
 213  
 214      function update_content_import($recordid, $value, $name='') {
 215          $values = explode(" ", $value, 2);
 216  
 217          foreach ($values as $index => $value) {
 218              $this->update_content($recordid, $value, $name . '_' . $index);
 219          }
 220      }
 221  
 222      function update_content($recordid, $value, $name='') {
 223          global $DB;
 224  
 225          $content = new stdClass();
 226          $content->fieldid = $this->field->id;
 227          $content->recordid = $recordid;
 228          // When updating these values (which might be region formatted) we should format
 229          // the float to allow for a consistent float format in the database.
 230          $value = unformat_float($value);
 231          $value = trim($value);
 232          if (strlen($value) > 0) {
 233              $value = floatval($value);
 234          } else {
 235              $value = null;
 236          }
 237          $names = explode('_', $name);
 238          switch ($names[2]) {
 239              case 0:
 240                  // update lat
 241                  $content->content = $value;
 242                  break;
 243              case 1:
 244                  // update long
 245                  $content->content1 = $value;
 246                  break;
 247              default:
 248                  break;
 249          }
 250          if ($oldcontent = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
 251              $content->id = $oldcontent->id;
 252              return $DB->update_record('data_content', $content);
 253          } else {
 254              return $DB->insert_record('data_content', $content);
 255          }
 256      }
 257  
 258      function get_sort_sql($fieldname) {
 259          global $DB;
 260          return $DB->sql_cast_char2real($fieldname, true);
 261      }
 262  
 263      function export_text_value($record) {
 264          // The content here is from the database and does not require location formating.
 265          return sprintf('%01.4f', $record->content) . ' ' . sprintf('%01.4f', $record->content1);
 266      }
 267  
 268      /**
 269       * Check if a field from an add form is empty
 270       *
 271       * @param mixed $value
 272       * @param mixed $name
 273       * @return bool
 274       */
 275      function notemptyfield($value, $name) {
 276          return isset($value) && !($value == '');
 277      }
 278  
 279      /**
 280       * Validate values for this field.
 281       * Both the Latitude and the Longitude fields need to be filled in.
 282       *
 283       * @param array $values The entered values for the lat. and long.
 284       * @return string|bool Error message or false.
 285       */
 286      public function field_validation($values) {
 287          $valuecount = 0;
 288          // The lat long class has two values that need to be checked.
 289          foreach ($values as $value) {
 290              if (isset($value->value) && !($value->value == '')) {
 291                  $valuecount++;
 292              }
 293          }
 294          // If we have nothing filled in or both filled in then everything is okay.
 295          if ($valuecount == 0 || $valuecount == 2) {
 296              return false;
 297          }
 298          // If we get here then only one field has been filled in.
 299          return get_string('latlongboth', 'data');
 300      }
 301  
 302      /**
 303       * Return the plugin configs for external functions.
 304       *
 305       * @return array the list of config parameters
 306       * @since Moodle 3.3
 307       */
 308      public function get_config_for_external() {
 309          // Return all the config parameters.
 310          $configs = [];
 311          for ($i = 1; $i <= 10; $i++) {
 312              $configs["param$i"] = $this->field->{"param$i"};
 313          }
 314          return $configs;
 315      }
 316  }