source: Dev/branches/jos-branch/server/classes/models/SurveyInstance.php @ 298

Last change on this file since 298 was 298, checked in by jkraaijeveld, 13 years ago

[Server] Made the models compliant with the Visio design in terms of ApplicationInstance?, SurveyInstance?, SessionInstance? and all of their fields.
[Server] Now stores references as RDF Resources for all models.
[Server] Changed some possible get() arguments to be more consistent.

File size: 8.5 KB
Line 
1<?php
2require_once 'rdfConstants.php';
3include(RDFAPI_INCLUDE_DIR . "RDFAPI.php");
4/**
5 * Description of SurveyInstance
6 *
7 * @author jkraaijeveld
8 */
9class SurveyInstance extends ResearchToolObject{
10    public static $filename = 'data/surveys/surveyinstances.rdf';
11   
12    public $survey;
13    public $starttime;
14    public $endtime;
15    public $open;
16    public $presetanswers;
17    public $answersets;
18
19    /**
20     * Constructor for a SurveyInstance object
21     * @param type $uid: The UID of the survey instance object.
22     * @param type $starttime: The starttime of the survey round.
23     * @param type $endtime: The endtime of the survey round.
24     * @param type $open: A boolean to specify whether the survey is open.
25     * @param type $presetanswers: A list of answers which are preset for everyone doing the survey.
26     * @param type $answersets: A list of answersets.
27     */
28        public function __construct($uid = null, $survey = null, $starttime = null, $endtime = null, $open = 0, $presetanswers = null, $answersets = null)
29    {
30        if(!isset($uid))
31        {
32                $uid = md5(uniqid(rand(), true));
33        }
34
35        $this->uid = $uid;
36        $this->survey = $survey;
37        $this->starttime = $starttime;
38        $this->endtime = $endtime;
39                $this->open = $open;
40        $this->presetanswers = $presetanswers;
41        $this->answersets = $answersets;
42        }
43
44
45    /**
46     * function evaluate()
47     * Evaluates the references in this object
48     */
49    public function evaluate()
50    {
51        if(is_string($this->survey))
52        {
53                        $surv = ResearchToolObject::stripUri($this->survey);
54            $result = Survey::get(array("uid" => $surv["uid"]));
55            if(!isset($result[0]))
56            {
57                return false;
58            }
59            $this->survey = $result[0];
60        }
61       
62        /* Check if all preset answers exist */
63        if(!empty($this->presetanswers) && is_string($this->presetanswers[0]))
64        {
65                $newPresets = array();
66                foreach($this->presetanswers as $answer)
67                {
68                                                $ans = ResearchToolObject::stripUri($answer);
69                        $result = Answer::get(array("uid" => $ans["uid"]));
70                        if(!isset($result[0]))
71                                return false;
72                        $newPresets[] = $result[0];
73                }
74                $this->presetanswers = $newPresets;
75        }
76
77        /* Check if all answersets exist */
78        if(!empty($this->answersets) && is_string($this->answersets[0]))
79        {
80                $newAnswerSets = array();
81                foreach($this->answersets as $answerSet)
82                {
83                                                $aset = ResearchToolObject::stripUri($answerSet);
84                        $result = AnswerSet::get(array("uid" => $aset["uid"]));
85                        if(!isset($result[0]))
86                        {
87                                return false;
88                        }
89                        $newAnswerSets[] = $result[0];
90                }
91                $this->answersets = $newAnswerSets;
92        }
93        return true;
94    }
95
96    /**
97     * function save()
98     * Saves the current object into the database.
99     */
100    public function save()
101    {
102        //If evaluation fails, some references are incorrect. We shouldn't save in this case.
103        //TODO: Decide how to fix invalid references graciously.
104        if(!$this->evaluate())
105                throw new Exception('Evaluation failed.');
106
107        //Ensure the required folder exists.
108        if(!is_dir('data/surveys/'))
109                mkdir('data/surveys/');
110
111        $model = ResearchToolObject::load(SurveyInstance::$filename);
112
113        $resourceSI = new Resource(SURVEYINSTANCE . '/' . $this->uid);
114        //Remove the old value stored with the given id
115        $model->subtract($model->find($resourceSI, null, null));
116
117        //Set the new values
118        $resourceSIType = new Resource(SURVEYINSTANCE);
119        $predicateRType = new Resource(RTYPE);
120        $model->add(new Statement($resourceSI, $predicateRType, $resourceSIType));
121
122        $SIID = new Literal($this->uid);
123        $predicateId = new Resource(UID);
124        $model->add(new Statement($resourceSI, $predicateId, $SIID));
125       
126        $SISurvey = new Resource(SURVEY . '/' . $this->survey->uid);
127        $predicateSurvey = new Resource(OF_SURVEY);
128        $model->add(new Statement($resourceSI, $predicateSurvey, $SISurvey));
129
130        $SIStartTime = new Literal($this->starttime->getTimestamp());
131        $predicateStartTime = new Resource(STARTTIME);
132        $model->add(new Statement($resourceSI, $predicateStartTime, $SIStartTime));
133
134        $SIEndTime = new Literal($this->endtime->getTimestamp());
135        $predicateEndTime = new Resource(ENDTIME);
136        $model->add(new Statement($resourceSI, $predicateEndTime, $SIEndTime));
137        $SIOpen = new Literal((bool) $this->open);
138        $predicateOpen = new Resource(OPEN);
139        $model->add(new Statement($resourceSI, $predicateOpen, $SIOpen));
140
141        if(isset($this->presetanswers))
142        {
143                foreach($this->presetanswers as $answer)
144                {
145                        $answerId = new Resource(ANSWER . '/' . $answer->uid);
146                        $predicateAnswer = new Resource(PRESET_ANSWER);
147                        $model->add(new Statement($resourceSI, $predicateAnswer, $answerId));
148                }
149        }
150
151        if(isset($this->answersets))
152        {
153                foreach($this->answersets as $answer)
154                {
155                        $answerSetId = new Resource(ANSWERSET . '/' . $answer->uid);
156                        $predicateAnswerSet = new Resource(HAS_ANSWERSET);
157                        $model->add(new Statement($resourceSI, $predicateAnswerSet, $answerSetId));
158                }
159        }
160        $model->saveAs(SurveyInstance::$filename, 'rdf');
161        return true;
162    }
163   /**
164        * function get($arguments)
165        * Gets the array of SurveyInstance objects belonging tothe arguments supplied.
166        * @param type $arguments: An array containing zero or more of the following keys:
167        *                                                 'uid', 'of_survey', 'starttime', 'endtime', 'open', 'preset_answers', 'answersets'
168        */
169        public static function get($arguments)
170        {
171                $model = ResearchToolObject::load(SurveyInstance::$filename);
172                //Build the query string
173                $querystring = '
174                        PREFIX predicates: <' . SURVEYTOOL_PREDICATES_NAMESPACE . '>
175                        PREFIX resources: <' . SURVEYTOOL_RESOURCES_NAMESPACE . '>
176                        SELECT DISTINCT ?uid, ?of_survey, ?starttime, ?endtime, ?open
177                        WHERE
178                        {
179                                _surveyinstance         predicates:resource_type        resources:surveyinstance;
180                                predicates:uid ?uid ;
181                                predicates:of_survey ?of_survey ;
182                                predicates:starttime ?starttime ;
183                                predicates:endtime ?endtime ;
184                                predicates:open ?open ;
185                                ' . ResearchToolObject::createArguments($arguments) . '
186                        }';
187                //Query the model
188                $results = $model->sparqlQuery($querystring);
189                //Create the corresponding SurveyInstance objects
190                $sInstances = array();
191                if(!empty($results))
192                {
193                        foreach($results as $result)
194                        {
195                                $startTime = new DateTime();
196                                $startTime->setTimestamp(intval($result['?starttime']->label));
197                                $endTime = new DateTime();
198                                $endTime->setTimestamp(intval($result['?endtime']->label));
199                                $open = (bool) $result['?open'];
200                                $fields = SurveyInstance::getFields($model, $result['?uid']->label);
201                                $sInstances[] = new SurveyInstance($result['?uid']->label, $result['?of_survey']->uri, $startTime, $endTime, $open, $fields[0], $fields[1]);
202                        }
203                }
204                return $sInstances;
205        }
206
207        /**
208         * function getFields()
209         * @param type $model : The RDF model to query against.
210         * @param type $uid : The UID of the SurveyInstance for which the preset answers and answersets should be retrieved.
211         * returns : an array with [0] => all preset answers and [1] => all answersets.
212         */
213        private static function getFields($model, $uid)
214        {
215                $result = $model->findRegex("[(".$uid.")]", "[(preset_answer)|(has_answerset)]", null);
216                $iterator = $result->getStatementIterator();
217                $answers = array();
218                $sets = array();
219                while($iterator->hasNext())
220                {
221                        $element = $iterator->next();
222                        if($element->getLabelPredicate() == PRESET_ANSWER)
223                                $answers[] = $element->getLabelObject();
224                        else if($element->getLabelPredicate() == HAS_ANSWERSET)
225                                $sets[] = $element->getLabelObject();
226                }
227                return array($answers, $sets);
228        }
229
230        /**
231         * Creates a new SurveyInstance object out of the given object.
232         */
233        public static function create($obj)
234        {
235                return new Survey($obj->uid, $obj->survey, $obj->starttime, $obj->endtime, $obj->open, $obj->presetanswers, $obj->answersets); 
236        }
237
238}
239
240?>
Note: See TracBrowser for help on using the repository browser.