Administrate.php 13.8 KB
Newer Older
Florent Chehab's avatar
Florent Chehab committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
<?php

include_once(APPPATH . 'core/My_Controller_with_login.php');

/**
 * This the controller used for form administration manipulations.
 * It's access is limited to connected user.
 */
class Administrate extends My_Controller_with_login
{
	/**
	 * This paramater has to be redefined so that ajax works correctly
	 */
		protected $className ="Administrate";

		/**
		 * Ajax redirector for this controller
		 * @param  string $redirect What function should treat the request.
		 * @param  JSONarray $data   The data sent to the server
		 * @return function call
		 */
		protected function ajaxRedirector($redirect,$data)
		// override the function in My controller with login
		{
			if ($redirect == 'ajaxGetAdmin'){
				return self::ajaxGetAdmin($data);
			} else if ($redirect == 'ajaxSaveAdmin'){
				return self::ajaxSaveAdmin($data);
			}

			return $this->JSONerror("No function fond for treating the request");
		}



		/**
		 * Function that lists all the forms that the user can administrate or those that he/she hasn't finished to build.
		 */
		public function index(){
			/// lists des formulaires auquels on peut accéder pour les résultats
			$this->load->model('Administrate_Model');

			$tmp = $this->Administrate_Model->administrate();
			if($tmp === $this->session->userErrorCode){
				self::errorRedirector('Welcome/errorSQL');
			}

			$finished = $tmp['finished'];
			$draft = $tmp['draft'];

			if (count($finished)===0){
				$finishedOutput = "Vous n'avez terminé aucun formulaire.";
			} else {

				$finishedOutput =  '<ul>';
				foreach ($finished as $form) {
					$title = htmlentities($form->title);
					$formId = $form->formid;
					$url = base_url("Administrate/admin/$formId");
					$finishedOutput.= '<li> <a href="'.$url.'">'.$title."</a></li>";
				}
				$finishedOutput .= '</ul>';
			}

			if (count($draft)===0){
				$draftOutput = "Vous avez terminé de construire tout vos formulaires.";
			} else {

				$draftOutput =  '<ul>';
				foreach ($draft as $form) {
					$title = htmlentities($form->title);
					$formId = $form->formid;
					$url = base_url("FormCreation/formTitle/$formId");
					$draftOutput.= '<li> <a href="'.$url.'">'.$title."</a></li>";
				}
				$draftOutput .= '</ul>';
			}


			$param = array(
				'finished'=>$finishedOutput,
				'draft'=>$draftOutput
			);

			$this->layouts->setTitle("Administrer un formulaire")
										->addView('administrate/administrate',$param)
										->display();

		}


		/**
		 * Function that lists all the form that the user can see the results of :
		 *  - his/her none-draft forms
		 *  - The forms where he has been granted access to for seeing results.
		 */
		public function results(){
			/// lists des formulaires auquels on peut accéder pour les résultats
			$this->load->model('Administrate_Model');

			$tmp = $this->Administrate_Model->seeResults();
			if($tmp === $this->session->userErrorCode){
				self::errorRedirector('Welcome/errorSQL');
			}

			$yours = $tmp['yours'];
			$others = $tmp['others'];

			if (count($yours)===0){
				$yourOutput = "Vous n'avez publié aucun formulaire.";
			} else {

				$yourOutput =  '<ul>';
				foreach ($yours as $form) {
					$title = htmlentities($form->title);
					$formId = $form->formid;
					$url = base_url("Administrate/showResults/$formId");
					$yourOutput.= '<li> <a href="'.$url.'">'.$title."</a></li>";
				}
				$yourOutput .= '</ul>';
			}

			if (count($others)===0){
				$othersOutput = "Vous ne pouvez voir les résultats d'aucun formulaire créé par d'autres personnes.";
			} else {

				$othersOutput =  '<ul>';
				foreach ($others as $form) {
					$title = $form->title;
					$formId = $form->formid;
					$url = base_url("Administrate/showResults/$formId");
132
					$othersOutput.= '<li> <a href="'.$url.'">'.$form->title."</a></li>";
Florent Chehab's avatar
Florent Chehab committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
				}
				$othersOutput .= '</ul>';
			}


			$param = array(
				'yours'=>$yourOutput,
				'others'=>$othersOutput
			);

			$this->layouts->setTitle("Répondre à un formulaire")
										->addView('administrate/results',$param)
										->display();
		}



		/**
		 * Function to show the results of a form
		 * The access to this function is obviously checked !
		 *
		 * @param  string $formId The id of the form to check (it's a string due to the URI process.)
		 */
		public function showResults($formId){
			$formId = intval($formId);
			/////////////////
			///////////////// security checks
			/////////////////
			$this->load->model('Administrate_Model');
			$title = $this->Administrate_Model->canSeeResults($formId);

			if($title === $this->session->userErrorCode){
				self::errorRedirector('Welcome/errorSQL');
			}
			if($title === false){
				self::errorRedirector('Welcome/errorNoSupport');
			}
			/////////////////
			/////////////////
			/////////////////



			// The user is allowed to access the part bellow if has passed the test

			$data = $this->Administrate_Model->getResults($formId);

			$this->load->model('FormCreation_model');
			$source = $this->FormCreation_model->getJSONformData($formId);

			if($data === false or $source===false){
				redirect('Welcome/errorNoSupport','location');
			} else if ($data === $this->session->userErrorCode or $source === $this->session->userErrorCode ){
				redirect('Welcome/errorSQL','location');
			}

			$this->load->library('ResultsBuilder');
			$result = $this->resultsbuilder->buildResults($data,$source);
			$this->load->helper('security');
			$result=$this->security->xss_clean($result);

			$param1 = array(
				'title'=>$title,
				'result' => $result,
				'formId' => $formId
			);

			$this->layouts->setTitle("Résultats")
										->addView('administrate/showResults',$param1)
										->addView('answer/script_confirm',array(),'bottom')
										->display();

		}




	/**
	 * Function to administrate a form
	 * The access to this function is obviously checked !
	 *
	 * @param  string $formId The id of the form to check (it's a string due to the URI process.)
	 */
	public function admin($formId){
		$formId = intval($formId);

		/////////////////
		///////////////// security checks
		/////////////////
		$this->load->model('Administrate_Model');
		$formTitle = $this->Administrate_Model->canAdministrate($formId);

		if($formTitle === $this->session->userErrorCode){
			self::errorRedirector('Welcome/errorSQL');
		}
		if($formTitle === false){
			self::errorRedirector('Welcome/errorNoSupport');
		}
		/////////////////
		/////////////////
		/////////////////


			$param = array(
				'id'=>$formId,
				'ajaxToken'=>$this->generateAjaxToken(),
				'ajaxLocation'=>self::ajaxLocation(),
				'mainSavingFormHandler' => 'ajaxSaveAdmin',
				'populateFormHandler' => 'ajaxGetAdmin',
			);

			$param2 = array(
				'formId'=>$formId,
				'title' => $formTitle,
				'shareUrl' => base_url("Answer/form/$formId")
			);

			$this->layouts->setTitle("Administration du formulaire $formId")
										->addView('administrate/admin',$param2)
										->addView('forms/scripts_formLibs',array(),'bottom')
										->addView('administrate/script_admin',$param,'bottom')
										->display();
	}



	/**
	 * Function to generate the administration form.
	 * This function will send the requested data back only if the user has the authorization to access it.
	 *
	 * @param  array $data  The data sent by the user trough ajax
	 */
	private function ajaxGetAdmin($data)
	{
		$formId = intval($data["id"]);
		/////////////////
		///////////////// security checks
		/////////////////
		$this->load->model('Administrate_Model');
		$test = $this->Administrate_Model->canAdministrate($formId);

		if($test === $this->session->userErrorCode){
			return $this->JSONerror('Erreur SQL, merci de contacter les admins');
		}
		if($test === false){
			return $this->JSONerror('VOUS NE POUVEZ PAS ACCÉDER À CES INFORMATIONS',false);
		}
		///////////////
		/////////////// Access check finished
		///////////////





		$this->load->model('FormCreation_model');
		$data = $this->FormCreation_model->getFormInfo($formId);
		if($data === $this->session->userErrorCode){
			return $this->JSONerror("Erreur lors de l'interrogation de la base de donnée, merci de contacter les administrateurs du site.");
		}

		$closeDate = $data->closedate;
		$publicJSONsource = $data->publicjsonsource;

		$this->load->library('tools');
		$closeDate = $this->tools->timestampToDate($closeDate);


		$this->load->model('Groupform_Model');
		$groupsThatCanAccess = $this->Groupform_Model->accessGroupForm($formId,false);
		$groupsCurrentlyAccessing = $this->Groupform_Model->groupsAccessingForm($formId);
		$groupsCanSeeResults=$this->Administrate_Model->getGroups();
		$groupsCurrentlySeeingResults = $this->Administrate_Model->groupsAccessingResults($formId);

		if($groupsThatCanAccess === $this->session->userErrorCode
		or $groupsCurrentlyAccessing === $this->session->userErrorCode
		or $groupsCanSeeResults === $this->session->userErrorCode
		or $groupsCurrentlySeeingResults === $this->session->userErrorCode
		)	return $this->JSONerror("Erreur lors de l'interrogation de la base de donnée, merci de contacter les administrateurs du site.");

		// building the awsome selector
		$this->load->library('FormBuilder');
		$form = $this->formbuilder->adminSelect("FormAccess",false)
															->addMultiple()
															->setFieldLabel("Quels sont les groupes d'utilisateurs⋅rices qui peuvent répondre à ce formulaire ?")
															->setFieldPlaceholder("Groupes disponibles")
															->addGroup("Groupes principaux");

		foreach ($groupsThatCanAccess['mainGroups'] as $element) {
			$id = $element->groupid;
			$form = $form -> addGroupOption(htmlspecialchars($element->title),$id,isset($groupsCurrentlyAccessing[$id]));
		}
		$form = $form->closeGroup()
									->addGroup("Autres groupes administratifs");

		foreach ($groupsThatCanAccess['otherAdministrativeGroups'] as $element) {
			$id = $element->groupid;
			$form = $form -> addGroupOption(htmlspecialchars($element->title),$id,isset($groupsCurrentlyAccessing[$id]));
		}
		$form = $form->closeGroup()
									->addGroup("Vos groupes");

		foreach ($groupsThatCanAccess['yourGroups'] as $element) {
			$id = $element->groupid;
			$form = $form -> addGroupOption(htmlspecialchars($element->title),$id,isset($groupsCurrentlyAccessing[$id]));
		}
		$form = $form->closeGroup()
									->addGroup("Autres groupes auxquels vous appartenez");

		foreach ($groupsThatCanAccess['otherGroupsYouBelongTo'] as $element) {
			$id = $element->groupid;
			$form = $form -> addGroupOption(htmlspecialchars($element->title).' (créé par '.htmlspecialchars($element->login).')',$id,isset($groupsCurrentlyAccessing[$id]));
		}
		$form = $form->closeGroup()
									->closeField()
									->adminSelect("FormResults",false)
									->addMultiple()
									->setFieldLabel("Quels sont les groupes d'utilisateurs⋅rices qui peuvent accéder aux résultats de ce formulaire ? (Parmi ceux que vous avez créés, ou créés par d'autres et auxquels vous appartenez)")
									->setFieldPlaceholder("Groupes disponibles")
									->addGroup("Vos groupes");


			foreach ($groupsCanSeeResults['yours'] as $element) {
				$id = $element->groupid;
				$form = $form -> addGroupOption(htmlspecialchars($element->title),$id,isset($groupsCurrentlySeeingResults[$id]));
			}
			$form = $form->closeGroup()
										->addGroup("Autres groupes auxquels vous appartenez");

			foreach ($groupsCanSeeResults['others'] as $element) {
				$id = $element->groupid;
				$form = $form -> addGroupOption(htmlspecialchars($element->title).' (créé par '.htmlspecialchars($element->creator).')',$id,isset($groupsCurrentlySeeingResults[$id]));
			}
			$form = $form->closeGroup()
										->closeField();

			$form = $form->date('closeDate',true,$closeDate)
									->setFieldLabel("À quelle date souhaitez-vous clore le formulaire ? (La clôture s'effectuera à 23h59)")
									->closeField()
									->radio("publicSource")
									->setFieldLabel("Souhaitez-vous que le code source de votre formulaire soit disponible auprès de l'ensemble des utilisateurs⋅rices pour qu'ils⋅elles puissent l'utiliser comme base ?")
									->addRadioOption("Oui, je le partage.",'true',$publicJSONsource)
									->addRadioOption("Non, je ne le partage pas.",'false',!$publicJSONsource)
									->closeField()
									->getFormAndPopulate();

		return $this->JSONsuccess($form);
	}





	/**
	 * Function to save the form generated
	 *
	 * @param  array $data  The data sent by the user trough ajax
	 */
	private function ajaxSaveAdmin($data)
	{
			$dataFromForm = $data["dataFromForm"];
			$results = $dataFromForm["results"];
			$formId = intval($data["id"]);
			/////////////////
			///////////////// security checks
			/////////////////

			$this->load->model('Administrate_Model');
			$test = $this->Administrate_Model->canAdministrate($formId);

			if($test === $this->session->userErrorCode){
				return $this->JSONerror('Erreur SQL, merci de contacter les admins');
			}
			if($test === false){
				return $this->JSONerror('VOUS NE POUVEZ PAS ACCÉDER À CES INFORMATIONS',false);
			}



			///////////////
			/////////////// Access check finished
			///////////////

			// automatic validation
			$test = $this->validateReturnedFormData($data);
			if ($test !== true){
				return $this->JSONerror($test);
			}

			$accessGroups = $results['FormAccess'];
			$closeDate = $results['closeDate'];
			$accessResults = $results['FormResults'];
			$publicSource = $results['publicSource'];

			$this->load->library("tools");
			$accessGroups = $this->cleanGroupResults($accessGroups);
			$accessResults = $this->cleanGroupResults($accessResults);

			$publicSource = $publicSource === 'true';
			$closeDate = $this->tools->dateToTimestamp($closeDate);

			$this->load->model('Administrate_Model');

			if ($this->Administrate_Model->administrateForm($formId, $publicSource,$closeDate,$accessGroups,$accessResults) === true){
					return $this->JSONsuccess();
			} else {
				return $this->JSONerror("Erreur lors de l'interrogation de la base de donnée, merci de contacter les administrateurs du site.");
			}

	}

}