summaryrefslogtreecommitdiffstats
path: root/modules-available/locationinfo/inc
diff options
context:
space:
mode:
Diffstat (limited to 'modules-available/locationinfo/inc')
-rw-r--r--modules-available/locationinfo/inc/coursebackend.inc.php283
-rw-r--r--modules-available/locationinfo/inc/coursebackend/coursebackend_davinci.inc.php140
-rw-r--r--modules-available/locationinfo/inc/coursebackend/coursebackend_dummy.inc.php116
-rw-r--r--modules-available/locationinfo/inc/coursebackend/coursebackend_hisinone.inc.php360
-rw-r--r--modules-available/locationinfo/inc/locationinfo.inc.php63
5 files changed, 962 insertions, 0 deletions
diff --git a/modules-available/locationinfo/inc/coursebackend.inc.php b/modules-available/locationinfo/inc/coursebackend.inc.php
new file mode 100644
index 00000000..11d833e6
--- /dev/null
+++ b/modules-available/locationinfo/inc/coursebackend.inc.php
@@ -0,0 +1,283 @@
+<?php
+
+/**
+ * Base class for course query backends
+ */
+abstract class CourseBackend
+{
+
+ /*
+ * Static part for handling interfaces
+ */
+
+ /**
+ * @var array list of known backends
+ * @var boolean true if there was an error
+ * @var string with the error message
+ * @var int as internal serverID
+ * @var string url of the service
+ */
+ private static $backendTypes = false;
+ public $error;
+ public $errormsg;
+ public $serverID;
+ public $location;
+ const nrOtherRooms = 5;
+
+ /**
+ * CourseBackend constructor.
+ */
+ public final function __construct()
+ {
+ $this->location = "";
+ $this->error = false;
+ $this->errormsg = "";
+ }
+
+ /**
+ * Load all known backend types. This is done
+ * by including *.inc.php from inc/coursebackend/.
+ */
+ public static function loadDb()
+ {
+ if (self::$backendTypes !== false)
+ return;
+ self::$backendTypes = array();
+ foreach (glob(dirname(__FILE__) . '/coursebackend/coursebackend_*.inc.php', GLOB_NOSORT) as $file) {
+ require_once $file;
+ preg_match('#coursebackend_([^/\.]+)\.inc\.php$#i', $file, $out);
+ if (!class_exists('coursebackend_' . $out[1])) {
+ trigger_error("Backend type source unit $file doesn't seem to define class CourseBackend_{$out[1]}", E_USER_ERROR);
+ }
+ self::$backendTypes[$out[1]] = true;
+ }
+ }
+
+ /**
+ * Get all known config module types.
+ *
+ * @return array list of modules
+ */
+ public static function getList()
+ {
+ self::loadDb();
+ return array_keys(self::$backendTypes);
+ }
+
+ /**
+ * Get fresh instance of ConfigModule subclass for given module type.
+ *
+ * @param string $moduleType name of module type
+ * @return \ConfigModule module instance
+ */
+ public static function getInstance($moduleType)
+ {
+ self::loadDb();
+ if (!isset(self::$backendTypes[$moduleType])) {
+ error_log('Unknown module type: ' . $moduleType);
+ return false;
+ }
+ if (!is_object(self::$backendTypes[$moduleType])) {
+ $class = "coursebackend_$moduleType";
+ self::$backendTypes[$moduleType] = new $class;
+ }
+ return self::$backendTypes[$moduleType];
+ }
+
+ /**
+ * @return string return display name of backend
+ */
+ public abstract function getDisplayName();
+
+
+ /**
+ * @returns array with parameter name as key and and an array with type, help text and mask as value
+ */
+ public abstract function getCredentials();
+
+ /**
+ * @return boolean true if the connection works, false otherwise
+ */
+ public abstract function checkConnection();
+
+ /**
+ * uses json to setCredentials, the json must follow the form given in
+ * getCredentials
+ *
+ * @param array $data with the credentials
+ * @param string $url address of the server
+ * @param int $serverID ID of the server
+ * @returns bool if the credentials were in the correct format
+ */
+ public abstract function setCredentials($data, $url, $serverID);
+
+ /**
+ * @return int desired caching time of results, in seconds. 0 = no caching
+ */
+ public abstract function getCacheTime();
+
+ /**
+ * @return int age after which timetables are no longer refreshed should be
+ * greater then CacheTime
+ */
+ public abstract function getRefreshTime();
+
+ /**
+ * Internal version of fetch, to be overridden by subclasses.
+ *
+ * @param $roomIds array with local ID as key and serverID as value
+ * @return array a recursive array that uses the roomID as key
+ * and has the schedule array as value. A shedule array contains an array in this format:
+ * ["start"=>'JJJJ-MM-DD HH:MM:SS',"end"=>'JJJJ-MM-DD HH:MM:SS',"title"=>string]
+ */
+ protected abstract function fetchSchedulesInternal($roomId);
+
+ /**
+ * Method for fetching the schedule of the given rooms on a server.
+ *
+ * @param array $roomId array of room ID to fetch
+ * @return array|bool array containing the timetables as value and roomid as key as result, or false on error
+ */
+ public final function fetchSchedule($roomIDs)
+ {
+ if (empty($roomIDs)) {
+ $this->error = true;
+ $this->errormsg = 'No roomid was given to fetch Shedule';
+ return false;
+ }
+ $sqlr = implode(",", $roomIDs);
+ $sqlr = '(' . $sqlr . ')';
+ $q = "SELECT locationid, calendar, serverroomid, lastcalendarupdate FROM location_info WHERE locationid IN " . $sqlr;
+ $dbquery1 = Database::simpleQuery($q);
+ $result = [];
+ $sRoomIDs = [];
+ $newResult = [];
+ foreach ($dbquery1->fetchAll(PDO::FETCH_ASSOC) as $row) {
+ $sRoomID = $row['serverroomid'];
+ $lastUpdate = $row['lastcalendarupdate'];
+ $calendar = $row['calendar'];
+ //Check if in cache if lastUpdate is null then it is interpreted as 1970
+ if ($lastUpdate > strtotime("-" . $this->getCacheTime() . "seconds")) {
+ $result[$row['locationid']] = json_decode($calendar);
+ } else {
+ $sRoomIDs[$row['locationid']] = $sRoomID;
+ }
+
+ }
+ //Check if we should refresh other rooms recently requested by front ends
+ if ($this->getCacheTime() > 0) {
+ $i = 0; //number of rooms getting refreshed
+ $dbquery4 = Database::simpleQuery("SELECT locationid ,serverroomid, lastcalendarupdate FROM location_info WHERE serverid= :id", array('id' => $this->serverID));
+ foreach ($dbquery4->fetchAll(PDO::FETCH_COLUMN) as $row) {
+ if (isset($row['lastcalendarupdate'])) {
+ $lastUpdate = $row['lastcalendarupdate'];
+ if ($lastUpdate < strtotime("-" . $this->getRefreshTime() . "seconds")
+ && $lastUpdate > strtotime("-" . $this->getCacheTime() . "seconds"
+ && $i < self::nrOtherRooms)) {
+ $sRoomIDs[$row['locationid']] = $row['serverroomid'];
+ $i = $i + 1;
+ }
+ }
+ }
+ }
+ //This is true if there is no need to check the HisInOne Server
+ if (empty($sRoomIDs)) {
+ return $result;
+ }
+ $results = $this->fetchSchedulesInternal($sRoomIDs);
+ if ($results === false) {
+ return false;
+ }
+
+ foreach ($sRoomIDs as $location => $serverRoom) {
+ $newResult[$location] = $results[$serverRoom];
+ }
+
+ if ($this->getCacheTime() > 0) {
+ foreach ($newResult as $key => $value) {
+ $value = json_encode($value);
+ $now = strtotime('Now');
+ Database::simpleQuery("UPDATE location_info SET calendar = :ttable, lastcalendarupdate = :now
+ WHERE locationid = :id ", array(
+ 'id' => $key,
+ 'ttable' => $value,
+ 'now' => $now
+ ));
+ }
+ }
+ //get all schedules that are wanted from roomIDs
+ foreach ($roomIDs as $id) {
+ if (isset($newResult[$id])) {
+ $result[$id] = $newResult[$id];
+ }
+ }
+ return $result;
+ }
+
+ /**
+ * @return false if there was no error string with error message if there was one
+ */
+ public final function getError()
+ {
+ if ($this->error) {
+ return $this->errormsg;
+ }
+ return false;
+ }
+
+ /**
+ * Query path in array-representation of XML document.
+ * e.g. 'path/syntax/foo/wanteditem'
+ * This works for intermediate nodes (that have more children)
+ * and leaf nodes. The result is always an array on success, or
+ * false if not found.
+ */
+ function getAttributes($array, $path)
+ {
+ if (!is_array($path)) {
+ // Convert 'path/syntax/foo/wanteditem' to array for further processing and recursive calls
+ $path = explode('/', $path);
+ }
+ do {
+ // Get next element from array, loop to ignore empty elements (so double slashes in the path are allowed)
+ $element = array_shift($path);
+ } while (empty($element) && !empty($path));
+ if (!isset($array[$element])) {
+ // Current path element does not exist - error
+ return false;
+ }
+ if (empty($path)) {
+ // Path is now empty which means we're at 'wanteditem' from out example above
+ if (!is_array($array[$element]) || !isset($array[$element][0])) {
+ // If it's a leaf node of the array, wrap it in plain array, so the function will
+ // always return an array on success
+ return array($array[$element]);
+ }
+ // 'wanteditem' is not a unique leaf node, return as is
+ // This means it's either a plain array, in case there are multiple 'wanteditem' elements on the same level
+ // or it's an associative array if 'wanteditem' has any sub-nodes
+ return $array[$element];
+ }
+ // Recurse
+ if (!is_array($array[$element])) {
+ // We're in the middle of the requested path, but the current element is already a leaf node with no
+ // children - error
+ return false;
+ }
+ if (isset($array[$element][0])) {
+ // The currently handled element of the path exists multiple times on the current level, so it is
+ // wrapped in a plain array - recurse into each one of them and merge the results
+ $return = [];
+ foreach ($array[$element] as $item) {
+ $test = $this->getAttributes($item, $path);
+ If (gettype($test) == "array") {
+ $return = array_merge($return, $test);
+ }
+
+ }
+ return $return;
+ }
+ // Unique non-leaf node - simple recursion
+ return $this->getAttributes($array[$element], $path);
+ }
+}
diff --git a/modules-available/locationinfo/inc/coursebackend/coursebackend_davinci.inc.php b/modules-available/locationinfo/inc/coursebackend/coursebackend_davinci.inc.php
new file mode 100644
index 00000000..11882a1e
--- /dev/null
+++ b/modules-available/locationinfo/inc/coursebackend/coursebackend_davinci.inc.php
@@ -0,0 +1,140 @@
+<?php
+
+class Coursebackend_Davinci extends CourseBackend
+{
+
+
+ public function setCredentials($data, $location, $serverID)
+ {
+ if ($location == "") {
+ $this->error = true;
+ $this->errormsg = "No url is given";
+ return !$this->error;
+ }
+ $this->location = $location . "/DAVINCIIS.dll?";
+ $this->serverID = $serverID;
+ //Davinci doesn't have credentials
+ return true;
+ }
+
+ public function checkConnection()
+ {
+ if ($this->location != "") {
+ $this->fetchSchedulesInternal(['B206']);
+ return !$this->error;
+ }
+ $this->error = true;
+ $this->errormsg = "Credentials are not set";
+ return !$this->error;
+ }
+
+ public function getCredentials()
+ {
+ $return = array();
+ return $return;
+ }
+
+ public function getDisplayName()
+ {
+ return 'Davinci';
+ }
+
+ public function getCacheTime()
+ {
+ return 0;
+ }
+
+ public function getRefreshTime()
+ {
+ return 0;
+ }
+
+ /**
+ * @param $response xml document
+ * @return bool|array array representation of the xml if possible
+ */
+ private function toArray($response)
+ {
+ try {
+ $cleanresponse = preg_replace('/(<\/?)(\w+):([^>]*>)/', "$1$2$3", $response);
+ $xml = new SimpleXMLElement($cleanresponse);
+ $array = json_decode(json_encode((array)$xml), true);
+ } catch (Exception $exception) {
+ $this->error = true;
+ $this->errormsg = "url did not answer with a xml, maybe the url is wrong or the room is wrong";
+ $array = false;
+ }
+ return $array;
+ }
+
+ /**
+ * @param $roomId string name of the room
+ * @return array|bool if successful the arrayrepresentation of the timetable
+ */
+ private function fetchArray($roomId)
+ {
+ $startDate = new DateTime('today 0:00');
+ $endDate = new DateTime('+7 days 0:00');
+ $url = $this->location . "content=xml&type=room&name=" . $roomId . "&startdate=" . $startDate->format('d.m.Y') . "&enddate=" . $endDate->format('d.m.Y');
+ $ch = curl_init();
+ $options = array(
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_FOLLOWLOCATION => true,
+ CURLOPT_SSL_VERIFYHOST => false,
+ CURLOPT_SSL_VERIFYPEER => false,
+ CURLOPT_URL => $url,
+ );
+
+ curl_setopt_array($ch, $options);
+ $output = curl_exec($ch);
+ if ($output === false) {
+ $this->error = true;
+ $this->errormsg = 'Curl error: ' . curl_error($ch) . $url;
+ return false;
+ } else {
+ $this->error = false;
+ $this->errormsg = "";
+ ///Operation completed successfully
+ }
+ curl_close($ch);
+ error_log($output);
+ return $this->toArray($output);
+
+ }
+
+ public function fetchSchedulesInternal($roomIds)
+ {
+ $schedules = [];
+ foreach ($roomIds as $sroomId) {
+ $return = $this->fetchArray($sroomId);
+ if ($return === false) {
+ return false;
+ }
+ $lessons = $this->getAttributes($return, 'Lessons/Lesson');
+ if (!$lessons) {
+ $this->error = true;
+ $this->errormsg = "url send a xml in a wrong format";
+ return false;
+ }
+ $timetable = [];
+ foreach ($lessons as $lesson) {
+ $date = $lesson['Date'];
+ $date = substr($date, 0, 4) . '-' . substr($date, 4, 2) . '-' . substr($date, 6, 2);
+ $start = $lesson['Start'];
+ $start = substr($start, 0, 2) . ':' . substr($start, 2, 2);
+ $end = $lesson['Finish'];
+ $end = substr($end, 0, 2) . ':' . substr($end, 2, 2);
+ $subject = $lesson['Subject'];
+ $json = array(
+ 'title' => $subject,
+ 'start' => $date . " " . $start . ':00',
+ 'end' => $date . " " . $end . ':00'
+ );
+ array_push($timetable, $json);
+ }
+ $schedules[$sroomId] = $timetable;
+ }
+ return $schedules;
+ }
+}
+
diff --git a/modules-available/locationinfo/inc/coursebackend/coursebackend_dummy.inc.php b/modules-available/locationinfo/inc/coursebackend/coursebackend_dummy.inc.php
new file mode 100644
index 00000000..484a5286
--- /dev/null
+++ b/modules-available/locationinfo/inc/coursebackend/coursebackend_dummy.inc.php
@@ -0,0 +1,116 @@
+<?php
+
+class Coursebackend_Dummy extends CourseBackend
+{
+ private $pw;
+
+ /**
+ * uses json to setCredentials, the json must follow the form given in
+ * getCredentials
+ *
+ * @param array $data with the credentials
+ * @param string $url address of the server
+ * @param int $serverID ID of the server
+ * @returns bool if the credentials were in the correct format
+ */
+ public function setCredentials($json, $location, $serverID)
+ {
+ $x = $json;
+ $this->pw = $x['password'];
+
+ if ($this->pw === "mfg") {
+ $this->error = false;
+ return true;
+ } else {
+ $this->errormsg = "USE mfg as password!";
+ $this->error = true;
+ return false;
+ }
+ }
+
+ /**
+ * @return boolean true if the connection works, false otherwise
+ */
+ public function checkConnection()
+ {
+ if ($this->pw == "mfg") {
+ $this->error = false;
+ return true;
+ } else {
+ $this->errormsg = "USE mfg as password!";
+ $this->error = true;
+ return false;
+ }
+ }
+
+ /**
+ * @returns array with parameter name as key and and an array with type, help text and mask as value
+ */
+ public function getCredentials()
+ {
+ $options = ["opt1", "opt2", "opt3", "opt4", "opt5", "opt6", "opt7", "opt8"];
+ $credentials = [
+ "username" => "string",
+ "password" => "password",
+ "integer" => "int",
+ "option" => $options,
+ "CheckTheBox" => "bool",
+ "CB2 t" => "bool"
+ ];
+ return $credentials;
+ }
+
+ /**
+ * @return string return display name of backend
+ */
+ public function getDisplayName()
+ {
+ return 'Dummy with array';
+ }
+
+ /**
+ * @return int desired caching time of results, in seconds. 0 = no caching
+ */
+ public function getCacheTime()
+ {
+ return 0;
+ }
+
+ /**
+ * @return int age after which timetables are no longer refreshed should be
+ * greater then CacheTime
+ */
+ public function getRefreshTime()
+ {
+ return 0;
+ }
+
+ /**
+ * Internal version of fetch, to be overridden by subclasses.
+ *
+ * @param $roomIds array with local ID as key and serverID as value
+ * @return array a recursive array that uses the roomID as key
+ * and has the schedule array as value. A shedule array contains an array in this format:
+ * ["start"=>'JJJJ-MM-DD HH:MM:SS',"end"=>'JJJJ-MM-DD HH:MM:SS',"title"=>string]
+ */
+ public function fetchSchedulesInternal($roomId)
+ {
+ $a = array();
+ foreach ($roomId as $id) {
+ $x['id'] = $id;
+ $calendar['title'] = "test exam";
+ $calendar['start'] = "2017-3-08 13:00:00";
+ $calendar['end'] = "2017-3-08 16:00:00";
+ $calarray = array();
+ $calarray[] = $calendar;
+ $x['calendar'] = $calarray;
+ $a[$id] = $calarray;
+ }
+
+
+ return $a;
+ }
+
+}
+
+?>
diff --git a/modules-available/locationinfo/inc/coursebackend/coursebackend_hisinone.inc.php b/modules-available/locationinfo/inc/coursebackend/coursebackend_hisinone.inc.php
new file mode 100644
index 00000000..0e7c5328
--- /dev/null
+++ b/modules-available/locationinfo/inc/coursebackend/coursebackend_hisinone.inc.php
@@ -0,0 +1,360 @@
+<?php
+
+class CourseBackend_HisInOne extends CourseBackend
+{
+ private $username;
+ private $password;
+ private $open;
+
+
+ public function setCredentials($data, $url, $serverID)
+ {
+ if (array_key_exists('password', $data) && array_key_exists('username', $data) && array_key_exists('role', $data) && isset($data['open'])) {
+ $this->error = false;
+ $this->password = $data['password'];
+ $this->username = $data['username'] . "\t" . $data['role'];
+ $this->open = $data['open'];
+ if ($url == "") {
+ $this->error = true;
+ $this->errormsg = "No url is given";
+ return !$this->error;
+ }
+ if ($this->open) {
+ $this->location = $url . "/qisserver/services2/OpenCourseService";
+ } else {
+ $this->location = $url . "/qisserver/services2/CourseService";
+ }
+ $this->serverID = $serverID;
+ } else {
+ $this->error = true;
+ $this->errormsg = "wrong credentials";
+ return false;
+ }
+
+ return true;
+ }
+
+ public function checkConnection()
+ {
+ if ($this->location == "") {
+ $this->error = true;
+ $this->errormsg = "Credentials are not set";
+ }
+ $this->findUnit(190);
+ return !$this->error;
+ }
+
+ /**
+ * @param $roomID int
+ * @return array|bool if successful an array with the subjectIDs that take place in the room
+ */
+ public function findUnit($roomID)
+ {
+ $termYear = date('Y');
+ $termType1 = date('n');
+ if ($termType1 > 3 && $termType1 < 10) {
+ $termType = 2;
+ } elseif ($termType1 > 10) {
+ $termType = 1;
+ $termYear = $termYear + 1;
+ } else {
+ $termType = 1;
+ }
+ $doc = new DOMDocument('1.0', 'utf-8');
+ $doc->formatOutput = true;
+ $envelope = $doc->createElementNS('http://schemas.xmlsoap.org/soap/envelope/', 'SOAP-ENV:Envelope');
+ $doc->appendChild($envelope);
+ if ($this->open) {
+ $envelope->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:ns1', 'http://www.his.de/ws/OpenCourseService');
+ } else {
+ $envelope->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:ns1', 'http://www.his.de/ws/CourseService');
+ $header = $this->getHeader($doc);
+ $envelope->appendChild($header);
+ }
+ //Body of the request
+ $body = $doc->createElement('SOAP-ENV:Body');
+ $envelope->appendChild($body);
+ $findUnit = $doc->createElement('ns1:findUnit');
+ $body->appendChild($findUnit);
+ $termYearN = $doc->createElement('termYear', $termYear);
+ $findUnit->appendChild($termYearN);
+ if ($termType1 != 3 && $termType1 != 10) {
+ $termTypeValueId = $doc->createElement('termTypeValueId', $termType);
+ $findUnit->appendChild($termTypeValueId);
+ }
+ $roomIdN = $doc->createElement('ns1:roomId', $roomID);
+ $findUnit->appendChild($roomIdN);
+
+ $soap_request = $doc->saveXML();
+ $response1 = $this->__doRequest($soap_request, "findUnit");
+ $id = [];
+ if ($this->error == true) {
+ return false;
+ }
+ $response2 = $this->toArray($response1);
+ if ($response2 === false) {
+ return false;
+ }
+ if (isset($response2['soapenvBody']['soapenvFault'])) {
+ $this->error = true;
+ $this->errormsg = $response2['soapenvBody']['soapenvFault']['faultcode'] . " " . $response2['soapenvBody']['soapenvFault']['faultstring'];
+ return false;
+ } elseif ($this->open) {
+ $units = $this->getAttributes($response2, 'soapenvBody/hisfindUnitResponse/hisunits/hisunit');
+ foreach ($units as $unit) {
+ $id[] = $unit['hisid'];
+ }
+ } elseif (!$this->open) {
+ $id = $this->getAttributes($response2, 'soapenvBody/hisfindUnitResponse/hisunitIds/hisid');
+ } else {
+ $this->error = true;
+ $this->errormsg = "url send a xml in a wrong format";
+ $id = false;
+ }
+ return $id;
+ }
+
+ /**
+ * @param $doc DOMDocument
+ * @return DOMElement
+ */
+ private function getHeader($doc)
+ {
+ $header = $doc->createElement('SOAP-ENV:Header');
+ $security = $doc->createElementNS('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', 'ns2:Security');
+ $mustunderstand = $doc->createAttribute('SOAP-ENV:mustUnderstand');
+ $mustunderstand->value = 1;
+ $security->appendChild($mustunderstand);
+ $header->appendChild($security);
+ $token = $doc->createElement('ns2:UsernameToken');
+ $security->appendChild($token);
+ $user = $doc->createElement('ns2:Username', $this->username);
+ $token->appendChild($user);
+ $pass = $doc->createElement('ns2:Password', $this->password);
+ $type = $doc->createAttribute('Type');
+ $type->value = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText';
+ $pass->appendChild($type);
+ $token->appendChild($pass);
+ return $header;
+ }
+
+ /**
+ * @param $request string with xml SOAP request
+ * @param $action string with the name of the SOAP action
+ * @return bool|string if successful the answer xml from the SOAP server
+ */
+ private function __doRequest($request, $action)
+ {
+ $header = array(
+ "Content-type: text/xml;charset=\"utf-8\"",
+ "SOAPAction: \"" . $action . "\"",
+ "Content-length: " . strlen($request),
+ );
+
+ $soap_do = curl_init();
+
+ $options = array(
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_FOLLOWLOCATION => true,
+ CURLOPT_SSL_VERIFYHOST => false,
+ CURLOPT_SSL_VERIFYPEER => false,
+ CURLOPT_URL => $this->location,
+ CURLOPT_POSTFIELDS => $request,
+ CURLOPT_HTTPHEADER => $header,
+ );
+
+ curl_setopt_array($soap_do, $options);
+
+ $output = curl_exec($soap_do);
+
+ if ($output === false) {
+ $this->error = true;
+ $this->errormsg = 'Curl error: ' . curl_error($soap_do);
+ } else {
+ $this->error = false;
+ $this->errormsg = "";
+ ///Operation completed successfully
+ }
+ curl_close($soap_do);
+ return $output;
+ }
+
+ /**
+ * @param $response xml document
+ * @return bool|array array representation of the xml if possible
+ */
+ private function toArray($response)
+ {
+ try {
+ $cleanresponse = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
+ $xml = new SimpleXMLElement($cleanresponse);
+ $array = json_decode(json_encode((array)$xml), true);
+ } catch (Exception $e) {
+ $this->error = true;
+ $this->errormsg = "url did not send a xml";
+ $array = false;
+ }
+ return $array;
+ }
+
+
+ public function getCacheTime()
+ {
+ return 30 * 60;
+ }
+
+
+ public function getRefreshTime()
+ {
+ return 60 * 60;
+ }
+
+
+ public function getDisplayName()
+ {
+ return "HisInOne";
+ }
+
+
+ public function getCredentials()
+ {
+ $credentials = ["username" => "string", "role" => "string", "password" => "password", "open" => "bool"];
+ return $credentials;
+ }
+
+
+ public function fetchSchedulesInternal($param)
+ {
+ if (empty($param)) {
+ $this->error = true;
+ $this->errormsg = 'Internal Error HisInOne';
+ error_log('No roomId was given in HisInOne fetchShedule');
+ return false;
+ }
+ $tTables = [];
+ //get all eventIDs in a given room
+ $eventIDs = [];
+ foreach ($param as $ID) {
+ $unitID = $this->findUnit($ID);
+ if ($unitID == false) {
+ $this->error = false;
+ error_log($this->errormsg);
+ continue;
+ }
+ $eventIDs = array_merge($eventIDs, $unitID);
+ $eventIDs = array_unique($eventIDs);
+ }
+ if (empty($eventIDs)) {
+ foreach ($param as $room) {
+ $tTables[$room] = [];
+ }
+ return $tTables;
+ }
+ $events = [];
+ //get all information on each event
+ foreach ($eventIDs as $each_event) {
+ $event = $this->readUnit(intval($each_event));
+ if ($event === false) {
+ $this->error = false;
+ error_log($this->errormsg);
+ continue;
+ }
+ $events[] = $event;
+ }
+ $currentWeek = $this->getCurrentWeekDates();
+ foreach ($param as $room) {
+ $timetable = array();
+ //Here I go over the soapresponse
+ foreach ($events as $event) {
+ $name = $this->getAttributes($event, '/hisunit/hisdefaulttext');
+ if ($name == false) {
+ //if HisInOne has no default text then there is no name
+ $name = [''];
+ }
+ $dates = $this->getAttributes($event,
+ '/hisunit/hisplanelements/hisplanelement/hisplannedDates/hisplannedDate/hisindividualDates/hisindividualDate');
+ foreach ($dates as $date) {
+ $roomID = $this->getAttributes($date, '/hisroomId')[0];
+ $datum = $this->getAttributes($date, '/hisexecutiondate')[0];
+ if (intval($roomID) == $room && in_array($datum, $currentWeek)) {
+ $startTime = $this->getAttributes($date, 'hisstarttime')[0];
+ $endTime = $this->getAttributes($date, 'hisendtime')[0];
+ $json = array(
+ 'title' => $name[0],
+ 'start' => $datum . " " . $startTime,
+ 'end' => $datum . " " . $endTime
+ );
+ array_push($timetable, $json);
+ }
+ }
+ }
+ $tTables[$room] = $timetable;
+ }
+ return $tTables;
+ }
+
+
+ /**
+ * @param $unit int ID of the subject in HisInOne database
+ * @return bool|array false if there was an error otherwise an array with the information about the subject
+ */
+ public function readUnit($unit)
+ {
+ $doc = new DOMDocument('1.0', 'utf-8');
+ $doc->formatOutput = true;
+ $envelope = $doc->createElementNS('http://schemas.xmlsoap.org/soap/envelope/', 'SOAP-ENV:Envelope');
+ $doc->appendChild($envelope);
+ if ($this->open) {
+ $envelope->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:ns1', 'http://www.his.de/ws/OpenCourseService');
+ } else {
+ $envelope->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:ns1', 'http://www.his.de/ws/CourseService');
+ $header = $this->getHeader($doc);
+ $envelope->appendChild($header);
+ }
+ //body of the request
+ $body = $doc->createElement('SOAP-ENV:Body');
+ $envelope->appendChild($body);
+ $readUnit = $doc->createElement('ns1:readUnit');
+ $body->appendChild($readUnit);
+ $unitId = $doc->createElement('ns1:unitId', $unit);
+ $readUnit->appendChild($unitId);
+
+ $soap_request = $doc->saveXML();
+ $response1 = $this->__doRequest($soap_request, "readUnit");
+ if ($response1 == false) {
+ return false;
+ }
+ $response2 = $this->toArray($response1);
+ if ($response2 != false) {
+ if (isset($response2['soapenvBody']['soapenvFault'])) {
+ $this->error = true;
+ $this->errormsg = 'SOAP-Fault' . $response2['soapenvBody']['soapenvFault']['faultcode'] . " " . $response2['soapenvBody']['soapenvFault']['faultstring'];
+ return false;
+ } elseif (isset($response2['soapenvBody']['hisreadUnitResponse'])) {
+ $this->error = false;
+ $response3 = $response2['soapenvBody']['hisreadUnitResponse'];
+ $this->errormsg = '';
+ return $response3;
+ } else {
+ $this->error = true;
+ $this->errormsg = "wrong url or the url send a xml in the wrong format";
+ return false;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * @return array with days of the current week in datetime format
+ */
+ private function getCurrentWeekDates()
+ {
+ $DateArray = array();
+ $startdate = strtotime('Now');
+ for ($i = 0; $i <= 7; $i++) {
+ $DateArray[] = date('Y-m-d', strtotime("+ {$i} day", $startdate));
+ }
+ return $DateArray;
+ }
+
+}
diff --git a/modules-available/locationinfo/inc/locationinfo.inc.php b/modules-available/locationinfo/inc/locationinfo.inc.php
new file mode 100644
index 00000000..7617d143
--- /dev/null
+++ b/modules-available/locationinfo/inc/locationinfo.inc.php
@@ -0,0 +1,63 @@
+<?php
+
+class LocationInfo
+{
+
+ /**
+ * Gets the pc data and returns it's state.
+ *
+ * @param array $pc The pc data from the db. Array('logintime' =>, 'lastseen' =>, 'lastboot' =>)
+ * @return int pc state
+ */
+ public static function getPcState($pc)
+ {
+ /* pcState:
+ * [0] = IDLE (NOT IN USE)
+ * [1] = OCCUPIED (IN USE)
+ * [2] = OFF
+ * [3] = 10 days offline (BROKEN?)
+ */
+ // TODO USE STATE NAME instead of numbers
+
+ $logintime = (int)$pc['logintime'];
+ $lastseen = (int)$pc['lastseen'];
+ $lastboot = (int)$pc['lastboot'];
+ $NOW = time();
+
+ if ($NOW - $lastseen > 14 * 86400) {
+ return "BROKEN";
+ } elseif (($NOW - $lastseen > 610) || $lastboot === 0) {
+ return "OFF";
+ } elseif ($logintime === 0) {
+ return "IDLE";
+ } elseif ($logintime > 0) {
+ return "OCCUPIED";
+ }
+ return -1;
+ }
+
+ /**
+ * Set current error message of given server. Pass null or false to clear.
+ *
+ * @param int $serverId id of server
+ * @param string $message error message to set, null or false clears error.
+ */
+ public static function setServerError($serverId, $message)
+ {
+ if ($message === false || $message === null) {
+ Database::exec("UPDATE `setting_location_info` SET error = NULL
+ WHERE serverid = :id", array('id' => $serverId));
+ } else {
+ if (empty($message)) {
+ $message = '<empty error message>';
+ }
+ $error = json_encode(array(
+ 'timestamp' => time(),
+ 'error' => (string)$message
+ ));
+ Database::exec("UPDATE `setting_location_info` SET error = :error
+ WHERE serverid = :id", array('id' => $serverId, 'error' => $error));
+ }
+ }
+
+}