Form.php 30.8 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
7
8
	const ANSWER_COLLECTION = "answers";
	const ICON = "fa-list-alt";
	const ICON_ANSWER = "fa-calendar-check-o";
9

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
	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
28
	
Tibor Katelbach's avatar
tweak    
Tibor Katelbach committed
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
	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",
54
		"tpls.forms.cplx.suiviFromBudget" =>"suivi de travaux basé sur les budgets",
Tibor Katelbach's avatar
tweak    
Tibor Katelbach committed
55
56
57
58
59
60
61
62
		"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
63
64
65
66
		"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
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
	 /*
	[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
	 */
102
103
	public static function newAnswer($data)
	{
Tibor Katelbach's avatar
Tibor Katelbach committed
104
		try{
105
	
106
107
			$answer = array(
				"formId"=>$data["id"],
Tibor Katelbach's avatar
Tibor Katelbach committed
108
109
				"user"=>$data["user"],
				"session"=>$data["session"],
110
111
				"name"=>$data["name"],
				"email"=>$data["email"],
Tibor Katelbach's avatar
tweak    
Tibor Katelbach committed
112
				"step" => "dossier",
113
114
				"created"=>time()
			);
115
116
117
118
			if( isset(Yii::app()->session["costum"]) && 
                isset(Yii::app()->session["costum"]["slug"]) ){
                $answer["source"] = array(   "key" => Yii::app()->session["costum"]["slug"],
                                            "keys" => array(Yii::app()->session["costum"]["slug"]),
Raph El's avatar
Hotfix    
Raph El committed
119
120
                                            "insertOrign" => "costum") ;
            }
121
122
123
124
125
126
127
128
			PHDB::insert( self::ANSWER_COLLECTION, $answer);
			return array( "result" => true,
						 "answer" => $answer );
		} catch (CTKException $e){
   			return $e->getMessage();
  		}
	}

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

    public static function delAnswer($id)
    {
		try {
			return PHDB::remove( Form::ANSWER_COLLECTION,
                    array( "_id" => new MongoId((string)$id)));
		} catch (CTKException $e){
   			return $e->getMessage();
  		}
    }

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

    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
165
166
    }

Clément Damiens's avatar
   
Clément Damiens committed
167
168
169
170
171
172
    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
173
174
175
176
    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
177
178
    public static function getLinksById($id){
    	return self::getByIdMongo($id,array("links"));
Clément Damiens's avatar
   
Clément Damiens committed
179
    }
Raph El's avatar
Raph El committed
180

Raph El's avatar
Raph El committed
181
    public static function getLinksFormsByFormId($id, $type="all", $role=null) {
Raph El's avatar
Raph El committed
182
183
184
185
186
187
188
	  	$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
189
	  	if (isset($form) && isset($form["links"]) && isset($form["links"]["Form"])) {
Raph El's avatar
Raph El committed
190
	  		$members=array();
Raph El's avatar
Raph El committed
191
	  		foreach($form["links"]["Form"] as $key => $member){
Raph El's avatar
Raph El committed
192
193
194
195
196
197
198
	  		 	if(!@$member["toBeValidated"] && !@$member["isInviting"])
	  		 		$members[$key]= $member;
	  		}
	  		//No filter needed
	  		if ($type == "all") {
	  			return $members;
	  		} else {
Raph El's avatar
Raph El committed
199
	  			foreach ($form["links"]["Form"] as $key => $member) {
Raph El's avatar
Raph El committed
200
		            if ($member['type'] == $type) {
Raph El's avatar
Modif    
Raph El committed
201
202
203
204
205
206
207
208
209
210
211
212
		            	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
213
		            }
Raph El's avatar
Modif    
Raph El committed
214
215

		           
Raph El's avatar
Raph El committed
216
217
218
219
220
	        	}
	  		}
	  	}
	  	return $res;
	}
Raph El's avatar
Raph El committed
221

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

		$scenario = array();
		

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

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

Tibor Katelbach's avatar
Tibor Katelbach committed
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
			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
256

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

Raph El's avatar
Raph El committed
261
				$orga = Element::getElementById($value["answers"][Project::CONTROLLER]["id"], Project::COLLECTION, null, array("name", "email", "shortDescription", "shortDescription"));
Tibor Katelbach's avatar
Tibor Katelbach committed
262
263
264
265
266
267
268
269
270
271
272
273
274
				$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
275
					
Tibor Katelbach's avatar
Tibor Katelbach committed
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
					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;
					}
339

Raph El's avatar
Raph El committed
340
				}
Tibor Katelbach's avatar
Tibor Katelbach committed
341
342
343
344
345
346
347
348
349
350
351
352
353

				$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
354
355
356
357
358
				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
359
360
361
				$uniqP[] = $value["answers"][Project::CONTROLLER]["id"];
			}

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

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

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

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

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

409
410
		//Rest::json($res); exit ;
		return $res ;	
Raph El's avatar
Modif    
Raph El committed
411
	}
Raph El's avatar
Raph El committed
412

Raph El's avatar
Raph El committed
413
	
Clément Damiens's avatar
Clément Damiens committed
414
415
416
	public static function canSeeAnswer($userId, $answer, $form, $parentForm){
		if(self::canEditAnswer($userId, $answer, $form, $parentForm))
			return true;
Clément Damiens's avatar
   
Clément Damiens committed
417
		else if(Costum::sameFunction("canSeeAnswer", array("answer"=>$answer))){
Clément Damiens's avatar
Clément Damiens committed
418
419
420
421
422
423
424
425
426
427
			return true;
		}
		return false;
	}
	public static function canEditAnswer($userId, $answer, $form, $parentForm){
		if(self::canAdmin((string)$form["_id"], $form))
			return true;
		else if($answer["user"] == $userId)
			return true;
		else if(Authorisation::canEditItem( Yii::app()->session["userId"], $parentForm["type"], $parentForm["id"] ))
Clément Damiens's avatar
   
Clément Damiens committed
428
			return true;
Clément Damiens's avatar
   
Clément Damiens committed
429
		else if(Costum::sameFunction("canEditAnswer", array("answer"=>$answer)))
Clément Damiens's avatar
Clément Damiens committed
430
431
432
433
			return true;
		
		return false;
	}
Raph El's avatar
Raph El committed
434
	public static function canAdmin($id, $form = array()){
Tibor Katelbach's avatar
Tibor Katelbach committed
435
436
		if(empty($form) && @$id)
			$form = PHDB::findOne( Form::COLLECTION , array("_id"=>new MongoId($id)));
Raph El's avatar
Raph El committed
437
438

		$res = false;
Raph El's avatar
Raph El committed
439
		if(	Yii::app()->session["userId"] == $form["author"] ||
440
			Yii::app()->session["userId"] == $form["author"] ||
Raph El's avatar
Raph El committed
441
442
			(	!empty($form["links"]["members"][Yii::app()->session["userId"]]) && 
				!empty($form["links"]["members"][Yii::app()->session["userId"]]["isAdmin"]) &&
Raph El's avatar
Raph El committed
443
444
				$form["links"]["members"][Yii::app()->session["userId"]]["isAdmin"] == true /*&&
				 !empty($form["links"]["members"][Yii::app()->session["userId"]]["roles"]) &&
445
446
447
448
449
				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
450
    		$res = true;
Raph El's avatar
Raph El committed
451
    		
Clément Damiens's avatar
Clément Damiens committed
452
        } else if(Authorisation::isInterfaceAdmin()){
Raph El's avatar
Raph El committed
453
454
			$res = true;
		}
Raph El's avatar
Raph El committed
455
456
457
        return $res ;
	}

Raph El's avatar
Raph El committed
458
	public static function canAdminRoles($id, $role, $form = array() ){
459
		if(empty($form))
Tibor Katelbach's avatar
Tibor Katelbach committed
460
			$form = PHDB::findOne( Form::COLLECTION , array("_id"=>new MongoId($id)));
Raph El's avatar
Raph El committed
461
462
463
464
465
466
467
468
469
470

		$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;
471
472
473
        }else if( Role::isSuperAdmin(Role::getRolesUserId(Yii::app()->session["userId"]) )){
			$res = true;
		}
Raph El's avatar
Modif    
Raph El committed
474
		//Rest::json($res); exit ;
Raph El's avatar
Raph El committed
475
476
477
        return $res ;
	}

Raph El's avatar
Hotfix    
Raph El committed
478
	public static function canSuperAdmin($id, $session, $form = array(), $formAdmin = array()){
Raph El's avatar
Raph El committed
479
		if(empty($form))
Tibor Katelbach's avatar
Tibor Katelbach committed
480
			$form = PHDB::findOne( Form::COLLECTION , array( "id"=>$id ));
Raph El's avatar
Raph El committed
481
482

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

Raph El's avatar
Raph El committed
485
		if(@$formAdmin["adminRole"])
Raph El's avatar
Hotfix    
Raph El committed
486
			$res = self::canAdminRoles( (String)$form["_id"], $formAdmin["adminRole"], $form ) ;
Raph El's avatar
Raph El committed
487
488
		else
			$res = false;
Raph El's avatar
Raph El committed
489
490
491
        return $res ;
	}

Raph El's avatar
Raph El committed
492
493
494
495
496
497
498
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
	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
525
	public static function isFinish($endDate){
526
527
		$res = false;
		$today = date(DateTime::ISO8601, strtotime("now"));
Tibor Katelbach's avatar
Tibor Katelbach committed
528
529
		if(!empty($endDate) ){
			$endDate = date(DateTime::ISO8601, $endDate->sec);
530
531
532
533
534
535
			if($endDate < $today)
				$res = true;
		}
		return $res ;
	}

Tibor Katelbach's avatar
Tibor Katelbach committed
536
	public static function notOpen($d){
Tibor Katelbach's avatar
Tibor Katelbach committed
537
		$res = false;
Tibor Katelbach's avatar
Tibor Katelbach committed
538
539
540
541
542
543
544
545
546
		$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
547
548
549
550
551
552
553
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
	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);
		}
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
	}

	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
604
605
            // reuse and not duplicate scenarios and dynform definitions
            $copyEl["scenario"] = "db.forms.id.".$copy.".scenario" ;
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622

            //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
623
624
625
            PHDB::update($pType, 
                       array("_id" => new MongoId($pId)) , 
                       array('$set' => array("links.".self::COLLECTION.".".(string)$copyEl["_id"] => array("type"=>self::COLLECTION, "copyForm"=>$copy))));
626
627
628
629
            $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
630
	}  			
Raph El's avatar
Raph El committed
631

Raph El's avatar
Raph El committed
632

Raph El's avatar
Raph El committed
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
	public static function getDataForAnswer($params){
		if(isset(Yii::app()->session["costum"]["contextType"]) && isset(Yii::app()->session["costum"]["contextId"]))
	            $params["el"] = Element::getByTypeAndId(Yii::app()->session["costum"]["contextType"], Yii::app()->session["costum"]["contextId"] );
        

        if(isset(Yii::app()->session['costum']["hasOpenForm"])){
            
            if(isset(Yii::app()->session['costum']["isMultiForms"])){
                $params["formList"] = Yii::app()->session["costum"]["form"]["ids"];
                $params["formId"] = implode("|", $params["formList"]);

                  //when inputs are interdependant on other inputs
                  $budgetInputList = []; 
                  $allforms = [];
                  $stockBudgetInputs = false;
                  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;
                      
                    }
                  }
                  if(count($budgetInputList))
                    Yii::app()->session["budgetInputList"] = $budgetInputList;
                  
                  //use the cache 
                  Yii::app()->session["forms"] = $allforms;
                  

            } else {
                if(isset($_GET["form"]))
                    $params["formId"] = $_GET["form"];
                else 
                    $params["formId"] = (isset(Yii::app()->session["costum"]["form"]["id"])) ? Yii::app()->session["costum"]["form"]["id"] : Form::generateOpenForm( $el["slug"] );
            }
            
            
            // $answer = ( isset(Yii::app()->session["costum"]["form"]["canModifyAnswer"]) && isset($_GET['answer'])) ? PHDB::findOne( Form::ANSWER_COLLECTION,[ "_id" => new MongoId($_GET['answer']) ] ) : null;
            $answer = ( isset($_GET['answer'])) ? PHDB::findOne( Form::ANSWER_COLLECTION,[ "_id" => new MongoId($_GET['answer']) ] ) : null;
            $showForm = true;
            $generateAnswer = false;
            $myAnswers = PHDB::find( Form::ANSWER_COLLECTION,[ 
                            "formId"     => $params["formId"],
                            "parentSlug" => $params["el"]["slug"],
                            "user"       => Yii::app()->session["userId"] ] );

           

            if(
              !isset(Yii::app()->session["costum"]["form"]["oneAnswerPerPerson"]) ||
                count($myAnswers) == 0                          
              )
            {
              //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
                  //var_dump(isset( $ans["answers"] ) );
                  if(!isset( $ans["answers"]) && $answer == null )
                    $answer = $ans;
                }
              }
              
              if( $answer == null && count( $myAnswers ) > 1 && !$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($_GET['answer']) && $_GET['answer'] == "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 

              ///TODO purger ANSwers via CRON
              if( $generateAnswer )
              {
                //var_dump("create new" );
                $ans = [ 
                    "formId" => $params["formId"],
                    "user" => Yii::app()->session["userId"],
                    "parentSlug" => $params["el"]["slug"],
                    "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["allAnswers"] = PHDB::find( Form::ANSWER_COLLECTION,[ 
                                                   "formId"     => $params["formId"],
                                                   "parentSlug" => $params["el"]["slug"] ] );
               //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>";
            }

        }

        return $params;
Clément Damiens's avatar
Clément Damiens committed
775
	}
Raph El's avatar
Raph El committed
776
777
	
}
778
?>