<?php
/**
 * Workshop module
 *
 * Provides basics methods called from public templates
 * These methods can be overriden. Discover logic and examples on :
 * @url http://dev.linea21.com/projects/linea21/wiki/Override
 * @url http://dev.linea21.com/projects/linea21/wiki/Personnalisation_de_l%27interface_publique
 *
 * @package linea21\modules\workshop
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

include_once(override('../workshop/'.SQL.'.inc.php'));

if(!function_exists('DisplayFiles')) {
    
    function DisplayFiles($work_id, $url) {
        
        if(!$GLOBALS['l21auth']->isWorkgroupUser($work_id, $GLOBALS['sql_object'])) return false;
        
        $r = $GLOBALS['sql_object'] -> DBSelect( SQL_getoneCompleteWorkshop($work_id));
        $workshop_status = $r[0]['workshop_statut'];
        if($workshop_status == 'P') $sharedpath = '../library/userfiles/workgroups/shared/';
        else $sharedpath = '../library/userfiles/workgroups/shared-archives/';
        
        echo '<h3>' ._t('workshop', 'files').' : </h3>'.PHP_EOL;
        echo '<div id="groupfiles">'.PHP_EOL;
        $path = '../library/userfiles/workgroups/'.$work_id.'/';
        if(!file_exists($path)) echo '<ul><li>'._t('divers', 'no_files').'</li></ul>';
        else {
            // we display files
            echo get_files(getDirContents($path), $work_id);
        }
        echo '</div>'.PHP_EOL;
        echo '<h3>'._t('workshop', 'common_files').' : </h3>'.PHP_EOL;
        
        echo '<div id="sharedfiles">'.PHP_EOL;
        if(!file_exists($sharedpath)) echo '<ul><li>'._t('divers', 'no_files').'</li></ul>';
        else {
            // we display files
            echo get_files(getDirContents($sharedpath), 'shared');
        }
        echo '</div>'.PHP_EOL;
        
        echo '<script type="text/javascript">
				  $( "div.folder-name + ul").hide();
                  $( "div.folder-name").click(function() {
					  if($(this).hasClass("active")) $(this).removeClass("active");
					  else $(this).addClass("active");
					  $(this).next("ul").fadeToggle();
					});
            </script>';
        
        if(MOD_COMMENT == 1) {
            echo '<script type="text/javascript">
                  jQuery(function() {
                  	jQuery(".comment_actions a").colorbox({width:"60%", height:"80%"});
                  });
            </script>';
        }
        
    }
    
}

if(!function_exists('getFileComments')) {
    
    function getFileComments($id) {
        $data=$GLOBALS['sql_object'] -> DBSelect(SQL_getCommentsNumber(array('module' => 'files', 'module_id' => $id)));
        return $data[0]['nb'];
    }
    
}


if(!function_exists('uploadForm')) {
    
    function uploadForm($id) {
        if(!$GLOBALS['l21auth']->isWorkgroupUser($id, $GLOBALS['sql_object'])) die('no way!');
        
        $r = $GLOBALS['sql_object'] -> DBSelect( SQL_getoneCompleteWorkshop($id));
        $workshop_status = $r[0]['workshop_statut'];
        if($workshop_status != 'P') ReloadIndex('public');
        
        include_once('../class/system/class.upload.php');
        
        if(isset($_FILES['file'])) {
            $upload = new upload;
            error_reporting(E_ALL);
            ini_set("display_errors", 1);
            $ext= $upload->GetExtension($_FILES['file']['name']);
            // extension check
            if(in_array(strtolower($ext), explode(',', MEDIA_ALLOWED_EXT))) {
                $dest = '../library/userfiles/workgroups/';
                if(isset($_POST['shared_file'])) {
                    $dest .= 'shared/';
                    $is_shared = true;
                }
                else {
                    $dest .= $id.'/';
                    $is_shared = false;
                }
                if($upload->CheckMaxFile(filesize($_FILES['file']['tmp_name']), MEDIA_ALLOWED_SIZE) === true) {
                    $filename_parts = pathinfo($_FILES['file']['name']);
                    $final_name = Stringy\Stringy::create($filename_parts['filename'], CHARSET)->slugify().'.'.$filename_parts['extension'];
                    $r = $upload->UploadFile($_FILES['file'], $final_name, $dest);
                    if($r === true) {
                        notifyUsersMsg(array('id' => $id,'user' => $_SESSION['userlogin'] ,'owner' => $_SESSION['userlogin'], 'action' => 'file_alert', 'is_shared'=> $is_shared, 'files' => array($final_name)));
                        $confirmation = $final_name . ' : ' . _t('upload', 'confirmed');
                    }
                } else {
                    $err_msg = $upload->CheckMaxFile(filesize($_FILES['file']['tmp_name']), MEDIA_ALLOWED_SIZE);
                }
            } else  {
                $err_msg = sprintf(_t('upload', 'wrong_ext'), str_replace(",", ", ", MEDIA_ALLOWED_EXT));
            }
        }
        
        
        echo '<form id="uploadform" action="index.php" method="post" enctype="multipart/form-data">
    			<input type="hidden" name="id" id="id" value='.$id.' />
          <input type="hidden" name="rub" id="rub" value='.$GLOBALS['links'][U_L]['files']['linkvalue'].' />
          <input type="file" name="file" />
          <div id="share-file" class="mts mbs"><input type="checkbox" value="1" id="shared_file" name="shared_file" />
          <label for="shared_file" class="autowidth">'._t('workshop', 'share_files').'</label>
          </div>
              
          <button style="float:right">'._t('divers', 'up_file').'</button>
          </form>';
        if(ALERT_NEWFILE == 2) echo '<p class="info" style="margin-bottom:3em">'._t('workshop','notify_file').'</p>'; else $notify = '';
        
        if(isset($err_msg)) echo '<div class="error">'.$err_msg.'</div>'.PHP_EOL;
        if(isset($confirmation)) echo '<div class="info">'.$confirmation.'</div>'.PHP_EOL;
        
        
        // *** Include dropzone ***
        $fileDesc = str_replace(',', ', ', MEDIA_ALLOWED_EXT);
        $filesAllowed = str_replace(',', ',.', MEDIA_ALLOWED_EXT);
        addDynamicCSS('../lib/js/dropzone-4.0.1/dist/min/dropzone.min.css');
        footerAddJS('../lib/js/dropzone-4.0.1/dist/min/dropzone.min.js');
        
        $maxfiles = 8 ;
        $limit_msg = sprintf(_t('upload', 'n_simultenaous_transfer'), $maxfiles);
        $limit_msg .= ' ' . sprintf(_t('upload', 'upload_max_size'), MEDIA_ALLOWED_SIZE);
        
        $js = '<script type="text/javascript">
            
    	Dropzone.autoDiscover = false;
        
        var queueCompleted = false; 
    	var fileslist = "";
            
    	$(document).ready( function() {
    		 var dropzoneDiv = "<div id=\"dropzone-container\">";
    				dropzoneDiv += "<div id=\"multiple-uploads\" class=\"dropzone\"></div>";
						dropzoneDiv += "<div id=\"dz-total-progress\"><div data-dz-uploadprogress=\"\" style=\"width:0%;\" class=\"dz-progress-bar\"></div></div>";
						dropzoneDiv += "<div class=\"limited-upload-notice\">'.$limit_msg.'</div>";
						dropzoneDiv += "<div class=\"share-prompt\"></div>";
						dropzoneDiv += "<button id=\"process-upload\">' . _t('divers', 'up').'</button><div class=\"upload-message clear\"></div>";
						dropzoneDiv += "</div>";
						    
				$( ".internal-content.files h2" ).after(dropzoneDiv);
				$(".share-prompt").append($("#share-file"));
    			$("#uploadform").remove();
						    
						    
	    	$("div#multiple-uploads").dropzone({
					paramName: "file",
					url: "'.SITE_ROOT_URL.'library/upload.php",
					maxFilesize: '.MEDIA_ALLOWED_SIZE.',
					maxFiles: '.$maxfiles.',
					addRemoveLinks: true,
					parallelUploads: '.$maxfiles.',
					dictCancelUpload: "' . mb_ucfirst(_t('btn', 'annul')).'",
					dictRemoveFile: "' . mb_ucfirst(_t('btn', 'annul')).'",
					dictMaxFilesExceeded: "' . _t('divers', 'up').'",
					dictDefaultMessage: "' . _t('upload', 'addfiles').'",
					dictInvalidFileType: "' . _t('upload', 'wrong_ext').'",
					dictFileTooBig: "' . sprintf(_t('upload','upload_size'), MEDIA_ALLOWED_SIZE).'",
					acceptedFiles: "'.$filesAllowed.'",
					autoProcessQueue:false,
					init: function() {
						// for accessing dropzone : https://github.com/enyo/dropzone/issues/180
						var dropzone = this;
					    $("#process-upload").click(function() {
					    	// to proceed full queue parallelUploads must be equal or > to maxFileSize
					    	// https://github.com/enyo/dropzone/issues/462
					    	dropzone.processQueue();
					    });
					},
					totaluploadprogress: function(progress) {
						$("#dz-total-progress .dz-progress-bar").css("width", progress + "%");
					},
					sending: function(file, xhr, formData) {
						formData.append("id", "'.$id.'");
						if ($("input[name=\"shared_file\"]").is(":checked")) formData.append("is_shared", "1");
					},
					success: function(file, response) {
						    
						var data = jQuery.parseJSON(response);
						if (data["transfer"] == "success") {
						    
							fileslist += "|" + data["filename"] ;
							this.removeFile(file);
                            queueCompleted = true;
						} else {
							// this.removeAllFiles();
                            queueCompleted = false;
							$("div.upload-message").removeClass("info error").addClass("error").html("' . _t('upload', 'error') . '");
							    
						}
					},
					queuecomplete: function(file) {
                        // behavior is bit strange on queuecompleted, also called when file is invalid
                        // https://github.com/enyo/dropzone/issues/578
                        // to prevent that bug, using queueCompleted flag, triggered in success method (see above)
						if (queueCompleted === true && this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
							$("#dz-total-progress .dz-progress-bar").css("width", "0%");
							$("div.upload-message").removeClass("info error").addClass("info").html("' . _t('upload', 'confirmed') . '");
							// console.log(fileslist);
							var d = new Date(); // to prevent cache issues
							jQuery.ajax({
									url: "'. SITE_ROOT_URL .'/workshop/_ajax_filelist.php", data: "id='.$id.'&folder='.$id.'&rooturl=' . SITE_ROOT_URL. '&upfiles=" + fileslist +  "&time=" + d.getMilliseconds(),
									cache: false,
									success: function(response){
											jQuery("#allfiles").empty().append(response).hide().fadeIn();
											jQuery("#allfiles").find("a[href$=\".jpg\"],a[href$=\".jpeg\"],a[href$=\".png\"],a[href$=\".gif\"], a[href$=\".JPG\"],a[href$=\".JPEG\"],a[href$=\".PNG\"],a[href$=\".GIF\"]").not(".dlfile").colorbox({transition:"fade"});
									    
									}
									    
  					});<!-- closing jQuery.ajax  -->
						fileslist = ""; // we empty the list
                        queueCompleted = false; // we init flag again
					  }
					//}
}
				});<!-- closing dropzone  -->
			}); <!-- closing dom ready  -->
    	</script>
    	';
        footerAddInlineJS($js, 'default', false);
        
    }
    
}

if(!function_exists('DisplayUrlFiles')) {
    
    function DisplayUrlFiles($work_id, $work_name) {
        ActiveItemKey($GLOBALS['activeitem'])=='files' ? $class='active' : $class='';
        
        $link = array('rub'=> $GLOBALS['links'][U_L]['files']['linkvalue'],'id'=>$work_id, 'name' => $work_name);
        $content='<a href="'.HrefMaker($link).'" title="'.formatText(_t('workshop','shared_files'), '2ATT').'" id="nav-files" class="'.$class.'">'._t('workshop','shared_files').'</a>'.PHP_EOL;
        echo $content;
    }
    
}

/**
 * DisplayUrlAllCalendar()
 * affichage de l'URL de détails d'un calendrier
 * @param $workshop_id
 * @return
 **/
if(!function_exists('DisplayUrlAllCalendar')) {
    
    function DisplayUrlAllCalendar($workshop_id) {
        $link_table= array('rub'=> $GLOBALS['links'][U_L]['calendar']['linkvalue'],'id'=>$workshop_id);
        $content='<p>'.PHP_EOL;
        $content.='<a href="'.HrefMaker($link_table).'" title="'.formatText(_t('workshop','cal_all'), '2ATT').'">'._t('workshop','cal_all').'</a>'.PHP_EOL;
        $content.='</p>'.PHP_EOL;
        echo $content;
    }
    
}

/**
 * DisplayUrlInscription()
 * affichage de l'URL d'inscription au groupe de travail
 * @param $workshop_id
 * @param $testcookie
 * @return
 **/
if(!function_exists('DisplayUrlInscription')) {
    
    function DisplayUrlInscription($workshop_id, $workshop_restricted, $testcookie) {
        $link_table= array('rub'=> $GLOBALS['links'][U_L]['workgroup-subscription']['linkvalue'],'id'=>$workshop_id);
        $link_table2= array('rub'=> $GLOBALS['links'][U_L]['user-prefs']['linkvalue']);
        
        if (!isset($_SESSION['authenticated'])) {
            $content='<div class="info">'._t('divers','noauth').''.PHP_EOL;
            $content.='<br />'._t('divers','creaauth').' : '.PHP_EOL;
            $content.='<a href="'.HrefMaker($link_table2).'" title="'.formatText(_t('divers','auth'), '2ATT').'" class="login-link">'._t('divers','auth').'</a>'.PHP_EOL;
            $content.='</div>'.PHP_EOL;
        }
        else{
            if ($testcookie <> true) {
                $content='<div class="info">'._t('workshop','noinscription').''.PHP_EOL;
                if($workshop_restricted == 1) {
                    $content .= '<span class="restricted-wg">'.mb_ucfirst(_t('workshop','restricted')).'.</span>'.PHP_EOL;
                } else {
                    $content.='<br />'._t('workshop','creainscription2').' : '.PHP_EOL;
                    $content.='<a href="'.HrefMaker($link_table).'" title="'.formatText(_t('workshop','creainscription'), '2ATT').'">'._t('workshop','creainscription').'</a>';
                }
                $content.='</div>'.PHP_EOL;
            }
        }
        echo $content;
    }
    
}

/**
 * DisplayUrlTopicList()
 * affichage URL pour accéder aux discussions
 * @param $work_id
 * @param $contenu
 * @return
 **/
if(!function_exists('DisplayUrlTopicList')) {
    
    function DisplayUrlTopicList($work_id, $work_name) {
        (ActiveItemKey($GLOBALS['activeitem'])=='topic-list' || ActiveItemKey($GLOBALS['activeitem'])=='topic-add' || ActiveItemKey($GLOBALS['activeitem'])=='topic' || ActiveItemKey($GLOBALS['activeitem'])=='post-update') ? $class='active' : $class='';
        
        $link_table= array('rub'=> $GLOBALS['links'][U_L]['topic-list']['linkvalue'],'id'=>$work_id, 'name' => $work_name);
        $content='<a href="'.HrefMaker($link_table).'" title="'.formatText(_t('workshop','com_public'), '2ATT').'" id="nav-discussion" class="'.$class.'">'._t('workshop','com_public').'</a>'.PHP_EOL;
        echo $content;
    }
    
}

/**
 * DisplayUrlCalendar()
 * affichage URL pour accéder aux calendrier
 * @param $work_id
 * @param $contenu
 * @return
 **/
if(!function_exists('DisplayUrlCalendar')) {
    
    function DisplayUrlCalendar($work_id, $work_name) {
        (ActiveItemKey($GLOBALS['activeitem'])=='calendar' || ActiveItemKey($GLOBALS['activeitem'])=='workgroup' )? $class='active' : $class='';
        
        $link_table= array('rub'=> $GLOBALS['links'][U_L]['calendar']['linkvalue'],'id'=>$work_id, 'name' => $work_name);
        $content='<a href="'.HrefMaker($link_table).'" title="'.formatText(_t('workshop','cal_all'), '2ATT').'" id="nav-calendar" class="'.$class.'">'._t('workshop','cal_all').'</a>'.PHP_EOL;
        echo $content;
    }
    
}

/**
 * DisplayUrlListerapport()
 * affichage URL pour accéder aux rapports
 * @param $work_id
 * @param $contenu
 * @return
 **/
if(!function_exists('DisplayUrlListerapport')) {
    
    function DisplayUrlListerapport($work_id, $work_name) {
        ActiveItemKey($GLOBALS['activeitem'])=='report-all' ? $class='active' : $class='';
        
        $link_table= array('rub'=> $GLOBALS['links'][U_L]['report-all']['linkvalue'],'id'=>$work_id, 'name' => $work_name);
        $content='<a href="'.HrefMaker($link_table).'" title="'.formatText(_t('workshop','barre_report'), '2ATT').'" id="nav-report" class="'.$class.'">'._t('workshop','barre_report').'</a>'.PHP_EOL;
        echo $content;
    }
    
}

/**
 * DisplayUrlListeutilisateurs()
 * affichage URL pour accéder aux utilisatuers
 * @param $work_id
 * @param $contenu
 * @return
 **/
if(!function_exists('DisplayUrlListeutilisateur')) {
    
    function DisplayUrlListeutilisateur($work_id, $work_name) {
        ActiveItemKey($GLOBALS['activeitem'])=='user-all' ? $class='active' : $class='';
        
        $link_table= array('rub'=> $GLOBALS['links'][U_L]['user-all']['linkvalue'],'id'=>$work_id, 'name' => $work_name);
        $content='<a href="'.HrefMaker($link_table).'" title="'.formatText(_t('workshop','participant'), '2ATT').'" id="nav-user" class="'.$class.'">'._t('workshop','participant').'</a>'.PHP_EOL;
        echo $content;
    }
    
}

if(!function_exists('DisplayUrlAddTopic')) {
    
    function DisplayUrlAddTopic($work_id) {
        $link_table= array('rub'=> $GLOBALS['links'][U_L]['topic-add']['linkvalue'],'id'=>$work_id);
        $content='<a href="'.HrefMaker($link_table).'" title="'.formatText(_t('workshop','add_com'), '2ATT').'" class="add_topic button"><i class="fa fa-plus" aria-hidden="true"></i> '._t('workshop','add_com').'</a>'.PHP_EOL;
        echo $content;
    }
    
}

/**
 * DisplayListWorkshop()
 * affichage de la liste de groupe de travail
 * @param integer $id_filter
 * @param integer $filter
 * @return
 **/
if(!function_exists('DisplayListWorkshop')) {
    
    function DisplayListWorkshop($id_filter=-1, $filter=-1) {
        
        if ($filter == -1) $filter='public';
        
        if($filter == 'LEVEL') {
            $levels = getLevelChildren($GLOBALS['sql_object']->DBSelect(SQL_getLevelsList()), $id_filter);
            $id_filter = array_extract($levels, 'level_id', true, 'children');
        }
        
        if(ActiveItemKey($GLOBALS['activeitem']) == 'workgroup-archives') $filter = 'archives_p';
        $data=$GLOBALS['sql_object'] -> DBSelect(SQL_getWorkshopList($debut=-1, $limite=-1, $filter , $id_filter));
        
        $sep = ' <span class="separator">/</span> ';
        
        if($data!=0)
        {
            $content= '';
            for($i=0; $i<count($data); $i++) {
                
                $levels = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList());
                $level = getLevelParent($levels, $data[$i]['level_id'], 0);
                
                $link_detail = array('rub'=> $GLOBALS['links'][U_L]['workgroup']['linkvalue'],'id'=>$data[$i]['workshop_id'],'name'=>$data[$i]['workshop_denomination']);
                if(is_array($level)) {
                    $link_level = array('rub' => $GLOBALS['links'][U_L]['workgroup']['linkvalue'], 'filter' => $GLOBALS['filters'][U_L]['level']['linkvalue'], 'id' => $level['id'], 'name' => $level['name']);
                }
                $workshop_title=formatText($data[$i]['workshop_denomination'], '2HTML');
                $workshop_resume=formatText($data[$i]['workshop_resume'], '2HTML');
                
                if($data[$i]['workshop_restricted'] == 1) {
                    $workshop_restricted = ' <span class="wg-restricted">('._t('workshop', 'restricted').')</span>'.PHP_EOL;
                } else {
                    $workshop_restricted = "";
                }
                
                $content.='<h2>'.PHP_EOL;
                $content.='<a href="'.HrefMaker($link_detail).'" title="'.formatText($workshop_title, '2ATT').'">'.$workshop_title.'</a>'.PHP_EOL;
                $content.=$workshop_restricted;
                $content.='</h2>'.PHP_EOL;
                $content.='<div class="chapo clear">'.$workshop_resume.'</div>'.PHP_EOL;
                $content.='<p class="filter_info">'.PHP_EOL;
                if(is_array($level)) $content .=  ' ' . $level['label'] . ' : <a href="' . HrefMaker($link_level) . '" title="' . $GLOBALS['filters'][U_L]['level']['desc'] . ' : ' . formatText($level['name'], '2ATT') . '" class="filter_info_theme">' . $level['name'] . '</a>'. PHP_EOL;
                $content.='</p>'.PHP_EOL;
                if($GLOBALS['l21auth']->isWorkgroupUser($data[$i]['workshop_id'], $GLOBALS['sql_object'])) $content .= '<div class="group-member">'. _t('workshop', 'member') .'</div>';
                
                $content.= '<a class="readmore" href="'.HrefMaker($link_detail).'">'._t('workshop', 'access_to').'</a>';
                $content.='<hr />'.PHP_EOL;
            }
        }
        else
        {
            $content='<p class="info">'._t('divers','nodata').'</p>';
        }
        
        echo $content;
    }
    
}

/**
 * DisplayCalendar()
 * affichage du calendrier
 * @param $workshop_id
 * @param $nb
 * @return
 **/
if(!function_exists('DisplayCalendar')) {
    
    function DisplayCalendar($workshop_id) {
        $data=$GLOBALS['sql_object'] -> DBSelect(SQL_getoneListCalWorkshop($workshop_id, "ALL"));
        $content = ''.PHP_EOL;
        if($data!=0)
        {
            $datenow= strtotime("now");
            $inter=1*24*3600;
            
            for($i=0; $i<count($data); $i++) {
                
                $workcal_id=$data[$i]['workcal_id'];
                $workcal_title=formatText($data[$i]['workcal_task'], '2HTML');
                $workcal_resume=formatText($data[$i]['workcal_task_details'], '2HTML');
                $workcal_author=formatText($data[$i]['user_login'], '2HTML');
                $workcal_date_publi=formatText($data[$i]['workcal_task_date_display'], '2HTML');
                $link_table= array('rub'=> $GLOBALS['links'][U_L]['user-profile']['linkvalue'],'id'=>$data[$i]['workcal_posted_by'], 'name'=>$workcal_author);
                
                if($data[$i]['workcal_workshop_id'] == 999999999) {
                    $common_task = '<span class="task_common">' . _t('workshop', 'task_common') . '</span>';
                } else {
                    $common_task = '';
                }
                
                $datetask=$data[$i]['workcal_task_date_display'];
                
                $datetask=formatDate($datetask, true);
                $datetask=explode("-", $datetask);
                $annee = $datetask[0];
                $mois = $datetask[1];
                $jour = $datetask[2];
                $datetask2 = mktime (0, 0, 0, $mois, $jour, $annee);
                
                
                $ical_url  = 'summary='.rawurlencode(strip_tags($workcal_title));
                $ical_url .= '&description='.rawurlencode(strip_tags($workcal_resume));
                $ical_url .= '&date='.rawurlencode($annee.$mois.$jour);
                $ical_url .= '&filename='.rawurlencode('wg'.$workshop_id.'-event'.$workcal_id);
                $ical_url .= '&uri='.rawurlencode(SITE_ROOT_URL.'public/index.php?'.$_SERVER["QUERY_STRING"]);
                
                
                $ical_url = SITE_ROOT_URL.'workshop/ical.php?'.$ical_url;
                
                if (($datetask2+$inter)>$datenow) $class='in'; else $class='out';
                
                $content.='<div id="cal-'.$workcal_id.'" class="task_'.$class.'">'.PHP_EOL;
                $content.='<div class="task_meta"><p><a class="ical" href="'. $ical_url .'" title="'._t('workshop', 'add_to_calendar').'"><span class="hide">'._t('workshop', 'add_to_calendar').'<span></a>'.$workcal_date_publi.'</p>';
                $content.='<p><a href="'.HrefMaker($link_table).'" title="'.formatText($workcal_author, '2ATT').'">'.$workcal_author.'</a></p></div>';
                $content.='<div class="task_content"><h3>'.$workcal_title.'</h3>'.PHP_EOL;
                $content.=$common_task.PHP_EOL;
                $content.='<div class="chapo clear">'.$workcal_resume.'</div></div>'.PHP_EOL;
                $content.='</div>'.PHP_EOL;
                $content.='<br style="clear:both" />'.PHP_EOL;
            }
        }
        else
        {
            $content.='<p class="info">'._t('divers','nodata').'</p>';
        }
        
        echo $content;
    }
    
}

/**
 * getAssociatedProjcts()
 * récupère les projets associés à un groupe de travail
 * @param $workshop_id
 * @param integer $title
 * @return
 **/
if(!function_exists('getAssociatedProjects')) {
    
    function getAssociatedProjects($workshop_id) {
        
        // getting associated projects
        $projects = $GLOBALS['sql_object'] -> DBSelect(SQL_getAssociatedProjects($workshop_id, array('P', 'PA')));
        $content = '';
        
        if(!$GLOBALS['l21auth']->isWorkgroupUser($workshop_id, $GLOBALS['sql_object'])) return false;
        
        if(isset($projects[0]['project_id'])) {
            $content = '<div class="wg-associated-projects">';
            $content .= '<span class="block-title">'._t('workshop', 'associated_projects').' :</span>';
            if(count($projects) > 1) $content .= '<ul>';
            for($i=0; $i < count($projects); $i++) {
                $link_project = array('rub' => $GLOBALS['links'][U_L]['project']['linkvalue'], 'id' => $projects[$i]['project_id'], 'name' => $projects[$i]['project_name']);
                if(count($projects) > 1) $content .= '<li>';
                $content .= ' <a href = "'. HrefMaker($link_project) .'" title="'. $projects[$i]['project_name'].'">'. $projects[$i]['project_name'] . '</a>';
                if(count($projects) > 1) $content .= '</li>';
            }
            if(count($projects) > 1) $content .= '</ul>';
            $content .= '</div>';
        }
        
        return $content;
        
    }
    
}

/**
 * DisplayOneWorkshop()
 * affichage du détail d'un groupe de travail
 * @param $workshop_id
 * @param integer $title
 * @return
 **/
if(!function_exists('DisplayOneWorkshop')) {
    
    function DisplayOneWorkshop($workshop_id, $title=-1) {
        $data=$GLOBALS['sql_object'] -> DBSelect(SQL_getoneCompleteWorkshop($workshop_id, array('P', 'PA')));
        
        $content = ''.PHP_EOL;
        
        if($data == 0) error_redirect();
        
        $levels = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList());
        $level = getLevelParent($levels, $data[0]['level_id'], 0);
        
        $sep = ' <span class="separator">/</span> ';
        
        if(count($data)!=1) exit;
        else {
            
            $link_self= array('rub'=> $GLOBALS['links'][U_L]['workgroup']['linkvalue'],'id'=>$workshop_id);
            if(is_array($level)) {
                $link_level = array('rub' => $GLOBALS['links'][U_L]['workgroup']['linkvalue'], 'filter' => $GLOBALS['filters'][U_L]['level']['linkvalue'], 'id' => $level['id'], 'name' => $level['name']);
            }
            $workshop_title=formatText($data[0]['workshop_denomination'], '2HTML');
            $workshop_resume=formatText($data[0]['workshop_resume'], '2HTML');
            //$workshop_comment=formatText(cutText($data[0]['workshop_comment'],150), '2HTML');
            $workshop_level=formatText(cutText($data[0]['level_name'],50), '2HTML');
            
            if($data[0]['workshop_restricted'] == 1) {
                $workshop_restricted = ' <span class="wg-restricted">('._t('workshop', 'restricted').')</span>'.PHP_EOL;
            } else {
                $workshop_restricted = "";
            }
            
            
            if ($title<>-1) {
                $content.='<h1>';
                $content.=$workshop_title;
                $content.=$workshop_restricted;
                $content.='</h1>'.PHP_EOL;
            }
            else{
                $content.='<p class="published_by">'.PHP_EOL;
                $content.= formatted_permalink($link_self);
                $content.='</p>'.PHP_EOL;
                
                //$content.='<h2>'._t('workshop','det').'</h2>'.PHP_EOL;
                $content.='<div class="chapo clear">'.$workshop_resume.'</div>'.PHP_EOL;
                //$content.='<p>'.$workshop_comment.'</p>'.PHP_EOL;
                if($GLOBALS['l21auth']->isWorkgroupUser($workshop_id, $GLOBALS['sql_object'])) $content .= '<span class="group-member">'. _t('workshop', 'member') .'</span>';
                
                $content.='<p class="filter_info">'.PHP_EOL;
                if(is_array($level)) $content .=  $level['label'] . ' : <a href="' . HrefMaker($link_level) . '" title="' . $GLOBALS['filters'][U_L]['level']['desc'] . ' : ' . formatText($level['name'], '2ATT') . '" class="filter_info_theme">' . $level['name'] . '</a>' . PHP_EOL;
                // $content .=  _t('divers','sousthemeref').' : '.$workshop_level.PHP_EOL;
                $content.='</p>'.PHP_EOL;
            }
            
        }
        
        
        echo $content;
    }
    
}

/**
 * DisplayUserWorkshop()
 * affichage des utilisateurs/organisateurs d'un groupe de travail
 * @param $workshop_id
 * @return
 **/
if(!function_exists('DisplayUserWorkshop')) {
    
    function DisplayUserWorkshop($workshop_id) {
        
        if(!$GLOBALS['l21auth']->isWorkgroupUser($workshop_id, $GLOBALS['sql_object'])) return false;
        
        $data=$GLOBALS['sql_object'] -> DBSelect(SQL_getWorkshopUserList($workshop_id));
        $content1='<div><p class="workgroup-users-list-header">'.mb_ucfirst(_t('workshop','organizer')).' : </p><ol class="workgroup-users-list">';
        $content2='<div><p class="workgroup-users-list-header">'.mb_ucfirst(_t('workshop','user')).' : </p><ol class="workgroup-users-list">';
        
        $sep_u = $sep_a = '';
        
        if($data!=0)
        {
            for($i=0; $i<count($data); $i++) {
                
                $workcal_author=formatText($data[$i]['user_login'], '2HTML');
                $link_table= array('rub'=> $GLOBALS['links'][U_L]['user-profile']['linkvalue'],'id'=>$data[$i]['jwu_user_id'], 'name'=>$data[$i]['user_login']);
                if($data[$i]['profile_firstname']!='' || $data[$i]['profile_lastname']!='') $name=' ('.formatText($data[$i]['profile_firstname'], '2HTML').' '. formatText($data[$i]['profile_lastname'], '2HTML') .')';
                else $name='';
                
                if($data[$i]['jwu_user_right']<>"U") {
                    $content1.= $sep_u.'<li><a href="'.HrefMaker($link_table).'" title="'.formatText($workcal_author, '2ATT').'">'.$workcal_author.$name.'</a> <a href="#sendmessage-content" class="send-message" data-user-login="'.$data[$i]['user_login'].'" title="' . sprintf(_t('contact', 'pm_send_to'), $data[$i]['user_login']) . '"><i class="fa fa-paper-plane-o" aria-hidden="true"></i><span> ' . sprintf(_t('contact', 'pm_send_to'), $data[$i]['user_login']) . '</span></a></li>';
                }
                else {
                    $content2.=$sep_a.'<li><a href="'.HrefMaker($link_table).'" title="'.formatText($workcal_author, '2ATT').'">'.$workcal_author.$name.'</a> <a href="#sendmessage-content" class="send-message" data-user-login="'.$data[$i]['user_login'].'" tile="' . sprintf(_t('contact', 'pm_send_to'), $data[$i]['user_login']) . '"><i class="fa fa-paper-plane-o" aria-hidden="true"></i><span> ' . sprintf(_t('contact', 'pm_send_to'), $data[$i]['user_login']) . '</span></a></li>';
                }
                
            }
            $content1.='</ol></div>'.PHP_EOL;
            $content2.='</ol></div>'.PHP_EOL;
            $content=$content1.$content2;
            echo get_pm_code($data[0]['user_login']);
        }
        else
        {
            $content.='<p class="info">'._t('workshop','no_user').'</p>';
        }
        echo $content;
    }
    
}

/**
 * DisplayListReport()
 * affichage de la liste des rapports d'un groupe de travail
 * @param $workshop_id
 * @return
 **/
if(!function_exists('DisplayListReport')) {
    
    function DisplayListReport($workshop_id, $status = 'P') {
        $data=$GLOBALS['sql_object'] -> DBSelect(SQL_getWorkshopReportList($workshop_id, $status));
        $content = ''.PHP_EOL;
        if($data!=0)
        {
            for($i=0; $i<count($data); $i++) {
                
                $link_table= array('rub'=> $GLOBALS['links'][U_L]['report']['linkvalue'],'id'=>$data[$i]['workrep_id'], 'name'=>$data[$i]['workrep_title']);
                $workrep_title=formatText($data[$i]['workrep_title'], '2HTML');
                $workrep_resume=formatText($data[$i]['workrep_resume'], '2HTML');
                $workrep_date_publi=formatText($data[$i]['workrep_published_date_display'], '2HTML');
                $content.='<h3><a href="'.HrefMaker($link_table).'" title="'.formatText($workrep_title, '2ATT').'">'.$workrep_title.'</a></h3>'.PHP_EOL;
                $content.='<div class="chapo clear">'.$workrep_resume.'</div>'.PHP_EOL;
                $content.='<a class="readmore" href="'.HrefMaker($link_table).'">'._t('btn', 'read_more').'</a>';
                $content.='<p class="filter_info">'._t('workshop','date_report').' : <span>'.$workrep_date_publi.'</span></p>'.PHP_EOL;
                
                $content.='<hr />'.PHP_EOL;
            }
        }
        else
        {
            $content.='<p class="info">'._t('workshop','no_report').'</p>';
        }
        echo $content;
    }
    
}

/**
 * DisplayListTopic()
 * affichage de la liste des discussions
 * @param $workshop_id
 * @param $debut
 * @return
 **/
if(!function_exists('DisplayListTopic')) {
    
    function DisplayListTopic($workshop_id, $debut) {
        
        if(!$GLOBALS['l21auth']->isWorkgroupUser($workshop_id, $GLOBALS['sql_object'])) return false;
        
        include_once('../class/class.workshop_com.php');
        $workshop_com_object = new workshop_com;
        
        // messages read by current user
        $read_messages = $workshop_com_object->getReadMessages($GLOBALS['sql_object']);
        // print_r($read_messages);
        
        $r = $GLOBALS['sql_object'] -> DBSelect( SQL_getoneCompleteWorkshop($workshop_id));
        $workshop_status = $r[0]['workshop_statut'];
        
        $result_workcom_list=$GLOBALS['sql_object'] -> DBSelect(SQL_getWorkcomList($debut, SELECT_LIMIT, $workshop_id));
        $result_nb_com=$GLOBALS['sql_object'] -> DBSelect(SQL_getcountnbcom($workshop_id));
        $bdd_nb_com=$result_nb_com[0]['num_rows'];
        
        //     print_r($result_workcom_list);
        
        $table_link=array('rub' => $GLOBALS['links'][U_L]['topic-list']['linkvalue'],'id' => $workshop_id);
        echo $bdd_nb_com_display = "<p class=\"nb_sujet\">".$bdd_nb_com." "._t('workshop','nb_total_com')."</p>\n";
        if($result_workcom_list!=0) {
            
            $content= "<table class=\"table_discussion\" summary=\""._t('workshop','com')."\">".PHP_EOL;
            $content.= "<thead>\n";
            $content.= "<tr>\n";
            $content.= "<td>".mb_ucfirst(_t('workshop','com_subject'))."</td>".PHP_EOL;
            // $content.= "<td>".mb_ucfirst(_t('workshop','com_author'))."</td>".PHP_EOL;
            $content.= "<td class=\"nb-replies\">".mb_ucfirst(_t('workshop','com_nb_rep'))."</td>".PHP_EOL;
            $content.= "<td class=\"nb-views\">".mb_ucfirst(_t('workshop','com_nb_views'))."</td>".PHP_EOL;
            $content.= "<td class=\"date\">".mb_ucfirst(_t('workshop','com_date_last'))."</td>".PHP_EOL;
            $content.= "</tr>".PHP_EOL;
            $content.= "</thead>".PHP_EOL;
            $content.= "<tbody>".PHP_EOL;
            
            
            for($i=0; $i<count($result_workcom_list); $i++) {
                
                $result_workcom_det=$GLOBALS['sql_object'] -> DBSelect(SQL_getWorkcom_detList($result_workcom_list[$i]['workcom_id']));
                $link_user= array('rub'=> $GLOBALS['links'][U_L]['user-profile']['linkvalue'],'id'=>$result_workcom_list[$i]['workcom_user_id'], 'name' => $result_workcom_list[$i]['user_login']);
                $link_det_com= array('rub'=> $GLOBALS['links'][U_L]['topic']['linkvalue'],'id'=>$result_workcom_list[$i]['workcom_id'], 'parentid' => $workshop_id, 'name' => $result_workcom_list[$i]['workcom_subject']);
                
                $workcom_title=formatText(Stringy\Stringy::create($result_workcom_list[$i]['workcom_subject'], CHARSET)->safeTruncate(100, ' ...'), '2HTML');
                
                $workcom_user=formatText(cutText($result_workcom_list[$i]['user_login'], 15, 1), '2HTML');
                
                //we check if thread has been read alreay and if new messages were posted
                $res = $GLOBALS['sql_object'] -> DBSelect(SQL_getLatestMessage($workshop_id, $result_workcom_list[$i]['workcom_id']));
                if(isset($read_messages[$result_workcom_list[$i]['workcom_id']])) {
                    $class = 'read';
                    $atitle = sprintf(_t('workshop', 'com_followed'), $workcom_title);
                } else {
                    $class = 'unread';
                    $atitle = sprintf(_t('workshop', 'com_not_followed'), $workcom_title);
                }
                
                // by default we take value from main thread
                $last_date_msg = $result_workcom_list[$i]['workcom_date_crea_display'];
                
                // there is, at least, one response to thread
                if(isset($res[0]['workcom_id'])) {
                    $debut = ((int) (($result_workcom_det[0]['nb_rep'] -1) / SELECT_LIMIT)) * SELECT_LIMIT;
                    $link_last_msg = array('rub'=> $GLOBALS['links'][U_L]['topic']['linkvalue'],'id'=>$result_workcom_list[$i]['workcom_id'], 'parentid' => $workshop_id, 'name' => $result_workcom_list[$i]['workcom_subject'], 'debut' => $debut,  '#' => 'msg-'.$res[0]['workcom_id']);
                    $last_date_msg = $res[0]['workcom_date_crea_display'];
                    
                    $link_last_user = array('rub'=> $GLOBALS['links'][U_L]['user-profile']['linkvalue'],'id'=>$res[0]['workcom_user_id'], 'name' => $res[0]['user_login']);
                    
                    $last_user =  formatText(cutText($res[0]['user_login'], 15, 1), '2HTML');
                }
                
                // echo $res[0]['workcom_id']. " - ";
                if(isset($res[0]['workcom_id']) && isset($read_messages[$result_workcom_list[$i]['workcom_id']]) && $read_messages[$result_workcom_list[$i]['workcom_id']] < $res[0]['workcom_id']) {
                    $class .= " new-msg";
                    
                    // we get post position to handle nicely pagination
                    $rpos = $GLOBALS['sql_object'] -> DBSelect( SQL_get_post_position($read_messages[$result_workcom_list[$i]['workcom_id']], $result_workcom_list[$i]['workcom_id']));
                    
                    $debut_lastread = ((int) (($rpos[0]['position'] ) / SELECT_LIMIT)) * SELECT_LIMIT;
                    // echo "position : " .$rpos[0]['position']." - debut : ".$debut_lastread."<br>";
                    
                    $link_lastread_msg= array('rub'=> $GLOBALS['links'][U_L]['topic']['linkvalue'],'id'=>$result_workcom_list[$i]['workcom_id'], 'parentid' => $workshop_id, 'name' => $result_workcom_list[$i]['workcom_subject'], 'debut' => $debut_lastread, '#' => 'msg-'.$read_messages[$result_workcom_list[$i]['workcom_id']]);
                    
                    $lastread_link = '<a class="last-read-msg" href="'.get_permalink($link_lastread_msg).'" title="'.formatText(_t('workshop', 'com_latest_read_msg'), '2ATT').'"><span>'._t('workshop', 'com_latest_read_msg').'</span></a>';
                } else $class .= " no-new-msg";
                
                
                $content.= "<tr>".PHP_EOL;
                if ($result_workcom_list[$i]['workcom_statut']=='C') {
                    $locked = "<img class=\"locked\" src=\"" .PUBLIC_THEME_URL. "images/lock.png\" alt=\"\" title=\""._t('workshop', 'com_p_lock')."\" />";
                } else {
                    $locked = '';
                }
                $content.= "<td class=\"subject ".$class."\">";
                $content.= "<a href=\"".HrefMaker($link_det_com)."\" title=\"".formatText($atitle, '2ATT')."\" class=\"table_title\">".$workcom_title."</a>";
                $content .= "<div class=\"subject-by\"> ". formatText(_t('workshop', 'com_by'), '2HTML')." <a href=\"".HrefMaker($link_user)."\" title=\"".formatText($workcom_user, '2ATT')."\" class=\"table_auth\">".$workcom_user."</a></div>";
                if(isset($lastread_link)) {
                    $content .= $lastread_link.PHP_EOL;
                    unset($lastread_link);
                }
                $content .=$locked;
                $content .= "</td>".PHP_EOL;
                if ($result_workcom_det[0]['nb_rep']=="") {
                    $content.= "<td class=\"nb-replies\">0</td>".PHP_EOL;
                }
                else $content.= "<td class=\"nb-replies\">".$result_workcom_det[0]['nb_rep']."</td>".PHP_EOL;
                $content.= "<td class=\"nb-views\">".$result_workcom_list[$i]['workcom_viewed']."</td>".PHP_EOL;
                $content.= "<td class=\"date\">";
                if(isset($link_last_msg)) {
                    $content.= '<a class="last-msg" href="'.get_permalink($link_last_msg).'" title="'.formatText(_t('workshop', 'com_latest_msg'), '2ATT').'"><span>'.$last_date_msg.'</span></a><br />'.formatText(_t('workshop', 'com_by'), '2HTML').' <a href="'.HrefMaker($link_last_user).'">'.$last_user.'</a>';
                    unset($link_last_msg);
                } else {
                    $content.= '<a class="last-msg" href="'.get_permalink($link_det_com).'" title="'.formatText(_t('workshop', 'com_latest_msg'), '2ATT').'"><span>'.$last_date_msg.'</span></a><br />'.formatText(_t('workshop', 'com_by'), '2HTML').' <a href="'.HrefMaker($link_user).'">'.$workcom_user.'</a>';
                }
                $content.= "</td>".PHP_EOL;
                
                $content.= "</tr>".PHP_EOL;
            }
            
            $content.= "</tbody>".PHP_EOL;
            $content.= "</table>".PHP_EOL;
        }else {
            $content= '<p class="info">'._t('workshop','no_com').'</p>'.PHP_EOL;
        }
        if($workshop_status == 'P' ) DisplayUrlAddTopic($workshop_id);
        echo get_linkin_page($table_link, $bdd_nb_com, $debut);
        if(isset($_SESSION['message'])) {
            echo $_SESSION['message'];
            unset($_SESSION['message']);
        }
        echo $content;
        echo get_linkin_page($table_link, $bdd_nb_com, $debut);
        if($workshop_status == 'P') DisplayUrlAddTopic($workshop_id);
    }
    
}

/**
 * DisplayTopic()
 * affichage d'une discussion
 * @param $workshop_id
 * @param $topic_id
 * @param $debut
 * @param $flash
 * @param $post_id
 * @return
 **/
if(!function_exists('DisplayTopic')) {
    
    function DisplayTopic($workshop_id, $topic_id, $debut) {
        
        if(!$GLOBALS['l21auth']->isWorkgroupUser($workshop_id, $GLOBALS['sql_object'])) return false;
        
        // we increment Views counter in database
        include_once('../class/class.workshop_com.php');
        $workshop_com_object = new workshop_com;
        $workshop_com_object->incrementViewsCounter($topic_id, $GLOBALS['sql_object']);
        
        $workshop_com_object->setReadMessages($workshop_id, $topic_id, $GLOBALS['sql_object']);
        
        $r = $GLOBALS['sql_object'] -> DBSelect( SQL_getoneCompleteWorkshop($workshop_id));
        $workshop_status = $r[0]['workshop_statut'];
        
        $dataroot=$GLOBALS['sql_object'] -> DBSelect(SQL_getOnetopicWorkcom($workshop_id, $topic_id, $topic_id));
        $topic_state=$dataroot[0]['workcom_statut'];
        $result_display="";
        
        if($dataroot == 0) error_redirect();
        
        $data=$GLOBALS['sql_object'] -> DBSelect(SQL_getOnetopicWorkcom2($workshop_id, $topic_id, $root= -1, $debut, SELECT_LIMIT));
        $result_nb_com=$GLOBALS['sql_object'] -> DBSelect(SQL_getWorkcom_detList($topic_id));
        $bdd_nb_com=$result_nb_com[0]['nb_rep'];
        
        
        $table_link=array('rub' => $GLOBALS['links'][U_L]['topic']['linkvalue'],'id' => $topic_id, 'parentid' => $workshop_id, 'name' => $dataroot[0]['workcom_subject'] );
        
        $post_title=formatText($dataroot[0]['workcom_subject'], '2HTML');
        $post_body=formatText($dataroot[0]['workcom_body'], '2HTML');
        $post_user=formatText(cutText($dataroot[0]['user_login'], 30, 1), '2HTML');
        
        $current_user_id = base64_decode($_SESSION['userid']);
        
        
        $content= '';
        echo "<p class=\"nb_sujet\">".$bdd_nb_com_display = $bdd_nb_com." "._t('workshop','nb_total_com_mes')."</p>".PHP_EOL;
        echo'<h1>'._t('workshop','com_name').' : '.$post_title.'</h1>'.PHP_EOL;
        echo get_linkin_page($table_link, $bdd_nb_com, $debut);
        echo '<br />'.PHP_EOL;
        
        if ($debut==0) {
            
            $complete_uri = SITE_ROOT_URL . $dataroot[0]['profile_avatar'];
            if($dataroot[0]['profile_avatar'] == "") $user_profile_avatar='<img src="'.PUBLIC_THEME_URL.'/images/no_avatar.png" alt="'.formatText($dataroot[0]['user_login'], '2HTML').'" class="user_profile"/>';
            else $user_profile_avatar='<img src="'.$complete_uri.'" alt="'. formatText($dataroot[0]['user_login'], '2HTML').'" class="user_profile"/>';
            
            if($dataroot[0]['profile_firstname']!='' || $dataroot[0]['profile_lastname']!='') $user_name=' ('.formatText($dataroot[0]['profile_firstname'], '2HTML').' '. formatText($dataroot[0]['profile_lastname'], '2HTML') .')';
            else $user_name='';
            
            $link_user= array('rub'=> $GLOBALS['links'][U_L]['user-profile']['linkvalue'],'id'=>$dataroot[0]['workcom_user_id'], 'name' => $dataroot[0]['user_login']);
            $link_edit= array('rub'=> $GLOBALS['links'][U_L]['post-update']['linkvalue'],'parentid'=>$workshop_id, 'id'=>$dataroot[0]['workcom_id'], 'parentparentid'=>$topic_id, 'name'=> $dataroot[0]['workcom_subject']);
            
            $edit = '';
            if(isset($_SESSION['authenticated']) && $workshop_status == 'P') {
                if (($dataroot[0]['workcom_user_id'] == $current_user_id || $GLOBALS['l21auth']->isWorkgroupOrganiser($current_user_id, $GLOBALS['sql_object'], $workshop_id)  || $GLOBALS['l21auth']->isSuperAdmin()) && $topic_state == 'P') {
                    $edit='<span><a class="edit_topic" href="'.HrefMaker($link_edit).'" title="'.formatText(_t('workshop','mod_com_mes'), '2ATT').'"><span>'._t('divers','modify').'</span></a></span>'.PHP_EOL;
                }
            }
            
            $content.='<div class="blocksujet" id="msg-'.$topic_id.'">'.PHP_EOL;
            $content.='<p class="workshop_auth_sujet">'.$user_profile_avatar.'<a href="'.HrefMaker($link_user).'" title="'.formatText($post_user, '2ATT').'">'.$post_user.'</a> <a href="#sendmessage-content" class="send-message" data-user-login="'.$post_user.'" tile="' . formatText(sprintf(_t('contact', 'pm_send_to'), $post_user), '2ATT'). '"><i class="fa fa-paper-plane-o" aria-hidden="true"></i><span> ' . sprintf(_t('contact', 'pm_send_to'), $post_user) . '</span></a><br />'.$post_user.'<br />'.PHP_EOL;
            $content.='</p>'.PHP_EOL;
            $content.='<span class="workshop_date_sujet">'._t('statut', 'published_on').' '.$dataroot[0]['workcom_date_crea_display'].'</span>'.PHP_EOL;
            $content.=$edit;
            $content.='<div class="post-content">'.PHP_EOL;
            $content.='<h3>'.$post_title.'</h3>'.PHP_EOL;
            $content.='<div class="body">'.$post_body.'</div>'.PHP_EOL;
            $content.='</div>'.PHP_EOL;
            $content.='</div>'.PHP_EOL;
            $last_title=$post_title;
        }
        
        if($data!=0)
        {
            
            for($i=0; $i<count($data); $i++) {
                $class = ($i & 1) ? '' : ' odd';
                $post_title=formatText($data[$i]['workcom_subject'], '2HTML');
                $post_body=formatText($data[$i]['workcom_body'], '2HTML');
                $post_user=formatText(cutText($data[$i]['user_login'], 30, 1), '2HTML');
                $post_id=$data[$i]['workcom_id'];
                $link_user= array('rub'=> $GLOBALS['links'][U_L]['user-profile']['linkvalue'],'id'=>$data[$i]['workcom_user_id'], 'name'=> $data[$i]['user_login']);
                $link_edit= array('rub'=> $GLOBALS['links'][U_L]['post-update']['linkvalue'],'parentid'=>$workshop_id, 'id'=>$data[$i]['workcom_id'], 'parentparentid'=>$topic_id, 'name'=> $data[$i]['workcom_subject']);
                
                // admin formatting
                $link_sup = CURRENT_APP_URL.'index.php?rub=workshop&amp;todo=sup_com&amp;id='.$workshop_id.'&amp;com_id='.$topic_id.'&amp;mes_id='. $data[$i]['workcom_id'];
                $complete_uri = SITE_ROOT_URL . $data[$i]['profile_avatar'];
                if($data[$i]['profile_avatar'] == "") $user_profile_avatar='<img src="'.PUBLIC_THEME_URL.'/images/no_avatar.png" alt="'. formatText($data[$i]['user_login'], '2HTML').'" class="user_profile"/>';
                else $user_profile_avatar='<img src="'.$complete_uri.'" alt="'. formatText($data[$i]['user_login'], '2HTML').'" class="user_profile"/>';
                
                if($data[$i]['profile_firstname']!='' || $data[$i]['profile_lastname']!='') $user_name=' ('.formatText($data[$i]['profile_firstname'], '2HTML').' '. formatText($data[$i]['profile_lastname'], '2HTML') .')';
                else $user_name='';
                
                $action = '';
                // if workshop is not archived, owner message and organizers can edit content
                if(isset($_SESSION['authenticated']) && $workshop_status == 'P') {
                    if (($data[$i]['workcom_user_id'] == $current_user_id || $GLOBALS['l21auth']->isWorkgroupOrganiser($current_user_id, $GLOBALS['sql_object'], $workshop_id)  || $GLOBALS['l21auth']->isSuperAdmin()) && $topic_state == 'P') {
                        $action ='<span><a class="delete_topic action-delete" href="'.$link_sup.'" title="'.formatText(_t('workshop','sup_com_mes'), '2ATT').'"><span>'._t('divers','delete').'</span></a></span>'.PHP_EOL;
                        $action.='<span><a class="edit_topic" href="'.HrefMaker($link_edit).'" title="'.formatText(_t('workshop','mod_com_mes'), '2ATT').'"><span>'._t('divers','modify').'</span></a></span>'.PHP_EOL;
                    }
                }
                $content.='<div class="blocksujet'.$class.'" id="msg-'.$post_id.'">'.PHP_EOL;
                $content.='<p class="workshop_auth_sujet">'.$user_profile_avatar.'<a href="'.HrefMaker($link_user).'" title="'.formatText($post_user, '2ATT').'">'.$post_user.'</a> <a href="#sendmessage-content" class="send-message" data-user-login="'.$post_user.'" tile="' . formatText(sprintf(_t('contact', 'pm_send_to'), $post_user), '2ATT'). '"><i class="fa fa-paper-plane-o" aria-hidden="true"></i><span> ' . sprintf(_t('contact', 'pm_send_to'), $post_user) . '</span></a><br />'.$user_name.'<br />'.PHP_EOL;
                $content.='</p>'.PHP_EOL;
                $content.='<span class="workshop_date_sujet">'._t('statut', 'published_on').' '.$data[$i]['workcom_date_crea_display'].'</span>'.PHP_EOL;
                $content.=$action;
                $content.='<div class="post-content">'.PHP_EOL;
                $content.='<h3>'.$post_title.'</h3>'.PHP_EOL;
                $content.='<div class="body">'.$post_body.'</div>'.PHP_EOL;
                $content.='</div>'.PHP_EOL;
                $content.='</div>'.PHP_EOL;
                $last_title=$post_title;
            }
            $str = '$(".action-delete").on( "click", function () {
						var url = $(this).attr("href");
						alertify.set({
							labels : {
								ok: "'._t('divers', 'yes').'", cancel: "'._t('divers', 'no').'" }
						});
						alertify.confirm("'._t('workshop','sup_com_mes_warning').'", function (e) {
							if (e) {
					    	$.ajax({
					      	  type: "GET",
					          url: "'. SITE_ROOT_URL .'/workshop/_ajax_admin.php",
					          data: { parameters: url },
					          dataType: "json",
					          success: function(data) {
											console.log(data);
					           	if(data.status == 1) {
												alertify.success(data.msg);
												$(data.el).fadeOut("slow");
					            } else {
												alertify.error(data.msg);
											}
					           }
					       });
					              
							}
						});
						return false;
					});';
            addDynamicCSS('../lib/js/alertify.js/dist/css/alertify.css');
            addDynamicCSS('../lib/js/alertify.js/dist/css/alertify-bootstrap.css');
            footerAddJS('../lib/js/alertify.js/dist/js/alertify.js');
            footerAddInlineJS($str);
            echo get_pm_code($data[0]['user_login']);
        }
        else
        {
            $content.='<p class="info">'._t('workshop','no_com_rep').'</p>';
        }
        
        if(isset($_SESSION['message'])) {
            
            echo $_SESSION['message'];
            
            echo '<script type="text/javascript">
                  $(function() {
                
					$("html, body").animate({
    					scrollTop: ($("div.blocksujet").last().offset().top)},500);
                  });
              </script>';
        }
        echo $content;
        
        if(isset($_SESSION['message'])) {
            echo $_SESSION['message'];
            unset($_SESSION['message']);
        }
        
        
        echo get_linkin_page($table_link, $bdd_nb_com, $debut);
        
        if($workshop_status == 'P' && $topic_state == "P") echo GetFormAddPost($workshop_id, $topic_id, '', $last_title);
        else echo $content='<p class="info">'._t('workshop','com_p_lock').'</p>';
    }
    
}


/**
 * AddTopic
 * Ajout d'une discussion
 * @param $workshop_id
 * @param $debut
 * @param $body
 * @param $title
 * @param $confirm
 */
if(!function_exists('AddTopic')) {
    
    function AddTopic($workshop_id, $debut, $body, $title, $confirm_update)
    {
        $r = $GLOBALS['sql_object'] -> DBSelect( SQL_getoneCompleteWorkshop($workshop_id));
        $workshop_status = $r[0]['workshop_statut'];
        if($workshop_status != 'P') ReloadIndex('public');
        
        if(!$confirm_update)  echo GetFormAddTopic($workshop_id);
        else
        {
            //test new value for this post in form
            $integrity=CheckComIntegrity($title, $body);
            if($integrity  == 1)
            {
                $topic_id=AddPersistentPost($title, $body, '', $workshop_id);
                notifyUsersMsg(array('id' => $workshop_id,'user' => $_SESSION['userlogin'] ,'owner' => $_SESSION['userlogin'], 'action' => 'topic_alert', 'topic_subject' => $title, 'topic_body' => $body));
                
                $_SESSION['message'] = '<p class="confirmed">'._t('workshop','confirm_add_com').'</p>'.PHP_EOL;
                
                $link = array('rub'=> $GLOBALS['links'][U_L]['topic-list']['linkvalue'],'id'=>$workshop_id, 'name' => $r[0]['workshop_denomination'], 'amp_no_conversion' =>1);
                header('Location: '.safe_redirect(HrefMaker($link)));
                
            }
            else
            {
                echo "<p class=\"error\">".$integrity."</p>";
                echo GetFormAddTopic($workshop_id, $body, $title);
            }
        }
    }
    
}

/**
 * AddPost
 * Ajout d'un Message
 * @param $workshop_id
 * @param $topic_id
 * @param $debut
 * @param $body
 * @param $title
 */
if(!function_exists('AddPost')) {
    
    function AddPost($workshop_id, $topic_id, $debut, $body, $title)
    {
        $r = $GLOBALS['sql_object'] -> DBSelect( SQL_getoneCompleteWorkshop($workshop_id));
        $workshop_status = $r[0]['workshop_statut'];
        if($workshop_status != 'P') ReloadIndex('public');
        
        $dataroot=$GLOBALS['sql_object'] -> DBSelect(SQL_getOnetopicWorkcom($workshop_id, $topic_id, $topic_id));
        $topic_state=$dataroot[0]['workcom_statut'];
        if ($topic_state<>"P")  DisplayTopic($workshop_id, $topic_id, $debut);
        else {
            $integrity=CheckComIntegrity($title, $body);
            if($integrity  == 1)
            {
                $post_id=AddPersistentPost($title, $body, $topic_id, $workshop_id);
                
                $result_nb_com=$GLOBALS['sql_object'] -> DBSelect(SQL_getWorkcom_detList($topic_id));
                $bdd_nb_com=$result_nb_com[0]['nb_rep'];
                
                $debut = ((int) (($bdd_nb_com-1) / SELECT_LIMIT)) * SELECT_LIMIT;
                
                notifyUsersMsg(array('action' => 'post_alert','user' => $_SESSION['userlogin'] ,'owner' => $_SESSION['userlogin'], 'topic_subject' => $title, 'topic_body' => $body, 'tid' => $topic_id, 'parentid' => $workshop_id, 'id' => $post_id, 'debut' => $debut));
                $_SESSION['message'] = '<p class="confirmed">'._t('workshop','confirm_add_com').'</p>'.PHP_EOL;
                
                $link = array('rub'=> $GLOBALS['links'][U_L]['topic']['linkvalue'],'id'=>$topic_id,'parentid'=> $workshop_id, 'name' => $dataroot[0]['workcom_subject'], 'debut' => $debut, '#' => 'msg-'.$post_id, 'amp_no_conversion' =>1);
                //         echo _debug(http_build_query ($link));
                //         echo '<p class="confirmed">'.http_build_query ($link).'</p>'.PHP_EOL;
                header('Location: '.safe_redirect(HrefMaker($link)));
                
            }
            else
            {
                echo "<p class=\"error\">".$integrity."</p>";
                echo GetFormAddPost($workshop_id, $topic_id, $body, $title);
            }
        }
    }
    
}

/**
 * UpdatePost
 * Mise à jour d'un message
 * @param $workshop_id
 * @param $topic_id
 * @param $debut
 * @param $new_body
 * @param $new_title
 * @param $post_id
 * @param $confirm_update
 * @return void
 */
if(!function_exists('UpdatePost')) {
    
    function UpdatePost($workshop_id, $topic_id, $debut, $new_body, $new_title, $post_id, $confirm_update)
    {
        $data=$GLOBALS['sql_object'] -> DBSelect(SQL_getOnetopicWorkcom($workshop_id, $post_id, "root"));
        $old_title=formatText($data[0]['workcom_subject'], '2FIELD');
        $old_body=formatText($data[0]['workcom_body'], '2FIELD');
        $topic_state=$data[0]['workcom_statut'];
        
        if ($topic_state<>"P")  DisplayTopic($workshop_id, $topic_id, $debut);
        else {
            //display old value for this post in form
            if(!$confirm_update)  echo GetFormModPost($workshop_id, $topic_id, $post_id, $old_body, $old_title);
            else
            {
                //test new value for this post in form
                $integrity=CheckComIntegrity($new_title, $new_body);
                if($integrity  == 1)
                {
                    $r=ModPersistentPost($new_title, $new_body, $post_id, $workshop_id, $topic_id);
                    echo '<p class="confirmed">'.$r.'</p>'.PHP_EOL;
                    //scroll jusque $post_id
                    echo DisplayTopic($workshop_id, $topic_id, $debut);
                }
                else
                {
                    echo "<p class=\"error\">".$integrity."</p>";
                    echo GetFormModPost($workshop_id, $topic_id, $post_id, $old_body, $old_title);
                }
            }
        }
    }
    
}


/**
 * GetFormAddTopic()
 * formulaire d'ajout d'un Topic
 * @param $workshop_id
 * @param $subject_body
 * @param $subject_title
 * @return
 **/
if(!function_exists('GetFormAddTopic')) {
    
    function GetFormAddTopic($workshop_id, $body='', $title='') {
        
        IncludeLightRte(array('id'=> 'post-body'));
        
        $form='<h3>'._t('workshop','add_com').'</h3>'.PHP_EOL;
        $form.='<form action="'. CURRENT_APP_URL .'index.php" method="post">'.PHP_EOL;
        $form.='<div id="reponse">'.PHP_EOL;
        $form.='<label for="post-title" class="labelised">'.mb_ucfirst(_t('workshop','com_subject')).' : </label>'.PHP_EOL;
        $form.='<input type="text" maxlength="100" size="40" name="post-title" id="post-title" value="'.$title.'" class="shorttextfield" required /><br />'.PHP_EOL;
        $form.='<label for="post-body" class="labelised">'.mb_ucfirst(_t('workshop','com_body')).' : </label>'.PHP_EOL;
        $form.='<textarea id="post-body" name="post-body" rows="10" cols="50" class="textfield" required>'.$body.'</textarea><br />'.PHP_EOL;
        $form.='<input type="hidden" value="'.$GLOBALS['links'][U_L]['topic-add']['linkvalue'].'" name="rub" id="rub" />'.PHP_EOL;
        $form.='<input type="hidden" value="'.$workshop_id.'" name="id" id="id" />'.PHP_EOL;
        $form.='<input type="hidden" value="true" name="confirm" id="confirm" />'.PHP_EOL;
        
        if(ALERT_NEWTOPIC== 2) $form .='<p class="info" style="margin-bottom:3em">'._t('workshop','notify_topic').'</p>'.PHP_EOL;
        
        $form.='<input type="submit" value="'._t('btn','valid').'" name="valider" id="valider" class="submitbut" />'.PHP_EOL;
        $form.='</div>'.PHP_EOL;
        $form.='</form>'.PHP_EOL;
        return $form;
    }
    
}

/**
 * GetFormModPost()
 * formulaire de modification d'un Post
 * @param $workshop_id
 * @param $topic_id
 * @param integer $post_id
 * @param $subject_body
 * @param $subject_title
 * @return
 **/
if(!function_exists('GetFormModPost')) {
    
    function GetFormModPost($workshop_id, $topic_id, $post_id, $body, $title) {
        
        IncludeLightRte(array('id'=> 'post-body'));
        
        $form='<h3>'._t('workshop','mod_com_mes').'</h3>'.PHP_EOL;
        $form.='<form action="'. CURRENT_APP_URL .'index.php" method="post">'.PHP_EOL;
        $form.='<div id="reponse">'.PHP_EOL;
        $form.='<label for="post-title" class="labelised">'.mb_ucfirst(_t('workshop','com_subject')).' : </label>'.PHP_EOL;
        $form.='<input type="text" maxlength="50"  name="post-title" id="post-title" value="'.$title.'" class="textfield" required /><br />'.PHP_EOL;
        $form.='<label for="post-body" class="labelised">'.mb_ucfirst(_t('workshop','com_body')).' : </label>'.PHP_EOL;
        $form.='<textarea id="post-body" name="post-body" rows="10" cols="50" class="textfield" required>'.$body.'</textarea>'.PHP_EOL;
        $form.='<input type="hidden" value="'.$GLOBALS['links'][U_L]['post-update']['linkvalue'].'" name="rub" id="rub" />'.PHP_EOL;
        $form.='<input type="hidden" value="'.$workshop_id.'" name="parentid" id="parentid" />'.PHP_EOL;
        $form.='<input type="hidden" value="'.$post_id.'" name="id" id="id" />'.PHP_EOL;
        $form.='<input type="hidden" value="true" name="confirm" id="confirm" />'.PHP_EOL;
        $form.='<input type="hidden" value="'.$topic_id.'" name="parentparentid" id="parentparentid" />'.PHP_EOL;
        $form.='<input type="submit" value="'._t('btn','valid').'" name="valider" id="valider" class="submitbut" />'.PHP_EOL;
        $form.='</div>'.PHP_EOL;
        $form.='</form>'.PHP_EOL;
        return $form;
    }
    
}
/**
 * GetFormAddPost()
 * formulaire d'ajout d'un Post
 * @param $workshop_id
 * @param $topic_id
 * @param $body
 * @param $title
 * @return
 **/
if(!function_exists('GetFormAddPost')) {
    
    function GetFormAddPost($workshop_id, $topic_id, $body='', $title=''){
        
        IncludeLightRte(array('id'=> 'post-body'));
        $form='<div class="no-print">';
        $form.='<h3>'._t('workshop','add_com_mes').'</h3>'.PHP_EOL;
        $form.='<form action="'. CURRENT_APP_URL .'index.php" method="post">'.PHP_EOL;
        $form.='<div id="reponse">'.PHP_EOL;
        $form.='<label for="post-title" class="labelised">'.mb_ucfirst(_t('workshop','com_subject')).' : </label>'.PHP_EOL;
        $form.='<input type="text" maxlength="100" size="40"  name="post-title" id="post-title" value="'.$title.'"  class="shorttextfield" required /><br />'.PHP_EOL;
        $form.='<label for="post-body" class="labelised">'.mb_ucfirst(_t('workshop','com_body')).' : </label>'.PHP_EOL;
        $form.='<textarea id="post-body" name="post-body" rows="10" cols="50" class="textfield" required>'.$body.'</textarea><br />'.PHP_EOL;
        $form.='<input type="hidden" value="'.$GLOBALS['links'][U_L]['post-add']['linkvalue'].'" name="rub" id="rub" />'.PHP_EOL;
        $form.='<input type="hidden" value="'.$topic_id.'" name="id" id="id" />'.PHP_EOL;
        $form.='<input type="hidden" value="'.$workshop_id.'" name="parentid" id="parentid" />'.PHP_EOL;
        
        if(ALERT_NEWPOST == 2) $form .='<p class="info" style="margin-bottom:3em">'._t('workshop','notify_post').'</p>'.PHP_EOL;
        
        $form.='<input type="submit" value="'._t('btn','valid').'" name="valider" id="valider" class="submitbut" />'.PHP_EOL;
        
        $form.='</div>'.PHP_EOL;
        $form.='</form>'.PHP_EOL;
        $form.='</div>';
        return $form;
    }
    
}

/**
 * CheckComIntegrity()
 * Vérification de l'intégrité des données
 * @param $title
 * @param $body
 * @param $workshop_com_object
 * @return
 **/
if(!function_exists('CheckComIntegrity')) {
    
    function CheckComIntegrity($title, $body){
        $integrity=1;
        if (strlen($title) < 3) $integrity=_t('workshop','com_no_subject');
        if (strlen($body) < 10) $integrity=_t('workshop','com_no_body');
        if(is_string($integrity)) return $integrity;
        else return 1;
    }
    
}

/**
 * AddPersistentPost()
 * Ajout dans la base d'un nouveau Post
 * @param $title
 * @param $body
 * @param $topic_id
 * @param $workshop_id
 * @return
 **/
if(!function_exists('AddPersistentPost')) {
    
    function AddPersistentPost($title, $body, $topic_id, $workshop_id){
        
        $r = $GLOBALS['sql_object'] -> DBSelect( SQL_getoneCompleteWorkshop($workshop_id));
        $workshop_status = $r[0]['workshop_statut'];
        if($workshop_status != 'P') ReloadIndex('public');
        
        if(isset($_SESSION['authenticated'])) {
            $user_id=base64_decode($_SESSION['userid']);
            
            include_once('../class/class.workshop_com.php');
            $workshop_com_object = new workshop_com;
            
            $result=CheckComIntegrity($title, $body);
            if ($result==1) {
                $table[0] = $title;
                $table[1] = $body;
                $table[2] = $topic_id;
                $table[3] = $user_id;
                $table[4] = $workshop_id;
                
                $result=$workshop_com_object->AddCom($table , $GLOBALS['sql_object']);
                return $result;
            }
            else return $result;
        } else return "<p class=\"error\">"._t('divers','errorauth')."</p>";
    }
    
}

/**
 * ModPersistentPost()
 * Modification dans la base d'un Post
 * @param $title
 * @param $body
 * @param $mes_id
 * @param $workshop_id
 * @param $topic_id
 * @return
 **/
if(!function_exists('ModPersistentPost')) {
    
    function ModPersistentPost($title, $body, $mes_id, $workshop_id, $topic_id){
        
        $r = $GLOBALS['sql_object'] -> DBSelect( SQL_getoneCompleteWorkshop($workshop_id));
        $workshop_status = $r[0]['workshop_statut'];
        if($workshop_status != 'P') ReloadIndex('public');
        
        if(isset($_SESSION['authenticated'])) {
            $user_id=base64_decode($_SESSION['userid']);
            if($GLOBALS['l21auth']->isWorkgroupUser($workshop_id, $GLOBALS['sql_object'])) {
                $hasRights = true;
            } else {
                $hasRights = false;
            }
            include_once('../class/class.workshop_com.php');
            $workshop_com_object = new workshop_com;
            
            $result=CheckComIntegrity($title, $body);
            if ($result==1) {
                $table[0] = $title;
                $table[1] = $body;
                $result=$workshop_com_object->ModifyComUser($mes_id, $table , $user_id, $GLOBALS['sql_object'], $hasRights);
                
                if (!is_string($result)) return _t('workshop','confirm_mod_com');
                else return $result;
            }
            else return $result;
        } else return _t('divers','errorauth');
    }
    
}
?>