Form.php 33.6 KB
Newer Older
1 2 3 4
<?php

class Form {
	const COLLECTION = "forms";
Raph El's avatar
Raph El committed
5
	const CONTROLLER = "forms";
Tibor Katelbach's avatar
Tibor Katelbach committed
6
	const ANSWER_COLLECTION = "answers";
Clément Damiens's avatar
 
Clément Damiens committed
7
	const ANSWER_CONTROLLER = "answer";
Tibor Katelbach's avatar
Tibor Katelbach committed
8 9
	const ICON = "fa-list-alt";
	const ICON_ANSWER = "fa-calendar-check-o";
10

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
	public static $riskWeight = array(
		"11" => array( "w" => 1 , "c" => "lightGreen"),
		"12" => array( "w" => 2 , "c" => "lightGreen"),
		"13" => array( "w" => 3 , "c" => "lightGreen"),
		"14" => array( "w" => 4 , "c" => "orange"),
		"21" => array( "w" => 5 , "c" => "lightGreen"),
		"22" => array( "w" => 6 , "c" => "lightGreen"),
		"23" => array( "w" => 7 , "c" => "orange"),
		"24" => array( "w" => 8 , "c" => "red"),
		"31" => array( "w" => 9 , "c" => "lightGreen"),
		"32" => array( "w" => 10 , "c" => "orange"),
		"33" => array( "w" => 11 , "c" => "red"),
		"34" => array( "w" => 12 , "c" => "red"),
		"41" => array( "w" => 13 , "c" => "orange"),
		"42" => array( "w" => 14 , "c" => "red"),
		"43" => array( "w" => 15 , "c" => "red"),
		"44" => array( "w" => 16 , "c" => "red")
	);
Tibor Katelbach's avatar
Tibor Katelbach committed
29
	
Tibor Katelbach's avatar
tweak  
Tibor Katelbach committed
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
	public static $inputTypes = [
	 	"text" 		=> "Text : petit text court",
	 	"textarea" 	=> "Textarea : Grande zone de texte",
		//"button"    => "button",
		"tpls.forms.checkbox"  => "checkbox : Case à cocher",
		"color"     => "color : Selectionner une couleur",
		"date"      => "date : Selectionner une date",
		"datetime-local" => "datetime-local : Selectionner une date et heure",
		"month" 	=> "Choisir un mois",
		"week" 		=> "week : Choisir un semaine",
		"time" 		=> "time : Ajouter une heure",
		"email" 	=> "Remplir un email",
		//"image" 	=> "Ajouter une image",
		"number" 	=> "Choisir un nombre",
		"radio" 	=> "radio : Choix unique",
		//"range" 	=> "range : ",
		"tel" 		=> "tel : Ajouter un Telephone",
		"url" 		=> "url : Ajouter un lien internet",
		"tags" 		=> "tags : Ajouter des tags",
		"tpls.forms.select"	=>"select : ajouter une liste de choix",
		"tpls.forms.cplx.calendar" =>"liste d'actions clefs avec des dates",
		"tpls.forms.cplx.partner" =>"Les partenaires et leurs engagements réciproques",
		"tpls.forms.cplx.budget"	=> "Liste de dépense",
		"tpls.forms.cplx.financement" =>"Liste de Financement",
		"tpls.forms.cplx.financementFromBudget" =>"Liste de Financement réutilisant les budgets",
55
		"tpls.forms.cplx.suiviFromBudget" =>"suivi de travaux basé sur les budgets",
Tibor Katelbach's avatar
tweak  
Tibor Katelbach committed
56 57 58 59 60 61 62 63
		"tpls.forms.cplx.indicateurs" =>"Liste d'Indicateur",
		"tpls.forms.cplx.element" =>"Créer un élément Person , Organisation, Projet,...",
		"tpls.forms.cplx.stepValidation" =>"Step Validation by Roles",
		"tpls.forms.cplx.generatePDF" =>"Generate PDF",
		"tpls.forms.cplx.address" =>"Geocode an address",
		"tpls.forms.cplx.regle" =>"règle d'attribution",
		"tpls.forms.cplx.multiCheckbox" =>"Liste of checkboxes",
		"sectionTitle" 		=> "Séparateur de Section avec Titre",
Anatole Rakotoson's avatar
sublist  
Anatole Rakotoson committed
64 65 66 67
		"tpls.forms.cplx.subList" 		=> "sublist : subliste",
        "tpls.forms.cplx.list" 		=> "list : liste",
        "tpls.forms.cplx.multiList" 		=> "multiList : multiListe"

Tibor Katelbach's avatar
tweak  
Tibor Katelbach committed
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
	 /*
	[X] author view pod 
    [X] add element
      [X] create new element 
      [X] limit to fixed number of elements
      [X] connect existing one
      [X] connect with the answer in an afterSave 
      [X] multiple element block in page with different types 
    [X] text [[~d/modules/costum/views/tpls/forms/text.php]] 
    [X] select [[~d/modules/costum/views/tpls/forms/select.php]]
      * TODO : dynform add key value question for list / or value list 
    [X] tags  [[~d/modules/costum/views/tpls/forms/text.php]]
      * BUG design
      * TODO : dynform add key value question for list / or value list 
    [X] calendar :oneByone: SAve [[~d/modules/costum/views/tpls/forms/cplx/calendar.php]]
    * BUG cannot have 2 calendars in the same time
    [X] multi checkbox  : multicheckbox
    [ ] finder 
      [ ] communityList 
    * link to openForm and connect to answer
    [ ] open select 
      * new options can be added to the list , 
      * other peoples answers become options, 
      * or my old options become answers
    [ ] wysiwyg
    [ ] markdown
    [ ] locality
    [ ] image
    [ ] tagList
    [ ] postalcode
    [ ] arrayForm
    [ ] array
    [ ] properties
	 */
103 104
	public static function newAnswer($data)
	{
Tibor Katelbach's avatar
Tibor Katelbach committed
105
		try{
106
	
107 108
			$answer = array(
				"formId"=>$data["id"],
Tibor Katelbach's avatar
Tibor Katelbach committed
109 110
				"user"=>$data["user"],
				"session"=>$data["session"],
111 112
				"name"=>$data["name"],
				"email"=>$data["email"],
Tibor Katelbach's avatar
tweak  
Tibor Katelbach committed
113
				"step" => "dossier",
114 115
				"created"=>time()
			);
thomas craipeau's avatar
thomas craipeau committed
116 117 118 119 120
			$costum = CacheHelper::getCostum();
			if( isset($costum) && 
                isset($costum["slug"]) ){
                $answer["source"] = array(   "key" => $costum["slug"],
                                            "keys" => array($costum["slug"]),
Raph El's avatar
Hotfix  
Raph El committed
121 122
                                            "insertOrign" => "costum") ;
            }
123 124 125 126 127 128 129 130
			PHDB::insert( self::ANSWER_COLLECTION, $answer);
			return array( "result" => true,
						 "answer" => $answer );
		} catch (CTKException $e){
   			return $e->getMessage();
  		}
	}

131 132
	public static function save($id,$data)
	{
133 134
		try
		{
135 136 137 138
			$step = $data["formId"];
			unset($data["formId"]);
			unset($data["parentSurvey"]);
			$data["created"] = time();
Clément Damiens's avatar
 
Clément Damiens committed
139
			return PHDB::update( self::ANSWER_COLLECTION,
Tibor Katelbach's avatar
Tibor Katelbach committed
140
                    array( "_id" => new MongoId((string)$id)), 
141
                    array( '$set' => array( "answers.".$step => $data)));
Tibor Katelbach's avatar
Tibor Katelbach committed
142 143 144
		} catch (CTKException $e){
   			return $e->getMessage();
  		}
145
    }
146 147 148 149

    public static function delAnswer($id)
    {
		try {
Clément Damiens's avatar
 
Clément Damiens committed
150 151
			Document::removeAllForElement($id, self::ANSWER_COLLECTION);
			return PHDB::remove( self::ANSWER_COLLECTION,
152 153 154 155 156 157
                    array( "_id" => new MongoId((string)$id)));
		} catch (CTKException $e){
   			return $e->getMessage();
  		}
    }

Tibor Katelbach's avatar
tweaks  
Tibor Katelbach committed
158
    public static function countStep($idParent){
Raph El's avatar
Raph El committed
159
    	return PHDB::count( self::COLLECTION, array("parentForm"=>$idParent));
Clément Damiens's avatar
 
Clément Damiens committed
160
    }
Tibor Katelbach's avatar
Tibor Katelbach committed
161
 
Raph El's avatar
Raph El committed
162 163
    public static function getById($parentForm, $fields=array()){
    	return PHDB::findOne( self::COLLECTION, array("id"=>$parentForm), $fields);
Raph El's avatar
Raph El committed
164 165 166 167
    }

    public static function getByIdMongo($id,$fields=array()){
    	return PHDB::findOne(self::COLLECTION,array("_id"=>new MongoId($id)), $fields);
Raph El's avatar
Modif  
Raph El committed
168 169
    }

Clément Damiens's avatar
 
Clément Damiens committed
170 171 172 173 174 175
    public static function canEditAnswerById($id){
    	$ans=self::getAnswerById($id);
    	$form = PHDB::findOne( Form::COLLECTION , array("id"=>$ans["formId"]));
		$parent = Slug::getElementBySlug($form["id"]);
		return self::canEditAnswer(Yii::app()->session["userId"], $ans, $form, $parent);
	}
Raph El's avatar
Raph El committed
176 177 178 179
    public static function getAnswerById($id,$fields=array()){
    	return PHDB::findOne(self::ANSWER_COLLECTION,array("_id"=>new MongoId($id)), $fields);
    }

Raph El's avatar
Raph El committed
180 181
    public static function getLinksById($id){
    	return self::getByIdMongo($id,array("links"));
Clément Damiens's avatar
 
Clément Damiens committed
182
    }
Raph El's avatar
Raph El committed
183

Raph El's avatar
Raph El committed
184
    public static function getLinksFormsByFormId($id, $type="all", $role=null) {
Raph El's avatar
Raph El committed
185 186 187 188 189 190 191
	  	$res = array();
	  	
	  	$form = self::getLinksById($id);

	  	if (empty($form)) {
            throw new CTKException(Yii::t("form", "The form id is unkown : contact your admin"));
        }
Raph El's avatar
Raph El committed
192
	  	if (isset($form) && isset($form["links"]) && isset($form["links"]["Form"])) {
Raph El's avatar
Raph El committed
193
	  		$members=array();
Raph El's avatar
Raph El committed
194
	  		foreach($form["links"]["Form"] as $key => $member){
Raph El's avatar
Raph El committed
195 196 197 198 199 200 201
	  		 	if(!@$member["toBeValidated"] && !@$member["isInviting"])
	  		 		$members[$key]= $member;
	  		}
	  		//No filter needed
	  		if ($type == "all") {
	  			return $members;
	  		} else {
Raph El's avatar
Raph El committed
202
	  			foreach ($form["links"]["Form"] as $key => $member) {
Raph El's avatar
Raph El committed
203
		            if ($member['type'] == $type) {
Raph El's avatar
Modif  
Raph El committed
204 205 206 207 208 209 210 211 212 213 214 215
		            	if ( !empty($role) && @$member[$role] == true ) {

			            	if($role=="isAdmin"){
			            		if(!@$member["isAdminPending"] && !@$member["toBeValidated"] && !@$member["isInviting"] && $member["isAdmin"] == true)
			            			$res[$key] = $member;	
			            	} else {
			                	$res[$key] = $member;

			            	}
			            } else if(empty($role) && !@$member["toBeValidated"] && !@$member["isInviting"]){
			            	$res[$key] = $member;
			            }
Raph El's avatar
Raph El committed
216
		            }
Raph El's avatar
Modif  
Raph El committed
217 218

		           
Raph El's avatar
Raph El committed
219 220 221 222 223
	        	}
	  		}
	  	}
	  	return $res;
	}
Raph El's avatar
Raph El committed
224

225
	public static function listForAdminNews($form, $answers = array() ){
Raph El's avatar
Modif  
Raph El committed
226 227 228 229 230
		$results = array();
		$uniq = array();
		$uniqO = array();
		$uniqP = array();
		$uniqE = array();
231 232 233 234 235 236 237 238

		$scenario = array();
		

		foreach ( $form["scenario"] as $key => $value) {
			$scenario[$key] = false;
		}

Raph El's avatar
Hotfix  
Raph El committed
239
		//Rest::json($answers);exit ;
Tibor Katelbach's avatar
Tibor Katelbach committed
240
		foreach ( $answers as $key => $value) {
Raph El's avatar
Hotfix  
Raph El committed
241 242 243
			if(empty($results[ $value["user"] ]))
				$results[ $value["user"] ] = array("userId" => $value["user"]);

Tibor Katelbach's avatar
Tibor Katelbach committed
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
			if( !empty($value["answers"]) && 
				!empty($value["answers"][Organization::CONTROLLER]) && 
				!in_array( $value["answers"][Organization::CONTROLLER]["id"], $uniqO )  && 
				( 	empty($results[$value["user"]]) || 
					(!empty($results[$value["user"]]) && empty($results[$value["user"]]["parentId"]) ) ) ) {

					$orga = Element::getElementById($value["answers"][Organization::CONTROLLER]["id"], Organization::COLLECTION, null, array("name", "email"));
					$ans["parentId"] = $value["answers"][Organization::CONTROLLER]["id"];
					$ans["parentType"] = Organization::COLLECTION;
					$ans["parentName"] = $orga["name"];
					$ans["userId"] = $value["user"];
					$results[$value["user"]] = $ans;
				
				$uniqO[] = $value["answers"][Organization::CONTROLLER]["id"];
			}
Raph El's avatar
Raph El committed
259

Tibor Katelbach's avatar
Tibor Katelbach committed
260 261 262 263
			if( !empty($value["answers"]) && 
				!empty($value["answers"][Project::CONTROLLER]) && 
				!in_array( $value["answers"][Project::CONTROLLER]["id"], $uniqP ) ){

Raph El's avatar
Raph El committed
264
				$orga = Element::getElementById($value["answers"][Project::CONTROLLER]["id"], Project::COLLECTION, null, array("name", "email", "shortDescription", "shortDescription"));
Tibor Katelbach's avatar
Tibor Katelbach committed
265 266 267 268 269 270 271 272 273 274 275 276 277
				$orga["id"] = $value["answers"][Project::CONTROLLER]["id"];
				$orga["type"] = Project::COLLECTION;

				if(!empty($value["answers"][Project::CONTROLLER]["parentId"])){
					$orga["parentId"] = $value["answers"][Project::CONTROLLER]["parentId"];
					$orga["parentType"] = Element::getCollectionByControler($value["answers"][Project::CONTROLLER]["parentType"]);
					$parent = Element::getSimpleByTypeAndId($orga["parentType"], $orga["parentId"]);
					$orga["parentName"] = $parent["name"];
				}else{
					$answersParent = PHDB::findOne( Form::ANSWER_COLLECTION , 
										array("parentSurvey"=>@$value["parentSurvey"], 
												"answers.organization" => array('$exists' => 1),
												"user" => $value["user"]) );
Raph El's avatar
Raph El committed
278
					
Tibor Katelbach's avatar
Tibor Katelbach committed
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
					if( !empty($value["answers"]) && 
						!empty($value["answers"][Organization::CONTROLLER]) && 
						!in_array( $value["answers"][Organization::CONTROLLER]["id"], $uniqO )  && 
						( 	empty($results[$value["user"]]) || 
							(!empty($results[$value["user"]]) && empty($results[$value["user"]]["parentId"]) ) ) ) {

							$orga = Element::getElementById($value["answers"][Organization::CONTROLLER]["id"], Organization::COLLECTION, null, array("name", "email"));
							$ans["parentId"] = $value["answers"][Organization::CONTROLLER]["id"];
							$ans["parentType"] = Organization::COLLECTION;
							$ans["parentName"] = $orga["name"];
							$ans["userId"] = $value["user"];
							$results[$value["user"]] = $ans;
						
						$uniqO[] = $value["answers"][Organization::CONTROLLER]["id"];
					}

					if( !empty($value["answers"]) && 
						!empty($value["answers"][Project::CONTROLLER]) && 
						!in_array( $value["answers"][Project::CONTROLLER]["id"], $uniqP ) ){

						$orga = Element::getElementById($value["answers"][Project::CONTROLLER]["id"], Project::COLLECTION, null, array("name", "email"));
						$orga["id"] = $value["answers"][Project::CONTROLLER]["id"];
						$orga["type"] = Project::COLLECTION;

						if(!empty($value["answers"][Project::CONTROLLER]["parentId"])){
							$orga["parentId"] = $value["answers"][Project::CONTROLLER]["parentId"];
							$orga["parentType"] = Element::getCollectionByControler($value["answers"][Project::CONTROLLER]["parentType"]);
							$parent = Element::getSimpleByTypeAndId($orga["parentType"], $orga["parentId"]);
							$orga["parentName"] = $parent["name"];
						}else{
							$answersParent = PHDB::findOne( Form::ANSWER_COLLECTION , 
												array("parentSurvey"=>@$value["parentSurvey"], 
														"answers.organization" => array('$exists' => 1),
														"user" => $value["user"]) );
							
							$orga["parentId"] = $answersParent["answers"][Organization::CONTROLLER]["id"];
							$orga["parentType"] = Organization::COLLECTION;
							$orga["parentName"] = $answersParent["answers"][Organization::CONTROLLER]["name"];
						}

						$orga["userId"] = $value["user"];
						$orga["userName"] = $value["name"];
						
						$results[ $value["user"] ]["id"] = @$orga["id"];
						$results[ $value["user"] ]["type"] = @$orga["type"];
						$results[ $value["user"] ]["name"] = @$orga["name"];
						$results[ $value["user"] ]["email"] = @$orga["email"];
						$results[ $value["user"] ]["parentId"] = @$orga["parentType"];
						$results[ $value["user"] ]["parentName"] = @$orga["parentName"];
						$results[ $value["user"] ]["userId"] = @$orga["userId"];
						$results[ $value["user"] ]["userName"] = @$orga["userName"];

						$uniqP[] = $value["answers"][Project::CONTROLLER]["id"];
					}


					if ( !empty($results[$value["user"]]) ) {
						if ( empty($results[$value["user"]]["scenario"]) )
							$results[$value["user"]]["scenario"] = $scenario;
						//var_dump($results[$value["user"]]); echo "</br></br>";
						if ( isset($results[$value["user"]]["scenario"][$value["formId"]]) )
							$results[$value["user"]]["scenario"][$value["formId"]] = true;
					}
342

Raph El's avatar
Raph El committed
343
				}
Tibor Katelbach's avatar
Tibor Katelbach committed
344 345 346 347 348 349 350 351 352 353 354 355 356

				$orga["userId"] = $value["user"];
				$orga["userName"] = $value["name"];
				
				$results[ $value["user"] ]["id"] = @$orga["id"];
				$results[ $value["user"]]["type"] = @$orga["type"];
				$results[ $value["user"]]["name"] = @$orga["name"];
				$results[ $value["user"]]["email"] = @$orga["email"];
				$results[ $value["user"]]["parentId"] = @$orga["parentType"];
				$results[ $value["user"]]["parentName"] = @$orga["parentName"];
				$results[ $value["user"]]["userId"] = @$orga["userId"];
				$results[ $value["user"]]["userName"] = @$orga["userName"];

Raph El's avatar
Raph El committed
357 358 359 360 361
				if(!empty($orga["shortDescription"]) )
					$results[ $value["user"]]["desc"] = $orga["shortDescription"];
				else if(!empty($orga["description"]) )
						$results[ $value["user"]]["desc"] = $orga["description"];

Tibor Katelbach's avatar
Tibor Katelbach committed
362 363 364
				$uniqP[] = $value["answers"][Project::CONTROLLER]["id"];
			}

Raph El's avatar
Hotfix  
Raph El committed
365
			//var_dump($value["name"]);echo "<br/>";
Tibor Katelbach's avatar
Tibor Katelbach committed
366 367 368 369
			if ( !empty($results[$value["user"]]) ) {

				if ( empty($results[$value["user"]]["scenario"]) )
					$results[$value["user"]]["scenario"] = $scenario;
Raph El's avatar
Hotfix  
Raph El committed
370 371

				if ( isset( $results[$value["user"]]["scenario"][$value["formId"]] ) )
Tibor Katelbach's avatar
Tibor Katelbach committed
372
					$results[$value["user"]]["scenario"][$value["formId"]] = true;
373 374
			}
		}
Raph El's avatar
Hotfix  
Raph El committed
375
		// exit;
376
		// Rest::json($results);exit ;
Raph El's avatar
Raph El committed
377 378 379
		return $results ;	
	}

Tibor Katelbach's avatar
Tibor Katelbach committed
380 381
	//rebuild answerList 
	// by  adding organizing organization (id,type) and project (id,type)
382 383
	public static function listForAdmin($answers){
		//Rest::json($answers); exit ;
Raph El's avatar
Raph El committed
384
		$uniq = array();
Raph El's avatar
Hotfix  
Raph El committed
385
		$res = array();
386 387 388
		if(!empty($answers)){
			foreach ( $answers as $key => $value) {
				$new = $value ;
Tibor Katelbach's avatar
Tibor Katelbach committed
389
				if( @$value["answers"] ){
390 391
				foreach ( $value["answers"] as $keyA => $valA) {
					
Raph El's avatar
Raph El committed
392
					
Raph El's avatar
Raph El committed
393
					if( !empty($valA["answers"][Organization::CONTROLLER]) && !empty($valA["answers"][Organization::CONTROLLER]["id"])){
Raph El's avatar
Raph El committed
394 395
						$orga = Element::getElementById($valA["answers"][Organization::CONTROLLER]["id"], Organization::COLLECTION, null, array("name", "email", "shortDescription"));
						$orga["id"] = $valA["answers"][Organization::CONTROLLER]["id"];
396 397 398
						$orga["type"] = Organization::COLLECTION;
						$new[Organization::CONTROLLER] = $orga;
					}
Raph El's avatar
Modif  
Raph El committed
399

Raph El's avatar
Raph El committed
400
					if( !empty($valA["answers"][Project::CONTROLLER]) && !empty($valA["answers"][Project::CONTROLLER]["id"])  ){
Raph El's avatar
Raph El committed
401 402
						$project = Element::getElementById($valA["answers"][Project::CONTROLLER]["id"], Project::COLLECTION, null, array("name", "email", "shortDescription"));
						$project["id"] = $valA["answers"][Project::CONTROLLER]["id"];
403 404 405
						$project["type"] = Project::COLLECTION;
						$new[Project::CONTROLLER] = $project;
					}
Raph El's avatar
Raph El committed
406
				}
Tibor Katelbach's avatar
Tibor Katelbach committed
407
			}
408
				$res[$key] = $new ;
Raph El's avatar
Modif  
Raph El committed
409 410 411
			}
		}

412 413
		//Rest::json($res); exit ;
		return $res ;	
Raph El's avatar
Modif  
Raph El committed
414
	}
Raph El's avatar
Raph El committed
415

Raph El's avatar
Raph El committed
416
	
Clément Damiens's avatar
Clément Damiens committed
417 418 419
	public static function canSeeAnswer($userId, $answer, $form, $parentForm){
		if(self::canEditAnswer($userId, $answer, $form, $parentForm))
			return true;
420 421
		else if(Costum::isSameFunction("canSeeAnswer", array("answer"=>$answer)))
			return Costum::sameFunction("canSeeAnswer", array("answer"=>$answer));
Clément Damiens's avatar
Clément Damiens committed
422 423
		return false;
	}
Clément Damiens's avatar
 
Clément Damiens committed
424

Clément Damiens's avatar
Clément Damiens committed
425 426 427 428 429
	public static function canEditAnswer($userId, $answer, $form, $parentForm){
		if(self::canAdmin((string)$form["_id"], $form))
			return true;
		else if($answer["user"] == $userId)
			return true;
430
		else if(Authorisation::canEditItem(Yii::app()->session["userId"], $parentForm["type"], $parentForm["id"] ))
Clément Damiens's avatar
Clément Damiens committed
431
			return true;
432 433 434 435
		// else if(Costum::sameFunction("canEditAnswer", array("answer"=>$answer)))
		// 	return true;
		else if(Costum::isSameFunction("canEditAnswer", array("answer"=>$answer)))
			return Costum::sameFunction("canEditAnswer", array("answer"=>$answer));
Clément Damiens's avatar
Clément Damiens committed
436 437 438
		
		return false;
	}
439

Raph El's avatar
Raph El committed
440
	public static function canAdmin($id, $form = array()){
Tibor Katelbach's avatar
Tibor Katelbach committed
441 442
		if(empty($form) && @$id)
			$form = PHDB::findOne( Form::COLLECTION , array("_id"=>new MongoId($id)));
Raph El's avatar
Raph El committed
443 444

		$res = false;
Raph El's avatar
Raph El committed
445
		if(	Yii::app()->session["userId"] == $form["author"] ||
446
			Yii::app()->session["userId"] == $form["author"] ||
Raph El's avatar
Raph El committed
447 448
			(	!empty($form["links"]["members"][Yii::app()->session["userId"]]) && 
				!empty($form["links"]["members"][Yii::app()->session["userId"]]["isAdmin"]) &&
Raph El's avatar
Raph El committed
449 450
				$form["links"]["members"][Yii::app()->session["userId"]]["isAdmin"] == true /*&&
				 !empty($form["links"]["members"][Yii::app()->session["userId"]]["roles"]) &&
451 452 453 454 455
				in_array("TCO", $form["links"]["members"][Yii::app()->session["userId"]]["roles"]) */ ) 
			||
			(	!empty( $form["links"]["contributors"][Yii::app()->session["userId"]] ) && 
				!empty( $form["links"]["contributors"][Yii::app()->session["userId"]]["isAdmin"] ) &&
				$form["links"]["contributors"][Yii::app()->session["userId"]]["isAdmin"] == true )      ){
Raph El's avatar
Raph El committed
456
    		$res = true;
Raph El's avatar
Raph El committed
457
    		
Clément Damiens's avatar
Clément Damiens committed
458
        } else if(Authorisation::isInterfaceAdmin()){
Raph El's avatar
Raph El committed
459
			$res = true;
Raph El's avatar
Raph El committed
460 461
		} else if (Authorisation::isParentAdmin($id, Form::COLLECTION , Yii::app()->session["userId"], $form) )
			$res = true;
Raph El's avatar
Raph El committed
462 463 464
        return $res ;
	}

Raph El's avatar
Raph El committed
465
	public static function canAdminRoles($id, $role, $form = array() ){
466
		if(empty($form))
Tibor Katelbach's avatar
Tibor Katelbach committed
467
			$form = PHDB::findOne( Form::COLLECTION , array("_id"=>new MongoId($id)));
Raph El's avatar
Raph El committed
468 469 470 471 472 473 474 475 476 477

		$res = false;
		if( !empty($form["links"]) && 
			!empty($form["links"]["members"]) && 
			!empty($form["links"]["members"][Yii::app()->session["userId"]]) &&
			!empty($form["links"]["members"][Yii::app()->session["userId"]]["isAdmin"]) &&
			$form["links"]["members"][Yii::app()->session["userId"]]["isAdmin"] == true &&
			!empty($form["links"]["members"][Yii::app()->session["userId"]]["roles"]) &&
			in_array($role, $form["links"]["members"][Yii::app()->session["userId"]]["roles"]) ){
    		$res = true;
478 479 480
        }else if( Role::isSuperAdmin(Role::getRolesUserId(Yii::app()->session["userId"]) )){
			$res = true;
		}
Raph El's avatar
Modif  
Raph El committed
481
		//Rest::json($res); exit ;
Raph El's avatar
Raph El committed
482 483 484
        return $res ;
	}

Raph El's avatar
Hotfix  
Raph El committed
485
	public static function canSuperAdmin($id, $session, $form = array(), $formAdmin = array()){
Raph El's avatar
Raph El committed
486
		if(empty($form))
Tibor Katelbach's avatar
Tibor Katelbach committed
487
			$form = PHDB::findOne( Form::COLLECTION , array( "id"=>$id ));
Raph El's avatar
Raph El committed
488 489

		if(empty($formAdmin))
Tibor Katelbach's avatar
Tibor Katelbach committed
490
			$formAdmin = PHDB::findOne( Form::COLLECTION , array("id"=>$id."Admin","session"=>$session));
Raph El's avatar
Hotfix  
Raph El committed
491

Raph El's avatar
Raph El committed
492
		if(@$formAdmin["adminRole"])
Raph El's avatar
Hotfix  
Raph El committed
493
			$res = self::canAdminRoles( (String)$form["_id"], $formAdmin["adminRole"], $form ) ;
Raph El's avatar
Raph El committed
494 495
		else
			$res = false;
Raph El's avatar
Raph El committed
496 497 498
        return $res ;
	}

Raph El's avatar
Raph El committed
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
	public static function updatePriorisation($params ){

		$res = Link::removeRole($params["contextId"], $params["contextType"], $params["childId"], $params["childType"], @$params["roles"], Yii::app()->session['userId'], $params["connectType"]);

		$answer = PHDB::findOne(self::ANSWER_COLLECTION,array("_id"=>new MongoId($params["answer"])));
		$roles = explode(",", $params["roles"]);
		$pourcentage = round(100 / count($roles), 2);
		$categories = array() ;
		$priorisation = array() ;

		foreach ($roles as $key => $value) {
			$slug = InflectorHelper::slugify( $value ) ; 
			if(!empty($answer["categories"][$slug])){
				$categories[$slug] = $answer["categories"][$slug];
				if(!empty($answer["answers"]["priorisation"][$slug]))
					$priorisation[$slug] = $answer["answers"]["priorisation"][$slug];
			}else{
				$categories[$slug] = array( "name" => $value,"pourcentage" => $pourcentage);
			}
			

		}

		PHDB::update(self::ANSWER_COLLECTION,
						array("_id"=>new MongoId($params["answer"])),
						array('$set' => array("categories"=>$categories, "answers.priorisation"=>$priorisation))
					);

        return $res ;
	}



Tibor Katelbach's avatar
Tibor Katelbach committed
532
	public static function isFinish($endDate){
533 534
		$res = false;
		$today = date(DateTime::ISO8601, strtotime("now"));
Tibor Katelbach's avatar
Tibor Katelbach committed
535 536
		if(!empty($endDate) ){
			$endDate = date(DateTime::ISO8601, $endDate->sec);
537 538 539 540 541 542
			if($endDate < $today)
				$res = true;
		}
		return $res ;
	}

Tibor Katelbach's avatar
Tibor Katelbach committed
543
	public static function notOpen($d){
Tibor Katelbach's avatar
Tibor Katelbach committed
544
		$res = false;
Tibor Katelbach's avatar
Tibor Katelbach committed
545 546 547 548 549 550 551 552 553
		$today = date(DateTime::ISO8601, strtotime("now"));
		if(!empty($d) ){
			$d = date(DateTime::ISO8601, $d->sec);
			if($d > $today)
				$res = true;
		}
		return $res ;
	}

Clément Damiens's avatar
Clément Damiens committed
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
	public static function createNotificationAnswer($comment){
		$answer=Form::getAnswerById($comment["contextId"]);
		$form=Form::getById($answer["formId"]);
		$projectName= (@$answer["answers"]["cte2"]["answers"]["project"]["name"]) ? @$answer["answers"]["cte2"]["answers"]["project"]["name"]." " : "";
		if($answer["user"]==Yii::app()->session["userId"]){
			//Notify admin and if answer
			$mails=[];
			if(@$form["links"] && @$form["links"]["members"]){
				foreach($form["links"]["members"] as $key => $v){
					if(@$v["isAdmin"] && $key!=Yii::app()->session["userId"] ){
						$email=Person::getEmailById($key);
						array_push($mails, $email["email"]);
					}
				}
			}
			$tplObject="[".$form["title"]."] Un candidat a laissé un message";
			$messages="<p>".$answer["name"]." a envoyé un message sur son projet ".$projectName.":</p>";
		}else{
			$tplObject="[".$form["title"]."] Vous avez reçu un message";
			$messages="<p>".Yii::app()->session["user"]["name"]." a envoyé un message sur votre projet ".$projectName.":</p>";
			$mails=[$answer["email"]];
		}
		$messages.="<br/><br/><p style='padding:10px 20px;margin:1%;border:1px solid lightgray; font-style:italic; border-radius:10px; width:90%;white-space: pre-line;'>".$comment["text"]."</p>".
				"<br/><br/><div style='text-align:center'><a href='".Yii::app()->getRequest()->getBaseUrl(true).Yii::app()->session["custom"]["url"]."' target='_blank' style='padding:7px 10px; border-radius:5px; background-color:#00b795;color:white;font-weight:800;font-variant:small-caps;'>Répondre</a></div>";
		$params=array(
			'formId'=>$answer["formId"],
			'session'=>$answer["session"],
			'answerId'=>(string)$answer["_id"],
			'answerUser'=>$answer["name"],
			"tpl"=>"eligibilite",
			"tplObject"=>$tplObject,
			"messages"=>$messages,
			"tplMail"=>""
		);
		foreach($mails as $email){
			$params["tplMail"]=$email;
			Mail::createAndSend($params);
		}
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
	}

	public static function generate($id, $copy,$pId,$pType){
		$res = null;
		$copyEl = PHDB::findOne( Form::COLLECTION , array("id"=>$copy));
		$checkExist = PHDB::findOne( Form::COLLECTION , array("id"=>$id));
    	if ( ! Person::logguedAndValid() ) {
            $res = array( "render"=>"co2.views.default.unTpl","msg"=>Yii::t("common","Please Login First"),"icon"=>"fa-sign-in");
        } 
        else if( $checkExist ) {
        	$res = array("msg"=>Yii::t("common","Success"));
        }
        else if( $copyEl ) {
            unset($copyEl["_id"]);
            unset($copyEl["modified"]);
            unset($copyEl["created"]);
            unset($copyEl["links"]);
            $copyEl["id"] = $id;
            $copyEl["copied"] = $copy;
Tibor Katelbach's avatar
Tibor Katelbach committed
611 612
            // reuse and not duplicate scenarios and dynform definitions
            $copyEl["scenario"] = "db.forms.id.".$copy.".scenario" ;
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629

            //parent elemnet information
            $copyEl["parentId"] = $pId;
            $copyEl["parentType"] = $pType;
            
            $el = Slug::getElementBySlug($id);
            if( !empty($el["el"]["profilThumbImageUrl"]))
                $copyEl['custom']["logo"] = $el["el"]["profilThumbImageUrl"];            

            $copyEl['title'] = $el["el"]["name"];                         
            $copyEl["created"] = time();
            $copyEl["updated"] = time();
            $copyEl["modified"] = new MongoDate(time());

            // var_dump($copyEl);
            // exit;
            PHDB::insert( Form::COLLECTION, $copyEl );
Clément Damiens's avatar
Clément Damiens committed
630 631 632
            PHDB::update($pType, 
                       array("_id" => new MongoId($pId)) , 
                       array('$set' => array("links.".self::COLLECTION.".".(string)$copyEl["_id"] => array("type"=>self::COLLECTION, "copyForm"=>$copy))));
633 634 635 636
            $res = array("msg"=>Yii::t("common","Success"));
        } else 
        	$res = array("render"=>"co2.views.default.unTpl", "msg"=>Yii::t("project", "Source Copy doesn't exist."),"icon"=>"fa-lock");
        return $res;
Clément Damiens's avatar
Clément Damiens committed
637
	}  			
Clément Damiens's avatar
 
Clément Damiens committed
638
	public static function canFormAccess($rules){
639 640
		$costum = CacheHelper::getCostum();
		//WARNING la c'est ce qui est lier à l'user du costum connecté
Clément Damiens's avatar
 
Clément Damiens committed
641 642 643
		if(Authorisation::isInterfaceAdmin())
			return true;
		if(isset($rules["roles"]) 
644 645
			&& isset(Yii::app()->session["costum"][$costum["slug"]]["hasRoles"]) 
			&& !empty(array_intersect(Yii::app()->session["costum"][$costum["slug"]]["hasRoles"], $rules["roles"])))
Clément Damiens's avatar
 
Clément Damiens committed
646 647 648 649
				return true;
		return false;
	}
	public static function getFormData($params){
650
		
651
		//WARNING la c'est bien data que l'on veut
652
		if(isset($params["parentForm"]["rules"])){
Clément Damiens's avatar
 
Clément Damiens committed
653
			foreach ($params["formList"] as $k => $value) {
654 655
				if(isset($params["parentForm"]["rules"][$value])){
					if(!self::canFormAccess($params["parentForm"]["rules"][$value])){
Clément Damiens's avatar
 
Clément Damiens committed
656 657 658 659 660 661 662 663 664
						array_splice($params["formList"], $k, -1);
					}
				}
			}
		}
			 //when inputs are interdependant on other inputs
        $budgetInputList = []; 
        $allforms = [];
        $stockBudgetInputs = false;
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
        if(!empty($params["formList"])){
        	foreach ($params["formList"] as $i => $formId) 
	      	{
	        	$f = PHDB::findOne(Form::COLLECTION, ["id"=>$formId]);
	            $allforms[$formId] = $f;
	            foreach ($f["inputs"] as $key => $inp) 
	            {
	              if( in_array($inp["type"], ["tpls.forms.cplx.budget"] ) )
	                $budgetInputList[$formId.".".$key] = $formId.".".$key; 
	              if( in_array($inp["type"], [
	                                          "tpls.forms.cplx.tpls.forms.cplx.financementFromBudget",
	                                          "tpls.forms.cplx.tpls.forms.cplx.suiviFromBudget",
	                                          "tpls.forms.cplx.tpls.forms.cplx.decideFromBudget"] ) )
	                $stockBudgetInputs = true;
	              
	            }
	      	}
        }
      	
Clément Damiens's avatar
 
Clément Damiens committed
684
      	if(count($budgetInputList))
685
        	Yii::app()->session["budgetInputList"] = $budgetInputList;
Raph El's avatar
Raph El committed
686
      	//var_dump($budgetInputList);
Clément Damiens's avatar
 
Clément Damiens committed
687
        //use the cache 
688
        	$params["forms"] = $allforms;
Clément Damiens's avatar
 
Clément Damiens committed
689
        return $params;
Raph El's avatar
Raph El committed
690

Clément Damiens's avatar
 
Clément Damiens committed
691
	}
692 693 694 695 696 697 698 699 700 701
	public static function getListAnswersBy($formId, $parent, $userId=null, $cond=null){
		$where=array("formId"=> $formId, "parentSlug" => $parent);
		if(!empty($userId)){
			$where["user"]=$userId;
		}
		if(!empty($cond))
			$where=array('$and'=> array($where, $cond));
		$lists=PHDB::find( Form::ANSWER_COLLECTION, $where);
		return $lists;
	}
Raph El's avatar
Raph El committed
702
	public static function getDataForAnswer($params){
Clément Damiens's avatar
 
Clément Damiens committed
703
		//var_dump(Yii::app()->session['costum']);exit;
704 705
		//WARNING
		$costum = CacheHelper::getCostum();
706 707 708 709
		if(isset($costum["contextType"]) && isset($costum["contextId"])){
			$params["el"] = Element::getByTypeAndId($costum["contextType"], $costum["contextId"] );
			$params["el"]["id"] = $costum["contextId"];
		}
710 711
	    
	    //if(isset($_GET["form"]))
Tibor Katelbach's avatar
Tibor Katelbach committed
712
	    $form = (isset($costum["form"])) ? $costum["form"] : PHDB::findOne( Form::COLLECTION, [ "_id" => new MongoId($_GET["form"]) ] );
713 714 715 716 717 718
	    $params["parentForm"] = $form;
	    
        if(isset($costum["hasOpenForm"]))
        {
            if(isset($costum["isMultiForms"]))
            {
Clément Damiens's avatar
 
Clément Damiens committed
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
               	$answerId=null;
	            $answer=null;
	            $generateAnswer = false;
	           
	            if(isset($_GET['answer']))
	            	$answerId=$_GET['answer'];
	            else if(isset($params["answerId"]))
	            	$answerId=$params["answerId"];
	           	//var_dump($answerId);
	            if(!empty($answerId) && $answerId !="new")
	            	$answer = self::getAnswerById($answerId);
	            //var_dump($answer);exit;
	           	if(!empty($answer)){
	           		$params["formList"] = explode("|", $answer["formId"]);
	                $params["formId"] = $answer["formId"];
	          
735 736
	           	}else if(isset($form)){
	                $params["formList"] = $form["ids"];
Clément Damiens's avatar
 
Clément Damiens committed
737 738
	                $params["formId"] = implode("|", $params["formList"]);
	            }
Clément Damiens's avatar
 
Clément Damiens committed
739 740
	            $params=self::getFormData($params);
	        } else {
Raph El's avatar
Raph El committed
741 742 743
                if(isset($_GET["form"]))
                    $params["formId"] = $_GET["form"];
                else 
744
                    $params["formId"] = (isset($form["id"])) ? $form["id"] : Form::generateOpenForm( $el["slug"] );
Raph El's avatar
Raph El committed
745 746 747 748
            }
            
            
            // $answer = ( isset(Yii::app()->session["costum"]["form"]["canModifyAnswer"]) && isset($_GET['answer'])) ? PHDB::findOne( Form::ANSWER_COLLECTION,[ "_id" => new MongoId($_GET['answer']) ] ) : null;
Clément Damiens's avatar
 
Clément Damiens committed
749 750 751 752
           	
           	if(!isset($params["el"]) && !empty($answer) && isset($answer["parentSlug"]))
           		$params["el"]=Slug::getElementBySlug($answer["parentSlug"])["el"];
        
Raph El's avatar
Raph El committed
753
            $showForm = true;
754

755 756 757

            if(!empty($params["formId"])){
            	$myAnswers = self::getListAnswersBy($params["formId"], $params["el"]["slug"], Yii::app()->session["userId"]);
Raph El's avatar
Raph El committed
758 759 760

           

761
	            if(!isset($form["oneAnswerPerPerson"]) || count($myAnswers) == 0){
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
	              	//si ya qu'une réponse  et  on la charge directe                      
	              	if(count($myAnswers) == 1 )
	                	$answer = $myAnswers[ array_keys($myAnswers)[0] ];
	              	else {
	                	//sinon on cherche la reponse incomplete 
	                	foreach ($myAnswers as $id => $ans) 
	                	{
		                  //chercher les reponse incomplete
		                  if(!isset( $ans["answers"]) && $answer == null )
		                    $answer = $ans;
		                }
	              	}

	              	if( $answer == null && count( $myAnswers ) > 1 && !$params["canEdit"] )
	                	$showForm = false;

		            //si aucune reponse existe 
		            //et qu'on a des input complexe alors on génere une answer 
		            // if( !isset($_GET['answer']) && $answer == null  ){
		            //     if(isset($params["formList"])){
		            //         $generateAnswer = true;
		            //     }
		            //     else if(isset($form["inputs"])){
		            //         foreach ($form["inputs"] as $key => $inp) 
		            //         {
		            //           if( stripos( $inp["type"] , "tpls.forms.cplx" ) !== false )
		            //             $generateAnswer = true;
		            //         }
		            //     }
	            	// }

			        // if( isset($answerId) && $answerId == "new" )
			        //     $generateAnswer = true;

			        //on pré genere un anwser que quand il n'y en pas 
			        //pour permettre le save onBlur , ou s'il y a des cplx forms
			        //il ne peut y avoir qu'un seul answer en cours simultanement 

	              //on pré genere un anwser que quand il n'y en pas 
	              //pour permettre le save onBlur , ou s'il y a des cplx forms
	              //il ne peut y avoir qu'un seul answer en cours simultanement 

	              ///TODO purger ANSwers via CRON
	              // if( $generateAnswer )
	              // {
	              //   //var_dump("create new" );
	              //   $ans = [ 
	              //       "formId" => $params["formId"],
	              //       "user" => Yii::app()->session["userId"],
	              //       "parentSlug" => $params["el"]["slug"],
	              //       "links"=>[
		             //        	"answered" => [ Yii::app()->session["userId"] ] ,
		             //        	//proposed ,particpated,decision,financed,financed,referenced,commented,worked,payed,tested,validated
		             //        	//each actor is connectable to his activitystream
	              //       ],
	              //       "created" => time()
	              //   ];
	              //   if(isset($params["formList"]))
	              //       $ans["formList"] = count($params["formList"]);
	              //  PHDB::insert(Form::ANSWER_COLLECTION, $ans);
	              //  $answer = PHDB::findOne( Form::ANSWER_COLLECTION, [ "_id" => new MongoId($ans["_id"]) ] );
	              // }
	            
	              // var_dump($params["el"]["slug"] );
	              // var_dump($params["formId"] );
	              // var_dump($answer );
	              // var_dump(Yii::app()->getRequest()->getQuery('answer'));
	              // exit;

	              $params["answer"] = $answer;
	              $params["showForm"] = $showForm;
	              $params["showAnswerActions"]=(isset($params["showAnswerActions"])) ? $params["showAnswerActions"] : true;
	              $allAnswers = self::getListAnswersBy($params["formId"], $params["el"]["slug"] ) ;
	               $params["allAnswers"] =  (isset($allAnswers)) ? $allAnswers : [] ;
	               //var_dump($params["el"]["slug"]);exit;
	            //var_dump($params["allAnswers"]);exit;
	            } else {
	                echo "<h4 class='text-center text-red'><i class='fa fa-warning'></i> Une seul réponse n'est possible.</h4>";
	                echo "<a class='btn btn-primary' href='/costum/co/index/slug/".$el["slug"]."/answer/".$myAnswers[0]."'>Votre réponse</a>";
	            }
842
            }
843
            
Raph El's avatar
Raph El committed
844
        }
Tibor Katelbach's avatar
tweaks  
Tibor Katelbach committed
845 846

        //var_dump($params);exit;
Raph El's avatar
Raph El committed
847
        return $params;
Clément Damiens's avatar
Clément Damiens committed
848
	}
Raph El's avatar
Raph El committed
849 850
	
}
851
?>