source: Dev/branches/jos-branch/server/classes/models/AnswerSet.php @ 266

Last change on this file since 266 was 263, checked in by hendrikvanantwerpen, 13 years ago
  • [Client] Finished page framework. See rft/ui/content.js or test files for details.
  • [Client] Allow login by pressing Enter.
  • [API] On exception include details in json response.
  • [Server Use Exceptions when save() fails, iso return values.
File size: 5.7 KB
Line 
1<?php
2// Survey database interface class as intermediate for storing data from the site to the RDF database
3require_once 'rdfConstants.php';
4// Include RAP Library to write RDF files
5include(RDFAPI_INCLUDE_DIR . "RDFAPI.php");
6
7/**
8 * AnswerSet is a collection of answers corresponding to a Session
9 *
10 */
11class AnswerSet extends ResearchToolObject{
12        public static $filename = 'data/results/answersets.rdf';
13
14        public $survey;
15        public $respondent;
16        public $datetime;
17        public $answers;
18
19        /**
20         * Constructor for an AnswerSet object
21         * @param type $uid
22         * @param type $survey
23         * @param type $respondent
24         * @param type $datetime
25         * @param type $answers
26         */
27        public function __construct($uid=null, $survey=null, $respondent=null, $datetime=null, $answers=null)
28        {
29                if(!isset($uid))
30                {
31                        $uid = md5(uniqid(rand(), true));
32                }
33                $this->uid = $uid;
34                $this->survey = $survey;
35                $this->respondent = $respondent;
36                $this->datetime = $datetime;
37                $this->answers = $answers;
38        }
39
40        /**
41         * function evaluate()
42         * evaluates the references of survey, respondent and answers.
43         */
44        public function evaluate()
45        {
46                if(is_string($this->survey))
47                {
48                        $result = Survey::get(array("uid" => $this->survey));
49                        if(!isset($result[0]))
50                                return false;
51                        $this->survey = $result[0];
52                }
53                if(is_string($this->respondent))
54                {
55                        $result = Respondent::get(array("uid" => $this->respondent));
56                        if(!isset($result[0]))
57                                return false;
58                        $this->respondent = $result[0];
59                }
60                if(!empty($this->answers) && is_string($this->answers[0]))
61                {
62                        $newanswers = array();
63                        foreach($this->answers as $answer)
64                        {
65                                $result = Answer::get(array("uid" => $answer));
66                                if(!isset($result[0]))
67                                        return false;
68                                $newanswers[] = $result[0];
69                        }
70                        $this->answers = $newanswers;
71                }
72                return true;
73        }
74
75
76        /**
77         * function save()
78         * Saves the current object into the database.
79         */
80        public function save()
81        {
82                //If evaluation fails, some references are incorrect.
83                //We shouldn't save in this case. Instead - let the user know. This function returns false if the evaluation has failed.
84                //TODO: Decide how to fix invalid references graciously.
85                if(!$this->evaluate())
86                        throw new Exception('Evaluation failed.');
87
88        //Ensure the required folder exists.
89                if(!is_dir('data/results/'))
90                        mkdir('data/results/');
91
92                $model = ResearchToolObject::load(AnswerSet::$filename);
93
94
95                $resourceAnswerSet = new Resource(ANSWERSET . '/' . $this->uid);
96                //Remove the old value stored with the given id
97                $model->subtract($model->find($resourceAnswerSet, null, null));
98
99                //Set the new values
100                $resourceAnswerSetType = new Resource(ANSWERSET);
101                $predicateRType = new Resource(RTYPE);
102                $model->add(new Statement($resourceAnswerSet, $predicateRType, $resourceAnswerSetType));
103
104                $answerSetId = new Literal($this->uid);
105                $predicateId = new Resource(UID);
106                $model->add(new Statement($resourceAnswerSet, $predicateId, $answerSetId));
107
108                $surveyId = new Literal($this->survey->uid);
109                $predicateSurvey = new Resource(FOR_SURVEY);
110                $model->add(new Statement($resourceAnswerSet, $predicateSurvey, $surveyId));
111
112                $respondentId = new Literal($this->respondent->uid);
113                $predicateRespondent = new Resource(BY_RESPONDENT);
114                $model->add(new Statement($resourceAnswerSet, $predicateRespondent, $respondentId));
115
116                $dateTime = new Literal($this->datetime->getTimestamp());
117                $predicateDateTime = new Resource(DATETIME);
118                $model->add(new Statement($resourceAnswerSet, $predicateDateTime, $dateTime));
119
120                if(isset($this->answers))
121                {
122                        foreach($this->answers as $answer)
123                        {
124                                $answerId = new Literal($answer->uid);
125                                $predicateAnswer = new Resource(GIVEN_ANSWER);
126                                $model->add(new Statement($resourceAnswerSet, $predicateAnswer, $answerId));
127                        }
128                }
129                $model->saveAs(AnswerSet::$filename, 'rdf');
130                return true;
131        }
132
133        /**
134         * function get()
135         * @param type $arguments : An array having one ore more of the following elements:
136         * 'uid', 'survey', 'respondent', 'datetime', 'answers'.
137         */
138        public static function get($arguments)
139        {
140                $model = ResearchToolObject::load(AnswerSet::$filename);
141
142                //Build the query string
143                $querystring = '
144                        PREFIX predicates: <' . SURVEYTOOL_PREDICATES_NAMESPACE . '>
145                        PREFIX resources: <' . SURVEYTOOL_RESOURCES_NAMESPACE . '>
146                        SELECT DISTINCT ?uid, ?for_survey, ?datetime ?by_respondent
147                        WHERE
148                        {
149                                _answerset      predicates:resource_type        resources:answerset ;
150                                predicates:uid ?uid ;
151                                predicates:for_survey ?for_survey ;
152                                predicates:by_respondent ?by_respondent ;
153                                predicates:datetime ?datetime ;
154                                ' . ResearchToolObject::createArguments($arguments) . '
155                        }';
156                //Query the model
157                $results = $model->sparqlQuery($querystring);
158                $answerSets = array();
159                if(!empty($results))
160                {
161                        foreach($results as $result)
162                        {
163                                $survey = $result['?for_survey']->label;
164                                $respondent = $result['?by_respondent']->label;
165                                $datetime = new DateTime();
166                                $datetime->setTimestamp(intval($result['?datetime']->label));
167                                $answers =      AnswerSet::getAnswers($model, $result['?uid']->label);
168                                $answerSets[] = new AnswerSet($result['?uid']->label, $survey, $respondent, $datetime, $answers);
169                        }
170                }
171                return $answerSets;
172        }
173
174        /**
175         * function getAnswers()
176         * @param type $uid : the uid for which the answers should be retrieved.
177         */
178        private static function getAnswers($model, $uid)
179        {
180                $result = $model->findRegex("[(".$uid.")]", "[(given_answer)]", null);
181                $iterator = $result->getStatementIterator();
182                $answers = array();
183                while($iterator->hasNext())
184                {
185                        $element = $iterator->next();
186                        $answers[] = $element->getLabelObject();
187                }
188                return $answers;
189        }
190}
191
Note: See TracBrowser for help on using the repository browser.