<?php
/*** COPYRIGHT NOTICE *********************************************************
 *
******************************************************************************
*** WARNING *** T H I S    F I L E    I S    N O T    O P E N    S O U R C E *
******************************************************************************
*
* Copyright 2017 ProjeQtOr - Pascal BERNARD - support@projeqtor.org
*
* This file is an add-on to ProjeQtOr, packaged as a plug-in module.
* It is NOT distributed under an open source license.
* It is distributed in a proprietary mode, only to the customer who bought
* corresponding licence.
* The company ProjeQtOr remains owner of all add-ons it delivers.
* Any change to an add-ons without the explicit agreement of the company
* ProjeQtOr is prohibited.
* The diffusion (or any kind if distribution) of an add-on is prohibited.
* Violators will be prosecuted.
*
*** DO NOT REMOVE THIS NOTICE ************************************************/

require_once "../tool/kanbanConstructPrinc.php";
function kanbanDisplayTicket($id, $type, $idKanban, $from, $line, $add, $mode) {
	global $typeKanbanC, $arrayProject;
	$kanB = new Kanban ( $idKanban, true );
	$json = $kanB->param;
	$jsonDecode = json_decode ( $json, true );
	$idType = $from;
	if ($type=='Status' and isset($line['idstatus'])) {
		$idType=$line['idstatus'];
	}
	if (! $typeKanbanC) {
		$typeKanbanC = $jsonDecode ['typeData'];
	}
	$handle = 'dojoDndHandle';
	if (securityGetAccessRightYesNo ( "menu" . $typeKanbanC, "update", new $typeKanbanC ( $line ['id'], true ) ) != "YES")
		$handle = "";
	
	$proJ = new Project ( $line ['idproject'], true );
	$arrayProject [$line ['idproject']] = $proJ->getColor ();
	$color = $arrayProject [$line ['idproject']];
	$kanbanFullWidthElement = Parameter::getUserParameter ( "kanbanFullWidthElement" );
	$destWidth=RequestHandler::getValue('destinationWidth');
	if (!$destWidth) $destWidth=1920;
	$nbCol=(isset($jsonDecode['column']) and is_array($jsonDecode['column']))?count($jsonDecode['column']):1;
	$spaces=10*($nbCol+1);
	$ticketWidth=(($destWidth-$spaces)/$nbCol)-40;
	if ($ticketWidth<305) $ticketWidth=305;
	$nbTktPerCol=intval($ticketWidth/150);
	$hidePlannedDate = Parameter::getUserParameter("kanbanHidePlannedDate");
	$hidePlannedDate = ($hidePlannedDate!='off')?true:false;
	$ticketWidthSmall=(round($ticketWidth/$nbTktPerCol,1)-(2*$nbTktPerCol)).'px';
	$ticketRelativeWidth=($kanbanFullWidthElement == "on")?$ticketWidth:(round($ticketWidth/$nbTktPerCol,1)-(2*$nbTktPerCol));
	$hideStatus = Parameter::getUserParameter("kanbanHideStatus");
	$hideStatus = ($hideStatus!='off')?true:false;
	$hideType = Parameter::getUserParameter("kanbanHideType");
	$hideType = ($hideType!='off')?true:false;
	$hideProjectName = Parameter::getUserParameter("kanbanHideProjectName");
	$hideProjectName = ($hideProjectName!='off')?true:false;
	$modeColorTitle = Parameter::getUserParameter( "kanbanModeColorTitle" . Parameter::getUserParameter( "kanbanIdKanban" ) );
	$hideColorTitle = Parameter::getUserParameter("kanbanHideColorTitle");
	$hideColorTitle = ($hideColorTitle=='on')?true:false;
	$hideProduct = Parameter::getUserParameter("kanbanHideProduct");
	$hideProduct = ($hideProduct!='off')?true:false;
	$hideActivityPlanning = Parameter::getUserParameter("kanbanHideActivityPlanning");
	$hideActivityPlanning = ($hideActivityPlanning!='off')?true:false;
	$seeWork = Parameter::getUserParameter ( "kanbanSeeWork" . Parameter::getUserParameter ( "kanbanIdKanban" ) );
	$seeWork=($seeWork=='on' or $seeWork=='1')?true:false;
	$hideResponsible = Parameter::getUserParameter("kanbanHideResponsible");
	$hideResponsible = ($hideResponsible!='off')?true:false;
	$hidePriority = Parameter::getUserParameter("kanbanHidePriority");
	$hidePriority = ($hidePriority!='off')?true:false;
	$hideCriticality = Parameter::getUserParameter("kanbanHideCriticality");
	$hideCriticality = ($hideCriticality!='off')?true:false;
	if (isset ( $line ['description'] )) {
	  $description=$line ['description'];
	  $minChar = 200;
	  if(pq_strpos($description, '<img ') != ''){
	    $minChar = 400;
	    $description=pq_str_replace('<img ','<img style="max-width:'.($ticketRelativeWidth-10).'px;" onClick="showImage(\'Note\',this.src,\' \');"',$description);
	    $img = pq_substr($description, pq_strpos($description, '<img '), (pq_strpos($description, '/>')-pq_strpos($description, '<img '))+2);
	    $description = pq_substr($description, 0, pq_strpos($description, '<img ')).'<div>#IMGREPLACED#</div>'.pq_substr($description, pq_strpos($description, '<img '));
	    $text = new Html2Text ($description);
	    $descr = $text->getText ();
	    $descr=pq_htmlspecialchars($descr);
	    $descr=pq_str_replace('#IMGREPLACED#',$img,$descr);
	  }else{
	    $text = new Html2Text ($description);
	    $descr = $text->getText ();
	    $descr=pq_htmlspecialchars($descr);
	  }
	  if (pq_strlen ($description) > 4000) {
	        $descr1 = pq_substr ( $descr, 0, 4000);
			$ticketDescr = nl2brForPlainText ( $descr1 );
			$descr2 = pq_substr ( $descr, 0, $minChar );
			$ticketDescr2 = nl2brForPlainText ( $descr2 );
	  } else {
	    $ticketDescr=$description;
	    $descr2 = pq_substr ( $descr, 0, $minChar);
	    $ticketDescr2 = nl2brForPlainText ( $descr2 );
	  }
	} else {
		$ticketDescr = '<div style="font-style:italic; color:#CDCADB; ">' . i18n ( "kanbanNoDescription" ) . '</div>';
		$ticketDescr2 = '<div style="font-style:italic; color:#CDCADB; ">' . i18n ( "kanbanNoDescription" ) . '</div>';
	}

	$titleObject=$typeKanbanC . ' #' . $line ['id'] 
	  ." (".SqlList::getNameFromId('Type', $line['idtickettype']).')'
	  ."\n".i18n('Project').' #'.$line['idproject'].' - '.$proJ->name;
	if ($kanbanFullWidthElement == "on") {
	$numCol = count ( $jsonDecode ['column'] );
	
	echo ' <script type="dojo/connect">
      //divWidthKanban(' . $id . ',\'' . $type . '\',' . $numCol . ');
     </script>';
	if ($mode != "refresh") {
	  echo '
      <div class="dojoDndItem ' . $handle . ' ticketKanBanStyleFull ticketKanBanColor " style="'.((isNewGui())?'border-radius:10px;':'').'" fromC="' . $from . '" id="itemRow' . $line ['id'] . '-' . $type . '"
      dndType="' . ($type == 'Status' ? 'typeRow' . $idType . $add : ($type == 'TargetProductVersion' ? $from : SqlList::getFieldFromId ( $typeKanbanC, $line ['id'], "idProject" ))) . '" 
          oncontextmenu="openKanbanContextMenu(' . $line['id'] . ', \''.$typeKanbanC.'\', \''.$line ['idproject'].'\', \''.$type.'\')">';
	}
	echo '<div style="position: relative;background: #FFFFFF;border-radius: 10px;">';
	echo '<div id="topTicket' . $line['id'] . '" style="position: relative;background-color:#FFFFFF;padding:3px;min-height:20px;max-height:20px;border-radius: 10px;cursor:move;">
      		<table style="width:100%">
      		  <tr title="'.$titleObject.'">
          		<td style="font-size:10px;font-family:arial;width:50%">';
                  echo '<div style="float:left;margin: 2px 5px 0px 2px;">'.formatColorRounded ($color, 12, 3, 'left', $titleObject).'</div>';
                  echo '<div style="float:left;margin-top: 3px;" title="'.$titleObject.'">#' . $line ['id'] . '</div>';
                  if($hideType){
                    $libType=SqlList::getNameFromId('Type', $line['idtickettype']);
            		  if ($libType){
            		    echo '<div style="float:left;margin: 3px 0px 0px 5px;">' . $libType . '</div>';
            		  }
                  }
          		echo '</td><td style="width:50%">';
          		if($hidePlannedDate){
          		  if(isset($line['plannedcolor']) and isset($line['plannedenddate'])){
          		    $noDynamicFontColor = ($typeKanbanC != 'Activity')?false:true;
          		    echo '<div style="float:right;padding:2px;opacity:0.9;">'.formatColorRounded ($line['plannedcolor'], 15  , 8, 'left', i18n('colPlannedEndDate'), htmlFormatDate($line['plannedenddate']), 6, $noDynamicFontColor).'</div>';
          		  }
          		}else{
          		  echo '&nbsp';
          		}
          		echo '</td>
              </tr>
            </table>
	  </div>';
    $backgroundColor = '#FFFFFF';
	if ($hideColorTitle){
      if($modeColorTitle=='colorProject'){
        $itemForColor = new Project($line['idproject']);
      }else if ($modeColorTitle=='colorItem'){
        $itemForColor = new Activity($line['id']);
      }else if($modeColorTitle=='colorType' and $line['idtickettype']){
        $itemForColor = new Type($line['idtickettype']);
      }else if($modeColorTitle=='colorPriority'){
        $itemForColor = new Priority($line['idpriority']);
      }else if($modeColorTitle=='colorUrgency'){
        $itemForColor = new Urgency($line['idurgency']);
      }
      if (!empty($itemForColor)) $backgroundColor = $itemForColor->getColor();
      $colorFont = getForeColor($backgroundColor);
    }     
	echo ' 
      <div id="titleTicket' . $line['id'] . '" style="position:relative;width:100%;background-color:#FFFFFF;z-index:99;min-height:25px;max-height:25px;cursor:move;">
        <div class="kanbanTitleTicket" id="name' . $line['id'] . '" style="min-height: 26px;' . (($hideColorTitle && $backgroundColor != '#FFFFFF') ? 'color:'.$colorFont.';background-color:'.$backgroundColor.';' : '') . '">' . htmlEncode($line['name']) . '</div>
      </div>';
	
     if($hideStatus or $hideProjectName){
       echo '<div style="display:flex;gap:5px;">';
       if ($hideStatus){
         echo '
          <div id="divPrincItem' . $line ['id'] . '" style="position: relative;cursor:move;">
            ' . kanbanAddPrinc ( $line ) . '
          </div>';
       }
       if ($hideProjectName){
         echo '
          <div id="divProjectNameItem' . $line ['id'] . '" style="position: relative;cursor:move;display:flex; align-items: center;padding-left: 5px;">
            ' . kanbanAddProjectName( $line ) . '
          </div>';
       }
       echo '</div>';
     }
     echo '
      <div id="objectDescr' . $line ['id'] . '" dojoType="dijit.layout.ContentPane" region="center" class=""
      style="width:95%;max-width:'.$ticketWidth.'px;padding:5px 5px 0px 5px;margin-bottom:5px;font-size:12px;font-family:arial;word-wrap:break-word;max-height:300px;overflow-x:hidden;overflow-y:auto;cursor:move;"
      onScroll="kanbanShowDescr(\'description\',\'' . $typeKanbanC . '\', ' . $ticketWidth . ', ' . $line ['id'] . ');">
      ' . $ticketDescr . '</div>';
     echo '<input dojoType="dijit.form.TextBox" id="descr_' . $line ['id'] . '" type="hidden" value="truncated" />';
     if($hideProduct ){
      echo '
      <div id="divProductItem' . $line ['id'] . '" style="position: relative;cursor:move;font-size:8pt;">
        ' . kanbanAddProduct ( $line ) . '        
      </div>';
     }
     if($hideActivityPlanning){
       echo '
      <div id="divActivityPlanningItem' . $line ['id'] . '" style="position: relative;cursor:move;font-size:8pt;">
        ' . kanbanAddActivityPlanning ( $line ) . '
      </div>';
     }
     if($seeWork){
       echo '<div id="divWorkItem'.$line ['id'].'" style="position: relative;">'. displayAllWork ( $line, 1, 4 ) . '</div>';
     }
	 echo '<div id="bottomTicket'.$line ['id'].'" style="position: relative;cursor:move;width:100%;height:26px;bottom:0;padding-top: 5px;">';
     if($hideResponsible){
       echo '<div class="" style="float:left;margin: 3px 4px 3px 4px;" id="userThumbTicket' . $line ['id'] . '">';
       if(isset ( $line ['iduser']) and $line ['iduser']){
  	        echo '<div style="position:relative;float:left;padding: 0px 5px 3px 0px;" >';
  	        $file=Affectable::getThumbUrl('Affectable', $line ['iduser'], 32);
  	        $title = SqlList::getNameFromId ( "Affectable", $line ['iduser'] ).'<br/><span style="font-size:80%"><i>('.i18n('colResponsible').')</i></span>';
  	        if (pq_substr($file,0,6)=='letter') {
  	          $title=htmlEncode($title,'quotes');
  	          echo '<div '.(($line ['id']>0) ? 'id="responsible'.$line ['id'].'"' : '') .' valueuser="'.$title.'">'.formatIconNewGui('Resource', 20, null, false).'</div>';
  	        } else {
              echo formatUserThumb ( $line ['iduser'], $title, "", 20, 'left', false, $line ['id'], true );
  	        }
  	        echo '</div>';
            echo '<div style="float:left;padding-top: 2px;" >'.formatUserThumbRounded ($line ['iduser'], SqlList::getNameFromId ( "Affectable", $line ['iduser'] ), i18n('colResponsible'),'15', '5', 'left','7.5',null,$line ['id']).'</div>';
       }
       echo '</div>';
     }
     if($hidePriority){
       if(isset ( $line ['idpriority']) and $line ['idpriority']){
         echo '<div style="float:left;margin: 3px 4px 3px 4px;" id="priotityThumbTicket' . $line ['id'] . '">
    	        <div style="float:left;padding: 2px 0px 0px 0px;" >'.formatColorThumb ( "idPriority", $line ['idpriority'], 20, 'left', 'kanbanLargeTiles', $line ['id'], true) .'</div>
    	        <div style="float:left;padding-top: 2px;" >'.formatColorThumbRounded ( "idPriority", $line ['idpriority'], 'left', SqlList::getNameFromId ( "Priority", $line ['idpriority'] ), '0px 5px 5px 0', '7.5',$line ['id']).'</div>
              </div>';
       }
     }
     if($hideCriticality){
       if(isset ( $line ['idurgency'] ) and $line ['idurgency']){
         echo '<div style="float:left;margin: 3px 4px 3px 4px;" id="urgencyThumbTicket' . $line ['id'] . '">
        	     <div style="float:left;padding: 2px 0px 0px 0px;" >'.formatColorThumb ("idUrgency", $line ['idurgency'], 20, 'left', 'kanbanLargeTiles', $line ['id'], true) .'</div>
                 <div style="float:left;padding-top: 2px;" >'.formatColorThumbRounded ("idUrgency", $line ['idurgency'], 'left', SqlList::getNameFromId ( "Urgency", $line ['idurgency'] ), '0px 5px 5px 0', '7.5',$line ['id']).'</div>
              </div>';
       }
     }
     $object= new $typeKanbanC ($line['id']);
	 $nbBadge=((isset($object->_Note))?count ($object->_Note):'');
	 $margin=($nbBadge>9)?'-10':'-7';
	 $badge= '<div id="kanbanBadge_'.$line['id'].'" class="kanbanBadge" style="">'.$nbBadge.'</div>';
	 $placeholder = i18n('textareaEnterText');
      echo '<table style="margin: 5px -4px 5px -2px;float:right;">
        <tr>';
      echo '<td>
        <div class="roundedButtonSmall"
            style="width:16px;height:16px;cursor:pointer;vertical-align:text-bottom;margin-right:6px;float:left;padding-top: 2px;"
            onclick="showDetail(\'refreshActionAdd' . $typeKanbanC . '\',1,\'' . $typeKanbanC . '\',false,' . $line['id'] . ');"
            title="' . i18n('kanbanEditItem', array($line['id'])) . '">
            ' . formatSmallButton('Edit', false) . '
        </div>
      </td>';
      echo'  <td>
              <div id="badges" style="position:relative">
              <div id="addComent" onclick="activityStreamKanban(' . $line ['id'] . ', \'' . $typeKanbanC . '\', \''.$type.'\',\'' .$placeholder. '\');" style="margin-right:5px;margin-top: 3px;" title=" ' . i18n ( 'commentImputationAdd' ) . ' ">
                ' . formatSmallButton ( 'AddComment' ) . '
                    <div  style="pointer-events: none;position:absolute;bottom:'.((isNewGui())?'-3px':'-1px').';margin-left:'.$margin.'px;width:5px;">
                    '.((count($object->_Note)!=0)?$badge:'').'
                    </div>
              </div>
            </div>
            </td>';
      if (Module::isModuleActive('moduleVoting')) {
        if(isset($object->VotingItem) and $object->VotingItem and !$object->VotingItem->locked){
          $voteAttr = new VotingAttribution();
          $typeName=SqlElement::getTypeName($object->VotingItem->refType);
          $idType = $object->$typeName;
          $canVote = $voteAttr->canVote($object->VotingItem->refType, $object->VotingItem->refId, $idType);
          $voteExist = false;
          $vote = SqlElement::getSingleSqlElementFromCriteria('Voting', array('refType'=>$object->VotingItem->refType,'refId'=>$object->VotingItem->refId,'idUser'=>getCurrentUserId()));
          if($vote->id)$voteExist=true;
          if(!$voteExist){
  //           $idUser = getCurrentUserId();
  //           $affectable = new Affectable($idUser);
  //           if($affectable->isContact){
  //             $contact = new Contact($idUser);
  //             if($contact->idClient){
  //               $vote = SqlElement::getSingleSqlElementFromCriteria('Voting', array('refType'=>$this->refType,'refId'=>$this->refId,'idClient'=>$contact->idClient));
  //               if($vote->id)$voteExist=true;
  //             }
  //           }
            $cpt=$vote->countSqlElementsFromCriteria(array('refType'=>$object->VotingItem->refType,'refId'=>$object->VotingItem->refId));
            if ($cpt>0) $voteExist=true;
          }
          $idRule=VotingItem::getIdUseRule($object->VotingItem->refType, $object->VotingItem->refId);
          $iconLogoVote = 'AddVote';
          if($object->VotingItem->pctRate > 0){
            $iconLogoVote = 'AddVote25';
          }
          if($object->VotingItem->pctRate > 24){
            $iconLogoVote = 'AddVote25';
          }
          if($object->VotingItem->pctRate > 49){
            $iconLogoVote = 'AddVote50';
          }
          if($object->VotingItem->pctRate > 74){
            $iconLogoVote = 'AddVote75';
          }
          if($object->VotingItem->pctRate >=  100){
            $iconLogoVote = 'AddVote100';
          }
          $voteButtonTitle=i18n('colPctRate').' : '.$object->VotingItem->pctRate.' %';
          if ($canVote) $voteButtonTitle.="\n". i18n ('addVoteKanban');
          $onClick="";
          if ($canVote and $idRule) $onClick="addVote('".$object->VotingItem->refType."','".$object->VotingItem->refId."','".getEditorType()."','add',".$idRule.",true);";
          if($canVote and !$voteExist and $idRule){
            echo'
             <td>
                <div id="badges2" style="position:relative">
                <div id="addComent" onclick="'.$onClick.'" style="margin-right:5px;margin-top: 3px;" title="'.$voteButtonTitle.'">
                  ' . formatSmallButton ( $iconLogoVote,false,($onClick=="")?false:true ) . '
                </div>
              </div>
              </td>';
          }
          if($voteExist and $idRule){
            echo'
             <td>
                <div id="badges2" style="position:relative">
                <div id="addComent" onclick="'.$onClick.'" style="margin-right:5px;margin-top: 3px;" title="'.$voteButtonTitle.'">
                  ' . formatSmallButton ( $iconLogoVote,false,($onClick=="")?false:true ) . '
                </div>
              </div>
              </td>';
          }
        }
      }
      echo'
            <td>
              <div class="roundedButtonSmall"
                style="width:20px;height:16px;cursor:pointer;float:right;vertical-align:text-bottom; padding-top: 3px;"
         		    onclick="gotoElement(\'' . $typeKanbanC . '\',' . htmlEncode ( $line ['id'] ) . ', true);"	title="' .i18n('kanbanGotoItem',array($line ['id'])) . '" style="width:18px;" >
         		   ' . formatSmallButton ( 'Goto',true ) . '
              </div>
           </td>';
          echo'
        </tr>
      </table>
     </div>';
echo '</div>';
		if ($mode != "refresh") {
			echo '</div>';
		}
	} else {
		// if button is unchecked elements are in normal mode
		if ($mode != "refresh") {
			echo '
    <div class="dojoDndItem ' . $handle . ' ticketKanBanStyle ticketKanBanColor " style="width:'.$ticketWidthSmall.';min-width: 160px;" fromC="' . $from . '" id="itemRow' . $line ['id'] . '-' . $type . '"
    dndType="' . ($type == 'Status' ? 'typeRow' . $idType . $add : ($type == 'TargetProductVersion' ? $from : SqlList::getFieldFromId ( $typeKanbanC, $line ['id'], "idProject" ))) . '"
         oncontextmenu="openKanbanContextMenu(' . $line['id'] . ', \''.$typeKanbanC.'\', \''.$line ['idproject'].'\', \''.$type.'\')">';
		}
		echo '<div style="position: relative;background: #FFFFFF;border-radius: 8px;cursor:move;">';
		echo '<div id="topTicket' . $line['id'] . '" style="position: relative;background-color:#FFFFFF;padding:3px;min-height:20px;max-height:20px;border-radius: 5px;cursor:move;">
        		<table style="width:100%">
        		  <tr title="'.$titleObject.'">
            		<td style="font-size:10px;font-family:arial;width:75%">';
                    echo '<div style="float:left;margin: 2px 5px 0px 2px;">'.formatColorRounded ($color, 12, 3, 'left', $titleObject).'</div>';
                    echo '<div style="float:left;margin: 3px 4px 0px 0px;">#' . $line ['id'] . '</div>';
	                $hideType = Parameter::getUserParameter("kanbanHideType");
                    $hideType = ($hideType!='off')?true:false;
                    if($hideType){
                      $libType=SqlList::getFieldFromId('Type', $line['idtickettype'],'code');
            		  if (!$libType) $libType=pq_substr(SqlList::getNameFromId('Type', $line['idtickettype']),0,3);
              		  if ($libType){
              		    echo '<div style="margin: 3px 0px 0px 5px;overflow: hidden;text-overflow: ellipsis;">' . $libType . '</div>';
              		  }
                    }
            		echo '</td>';
            		$hidePlannedDate = Parameter::getUserParameter("kanbanHidePlannedDate");
            		$hidePlannedDate = ($hidePlannedDate!='off')?true:false;
            		if($hidePlannedDate){
            		  if(isset($line['plannedcolor']) and isset($line['plannedenddate'])){
            		    $noDynamicFontColor = ($typeKanbanC != 'Activity')?false:true;
            		    echo '<td style="width:25%">';
            		    echo '<div style="float:right;padding:2px;opacity:0.9;">'.formatColorRounded ($line['plannedcolor'], 15  , 8, 'left', i18n('colPlannedEndDate'), htmlFormatDate($line['plannedenddate']), 6, $noDynamicFontColor).'</div>';
            		    echo '</td>';
            		  }
            		}
            		echo '</tr>
              </table>
		  </div>';
            		
        $backgroundColor = '#FFFFFF';
        if ($hideColorTitle){
          if($modeColorTitle=='colorProject'){
            $itemForColor = new Project($line['idproject']);
          }else if ($modeColorTitle=='colorItem'){
            $itemForColor = new Activity($line['id']);
          }else if($modeColorTitle=='colorType' and $line['idtickettype']){
            $itemForColor = new Type($line['idtickettype']);
          }else if($modeColorTitle=='colorPriority'){
            $itemForColor = new Priority($line['idpriority']);
          }else if($modeColorTitle=='colorUrgency'){
            $itemForColor = new Urgency($line['idurgency']);
          }
          if (!empty($itemForColor)) $backgroundColor = $itemForColor->getColor();
          $colorFont = getForeColor($backgroundColor);
        }
		echo ' 
        <div id="titleTicket' . $line['id'] . '" style="position:relative;width:100%;background-color:#FFFFFF;z-index:99;min-height:38px;max-height:38px;cursor:move;">
          <div class="kanbanTitleTicket kanbanTitleSmallTiles" id="name' . $line['id'] . '" style="font-size:13px;min-height:40px;' . ($hideColorTitle && $backgroundColor != '#FFFFFF' ? 'background-color:' . $backgroundColor . ';color:' . $colorFont . ';' : '') . '">' . htmlEncode($line['name']) . '</div>
        </div>';
       $hideStatus = Parameter::getUserParameter("kanbanHideStatus");
       $hideStatus = ($hideStatus!='off')?true:false;
       if($hideStatus){ //no large kanban = no Project Name
        echo '
        <div id="divPrincItem' . $line ['id'] . '" style="position: relative;cursor:move;">
          ' . kanbanAddPrinc ( $line ) . '        
        </div>';
       }
       $hideProduct = Parameter::getUserParameter("kanbanHideProduct");
       $hideProduct = ($hideProduct!='off')?true:false;
       $hideActivityPlanning = Parameter::getUserParameter("kanbanHideActivityPlanning");
       $hideActivityPlanning = ($hideActivityPlanning!='off')?true:false;
       $descMaxHeight = 50;
	   if($hideProduct and !isset($line['idtargetproductversion'])){
         $descMaxHeight += 20;
       }
       if($hideActivityPlanning and !isset($line['idactivity'])){
         $descMaxHeight += 20;
       }
       echo '
      <div id="objectDescr' . $line ['id'] . '" class=""
        style="position: relative;padding:5px 5px 0px 5px;margin-bottom:5px;font-size:12px;font-family:arial;max-width:'.$ticketWidthSmall.';max-height:'.$descMaxHeight.'px;'.((isNewGui())?'min-height:'.$descMaxHeight.'px;':'').'overflow-y:auto;overflow-x: hidden;"
        onScroll="kanbanShowDescr(\'description\',\'' . $typeKanbanC . '\', ' . $ticketRelativeWidth . ', ' . $line ['id'] . ');" >
          ' . $ticketDescr2 . '
      </div>';
       echo '<input dojoType="dijit.form.TextBox" id="descr_' . $line ['id'] . '" type="hidden" value="truncated" />';
       if($hideProduct){
        echo '
        <div id="divProductItem' . $line ['id'] . '" style="position: relative;cursor:move;font-size:8pt;">
          ' . kanbanAddProduct ( $line ) . '        
        </div>';
       }
       if($hideActivityPlanning){
         echo '
        <div id="divActivityPlanningItem' . $line ['id'] . '" style="position: relative;cursor:move;font-size:8pt;">
          ' . kanbanAddActivityPlanning ( $line ) . '
        </div>';
       }
       $seeWork = Parameter::getUserParameter ( "kanbanSeeWork" . Parameter::getUserParameter ( "kanbanIdKanban" ) );
       $seeWork=($seeWork=='on' or $seeWork=='1')?true:false;
       if($seeWork){
         echo '<div id="divWorkItem'.$line ['id'].'" style="position: relative;">'. displayAllWork ( $line, 1, 4 ) . '</div>';
       }
       echo '<div id="bottomTicket'.$line ['id'].'" style="position: relative;cursor:move;width:100%;height:26px;bottom:0;">';
       $hideResponsible = Parameter::getUserParameter("kanbanHideResponsible");
       $hideResponsible = ($hideResponsible!='off')?true:false;
       if($hideResponsible){
         echo '<div style="float:left;margin:5px 0px 5px 5px;position:relative" id="userThumbTicket' . $line ['id'] . '">';
         if(isset ( $line ['iduser'] ) and $line ['iduser']){
           echo formatUserThumb ( $line ['iduser'], SqlList::getNameFromId ( "Affectable", $line ['iduser'] ).'<br/><span style="font-size:80%"><i>('.i18n('colResponsible').')</i></span>', "", 20, 'left', false, $line ['id'], true );
         }
         echo '</div>';
       }
       $hidePriority = Parameter::getUserParameter("kanbanHidePriority");
       $hidePriority = ($hidePriority!='off')?true:false;
       if($hidePriority){
         if(isset ( $line ['idpriority'] ) and $line ['idpriority']){
          echo '<div style="float:left;margin:5px 0px 5px 5px;position:relative">
                ' . formatColorThumb ( "idPriority", $line ['idpriority'], 20, 'left', SqlList::getNameFromId ( "Priority", $line ['idpriority'] ), $line ['id'], true ) . '
                </div>';
         }
       }
       $hideCriticality = Parameter::getUserParameter("kanbanHideCriticality");
       $hideCriticality = ($hideCriticality!='off')?true:false;
       if($hideCriticality){
        if(isset ( $line ['idurgency'] ) and $line ['idurgency']){
          echo '<div style="float:left;margin:5px 0px 5px 5px;position:relative">
                ' . formatColorThumb ("idUrgency", $line ['idurgency'], 20, 'left', SqlList::getNameFromId ( "Urgency", $line ['idurgency'] ), $line ['id'], true ) . '
                </div>';
        }
       }
		$object= new $typeKanbanC ($line['id']);
		$nbBadge=((isset($object->_Note) )?count ($object->_Note):'');
		$margin=($nbBadge>9)?'-10':'-7';
		$badge= '<div id="'.$line['name'].'BadgeTab" class="kanbanBadge" style="">'.$nbBadge.'</div>';
		$placeholder = i18n('textareaEnterText');
		//gautier #voting
       echo  '<table style="float:right;margin:5px -4px 5px -2px;">
          <tr>';
       
       echo '<td>
        <div class="roundedButtonSmall"
            style="width:16px;height:16px;cursor:pointer;vertical-align:text-bottom;margin-right:6px;float:left;padding-top: 2px;"
            onclick="showDetail(\'refreshActionAdd' . $typeKanbanC . '\',1,\'' . $typeKanbanC . '\',false,' . $line['id'] . ');"
            title="' . i18n('kanbanEditItem', array($line['id'])) . '">
            ' . formatSmallButton('Edit', false) . '
        </div>
      </td>';
       
       echo'
            <td>
              <div id="badges" style="position:relative">
              <div id="addComent" onclick="activityStreamKanban(' . $line ['id'] . ', \'' . $typeKanbanC . '\', \''.$type.'\',\'' .$placeholder. '\');" style="margin-right:5px;margin-top: 3px;" title=" ' . i18n ( 'commentImputationAdd' ) . ' ">
                ' . formatSmallButton ( 'AddComment' ) . '
                    <div  style="pointer-events: none;position:absolute;bottom:'.((isNewGui())?'-3px':'-1px').';margin-left:'.$margin.'px;width:5px;">
                    '.((count($object->_Note)!=0)?$badge:'').'
                    </div>
              </div>
            </div>
            </td>';
      if (Module::isModuleActive('moduleVoting')) {
        if(isset($object->VotingItem) and $object->VotingItem and !$object->VotingItem->locked){
          $voteAttr = new VotingAttribution();
          $typeName=SqlElement::getTypeName($object->VotingItem->refType);
          $idType = $object->$typeName;
          $canVote = $voteAttr->canVote($object->VotingItem->refType, $object->VotingItem->refId, $idType);
          $voteExist = false;
          $vote = SqlElement::getSingleSqlElementFromCriteria('Voting', array('refType'=>$object->VotingItem->refType,'refId'=>$object->VotingItem->refId,'idUser'=>getCurrentUserId()));
          if($vote->id)$voteExist=true;
          if(!$voteExist){
  //           $idUser = getCurrentUserId();
  //           $affectable = new Affectable($idUser);
  //           if($affectable->isContact){
  //             $contact = new Contact($idUser);
  //             if($contact->idClient){
  //               $vote = SqlElement::getSingleSqlElementFromCriteria('Voting', array('refType'=>$this->refType,'refId'=>$this->refId,'idClient'=>$contact->idClient));
  //               if($vote->id)$voteExist=true;
  //             }
  //           }
            $cpt=$vote->countSqlElementsFromCriteria(array('refType'=>$object->VotingItem->refType,'refId'=>$object->VotingItem->refId));
            if ($cpt>0) $voteExist=true;
          }
          $idRule=VotingItem::getIdUseRule($object->VotingItem->refType, $object->VotingItem->refId);
          $iconLogoVote = 'AddVote';
          if($object->VotingItem->pctRate > 0){
            $iconLogoVote = 'AddVote25';
          }
          if($object->VotingItem->pctRate > 24){
            $iconLogoVote = 'AddVote25';
          }
          if($object->VotingItem->pctRate > 49){
            $iconLogoVote = 'AddVote50';
          }
          if($object->VotingItem->pctRate > 74){
            $iconLogoVote = 'AddVote75';
          }
          if($object->VotingItem->pctRate >=  100){
            $iconLogoVote = 'AddVote100';
          }
          $voteButtonTitle=i18n('colPctRate').' : '.$object->VotingItem->pctRate.' %';
          if ($canVote) $voteButtonTitle.="\n". i18n ('addVoteKanban');
          $onClick="";
          if ($canVote and $idRule) $onClick="addVote('".$object->VotingItem->refType."','".$object->VotingItem->refId."','".getEditorType()."','add',".$idRule.",true);";
          if($canVote and !$voteExist and $idRule){
            echo'
             <td>
                <div id="badges2" style="position:relative">
                <div id="addComent" onclick="'.$onClick.'" style="margin-right:5px;margin-top: 3px;" title="'.$voteButtonTitle.'">
                  ' . formatSmallButton ( $iconLogoVote,false,($onClick=="")?false:true) . '
                </div>
              </div>
              </td>';
          }
          if($voteExist){
            echo'
             <td>
                <div id="badges2" style="position:relative">
                <div id="addComent" onclick="'.$onClick.'" style="margin-right:5px;margin-top: 3px;" title="'.$voteButtonTitle.'">
                  ' . formatSmallButton ( $iconLogoVote,false,($onClick=="")?false:true) . '
                </div>
              </div>
              </td>';
          }
       }
     }
     echo'
            <td>
              <div class="roundedButtonSmall"
                style="width:20px;height:16px;cursor:pointer;float:right;vertical-align:text-bottom;padding-top: 3px;"
         		    onclick="gotoElement(\'' . $typeKanbanC . '\',' . htmlEncode ( $line ['id'] ) . ', true);"	title="' .i18n('kanbanGotoItem',array($line ['id'])) . '" style="width:18px;" >
         		   ' . formatSmallButton ( 'Goto',true ) . '
              </div>
           </td>';
      echo'
          </tr>
        </table>
      </div>
    </div>';
    echo '</div>';
		if ($mode != "refresh") {
			echo '</div>';
		}
	}
}

//function of kanbanView origine

function myKanban($idKanban){
  $kanban = new Kanban($idKanban,true);
  return $kanban->idUser==getSessionUser()->id;
}

function kanbanListSelect($user,$name,$type,$idKanban) {
  global $typeKanbanC;
  $kanban=new Kanban();
  $mineList=$kanban->getSqlElementsFromCriteria(null, false," idUser=$user->id ");
  $res= new Resource();
  $reTable= $res->getDatabaseTableName();
  $clauseWhere=" idUser in (Select id from $reTable where id!=$user->id and idle=0 ) AND isShared=1 ";
  $kanbanList=$kanban->getSqlElementsFromCriteria(null, false,$clauseWhere, "idUser ASC");
  $kanbanName = ($idKanban != -1)?SqlList::getNameFromId('Kanban', $idKanban, false):i18n("noKanbanSelected");
  // Display Result
  echo '<div style="float:left;">
            <div dojoType="dijit.form.DropDownButton"
              style="min-width:75px;height:24px;margin:0 auto;color:#000;float:left;margin-right:15px;'.(($idKanban == -1)?'font-style:italic;':'').'"
              id="kanbanListSelect" name="entity">
              <span>'.$kanbanName.'</span>
                <div data-dojo-type="dijit/TooltipDialog">';
  $iterateur=0;
  echo '<span class="kanbanTextTitle" style="float:left;height:15px;font-weight:bold;" disabled="disabled" value="-2" '
      . ' title="' . i18n("kanbanSelectKanban") . '" >'.i18n("kanbanMine").'</span><br/>';
  if(count($mineList)==0)echo '<span disabled="disabled" onclick="dijit.byId(\'kanbanListSelect\').closeDropDown();" style="float:left;height:15px;" '
      . ' >&nbsp;&nbsp;&nbsp;&nbsp;'.i18n('noDataFound').'</span><br/>';
  echo '<div style="position:absolute;top:20px;right:'. (empty($mineList) ? '10' : '70') .'px;"';
  echo 'onclick="loadDialog(\'dialogKanbanUpdate\', function(){kanbanFindTitle(\'addKanban\');}, true, \'&typeDynamic=addKanban\', true, false);" title="'.i18n('kanbanAdd').'">'.formatSmallButton('KanbanAdd',true).'</div>';
  foreach ($mineList as $line) {
    $jsonDecode=json_decode($line->param,true);
    if(!isset($jsonDecode['typeData'])){
      $jsonDecode['typeData']='Ticket';
      $line->param=json_encode($jsonDecode);
      $line->save();
    }
    $typeKanbanCTmp=$jsonDecode['typeData'];
    if (isNewGui()) echo '<div style="margin-top:5px">';
    echo '
    <div class="imageColorNewGuiNoSelection icon'.$typeKanbanCTmp.'16 icon'.$typeKanbanCTmp.' iconSize16" style="width:16px;height:16px;float:left"></div>
    <span onclick="kanbanGoToKan('.$line->id.');dijit.byId(\'kanbanListSelect\').closeDropDown();" class="kanbanMenuTree" style="float:left;height:15px;'.((isNewGui())?'position:relative;top:-2px;':'').'" '
        . ' >&nbsp;&nbsp'
            . htmlEncode($line->name)
            . "</span>";
    echo '  <a class="" onClick="copyKanban('.$line->id.')" title="' . i18n('kanbanCopy'). '" >'
        .formatSmallButton('Copy')
        .'</a> ';
    echo '  <a class="" onClick="editKanban('.$line->id.')" title="' . i18n('kanbanEdit'). '" >'
        .formatSmallButton('Edit')
        .'</a> ';
    if($line->isShared==0) echo '  <a class="" onClick="plgShareKanban('.$line->id.')" title="' . i18n('kanbanShare'). '" >'
        .formatSmallButton('Share')
        .'</a> ';
    if($line->isShared==1) echo '  <a class="" onClick="plgShareKanban('.$line->id.')" title="' . i18n('kanbanUnshare'). '" >'
        .formatSmallButton('Shared')
        .'</a> ';
    echo '  <a class="" onClick="delKanban('.$line->id.', \''.i18n("kanbanDel").'\')" title="' . i18n('kanbanDelete'). '" >'
        .formatSmallButton('Remove')
        .'</a> ';
    if (isNewGui()) echo '</div>';
    else echo "<br/>";
  }
  echo '<span style="float:left;height:15px;" value="-1" '
      . ' title="' . i18n("kanbanSelectKanban") . '" ></span><br/>';
  echo '<span class="kanbanTextTitle" style="float:left;height:15px;font-weight:bold;" disabled="disabled" value="-2" '
      . ' title="' . i18n("kanbanSelectKanban") . '" >'.i18n("kanbanShared").'</span><br/>';
  if(count($kanbanList)==0)echo '<span disabled="disabled" onclick="dijit.byId(\'kanbanListSelect\').closeDropDown();" style="float:left;height:15px;" '
      . ' >&nbsp;&nbsp;&nbsp;&nbsp;'.i18n('noDataFound').'</span><br/><br/>';
  $lastUser="";
  foreach ($kanbanList as $line) {
    if($lastUser!=$line->idUser){
      $lastUser=$line->idUser;
      echo '<div style="width:100%;height:18px;" ><span class="kanbanTextTitle" style="float:left;height:15px;font-weight:bold;margin-top:4px;">'.htmlEncode(SqlList::getNameFromId('Affectable', $lastUser)).'</span></div>';
    }
    $jsonDecode=json_decode($line->param,true);
    if(!isset($jsonDecode['typeData'])){
      $jsonDecode['typeData']='Ticket';
      $line->param=json_encode($jsonDecode);
      $line->save();
    }
    $typeKanbanCTmp=$jsonDecode['typeData'];
    if (isNewGui()) echo '<div style="margin-top:5px">';
    echo '
        <div class="imageColorNewGuiNoSelection icon'.$typeKanbanCTmp.'16 icon'.$typeKanbanCTmp.' iconSize16" style="width:16px;height:16px;float:left;"></div>
        <span onclick="kanbanGoToKan('.$line->id.');dijit.byId(\'kanbanListSelect\').closeDropDown();" class="kanbanMenuTree" style="float:left;height:15px;'.((isNewGui())?'position:relative;top:-2px;':'').'" '
            . ' >&nbsp;&nbsp'
                . htmlEncode($line->name)
                . "</span>";
    echo '  <a onClick="copyKanban('.$line->id.')" title="' . i18n('kanbanCopy'). '" class="">'
        .formatSmallButton('Copy')
        .'</a> ';
    if (isNewGui()) echo '</div>';
    else echo "<br/>";
  }
  echo "</div></div>";
  // }
}

function kanbanParameterList($idKanban){
  global $typeKanbanC, $type;
  $seeWork=Parameter::getUserParameter("kanbanSeeWork".Parameter::getUserParameter("kanbanIdKanban"));
  $seeWork=($seeWork=='on' or $seeWork=='1')?true:false;
  if($seeWork && PlanningElement::getWorkVisibiliy(getSessionUser()->idProfile)=="ALL")$seeWork=true; else $seeWork=false;
  if ($typeKanbanC=='Requirement' or $typeKanbanC=='Action'){
    $seeWork=false;
    Parameter::storeUserParameter("kanbanSeeWork".Parameter::getUserParameter("kanbanIdKanban"), $seeWork);
  }

  $showIdle = Parameter::getUserParameter("kanbanShowIdle");
  $showIdle = ($showIdle=='on' or $showIdle=='1')?true:false;

  $fullWidthElement = Parameter::getUserParameter("kanbanFullWidthElement");
  $fullWidthElement = ($fullWidthElement=='on' or $fullWidthElement=='1')?true:false;

  $hideBacklog = Parameter::getUserParameter("kanbanHideBacklog");
  $hideBacklog = ($hideBacklog=='on' or $hideBacklog=='1')?true:false;

  $hideStatus = Parameter::getUserParameter("kanbanHideStatus");
  $hideStatus = ($hideStatus=='on' or $hideStatus=='')?true:false;

  $hideProduct = Parameter::getUserParameter("kanbanHideProduct");
  $hideProduct = ($hideProduct=='on' or $hideProduct=='')?true:false;

  $hideActivityPlanning = Parameter::getUserParameter("kanbanHideActivityPlanning");
  $hideActivityPlanning = ($hideActivityPlanning=='on' or $hideActivityPlanning=='')?true:false;

  $hideResponsible = Parameter::getUserParameter("kanbanHideResponsible");
  $hideResponsible = ($hideResponsible=='on' or $hideResponsible=='')?true:false;

  $hidePriority = Parameter::getUserParameter("kanbanHidePriority");
  $hidePriority = ($hidePriority=='on' or $hidePriority=='')?true:false;

  $hideCriticality = Parameter::getUserParameter("kanbanHideCriticality");
  $hideCriticality = ($hideCriticality=='on' or $hideCriticality=='')?true:false;

  $hidePlannedDate = Parameter::getUserParameter("kanbanHidePlannedDate");
  $hidePlannedDate = ($hidePlannedDate=='on' or $hidePlannedDate=='')?true:false;

  $hidedeType = Parameter::getUserParameter("kanbanHideType");
  $hidedeType = ($hidedeType=='on' or $hidedeType=='')?true:false;

  $hideProjectName = Parameter::getUserParameter("kanbanHideProjectName");
  $hideProjectName = ($hideProjectName=='on' or $hideProjectName=='')?true:false;

  $modeColorTitle = Parameter::getUserParameter( "kanbanModeColorTitle" . Parameter::getUserParameter("kanbanIdKanban") );
  $modeColorTitle = (!$modeColorTitle)? 'noColor' : $modeColorTitle;

  $hideColorTitle = Parameter::getUserParameter("kanbanHideColorTitle");
  $hideColorTitle = ($hideColorTitle=='on')?true:false;

  echo '<table style="width:100%;">';
  echo '  <tr>';
  echo '    <td style="vertical-align:top;">';
  echo '<table style="width:240px;margin:5px 15px 5px 5px;display:inline-block;">';
  echo '  <tr>';
  echo '    <td style="width:40px;"><div class="iconDisplayOnKanban iconSize32 imageColorNewGuiNoSelection" style="border:0"></div></td>';
  echo '    <td class="dependencyHeader planningDialogTitle" style="width:200px;text-align:left;padding-left: 5px;">'.i18n('displayOnKanban').'</td>';
  echo '  </tr>';
  echo '  <tr>';
  echo '    <td style="padding-top:10px;">';
  echo '      <div id="kanbanSeeWork" name="kanbanSeeWork" class="colorSwitch" data-dojo-type="dojox/mobile/Switch" '.(($seeWork)?'value="on"':'value="off"').' leftLabel="" rightLabel="" style="width:25px;">';
  echo '        <script type="dojo/method" event="onStateChanged" >';
  echo '          saveDataToSession("kanbanSeeWork",this.value,true);';
  echo '          kanbanSeeWork()';
  echo '        </script>';
  echo '      </div>';
  echo '    </td>';
  echo '    <td style="padding-left:5px;" class="checkboxLabel"><span onclick="invertSwitchValue(\'kanbanSeeWork\');">'.pq_ucfirst(i18n("kanbanSeeWork")).'</span></td>';
  echo '  </tr>';
  echo '  <tr>';
  echo '    <td style="padding-top:2px;">';
  echo '      <div id="kanbanShowIdle" name="kanbanShowIdle" class="colorSwitch" data-dojo-type="dojox/mobile/Switch" '.(($showIdle)?'value="on"':'value="off"').' leftLabel="" rightLabel="" style="width:25px;">';
  echo '        <script type="dojo/method" event="onStateChanged" >';
  echo '          saveDataToSession("kanbanShowIdle",this.value,true);';
  echo '          kanbanShowIdle('.$idKanban.')';
  echo '        </script>';
  echo '      </div>';
  echo '    </td>';
  echo '    <td style="padding-left:5px;" class="checkboxLabel"><span onclick="invertSwitchValue(\'listShowIdle\');">'.pq_ucfirst(i18n("labelKanbanShowIdle")).'</span></td>';
  echo '  </tr>';
  echo '  <tr>';
  echo '    <td style="padding-top:2px;">';
  echo '      <div id="kanbanFullWidthElement" name="kanbanFullWidthElement" class="colorSwitch" data-dojo-type="dojox/mobile/Switch" '.(($fullWidthElement)?'value="on"':'value="off"').' leftLabel="" rightLabel="" style="width:25px;">';
  echo '        <script type="dojo/method" event="onStateChanged" >';
  echo '          saveDataToSession("kanbanFullWidthElement",this.value,true);';
  echo '          kanbanFullWidthElement()';
  echo '        </script>';
  echo '      </div>';
  echo '    </td>';
  echo '    <td style="padding-left:5px;" class="checkboxLabel"><span onclick="invertSwitchValue(\'kanbanFullWidthElement\');">'.pq_ucfirst(i18n("labelKanbanFullWidthElement")).'</span></td>';
  echo '  </tr>';
  echo '  <tr>';
  echo '    <td style="padding-top:2px;">';
  echo '      <div id="kanbanHideBacklog" name="kanbanHideBacklog" class="colorSwitch" data-dojo-type="dojox/mobile/Switch" '.(($hideBacklog)?'value="on"':'value="off"').' leftLabel="" rightLabel="" style="width:25px;">';
  echo '        <script type="dojo/method" event="onStateChanged" >';
  echo '          saveDataToSession("kanbanHideBacklog",this.value,true);';
  echo '          kanbanHideBacklog()';
  echo '        </script>';
  echo '      </div>';
  echo '    </td>';
  echo '    <td style="padding-left:5px;" class="checkboxLabel"><span onclick="invertSwitchValue(\'kanbanHideBacklog\');">'.pq_ucfirst(i18n("labelKanbanHideBacklog")).'</span></td>';
  echo '  </tr>';
  echo '</table>';
  echo '    </td>';
  echo '    <td rowspan="2" style="vertical-align:top;">';
  echo '<table style="width:240px;margin:5px 5px 0px 5pxpx;display:inline-block;">';
  echo '  <tr style="padding:5px;">';
  echo '    <td style="width:40px;"><div class="iconDisplayOnKanbanTiles iconSize32 imageColorNewGuiNoSelection" style="border:0"></div></td>';
  echo '    <td class="dependencyHeader planningDialogTitle" style="width:200px;text-align:left;padding-left: 5px;">'.i18n('displayOnKanbanTiles').'</td>';
  echo '  </tr>';
  echo '  <tr>';
  echo '    <td style="padding-top:2px;">';
  echo '      <div id="kanbanHideStatus" name="kanbanHideStatus" class="colorSwitch" data-dojo-type="dojox/mobile/Switch" '.(($hideStatus)?'value="on"':'value="off"').' leftLabel="" rightLabel="" style="width:25px;">';
  echo '        <script type="dojo/method" event="onStateChanged" >';
  echo '          saveDataToSession("kanbanHideStatus",this.value,true);';
  echo '          kanbanHideStatus()';
  echo '        </script>';
  echo '      </div>';
  echo '    </td>';
  echo '    <td style="padding-left:5px;" class="checkboxLabel"><span onclick="invertSwitchValue(\'kanbanHideStatus\');">'.pq_ucfirst(i18n("labelKanbanHideStatus")).'</span></td>';
  echo '  </tr>';
  echo '  <tr>';
  echo '    <td style="padding-top:2px;">';
  echo '      <div id="kanbanHideProduct" name="kanbanHideProduct" class="colorSwitch" data-dojo-type="dojox/mobile/Switch" '.(($hideProduct)?'value="on"':'value="off"').' leftLabel="" rightLabel="" style="width:25px;">';
  echo '        <script type="dojo/method" event="onStateChanged" >';
  echo '          saveDataToSession("kanbanHideProduct",this.value,true);';
  echo '          kanbanHideProduct()';
  echo '        </script>';
  echo '      </div>';
  echo '    </td>';
  echo '    <td style="padding-left:5px;" class="checkboxLabel"><span onclick="invertSwitchValue(\'kanbanHideProduct\');">'.pq_ucfirst(i18n("labelKanbanHideProduct")).'</span></td>';
  echo '  </tr>';
  echo '  <tr>';
  echo '    <td style="padding-top:2px;">';
  echo '      <div id="kanbanHideActivityPlanning" name="kanbanHideActivityPlanning" class="colorSwitch" data-dojo-type="dojox/mobile/Switch" '.(($hideActivityPlanning)?'value="on"':'value="off"').' leftLabel="" rightLabel="" style="width:25px;">';
  echo '        <script type="dojo/method" event="onStateChanged" >';
  echo '          saveDataToSession("kanbanHideActivityPlanning",this.value,true);';
  echo '          kanbanHideActivityPlanning()';
  echo '        </script>';
  echo '      </div>';
  echo '    </td>';
  echo '    <td style="padding-left:5px;" class="checkboxLabel"><span onclick="invertSwitchValue(\'kanbanHideActivityPlanning\');">'.pq_ucfirst(i18n("labelKanbanHideActivityPlanning")).'</span></td>';
  echo '  </tr>';
  echo '  <tr>';
  echo '    <td style="padding-top:2px;">';
  echo '      <div id="kanbanHideResponsible" name="kanbanHideProduct" class="colorSwitch" data-dojo-type="dojox/mobile/Switch" '.(($hideResponsible)?'value="on"':'value="off"').' leftLabel="" rightLabel="" style="width:25px;">';
  echo '        <script type="dojo/method" event="onStateChanged" >';
  echo '          saveDataToSession("kanbanHideResponsible",this.value,true);';
  echo '          kanbanHideResponsible()';
  echo '        </script>';
  echo '      </div>';
  echo '    </td>';
  echo '    <td style="padding-left:5px;" class="checkboxLabel"><span onclick="invertSwitchValue(\'kanbanHideResponsible\');">'.pq_ucfirst(i18n("labelKanbanHideResponsible")).'</span></td>';
  echo '  </tr>';
  echo '  <tr>';
  echo '    <td style="padding-top:2px;">';
  echo '      <div id="kanbanHidePriority" name="kanbanHidePriority" class="colorSwitch" data-dojo-type="dojox/mobile/Switch" '.(($hidePriority)?'value="on"':'value="off"').' leftLabel="" rightLabel="" style="width:25px;">';
  echo '        <script type="dojo/method" event="onStateChanged" >';
  echo '          saveDataToSession("kanbanHidePriority",this.value,true);';
  echo '          kanbanHidePriority()';
  echo '        </script>';
  echo '      </div>';
  echo '    </td>';
  echo '    <td style="padding-left:5px;" class="checkboxLabel"><span onclick="invertSwitchValue(\'kanbanHidePriority\');">'.pq_ucfirst(i18n("labelKanbanHidePriority")).'</span></td>';
  echo '  </tr>';
  echo '  <tr>';
  echo '    <td style="padding-top:2px;">';
  echo '      <div id="kanbanHideCriticality" name="kanbanHideProduct" class="colorSwitch" data-dojo-type="dojox/mobile/Switch" '.(($hideCriticality)?'value="on"':'value="off"').' leftLabel="" rightLabel="" style="width:25px;">';
  echo '        <script type="dojo/method" event="onStateChanged" >';
  echo '          saveDataToSession("kanbanHideCriticality",this.value,true);';
  echo '          kanbanHideCriticality()';
  echo '        </script>';
  echo '      </div>';
  echo '    </td>';
  echo '    <td style="padding-left:5px;" class="checkboxLabel"><span onclick="invertSwitchValue(\'kanbanHideCriticality\');">'.pq_ucfirst(i18n("labelKanbanHideUrgency")).'</span></td>';
  echo '  </tr>';
  echo '  <tr>';
  echo '    <td style="padding-top:2px;">';
  echo '      <div id="kanbanHidePlannedDate" name="kanbanHidePlannedDate" class="colorSwitch" data-dojo-type="dojox/mobile/Switch" '.(($hidePlannedDate)?'value="on"':'value="off"').' leftLabel="" rightLabel="" style="width:25px;">';
  echo '        <script type="dojo/method" event="onStateChanged" >';
  echo '          saveDataToSession("kanbanHidePlannedDate",this.value,true);';
  echo '          kanbanHidePlannedDate()';
  echo '        </script>';
  echo '      </div>';
  echo '    </td>';
  echo '    <td style="padding-left:5px;" class="checkboxLabel"><span onclick="invertSwitchValue(\'kanbanHidePlannedDate\');">'.pq_ucfirst(i18n("labelKanbanHidePlannedDate")).'</span></td>';
  echo '  </tr>';
  echo '  <tr>';
  echo '    <td style="padding-top:2px;">';
  echo '      <div id="kanbanHideType" name="kanbanHideType" class="colorSwitch" data-dojo-type="dojox/mobile/Switch" '.(($hidedeType)?'value="on"':'value="off"').' leftLabel="" rightLabel="" style="width:25px;">';
  echo '        <script type="dojo/method" event="onStateChanged" >';
  echo '          saveDataToSession("kanbanHideType",this.value,true);';
  echo '          kanbanHideType()';
  echo '        </script>';
  echo '      </div>';
  echo '    </td>';
  echo '    <td style="padding-left:5px;" class="checkboxLabel"><span onclick="invertSwitchValue(\'kanbanHideType\');">'.pq_ucfirst(i18n("labelKanbanHideType")).'</span></td>';
  echo '  </tr>';

  echo '  <tr>';
  echo '    <td style="padding-top:2px;">';
  echo '      <div id="kanbanHideColorTitle" name="kanbanHideColorTitle" class="colorSwitch" data-dojo-type="dojox/mobile/Switch" '.(($hideColorTitle)?'value="on"':'value="off"').' leftLabel="" rightLabel="" style="width:25px;">';
  echo '        <script type="dojo/method" event="onStateChanged" >';
  echo '          saveDataToSession("kanbanHideColorTitle",this.value,true);';
  echo '          kanbanHideColorTitle()';
  echo '        </script>';
  echo '      </div>';
  echo '    </td>';
  echo '      <td colspan="2" style="padding-left:5px;"><span class="checkboxLabel" onclick="invertSwitchValue(\'kanbanHideColorTitle\');">'.pq_ucfirst(i18n("labelKanbanHideColorTitle")).'</span>';
  echo '        <select id="kanbanModeColorTitle" name="kanbanModeColorTitle" class="comboButton" dojoType="dijit.form.FilteringSelect" style="width:75px;" value="'.$modeColorTitle.'">';
  $arrOpt=array(
      "noColor"=>" ",
      "colorProject"=>'Replan',
      "colorItem"=>'sectionActivity',
      "colorType"=>'colType',
      "colorPriority"=>'colPriority',
      "colorUrgency"=>"colUrgency");
  foreach ($arrOpt as $key=>$val){
    if ($key == 'noColor') {
      $label = '&nbsp;';
    } else {
      $label = ucfirst(i18n($val));
    }
    if ($key == 'colorItem' && $typeKanbanC != 'Activity') continue;
    if ($key == 'colorUrgency' && ($typeKanbanC == 'Activity' || $typeKanbanC == 'Action')) continue;
    if ($key == 'colorPriority' && $typeKanbanC == 'Activity') continue;
    if ($key == 'colorType' && ($typeKanbanC == 'Action' || $typeKanbanC == 'Ticket' || $typeKanbanC == 'Requirement')) continue;
    echo '        <option value="'.$key.'">'.$label.'</option>';
  }
  echo '        <script type="dojo/method" event="onChange" >';
  echo '          saveDataToSession("kanbanModeColorTitle",this.value,true);';
  echo '          if (this.value == "noColor") {';
  echo '            dijit.byId("kanbanHideColorTitle").set("value", "off");';
  echo '          } else {';
  echo '            dijit.byId("kanbanHideColorTitle").set("value", "on");';
  echo '          }';
  echo '          kanbanModeColorTitle()';
  echo '        </script>';
  echo '        </select>';
  echo '      </td>';
  echo '  </tr>';

  if ($fullWidthElement){
    echo '  <tr>';
    echo '    <td style="padding-top:2px;">';
    echo '      <div id="kanbanHideProjectName" name="kanbanHideProjectName" class="colorSwitch" data-dojo-type="dojox/mobile/Switch" '.(($hideProjectName)?'value="on"':'value="off"').' leftLabel="" rightLabel="" style="width:25px;">';
    echo '        <script type="dojo/method" event="onStateChanged" >';
    echo '          saveDataToSession("kanbanHideProjectName",this.value,true);';
    echo '          kanbanHideProjectName()';
    echo '        </script>';
    echo '      </div>';
    echo '    </td>';
    echo '    <td style="padding-left:5px;" class="checkboxLabel"><span onclick="invertSwitchValue(\'kanbanHideProjectName\');">'.pq_ucfirst(i18n("labelKanbanHideProjectName")).'</span></td>';
    echo '  </tr>';
  }
  echo '</table>';
  echo '    </td>';
  echo '  </tr>';
  echo '  <tr>';
  echo '    <td style="vertical-align:top;">';
  echo '<table style="width:240px;margin:5px 15px 0px 5px;display:inline-block;">';
  echo '  <tr>';
  echo '    <td style="width:40px;"><div class="iconDisplayOnKanbanManagement iconSize32 imageColorNewGuiNoSelection" style="border:0"></div></td>';
  echo '    <td class="dependencyHeader planningDialogTitle" style="width:200px;text-align:left;padding-left: 5px;">'.i18n('displayOnKanbanManagement').'</td>';
  echo '  </tr>';
  echo '  <tr>';
  echo '    <td colspan="2">';
  echo '      <table style="width:100%;text-align:center;margin-top: 5px;">';
  echo '        <tr>';
  echo '          <td style="width:80px;text-align:center;vertical-align:top;">';
  if($idKanban!=-1){
    echo '          <div dojoType="dijit.form.Button" class="detailButton" style="position:relative;cursor:pointer;padding-right: 5px"';
    echo '            onclick="loadDialog(\'dialogKanbanUpdate\', function(){kanbanFindTitle(\'addKanban\');}, true, \'&typeDynamic=addKanban\', true, false);">'.formatIcon('KanbanAdd',32,i18n('kanbanAdd')).'</div>';
  }
  echo '          </td>';
  echo '          <td style="width:80px;text-align:center;vertical-align:top;">';
  if($idKanban!=-1 && myKanban($idKanban)){
    echo '          <div dojoType="dijit.form.Button" class="detailButton" style="position:relative;cursor:pointer;padding-right: 5px"';
    echo '            onclick="loadDialog(\'dialogKanbanUpdate\', function(){kanbanFindTitle(\'kanbanEdit\');}, true, \'&typeDynamic=addColumnKanban&typeD='.$type.'&idKanban='.$idKanban.'\', true, false);">'.formatIcon('KanbanAddColumns',32,i18n('kanbanAddColumn')).'</div>';
  }
  echo '          </td>';
  echo '          <td style="width:80px;text-align:center;vertical-align:top;">';
  if($idKanban!=-1){
    echo '          <div dojoType="dijit.form.Button" class="detailButton" style="position:relative;cursor:pointer;padding-right: 5px"';
    echo '            onclick="showDetail(\'refreshActionAdd'.$typeKanbanC.'\',1,\''.$typeKanbanC.'\',false,\'new\');">'.formatIcon('KanbanAdd'.$typeKanbanC,32, i18n('kanbanAdd'.$typeKanbanC)).'</div>';
  }
  echo '          </td>';
  echo '        </tr>';
  echo '        <tr>';
  echo '          <td style="font-size:80%;color:#a0a0a0;vertical-align: top;">'.i18n('kanbanAddShort').'</td>';
  echo '          <td style="font-size:80%;color:#a0a0a0;vertical-align: top;">'.i18n('kanbanAddColumnShort').'</td>';
  echo '          <td style="font-size:80%;color:#a0a0a0;vertical-align: top;">'.i18n('kanbanAdd'.$typeKanbanC.'Short').'</td>';
  echo '        </tr>';
  echo '      </table>';
  echo '    </td>';
  echo '  </tr>';
  echo '</table>';
  echo '    </td>';
  echo '  </tr>';
  echo '</table>';
}

function getLastStatus(){
  $status=new Status();
  $tableName=$status->getDatabaseTableName();
  $result=Sql::query("SELECT t.id as id
      FROM $tableName t where idle=0 order by t.sortOrder desc");
  while ($line = Sql::fetchLine($result)) {
    return $line["id"];
  }
  return '';
}

function drawColumnKanban($type,$jsonD,$idKanban){
  global $typeKanbanC;
  $statusList=SqlList::getList('Status','name',null,true);
  $allowedStatus=array();
  $kanbanFullWidthElement = Parameter::getUserParameter ( "kanbanFullWidthElement" );
  $hideBacklog = (Parameter::getUserParameter ( "kanbanHideBacklog" )=='on' or Parameter::getUserParameter ( "kanbanHideBacklog" )=='1')?1:0;
  if(count($jsonD['column'])!=0){
    $jsonArray=array();
    $keyJsonOrder=array();
    $sortedColumns=array();
    foreach ($jsonD['column'] as $key=>$itemKanban) {
      if((isset($itemKanban['cantDelete']) or $itemKanban['name'] == 'Backlog') and $hideBacklog == 0 and count($jsonD['column']) > 1){
        unset($jsonD['column'][$key]);
        continue;
      }
      if($itemKanban['from']!='n'){
        $obj = new $type($itemKanban['from'],true);
        if(isset($obj->sortOrder)){
          $jsonArray[str_pad($obj->sortOrder,5,'0', STR_PAD_LEFT).'-'.$obj->id]=$itemKanban;
        }else{
          $jsonArray[$obj->name.'-'.$obj->id]=$itemKanban;
        }
      }else{
        $jsonArray['00000-'.$itemKanban['from']]=$itemKanban;
      }
    }
    ksort($jsonArray);
    foreach ($jsonArray as $key=>$itemKanban) {
      $keyJsonOrder[]=$key;
      $sortedColumns[]=$itemKanban;
    }
    $numCol = count($jsonD['column']);
    $isStatus=$type=="Status";
    $mapAccept=array();
    $accept="[";
    $iterateur=0;
    if(!$isStatus){ // Form Kanban on other than Status, Accept is simple : no restriction for moves
      foreach ($jsonD['column'] as $itemKanban) {
        $accept.='\'typeRow'.$itemKanban['from'].'\'';
        if($iterateur!=count($jsonD['column'])-1)$accept.=',';
      }
    }else{ // For Kanban on Status, Accept must respect workflow, corresponding to user profile
      $user=getSessionUser();
      $mapWorkflow=array();
      $curCol=null;
      $culSta=null;
      for ($i=0;$i<count($sortedColumns);$i++) {
        $itemKanban=$sortedColumns[$i];
        $idFrom=$itemKanban['from'];
        $allowedStatus[$idFrom]=array($idFrom=>$idFrom);
        $found=false;
        foreach ($statusList as $idS=>$nameS) {
          if ($found) {
            if (isset($sortedColumns[$i+1]) and $idS==$sortedColumns[$i+1]['from']) {
              break;
            } else {
              $allowedStatus[$idFrom][$idS]=$idS;
            }
          } else if ($idS==$idFrom) {
            $found=true;
          }
        }
      }
      //$visibleProjects=pq_explode(',',pq_trim(getVisibleProjectsList(true),'()'));
      foreach ($user->getAllProfiles() as $idProfile){ // For each profile of the user (on any project)
        //$idProfil=$user->getProfile($idProject);
        foreach (SqlList::getList("Status",'id') as $idStatus){ // For every status
          foreach (SqlList::getList($typeKanbanC."Type",'id') as $idTicketType){ // For every type (Ticket type or Activity Type)
            $workflowId=SqlList::getFieldFromId($typeKanbanC."Type", $idTicketType, 'idWorkflow');
            if(!isset($mapWorkflow[$workflowId])){
              $woTmp=new Workflow($workflowId);
              $mapWorkflow[$workflowId]=$woTmp->getWorkflowstatusArray();
            }
            foreach ($jsonD['column'] as $itemKanban) { // For all defined columns on the Kanban (id of status is in the from field
              foreach ($allowedStatus[$itemKanban['from']] as $idStatusTo) {
                $toPut="";
                if($idStatusTo!=$idStatus) {
                  if(isset($idProfile)
                      && isset($mapWorkflow[$workflowId][$idStatus])
                      && isset($mapWorkflow[$workflowId][$idStatus][$idStatusTo])) {
                        if(isset($mapWorkflow[$workflowId][$idStatus][$idStatusTo][$idProfile])
                            && $mapWorkflow[$workflowId][$idStatus][$idStatusTo][$idProfile]) {
                              $toPut='typeRow'.$idStatus.'-'.$idTicketType.'-'.pq_trim($idProfile);
                            }
                      }
                }
                if($toPut!=""){
                  $exist=false;
                  if(isset($mapAccept[$itemKanban['from']]))if(pq_strpos($mapAccept[$itemKanban['from']], $toPut) !== false)$exist=true;
                  if(!$exist){
                    if(!isset($mapAccept[$itemKanban['from']])){
                      $mapAccept[$itemKanban['from']]="'$toPut'";
                    }else{
                      $mapAccept[$itemKanban['from']].=",'$toPut'";
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    $accept.="]";
    $percent=100/count($jsonD['column']);
    $iterateur=0;
    foreach ($jsonArray as $itemKanban) {
      $nextFrom=$itemKanban['from'];
      if($iterateur<count($jsonArray)-1 && $isStatus){
        $nextFrom=getNextFrom($itemKanban['from'],$jsonArray[$keyJsonOrder[$iterateur+1]]['from'],$type); //bug offset too high
      }else if($isStatus){
        $nextFrom=getLastStatus();
      }
      $result=queryToDo($itemKanban['from'],$nextFrom,$type,$isStatus);
      $realWork=0;
      $plannedWork=0;
      $leftWork=0;
      foreach($result as $line){
        $realWork+=$line['realwork'];
        $plannedWork+=$line['plannedwork'];
        $leftWork+=$line['leftwork'];
      }
      $nbItems=Sql::$lastQueryNbRows;
      $acceptTmp=$accept;
      if(isset($mapAccept[$itemKanban['from']]))$acceptTmp='['.$mapAccept[$itemKanban['from']].']';
      if($type=="Activity")$acceptTmp="[".SqlList::getFieldFromId("Activity", $itemKanban['from'], "idProject")."]";
      if($itemKanban['from']=="n" || $type=="TargetProductVersion")$acceptTmp="[";
      if($type=="TargetProductVersion")$acceptTmp.="'n',";
      if($itemKanban['from']=="n" || $type=="TargetProductVersion"){
        $iterateur2=0;
        foreach($jsonD['column'] as $keyy=>$vall){
          if($vall['from']!='n'){
            if($type=='Activity')$acceptTmp.=SqlList::getFieldFromId('Activity', $vall['from'], 'idProject');
            else $acceptTmp.=$vall['from'];
            $iterateur2++;
            if($iterateur2!=count($jsonD['column'])-1)$acceptTmp.=",";
          }
        }
      }
      if($itemKanban['from']=="n" || $type=="TargetProductVersion")$acceptTmp.="]";
      if($type=="Milestone"){
        $projectList = getVisibleProjectsList();
        $projectList = pq_str_replace('(', '', $projectList);
        $projectList = pq_str_replace(')', '', $projectList);
        $acceptTmp = "[".$projectList."]";
      }
      $destHeight=RequestHandler::getValue('destinationHeight');
      $destWidth=RequestHandler::getValue('destinationWidth');
      if ($destHeight) {
         $maxHeight=($destHeight-((RequestHandler::getValue('xhrPostDestination')=='divKanbanContainer')?76:161));
         $seeWork=Parameter::getUserParameter("kanbanSeeWork".Parameter::getUserParameter("kanbanIdKanban"));
         $seeWork=($seeWork=='on' or $seeWork=='1')?true:false;
         if ($seeWork) $maxHeight-=32;
         if (isNewGui()) $maxHeight-=6;
         $maxHeight.='px';
      } else {
        $maxHeight='100%';
      }
      if ($destWidth) {
        $nbCols=count($jsonD['column']);
        $maxWidth=((($destWidth)/$nbCols)-20)."px";
      } else {
        $maxWidth="332px";
      }
      
      echo '<td style="vertical-align:top;;width:'.$maxWidth.';min-width:355px;">
            <table style="width:100%;"><tr style="min-height:47px;height:47px;max-height:47px;">
            <td class="kanbanColumn" style="position:relative;background-color:'.((isNewGui())?'var(--color-light);border-radius:10px 10px 0 0':'#e2e4e6').';padding:3px 8px 0px;border-bottom:2px solid #ffffff;min-width:355px;">';
      getNameFromTypeKanban($itemKanban,$nextFrom,$type,$isStatus,$nbItems,$idKanban,$realWork,$plannedWork,$leftWork);
      echo '</td></tr><tr>';
      echo '
        <td class="kanbanColumn" style="overflow-y:scroll;overflow-x:hidden;display:block; height:'.$maxHeight.';max-height:'.$maxHeight.'; position:relative;background-color:'.((isNewGui())?'var(--color-light);border:2px solid var(--color-light);border-radius:0 0 10px 10px':'#e2e4e6').';padding:'.(($kanbanFullWidthElement=='on')?'8px':'6px 0px 6px 4px').';width:auto;min-width:355px;" id="dialogRow'.$itemKanban['from']. '"
        jsId="dialogRow'.$itemKanban['from']. '" dojotype="dojo.dnd.Source" dndType="typeRow'.$itemKanban['from']. '" withhandles="true"
        '.($acceptTmp!='[]' ? 'data-dojo-props="accept: '.$acceptTmp.',singular:true, horizontal:'.(($kanbanFullWidthElement == 'on')?'false':'true').'"':'data-dojo-props="singular:true, horizontal:'.(($kanbanFullWidthElement == 'on')?'false':'true').'"').' width="'.((100/count($jsonArray))).'%" valign="top">';
      echo '
      <script type="dojo/connect" event="onDndStart" args="evt">
        anchorTmp=evt.anchor;
        evt.anchor.style.display=\'none\';
        return true;
      </script>
      <script type="dojo/connect" event="onDndCancel" args="evt">
      anchorTmp.style.display=\'block\';
        return true;
      </script>';
      getItemsFromTypeIdKanban($itemKanban['from'], $nextFrom, $type,$isStatus,$result,$jsonD);

      echo '</td></tr></table>
      </td>';
      $iterateur++;
      if ($iterateur<count($jsonArray)) {
        echo '
        <td style="min-width:10px;max-width:10px;width:10px" width="10px"></td>';
      }
    }
  }
}

function getNextFrom($from,$next,$type){
  global $typeKanbanC;
  $min=SqlList::getFieldFromId($type, $from, "sortOrder");

  $obT=new $type();
  $tableName=$obT->getDatabaseTableName();
  if ($type=='Status') {
    $workflowStatus = new WorkflowStatus ();
    $tableName2 = $workflowStatus->getDatabaseTableName ();
    $type = new Type ();
    $tableName3 = $type->getDatabaseTableName ();
    $result = Sql::query ( "SELECT s.id as typen, s.sortOrder as sortorder from $tableName s where s.idle=0 and (s.id in (select idStatusFrom from $tableName2 w, $tableName3 t where t.idWorkflow=w.idWorkflow and t.scope='$typeKanbanC')
        or s.id in (select idStatusTo from $tableName2 w, $tableName3 t where t.idWorkflow=w.idWorkflow and t.scope='$typeKanbanC') ) order by s.sortOrder" );
  } else {
    $result=Sql::query("SELECT t.id as typen, t.sortOrder as sortorder FROM $tableName t WHERE t.sortOrder>=$min order by t.sortOrder ");
  }
  $ite=0;
  while ($line = Sql::fetchLine($result)) {
    $listId[]=$line;
  }
  $last=-1;
  foreach($listId as $line){
    if(count($listId)-1!=$ite+1){
      if(isset($listId[$ite+1]) && $listId[$ite+1]['typen']==$next) {
        return $line['typen'];
      }
    }
    $last=$line['typen'];
    $ite++;
  }
  return $last;
}

function getNameFromTypeKanban($itemKanban,$to,$type,$isStatus,$nb,$idKanban,$realWork,$plannedWork,$leftWork){
  $name=$itemKanban['name'];
  $from=$itemKanban['from'];
  $itemWork['realWork']=$realWork;
  $itemWork['plannedWork']=$plannedWork;
  $itemWork['leftWork']=$leftWork;
  $itemWork['id']=$itemKanban['from'];
  $seeWork=Parameter::getUserParameter("kanbanSeeWork".Parameter::getUserParameter("kanbanIdKanban"));
  $seeWork=($seeWork=='on' or $seeWork=='1')?true:false;
  if(PlanningElement::getWorkVisibiliy(getSessionUser()->idProfile) != "ALL")$seeWork=false;
  if($seeWork && PlanningElement::getWorkVisibiliy(getSessionUser()->idProfile)=="ALL")$seeWork=true; else $seeWork=false;
  $addHeight='';
  if($seeWork)$addHeight="height:65px;";
  echo '<div style="margin-bottom:10px;'.$addHeight.'>';
  if($isStatus){
    echo '<h2 style="font-size: 14px;font-weight:bold;margin: 8px 8px 2px;color:#4d4d4d">'.htmlEncode($name);
    if(!isset($itemKanban['cantDelete']) && myKanban($idKanban))
      echo ' <a onClick="delKanban('.$idKanban.', \''.i18n("kanbanDelColumn").'\','.$from.')" title="' . i18n('kanbanColumnDelete') . '" class="smallButton"/> '.formatSmallButton('Remove').'</a>';
    if(myKanban($idKanban)) {
      echo '<a onClick="loadDialog(\'dialogKanbanUpdate\', function(){kanbanFindTitle(\'editColumnKanban\');}, true, \'&typeDynamic=addColumnKanban&typeD='.$type.'&idKanban='.$idKanban.'&idFrom='.$from.'\', true, false);"title="' . i18n('kanbanColumnEdit') . '" class="smallButton"  /> '.formatSmallButton('Edit').'</a>';
    }
    echo '</h2><div id="numberTickets'.$from.'" class="sectionBadge">'.$nb.'</div>'.displayAllWork($itemWork);
    echo '<h3 class="kanbanTextTitle" style="font-size: 10px;font-weight:bold;margin: 0 8px 9px;">'.i18n("from").' '.SqlList::getNameFromId($type, $from).' '.i18n("to").' '.SqlList::getNameFromId($type, $to).'</h3>';
  }else{
    $nameN=SqlList::getNameFromId(((pq_substr($type,-7)=='Version')?'Version':$type), $from);
    if($name!='')$nameN=$name;
    echo '<h2 style="font-size: 14px;font-weight:bold;margin: 8px 8px 2px;color:#4d4d4d">'.$nameN;
    if(!isset($itemKanban['cantDelete']) && myKanban($idKanban))
      echo ' <a onClick="delKanban('.$idKanban.', \''.i18n("kanbanDelColumn").'\','.$from.')" title="' . i18n('kanbanColumnDelete') . '" class="smallButton"/> '.formatSmallButton('Remove').'</a>';
    if(myKanban($idKanban) && $from!= 'n')
      echo ' <a onClick="loadDialog(\'dialogKanbanUpdate\', function(){kanbanFindTitle(\'editColumnKanban\');}, true, \'&typeDynamic=addColumnKanban&typeD='.$type.'&idKanban='.$idKanban.'&idFrom='.$from.'\', true, false);" title="' . i18n('kanbanColumnEdit') . '" class="smallButton"  /> '.formatSmallButton('Edit').'</a>';
    echo '</h2><div id="numberTickets'.$from.'" class="sectionBadge">'.$nb.'</div>'.displayAllWork($itemWork);
  }
  echo '</div>';
}

function queryToDo($from,$nextFrom,$type,$isStatus){

  global $typeKanbanC,$hasVersion;
  global $orderBy;
  $obT=new $typeKanbanC();
  $obT2=new WorkElement();
  $obT3=new Status();
  $obT4=new Resource();
  $obT5=new TargetProductVersion();
  $obj=$obT;
  if($typeKanbanC=='Activity')$obT2=new PlanningElement();
  $tableName=$obT->getDatabaseTableName();
  if($typeKanbanC!='Requirement' and $typeKanbanC!='Action'){
    $tableName2=$obT2->getDatabaseTableName();
  }else{
    $tableName2=null;
  }
  $tableName3=$obT3->getDatabaseTableName();
  $tableName4=$obT4->getDatabaseTableName();
  if ($hasVersion) {
    $tableName5=$obT5->getDatabaseTableName();
  } else {
    $tableName5=null;
  }
  //   $prio = new Priority();
  //   $tableName7=$prio->getDatabaseTableName();
  if($from=='n'){
    $listType=' is null ';
  }else{
    $listType='in ('.getIdsOfType($from,$nextFrom,$type).') ';
  }
  $arrayFilter=array();
  if(isset(getSessionUser()->_arrayFilters[$typeKanbanC]) && is_array(getSessionUser()->_arrayFilters[$typeKanbanC]))$arrayFilter=getSessionUser()->_arrayFilters[$typeKanbanC];
  $queryFrom=$tableName;
  $queryWhere=" and 1=1 ";
  $queryOrderBy='';
  $idTab=0;
  $crit=$obT->getDatabaseCriteria();
  /*foreach ($crit as $col => $val) {
   $queryWhere.= ($queryWhere=='')?'':' and ';
   $queryWhere.= $obj->getDatabaseTableName() . '.' . $obj->getDatabaseColumnName($col) . "=" . Sql::str($val) . " ";
  }*/
  $table=$tableName;
  foreach ($arrayFilter as $i => $crit) {
    if (pq_trim($crit['sql']['operator'])=='exists') {
      $crit['sql']['attribute']=null;
    }
    if ($crit['sql']['operator']!='SORT') { // Sorting already applied above
      $split=pq_explode('_', $crit['sql']['attribute']);
      if (pq_strpos($crit['sql']['attribute'], '__id')>0) $split=array();
      $critSqlValue=$crit['sql']['value'];
      
      // Dynamic filter
      if (array_key_exists('isDynamic', $crit) and $crit['isDynamic']=='1' and ($crit['sql']['operator']=='IN' or $crit['sql']['operator']=='NOT IN')) {
        if ($crit['sql']['value']==0) continue;
      }
      
      // Work
      if (pq_substr($crit['sql']['attribute'], -4, 4) == 'Work' and pq_substr($critSqlValue,0,1)!='[') {
        if ($typeKanbanC=='Ticket') {
          $critSqlValue=Work::convertImputation(pq_trim($critSqlValue,"'"));
        } else {
          $critSqlValue=Work::convertWork(pq_trim($critSqlValue,"'"));
        }
      }
      
      if ($crit['sql']['operator']=='IN'
          and ($crit['sql']['attribute']=='idProduct' or $crit['sql']['attribute']=='idProductOrComponent' or $crit['sql']['attribute']=='idComponent')) {
            $critSqlValue=pq_str_replace(array(' ','(',')'), '', $critSqlValue);
            $splitVal=pq_explode(',',$critSqlValue);
            $critSqlValue='(0';
            foreach ($splitVal as $idP) {
              $prod=new Product($idP,true);
              $critSqlValue.=', '.$idP;
              $list=$prod->getRecursiveSubProductsFlatList(false, false); // Will work only if selected is Product, not for Component
              foreach ($list as $idPrd=>$namePrd) {
                $critSqlValue.=', '.$idPrd;
              }
            }
            $critSqlValue.=')';
          }
          
          // itemName
          if ($crit['sql']['attribute'] == 'itemName') {
            $queryWhere.=($queryWhere=='')?'':' and ';
            $queryWhere .= '(';
            $ass = new Assignment();
            $assTable = $ass->getDatabaseTableName();
            $queryRefTypes = Sql::query("SELECT DISTINCT refType FROM $assTable");
            $refTypes = [];
            $isPgSql = Sql::isPgsql();
            while ($row = Sql::fetchLine($queryRefTypes)) {
              if ($isPgSql){
                if (isset($row['reftype']) && !in_array($row['reftype'], $refTypes)) {
                  if (class_exists($row['reftype'])) $refTypes[] = $row['reftype'];
                }
              }else{
                if (isset($row['refType']) && !in_array($row['refType'], $refTypes)) {
                  if (class_exists($row['refType'])) $refTypes[] = $row['refType'];
                }
              }
            }
            $conditions = [];
            $operator = strtoupper(trim($crit['sql']['operator']));
            foreach ($refTypes as $refType) {
              $alias = strtoupper(substr($refType, 0, 2));
              $conditions[] = "($tableName.refType = '$refType' AND $alias.name $operator " .$critSqlValue. ")";
            }
            if ($operator == 'IS NULL') {
              $refTypeList = "'" . implode("','", $refTypes) . "'";
              $conditions[] = "($tableName.refType NOT IN ($refTypeList))";
            }
            $queryWhere .= implode(' OR ', $conditions) . ')';
            continue;
          }
          
          // indicatorFileNoteLink
          if ($crit['sql']['attribute'] == 'indicatorFileNoteLink') {
            $queryWhere.=($queryWhere=='')?'':' and ';
            $aff=new Affectable(getSessionUser()->id,true);
            $idTeamCurrentUser = $aff->idTeam;
            $userId = getSessionUser()->id;
            $note = new Note();
            $noteTable = $note->getDatabaseTableName();
            $link = new Link();
            $linkTable = $link->getDatabaseTableName();
            $attachment = new Attachment();
            $attachmentTable = $attachment->getDatabaseTableName();
            $operator = strtoupper(trim($crit['sql']['operator']));
            $nullOrNot = ($operator == 'IS NULL') ? '=' : '>';
            $andOr = ($operator == 'IS NULL') ? 'AND' : 'OR';
            $isNullIsNotNull = ($operator == 'IS NULL' || $operator == 'IS NOT NULL') ? true : false;
            $queryWhere.='(';
            if ($operator == 'HASNOTES' || $isNullIsNotNull){
              $queryWhere .= '((SELECT COUNT(n.id) FROM '.$noteTable.' n WHERE n.refType = \'' . $typeKanbanC . '\' AND n.refId = ' . $tableName . '.id
                                  AND (n.idPrivacy=1 OR (n.idPrivacy=2 and n.idTeam=' . Sql::fmtId($idTeamCurrentUser) . ') OR (n.idPrivacy=3 and n.idUser=' . Sql::fmtId($userId) . '))) ' . $nullOrNot . ' 0) ';
              if ($isNullIsNotNull) $queryWhere .= $andOr;
            }
            if ($operator == 'HASATTACHMENTS' || $isNullIsNotNull){
              $queryWhere .= '((SELECT COUNT(a.id) FROM '.$attachmentTable.' a WHERE a.refType = \'' . $typeKanbanC . '\' AND a.refId = ' . $tableName . '.id
                                  AND (a.idPrivacy=1 OR (a.idPrivacy=2 and a.idTeam=' . Sql::fmtId($idTeamCurrentUser) . ') OR (a.idPrivacy=3 and a.idUser=' . Sql::fmtId($userId) . '))) ' . $nullOrNot . ' 0) ';
              if ($isNullIsNotNull) $queryWhere .=  $andOr;
            }
            if ($operator == 'HASLINKS' || $isNullIsNotNull){
              $queryWhere .= '((SELECT COUNT(l.id) FROM '.$linkTable.' l WHERE (l.ref1Type = \'' . $typeKanbanC . '\' AND l.ref1Id = ' . $tableName . '.id
                                  OR l.ref2Type = \'' . $typeKanbanC . '\' AND l.ref2Id = ' . $tableName . '.id)) ' . $nullOrNot .' 0) ';
            }
            $queryWhere.=')';
            continue;
          }
          
          if (count($split)>1 ) {
            $externalClass=$split[0];
            $externalObj=new $externalClass();
            $externalTable = $externalObj->getDatabaseTableName();
            $idTab+=1;
            $externalTableAlias = 'T' . $idTab;
            $queryFrom .= ' left join ' . $externalTable . ' as ' . $externalTableAlias .
            ' on ( ' . $externalTableAlias . ".refType='" . get_class($obj) . "' and " .  $externalTableAlias . '.refId = ' . $table . '.id )';
            $queryWhere.=($queryWhere=='')?'':' and ';
            
            $extField=$externalObj->getDatabaseColumnName($split[1]);
            $testField=pq_str_replace(array($externalClass.'_','[',']'),'',$critSqlValue);
            $isPgSql = Sql::isPgsql();
            
            //arithmetic expressions of the type ‘[field] +2’
            if (preg_match('/^([A-Za-z_][A-Za-z0-9_]*)\s*([+\-x])\s*(\d+(?:\.\d+)?)$/', $testField, $matches)){
              $fieldName = $matches[1];
              $operatorCompare = $matches[2];
              if ($operatorCompare =="x") $operatorCompare='*';
              $filterCompareValue = $matches[3];
              if (substr($crit['sql']['attribute'], -4) === "Date" || substr($crit['sql']['attribute'], -8) === "DateTime") {
                if ($isPgSql) $queryWhere .= $externalTableAlias . "." . $extField. " " . $crit['sql']['operator'] . " ". $externalTableAlias . "." . $fieldName . " ". $operatorCompare . " INTERVAL '" . $filterCompareValue . " day'";
                else $queryWhere .= $externalTableAlias . "." . $extField. " " . $crit['sql']['operator'] . " ". $externalTableAlias . "." . $fieldName . " ". $operatorCompare . " INTERVAL " . $filterCompareValue . " DAY";
              } else {
                $queryWhere .= $externalTableAlias . "." . $extField. " " . $crit['sql']['operator'] . " ". $externalTableAlias . "." . $fieldName . " ". $operatorCompare . " " . $filterCompareValue;
              }
            }
            // "[ClassName_field]"
            else if ($critSqlValue=='['.$externalClass.'_'.$testField.']') {
              $queryWhere.=$externalTableAlias.".".$extField.' '.$crit['sql']['operator']." $externalTableAlias.$testField";
            }else if ($critSqlValue=='['.$testField.']') {
              $queryWhere.=$externalTableAlias.".".$extField.' '.$crit['sql']['operator']." $tableName.$testField";
            }else if ($crit['sql']['operator']=='=month+' or $crit['sql']['operator']=='=year+'){
              $queryWhere.=$externalTableAlias.".".$extField.' '.$critSqlValue;
            }else{
              $queryWhere.=$externalTableAlias.".".$extField.' '.$crit['sql']['operator'].' '.$critSqlValue;
            }
          } else {
            $queryWhere.=($queryWhere=='')?'':' and ';
            if ($crit['sql']['operator']!=' exists ') {
              $queryWhere.="(".$tableName . "." . $crit['sql']['attribute'] . ' ';
            }
            
            $testField=pq_str_replace(array('[',']'),'',$critSqlValue);
            if ($crit['sql']['operator']=='=month+' or $crit['sql']['operator']=='=year+') {
              $queryWhere.=$critSqlValue;
            }else if ($critSqlValue=="[$testField]"){
              $queryWhere.=$crit['sql']['operator']." $tableName.$testField";
            }else {
              $queryWhere.=$crit['sql']['operator'] . ' ' . $critSqlValue;
            }
            
            if (pq_strlen($crit['sql']['attribute'])>=9
                and pq_substr($crit['sql']['attribute'],0,2)=='id'
                and ( pq_substr($crit['sql']['attribute'],-7)=='Version' and SqlElement::is_a(pq_substr($crit['sql']['attribute'],2), 'Version') )
                and $crit['sql']['operator']=='IN') {
                  $scope=pq_substr($crit['sql']['attribute'],2);
                  $vers=new OtherVersion();
                  $queryWhere.=" or exists (select 'x' from ".$vers->getDatabaseTableName()." VERS "
                      ." where VERS.refType=".Sql::str($typeKanbanC)." and VERS.refId=".$tableName.".id and scope=".Sql::str($scope)
                      ." and VERS.idVersion IN ".$critSqlValue
                      .")";
                }
                if ($crit['sql']['operator']=='NOT IN') {
                  $queryWhere.=" or ".$tableName . "." . $crit['sql']['attribute']. " IS NULL ";
                }
                if ($crit['sql']['operator']!=' exists ') {
                  $queryWhere.=")";
                }
          }
    }
  }
  foreach ($arrayFilter as $crit) {
    if ($crit['sql']['operator']=='SORT') {
      $doneSort=false;
      $split=pq_explode('_', $crit['sql']['attribute']);
      if (count($split)>1 ) {
        $externalClass=$split[0];
        $externalObj=new $externalClass();
        $externalTable = $externalObj->getDatabaseTableName();
        $idTab+=1;
        $externalTableAlias = 'T' . $idTab;
        $queryFrom .= ' left join ' . $externalTable . ' as ' . $externalTableAlias .
        ' on ( ' . $externalTableAlias . ".refType='" . get_class($obj) . "' and " .  $externalTableAlias . '.refId = ' . $table . '.id )';
        $queryOrderBy .= ($queryOrderBy=='')?'':', ';
        $queryOrderBy .= " " . $externalTableAlias . '.' . $split[1]
        . " " . $crit['sql']['value'];
        $doneSort=true;
      }
      if (pq_substr($crit['sql']['attribute'],0,2)=='id' and pq_strlen($crit['sql']['attribute'])>2 ) {
        $externalClass = pq_substr($crit['sql']['attribute'],2);
        $externalObj=new $externalClass();
        $externalTable = $externalObj->getDatabaseTableName();
        $sortColumn='id';
        if (property_exists($externalObj,'sortOrder')) {
          $sortColumn=$externalObj->getDatabaseColumnName('sortOrder');
        } else {
          $sortColumn=$externalObj->getDatabaseColumnName('name');
        }
        $idTab+=1;
        $externalTableAlias = 'T' . $idTab;
        $queryOrderBy .= ($queryOrderBy=='')?'':', ';
        $queryOrderBy .= " " . $externalTableAlias . '.' . $sortColumn
        . " " . pq_str_replace("'","",$crit['sql']['value']);
        $queryFrom .= ' left join ' . $externalTable . ' as ' . $externalTableAlias .
        ' on ' . $table . "." . $obj->getDatabaseColumnName('id' . $externalClass) .
        ' = ' . $externalTableAlias . '.' . $externalObj->getDatabaseColumnName('id');
        $doneSort=true;
      }
      if (! $doneSort) {
        $queryOrderBy .= ($queryOrderBy=='')?'':', ';
        $queryOrderBy .= " " . $table . "." . $obj->getDatabaseColumnName($crit['sql']['attribute'])
        . " " . $crit['sql']['value'];
      }
    }
  }
  $queryWhere.=($queryWhere)?' and ':'';
  //$queryWhere.= "$tableName.idProject in ".getVisibleProjectsList(false);
  $queryWhere.=getAccesRestrictionClause(get_class($obT),$tableName, true);
  if (property_exists($obT,'isPrivate')) {
    $queryWhere.= ($queryWhere=='')?'':' and ';
    $queryWhere.= SqlElement::getPrivacyClause($obT);
  }
  if(Parameter::getGlobalParameter('hideItemTypeRestrictionOnProject')=='YES'){
    $user=getSessionUser();
    $objectClass=get_class($obj);
    $showIdleProjects=(sessionValueExists('projectSelectorShowIdle') and getSessionValue('projectSelectorShowIdle')==1)?1:0;
    $showIdle=1;
    $lstGetClassList = Type::getClassList();
    $objType = $obj->getDatabaseColumnName($objectClass . 'Type');
    $lstGetClassList = array_flip($lstGetClassList);
    if(in_array($objType,$lstGetClassList)){
      $queryWhere.=($queryWhere)?' and ':'';
      $queryWhere.= $user->getItemTypeRestriction($obj,$objectClass,$user,$showIdle,$showIdleProjects);
    }
  }
  $newOrderBy="";
  if($orderBy!='' && $queryOrderBy!='')$queryOrderBy=','.$queryOrderBy;
  if($orderBy=="idstatus")$newOrderBy=$tableName3.'.sortOrder';
  if($orderBy=="idresponsible")$newOrderBy=$tableName4.'.fullName';
  if($orderBy=="idtargetproductversion")$newOrderBy=$tableName5.'.name';
  if($orderBy!= "idtargetproductversion" && $orderBy!= "idresponsible" && $orderBy!= "idstatus" && $orderBy!='')$newOrderBy=$tableName.'.'.$orderBy;
  if($orderBy=="idpriority"){
    if($typeKanbanC == 'Activity'){
      $plan = new PlanningElement();
      $tableName6=$plan->getDatabaseTableName();
      $newOrderBy=$tableName6.'.priority';
    }else{
      $newOrderBy=$tableName.'.idPriority';
    }
  }
  if($typeKanbanC == 'Activity'){
    $plan = new PlanningElement();
    $tableName6=$plan->getDatabaseTableName();
    if($orderBy=="validatedenddate")$newOrderBy=$tableName6.'.validatedEndDate';
  }

  //   if(!$isStatus){
  //     $query="SELECT $tableName.id as id,
  //            $tableName.name as name,
  //            $tableName.id".$typeKanbanC."Type as idtickettype,
  //            $tableName.idStatus as idstatus,
  //            $tableName.idProject as idproject,";
  //     if(property_exists($typeKanbanC, "idPriority")) {
  //     	$query.="$tableName.idPriority as idpriority, ";
  //     } else {
  //     	$query.=" 0 as idpriority, ";
  //     }
  //     $query.=" $tableName.".$obT->getDatabaseColumnName('idTargetProductVersion')." as idtargetproductversion, ";
  //     if(property_exists($typeKanbanC, "idActivity")){
  //       $query.="$tableName.idActivity as idactivity,";
  //     }else{
  //       $query.="0 as idactivity, ";
  //     }
  //     if(property_exists($obj, "WorkElement")){
  //       $query.="$tableName2.plannedWork as plannedwork,";
  //     }else if (property_exists($typeKanbanC, 'plannedWork')){
  //       $query .=" $tableName.plannedWork as plannedwork,";
  //     }else{
  //       $query .=" 0 as plannedwork, ";
  //     }
  //     $query.=" $tableName2.realWork as realwork,
  //               $tableName2.leftWork as leftwork,
  //               $tableName.description as description,
  //               $tableName.idResource as iduser,
  //               $tableName3.sortOrder,
  //               $tableName4.fullName as name4,
  //               $tableName5.name as name5";
  //     $query.=" FROM  $tableName2, $tableName3, $queryFrom";
  //     $query.=" left join $tableName4 on $tableName.idresource=$tableName4.id";
  //     $query.=" left join $tableName5 on $tableName.".$obT->getDatabaseColumnName('idTargetProductVersion')."=$tableName5.id";
  //     $query.=" WHERE $tableName3.id=$tableName.idStatus";
  //     $query.=" AND $tableName.".$obT->getDatabaseColumnName('id'.$type)." $listType";
  //     $query.=" AND $tableName2.refType='".$typeKanbanC."' AND $tableName2.refId=$tableName.id $queryWhere";
  //     $query.=" AND $tableName.idProject in ".getVisibleProjectsList(false).(Parameter::getUserParameter("kanbanShowIdle") ? '' : ' AND '.$tableName.'.idle=0');
  //     if ($queryOrderBy!='' || $orderBy!='') {
  //     	$query.=" order by $newOrderBy $queryOrderBy ";
  //     }
  //     $result=Sql::query($query);
  //   }else{
  /*$result=Sql::query("SELECT $tableName.id as id,
   $tableName.name as name,
   $tableName.id".$typeKanbanC."Type as idtickettype,
   $tableName.idStatus as idstatus,
   $tableName.idProject as idproject,
   ".(property_exists($typeKanbanC, "idPriority") ? "$tableName.idPriority as idpriority, " : "")."
   $tableName.".$obT->getDatabaseColumnName('idTargetProductVersion')." as idtargetproductversion,
   $tableName.idActivity as idactivity,
   ".( (isset($tableName2)) ? " $tableName2.plannedWork as plannedwork, " : ( (property_exists($typeKanbanC, 'plannedWork'))?" $tableName.plannedWork as plannedwork,":"0 as plannedwork,") )."
   ".(isset($tableName2) ? "   $tableName2.realWork as realwork, " : "")."
   $tableName.description as description,
   ".(isset($tableName2) ? "    $tableName2.leftWork as leftwork, " : "")."
   $tableName.idResource as iduser,
   $tableName3.sortOrder,
   $tableName4.fullName as name4,
   $tableName5.name as name5
   FROM  $tableName2, $tableName3, $queryFrom left join $tableName4 on $tableName.idresource=$tableName4.id left join $tableName5 on $tableName.".$obT->getDatabaseColumnName('idTargetProductVersion')."=$tableName5.id WHERE $tableName3.id=$tableName.idStatus AND $tableName.".$obT->getDatabaseColumnName('id'.$type)." $listType AND $tableName2.refType='".$typeKanbanC."' AND $tableName2.refId=$tableName.id $queryWhere AND $tableName.idProject in ".getVisibleProjectsList(false).(Parameter::getUserParameter("kanbanShowIdle") ? '' : ' AND '.$tableName.'.idle=0').( ($queryOrderBy!='' || $orderBy!='') ? " order by $newOrderBy ".$queryOrderBy : ''));*/
  $query="SELECT $tableName.id as id,
  $tableName.name as name,
  $tableName.id".$typeKanbanC."Type as idtickettype,
  $tableName.idStatus as idstatus,
  $tableName.idProject as idproject,";
  if(property_exists($typeKanbanC, "idUrgency"))$query.="$tableName.idUrgency as idurgency,";
  if(property_exists($typeKanbanC, "idPriority")) {
    $query.="$tableName.idPriority as idpriority, ";
  } else {
    $query.=" 0 as idpriority, ";
  }
  if(property_exists($typeKanbanC, "idCriticality")) {
    $query.="$tableName.idCriticality as idcriticality, ";
  } else {
    $query.=" 0 as idcriticality, ";
  }
  if ($hasVersion) $query.=" $tableName.".$obT->getDatabaseColumnName('idTargetProductVersion')." as idtargetproductversion,";
  else $query.=" null as idtargetproductversion,";
  if (property_exists($typeKanbanC, "idActivity")) {
    $query.=" $tableName.idActivity as idactivity,";
  }else{
    $query.=" null as idactivity, ";
  }
  if(isset($tableName2)){
    $query.=" $tableName2.plannedWork as plannedwork,";
  }else if(property_exists($typeKanbanC, 'plannedWork')){
    $query .=" $tableName.plannedWork as plannedwork, ";
  }else{
    $query .=" 0 as plannedwork, ";
  }
  if(isset($tableName2)){
    $query .=" $tableName2.realWork as realwork, ";
  }else{
    $query.= " 0 as realwork, ";
  }
  $obj = new $typeKanbanC();
  if ($typeKanbanC == 'Activity'){
    if(isset($tableName2)){
      $query.=" $tableName2.validatedEndDate as validatedenddate,";
      $query.=" $tableName2.validatedStartDate as validatedstartdate,";
      $query.=" $tableName2.plannedEndDate as plannedenddate,";
      $query.=" $tableName2.plannedStartDate as plannedstartdate,";
      $query.=" $tableName2.notPlannedWork as notplannedwork,";
      $query.=" $tableName2.assignedWork as assignedwork,";
      $query.=" $tableName2.validatedDuration as validatedduration,";
      $query.=" $tableName2.plannedDuration as plannedduration,";
      $query.=" $tableName2.idPlanningMode as idplanningmode,";
      $query.=" $tableName2.inheritedEndDate as inheritedenddate,";
      $query.=" $tableName2.surbooked as surbooked,";
    }
  }else if($typeKanbanC == 'Action' or $typeKanbanC == 'Requirement'){
    $query.=" $tableName.actualDueDate as plannedenddate,";
  }else if($typeKanbanC == 'Ticket'){
    $query.=" $tableName.actualDueDateTime as plannedenddate,";
  }
  $query .=" $tableName.description as description, ";
  if(isset($tableName2)){
    $query .=" $tableName2.leftWork as leftwork, ";
  } else {
    $query .=" 0 as leftwork, ";
  }
  $query .=" $tableName.idResource as iduser,
  $tableName3.sortOrder,
  $tableName4.fullName as name4";
  //     if(property_exists($typeKanbanC, "idPriority")){
  //       $query.=", $tableName7.value as priorityVal";
  //     }
  if ($hasVersion) $query .=", $tableName5.name as name5";
  $query.=" FROM ";
  if (isset($tableName2)) {
    $query.=" $tableName2,";
  }else {
    $query.="";
  }
  $query.=" $tableName3, $queryFrom";
  //     if(property_exists($typeKanbanC, "idPriority")){
  //       $query.=" LEFT JOIN $tableName7 ON $tableName7.id = $tableName.idPriority";
  //     }
  $query.=" left join $tableName4 on $tableName.idresource=$tableName4.id";
  if ($hasVersion) $query.=" left join $tableName5 on $tableName.".$obT->getDatabaseColumnName('idTargetProductVersion')."=$tableName5.id";
  $query.=" WHERE $tableName3.id=$tableName.idStatus";
  $query.=" AND $tableName.".$obT->getDatabaseColumnName('id'.$type)." $listType";
  if (isset($tableName2)) {
    $query.=" AND $tableName2.refType='".$typeKanbanC."' AND $tableName2.refId=$tableName.id $queryWhere";
  }else {
    $query.=" $queryWhere";
  }
  $query.=" AND ($tableName.idProject in ".getVisibleProjectsList(false).(($typeKanbanC=='Requirement' and getSessionValue('project')=='*')?" or $tableName.idProject is null":"").')'.(Parameter::getUserParameter("kanbanShowIdle") == 'on' ? '' : ' AND '.$tableName.'.idle=0');
  //     if(property_exists($typeKanbanC, "idPriority")){
  //       $query.=" AND ($tableName7.id=$tableName.idPriority or $tableName.idPriority is null) ";
  //     }
  if ($queryOrderBy!='' || $orderBy!='') {
    if (pq_strpos($queryOrderBy, '.wbs') !== false) {
      $queryOrderBy = pq_str_replace('.wbs', '.wbsSortable', $queryOrderBy);
    }
    if(pq_strpos($newOrderBy, "idPriority")!== false){
      $query.=" order by $newOrderBy $queryOrderBy DESC ";
    }else{
      $query.=" order by $newOrderBy $queryOrderBy  ";
    }
  }
  //     }else if(property_exists($typeKanbanC, "idPriority")){
  //       $query.=" ORDER BY CASE WHEN $tableName.idPriority IS NULL THEN 1 ELSE 0 END ASC, priorityVal DESC";
  //     }
  $result=Sql::query($query);
  $final=array();

  $isColorBlind=(Parameter::getUserParameter('colorBlindPlanning') == 'YES')?true:false;
  while ($line = Sql::fetchLine($result)) {
    if ($typeKanbanC == 'Activity'){
      $pColor='#50BB50';
      $pColorBlindColor = $pColor;
      if ($line['notplannedwork'] > 0) { // Some left work not planned
        $pColor = '#9933CC';
        $pColorBlindColor = '#BB5050';
      } else if (pq_trim($line['validatedenddate']) != "" and $line['validatedenddate'] < $line['plannedenddate']) { // Not respected constraints end date : red
        if ($typeKanbanC!='Milestone' and ( ! $line['assignedwork'] or $line['assignedwork']==0 ) and ( ! $line['leftwork'] or $line['leftwork']==0 ) and ( ! $line['realwork'] or $line['realwork']==0 )) {
          $pColor = '#BB9099';
          $pColorBlindColor = 'linear-gradient(45deg, #63226b 5%, #9a3ec9 5%, #9a3ec9 45%, #63226b 45%, #63226b 55%, #9a3ec9 55%, #9a3ec9 95%, #63226b 95%);';
        } else {
          $pColor = '#BB5050';
          $pColorBlindColor = 'linear-gradient(45deg, #63226b 5%, #9a3ec9 5%, #9a3ec9 45%, #63226b 45%, #63226b 55%, #9a3ec9 55%, #9a3ec9 95%, #63226b 95%);';
        }
      } else if ( ( ($line['idplanningmode']==8 or $line['idplanningmode']==14) and intval($line['validatedduration']) < intval($line['plannedduration']) )
          or ( ($line['idplanningmode']==25 or $line['idplanningmode']==26) and $line['plannedstartdate'] != $line['validatedstartdate'] )
          or ( ($line['idplanningmode']==19 or $line['idplanningmode']==21) and $line['plannedstartdate'] < $line['validatedstartdate'] )  ) {
            $pColor = '#BB5050';
            $pColorBlindColor = 'linear-gradient(45deg, #63226b 5%, #9a3ec9 5%, #9a3ec9 45%, #63226b 45%, #63226b 55%, #9a3ec9 55%, #9a3ec9 95%, #63226b 95%);';
          } else if ($typeKanbanC!='Milestone' and ( ! $line['assignedwork'] or $line['assignedwork']==0 ) and ( ! $line['leftwork'] or $line['leftwork']==0 ) and ( ! $line['realwork'] or $line['realwork']==0 ) ) { // No workassigned : greyed
            $pColor = '#AEC5AE';
          }
          if ($line['surbooked']==1) {
            $pColor='#f4bf42';
            $pColorBlindColor='#bfbfbf';
          }
          // Color for late from inheritedEndDate
          if (pq_trim($line['validatedenddate'])=="" and pq_trim($line['inheritedenddate'])!="" and $line['inheritedenddate'] < $line['plannedenddate']) {
            if ($line['assignedwork']>0) $pColor = '#DA70D6';
            else $pColor = '#DDA0DD';
          }
          $line['plannedcolor'] = ($isColorBlind)?$pColorBlindColor:$pColor;
    } else {
      $pColor='#F1F1F1';
      $pColorBlindColor = $pColor;
      $line['plannedcolor'] = ($isColorBlind)?$pColorBlindColor:$pColor;
    }
    $final[]=$line;
  }
  return $final;
}

function getItemsFromTypeIdKanban($from,$nextFrom,$type,$isStatus,$result,$jsonD){
  global $typeKanbanC,$arrayProject;
  $arrayProfile=array();
  $nb=0;
  $nListQuery=array();
  foreach($result as $line) {
    $nListQuery[$line['id']]=$line;
  }
  foreach ($nListQuery as $line) {
    $idType=$from;
    $add="";
    if(!isset($arrayProject[$line['idproject']])){
      $proJ=new Project($line['idproject'],true);
      $arrayProject[$line['idproject']]=$proJ->getColor();
    }
    if(!isset($arrayProfile[$line['idproject']])){
      $arrayProfile[$line['idproject']]=getSessionUser()->getProfile($line['idproject']);
    }
    $color=$arrayProject[$line['idproject']];
    if($isStatus){
      $idType=$line['idstatus'];
      $add='-'.$line['idtickettype'].'-'.$arrayProfile[$line['idproject']];
    }
    $seeWork=Parameter::getUserParameter("kanbanSeeWork".Parameter::getUserParameter("kanbanIdKanban"));
    $seeWork=($seeWork=='on' or $seeWork=='1')?true:false;
    if($seeWork && PlanningElement::getWorkVisibiliy(getSessionUser()->idProfile)=="ALL")$seeWork=true; else $seeWork=false;

    $idKanban = Parameter::getUserParameter("kanbanIdKanban");
    $handle='dojoDndHandle';

    if(securityGetAccessRightYesNo("menu".$typeKanbanC, "update", new $typeKanbanC($line['id'],true))!="YES")$handle="";
    $numCol = count($jsonD['column']);
    $mode = "display";
    kanbanDisplayTicket($line['id'],$type, $idKanban,$from, $line, $add, $mode);
    $nb++;
  }
}


function getIdsOfType($from,$nextFrom,$type){
  if($from==$nextFrom){
    return $from;
  }else{
    $listId=Array();
    $min=-100000000;
    $max=100000000;
    if($from!=0)$min=SqlList::getFieldFromId($type, $from, "sortOrder");
    if($nextFrom!=0)$max=SqlList::getFieldFromId($type, $nextFrom, "sortOrder");
    $sub=$min;
    if($min>$max){
      $min=$max;
      $max=$sub;
    }
    $obT=new $type();
    $tableName=$obT->getDatabaseTableName();
    //$result=Sql::query("SELECT t.id as typen FROM $tableName t WHERE t.sortOrder<=$max and t.sortOrder>=$min ");
    $fromBacklog = ($type == 'Status' and ($from == 'n' or $from == '1'))?' or t.isCopyStatus = 1':'';
    $result=Sql::query("SELECT t.id as typen FROM $tableName t WHERE (t.sortOrder<$max or t.id=$nextFrom) and (t.sortOrder>$min or t.id=$from) $fromBacklog");
    while ($line = Sql::fetchLine($result)) {
      $listId[]=$line["typen"];
    }
    $final="";
    $ite=0;
    if (count($listId)==0) return 0;
    foreach ($listId as $idType){
      $final.=$idType;
      if(count($listId)!=$ite+1) $final.=",";
      $ite++;
    }
    return $final;
  }
}
?>