Answer.php 15.6 KB
Newer Older
Raph El's avatar
Hotfix  
Raph El committed
1 2 3 4 5 6 7
<?php

class Answer{
	const COLLECTION = "answers";
	const CONTROLLER = "answer";
	const ICON = "fa-calendar-check-o";

8

Raph El's avatar
Hotfix  
Raph El committed
9 10 11 12 13
	public static function getById($id, $fields=array()){
		return PHDB::findOne( self::COLLECTION, array( "_id" => new MongoId((string)$id) ), $fields );
	}


Raph El's avatar
Raph El committed
14
	public static function generateAnswer($form, $draft = false){
Raph El's avatar
Hotfix  
Raph El committed
15
		$costum = CacheHelper::getCostum();
16
		//Rest::json($costum); exit;
Raph El's avatar
Hotfix  
Raph El committed
17 18 19 20 21 22 23 24 25
		$ans = [
			"user" => Yii::app()->session["userId"],
			"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()
		];
Raph El's avatar
Raph El committed
26 27
		if($draft === true)
			$ans["draft"] =  true;
Raph El's avatar
Raph El committed
28
		
Raph El's avatar
Hotfix  
Raph El committed
29
		$formList = null ;
30 31
		if( !empty($form) ){
			$ans["form"] = (String)$form["_id"];
Tibor Katelbach's avatar
Tibor Katelbach committed
32 33
			if(!empty($form["subForms"])){
				$formList = $form["subForms"];
Raph El's avatar
Raph El committed
34 35 36
				$ans["formId"] = implode("|", $formList);
				$ans["formList"] = count($formList);
			}
37
			//$ans["step"] = $formList[0];
Raph El's avatar
Hotfix  
Raph El committed
38
		}
Raph El's avatar
Raph El committed
39 40 41 42 43
		//Rest::json($costum); exit;
		if(!empty($costum) && !empty($costum["slug"]) ) {
			$ans["source"] = Costum::getSource($costum["slug"]);
		}
		//Rest::json($ans); exit;
44 45 46 47 48 49 50 51 52
		if(Costum::isSameFunction("generateAnswerBeforeSave")){
			$paramBeforeSave=Costum::sameFunction("generateAnswerBeforeSave", 
										array("answer" => $ans, "formList"=>$formList) );
			$ans = $paramBeforeSave["answer"]; 
		}

		PHDB::insert(Answer::COLLECTION, $ans);
		$answer = PHDB::findOne( Answer::COLLECTION, [ "_id" => new MongoId($ans["_id"]) ] ) ;
		return $answer;
Raph El's avatar
Hotfix  
Raph El committed
53 54
		
	}
55 56 57 58 59 60 61 62 63 64

	public static function canAdmin($ans, $form=null){
	    if(Form::canAdmin((string)$form["_id"], $form))
			return true;
		else if(Costum::isSameFunction("canAdminAnswer", array("answer"=>$ans)))
			return Costum::sameFunction("canAdminAnswer", array("answer"=>$ans));
		
		return false;
	}

Clément Damiens's avatar
 
Clément Damiens committed
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
	public static function canEdit($ans, $form=null, $userId=null, $parent=null){
	    if(ctype_xdigit($ans)){
	    	$ans=self::getById($ans);
	    	$form = Form::getByIdMongo($ans["form"]);
			$parent = Slug::getElementBySlug($form["id"]);
			$userId=Yii::app()->session["userId"];
		}
		if($ans["user"] == $userId)
			return true;
		else if(Form::canAdmin((string)$form["_id"], $form))
			return true;
		else if(Costum::isSameFunction("canEditAnswer", array("answer"=>$ans)))
			return Costum::sameFunction("canEditAnswer", array("answer"=>$ans));
		
		return false;
	}
	public static function canAccess($answer, $form=null, $userId=null, $parentForm=null){
		if(ctype_xdigit($answer)){
			$answer=self::getById($answer);
	    	$form = Form::getByIdMongo($answer["form"]);
			$parent = Slug::getElementBySlug($form["id"]);
	    }
		if(self::canEdit( $answer, $form, $userId, $parentForm))
			return true;
		else if(Costum::isSameFunction("canAccessAnswer", array("answer"=>$answer)))
			return Costum::sameFunction("canAccessAnswer", array("answer"=>$answer));
		return false;
	}
	public static function getListBy($form=null, $costum=null, $userId=null, $cond=null){
		$where =  array();
		$lists = array();
		if(!empty($form))
			$where["form"]=$form;
		if(!empty($costum))
			$where["source.keys"]=array('$in' => array($costum) );
		if(!empty($userId))
			$where["user"]=$userId;
		if(!empty($cond)){
			$where=array('$and'=> array($where, $cond));
		}
		if(!empty($where))
			$lists=PHDB::find( Answer::COLLECTION, $where);
		return $lists;
	}

Clément Damiens's avatar
 
Clément Damiens committed
110
	public static function globalAutocomplete($form, $searchParams){
111
		//var_dump($form);
Clément Damiens's avatar
 
Clément Damiens committed
112 113 114 115
		$searchParams["indexMin"] = (isset($searchParams["indexMin"])) ? $searchParams["indexMin"] : 0;
		$searchParams["indexStep"] = (isset($searchParams["indexStep"])) ? $searchParams["indexStep"] : 100;
		$mappingData=(isset($form["mapping"])) ? $form["mapping"] : array("name"=>"name", "address"=>"address");
		$query=array("form"=>(string)$form["_id"]);
116 117 118 119 120 121 122 123 124 125

		if(!empty($searchParams["userId"])){
			$query = array('$and' => 
								array( 
									$query , 
									array("user" => $searchParams["userId"] )
								)
							) ;
		}

Clément Damiens's avatar
 
Clément Damiens committed
126 127 128 129 130 131 132 133
		if(!empty($searchParams["name"])){
			$searchRegExp = Search::accentToRegex(trim(urldecode($searchParams['name'])));
			$query = array('$and' => 
								array( 
									$query , 
									array($mappingData["name"] => new MongoRegex("/.*{$searchRegExp}.*/i"))
								)
							) ;
Raph El's avatar
Hotfix  
Raph El committed
134

Clément Damiens's avatar
 
Clément Damiens committed
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
		}
		if(!empty($searchParams["filters"]["address"])){
			$searchRegExp = Search::accentToRegex(trim(urldecode($searchParams["filters"]['address'])));
			$query = array('$and' => 
								array( 
									$query , 
									array('$or'=> array(
										array($mappingData["address"].".postalCode" => new MongoRegex("/.*{$searchRegExp}.*/i")),
										array($mappingData["address"].".cityName" => new MongoRegex("/.*{$searchRegExp}.*/i"))
									))
								)
							) ;

		}	
		if(!empty($searchParams['filters'])){
			$query = Search::searchFilters($searchParams['filters'], $query);
		}
		$res= array();
153
		//Rest::json($query);exit;
Clément Damiens's avatar
 
Clément Damiens committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
		$res["results"] = PHDB::findAndLimitAndIndex ( self::COLLECTION , $query, $searchParams["indexStep"], $searchParams["indexMin"]);
		if(isset($searchParams["count"]))
			$res["count"][self::COLLECTION] = PHDB::count( self::COLLECTION , $query);
		return $res;
	}
	public static function getMappingValues($mapping, $ans){
		foreach($mapping as $k => $path){
			$mapping[$k]=self::getValueByPath($path, $ans);
		}
		return $mapping;
	}
	public static function getValueByPath($indexes, $arrayToAccess){
		if(is_string($indexes))
		$indexes = explode( ".", $indexes );
		if(isset($arrayToAccess[$indexes[0]])){	
		   if(count($indexes) > 1) 
		    return self::getValueByPath(array_slice($indexes, 1), $arrayToAccess[$indexes[0]]);
		   else
		    return $arrayToAccess[$indexes[0]];
		}
	}
Raph El's avatar
Raph El committed
175 176


Raph El's avatar
Raph El committed
177
	public static function getDataAnswers($answerList, $subForms, $form){
Raph El's avatar
Raph El committed
178 179 180 181
		$globalLinks = [];
		$gUids = [];
		if(!empty($answerList)){
			foreach ($answerList as $key => $ans) {
Raph El's avatar
Raph El committed
182 183
				if(isset($form["mapping"])){
					$answerList[$key]["mappingValues"]=Answer::getMappingValues($form["mapping"], $ans);
Raph El's avatar
Raph El committed
184 185 186 187 188 189 190 191 192 193 194 195 196
				}
				$answerList[$key]["countComment"] = PHDB::count(Comment::COLLECTION, array("contextId"=>$key,"contextType"=>Form::ANSWER_COLLECTION));
				
				$localLinks = [];
				$uids = [];
				$todo = 0;
				$done = 0;
				$tasksPerson = [];
				if(!isset($ans["answers"])) {
					$percent = 0;
				} else {
					$totalInputs = 0;
					$answeredInputs = 0;
Raph El's avatar
Raph El committed
197
					foreach ($subForms as $fid => $f){
Raph El's avatar
Raph El committed
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
						$totalInputs += count($f["inputs"]);
						if( isset( $ans["answers"][$fid] ) ){
							$answeredInputs += count( $ans["answers"][$fid] );
						}

						//todo lists are on depense for the moment 
						//todo genereaclly not with a fixed input ID
						if( isset( $ans["answers"][$fid]["depense"] ) ){
							foreach ( $ans["answers"][$fid]["depense"]  as $ix => $dep) {
								if( isset( $dep["todo"] ) ){
									foreach ($dep["todo"] as $ixx => $t) {
										if(!isset($t["done"]) || $t["done"] == "0"){
											$todo++;
											$whos = (is_array($t["who"])) ? $t["who"] : explode(",",$t["who"]);
											foreach ( $whos as $whoix => $who ) {
												if( !isset( $tasksPerson[ $who ] ) ) 
													$tasksPerson[ $who ] = [];
												$tasksPerson[ $who ][] = $t["what"];
											}
										}
										else
											$done++;
									}
								}
							}
						}
					}
					if(isset($ans["links"])){
						foreach ( $ans["links"] as $type => $ls ){
							if(!isset($localLinks[$type]))
								$localLinks[$type] = [];

							if(!isset($globalLinks[$type]))
								$globalLinks[$type] = [];

							foreach ($ls as $uid => $time) {
								if(is_string($uid) && strlen($uid) == 24 && ctype_xdigit($uid)){
									if(!in_array($uid, $localLinks[$type] ))
										$localLinks[$type][] = $uid;	
									if(!in_array($uid, $uids ))
										$uids[] = new MongoId( $uid );
									if(!in_array($uid, $globalLinks[$type] ))
										$globalLinks[$type][] = $uid;
									if(!in_array($uid, $gUids ))
										$gUids[] = new MongoId( $uid );
								}
							}
							
						}
					}
					$percent = floor( $answeredInputs*100 / $totalInputs );
				}
				$answerList[$key]["percent"] = $percent;
				$answerList[$key]["uids"] = $uids;
				$answerList[$key]["todo"] = $todo;
				$answerList[$key]["done"] = $done;
				$answerList[$key]["tasksPerson"] = $tasksPerson;
255
				$answerList[$key]["canEdit"] = self::canEdit( $ans, $form, Yii::app()->session["userId"]) ;
Raph El's avatar
Raph El committed
256 257 258 259
			}	
		}
		return $answerList;
	}
Raph El's avatar
Raph El committed
260 261 262 263

	public static function csv($elements, $idElt, $valElt, $forms ){
		$elements[$idElt]["id"] = $idElt;
		$elements[$idElt]["user"] = $valElt["user"];
264
		$elements[$idElt]["created"] = date("d/m/Y", $valElt["created"]);
Raph El's avatar
Raph El committed
265 266 267 268 269 270 271 272 273 274 275 276 277
		if(!empty($valElt["answers"])){
			foreach ($forms as $keyF => $valF) {
				if(!empty($valF["id"]) && !empty($valElt["answers"][$valF["id"]])){
					foreach ($valElt["answers"][$valF["id"]] as $keyAns => $valAns) {
						if(!empty($valF["inputs"]) && !empty($valF["inputs"][$keyAns]) && !empty($valF["inputs"][$keyAns]["label"])){
							$elements[$idElt][$valF["inputs"][$keyAns]["label"]] = $valAns;
						}
					}
				}
			}
		}
		return $elements;
	}
Clément Damiens's avatar
 
Clément Damiens committed
278 279 280 281
	public static $mailConfig=array(
		"validation"=>["tpl"=>"answer.validation", "subject"=>"La candidature {what} a été validée"],
		"rejected"=>["tpl"=>"answer.rejected", "subject"=>"La candidature {what} a été rejetée"],
		"default"=>["tpl"=>"answer.default", "subject"=>""]
282 283 284 285 286 287 288
	);
	public static function getCommunityToNotify($answer, $entry=null){
		$arrayMail=array();
		if(!empty($answer["links"])){
			foreach($answer["links"] as $k => $v){
				if($k=="answered" && (empty($entry) || in_array("answered",$entry))){
					foreach($v as $id){
Clément Damiens's avatar
 
Clément Damiens committed
289 290
						$people=Element::getElementById($id, Person::COLLECTION, null, array("email","name","slug") );
						array_push($arrayMail, $people);
291 292 293 294 295 296 297 298 299 300 301 302
					}
				}
			}
			if(Costum::isSameFunction("getAnswerCommunityToNotify")){
                // CARREFUL $costumUserArray need to be return as result : return $params["costumUserArray"]
                array_merge($arrayMail, Costum::sameFunction("getAnswerCommunityToNotify", array(
                    "answer"=>$answer)));
            }
        }
        return $arrayMail;
		
	}
Clément Damiens's avatar
 
Clément Damiens committed
303
	public static function mailProcess($id, $tpl, $step, $infos){
304
		$costum = CacheHelper::getCostum();
Clément Damiens's avatar
 
Clément Damiens committed
305
		$answer=self::getById($id);
Clément Damiens's avatar
 
Clément Damiens committed
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
		$mailsCommunity=array();
		if(isset($infos["emails"]) && !empty($infos["emails"])){
			foreach($infos["emails"] as $v){
				array_push($mailsCommunity, Element::getElementByWhere(Person::COLLECTION, array("email"=>$v),array("email","name","slug") ) );
			}
		}
		if(isset($infos["community"]) && !empty($infos["community"])){
			$mailsCommunity=array();
			foreach($infos["community"] as $k => $v){
				if($v["type"]==Person::COLLECTION){
					array_push($mailsCommunity, Element::getElementById($k, Person::COLLECTION, null, array("email","name","slug") ));
				}else{
					$community=Element::getCommunityByTypeAndId(Organization::COLLECTION, $k,Person::COLLECTION, "isAdmin");
                    foreach($community as $e => $val){
                		array_push($mailsCommunity, Element::getElementById($e, Person::COLLECTION, null, array("email","name","slug") ));	
                	}
				}

			}
		}
		if(empty($mailsCommunity))
			$mailsCommunity=self::getCommunityToNotify($answer);
328
		$answer["mappingValues"]=array();
Clément Damiens's avatar
 
Clément Damiens committed
329
		$form=Form::getByIdMongo($answer["form"]);
330
		if(isset($form["mapping"]))
Clément Damiens's avatar
 
Clément Damiens committed
331
			$answer["mappingValues"]=self::getMappingValues($form["mapping"], $answer);
332
		$nameAnsw=(isset($answer["mappingValues"]["name"])) ? $answer["mappingValues"]["name"] : ""; 
Clément Damiens's avatar
 
Clément Damiens committed
333 334 335
		$objMail="[".Mail::getAppName()."] ".Yii::t("mail",self::$mailConfig[$tpl]["subject"], array("{what}"=>$nameAnsw));
		if(isset($infos["tplObject"]))
			$objMail="[".Mail::getAppName()."] ".$infos["tplObject"];
Clément Damiens's avatar
 
Clément Damiens committed
336 337 338 339
		foreach($mailsCommunity as $c){
			$params = array (
                "type" => Cron::TYPE_MAIL,
                "tpl"=>self::$mailConfig[$tpl]["tpl"],
Clément Damiens's avatar
 
Clément Damiens committed
340
                "subject" => $objMail,
Clément Damiens's avatar
 
Clément Damiens committed
341 342 343 344 345 346
                "from"=>Yii::app()->params['adminEmail'],
                "to" => $c["email"],
                "tplParams" => array(  "user"=> $c ,
                                        "title" => Mail::getAppName() ,
                                        "answer" => $answer,
                                        "form"=>$form,
Clément Damiens's avatar
 
Clément Damiens committed
347 348 349 350 351 352
                                        "msg"=>@$infos));
            if(isset($infos["msg"]))
            	$params["tplParams"]["msg"]=$infos["msg"];
            if(isset($infos["html"]))
            	$params["tplParams"]["html"]=$infos["html"];
            	                                        
Clément Damiens's avatar
 
Clément Damiens committed
353 354
            $params=Mail::getCustomMail($params); 
            Mail::schedule($params);
355
		}
Clément Damiens's avatar
 
Clément Damiens committed
356 357 358 359 360 361 362 363 364 365
		if(Costum::isSameFunction("AnswerMailProcess")){
            // CARREFUL $costumUserArray need to be return as result : return $params["costumUserArray"]
            Costum::sameFunction("AnswerMailProcess", array(
                "tpl"=>$tpl, 
                "step"=>$step,
                "infos"=>$infos,
                "form"=>$form,
                "answer"=>$answer)
            );
        }
366
	}
Raph El's avatar
Raph El committed
367

Raph El's avatar
Raph El committed
368 369 370
	public static function validate($params){
		$costum = CacheHelper::getCostum();
		$set = array();
Raph El's avatar
Raph El committed
371 372 373
		$res = array('result' => false, "msg" => "Erreur");
		if(!empty($params["answerId"]))
			$answer = PHDB::findOneById(Answer::COLLECTION, $params["answerId"]);
Raph El's avatar
Raph El committed
374

Raph El's avatar
Raph El committed
375 376 377 378 379
		if(!empty($answer)){
			if(!empty($params["input"]["validated"]) && ( $params["input"]["validated"] === true || $params["input"]["validated"] === "true" ) )
			$set["validated"] = true;
		
			if(!empty($params["input"]["generateElement"])){
Raph El's avatar
Raph El committed
380
				$mapping = array();
Raph El's avatar
Raph El committed
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
				$import = array(
					'file' => array(json_encode(array($params["answer"]))),
					'nameFile' => "test",
					'typeFile' => 'json',
					"warnings" => "false"
				);

				foreach ($params["input"]["generateElement"] as $type => $map) {
					$mapping = array();
					foreach ($map as $k => $v) {
						$mapping[] =array(
							'idHeadCSV' => $v["from"],
							'valueAttributeElt' => $v["to"]
						);
					}
					$import['infoCreateData'] = $mapping;
					$import['typeElement'] = $type;
					//Rest::json($import); exit;
					$resImport = Import::previewData($import, true, true, true);
					//Rest::json($resImport); exit;
					foreach ($resImport["elementsObj"] as $keyElt => $elt) {
	                    $elt = Import::checkElement($elt, $type);
	                    if(!empty($elt["msgError"]))
	                        unset($elt["msgError"]);
	                    $elt["collection"] = $type;
	                    $elt["key"] = $type;
	                    if(Costum::isSameFunction("generateElementBeforeSave")){
							$elt = Costum::sameFunction("generateElementBeforeSave", $elt);
						}
	                    $save = Element::save($elt);
	                    //Rest::json($save); exit;
	                    Link::connect($save["id"], $type, $params["answerId"], Answer::COLLECTION, Yii::app()->session["userId"], "answers",false,false,false,false);
	                    Link::connect($params["answerId"], Answer::COLLECTION, $save["id"], $type, Yii::app()->session["userId"], $type,false,false,false,false);
	                    
	                }
	                $res = array('result' => true, "msg" => "Valider");
					//Rest::json($resImport); exit;
Raph El's avatar
Raph El committed
418 419 420 421
				}
			}


Raph El's avatar
Raph El committed
422 423 424 425 426 427 428 429
			if(Costum::isSameFunction("answerValidate")){
				$paramBeforeValidate = Costum::sameFunction("answerValidate", $params);
			}
			
			if(!empty($set)){
				PHDB::update(Answer::COLLECTION,
		            array( "_id" => new MongoId((string)$params["answerId"])), 
		            array( '$set' => $set ) );
Raph El's avatar
Raph El committed
430

Raph El's avatar
Raph El committed
431 432 433
				$res = array('result' => true, "msg" => "Valider");
			}
			
Raph El's avatar
Raph El committed
434

Raph El's avatar
Raph El committed
435 436 437
			if($res["result"] === true){
				$res["html"] = $params["controller"]->renderPartial('survey.views.tpls.forms.finish', $res, true);
			}
Raph El's avatar
Raph El committed
438 439
		}
		
Raph El's avatar
Raph El committed
440 441 442
		return $res;
	}

Raph El's avatar
Hotfix  
Raph El committed
443 444
}
?>