private function _timecheck(&$times, $sameday)
 {
     foreach ($times as &$range) {
         //TODO interpet any sun-related times
         $s = $sameday ? MAX($range[0], $tstart) : $range[0];
         //TODO support roll-over to contiguous day(s) & time(s)
         if ($range[1] >= $s + $length) {
             unset($range);
             return $s;
         }
     }
     unset($range);
     return FALSE;
 }
Esempio n. 2
0
 function page($total = 0, $everpage = 10, $query = array())
 {
     $this->total = $this->totalItems = $total;
     $this->everpage = $everpage;
     $this->pages = max(1, abs(ceil($total / $everpage)));
     $this->currentPage = max((int) $_GET['pageID'], 1);
     //2
     $num = ceil(3 / 2);
     $this->max = MIN(MAX($this->currentPage + $num, 3), $this->pages);
     $this->min = MAX(MIN($this->currentPage - $num, $this->pages - 3), 1);
     $this->limit_1 = ($this->currentPage - 1) * $this->everpage;
     $this->limit_2 = $this->everpage;
     $this->limit_3 = $this->currentPage * $this->everpage;
     $this->num_1 = '';
     $this->num_3 = ' LIMIT ' . $this->limit_1 . ',' . $this->limit_2;
 }
Esempio n. 3
0
 function addLine($worksheet_name, $clo)
 {
     $cfg = $this->worksheet_cfg[$worksheet_name];
     $start_row = $this->start_row;
     $formats = (array) $this->formats;
     $worksheet = $this->worksheet;
     $hasRender = false;
     $r = 0;
     $cl = $clo;
     if (is_object($clo)) {
         $cl = (array) $clo;
         // lossless converstion..
     }
     if (isset($cfg['row_height'])) {
         $worksheet->setRow($start_row + $r, $cfg['row_height']);
     }
     $line_height = isset($cfg['line_height']) ? $cfg['line_height'] : 12;
     $height = 0;
     foreach ($cfg['cols'] as $c => $col_cfg) {
         if (isset($col_cfg['dataIndex']) && isset($cl[$col_cfg['dataIndex']])) {
             $v = $cl[$col_cfg['dataIndex']];
         } else {
             if (isset($col_cfg['fillBlank'])) {
                 $worksheet->write($start_row + $r, $c, '', $formats[$col_cfg['fillBlank']]);
             }
             continue;
         }
         if (!isset($cl[$col_cfg['dataIndex']])) {
             continue;
         }
         if (isset($col_cfg['txtrenderer'])) {
             if (is_a($col_cfg['txtrenderer'], 'Closure')) {
                 $v = $col_cfg['txtrenderer']($cl[$col_cfg['dataIndex']], $worksheet, $r + 1, $c, $clo);
             } else {
                 $v = call_user_func($col_cfg['txtrenderer'], $cl[$col_cfg['dataIndex']], $worksheet, $r + 1, $c, $clo);
             }
             if ($v === false) {
                 continue;
             }
             //  var_dump($v);
         }
         if (isset($col_cfg['renderer'])) {
             $hasRender = true;
             continue;
         }
         $v = @iconv('UTF-8', 'UTF-8//TRANSLIT//IGNORE', $v);
         $dataFormat = empty($col_cfg['dataFormat']) ? '' : $col_cfg['dataFormat'];
         $format = isset($col_cfg['format']) && isset($formats[$col_cfg['format']]) ? $formats[$col_cfg['format']] : false;
         //  print_R(array($start_row+$r, $c, $v, $format));exit;
         // handle 0 prefixes..
         if (is_numeric($v) && strlen($v) > 1 && substr($v, 0, 1) == '0' && substr($v, 1, 1) != '.' || $dataFormat == 'string') {
             $worksheet->writeString($start_row + $r, $c, $v, $format);
         } else {
             $worksheet->write($start_row + $r, $c, $v, $format);
         }
         if (isset($col_cfg['autoHeight'])) {
             $vv = explode("\n", $v);
             $height = MAX(count($vv) * $line_height, $height);
             $worksheet->setRow($start_row + $r, $height);
         }
     }
     $this->start_row++;
     return $hasRender;
 }
Esempio n. 4
0
<?php

include "./config/connectDatabase.php";
$cancleFavSql = "DELETE FROM jobs_user_fav \n\t\t\t\t\tWHERE activity_id = '{$_POST['activityID']}' \n\t\t\t\t\tAND activity_type = '{$_POST['activityType']}'\n\t\t\t\t\tAND user_id = '{$_POST['userID']}'\n\t\t\t\t\tAND type = '{$_POST['userType']}';";
$conn->query($cancleFavSql);
$getFavNumSql = "SELECT fav_num \n\t\t\t\t\tfrom jobs_activity \n\t\t\t\t\tWHERE id = '{$_POST['activityID']}';";
$favNumResult = $conn->query($getFavNumSql);
$favNum = $favNumResult->fetch_row();
$newFavNum = MAX($favNum[0] - 1, 0);
$favNumDecreaseSql = "UPDATE jobs_activity \n                            SET fav_num = " . $newFavNum . " WHERE id = '{$_POST['activityID']}';";
$conn->query($favNumDecreaseSql);
mysql_errno();
$conn->close();
Esempio n. 5
0
function WriteFlowingBlock( $s)
{
	$currentx = $this->x; 
	$is_table = $this->flowingBlockAttr[ 'is_table' ];
	$is_list = $this->flowingBlockAttr[ 'is_list' ];
	// width of all the content so far in points
	$contentWidth =& $this->flowingBlockAttr[ 'contentWidth' ];
	// cell width in points
	$maxWidth =& $this->flowingBlockAttr[ 'width' ];
	$lineCount =& $this->flowingBlockAttr[ 'lineCount' ];
	// line height in user units
	$lineHeight =& $this->flowingBlockAttr[ 'height' ];
	$align =& $this->flowingBlockAttr[ 'align' ];
	$content =& $this->flowingBlockAttr[ 'content' ];
	$contentB =& $this->flowingBlockAttr[ 'contentB' ];
	$font =& $this->flowingBlockAttr[ 'font' ];
	$valign =& $this->flowingBlockAttr[ 'valign' ];
	$blockstate = $this->flowingBlockAttr[ 'blockstate' ];

	$newblock = $this->flowingBlockAttr[ 'newblock' ];
	$blockdir = $this->flowingBlockAttr['blockdir'];
	// *********** BLOCK BACKGROUND COLOR ***************** //
	if ($this->blk[$this->blklvl]['bgcolor'] && !$is_table) {
		$fill = 0;
	}
	else {
		$this->SetFColor($this->ConvertColor(255));
		$fill = 0;
	}
	$font[] = $this->saveFont();
	$content[] = '';
	$contentB[] = '';
	$currContent =& $content[ count( $content ) - 1 ];
	// where the line should be cutoff if it is to be justified
	$cutoffWidth = $contentWidth;

	$CJKoverflow = false;
	$hanger = '';	// mPDF 5.6.40

	// COLS
	$oldcolumn = $this->CurrCol;

	if ($this->ColActive && !$is_table) { $this->breakpoints[$this->CurrCol][] = $this->y; }	// *COLUMNS*

/*-- TABLES --*/
   if ($is_table) { 
	$ipaddingL = 0; 
	$ipaddingR = 0; 
	$paddingL = 0; 
	$paddingR = 0; 
	$cpaddingadjustL = 0;
	$cpaddingadjustR = 0;
 	// Added mPDF 3.0
	$fpaddingR = 0;
	$fpaddingL = 0;
  } 
   else { 
/*-- END TABLES --*/
		$ipaddingL = $this->blk[$this->blklvl]['padding_left']; 
		$ipaddingR = $this->blk[$this->blklvl]['padding_right']; 
		$paddingL = ($ipaddingL * _MPDFK); 
		$paddingR = ($ipaddingR * _MPDFK); 
		$this->cMarginL =  $this->blk[$this->blklvl]['border_left']['w'];
		$cpaddingadjustL = -$this->cMarginL;
		$this->cMarginR =  $this->blk[$this->blklvl]['border_right']['w'];
		$cpaddingadjustR = -$this->cMarginR;
		// Added mPDF 3.0 Float DIV
		$fpaddingR = 0;
		$fpaddingL = 0;
/*-- CSS-FLOAT --*/
		if (count($this->floatDivs)) {
			list($l_exists, $r_exists, $l_max, $r_max, $l_width, $r_width) = $this->GetFloatDivInfo($this->blklvl);
			if ($r_exists) { $fpaddingR = $r_width; }
			if ($l_exists) { $fpaddingL = $l_width; }
		}
/*-- END CSS-FLOAT --*/

		$usey = $this->y + 0.002;
		if (($newblock) && ($blockstate==1 || $blockstate==3) && ($lineCount == 0) ) { 
			$usey += $this->blk[$this->blklvl]['margin_top'] + $this->blk[$this->blklvl]['padding_top'] + $this->blk[$this->blklvl]['border_top']['w'];
		}
/*-- CSS-IMAGE-FLOAT --*/
		// If float exists at this level
		if (isset($this->floatmargins['R']) && $usey <= $this->floatmargins['R']['y1'] && $usey >= $this->floatmargins['R']['y0'] && !$this->floatmargins['R']['skipline']) { $fpaddingR += $this->floatmargins['R']['w']; }
		if (isset($this->floatmargins['L']) && $usey <= $this->floatmargins['L']['y1'] && $usey >= $this->floatmargins['L']['y0'] && !$this->floatmargins['L']['skipline']) { $fpaddingL += $this->floatmargins['L']['w']; }
/*-- END CSS-IMAGE-FLOAT --*/
   }	// *TABLES*

     //OBJECTS - IMAGES & FORM Elements (NB has already skipped line/page if required - in printbuffer)
      if (substr($s,0,3) == "\xbb\xa4\xac") { //identifier has been identified!
		$objattr = $this->_getObjAttr($s);
		$h_corr = 0; 
		if ($is_table) {	// *TABLES*
			$maximumW = ($maxWidth/_MPDFK) - ($this->cellPaddingL + $this->cMarginL + $this->cellPaddingR + $this->cMarginR); 	// *TABLES*
		}	// *TABLES*
		else {	// *TABLES*
			if (($newblock) && ($blockstate==1 || $blockstate==3) && ($lineCount == 0) && (!$is_table)) { $h_corr = $this->blk[$this->blklvl]['padding_top'] + $this->blk[$this->blklvl]['border_top']['w']; }
			$maximumW = ($maxWidth/_MPDFK) - ($this->blk[$this->blklvl]['padding_left'] + $this->blk[$this->blklvl]['border_left']['w'] + $this->blk[$this->blklvl]['padding_right'] + $this->blk[$this->blklvl]['border_right']['w'] + $fpaddingL + $fpaddingR ); 
		}	// *TABLES*
		$objattr = $this->inlineObject($objattr['type'],$this->lMargin + $fpaddingL + ($contentWidth/_MPDFK),($this->y + $h_corr), $objattr, $this->lMargin,($contentWidth/_MPDFK),$maximumW,$lineHeight,true,$is_table);

		// SET LINEHEIGHT for this line ================ RESET AT END
		$lineHeight = MAX($lineHeight,$objattr['OUTER-HEIGHT']);
		$this->objectbuffer[count($content)-1] = $objattr;
		// if (isset($objattr['vertical-align'])) { $valign = $objattr['vertical-align']; }
		// else { $valign = ''; }
		$contentWidth += ($objattr['OUTER-WIDTH'] * _MPDFK);
		return;
	}

	$lbw = $rbw = 0;	// Border widths
	if (!empty($this->spanborddet)) { 
		if (isset($this->spanborddet['L'])) $lbw = $this->spanborddet['L']['w'];
		if (isset($this->spanborddet['R'])) $rbw = $this->spanborddet['R']['w'];
	}

   if ($this->usingCoreFont) {
	$tmp = strlen( $s );
   }
   else {
	$tmp = mb_strlen( $s, $this->mb_enc );
   }

   // for every character in the string
   for ( $i = 0; $i < $tmp; $i++ )  {
	// extract the current character
	// get the width of the character in points
	if ($this->usingCoreFont) {
       	$c = $s[$i];
		// Soft Hyphens chr(173)
		$cw = ($this->GetCharWidthCore($c) * _MPDFK);
		if ($this->kerning && $this->useKerning && $i > 0) {
			if (isset($this->CurrentFont['kerninfo'][$s[($i-1)]][$c])) { 
				$cw += ($this->CurrentFont['kerninfo'][$s[($i-1)]][$c] * $this->FontSizePt / 1000 );
			}
		}
	}
	else {
	      $c = mb_substr($s,$i,1,$this->mb_enc );
		$cw = ($this->GetCharWidthNonCore($c, false) * _MPDFK);
		if ($this->kerning && $this->useKerning && $i > 0) {
	     		$lastc = mb_substr($s,($i-1),1,$this->mb_enc );
			$ulastc = $this->UTF8StringToArray($lastc, false);
			$uc = $this->UTF8StringToArray($c, false);
			if (isset($this->CurrentFont['kerninfo'][$ulastc[0]][$uc[0]])) { 
				$cw += ($this->CurrentFont['kerninfo'][$ulastc[0]][$uc[0]] * $this->FontSizePt / 1000 );
			}
		}
	}

	if ($i==0) {
		$cw += $lbw*_MPDFK;
		$contentB[(count($contentB)-1)] .= 'L';
	}
	if ($i==($tmp-1)) {
		$cw += $rbw*_MPDFK;
		$contentB[(count($contentB)-1)] .= 'R';
	}
	// mPDF 5.6.45
	if ($c==' ') { 
		$currContent .= $c;
		$cutoffWidth = $contentWidth;
		$contentWidth += $cw;
		continue;
	}

	// ADDED for Paragraph_indent
	$WidthCorrection = 0; 
	if (($newblock) && ($blockstate==1 || $blockstate==3) && isset($this->blk[$this->blklvl]['text_indent']) && ($lineCount == 0) && (!$is_table) && (!$is_list) && ($align != 'C')) { 
		$ti = $this->ConvertSize($this->blk[$this->blklvl]['text_indent'],$this->blk[$this->blklvl]['inner_width'],$this->FontSize,false); 
		$WidthCorrection = ($ti*_MPDFK); 
	} 

	// Added mPDF 3.0 Float DIV
	$fpaddingR = 0;
	$fpaddingL = 0;
/*-- CSS-FLOAT --*/
	if (count($this->floatDivs)) {
		list($l_exists, $r_exists, $l_max, $r_max, $l_width, $r_width) = $this->GetFloatDivInfo($this->blklvl);
		if ($r_exists) { $fpaddingR = $r_width; }
		if ($l_exists) { $fpaddingL = $l_width; }
	}
/*-- END CSS-FLOAT --*/

	$usey = $this->y + 0.002;
	if (($newblock) && ($blockstate==1 || $blockstate==3) && ($lineCount == 0) ) { 
		$usey += $this->blk[$this->blklvl]['margin_top'] + $this->blk[$this->blklvl]['padding_top'] + $this->blk[$this->blklvl]['border_top']['w'];
	}

/*-- CSS-IMAGE-FLOAT --*/
	// If float exists at this level
	if (isset($this->floatmargins['R']) && $usey <= $this->floatmargins['R']['y1'] && $usey >= $this->floatmargins['R']['y0'] && !$this->floatmargins['R']['skipline']) { $fpaddingR += $this->floatmargins['R']['w']; }
	if (isset($this->floatmargins['L']) && $usey <= $this->floatmargins['L']['y1'] && $usey >= $this->floatmargins['L']['y0'] && !$this->floatmargins['L']['skipline']) { $fpaddingL += $this->floatmargins['L']['w']; }
/*-- END CSS-IMAGE-FLOAT --*/



       // try adding another char
	if (( $contentWidth + $cw > $maxWidth - $WidthCorrection - (($this->cMarginL+$this->cMarginR)*_MPDFK) - ($paddingL+$paddingR +(($fpaddingL + $fpaddingR) * _MPDFK) ) +  0.001))  {// 0.001 is to correct for deviations converting mm=>pts
		// it won't fit, output what we already have
		$lineCount++;

		// contains any content that didn't make it into this print
		$savedContent = '';
		$savedContentB = '';
		$savedFont = array();
		$savedObj = array();
		// mPDF 5.6.20
		$savedPreContent = array();
		$savedPreContentB = array();
		$savedPreFont = array();

		// cut off and save any partial words at the end of the string
		$words = explode( ' ', $currContent ); 
		///////////////////
		// HYPHENATION
		$currWord = $words[count($words)-1] ;
		$success = false;

		// mPDF 5.6.21   Hard Hyphens -
		$hardsuccess = false;
		if ($this->textparam['hyphens'] != 2 && preg_match("/\-/",$currWord)) {	
			$rem = $maxWidth - $WidthCorrection - (($this->cMarginL+$this->cMarginR)*_MPDFK) - ($paddingL+$paddingR +(($fpaddingL + $fpaddingR) * _MPDFK) );
			list($hardsuccess,$pre,$post,$prelength) = $this->hardHyphenate($currWord, (($rem-$cutoffWidth)/_MPDFK -$this->GetCharWidth("-", false)) );
			if ($hardsuccess) { 
				$already = array_pop( $words );
				$forward = mb_substr($already,$prelength+1,mb_strlen($already, $this->mb_enc), $this->mb_enc);
				$words[] = $pre.'-';
				$words[] = $forward;
				$currContent = mb_substr($currContent,0,mb_strlen($currContent, $this->mb_enc)+1-mb_strlen($post, $this->mb_enc), $this->mb_enc) . '-';
			}
		}
		
/*-- HYPHENATION --*/
		// Soft Hyphens chr(173)
		else if ($this->textparam['hyphens'] != 2 && (!$this->usingCoreFont && preg_match("/\xc2\xad/",$currWord)) || ($this->usingCoreFont && preg_match("/".chr(173)."/",$currWord) && ($this->FontFamily!='csymbol' && $this->FontFamily!='czapfdingbats')) ) {	// mPDF 5.6.06
			$rem = $maxWidth - $WidthCorrection - (($this->cMarginL+$this->cMarginR)*_MPDFK) - ($paddingL+$paddingR +(($fpaddingL + $fpaddingR) * _MPDFK) );
			list($success,$pre,$post,$prelength) = $this->softHyphenate($currWord, (($rem-$cutoffWidth)/_MPDFK -$this->GetCharWidth(" ", false)) );
		}

		if (!$success && !$hardsuccess && $this->textparam['hyphens'] == 1 ) { 	// mPDF 5.6.06	// mPDF 5.6.21
			// Look ahead to get current word
			for($ac = $i; $ac<(mb_strlen($s)-1); $ac++) {
				$addc = mb_substr($s,$ac,1,$this->mb_enc );
				if ($addc == ' ') { break; }
				$currWord .= $addc;
			}
			$rem = $maxWidth - $WidthCorrection - (($this->cMarginL+$this->cMarginR)*_MPDFK) - ($paddingL+$paddingR +(($fpaddingL + $fpaddingR) * _MPDFK) );
			list($success,$pre,$post,$prelength) = $this->hyphenateWord($currWord, (($rem-$cutoffWidth)/_MPDFK -$this->GetCharWidth(" ", false)) );
		}
		if ($success) { 
			$already = array_pop( $words );
			$forward = mb_substr($already,$prelength,mb_strlen($already, $this->mb_enc), $this->mb_enc);
			$words[] = $pre.'-';
			$words[] = $forward;
			$currContent = mb_substr($currContent,0,mb_strlen($currContent, $this->mb_enc)+1-mb_strlen($post, $this->mb_enc), $this->mb_enc) . '-';
		}
/*-- END HYPHENATION --*/

		// mPDF 5.6.13 Decimal alignment (cancel if wraps to > 1 line)
		if ($is_table && substr($align,0,1)=='D' ) { $align=substr($align,2,1); }

/*-- CJK-FONTS --*/
		// mPDF 5.6.42
		if ($this->checkCJK) {
			$lastchar = mb_substr($words[(count($words)-1)],mb_strlen($words[(count($words)-1)], $this->mb_enc)-1, 1, $this->mb_enc);
		}
		// Next character is suitable to add as overhanging or squeezed punctuation
		if ($this->checkCJK && preg_match("/[".$this->CJKoverflow."]/u", $c) && $this->allowCJKorphans && !$CJKoverflow) {
			// add character onto this line
			$currContent .= $c;
			$cutoffWidth = $contentWidth;
			$contentWidth += $cw;
			$CJKoverflow = true;
			continue;
		}
		// Last character that fits is not allowed to end a line - move lastchar(s) to start of next line
		else if ($this->checkCJK && preg_match("/[".$this->CJKleading."]/u", $lastchar)) {
			//move lastchar(s) to next line
			$m0 = $lastchar;
			$m1 = $c;
			while(preg_match("/[".$this->CJKleading."]/u", $m0) && mb_strlen($words[(count($words)-1)], $this->mb_enc)>2) {
				// trim last letter off word[0]
				$words[(count($words)-1)] = mb_substr($words[(count($words)-1)],0,mb_strlen($words[(count($words)-1)], $this->mb_enc)-1, $this->mb_enc);
				// and add it to savedContent for next line
				$savedContent = $m0.$savedContent;
				$m1 = $lastchar;
				$lastchar = mb_substr($words[(count($words)-1)],mb_strlen($words[(count($words)-1)], $this->mb_enc)-1, 1, $this->mb_enc);
				$m0 = $lastchar;
			}
			$lastContent = '';
			for ( $w = 0; $w < count( $words ) ; $w++) { $lastContent .= $words[ $w ]." "; }
			$savedFont = $this->saveFont();
			// replace the current content with the cropped version
			$currContent = rtrim( $lastContent );
		}
		// Next character is not allowed to start a new line
		else if ($this->checkCJK && preg_match("/[".$this->CJKfollowing."]/u", $c)) {
			// try squeezing another character(s) onto this line = Oikomi
			if ($this->allowCJKorphans && !$CJKoverflow) {	// mPDF 5.6.40
			      $lookahead = mb_substr($s,$i+1,1,$this->mb_enc );
				//if lookahead is not another following char
				if (!$lookahead || ($lookahead && !preg_match("/[".$this->CJKfollowing."]/u", $lookahead))) {
					$currContent .= $c;
					$cutoffWidth = $contentWidth;
					$contentWidth += $cw;
					if ($this->allowCJKoverflow && preg_match("/[".$this->CJKoverflow."]/u", $c)) { $CJKoverflow = true; }
					continue;
				}
			}
			// or move lastchar(s) to next line to keep $c company = Oidashi
			$m0 = $lastchar;
			$m1 = $c;
			while(preg_match("/[".$this->CJKfollowing."]/u", $m1) && mb_strlen($words[(count($words)-1)], $this->mb_enc)>2) {
				// trim last letter off word[0]
				$words[(count($words)-1)] = mb_substr($words[(count($words)-1)],0,mb_strlen($words[(count($words)-1)], $this->mb_enc)-1, $this->mb_enc);
				// and add it to savedContent for next line
				$savedContent = $m0.$savedContent;
				$m1 = $lastchar;
				$lastchar = mb_substr($words[(count($words)-1)],mb_strlen($words[(count($words)-1)], $this->mb_enc)-1, 1, $this->mb_enc);
				$m0 = $lastchar;
			}
			$lastContent = '';
			for ( $w = 0; $w < count( $words ) ; $w++) { $lastContent .= $words[ $w ]." "; }
			$savedFont = $this->saveFont();
			// replace the current content with the cropped version
			$currContent = rtrim( $lastContent );
		}
		// mPDF 5.6.42
	  	else if ($this->checkCJK && preg_match("/([".$this->pregCJKchars."]+[0-9\x{ff10}-\x{ff19}]+$)/u", $words[0])) {
			$lookahead = mb_substr($s,$i,16,$this->mb_enc );
			//and if lookahead starts with a few numerals
			if ($lookahead && (preg_match("/^([0-9\x{ff10}-\x{ff19}]+[".$this->pregCJKchars."]+)/u", $lookahead) || preg_match("/^([0-9\x{ff10}-\x{ff19}]+$)/u", $lookahead)) ) {
				// or move lastchar(s) to next line to keep numerals together
				$m0 = $lastchar;
				while(preg_match("/[0-9\x{ff10}-\x{ff19}]/u", $m0) && mb_strlen($words[(count($words)-1)], $this->mb_enc)>2) {
					// trim last letter off word[0]
					$words[(count($words)-1)] = mb_substr($words[(count($words)-1)],0,mb_strlen($words[(count($words)-1)], $this->mb_enc)-1, $this->mb_enc);
					// and add it to savedContent for next line
					$savedContent = $m0.$savedContent;
					$lastchar = mb_substr($words[(count($words)-1)],mb_strlen($words[(count($words)-1)], $this->mb_enc)-1, 1, $this->mb_enc);
					$m0 = $lastchar;
				}
			}
			$lastContent = '';
			for ( $w = 0; $w < count( $words ) ; $w++) { $lastContent .= $words[ $w ]." "; }
			$savedFont = $this->saveFont();
			// replace the current content with the cropped version
			$currContent = rtrim( $lastContent );
		}
		else 
/*-- END CJK-FONTS --*/
		// if it looks like we didn't finish any words for this chunk
		if ( count( $words ) == 1 ) {
		  // TO correct for error when word too wide for page - but only when one long word from left to right margin
		  if (count($content) == 1 && $currContent != ' ') {
			$lastchar = mb_substr($words[0],mb_strlen($words[0], $this->mb_enc)-1, 1, $this->mb_enc);
			$lastContent = $words[0]; 
			$savedFont = $this->saveFont();
			// replace the current content with the cropped version
			$currContent = rtrim( $lastContent );
		  }
		  // mPDF 5.6.20
		  else if (	count($content)>1
				&& (!isset($this->objectbuffer[(count($content)-1)]) && !isset($this->objectbuffer[(count($content)-2)]))
				&& substr($content[count($content)-2],-1,1) != ' '
				&& substr($currContent,0,1) != ' '
			) {
			// Go back to find a space in a previous chunk of content
			$found = false;
			for ($ix=count($content)-1;$ix>=0;$ix--) {
				// mPDF 5.6.29
				if ($this->usingCoreFont && preg_match('/[ '.chr(173).']/',$content[$ix],$m)) { $match = $m[0]; $found = $ix; break; }
				else if (!$this->usingCoreFont) {
					if (preg_match('/[ ]/',$content[$ix])) { $match = ' '; $found = $ix; break; }
					else if (preg_match('/[\x{00AD}]/u',$content[$ix])) {
						// even though it is UTF-8 replace it temporarily with chr(173)
						$content[$ix] = preg_replace('/[\x{00AD}]/u',chr(173),$content[$ix]);
						$match = chr(173); $found = $ix; break; 
					}
				}
			}
			if ($found !== false) {
				$charpos = strrpos($content[$found],$match);	// mPDF 5.6.29
				for ($ix=count($content)-1;$ix>$found;$ix--) {
					// save and crop off any subsequent chunks
					$savedPreContent[] = array_pop($content);
					$savedPreContentB[] = array_pop($contentB);
					$savedPreFont[] = array_pop($font);
				}
				if (substr($content[count($content)-1],$charpos+1,strlen($content[count($content)-1])-1) != '') {
					$savedPreContent[] = substr($content[count($content)-1],$charpos+1,strlen($content[count($content)-1])-1);
					$savedPreContentB[] = preg_replace('/L/','',$contentB[count($content)-1]);	// ???
					$savedPreFont[] = $font[count($content)-1];
				}
				$savedContent = '';
				$savedContentB = '';
				$savedFont = array();

				$currContent =& $content[ count( $content ) - 1 ];
				$currContent = substr($currContent,0,$charpos);
				if ($match == chr(173)) { $currContent .= '-'; }	// mPDF 5.6.29
				if (strpos($contentB[(count($contentB)-1)],'R')!==false) {			// ???
					$contentB[count($content)-1] = preg_replace('/R/','',$contentB[count($content)-1]);	// ???
				}

				$currContent = rtrim( $currContent );
			}
			else {
				$savedContent = array_pop( $content );
				$savedContentB = array_pop($contentB);
				$savedFont = array_pop( $font );
				$currContent =& $content[ count( $content ) - 1 ];
				$currContent = rtrim( $currContent );
			}
		  }
		  else {
			// save and crop off the content currently on the stack
			$savedContent = array_pop( $content );
			$savedContentB = array_pop($contentB);	// mPDF 5.6.20
			$savedFont = array_pop( $font );
			// trim any trailing spaces off the last bit of content
			$currContent =& $content[ count( $content ) - 1 ];
			$currContent = rtrim( $currContent );
		  }
		}
		else {	// otherwise, we need to find which bit to cut off
		  $lastContent = '';
              for ( $w = 0; $w < count( $words ) - 1; $w++) { $lastContent .= $words[ $w ]." "; }
              $savedContent = $words[ count( $words ) - 1 ];
              $savedFont = $this->saveFont();
              // replace the current content with the cropped version
              $currContent = rtrim( $lastContent );
		}
		// CJK - strip CJK space at end of line
		// &#x3000; = \xe3\x80\x80 = CJK space
		if ($this->checkCJK) { $currContent = preg_replace("/\xe3\x80\x80$/",'',$currContent) ; }	// *CJK-FONTS*


		if (isset($this->objectbuffer[(count($content)-1)]) && $this->objectbuffer[(count($content)-1)]['type']=='dottab') {
			$savedObj = array_pop( $this->objectbuffer );
			$contentWidth -= ($this->objectbuffer[(count($content)-1)]['OUTER-WIDTH'] * _MPDFK);
		}

		// Set Current lineheight (correction factor)
		$lhfixed = false; 
/*-- LISTS --*/
		if ($is_list) {
			if (preg_match('/([0-9.,]+)mm/',$this->list_lineheight[$this->listlvl][$this->listOcc],$am)) { 
				$lhfixed = true; 
				$def_fontsize = $this->InlineProperties['LISTITEM'][$this->listlvl][$this->listOcc][$this->listnum]['size'];
				$this->lineheight_correction = $am[1] / $def_fontsize ;
			}
			else { 
				$this->lineheight_correction = $this->list_lineheight[$this->listlvl][$this->listOcc]; 
			}
		}
		else
/*-- END LISTS --*/
/*-- TABLES --*/
		if ($is_table) {
			if (preg_match('/([0-9.,]+)mm/',$this->table_lineheight,$am)) { 
				$lhfixed = true; 
				$def_fontsize = $this->FontSize; 				// needs to be default font-size for block ****
				$this->lineheight_correction = $lineHeight / $def_fontsize ; 
			}
			else { 
				$this->lineheight_correction = $this->table_lineheight; 
			}
		}
		else
/*-- END TABLES --*/
		if (isset($this->blk[$this->blklvl]['line_height']) && $this->blk[$this->blklvl]['line_height']) {
			if (preg_match('/([0-9.,]+)mm/',$this->blk[$this->blklvl]['line_height'],$am)) { 
				$lhfixed = true; 
				$def_fontsize = $this->blk[$this->blklvl]['InlineProperties']['size']; 	// needs to be default font-size for block ****
				$this->lineheight_correction = $am[1] / $def_fontsize ;
			}
			else { 
				$this->lineheight_correction = $this->blk[$this->blklvl]['line_height']; 
			}
		} 
		else {
			$this->lineheight_correction = $this->normalLineheight; 
		}
		// update $contentWidth and $cutoffWidth since they changed with cropping
		// Also correct lineheight to maximum fontsize (not for tables)
		$contentWidth = 0;
		//  correct lineheight to maximum fontsize
		if ($lhfixed) { $maxlineHeight = $this->lineheight; }
		else { $maxlineHeight = 0; }
		$this->forceExactLineheight = true;
		$maxfontsize = 0;
		// While we're at it, check for cursive text
		$checkCursive=false;
		if ($this->biDirectional) {  $checkCursive=true; }	// *RTL*
		foreach ( $content as $k => $chunk )
		{
              $this->restoreFont( $font[ $k ]);
		  if (!isset($this->objectbuffer[$k])) { 
			// mPDF 5.6.40
			if ($this->checkCJK && $k == count($content)-1 && $CJKoverflow && $align=='J' && $this->allowCJKoverflow && $this->CJKforceend) {
			  // force-end overhang
				$hanger = mb_substr($chunk,mb_strlen($chunk,$this->mb_enc)-1,1,$this->mb_enc );
				$content[$k] = $chunk = mb_substr($chunk,0,mb_strlen($chunk,$this->mb_enc)-1,$this->mb_enc );
			}
			if (!$this->usingCoreFont) {
			      $content[$k] = $chunk = str_replace("\xc2\xad",'',$chunk ); 
				if (isset($this->CurrentFont['indic']) && $this->CurrentFont['indic']) {  $checkCursive=true; }	// *INDIC*
			}
			// Soft Hyphens chr(173)
			else if ($this->FontFamily!='csymbol' && $this->FontFamily!='czapfdingbats') {
			      $content[$k] = $chunk = str_replace(chr(173),'',$chunk );
			}
			$contentWidth += $this->GetStringWidth( $chunk ) * _MPDFK; 
			if (!empty($this->spanborddet)) { 
				if (strpos($contentB[$k],'L')!==false) $contentWidth += $this->spanborddet['L']['w'] * _MPDFK; 
				if (strpos($contentB[$k],'R')!==false) $contentWidth += $this->spanborddet['R']['w'] * _MPDFK; 
			}
			if (!$lhfixed) { $maxlineHeight = max($maxlineHeight,$this->FontSize * $this->lineheight_correction ); }
			if ($lhfixed && ($this->FontSize > $def_fontsize || ($this->FontSize > ($lineHeight * $this->lineheight_correction) && $is_list))) { 
				$this->forceExactLineheight = false; 
			}
			$maxfontsize = max($maxfontsize,$this->FontSize); 
		  }
		}

		$lastfontreqstyle = $font[count($font)-1]['ReqFontStyle'];
		$lastfontstyle = $font[count($font)-1]['style'];
		if ($blockdir == 'ltr' && strpos($lastfontreqstyle,"I") !== false && strpos($lastfontstyle,"I") === false) {	// Artificial italic
			$lastitalic = $this->FontSize*0.15*_MPDFK;
		}
		else { $lastitalic = 0; }


/*-- LISTS --*/
		if ($is_list && is_array($this->bulletarray) && $this->bulletarray) {
	  		$actfs = $this->bulletarray['fontsize'];
			if (!$lhfixed) { $maxlineHeight = max($maxlineHeight,$actfs * $this->lineheight_correction );  }
			if ($lhfixed && $actfs > $def_fontsize) { $this->forceExactLineheight = false; }
			$maxfontsize = max($maxfontsize,$actfs);
		}
/*-- END LISTS --*/

		// when every text item checked i.e. $maxfontsize is set properly

		$af = 0; 	// Above font
		$bf = 0; 	// Below font
		$mta = 0;	// Maximum top-aligned 
		$mba = 0;	// Maximum bottom-aligned 

		foreach ( $content as $k => $chunk ) {
		  if (isset($this->objectbuffer[$k]) && $this->objectbuffer[$k]) { 
			$contentWidth += $this->objectbuffer[$k]['OUTER-WIDTH'] * _MPDFK; 
			$oh = $this->objectbuffer[$k]['OUTER-HEIGHT'];
			$va = $this->objectbuffer[$k]['vertical-align']; // = $objattr['vertical-align'] = set as M,T,B,S
			if ($lhfixed && $oh > $def_fontsize) { $this->forceExactLineheight = false; }

			if ($va == 'BS') {	//  (BASELINE default)
				$af = max($af, ($oh - ($maxfontsize * (0.5 + $this->baselineC))));
			}
			else if ($va == 'M') { 
				$af = max($af, ($oh - $maxfontsize)/2);
				$bf = max($bf, ($oh - $maxfontsize)/2);
			}
			else if ($va == 'TT') { 
				$bf = max($bf, ($oh - $maxfontsize));
			}
			else if ($va == 'TB') { 
				$af = max($af, ($oh - $maxfontsize));
			}
			else if ($va == 'T') { 
				$mta = max($mta, $oh);
			}
			else if ($va == 'B') { 
				$mba = max($mba, $oh);
			}
		  }
		}
		if ((!$lhfixed || !$this->forceExactLineheight) && ($af > (($maxlineHeight - $maxfontsize)/2) || $bf > (($maxlineHeight - $maxfontsize)/2))) {
			$maxlineHeight = $maxfontsize + $af + $bf;
		}
		else if (!$lhfixed) { $af = $bf = ($maxlineHeight - $maxfontsize)/2; }

		if ($mta > $maxlineHeight) { 
			$bf += ($mta - $maxlineHeight);
			$maxlineHeight = $mta;
		}
		if ($mba > $maxlineHeight) { 
			$af += ($mba - $maxlineHeight);
			$maxlineHeight = $mba;
		}


		$lineHeight = $maxlineHeight; 
		$cutoffWidth = $contentWidth;
		// If NOT images, and maxfontsize NOT > lineHeight - this value determines text baseline positioning
		if ($lhfixed && $af==0 && $bf==0 && $maxfontsize<=($def_fontsize * $this->lineheight_correction * 0.8 )) { 
			$this->linemaxfontsize = $def_fontsize; 
		}
		else { $this->linemaxfontsize = $maxfontsize; }


		$inclCursive=false;
		foreach ( $content as $k => $chunk ) {
			if (!isset($this->objectbuffer[$k]) || (isset($this->objectbuffer[$k]) && !$this->objectbuffer[$k])) {
				if ($this->usingCoreFont) {
				      $content[$k] = str_replace(chr(160),chr(32),$chunk );
				}
				else {
				      $content[$k] = str_replace(chr(194).chr(160),chr(32),$chunk ); 
					if ($checkCursive) {
						if (preg_match("/([".$this->pregRTLchars."])/u", $chunk)) { $inclCursive = true; }	// *RTL*
						if (preg_match("/([".$this->pregHIchars.$this->pregBNchars.$this->pregPAchars."])/u", $chunk)) { $inclCursive = true; }	// *INDIC*
					}
				}
			}
		}

		// JUSTIFICATION J
		$jcharspacing = 0;
		$jws = 0;
		$nb_carac = 0;
		$nb_spaces = 0;
		// if it's justified, we need to find the char/word spacing (or if orphans have allowed length of line to go over the maxwidth)
		if ( ($align == 'J' && !$CJKoverflow) || (($cutoffWidth + $lastitalic > $maxWidth - $WidthCorrection - (($this->cMarginL+$this->cMarginR)*_MPDFK) - ($paddingL+$paddingR +(($fpaddingL + $fpaddingR) * _MPDFK) ) +  0.001) && (!$CJKoverflow || ($CJKoverflow && !$this->allowCJKoverflow))) || $CJKoverflow && $align=='J' && $this->allowCJKoverflow && $hanger && $this->CJKforceend) {   // 0.001 is to correct for deviations converting mm=>pts	// mPDF 5.6.40
		  // JUSTIFY J (Use character spacing)
 		  // WORD SPACING
			foreach ( $content as $k => $chunk ) {
				if (!isset($this->objectbuffer[$k]) || (isset($this->objectbuffer[$k]) && !$this->objectbuffer[$k])) {
					$nb_carac += mb_strlen( $chunk, $this->mb_enc ) ;  
					$nb_spaces += mb_substr_count( $chunk,' ', $this->mb_enc ) ;  
				}
			}
			list($jcharspacing,$jws) = $this->GetJspacing($nb_carac,$nb_spaces,($maxWidth-$lastitalic-$cutoffWidth-$WidthCorrection-(($this->cMarginL+$this->cMarginR)*_MPDFK)-($paddingL+$paddingR +(($fpaddingL + $fpaddingR) * _MPDFK) )),$inclCursive);
		}


		// WORD SPACING
		$empty = $maxWidth - $lastitalic-$WidthCorrection - $contentWidth - (($this->cMarginL+$this->cMarginR)* _MPDFK) - ($paddingL+$paddingR +(($fpaddingL + $fpaddingR) * _MPDFK) );

		$empty -= ($jcharspacing * $nb_carac);
		$empty -= ($jws * $nb_spaces);

		$empty /= _MPDFK;
		$b = ''; //do not use borders
		// Get PAGEBREAK TO TEST for height including the top border/padding
		$check_h = max($this->divheight,$lineHeight);
		if (($newblock) && ($blockstate==1 || $blockstate==3) && ($this->blklvl > 0) && ($lineCount == 1) && (!$is_table) && (!$is_list)) { 
			$check_h += ($this->blk[$this->blklvl]['padding_top'] + $this->blk[$this->blklvl]['margin_top'] + $this->blk[$this->blklvl]['border_top']['w']);
		}

		if ($this->ColActive && $check_h > ($this->PageBreakTrigger - $this->y0)) { 
			$this->SetCol($this->NbCol-1);
		}

		// PAGEBREAK
		// 'If' below used in order to fix "first-line of other page with justify on" bug 
		if(!$is_table && ($this->y+$check_h) > $this->PageBreakTrigger and !$this->InFooter and $this->AcceptPageBreak()) {
			$bak_x=$this->x;//Current X position

			// WORD SPACING
			$ws=$this->ws;//Word Spacing
			$charspacing=$this->charspacing;//Character Spacing
			$this->ResetSpacing();

		      $this->AddPage($this->CurOrientation);

		      $this->x = $bak_x;
			// Added to correct for OddEven Margins
			$currentx += $this->MarginCorrection;
			$this->x += $this->MarginCorrection;

			// WORD SPACING
			$this->SetSpacing($charspacing,$ws);
		}

		if ($this->keep_block_together && !$is_table && $this->kt_p00 < $this->page && ($this->y+$check_h) > $this->kt_y00) {
			$this->printdivbuffer();
			$this->keep_block_together = 0;
		}


/*-- COLUMNS --*/
		// COLS
		// COLUMN CHANGE
		if ($this->CurrCol != $oldcolumn) {
			$currentx += $this->ChangeColumn * ($this->ColWidth+$this->ColGap);
			$this->x += $this->ChangeColumn * ($this->ColWidth+$this->ColGap);
			$oldcolumn = $this->CurrCol;
		}

		if ($this->ColActive && !$is_table) { $this->breakpoints[$this->CurrCol][] = $this->y; }	// *COLUMNS*
/*-- END COLUMNS --*/

		// TOP MARGIN
		if (($newblock) && ($blockstate==1 || $blockstate==3) && ($this->blk[$this->blklvl]['margin_top']) && ($lineCount == 1) && (!$is_table) && (!$is_list)) { 
			$this->DivLn($this->blk[$this->blklvl]['margin_top'],$this->blklvl-1,true,$this->blk[$this->blklvl]['margin_collapse']); 
			if ($this->ColActive) { $this->breakpoints[$this->CurrCol][] = $this->y; }	// *COLUMNS*
		}


		// Update y0 for top of block (used to paint border)
		if (($newblock) && ($blockstate==1 || $blockstate==3) && ($lineCount == 1) && (!$is_table) && (!$is_list)) { 
			$this->blk[$this->blklvl]['y0'] = $this->y;
			$this->blk[$this->blklvl]['startpage'] = $this->page;
			if ($this->blk[$this->blklvl]['float']) { $this->blk[$this->blklvl]['float_start_y'] = $this->y; } // mPDF 5.6.63
		}

		// TOP PADDING and BORDER spacing/fill
		if (($newblock) && ($blockstate==1 || $blockstate==3) && (($this->blk[$this->blklvl]['padding_top']) || ($this->blk[$this->blklvl]['border_top'])) && ($lineCount == 1) && (!$is_table) && (!$is_list)) { 
			// $state = 0 normal; 1 top; 2 bottom; 3 top and bottom
			$this->DivLn($this->blk[$this->blklvl]['padding_top'] + $this->blk[$this->blklvl]['border_top']['w'],-3,true,false,1);
			if ($this->ColActive) { $this->breakpoints[$this->CurrCol][] = $this->y; }	// *COLUMNS*
		}

		$arraysize = count($content);

		$margins = ($this->cMarginL+$this->cMarginR) + ($ipaddingL+$ipaddingR + $fpaddingR + $fpaddingR );
 
		// PAINT BACKGROUND FOR THIS LINE
		if (!$is_table) { $this->DivLn($lineHeight,$this->blklvl,false); }	// false -> don't advance y

		$this->x = $currentx + $this->cMarginL + $ipaddingL + $fpaddingL ;
		if ($align == 'R') { $this->x += $empty; }
		else if ($align == 'C') { $this->x += ($empty / 2); }

		// Paragraph INDENT
		if (isset($this->blk[$this->blklvl]['text_indent']) && ($newblock) && ($blockstate==1 || $blockstate==3) && ($lineCount == 1) && (!$is_table) && ($blockdir !='rtl') && ($align !='C')) { 
			$ti = $this->ConvertSize($this->blk[$this->blklvl]['text_indent'],$this->blk[$this->blklvl]['inner_width'],$this->FontSize,false); 
			$this->x += $ti; 
		}

		// DIRECTIONALITY RTL
		$all_rtl = false;
		$contains_rtl = false;
/*-- RTL --*/
   		if ($blockdir == 'rtl' || $this->biDirectional)  {
			$all_rtl = true;
			foreach ( $content as $k => $chunk ) {
				$reversed = $this->magic_reverse_dir($chunk, false, $blockdir);

				if ($reversed > 0) { $contains_rtl = true; }
				if ($reversed < 2) { $all_rtl = false; }
				$content[$k] = $chunk;
			}
			if (($blockdir =='rtl' && $contains_rtl) || $all_rtl) { 
				$content = array_reverse($content,false); 
				$contentB = array_reverse($contentB,false);
			}
		}
/*-- END RTL --*/

		foreach ( $content as $k => $chunk ) {

			// FOR IMAGES - UPDATE POSITION
			if (($blockdir =='rtl' && $contains_rtl) || $all_rtl) { $dirk = $arraysize-1 - $k ; } else { $dirk = $k; }

			$va = 'M';	// default for text
			if (isset($this->objectbuffer[$dirk]) && $this->objectbuffer[$dirk]) {
			  $xadj = $this->x - $this->objectbuffer[$dirk]['OUTER-X'] ; 
			  $this->objectbuffer[$dirk]['OUTER-X'] += $xadj;
			  $this->objectbuffer[$dirk]['BORDER-X'] += $xadj;
			  $this->objectbuffer[$dirk]['INNER-X'] += $xadj;
			  $va = $this->objectbuffer[$dirk]['vertical-align'];
			  $yadj = $this->y - $this->objectbuffer[$dirk]['OUTER-Y'];
			  if ($va == 'BS') { 
				$yadj += $af + ($this->linemaxfontsize * (0.5 + $this->baselineC)) - $this->objectbuffer[$dirk]['OUTER-HEIGHT'];
			  }
			  else if ($va == 'M' || $va == '') { 
				$yadj += $af + ($this->linemaxfontsize /2) - ($this->objectbuffer[$dirk]['OUTER-HEIGHT']/2);
			  }
			  else if ($va == 'TB') { 
				$yadj += $af + $this->linemaxfontsize - $this->objectbuffer[$dirk]['OUTER-HEIGHT'];
			  }
			  else if ($va == 'TT') { 
				$yadj += $af;
			  }
			  else if ($va == 'B') { 
				$yadj += $af + $this->linemaxfontsize + $bf - $this->objectbuffer[$dirk]['OUTER-HEIGHT'];
			  }
			  else if ($va == 'T') { 
				$yadj += 0;
			  }
			  $this->objectbuffer[$dirk]['OUTER-Y'] += $yadj;
			  $this->objectbuffer[$dirk]['BORDER-Y'] += $yadj;
			  $this->objectbuffer[$dirk]['INNER-Y'] += $yadj;
			}

			// DIRECTIONALITY RTL
			if ((($blockdir == 'rtl') && ($contains_rtl )) || ($all_rtl )) { $this->restoreFont($font[$arraysize-1 - $k]); }
			else { $this->restoreFont( $font[ $k ] ); }

			$this->SetSpacing(($this->fixedlSpacing*_MPDFK)+$jcharspacing,($this->fixedlSpacing+$this->minwSpacing)*_MPDFK+$jws);
			// Now unset these values so they don't influence GetStringwidth below or in fn. Cell
			$this->fixedlSpacing = false;
			$this->minwSpacing = 0;

			// mPDF 5.6.26
			$save_vis = $this->visibility;
			if (isset($this->textparam['visibility']) && $this->textparam['visibility'] && $this->textparam['visibility'] != $this->visibility) {
				$this->SetVisibility($this->textparam['visibility']);
			}
	 		// *********** SPAN BACKGROUND COLOR ***************** //
			if ($this->spanbgcolor) { 
				$cor = $this->spanbgcolorarray;
				$this->SetFColor($cor);
				$save_fill = $fill; $spanfill = 1; $fill = 1;
			}
			if (!empty($this->spanborddet)) { 
				if (strpos($contentB[$k],'L')!==false) $this->x += $this->spanborddet['L']['w'];
				if (strpos($contentB[$k],'L')===false) $this->spanborddet['L']['s'] = $this->spanborddet['L']['w'] = 0; 
				if (strpos($contentB[$k],'R')===false) $this->spanborddet['R']['s'] = $this->spanborddet['R']['w'] = 0; 
			}

			// WORD SPACING
		      $stringWidth = $this->GetStringWidth($chunk );
			$stringWidth += ( $this->charspacing * mb_strlen($chunk,$this->mb_enc ) / _MPDFK );
			$stringWidth += ( $this->ws * mb_substr_count($chunk,' ',$this->mb_enc ) / _MPDFK );
			if (isset($this->objectbuffer[$dirk])) { $stringWidth = $this->objectbuffer[$dirk]['OUTER-WIDTH'];  }

			if ($stringWidth==0) { $stringWidth = 0.000001; }
			if ($k == $arraysize-1) {
				$stringWidth -= ( $this->charspacing / _MPDFK ); 
				// mPDF 5.6.40
				if ($this->checkCJK && $CJKoverflow && $align=='J' && $this->allowCJKoverflow && $hanger && $this->CJKforceend) {
				  // force-end overhang
					$this->Cell( $stringWidth, $lineHeight, $chunk, '', 0, '', $fill, $this->HREF, $currentx,0,0,'M', $fill, $af, $bf, true ); 
					$this->Cell( $this->GetStringWidth($hanger), $lineHeight, $hanger, '', 1, '', $fill, $this->HREF, $currentx,0,0,'M', $fill, $af, $bf, true );
				}
				else {
					$this->Cell( $stringWidth, $lineHeight, $chunk, '', 1, '', $fill, $this->HREF, $currentx,0,0,'M', $fill, $af, $bf, true ); //mono-style line or last part (skips line)
				}

			}
			else $this->Cell( $stringWidth, $lineHeight, $chunk, '', 0, '', $fill, $this->HREF, 0, 0,0,'M', $fill, $af, $bf, true );//first or middle part	

			if (!empty($this->spanborddet)) { 
				if (strpos($contentB[$k],'R')!==false && $k != $arraysize-1)  $this->x += $this->spanborddet['R']['w'];
			}
	 		// *********** SPAN BACKGROUND COLOR OFF - RESET BLOCK BGCOLOR ***************** //
			if (isset($spanfill) && $spanfill) { 
				$fill = $save_fill; $spanfill = 0; 
				if ($fill) { $this->SetFColor($bcor); }
			}
			// mPDF 5.6.26
			if (isset($this->textparam['visibility']) && $this->textparam['visibility'] && $this->visibility != $save_vis) {
				$this->SetVisibility($save_vis);
			}

		}
		if (!$is_table) { 
			$this->maxPosR = max($this->maxPosR , ($this->w - $this->rMargin - $this->blk[$this->blklvl]['outer_right_margin'])); 
			$this->maxPosL = min($this->maxPosL , ($this->lMargin + $this->blk[$this->blklvl]['outer_left_margin'])); 
		}

		// move on to the next line, reset variables, tack on saved content and current char

		$this->printobjectbuffer($is_table, $blockdir);
		$this->objectbuffer = array();

/*-- LISTS --*/
		// LIST BULLETS/NUMBERS
		if ($is_list && is_array($this->bulletarray) && ($lineCount == 1) ) {
		  
		  $this->ResetSpacing();

		  $bull = $this->bulletarray;
	  	  if (isset($bull['level']) && isset($bull['occur']) && isset($this->InlineProperties['LIST'][$bull['level']][$bull['occur']])) { 
			$this->restoreInlineProperties($this->InlineProperties['LIST'][$bull['level']][$bull['occur']]); 
		  }
		  if (isset($bull['level']) && isset($bull['occur']) && isset($bull['num']) && isset($this->InlineProperties['LISTITEM'][$bull['level']][$bull['occur']][$bull['num']]) && $this->InlineProperties['LISTITEM'][$bull['level']][$bull['occur']][$bull['num']]) { $this->restoreInlineProperties($this->InlineProperties['LISTITEM'][$bull['level']][$bull['occur']][$bull['num']]); }
	  	  if (isset($bull['font']) && $bull['font'] == 'czapfdingbats') {
			$this->bullet = true;
			$this->SetFont('czapfdingbats','',$this->FontSizePt/2.5);
		  }
		  else { $this->SetFont($this->FontFamily,$this->FontStyle,$this->FontSizePt,true,true); }	// force output
	        //Output bullet
	  	  $this->x = $currentx;
	 	  if (isset($bull['x'])) { $this->x += $bull['x']; }
		  $this->y -= $lineHeight;
		  if (isset($bull['col']) && $bull['col']) { $this->SetTColor($bull['col']); }	// mPDF 5.6.67
		  if (isset($bull['txt'])) { $this->Cell($bull['w'], $lineHeight,$bull['txt'],'','',$bull['align'],0,'',0,-$this->cMarginL, -$this->cMarginR ); }
	  	  if (isset($bull['font']) && $bull['font'] == 'czapfdingbats') {
			$this->bullet = false;
		  }
		  $this->x = $currentx;	// Reset
		  $this->y += $lineHeight;

		  if ($this->ColActive && !$is_table) { $this->breakpoints[$this->CurrCol][] = $this->y; }	// *COLUMNS*

		  $this->bulletarray = array();	// prevents repeat of bullet/number if <li>....<br />.....</li>
		}
/*-- END LISTS --*/


/*-- CSS-IMAGE-FLOAT --*/
		// Update values if set to skipline
		if ($this->floatmargins) { $this->_advanceFloatMargins(); }
/*-- END CSS-IMAGE-FLOAT --*/

		// Reset lineheight
		$lineHeight = $this->divheight;
		$valign = 'M';

		$font = array();
		$content = array();
		$contentB = array();
		$contentWidth = 0;
		if (!empty($savedObj)) {
			$this->objectbuffer[] = $savedObj;
			$font[] = $savedFont;
			$content[] = '';
			$contentB[] = '';
			$contentWidth += $savedObj['OUTER-WIDTH'] * _MPDFK;
		}
		// mPDF 5.6.20
		if (count($savedPreContent) > 0) {
			for($ix=count($savedPreContent)-1;$ix>=0;$ix--) {
				$font[] = $savedPreFont[$ix];
				$content[] = $savedPreContent[$ix];
				$contentB[] = $savedPreContentB[$ix];
				$this->restoreFont( $savedPreFont[$ix] );
				$lbw = $rbw = 0;	// Border widths
				if (!empty($this->spanborddet)) { 
					$lbw = $this->spanborddet['L']['w'];
					$rbw = $this->spanborddet['R']['w'];
				}
				if ($ix>0) {
					$contentWidth += $this->GetStringWidth( $savedPreContent[$ix] ) * _MPDFK;
					if (strpos($savedPreContentB[$ix],'L')!==false) $contentWidth += $lbw;
					if (strpos($savedPreContentB[$ix],'R')!==false) $contentWidth += $rbw;
				}
			}
			$savedPreContent = array();
			$savedPreContentB = array();
			$savedPreFont = array();
			$content[ (count($content)-1) ] .= $c;
		}
		else {
			$font[] = $savedFont;
			$content[] = $savedContent . $c;
			$contentB[] = $savedContentB ;
		}

		$currContent =& $content[ (count($content)-1) ];

		// CJK - strip CJK space at end of line
		// &#x3000; = \xe3\x80\x80 = CJK space
		if ($this->checkCJK && $currContent == "\xe3\x80\x80") { $currContent = '' ; }	// *CJK-FONTS*

		$this->restoreFont( $savedFont );
		$lbw = $rbw = 0;	// Border widths
		if (!empty($this->spanborddet)) { 
			$lbw = $this->spanborddet['L']['w'];
			$rbw = $this->spanborddet['R']['w'];
		}
		$contentWidth += $this->GetStringWidth( $currContent ) * _MPDFK;
		if (strpos($savedContentB,'L')!==false) $contentWidth += $lbw;
		$cutoffWidth = $contentWidth;
		$CJKoverflow = false;
		$hanger = '';	// mPDF 5.6.40
      }
      // another character will fit, so add it on
	else {
		$contentWidth += $cw;
		$currContent .= $c;
	}
    }
    unset($content);
    unset($contentB);
}
Esempio n. 6
0
 /**
  * _buildHeaderParam()
  *
  * Encodes the paramater of a header.
  *
  * @param $name         The name of the header-parameter
  * @param $value        The value of the paramter
  * @param $charset      The characterset of $value
  * @param $language     The language used in $value
  * @param $maxLength    The maximum length of a line. Defauls to 75
  *
  * @access private
  */
 function _buildHeaderParam($name, $value, $charset = NULL, $language = NULL, $maxLength = 75)
 {
     //If we find chars to encode, or if charset or language
     //is not any of the defaults, we need to encode the value.
     $shouldEncode = 0;
     $secondAsterisk = '';
     if (preg_match('#([\\x80-\\xFF]){1}#', $value)) {
         $shouldEncode = 1;
     } elseif ($charset && strtolower($charset) != 'us-ascii') {
         $shouldEncode = 1;
     } elseif ($language && ($language != 'en' && $language != 'en-us')) {
         $shouldEncode = 1;
     }
     if ($shouldEncode) {
         $search = array('%', ' ', "\t");
         $replace = array('%25', '%20', '%09');
         $encValue = str_replace($search, $replace, $value);
         $encValue = preg_replace('#([\\x80-\\xFF])#e', '"%" . strtoupper(dechex(ord("\\1")))', $encValue);
         $value = "{$charset}'{$language}'{$encValue}";
         $secondAsterisk = '*';
     }
     $header = " {$name}{$secondAsterisk}=\"{$value}\"; ";
     if (strlen($header) <= $maxLength) {
         return $header;
     }
     $preLength = strlen(" {$name}*0{$secondAsterisk}=\"");
     $sufLength = strlen("\";");
     $maxLength = MAX(16, $maxLength - $preLength - $sufLength - 2);
     $maxLengthReg = "|(.{0,{$maxLength}}[^\\%][^\\%])|";
     $headers = array();
     $headCount = 0;
     while ($value) {
         $matches = array();
         $found = preg_match($maxLengthReg, $value, $matches);
         if ($found) {
             $headers[] = " {$name}*{$headCount}{$secondAsterisk}=\"{$matches[0]}\"";
             $value = substr($value, strlen($matches[0]));
         } else {
             $headers[] = " {$name}*{$headCount}{$secondAsterisk}=\"{$value}\"";
             $value = "";
         }
         $headCount++;
     }
     $headers = implode(MAIL_MIMEPART_CRLF, $headers) . ';';
     return $headers;
 }
Esempio n. 7
0
    function EndStayEvent()
    {
        global $pricelist, $reslist;
        $LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']);
        $expeditionPoints = array();
        foreach ($reslist['fleet'] as $ID) {
            $expeditionPoints[$ID] = ($pricelist[$ID]['cost'][901] + $pricelist[$ID]['cost'][902]) / 1000000;
        }
        $expeditionPoints[202] = 12;
        $expeditionPoints[203] = 47;
        $expeditionPoints[204] = 12;
        $expeditionPoints[205] = 110;
        $expeditionPoints[206] = 47;
        $expeditionPoints[207] = 160;
        $fleetRaw = explode(";", $this->_fleet['fleet_array']);
        $fleetPoints = 0;
        $fleetCapacity = 0;
        $find_stardust = 5;
        $fleetArray = array();
        $stardustCount = $GLOBALS['DATABASE']->query("SELECT COUNT(planetarium) as planetarium FROM " . PLANETS . " WHERE id_owner = " . $this->_fleet['fleet_end_id'] . ";");
        $stardustCount = $GLOBALS['DATABASE']->fetch_array($stardustCount);
        $find_stardust = $find_stardust + $stardustCount['planetarium'];
        foreach ($fleetRaw as $Group) {
            if (empty($Group)) {
                continue;
            }
            $Class = explode(",", $Group);
            $fleetArray[$Class[0]] = $Class[1];
            $fleetCapacity += $Class[1] * $pricelist[$Class[0]]['capacity'];
            $fleetPoints += $Class[1] * $expeditionPoints[$Class[0]];
        }
        $fleetCapacity -= $this->_fleet['fleet_resource_metal'] + $this->_fleet['fleet_resource_crystal'] + $this->_fleet['fleet_resource_deuterium'] + $this->_fleet['fleet_resource_darkmatter'];
        /*if($GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['purchase_bonus_timer'] > TIMESTAMP || $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['cosmonaute'] == 1){
        		$GetEvent       = mt_rand(1,7);
        		}else{
        		$GetEvent       = mt_rand(1,6);
        		} */
        $GetEvent = mt_rand(1, 7);
        $combat_bonus = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM " . USERS . " WHERE id = " . $this->_fleet['fleet_owner'] . ";");
        $Message = $LNG['sys_expe_nothing_' . mt_rand(1, 8)];
        $chancetogetstar = mt_rand(0, 100);
        if ($chancetogetstar < $find_stardust) {
            $find_stardust = 1;
        } else {
            $find_stardust = 0;
        }
        switch ($GetEvent) {
            case 1:
                $WitchFound = mt_rand(1, 3);
                $FindSize = mt_rand(0, 100);
                $Factor = 0;
                if (10 < $FindSize) {
                    $Factor = mt_rand(100, 500) / $WitchFound * $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['resource_multiplier'];
                    $Factor = $Factor + $Factor / 100 * $combat_bonus['combat_reward_expe'];
                    $Message = $LNG['sys_expe_found_ress_1_' . mt_rand(1, 4)];
                } elseif (0 < $FindSize && 10 >= $FindSize) {
                    $Factor = mt_rand(520, 1000) / $WitchFound * $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['resource_multiplier'];
                    $Factor = $Factor + $Factor / 100 * $combat_bonus['combat_reward_expe'];
                    $Message = $LNG['sys_expe_found_ress_2_' . mt_rand(1, 3)];
                } elseif (0 == $FindSize) {
                    $Factor = mt_rand(1020, 2000) / $WitchFound * $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['resource_multiplier'];
                    $Factor = $Factor + $Factor / 100 * $combat_bonus['combat_reward_expe'];
                    $Message = $LNG['sys_expe_found_ress_3_' . mt_rand(1, 2)];
                }
                $StatFactor = $GLOBALS['DATABASE']->getFirstRow("SELECT MAX(total_points) as total FROM `" . STATPOINTS . "` WHERE `stat_type` = 1 AND `universe` = '" . $this->_fleet['fleet_universe'] . "';");
                $MaxPoints = $StatFactor['total'] < 5000000 ? 9000 : 12000;
                $Size = min($Factor * MAX(MIN($fleetPoints / 1000, $MaxPoints), 200), $fleetCapacity);
                switch ($WitchFound) {
                    case 1:
                        $this->UpdateFleet('fleet_resource_metal', $this->_fleet['fleet_resource_metal'] + $Size);
                        break;
                    case 2:
                        $this->UpdateFleet('fleet_resource_crystal', $this->_fleet['fleet_resource_crystal'] + $Size);
                        break;
                    case 3:
                        $this->UpdateFleet('fleet_resource_deuterium', $this->_fleet['fleet_resource_deuterium'] + $Size);
                        break;
                }
                $GLOBALS['DATABASE']->query("UPDATE " . USERS . " set `achievements_expedition` = `achievements_expedition` + '1', `expedition_count` = `expedition_count` + '1' where `id` = '" . $this->_fleet['fleet_owner'] . "';");
                $GLOBALS['DATABASE']->query("UPDATE " . USERS . " SET stardust = stardust + '" . $find_stardust . "' where `id` = " . $this->_fleet['fleet_owner'] . ";");
                $INFOR = $GLOBALS['DATABASE']->query("SELECT * FROM `uni1_users` WHERE id = " . $this->_fleet['fleet_owner'] . ";");
                if ($GLOBALS['DATABASE']->numRows($INFOR) > 0) {
                    while ($xkf = mysqli_fetch_assoc($INFOR)) {
                        $ACTUA = $xkf['expedition_count'];
                        $ACTUAL = 10 * $xkf['achievements_misc_expe'] + 10;
                        $expe_lvl = $xkf['achievements_misc_expe'] + 1;
                        $expe_reward_points = 50;
                        $expe_reward_am = 50;
                        $expe_reward_points = $expe_reward_points + $xkf['achievements_misc_expe'] * $expe_reward_points;
                        $expe_reward_am = $expe_reward_am + $xkf['achievements_misc_expe'] * $expe_reward_am;
                    }
                    if ($ACTUA == $ACTUAL) {
                        $GLOBALS['DATABASE']->query("UPDATE " . USERS . " SET achievements_misc_expe = achievements_misc_expe + '1', antimatter = antimatter + " . $expe_reward_am . " WHERE id = " . $this->_fleet['fleet_owner'] . ";");
                        $msg = '<img alt="" style="float:left; width:60px; margin-right:6px;" src="styles/images/achiev/ach_expedition.png">reached: <span class="achiev_mes_head">expeditions lvl. ' . $expe_lvl . '</span><br> received:<br> ' . $expe_reward_am . ' antimatter <br> ' . $expe_reward_points . ' achievement points';
                        SendSimpleMessage($this->_fleet['fleet_owner'], '', TIMESTAMP, 4, 'System', 'Achievements', $msg);
                    }
                }
                break;
            case 2:
                $FindSize = mt_rand(0, 100);
                $Size = 0;
                if (10 < $FindSize) {
                    $Size = mt_rand(1000, 3000);
                    $Size = $Size + $Size / 100 * $combat_bonus['combat_reward_expe'];
                    $Message = $LNG['sys_expe_found_dm_1_' . mt_rand(1, 5)];
                } elseif (0 < $FindSize && 10 >= $FindSize) {
                    $Size = mt_rand(3001, 6000);
                    $Size = $Size + $Size / 100 * $combat_bonus['combat_reward_expe'];
                    $Message = $LNG['sys_expe_found_dm_2_' . mt_rand(1, 3)];
                } elseif (0 == $FindSize) {
                    $Size = mt_rand(6001, 30000);
                    $Size = $Size + $Size / 100 * $combat_bonus['combat_reward_expe'];
                    $Message = $LNG['sys_expe_found_dm_3_' . mt_rand(1, 2)];
                }
                $GLOBALS['DATABASE']->query("UPDATE " . USERS . " set `achievements_expedition` = `achievements_expedition` + '1', `expedition_count` = `expedition_count` + '1' where `id` = '" . $this->_fleet['fleet_owner'] . "';");
                $GLOBALS['DATABASE']->query("UPDATE " . USERS . " SET stardust = stardust + '" . $find_stardust . "' where `id` = " . $this->_fleet['fleet_owner'] . ";");
                $this->UpdateFleet('fleet_resource_darkmatter', $this->_fleet['fleet_resource_darkmatter'] + $Size);
                break;
            case 3:
                $FindSize = mt_rand(0, 100);
                $Size = 0;
                $Message = "";
                if (10 < $FindSize) {
                    $Size = mt_rand(100, 500);
                    $Size = $Size + $Size / 100 * $combat_bonus['combat_reward_expe'];
                    $Message = $LNG['sys_expe_found_ships_1_' . mt_rand(1, 4)];
                } elseif (0 < $FindSize && 10 >= $FindSize) {
                    $Size = mt_rand(520, 1000);
                    $Size = $Size + $Size / 100 * $combat_bonus['combat_reward_expe'];
                    $Message = $LNG['sys_expe_found_ships_2_' . mt_rand(1, 2)];
                } elseif (0 == $FindSize) {
                    $Size = mt_rand(1020, 2000);
                    $Size = $Size + $Size / 100 * $combat_bonus['combat_reward_expe'];
                    $Message = $LNG['sys_expe_found_ships_3_' . mt_rand(1, 2)];
                }
                $StatFactor = $GLOBALS['DATABASE']->getFirstCell("SELECT MAX(total_points) FROM `" . STATPOINTS . "` WHERE `stat_type` = 1 AND `universe` = '" . $this->_fleet['fleet_universe'] . "';");
                $MaxPoints = $StatFactor < 5000000 ? 4500 : 6000;
                $FoundShips = max(round($Size * min($fleetPoints, $MaxPoints)), 10000);
                $FoundShipMess = "";
                $NewFleetArray = "";
                $Found = array();
                foreach ($reslist['fleet'] as $ID) {
                    if (!isset($fleetArray[$ID]) || $ID == 208 || $ID == 209 || $ID == 214) {
                        continue;
                    }
                    $MaxFound = floor($FoundShips / ($pricelist[$ID]['cost'][901] + $pricelist[$ID]['cost'][902]));
                    if ($MaxFound <= 0) {
                        continue;
                    }
                    $Count = mt_rand(0, $MaxFound);
                    if ($Count <= 0) {
                        continue;
                    }
                    $Found[$ID] = $Count;
                    $FoundShips -= $Count * ($pricelist[$ID]['cost'][901] + $pricelist[$ID]['cost'][902]);
                    $FoundShipMess .= '<br>' . $LNG['tech'][$ID] . ': ' . pretty_number($Count);
                    if ($FoundShips <= 0) {
                        break;
                    }
                }
                if (empty($Found)) {
                    $FoundShipMess .= '<br><br>' . $LNG['sys_expe_found_ships_nothing'];
                }
                foreach ($fleetArray as $ID => $Count) {
                    if (!empty($Found[$ID])) {
                        $Count += $Found[$ID];
                    }
                    $NewFleetArray .= $ID . "," . floattostring($Count) . ';';
                }
                $Message .= $FoundShipMess;
                $this->UpdateFleet('fleet_array', $NewFleetArray);
                $this->UpdateFleet('fleet_amount', array_sum($fleetArray));
                break;
            case 4:
                $Chance = mt_rand(1, 2);
                if ($Chance == 1) {
                    $Points = array(-6, -8, -10);
                    $Which = 1;
                    $Def = -3;
                    $Name = $LNG['sys_expe_attackname_1'];
                    $Add = 0;
                    $Rand = array(5, 3, 2);
                    $DefenderFleetArray = "204,5;206,3;207,2;";
                } else {
                    $Points = array(-7, -9, -11);
                    $Which = 2;
                    $Def = 3;
                    $Name = $LNG['sys_expe_attackname_2'];
                    $Add = 0.1;
                    $Rand = array(4, 3, 2);
                    $DefenderFleetArray = "205,5;215,3;213,2;";
                }
                $messageHTML = <<<HTML
<div class="raportMessage">
<table>
<tr>
<td colspan="2"><a href="CombatReport.php?raport=%s" target="_blank"><span %s>%s %s (%s)</span></a></td>
</tr>
<tr>
<td>%s</td><td><span %s>%s: %s</span>&nbsp;<span %s>%s: %s</span></td>
</tr>
<tr>
\t\t\t<td>%s</td><td><span>%s:&nbsp;<span style="color:#a47d7a;">%s</span>&nbsp;</span><span>%s:&nbsp;<span style="color:#5ca6aa;">%s</span>&nbsp;</span><span>%s:&nbsp;<span style="color:#339966;">%s</span></span></td>
\t\t</tr>
<tr>
\t\t\t<td>%s</td><td><span>%s:&nbsp;<span style="color:#a47d7a;">%s</font>&nbsp;</span><span>%s:&nbsp;<span style="color:#5ca6aa;">%s</span></span></td>
\t\t</tr>
</table>
</div>
HTML;
                //Minize HTML
                $messageHTML = str_replace(array("\n", "\t", "\r"), "", $messageHTML);
                $FindSize = mt_rand(0, 100);
                $maxAttack = 0;
                if (10 < $FindSize) {
                    $Message = $LNG['sys_expe_attack_' . $Which . '_1_' . $Rand[0]];
                    $maxAttack = 0.3 + $Add + mt_rand($Points[0], abs($Points[0])) * 0.01;
                } elseif (0 < $FindSize && 10 >= $FindSize) {
                    $Message = $LNG['sys_expe_attack_' . $Which . '_2_' . $Rand[1]];
                    $maxAttack = 0.3 + $Add + mt_rand($Points[1], abs($Points[1])) * 0.01;
                } elseif (0 == $FindSize) {
                    $Message = $LNG['sys_expe_attack_' . $Which . '_3_' . $Rand[2]];
                    $maxAttack = 0.3 + $Add + mt_rand($Points[2], abs($Points[2])) * 0.01;
                }
                foreach ($fleetArray as $ID => $count) {
                    $DefenderFleetArray .= $ID . "," . round($count * $maxAttack) . ";";
                }
                $AttackerTechno = $GLOBALS['DATABASE']->getFirstRow("SELECT * FROM " . USERS . " WHERE id = " . $this->_fleet['fleet_owner'] . ";");
                $DefenderTechno = array('id' => 0, 'username' => $Name, 'military_tech' => min($AttackerTechno['military_tech'] + $Def, 0), 'defence_tech' => min($AttackerTechno['defence_tech'] + $Def, 0), 'shield_tech' => min($AttackerTechno['shield_tech'] + $Def, 0), 'laser_tech' => 0, 'ion_tech' => 0, 'plasma_tech' => 0, 'gravity_tech' => 0, 'rpg_amiral' => 0, 'dm_defensive' => 0, 'dm_attack' => 0, 'experience_combat_level' => min($AttackerTechno['experience_combat_level'], 0), 'academy_1101' => 0, 'academy_1102' => 0, 'academy_1301' => 0, 'academy_1302' => 0, 'academy_1103' => 0, 'academy_1108' => 0, 'academy_1109' => 0, 'academy_1110' => 0, 'academy_1111' => 0, 'academy_1303' => 0, 'academy_1311' => 0);
                $fleetID = $this->_fleet['fleet_id'];
                $fleetAttack[$fleetID]['fleetDetail'] = $this->_fleet;
                $fleetAttack[$fleetID]['player'] = $AttackerTechno;
                $fleetAttack[$fleetID]['player']['factor'] = getFactors($fleetAttack[$this->_fleet['fleet_id']]['player'], 'attack', $this->_fleet['fleet_start_time']);
                $fleetAttack[$fleetID]['unit'] = array();
                $temp = explode(';', $this->_fleet['fleet_array']);
                foreach ($temp as $temp2) {
                    $temp2 = explode(',', $temp2);
                    if ($temp2[0] < 100) {
                        continue;
                    }
                    if (!isset($fleetAttack[$fleetID]['unit'][$temp2[0]])) {
                        $fleetAttack[$fleetID]['unit'][$temp2[0]] = 0;
                    }
                    $fleetAttack[$fleetID]['unit'][$temp2[0]] += $temp2[1];
                }
                $fleetDefend = array();
                $defRowDef = explode(';', $DefenderFleetArray);
                foreach ($defRowDef as $Element) {
                    $Element = explode(',', $Element);
                    if ($Element[0] < 100) {
                        continue;
                    }
                    if (!isset($fleetDefend[0]['unit'][$Element[0]])) {
                        $fleetDefend[0]['unit'][$Element[0]] = 0;
                    }
                    $fleetDefend[0]['unit'][$Element[0]] += $Element[1];
                }
                $fleetDefend[0]['fleetDetail'] = array('fleet_start_galaxy' => $this->_fleet['fleet_end_galaxy'], 'fleet_start_system' => $this->_fleet['fleet_end_system'], 'fleet_start_planet' => $this->_fleet['fleet_end_planet'], 'fleet_start_type' => 1, 'fleet_end_galaxy' => $this->_fleet['fleet_end_galaxy'], 'fleet_end_system' => $this->_fleet['fleet_end_system'], 'fleet_end_planet' => $this->_fleet['fleet_end_planet'], 'fleet_end_type' => 1, 'fleet_resource_metal' => 0, 'fleet_resource_crystal' => 0, 'fleet_resource_deuterium' => 0);
                $fleetDefend[0]['player'] = $DefenderTechno;
                $fleetDefend[0]['player']['factor'] = 0;
                require_once 'calculateAttack.php';
                $fleetIntoDebris = $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['Fleet_Cdr'];
                $defIntoDebris = $GLOBALS['CONFIG'][$this->_fleet['fleet_universe']]['Defs_Cdr'];
                $combatResult = calculateAttack($fleetAttack, $fleetDefend, $fleetIntoDebris, $defIntoDebris);
                $fleetArray = '';
                $totalCount = 0;
                $fleetAttack[$fleetID]['unit'] = array_filter($fleetAttack[$fleetID]['unit']);
                foreach ($fleetAttack[$fleetID]['unit'] as $element => $amount) {
                    $fleetArray .= $element . ',' . $amount . ';';
                    $totalCount += $amount;
                }
                if ($totalCount <= 0) {
                    $this->KillFleet();
                } else {
                    $this->UpdateFleet('fleet_array', substr($fleetArray, 0, -1));
                    $this->UpdateFleet('fleet_amount', $totalCount);
                }
                require_once 'GenerateReport.php';
                $debrisRessource = array(901, 902);
                foreach ($debrisRessource as $elementID) {
                    $debris[$elementID] = 0;
                }
                $stealResource = array(901 => 0, 902 => 0, 903 => 0);
                $raportInfo = array('thisFleet' => $this->_fleet, 'debris' => $debris, 'stealResource' => $stealResource, 'moonChance' => 0, 'moonDestroy' => false, 'moonName' => null, 'moonDestroyChance' => null, 'moonDestroySuccess' => null, 'fleetDestroyChance' => null, 'fleetDestroySuccess' => null);
                $raportData = GenerateReport($combatResult, $raportInfo);
                $raportID = md5(uniqid('', true) . TIMESTAMP);
                $sqlQuery = "INSERT INTO " . RW . " SET rid = '" . $raportID . "', raport = '" . serialize($raportData) . "', time = '" . $this->_fleet['fleet_start_time'] . "', attacker = '" . $this->_fleet['fleet_owner'] . "';";
                $GLOBALS['DATABASE']->query($sqlQuery);
                switch ($combatResult['won']) {
                    case "a":
                        $attackClass = 'style="color:green;"';
                        $defendClass = 'style="color:red;"';
                        break;
                    case "w":
                        $attackClass = 'style="color:orange;"';
                        $defendClass = 'style="color:orange;"';
                        break;
                    case "r":
                        $attackClass = 'style="color:red;"';
                        $defendClass = 'style="color:green;"';
                        break;
                }
                $message = sprintf($messageHTML, $raportID, $attackClass, $LNG['sys_mess_attack_report'], sprintf($LNG['sys_adress_planet'], $this->_fleet['fleet_start_galaxy'], $this->_fleet['fleet_start_system'], $this->_fleet['fleet_start_planet'], $this->_fleet['fleet_end_galaxy'], $this->_fleet['fleet_end_system'], $this->_fleet['fleet_end_planet']), $LNG['type_planet_short'][$this->_fleet['fleet_end_type']], $LNG['sys_lost'], $attackClass, $LNG['sys_attack_attacker_pos'], pretty_number($combatResult['unitLost']['attacker']), $defendClass, $LNG['sys_attack_defender_pos'], pretty_number($combatResult['unitLost']['defender']), $LNG['sys_gain'], $LNG['tech'][901], pretty_number($stealResource[901]), $LNG['tech'][902], pretty_number($stealResource[902]), $LNG['tech'][903], pretty_number($stealResource[903]), $LNG['sys_debris'], $LNG['tech'][901], pretty_number($debris[901]), $LNG['tech'][902], pretty_number($debris[902]));
                if ($combatResult['won'] == 'a') {
                    $GLOBALS['DATABASE']->query("UPDATE " . USERS . " set `achievements_expedition` = `achievements_expedition` + '1', `expedition_count` = `expedition_count` + '1' where `id` = '" . $this->_fleet['fleet_owner'] . "';");
                    $GLOBALS['DATABASE']->query("UPDATE " . USERS . " SET stardust = stardust + '" . $find_stardust . "' where `id` = " . $this->_fleet['fleet_owner'] . ";");
                }
                SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_end_stay'], 3, $LNG['sys_mess_tower'], $LNG['sys_mess_attack_report'], $message);
                break;
            case 5:
                $this->KillFleet();
                $Message = $LNG['sys_expe_lost_fleet_' . mt_rand(1, 4)];
                break;
            case 6:
                # http://owiki.de/Expedition#Ver.C3.A4nderte_Flugzeit
                $MoreTime = mt_rand(0, 100);
                $Wrapper = array();
                $Wrapper[] = 2;
                $Wrapper[] = 2;
                $Wrapper[] = 2;
                $Wrapper[] = 2;
                $Wrapper[] = 2;
                $Wrapper[] = 2;
                $Wrapper[] = 2;
                $Wrapper[] = 3;
                $Wrapper[] = 3;
                $Wrapper[] = 5;
                if ($MoreTime < 75) {
                    $this->UpdateFleet('fleet_end_time', $this->_fleet['fleet_end_stay'] + ($this->_fleet['fleet_end_time'] - $this->_fleet['fleet_end_stay'] + ($this->_fleet['fleet_end_stay'] - $this->_fleet['fleet_start_time']) * $Wrapper[mt_rand(0, 9)]));
                    $Message = $LNG['sys_expe_time_slow_' . mt_rand(1, 6)];
                } else {
                    $this->UpdateFleet('fleet_end_time', $this->_fleet['fleet_end_stay'] + max(1, $this->_fleet['fleet_end_time'] - $this->_fleet['fleet_end_stay'] - ($this->_fleet['fleet_end_stay'] - $this->_fleet['fleet_start_time']) / 3 * $Wrapper[mt_rand(0, 9)]));
                    $Message = $LNG['sys_expe_time_fast_' . mt_rand(1, 3)];
                }
                break;
            case 7:
                $FindSize = mt_rand(0, 100);
                if (30 < $FindSize) {
                    $Message = 'You found one frisbee';
                    $varis = 'frisbee';
                } elseif (10 < $FindSize && 30 >= $FindSize) {
                    $Message = 'You found one alien';
                    $varis = 'alien';
                } elseif (0 < $FindSize && 10 >= $FindSize) {
                    $Message = 'You found one rocket';
                    $varis = 'rocket';
                }
                $GLOBALS['DATABASE']->query("UPDATE " . USERS . " set `achievements_expedition` = `achievements_expedition` + '1', `expedition_count` = `expedition_count` + '1' where `id` = '" . $this->_fleet['fleet_owner'] . "';");
                $GLOBALS['DATABASE']->query("UPDATE " . USERS . " set " . $varis . " = " . $varis . " + '1' where `id` = '" . $this->_fleet['fleet_owner'] . "';");
                break;
        }
        SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_end_stay'], 15, $LNG['sys_mess_tower'], $LNG['sys_expe_report'], $Message);
        $this->setState(FLEET_RETURN);
        $this->SaveFleet();
    }
Esempio n. 8
0
<?php } ?>
<?php 
		$emp_roll_no = EmployeeInfo::model()->findAll();
		$empno='';
		if(Yii::app()->controller->action->id=='create')
		{
			if(empty($emp_roll_no))
			{
			$empno=$info->employee_unique_id=1;
			}
			else
			{
				foreach($emp_roll_no as $s)
				{
		            		$emp[]=$s['employee_unique_id'];
					$empno=MAX($emp)+1;
				}			
			}
		}
		else
		{
			if(!empty($emp_roll_no))
			{
				$empno=$info->employee_unique_id;
			}
		}

	/*	if(empty($emp_roll_no))
		{
			$empno=$info->employee_unique_id=1;
		}
 public function sync()
 {
     $user = $this->Users->get($this->Auth->user('id'));
     $atts = TableRegistry::get('Attendees');
     $attRef = $atts->find('all')->where(['user_attendee' => true, 'user_id' => $user->id]);
     $attName = $atts->find('all')->where(['firstname' => $user->firstname, 'lastname' => $user->lastname, 'user_id' => $user->id]);
     $count = MAX($attRef->count(), $attName->count());
     if ($count == 1) {
         if ($attRef->count() == 1) {
             $att = $attRef->first();
         } else {
             $att = $attName->first();
         }
     } else {
         $newAttendeeData = ['dateofbirth' => '01-01-1990'];
         $att = $atts->newEntity($newAttendeeData);
     }
     $attendeeData = ['user_id' => $user->id, 'firstname' => $user->firstname, 'lastname' => $user->lastname, 'address_1' => $user->address_1, 'address_2' => $user->address_2, 'city' => $user->city, 'county' => $user->county, 'user_attendee' => true, 'postcode' => $user->postcode, 'role_id' => $user->role_id, 'scoutgroup_id' => $user->scoutgroup_id, 'phone' => $user->phone];
     $att = $atts->patchEntity($att, $attendeeData);
     if ($atts->save($att)) {
         $this->Flash->success(__('An Attendee for your User has been Syncronised.'));
     } else {
         $this->Flash->error(__('An Attendee for your User could not be Syncronised. Please, try again.'));
     }
     return $this->redirect(['controller' => 'Landing', 'action' => 'user_home']);
 }
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new StudentTransaction;
		$info =new StudentInfo;
		$user =new User;
		$photo =new StudentPhotos;
		$address=new StudentAddress;
		$lang=new LanguagesKnown;
		$auth_assign = new AuthAssignment;
		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation(array($info,$model,$user));

		if(!empty($_POST['StudentTransaction']) || !empty($_POST['StudentInfo'] ))
		{
			
		$stud_roll_no = StudentInfo::model()->findAll();
	     if(Yii::app()->controller->action->id=='create'){
		if(empty($stud_roll_no))
		{
			$rollno=$info->student_roll_no=1;
		}
		else
		{
			//$rand=mt_rand(1,2000);
			foreach($stud_roll_no as $s)
			{
                    		$stud[]=$s['student_roll_no'];
				$rollno_m=MAX($stud)+1;
			}		
				if(StudentInfo::model()->exists('student_roll_no='.$rollno_m))
				{
					$rollno=$rollno_m+1;
				}
				else
				{
					$rollno=$rollno_m;
				}			
		}
	      }
	    else
		{
		
		}
		//echo $rollno; exit;
					
		
			
			
			/*$batch_id=$_POST['StudentTransaction']['student_transaction_batch_id'];
			$batch=Batch::model()->findByPk($batch_id);
			$course=$batch->course_id;
			$academic_year=AcademicTerm::model()->findByPk($course);
		
			$model->academic_term_period_id=$academic_year->academic_term_period_id;
			$model->course_id=$batch->course_id;
			$model->academic_term_id=$batch->academic_term_id; */
			$model->attributes=$_POST['StudentTransaction'];			
			$info->attributes=$_POST['StudentInfo'];
			$user->attributes=$_POST['User'];
					
			$info->student_created_by = Yii::app()->user->id;
			$info->student_creation_date = new CDbExpression('NOW()');
			$info->student_email_id_1=strtolower($user->user_organization_email_id);
			$info->student_adm_date = date('Y-m-d',strtotime($_POST['StudentInfo']['student_adm_date']));			
			$info->student_roll_no=$rollno;
			$info->passport_exp_date=date('Y-m-d',strtotime($_POST['StudentInfo']['passport_exp_date']));
			$user->user_organization_email_id = strtolower($info->student_email_id_1);
			$user->user_password =  md5($info->student_email_id_1.$info->student_email_id_1);
			$user->user_created_by =  Yii::app()->user->id;
			$user->user_creation_date = new CDbExpression('NOW()');
			$user->user_type = "student";
			
			if($info->save(false))  
			{  
				$user->save(false);
				$address->save(false);
				$lang->save(false); 						
				$photo->student_photos_path = "no-images";
				$photo->save();
			}
			//if(empty($model->student_transaction_batch_id))
			//$model->student_transaction_batch_id=0;
			//$model->academic_term_id=$_POST['StudentTransaction']['academic_term_id'];
			//$model->academic_term_period_id=$_POST['StudentTransaction']['academic_term_period_id'];
			$model->course_id=$_POST['StudentTransaction']['course_id'];	  
			$model->student_transaction_languages_known_id= $lang->languages_known_id;
			$model->student_transaction_student_id = $info->student_id;
			$model->student_transaction_user_id = $user->user_id;
			$model->student_transaction_student_address_id = $address->student_address_id;
			$model->student_transaction_student_photos_id = $photo->student_photos_id;
			$flag = Studentstatusmaster::model()->findByAttributes(array('status_name'=>'Regular'))->id;
			$model->student_transaction_detain_student_flag = 1;
			$model->save(false);
			
			StudentInfo::model()->updateByPk($model->student_transaction_student_id, array('student_info_transaction_id'=>$model->student_transaction_id));
			$auth_assign->itemname = 'Student';
			$auth_assign->userid = $user->user_id;
			$auth_assign->bizrule = '';
			$auth_assign->data = '';
			$auth_assign->save(true);	
			$this->redirect(array('update','id'=>$model->student_transaction_id));
		} //end of isset if
		else
		{
			$this->render('create',array(
			'model'=>$model,'info'=>$info,'user'=>$user
			));
		}
	}
Esempio n. 11
0
             $res1t['opacity'] = 0;
         }
         $res[] = $res1t;
     }
     $responseData = json_encode($res, FALSE);
     echo $responseData;
     exit;
 }
 if ($action_ajax == 'add_links') {
     if (!API::Host()->isWritable(array($hostid))) {
         rightsErrorAjax();
     }
     $shost = $hostid;
     foreach ($thostid as $thost) {
         if (API::Host()->isWritable(array($hostid))) {
             $newlink = array('host1' => MIN($shost, $thost), 'host2' => MAX($shost, $thost));
             $res = DBimap::insert('hosts_links', array($newlink));
         }
     }
     $responseData = json_encode(array('result' => $res), FALSE);
     echo $responseData;
     exit;
 }
 if ($action_ajax == 'update_link') {
     if (!rightsForLink($linkid)) {
         rightsErrorAjax();
     }
     $link = $linkid;
     $newlink = array('values' => array('name' => $linkoptions['linkname']), 'where' => array('id' => $link));
     $res = DBimap::update('hosts_links', array($newlink));
     $res = DBimap::delete('hosts_links_settings', array('ids' => array($link)));
 function get_week_info($tabrange, $week)
 {
     global $SESSION;
     if ($this->course->numsections == FNMAXTABS) {
         $tablow = 1;
         $tabhigh = FNMAXTABS;
     } else {
         if ($tabrange > 1000) {
             $tablow = $tabrange / 1000;
             $tabhigh = $tablow + FNMAXTABS - 1;
         } else {
             if ($tabrange == 0 && $week == 0) {
                 $tablow = (int) ((int) ($this->course->numsections - 1) / (int) FNMAXTABS) * FNMAXTABS + 1;
                 $tabhigh = $tablow + FNMAXTABS - 1;
             } else {
                 if ($tabrange == 0) {
                     $tablow = (int) ((int) $week / (int) FNMAXTABS) * FNMAXTABS + 1;
                     $tabhigh = $tablow + FNMAXTABS - 1;
                 } else {
                     $tablow = 1;
                     $tabhigh = FNMAXTABS;
                 }
             }
         }
     }
     $tabhigh = MIN($tabhigh, $this->course->numsections);
     /// Normalize the tabs to always display FNMAXTABS...
     if ($tabhigh - $tablow + 1 < FNMAXTABS) {
         $tablow = $tabhigh - FNMAXTABS + 1;
     }
     /// Save the low and high week in SESSION variables... If they already exist, and the selected
     /// week is in their range, leave them as is.
     if ($tabrange >= 1000 || !isset($SESSION->FN_tablow[$this->course->id]) || !isset($SESSION->FN_tabhigh[$this->course->id]) || $week < $SESSION->FN_tablow[$this->course->id] || $week > $SESSION->FN_tabhigh[$this->course->id]) {
         $SESSION->FN_tablow[$this->course->id] = $tablow;
         $SESSION->FN_tabhigh[$this->course->id] = $tabhigh;
     } else {
         $tablow = $SESSION->FN_tablow[$this->course->id];
         $tabhigh = $SESSION->FN_tabhigh[$this->course->id];
     }
     $tablow = MAX($tablow, 1);
     $tabhigh = MIN($tabhigh, $this->course->numsections);
     /// If selected week in a different set of tabs, move it to the current set...
     if ($week != 0 && $week < $tablow) {
         $week = $SESSION->G8_selected_week[$this->course->id] = $tablow;
     } else {
         if ($week > $tabhigh) {
             $week = $SESSION->G8_selected_week[$this->course->id] = $tabhigh;
         }
     }
     return array($tablow, $tabhigh, $week);
 }
require_once 'class/graph.php';
WEBPAGE::START();
$_LABELS = WEBPAGE::getCacheData(sprintf(WEBPAGE::_APP_LABELS_FILE, $_GET['lang']));
//get question list   $ql_a
$sql = sprintf("SELECT question_list FROM tblSurveys WHERE id = '%s'", $_GET[survey_id]);
$row = current(WEBPAGE::$dbh->getAll($sql));
$ql = $row[question_list];
$ql_a = explode(',', $ql);
//get answer num - cal.   $an_a
$sql = sprintf("SELECT id, answer_num, category FROM tblSurveyItems WHERE FIND_IN_SET(id, '%s')", $ql);
$mrow = WEBPAGE::$dbh->getAll($sql);
for ($i = 0; $i < count($mrow); $i++) {
    $an_a_cal[$mrow[$i][id]] = explode('|', $mrow[$i][answer_num]);
    $an_a_cat[$mrow[$i][id]] = $mrow[$i][category];
    foreach ($an_a_cal[$mrow[$i][id]] as $key => $value) {
        $an_a_cmax[$mrow[$i][id]] = MAX($an_a_cmax[$mrow[$i][id]], $value);
    }
}
// get survey answers $sa
$sql = "SELECT client_id, answer_list FROM tblSurveyAnswers WHERE survey_id = '{$_GET['survey_id']}'";
$mrow = WEBPAGE::$dbh->getAll($sql);
for ($i = 0; $i < count($mrow); $i++) {
    $sa_a_ref = explode(',', $mrow[$i][answer_list]);
    unset($sa_a_cal);
    foreach ($sa_a_ref as $key => $value) {
        $sa_a_cal[] = $an_a_cal[$ql_a[$key]][$value - 1];
    }
    $sa_a[$mrow[$i][client_id]][] = $sa_a_cal;
}
// ready to graph
foreach ($sa_a as $key => $value) {
 function get_week_info($tabrange, $week, $chapter = 0)
 {
     global $SESSION, $DB, $USER;
     $c = $this->get_chapter($chapter);
     // added by oncampus
     $lections = $c['lections'];
     // added by oncampus
     //$fnmaxtab = $DB->get_field('course_config_fn', 'value', array('courseid' => $this->course->id, 'variable' => 'maxtabs'));
     /* if ($fnmaxtab) {
            $maximumtabs = $fnmaxtab;
        } else {
            $maximumtabs = 12;
        } */
     $maximumtabs = 6;
     if ($lections < 6) {
         $maximumtabs = $lections;
     }
     $last_lection = $this->get_last_lection();
     // oncampus
     if ($USER->username == 'rieger') {
         //echo 'range: '.$tabrange.', week: '.$week.', chapter: '.$chapter.', last_section: '.$last_lection.'<br />';
     }
     if ($last_lection == $maximumtabs) {
         // oncampus
         //if ($USER->username == 'rieger') { echo '1<br />';}
         $tablow = 1;
         $tabhigh = $maximumtabs;
     } else {
         if ($maximumtabs < 6) {
             //if ($USER->username == 'rieger') { echo '1.5<br />';}
             $tablow = 1;
             $tabhigh = $maximumtabs;
         } else {
             if ($tabrange > 1000) {
                 //if ($USER->username == 'rieger') { echo '2<br />';}
                 $tablow = (int) ($tabrange / 1000);
                 $tabhigh = (int) ($tablow + $maximumtabs - 1);
             } else {
                 if ($tabrange == 0 && $week == 0) {
                     //if ($USER->username == 'rieger') { echo '3<br />';}
                     $tablow = (int) ((int) ($last_lection - 1) / (int) $maximumtabs) * $maximumtabs + 1;
                     $tabhigh = $tablow + $maximumtabs - 1;
                 } else {
                     if ($tabrange == 0) {
                         $tablow = $week;
                         //((int) ((int) $week / (int) $maximumtabs) * $maximumtabs) + 1;
                         $tabhigh = $tablow + $maximumtabs - 1;
                         //if ($USER->username == 'rieger') { echo 'nr. 4 ('.$tablow.' '.$tabhigh.')<br />';}
                         //echo '('.$tablow.' '.$tabhigh.')';
                     } else {
                         //if ($USER->username == 'rieger') { echo '5<br />';}
                         $tablow = 1;
                         $tabhigh = $maximumtabs;
                     }
                 }
             }
         }
     }
     $tabhigh = MIN($tabhigh, $last_lection);
     /// Normalize the tabs to always display FNMAXTABS...
     if ($tabhigh - $tablow + 1 < $maximumtabs) {
         $tablow = $tabhigh - $maximumtabs + 1;
     }
     /// Save the low and high week in SESSION variables... If they already exist, and the selected
     /// week is in their range, leave them as is.
     if ($tabrange >= 1000 || !isset($SESSION->FN_tablow[$this->course->id]) || !isset($SESSION->FN_tabhigh[$this->course->id]) || $week < $SESSION->FN_tablow[$this->course->id] || $week > $SESSION->FN_tabhigh[$this->course->id]) {
         $SESSION->FN_tablow[$this->course->id] = $tablow;
         $SESSION->FN_tabhigh[$this->course->id] = $tabhigh;
     } else {
         $tablow = $SESSION->FN_tablow[$this->course->id];
         $tabhigh = $SESSION->FN_tabhigh[$this->course->id];
     }
     $tablow = MAX($tablow, 1);
     $tabhigh = MIN($tabhigh, $last_lection);
     // oncampus
     /* $low = $c['first_lection'] - ((int)(($maximumtabs - $lections) / 2));
     		
     		if (($low + $maximumtabs - 1) > $last_lection) {
     			$low = $last_lection - $maximumtabs + 1;
     		}
     		$high = $low + $maximumtabs - 1;
     		if ($chapter != 0 and (($tabrange > $low and $tabrange <= $high) or $tabrange == 0 )) {
     			$tablow = $low;
                 $tabhigh = $high;
     		} */
     // oncampus ende
     unset($maximumtabs);
     return array($tablow, $tabhigh, $week);
 }
 public function sync()
 {
     $settings = TableRegistry::get('Settings');
     $users = TableRegistry::get('Users');
     $atts = TableRegistry::get('Attendees');
     $session = $this->request->session();
     $user = $users->get($this->Auth->user('id'));
     $now = Time::now();
     $apiId = $settings->get('10')->text;
     $apiToken = $settings->get('11')->text;
     $apiBase = $settings->get('12')->text;
     if (empty($user->osm_secret) || !$session->check('OSM.Secret')) {
         $this->Flash->error(__('Please link your account first'));
         return $this->redirect(['action' => 'link']);
     } elseif (empty($user->osm_section_id)) {
         $this->Flash->error(__('Please select your section first'));
         return $this->redirect(['action' => 'section']);
     } elseif (empty($user->osm_current_term) && $user->osm_term_end > $now) {
         $this->Flash->error(__('Please choose your Term first'));
         return $this->redirect(['action' => 'term']);
     } else {
         $userOsmId = $user->osm_user_id;
         $userOsmSecret = $user->osm_secret . $session->read('OSM.Secret');
         $userOsmSection = $user->osm_section_id;
         $userOsmTerm = $user->osm_current_term;
     }
     if (!isset($successCnt)) {
         $successCnt = 0;
     }
     if (!isset($errCnt)) {
         $errCnt = 0;
     }
     $http = new Client(['host' => $apiBase, 'scheme' => 'https']);
     $url = '/ext/members/contact/grid/' . '?action=getMembers';
     $response = $http->post($url, ['userid' => $userOsmId, 'secret' => $userOsmSecret, 'token' => $apiToken, 'apiid' => $apiId, 'section_id' => $userOsmSection, 'term_id' => $userOsmTerm]);
     if ($response->isOk()) {
         $preBody = $response->json;
         //Debugger::dump($preBody);
         $status = Hash::get($preBody, 'status');
         if ($status == false) {
             $error = Hash::get($preBody, 'error');
             $message = Hash::get($error, 'message');
             $this->Flash->error(__($message . ' Please see instructions for granting access in OSM.'));
             return $this->redirect(['action' => 'access']);
         }
         $cubs = Hash::get($preBody, 'data');
         //Debugger::dump($cubs);
         //$cubs = Hash::extract($body, 'items');
         //$cubs = Hash::normalize($cubs);
         foreach ($cubs as $cub) {
             $active = Hash::get($cub, 'active');
             if ($active == true) {
                 //Debugger::dump($cub);
                 $firstname = Hash::get($cub, 'first_name');
                 $lastname = Hash::get($cub, 'last_name');
                 $osmId = Hash::get($cub, 'member_id');
                 $dateofbirth = Hash::get($cub, 'date_of_birth');
                 //$dateofbirth = Time::parse($dateofbirth);
                 $patrol = Hash::get($cub, 'patrol');
                 //Debugger::dump($patrol);
                 $customData = Hash::get($cub, 'custom_data');
                 if ($patrol == 'Leaders') {
                     $roleId = 19;
                     $address = Hash::get($customData, 6);
                     $phoneAddress = Hash::get($customData, 6);
                 } else {
                     $roleId = 1;
                     $address = Hash::get($customData, 1);
                     $phoneAddress = Hash::get($customData, 1);
                 }
                 // Debugger::dump($customData);
                 $address1 = Hash::get($address, 7);
                 $address2 = Hash::get($address, 8);
                 $city = Hash::get($address, 9);
                 $county = Hash::get($address, 10);
                 $postcode = Hash::get($address, 11);
                 if (empty($address1) && empty($address2) && empty($city) && empty($county) && empty($postcode)) {
                     $address = Hash::get($customData, 1);
                     $address1 = Hash::get($address, 7);
                     $address2 = Hash::get($address, 8);
                     $city = Hash::get($address, 9);
                     $county = Hash::get($address, 10);
                     $postcode = Hash::get($address, 11);
                     if (empty($address1) && empty($address2) && empty($city) && empty($county) && empty($postcode)) {
                         $address = Hash::get($customData, 2);
                         $address1 = Hash::get($address, 7);
                         $address2 = Hash::get($address, 8);
                         $city = Hash::get($address, 9);
                         $county = Hash::get($address, 10);
                         $postcode = Hash::get($address, 11);
                         if (empty($address1) && empty($address2) && empty($city) && empty($county) && empty($postcode)) {
                             $address = Hash::get($customData, 3);
                             $address1 = Hash::get($address, 7);
                             $address2 = Hash::get($address, 8);
                             $city = Hash::get($address, 9);
                             $county = Hash::get($address, 10);
                             $postcode = Hash::get($address, 11);
                             if (empty($address1) && empty($address2) && empty($city) && empty($county) && empty($postcode)) {
                                 $address = Hash::get($customData, 6);
                                 $address1 = Hash::get($address, 7);
                                 $address2 = Hash::get($address, 8);
                                 $city = Hash::get($address, 9);
                                 $county = Hash::get($address, 10);
                                 $postcode = Hash::get($address, 11);
                             }
                         }
                     }
                 }
                 $address1 = trim($address1);
                 $address2 = trim($address2);
                 $city = trim($city);
                 $county = trim($county);
                 $postcode = trim($postcode);
                 if (empty($city)) {
                     $city = $address2;
                     $address2 = null;
                 }
                 if (strtoupper($city) == 'HERTS' || strtoupper($city) == 'HERTFORDSHIRE') {
                     $county = $city;
                     $city = $address2;
                     $address2 = null;
                 }
                 if (strtoupper($county) == 'HERTS') {
                     $county = ucwords(strtolower('HERTFORDSHIRE'));
                 }
                 if (empty($county)) {
                     $county = ucwords(strtolower('HERTFORDSHIRE'));
                 }
                 $postcode = str_replace(' ', '', $postcode);
                 $postcode = str_replace('-', '', $postcode);
                 $postcode = str_replace('/', '', $postcode);
                 $postcode = str_replace('.', '', $postcode);
                 $postcode = str_replace(',', '', $postcode);
                 $postcode = substr($postcode, 0, -3) . ' ' . substr($postcode, -3);
                 // GET TELEPHONE VALUES
                 $phone1 = Hash::get($phoneAddress, 18);
                 $phone2 = Hash::get($phoneAddress, 20);
                 if (empty($phone1) && empty($phone2)) {
                     $phoneAddress = Hash::get($customData, 1);
                     $phone1 = Hash::get($phoneAddress, 18);
                     $phone2 = Hash::get($phoneAddress, 20);
                     if (empty($phone1) && empty($phone2)) {
                         $phoneAddress = Hash::get($customData, 2);
                         $phone1 = Hash::get($phoneAddress, 18);
                         $phone2 = Hash::get($phoneAddress, 20);
                         if (empty($phone1) && empty($phone2)) {
                             $phoneAddress = Hash::get($customData, 3);
                             $phone1 = Hash::get($phoneAddress, 18);
                             $phone2 = Hash::get($phoneAddress, 20);
                             if (empty($phone1) && empty($phone2)) {
                                 $phoneAddress = Hash::get($customData, 6);
                                 $phone1 = Hash::get($phoneAddress, 18);
                                 $phone2 = Hash::get($phoneAddress, 20);
                             }
                         }
                     }
                 }
                 $phone1 = trim($phone1);
                 $phone2 = trim($phone2);
                 if (empty($phone1) && empty($phone2)) {
                     $phone1 = 0700;
                 } elseif (empty($phone1)) {
                     $phone1 = $phone2;
                     $phone2 = null;
                 }
                 $phone1 = str_replace(' ', '', $phone1);
                 $phone1 = str_replace('-', '', $phone1);
                 $phone1 = str_replace('/', '', $phone1);
                 $phone1 = str_replace('+44', '0', $phone1);
                 $phone1 = substr($phone1, 0, 5) . ' ' . substr($phone1, 5);
                 if (!empty($phone2)) {
                     $phone2 = str_replace(' ', '', $phone2);
                     $phone2 = str_replace('-', '', $phone2);
                     $phone2 = str_replace('/', '', $phone2);
                     $phone2 = str_replace('+44', '0', $phone2);
                     $phone2 = substr($phone2, 0, 5) . ' ' . substr($phone2, 5);
                     if ($phone1 == $phone2) {
                         $phone2 = null;
                     }
                 }
                 //Debugger::dump($address);
                 $attsName = $atts->find('all')->where(['firstname' => $firstname, 'lastname' => $lastname, 'user_id' => $user->id]);
                 $attsID = $atts->find('all')->where(['osm_id' => $osmId, 'user_id' => $user->id]);
                 $count = MAX($attsID->count(), $attsName->count());
                 if ($count == 1) {
                     if ($attsID->count() == 1) {
                         $att = $attsID->first();
                     } else {
                         $att = $attsName->first();
                     }
                     $cubData = ['osm_id' => $osmId, 'dateofbirth' => $dateofbirth, 'address_1' => ucwords(strtolower($address1)), 'address_2' => ucwords(strtolower($address2)), 'city' => ucwords(strtolower($city)), 'county' => ucwords(strtolower($county)), 'postcode' => strtoupper($postcode), 'phone' => strtoupper($phone1), 'phone2' => strtoupper($phone2), 'osm_sync_date' => $now, 'deleted' => null];
                 } else {
                     $att = $atts->newEntity();
                     $cubData = ['firstname' => ucwords(strtolower($firstname)), 'lastname' => ucwords(strtolower($lastname)), 'osm_id' => $osmId, 'user_id' => $user->id, 'scoutgroup_id' => $user->scoutgroup_id, 'dateofbirth' => $dateofbirth, 'role_id' => $roleId, 'osm_generated' => true, 'address_1' => ucwords(strtolower($address1)), 'address_2' => ucwords(strtolower($address2)), 'city' => ucwords(strtolower($city)), 'county' => ucwords(strtolower($county)), 'postcode' => strtoupper($postcode), 'phone' => strtoupper($phone1), 'phone2' => strtoupper($phone2), 'osm_sync_date' => $now];
                 }
                 $att = $atts->patchEntity($att, $cubData);
                 if ($atts->save($att)) {
                     $successCnt = $successCnt + 1;
                 } else {
                     $errCnt = $errCnt + 1;
                 }
             }
         }
         if (isset($errCnt) && $errCnt > 0) {
             $this->Flash->error(__('There were ' . $errCnt . ' records which did not sync, please try again.'));
         }
         if (isset($successCnt) && $successCnt > 0) {
             $this->Flash->success(__('Synced ' . $successCnt . ' records sucessfully.'));
         }
         $osmEnt = ['Entity Id' => null, 'Controller' => 'OSM', 'Action' => 'Sync', 'User Id' => $this->Auth->user('id'), 'Creation Date' => $now, 'Modified' => null, 'OSM' => ['ErrorNumber' => $errCnt, 'SuccessNumber' => $successCnt]];
         $sets = TableRegistry::get('Settings');
         $jsonOSM = json_encode($osmEnt);
         $apiKey = $sets->get(13)->text;
         $projectId = $sets->get(14)->text;
         $eventType = 'Action';
         $keenURL = 'https://api.keen.io/3.0/projects/' . $projectId . '/events/' . $eventType . '?api_key=' . $apiKey;
         $http = new Client();
         $response = $http->post($keenURL, $jsonOSM, ['type' => 'json']);
         return $this->redirect(['action' => 'home']);
     } else {
         $this->Flash->error(__('There was a request error, please try again.'));
         return $this->redirect(['action' => 'home']);
     }
 }
Esempio n. 16
0
	<div class="row">
	 <?php 
		$stud_roll_no = StudentInfo::model()->findAll();
		$rollno='';
		if(Yii::app()->controller->action->id=='create')
		{
			if(empty($stud_roll_no))
			{
				$rollno=$info->student_roll_no=1;
			}
			else
			{
				foreach($stud_roll_no as $s)
				{
		            		$stud[]=$s['student_roll_no'];
					$rollno=MAX($stud)+1;
				}			
			}
		}
		else
		{
			if(!empty($stud_roll_no))
			{
				$rollno=$info->student_roll_no;
			}
		}
		//echo $rollno; exit;
					
		
		?>
		
 public function repopulate($invID = null)
 {
     // Find Existing Lines
     $existingCubDep = $this->InvoiceItems->find()->where(['itemtype_id' => 1, 'invoice_id' => $invID])->first();
     $existingCub = $this->InvoiceItems->find()->where(['itemtype_id' => 2, 'invoice_id' => $invID])->first();
     $existingYl = $this->InvoiceItems->find()->where(['itemtype_id' => 3, 'invoice_id' => $invID])->first();
     $existingLeader = $this->InvoiceItems->find()->where(['itemtype_id' => 4, 'invoice_id' => $invID])->first();
     $existingDiscount = $this->InvoiceItems->find()->where(['itemtype_id' => 5, 'invoice_id' => $invID])->first();
     // Retrive IDs
     $existingCubDepID = $existingCubDep->id;
     $existingCubID = $existingCub->id;
     $existingYlID = $existingYl->id;
     $existingLeaderID = $existingLeader->id;
     $existingDiscountID = $existingDiscount->id;
     // Get Existing Lines
     $existingCubDepItem = $this->InvoiceItems->get($existingCubDepID);
     $existingCubItem = $this->InvoiceItems->get($existingCubID);
     $existingYlItem = $this->InvoiceItems->get($existingYlID);
     $existingLeaderItem = $this->InvoiceItems->get($existingLeaderID);
     $existingDiscountItem = $this->InvoiceItems->get($existingDiscountID);
     // Retrive Quantity Values
     $existingCubDepQty = $existingCubDepItem->Quantity;
     $existingCubQty = $existingCubItem->Quantity;
     $existingYlQty = $existingYlItem->Quantity;
     $existingLeaderQty = $existingLeaderItem->Quantity;
     $existingDiscountQty = $existingDiscountItem->Quantity;
     // Retrive Cancelled Quantities
     // Find Existing Cancelled Lines
     $existingCanCubDep = $this->InvoiceItems->find()->where(['itemtype_id' => 7, 'invoice_id' => $invID])->first();
     $existingCanCub = $this->InvoiceItems->find()->where(['itemtype_id' => 8, 'invoice_id' => $invID])->first();
     $existingCanYl = $this->InvoiceItems->find()->where(['itemtype_id' => 9, 'invoice_id' => $invID])->first();
     $existingCanLeader = $this->InvoiceItems->find()->where(['itemtype_id' => 10, 'invoice_id' => $invID])->first();
     // Retrive Cancelled Deposit
     if (!empty($existingCanCubDep)) {
         $existingCanCubDepID = $existingCanCubDep->id;
         $existingCanCubDepItem = $this->InvoiceItems->get($existingCanCubDepID);
         $existingCanCubDepQty = $existingCanCubDepItem->Quantity;
     } else {
         $existingCanCubDepQty = 0;
         $existingCanCubDepItem = $this->InvoiceItems->newEntity();
     }
     if (!empty($existingCanCub)) {
         $existingCanCubID = $existingCanCub->id;
         $existingCanCubItem = $this->InvoiceItems->get($existingCanCubID);
         $existingCanCubQty = $existingCanCubItem->Quantity;
     } else {
         $existingCanCubQty = 0;
         $existingCanCubItem = $this->InvoiceItems->newEntity();
     }
     if (!empty($existingCanYl)) {
         $existingCanYlID = $existingCanYl->id;
         $existingCanYlItem = $this->InvoiceItems->get($existingCanYlID);
         $existingCanYlQty = $existingCanYlItem->Quantity;
     } else {
         $existingCanYlQty = 0;
         $existingCanYlItem = $this->InvoiceItems->newEntity();
     }
     if (!empty($existingCanLeader)) {
         $existingCanLeaderID = $existingCanLeader->id;
         $existingCanLeaderItem = $this->InvoiceItems->get($existingCanLeaderID);
         $existingCanLeaderQty = $existingCanLeaderItem->Quantity;
     } else {
         $existingCanLeaderQty = 0;
         $existingCanLeaderItem = $this->InvoiceItems->newEntity();
     }
     $totalExistingCancelled = $existingCanCubQty + $existingCanYlQty + $existingCanLeaderQty + $existingCanCubDepQty;
     // Set Variable for the Modeless Form to take Values
     $invPop = new InvcanForm();
     $limitTextCubs = 'There is a limit for Cubs on this event.';
     $limitTextYls = 'There is a limit for Young Leaders on this event.';
     $limitTextLeaders = 'There is a limit for Leaders on this event.';
     // Connect Registry
     $settings = TableRegistry::get('Settings');
     $events = TableRegistry::get('Events');
     $applications = TableRegistry::get('Applications');
     $attendees = TableRegistry::get('Attendees');
     $invoices = TableRegistry::get('Invoices');
     $discounts = TableRegistry::get('Discounts');
     // Insantiate Objects
     $invoice = $invoices->get($invID, ['contain' => ['Users', 'Payments', 'InvoiceItems', 'Applications']]);
     $application = $applications->get($invoice->application_id, ['contain' => ['Attendees']]);
     $event = $events->get($application->event_id, ['contain' => ['Applications', 'Settings']]);
     if (isset($event->discount_id)) {
         $discount = $discounts->get($event->discount_id);
     }
     // Set Item Description Text
     $depositDescription = $event->deposit_text;
     $cubsDescription = $event->cubs_text;
     $ylsDescription = $event->yls_text;
     $leadersDescription = $event->leaders_text;
     // Set Item Price
     $depositEventPrice = $event->deposit_value;
     $cubsEventPrice = $event->cubs_value;
     $ylsEventPrice = $event->yls_value;
     $leadersEventPrice = $event->leaders_value;
     // Set Cancelled Item Description Text
     $depositCanDescription = 'CANCELLED: ' . $event->deposit_text;
     $cubsCanDescription = 'CANCELLED: ' . $event->cubs_text;
     $ylsCanDescription = 'CANCELLED: ' . $event->yls_text;
     $leadersCanDescription = 'CANCELLED: ' . $event->leaders_text;
     // Set Cancelled Item Price  // THIS WILL BE WHERE CANCELLATION RATIO WILL COME IN
     $depositCanEventPrice = $event->deposit_value;
     $cubsCanEventPrice = $event->cubs_value;
     $ylsCanEventPrice = $event->yls_value;
     $leadersCanEventPrice = $event->leaders_value;
     // Set Application ID
     $appID = $invoice->application_id;
     // Set Attendee Counts
     $attendeeCubCount = $applications->find()->hydrate(false)->join(['x' => ['table' => 'applications_attendees', 'type' => 'LEFT', 'conditions' => 'x.application_id = Applications.id'], 't' => ['table' => 'attendees', 'type' => 'INNER', 'conditions' => 't.id = x.attendee_id'], 'r' => ['table' => 'roles', 'type' => 'INNER', 'conditions' => 'r.id = t.role_id']])->where(['r.minor' => 1, 't.role_id' => 1, 'Applications.id' => $appID, 't.deleted IS' => null]);
     $attendeeYlCount = $applications->find()->hydrate(false)->join(['x' => ['table' => 'applications_attendees', 'type' => 'LEFT', 'conditions' => 'x.application_id = Applications.id'], 't' => ['table' => 'attendees', 'type' => 'INNER', 'conditions' => 't.id = x.attendee_id'], 'r' => ['table' => 'roles', 'type' => 'INNER', 'conditions' => 'r.id = t.role_id']])->where(['r.minor' => 1, 't.role_id <>' => 1, 'Applications.id' => $appID, 't.deleted IS' => null]);
     $attendeeLeaderCount = $applications->find()->hydrate(false)->join(['x' => ['table' => 'applications_attendees', 'type' => 'LEFT', 'conditions' => 'x.application_id = Applications.id'], 't' => ['table' => 'attendees', 'type' => 'INNER', 'conditions' => 't.id = x.attendee_id'], 'r' => ['table' => 'roles', 'type' => 'INNER', 'conditions' => 'r.id = t.role_id']])->where(['r.minor' => 0, 'Applications.id' => $appID, 't.deleted IS' => null]);
     // Load into Variables
     $predictedAttCubs = $attendeeCubCount->count(['t.id']);
     $predictedAttYls = $attendeeYlCount->count(['t.id']);
     $predictedAttLeaders = $attendeeLeaderCount->count(['t.id']);
     // Perform the Post
     if ($this->request->is('post')) {
         $numCubs = $this->request->data['cubs'];
         $numYls = $this->request->data['yls'];
         $numLeaders = $this->request->data['leaders'];
         $totalAtts = $numCubs + $numLeaders + $numYls;
         // Patch Items with Deposit Invoices
         if ($event->deposit) {
             $depValue = $event->deposit_value;
             $depDescription = $depositDescription;
             if ($event->deposit_inc_leaders) {
                 $depNum = $totalAtts;
             } else {
                 $depNum = $numCubs;
             }
         } else {
             $depValue = 0;
             $depDescription = 'No Deposit Required';
             $depNum = 0;
         }
         // Add Discount
         if (isset($discount) && $discount->active) {
             $disCubs = floor($numCubs / $discount->discount_number);
             $discountValue = $discount->discount_value;
             $discountDescription = 'Discount: ' . $discount->text;
         } else {
             $discountValue = 0;
             $discountDescription = 'No Discount Available';
             $disCubs = 0;
         }
         // Set Visiblity for Display
         if ($depNum > 0) {
             $DepVis = 1;
         } else {
             $DepVis = $event->deposit;
         }
         if ($numCubs > 0) {
             $CubsVis = 1;
         } else {
             $CubsVis = $event->cubs;
         }
         if ($numYls > 0) {
             $YlsVis = 1;
         } else {
             $YlsVis = $event->yls;
         }
         if ($numLeaders > 0) {
             $LeadersVis = 1;
         } else {
             $LeadersVis = $event->leaders;
         }
         if ($disCubs > 0) {
             $DisVis = 1;
         } elseif (isset($discount) && $discount->active) {
             $DisVis = 1;
         } else {
             $DisVis = 0;
         }
         // Patch Items with Standard Info
         $cubDeposit = ['invoice_id' => $invID, 'Value' => $depValue, 'Description' => $depDescription, 'Quantity' => $depNum, 'itemtype_id' => 1, 'visible' => $DepVis];
         $cubStandard = ['invoice_id' => $invID, 'Value' => $cubsEventPrice, 'Description' => $cubsDescription, 'Quantity' => $numCubs, 'itemtype_id' => 2, 'visible' => $CubsVis];
         $ylStandard = ['invoice_id' => $invID, 'Value' => $ylsEventPrice, 'Description' => $ylsDescription, 'Quantity' => $numYls, 'itemtype_id' => 3, 'visible' => $YlsVis];
         $leaderStandard = ['invoice_id' => $invID, 'Value' => $leadersEventPrice, 'Description' => $leadersDescription, 'Quantity' => $numLeaders, 'itemtype_id' => 4, 'visible' => $LeadersVis];
         $disStandard = ['invoice_id' => $invID, 'Value' => $discountValue, 'Description' => $discountDescription, 'Quantity' => $disCubs, 'itemtype_id' => 5, 'visible' => $DisVis];
         $existingCubDepItem = $this->InvoiceItems->patchEntity($existingCubDepItem, $cubDeposit);
         $existingCubItem = $this->InvoiceItems->patchEntity($existingCubItem, $cubStandard);
         $existingYlItem = $this->InvoiceItems->patchEntity($existingYlItem, $ylStandard);
         $existingLeaderItem = $this->InvoiceItems->patchEntity($existingLeaderItem, $leaderStandard);
         $existingDiscountItem = $this->InvoiceItems->patchEntity($existingDiscountItem, $disStandard);
         // REPEAT FOR CANCELLED
         $numCanCubs = $this->request->data['cancelled_cubs'];
         $numCanYls = $this->request->data['cancelled_yls'];
         $numCanLeaders = $this->request->data['cancelled_leaders'];
         $totalCancelled = $numCanCubs + $numCanLeaders + $numCanYls;
         $cancelledEver = MAX($totalCancelled, $totalExistingCancelled);
         // SET CANCELLED VISIBLITY
         if (MAX($existingCanCubDepQty, $cancelledEver) > 0) {
             $DepCanVis = 1;
         } else {
             $DepCanVis = 0;
         }
         if (MAX($existingCanCubQty, $numCanCubs) > 0) {
             $CubsCanVis = 1;
         } else {
             $CubsCanVis = 0;
         }
         if (MAX($existingCanYlQty, $numCanYls) > 0) {
             $YlsCanVis = 1;
         } else {
             $YlsCanVis = 0;
         }
         if (MAX($existingCanLeaderQty, $numCanLeaders) > 0) {
             $LeadersCanVis = 1;
         } else {
             $LeadersCanVis = 0;
         }
         // Patch Items with Deposit Invoices
         if ($event->deposit) {
             $depCanValue = $depositCanEventPrice;
             $depCanDescription = $depositCanDescription;
             if ($event->deposit_inc_leaders) {
                 $depCanNum = $totalCancelled;
             } else {
                 $depCanNum = $numCanCubs;
             }
         } else {
             $depCanValue = 0;
             $depCanDescription = 'No Deposit Required';
             $depCanNum = 0;
         }
         $depositCancelled = ['invoice_id' => $invID, 'Value' => $depCanValue, 'Description' => $depCanDescription, 'Quantity' => $depCanNum, 'itemtype_id' => 7, 'visible' => $DepCanVis];
         $existingCanCubDepItem = $this->InvoiceItems->patchEntity($existingCanCubDepItem, $depositCancelled);
         // Patch Items with Cancelled Info
         $cubCancelled = ['invoice_id' => $invID, 'Value' => $cubsCanEventPrice, 'Description' => $cubsCanDescription, 'Quantity' => $numCanCubs, 'itemtype_id' => 8, 'visible' => $CubsCanVis];
         $ylCancelled = ['invoice_id' => $invID, 'Value' => $ylsCanEventPrice, 'Description' => $ylsCanDescription, 'Quantity' => $numCanYls, 'itemtype_id' => 9, 'visible' => $YlsCanVis];
         $leaderCancelled = ['invoice_id' => $invID, 'Value' => $leadersCanEventPrice, 'Description' => $leadersCanDescription, 'Quantity' => $numCanLeaders, 'itemtype_id' => 10, 'visible' => $LeadersCanVis];
         $existingCanCubItem = $this->InvoiceItems->patchEntity($existingCanCubItem, $cubCancelled);
         $existingCanYlItem = $this->InvoiceItems->patchEntity($existingCanYlItem, $ylCancelled);
         $existingCanLeaderItem = $this->InvoiceItems->patchEntity($existingCanLeaderItem, $leaderCancelled);
         // SAVE THE ENTITIES AND COMPLETE
         if ($this->InvoiceItems->save($existingCubDepItem) && $this->InvoiceItems->save($existingCubItem) && $this->InvoiceItems->save($existingYlItem) && $this->InvoiceItems->save($existingLeaderItem) && $this->InvoiceItems->save($existingDiscountItem)) {
             if ($cancelledEver > 0) {
                 if ($this->InvoiceItems->save($existingCanCubDepItem) && $this->InvoiceItems->save($existingCanCubItem) && $this->InvoiceItems->save($existingCanYlItem) && $this->InvoiceItems->save($existingCanLeaderItem)) {
                     // SUCCESS
                     $this->Flash->success(__('The invoice has been repopulated with updated values.'));
                     return $this->redirect(['controller' => 'Invoices', 'action' => 'view', $invID]);
                 } else {
                     $this->Flash->error(__('There was an error with Cancellation.'));
                 }
             } else {
                 // SUCCESS
                 $this->Flash->success(__('The invoice has been repopulated with updated values.'));
                 return $this->redirect(['controller' => 'Invoices', 'action' => 'view', $invID]);
             }
         } else {
             $this->Flash->error(__('There was an error.'));
         }
     }
     $this->set(compact('invoiceItem', 'invoices'));
     $this->set('_serialize', ['invoiceItem']);
     $this->set('invPop', $invPop);
     // Set Field Loader Variables (for Get)
     if (isset($predictedAttCubs) && $predictedAttCubs > $existingCubQty) {
         if ($event->max && $predictedAttCubs >= $event->max_cubs) {
             $predictedCubs = $event->max_cubs;
             $this->Flash->error(__($limitTextCubs));
         } else {
             $predictedCubs = $predictedAttCubs;
         }
     } elseif ($event->max && $predictedAttCubs >= $event->max_cubs) {
         $predictedCubs = $event->max_cubs;
         $this->Flash->error(__($limitTextCubs));
     } else {
         $predictedCubs = $existingCubQty;
     }
     if (isset($predictedAttYls) && $predictedAttYls > $existingYlQty) {
         if ($event->max && $predictedAttYls >= $event->max_yls) {
             $predictedYls = $event->max_yls;
             $this->Flash->error(__($limitTextYls));
         } else {
             $predictedYls = $predictedAttYls;
         }
     } elseif ($event->max && $predictedAttYls >= $event->max_yls) {
         $predictedYls = $event->max_yls;
         $this->Flash->error(__($limitTextYls));
     } else {
         $predictedYls = $existingYlQty;
     }
     if (isset($predictedAttLeaders) && $predictedAttLeaders > $existingLeaderQty) {
         if ($event->max && $predictedAttLeaders >= $event->max_leaders) {
             $predictedLeaders = $event->max_leaders;
             $this->Flash->error(__($limitTextLeaders));
         } else {
             $predictedLeaders = $predictedAttLeaders;
         }
     } elseif ($event->max && $predictedAttLeaders >= $event->max_leaders) {
         $predictedLeaders = $event->max_leaders;
         $this->Flash->error(__($limitTextLeaders));
     } else {
         $predictedLeaders = $existingLeaderQty;
     }
     if ($this->request->is('get')) {
         // Values from the User Model e.g.
         $this->request->data['cubs'] = $predictedCubs;
         $this->request->data['yls'] = $predictedYls;
         $this->request->data['leaders'] = $predictedLeaders;
         $this->request->data['cancelled_cubs'] = $existingCanCubQty;
         $this->request->data['cancelled_yls'] = $existingCanYlQty;
         $this->request->data['cancelled_leaders'] = $existingCanLeaderQty;
         $this->set(compact('CubsVis', 'YlsVis', 'LeadersVis'));
     }
 }
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new EmployeeTransaction;
		$info=new EmployeeInfo;
		$user =new User;
		$photo =new EmployeePhotos;
		$address=new EmployeeAddress;
		$lang=new LanguagesKnown;
		$auth_assign = new AuthAssignment;


		// Uncomment the following line if AJAX validation is needed
		 $this->performAjaxValidation(array($info,$model,$user));

		if(!empty($_POST['EmployeeTransaction']) || !empty($_POST['EmployeeInfo']))
		{
			$model->attributes=$_POST['EmployeeTransaction'];
			$info->attributes=$_POST['EmployeeInfo'];
			$user->attributes=$_POST['User'];			
			
			$emp_roll_no = EmployeeInfo::model()->findAll();
			if(empty($emp_roll_no))
			{
			$empno=$info->employee_unique_id=1;
			}
			else
			{
			//$rand=mt_rand(1,2000);
				foreach($emp_roll_no as $s)
				{
		            		$emp[]=$s['employee_unique_id'];
					$empno_m=MAX($emp)+1;
				}		
				if(EmployeeInfo::model()->exists('employee_unique_id='.$empno_m))
				{
					$empno=$empno_m+1;
				}
				else
				{
					$empno=$empno_m;
				}			
			}
			$doa = $info->employee_joining_date;
			$dateofadmission = date("Y-m-d", strtotime($doa));
			$info->employee_joining_date = $dateofadmission;
			$info->employee_unique_id=$empno;
			$cardid_length = strlen((string) $info->employee_attendance_card_id);
			
			$cardid = $info->employee_attendance_card_id;
			$digit = 0;
			$diff = 10-$cardid_length;
			for($i=1;$i<=$diff;$i++)
			{
				$cardid = $digit.$cardid;
			}
			$info->employee_attendance_card_id = $cardid;
			$info->employee_private_email =strtolower($user->user_organization_email_id); 
			$info->employee_created_by = Yii::app()->user->id;
            		$info->employee_creation_date = new CDbExpression('NOW()');
			
			$user->user_organization_email_id = $info->employee_private_email;
			$user->user_password =  md5($info->employee_private_email.$info->employee_private_email);
			$user->user_created_by =  Yii::app()->user->id;
			$user->user_creation_date = new CDbExpression('NOW()');
			$user->user_type = "employee";
			if($info->save(false))  
			{  
			        $user->save(false);
				$address->save(false);
				$lang->save(false);			
				$photo->employee_photos_path = "no-images" ;
				$photo->save(false);
			}
			$model->employee_transaction_employee_id = $info->employee_id;
			$model->employee_transaction_user_id = $user->user_id;
			$model->employee_transaction_emp_photos_id = $photo->employee_photos_id;
	                $model->employee_transaction_emp_address_id = $address->employee_address_id;
			$model->employee_transaction_languages_known_id=$lang->languages_known_id;
			$model->employee_status = 0;

	        	$model->save(false); 
			EmployeeInfo::model()->updateByPk($model->employee_transaction_employee_id, array('employee_info_transaction_id'=>$model->employee_transaction_id));

			$auth_assign->itemname = 'Employee';
			$auth_assign->userid = $user->user_id;
			$auth_assign->bizrule = '';
			$auth_assign->data = '';
			$auth_assign->save(false);

			$this->redirect(array('update','id'=>$model->employee_transaction_id));

	 	}			 
		else
		{
			$this->render('create',array(
			'model'=>$model,'info'=>$info,'user'=>$user,
		));
		}
	}
 /**
  * Get the data to display for this table page.
  *
  * @param bool $download Flag to not include HTML for report download.
  * @return array An array of data records.
  */
 function get_data($download = false)
 {
     global $CURMAN;
     $LIKE = $CURMAN->db->sql_compare();
     if ($CURMAN->db->_dbconnection->databaseType == 'postgres7') {
         $FULLNAME = 'usr.firstname || \' \' || COALESCE(usr.mi, \'\') || \' \' || usr.lastname';
     } else {
         $FULLNAME = 'CONCAT(usr.firstname,\' \',IFNULL(usr.mi, \'\'),\' \',usr.lastname)';
     }
     $select = "SELECT cls.id as classid,\n                           cls.idnumber as classidnumber,\n                           crs.id as courseid,\n                           crs.idnumber as courseidnumber,\n                           crs.name as coursename,\n                           crs.credits as credits,\n                           stu.completetime as datecomplete,\n                           stu.completestatusid as completed,\n                           stu.grade as classgrade,\n                           stu.userid as userid\n                   ";
     $tables = "FROM " . $CURMAN->db->prefix_table(STUTABLE) . " stu\n                    INNER JOIN " . $CURMAN->db->prefix_table(CLSTABLE) . " cls ON cls.id = stu.classid\n                    INNER JOIN " . $CURMAN->db->prefix_table(CRSTABLE) . " crs ON crs.id = cls.courseid\n                   ";
     $where = "WHERE stu.userid = '{$this->usrid}' AND stu.completestatusid != 0 ";
     $sort = "ORDER BY datecomplete ASC ";
     /// Get the current 'page' of results.
     $sql = $select . $tables . $where . $sort;
     $data2 = $CURMAN->db->get_records_sql($sql);
     /// Add non-DB info to the records for display.
     $this->_maxexams = 0;
     if (!empty($data2)) {
         foreach ($data2 as $di => $datum) {
             if (!is_null($datum->classid) && !is_null($datum->userid)) {
                 /// Get any course element id's.
                 $select = 'SELECT cc.id, cc.courseid, cc.idnumber as elementname, ccg.id as ccgid,' . 'ccg.grade as grade,ccg.timegraded as timegraded ' . 'FROM ' . $CURMAN->db->prefix_table(CRSCOMPTABLE) . ' cc ' . 'LEFT JOIN ' . $CURMAN->db->prefix_table(CLSGRTABLE) . ' ccg ' . 'ON ccg.classid = ' . $datum->classid . ' AND ccg.userid = ' . $datum->userid . ' ' . 'AND ccg.completionid = cc.id ' . 'WHERE cc.courseid = ' . $datum->courseid . ' ' . 'ORDER BY id ASC';
             } else {
                 /// Get any course element id's.
                 $select = 'SELECT cc.id, cc.courseid, cc.idnumber as elementname ' . 'FROM ' . $CURMAN->db->prefix_table(CRSCOMPTABLE) . ' cc ' . 'WHERE cc.courseid = ' . $datum->courseid . ' ' . 'ORDER BY id ASC';
             }
             if (!($ccs = get_records_sql($select))) {
                 $ccs = array();
             }
             $this->_maxexams = MAX(count($ccs), $this->_maxexams);
             $i = 1;
             foreach ($ccs as $cc) {
                 $datum->{'ccid' . $i} = $cc->id;
                 $datum->{'ccelementname' . $i} = $cc->elementname;
                 $datum->{'ccgid' . $i} = isset($cc->ccgid) ? $cc->ccgid : '';
                 $datum->{'ccgrade' . $i} = isset($cc->grade) ? $cc->grade : '';
                 $datum->{'cctimegraded' . $i} = isset($cc->timegraded) ? !empty($cc->timegraded) ? date('M j, Y', $cc->timegraded) : '-' : '';
                 $i++;
             }
             if (!empty($datum->datecomplete) && !empty($datum->frequency)) {
                 switch ($datum->timeperiod) {
                     case 'year':
                         $datum->dnextdue = cm_timedelta($datum->datecomplete, $datum->frequency);
                         break;
                     case 'month':
                         $datum->dnextdue = cm_timedelta($datum->datecomplete, 0, $datum->frequency);
                         break;
                     case 'week':
                         $datum->dnextdue = cm_timedelta($datum->datecomplete, 0, 0, $datum->frequency);
                         break;
                     case 'day':
                         $datum->dnextdue = cm_timedelta($datum->datecomplete, 0, 0, 0, $datum->frequency);
                         break;
                     default:
                         $datum->dnextdue = 0;
                         break;
                 }
                 $datum->nextdue = !empty($datum->dnextdue) ? date('M j, Y', $datum->dnextdue) : '-';
             } else {
                 $datum->nextdue = '-';
             }
             if (!empty($datum->datecomplete)) {
                 $datum->datecomplete = !empty($datum->datecomplete) ? cm_timestamp_to_date($datum->datecomplete) : '<span style="color: red;">' . get_string('incomplete', 'block_curr_admin') . '</span>';
             } else {
                 $datum->datecomplete = '<span style="color: red;">' . get_string('incomplete', 'block_curr_admin') . '</span>';
             }
             switch ($datum->completed) {
                 case STUSTATUS_FAILED:
                     if (!$download) {
                         $datum->completestatus = '<span style="color: red;">' . get_string('failed', 'block_curr_admin') . '</span>';
                     } else {
                         $datum->completestatus = get_string('failed', 'block_curr_admin');
                     }
                     break;
                 case STUSTATUS_PASSED:
                     if (!$download) {
                         $datum->completestatus = '<span style="color: green;">' . get_string('complete', 'block_curr_admin') . '</span>';
                     } else {
                         $datum->completestatus = get_string('complete', 'block_curr_admin');
                     }
                     break;
                 case STUSTATUS_NOTCOMPLETE:
                 default:
                     $timenow = time();
                     if (!empty($datum->clsend) && $datum->clsend > $timenow && $datum->clsend - $timenow < 90 * 24 * 60 * 60) {
                         /// If the course is due within 90 days, colour code it accordingly.
                         if (!$download) {
                             $datum->completestatus = '<span style="color: red;">' . get_string('incomplete', 'block_curr_admin') . '</span>';
                         } else {
                             $datum->completestatus = get_string('incomplete', 'block_curr_admin');
                         }
                     } else {
                         if (!empty($datum->clsend) && $datum->clsend < $timenow) {
                             /// If the course is overdue, then display by how many days.
                             $timedelta = $timenow - $datum->clsend;
                             $timeday = 24 * 60 * 60;
                             // Number of seconds in a day.
                             if ($timedelta < $timeday) {
                                 if (!$download) {
                                     $datum->completestatus = '<span style="colur: red;">' . get_string('overdue_zero', 'block_curr_admin') . '</span>';
                                 } else {
                                     $datum->completestatus = get_string('overdue_zero', 'block_curr_admin');
                                 }
                             } else {
                                 $daysover = floor($timedelta / $timeday);
                                 if (!$download) {
                                     $datum->completestatus = '<span style="color: red;">' . get_string('overdue', 'block_curr_admin') . ': ' . $daysover . ($daysover > 1 ? get_string('duration_days', 'block_curr_admin') : get_string('duration_day', 'block_curr_admin')) . '</span>';
                                 } else {
                                     $datum->completestatus = 'Overdue: ' . $daysover . ($daysover > 1 ? get_string('duration_days', 'block_curr_admin') : get_string('duration_day', 'block_curr_admin'));
                                 }
                             }
                         } else {
                             if (!$download) {
                                 $datum->completestatus = '<span style="color: red;">' . get_string('incomplete', 'block_curr_admin') . '</span>';
                             } else {
                                 $datum->completestatus = get_string('incomplete', 'block_curr_admin');
                             }
                         }
                     }
                     break;
             }
             $datum->classpercent = $datum->classgrade;
             if (empty($datum->classpercent)) {
                 $datum->classpercent = 'I';
                 $datum->gradepoints = 0;
             } else {
                 if ($datum->classpercent >= 90) {
                     $datum->classgrade = 'A';
                     $datum->gradepoints = 4;
                 } else {
                     if ($datum->classpercent >= 80) {
                         $datum->classgrade = 'B';
                         $datum->gradepoints = 3;
                     } else {
                         if ($datum->classpercent >= 70) {
                             $datum->classgrade = 'C';
                             $datum->gradepoints = 2;
                         } else {
                             $datum->classgrade = 'I';
                             $datum->gradepoints = 0;
                         }
                     }
                 }
             }
             $data2[$di] = $datum;
         }
     }
     /// Organize the data into udergraduate and graduate courses
     $this->rawdata = array();
     if (!empty($data2)) {
         foreach ($data2 as $di2 => $datum2) {
             if ($datum2->courseidnumber[0] == 'M') {
                 $coursecat = 'grad';
                 $name = get_string('grad_courses', 'block_curr_admin');
             } else {
                 $coursecat = 'undergrad';
                 $name = get_string('undergrad_courses', 'block_curr_admin');
             }
             if (!isset($this->rawdata[$coursecat])) {
                 $this->rawdata[$coursecat] = new Object();
                 $this->rawdata[$coursecat]->curriculumname = $name;
                 $this->rawdata[$coursecat]->numcredits = 0;
                 $this->rawdata[$coursecat]->gpa = 0;
             }
             if ((int) $datum2->completed > 0) {
                 $this->rawdata[$coursecat]->numcredits += $datum2->credits;
                 $this->rawdata[$coursecat]->gpa += $datum2->gradepoints * $datum2->credits;
             }
             $this->rawdata[$coursecat]->data[] = clone $datum2;
         }
     }
 }
Esempio n. 20
0
function get_week_info($tabrange, $week, $resubmission = false)
{
    global $SESSION;
    $fnmaxtab = $DB->get_field('course_config_fn', 'value', array('courseid' => $this->course->id, 'variable' => 'maxtabs'));
    if ($fnmaxtab) {
        $maximumtabs = $fnmaxtab;
    } else {
        $maximumtabs = 12;
    }
    if ($this->course->numsections == $maximumtabs) {
        $tablow = 1;
        $tabhigh = $maximumtabs;
    } else {
        if ($tabrange > 1000) {
            $tablow = $tabrange / 1000;
            $tabhigh = $tablow + $maximumtabs - 1;
        } else {
            if ($tabrange == 0 && $week == 0) {
                $tablow = (int) ((int) ($this->course->numsections - 1) / (int) $maximumtabs) * $maximumtabs + 1;
                $tabhigh = $tablow + $maximumtabs - 1;
            } else {
                if ($tabrange == 0) {
                    $tablow = (int) ((int) $week / (int) $maximumtabs) * $maximumtabs + 1;
                    $tabhigh = $tablow + $maximumtabs - 1;
                } else {
                    $tablow = 1;
                    $tabhigh = $maximumtabs;
                }
            }
        }
    }
    $tabhigh = MIN($tabhigh, $this->course->numsections);
    /// Normalize the tabs to always display FNMAXTABS...
    if ($tabhigh - $tablow + 1 < $maximumtabs) {
        $tablow = $tabhigh - $maximumtabs + 1;
    }
    /// Save the low and high week in SESSION variables... If they already exist, and the selected
    /// week is in their range, leave them as is.
    if ($tabrange >= 1000 || !isset($SESSION->FN_tablow[$this->course->id]) || !isset($SESSION->FN_tabhigh[$this->course->id]) || $week < $SESSION->FN_tablow[$this->course->id] || $week > $SESSION->FN_tabhigh[$this->course->id]) {
        $SESSION->FN_tablow[$this->course->id] = $tablow;
        $SESSION->FN_tabhigh[$this->course->id] = $tabhigh;
    } else {
        $tablow = $SESSION->FN_tablow[$this->course->id];
        $tabhigh = $SESSION->FN_tabhigh[$this->course->id];
    }
    $tablow = MAX($tablow, 1);
    $tabhigh = MIN($tabhigh, $this->course->numsections);
    /// If selected week in a different set of tabs, move it to the current set...
    if ($week != 0 && $week < $tablow) {
        $week = $SESSION->G8_selected_week[$this->course->id] = $tablow;
    } else {
        if ($week > $tabhigh) {
            $week = $SESSION->G8_selected_week[$this->course->id] = $tabhigh;
        }
    }
    return array($tablow, $tabhigh, $week);
}
Esempio n. 21
0
 function EndStayEvent()
 {
     global $pricelist, $CONF, $db, $reslist;
     $LNG = $this->GetUserLang($this->_fleet['fleet_owner']);
     foreach ($reslist['fleet'] as $ID) {
         $Expowert[$ID] = ($pricelist[$ID]['metal'] + $pricelist[$ID]['crystal']) / 1000;
     }
     $Expowert[202] = 12;
     $Expowert[203] = 47;
     $Expowert[204] = 12;
     $Expowert[205] = 110;
     $Expowert[206] = 47;
     $Expowert[207] = 160;
     $farray = explode(";", $this->_fleet['fleet_array']);
     $FleetPoints = 0;
     $FleetCapacity = 0;
     foreach ($farray as $Item => $Group) {
         if (empty($Group)) {
             continue;
         }
         $Class = explode(",", $Group);
         $FleetCount[$Class[0]] = $Class[1];
         $FleetCapacity += $Class[1] * $pricelist[$Class[0]]['capacity'];
         $FleetPoints += $Class[1] * $Expowert[$Class[0]];
     }
     $FleetCapacity -= $this->_fleet['fleet_resource_metal'] + $this->_fleet['fleet_resource_crystal'] + $this->_fleet['fleet_resource_deuterium'] + $this->_fleet['fleet_resource_darkmatter'];
     $GetEvent = mt_rand(0, 10);
     switch ($GetEvent) {
         case 1:
             $WitchFound = mt_rand(1, 3);
             $FindSize = mt_rand(0, 100);
             if (10 < $FindSize) {
                 $WitchSize = 1;
                 $Factor = mt_rand(10, 50) / $WitchFound * $CONF['resource_multiplier'];
                 $Message = $LNG['sys_expe_found_ress_1_' . mt_rand(1, 4)];
             } elseif (0 < $FindSize && 10 >= $FindSize) {
                 $WitchSize = 2;
                 $Factor = mt_rand(52, 100) / $WitchFound * $CONF['resource_multiplier'];
                 $Message = $LNG['sys_expe_found_ress_2_' . mt_rand(1, 3)];
             } elseif (0 == $FindSize) {
                 $WitchSize = 3;
                 $Factor = mt_rand(102, 200) / $WitchFound * $CONF['resource_multiplier'];
                 $Message = $LNG['sys_expe_found_ress_3_' . mt_rand(1, 2)];
             }
             $StatFactor = $db->uniquequery("SELECT MAX(total_points) as total FROM `" . STATPOINTS . "` WHERE `stat_type` = 1;");
             $MaxPoints = $StatFactor['total'] < 5000000 ? 9000 : 12000;
             $Size = min($Factor * MAX(MIN($FleetPoints / 1000, $MaxPoints), 200), $FleetCapacity);
             switch ($WitchFound) {
                 case 1:
                     $this->UpdateFleet('fleet_resource_metal', $this->_fleet['fleet_resource_metal'] + $Size);
                     break;
                 case 2:
                     $this->UpdateFleet('fleet_resource_crystal', $this->_fleet['fleet_resource_crystal'] + $Size);
                     break;
                 case 3:
                     $this->UpdateFleet('fleet_resource_deuterium', $this->_fleet['fleet_resource_deuterium'] + $Size);
                     break;
             }
             break;
         case 2:
             $FindSize = mt_rand(0, 100);
             if (10 < $FindSize) {
                 $Size = mt_rand(100, 300);
                 $Message = $LNG['sys_expe_found_dm_1_' . mt_rand(1, 5)];
             } elseif (0 < $FindSize && 10 >= $FindSize) {
                 $Size = mt_rand(301, 600);
                 $Message = $LNG['sys_expe_found_dm_2_' . mt_rand(1, 4)];
             } elseif (0 == $FindSize) {
                 $Size = mt_rand(601, 3000);
                 $Message = $LNG['sys_expe_found_dm_3_' . mt_rand(1, 2)];
             }
             $this->UpdateFleet('fleet_resource_darkmatter', $this->_fleet['fleet_resource_darkmatter'] + $Size);
             break;
         case 3:
         default:
             unset($FleetCount[208]);
             unset($FleetCount[209]);
             unset($FleetCount[214]);
             $FindSize = mt_rand(0, 100);
             if (10 < $FindSize) {
                 $Size = mt_rand(2, 50);
                 $Message = $LNG['sys_expe_found_ships_1_' . mt_rand(1, 4)];
                 $MaxFound = 300000;
             } elseif (0 < $FindSize && 10 >= $FindSize) {
                 $Size = mt_rand(51, 100);
                 $Message = $LNG['sys_expe_found_ships_2_' . mt_rand(1, 2)];
                 $MaxFound = 600000;
             } elseif (0 == $FindSize) {
                 $Size = mt_rand(101, 200);
                 $Message = $LNG['sys_expe_found_ships_3_' . mt_rand(1, 2)];
                 $MaxFound = 1200000;
             }
             $StatFactor = $db->uniquequery("SELECT MAX(total_points) as total FROM `" . STATPOINTS . "` WHERE `stat_type` = 1;");
             $MaxPoints = $StatFactor['total'] < 5000000 ? 4500 : 6000;
             $FoundShips = max(min(round($Size * $FleetPoints), $MaxPoints), 10000);
             $MinFound = mt_rand(7000, 10000);
             $FoundShipMess = "";
             $NewFleetArray = "";
             $LNG += $this->GetUserLang($this->_fleet['fleet_owner'], 'TECH');
             foreach ($reslist['fleet'] as $ID) {
                 if (!isset($FleetCount[$ID])) {
                     continue;
                 }
                 $Count = mt_rand(1, floor($FoundShips / ($pricelist[$ID]['metal'] + $pricelist[$ID]['crystal'])));
                 $FleetCount[$ID] = bcadd($Count, $FleetCount[$ID]);
                 $NewFleetArray .= $ID . "," . floattostring($Count + $FleetCount[$ID]) . ";";
                 $FoundShips -= $Count * ($pricelist[$ID]['metal'] + $pricelist[$ID]['crystal']);
                 $FoundShipMess .= '<br>' . $LNG['tech'][$ID] . ': ' . pretty_number($Count);
                 if ($FoundShips <= 0) {
                     break;
                 }
             }
             $Message .= $FoundShipMess;
             foreach ($FleetCount as $ID => $Count) {
                 if (empty($Count)) {
                     continue;
                 }
             }
             $this->UpdateFleet('fleet_array', $NewFleetArray);
             $this->UpdateFleet('fleet_amount', array_sum($FleetCount));
             break;
         case 4:
             $Chance = mt_rand(1, 2);
             if ($Chance == 1) {
                 $Points = array(-3, -5, -8);
                 $Which = 1;
                 $Def = -3;
                 $Name = $LNG['sys_expe_attackname_1'];
                 $Add = 0;
                 $Rand = array(5, 3, 2);
                 $DefenderFleetArray = "204,5;206,3;207,2;";
             } else {
                 $Points = array(-4, -6, -9);
                 $Which = 2;
                 $Def = 3;
                 $Name = $LNG['sys_expe_attackname_2'];
                 $Add = 0.1;
                 $Rand = array(4, 3, 2);
                 $DefenderFleetArray = "205,5;215,3;213,2;";
             }
             $FindSize = mt_rand(0, 100);
             if (10 < $FindSize) {
                 $Message = $LNG['sys_expe_attack_' . $Which . '_1_' . $Rand[0]];
                 $MaxAttackerPoints = 0.3 + $Add + mt_rand($Points[0], abs($Points[0])) * 0.01;
             } elseif (0 < $FindSize && 10 >= $FindSize) {
                 $Message = $LNG['sys_expe_attack_' . $Which . '_2_' . $Rand[1]];
                 $MaxAttackerPoints = 0.3 + $Add + mt_rand($Points[1], abs($Points[1])) * 0.01;
             } elseif (0 == $FindSize) {
                 $Message = $LNG['sys_expe_attack_' . $Which . '_3_' . $Rand[2]];
                 $MaxAttackerPoints = 0.3 + $Add + mt_rand($Points[2], abs($Points[2])) * 0.01;
             }
             foreach ($FleetCount as $ID => $count) {
                 $DefenderFleetArray .= $ID . "," . round($count * $MaxAttackerPoints) . ";";
             }
             $AttackerTechno = $db->uniquequery('SELECT id,username,military_tech,defence_tech,shield_tech,rpg_amiral,dm_defensive,dm_attack FROM ' . USERS . ' WHERE id=' . $this->_fleet['fleet_owner'] . ";");
             $DefenderTechno = array('id' => 0, 'username' => $Name, 'military_tech' => min($AttackerTechno['military_tech'] + $Def, 0), 'defence_tech' => min($AttackerTechno['defence_tech'] + $Def, 0), 'shield_tech' => min($AttackerTechno['shield_tech'] + $Def, 0), 'rpg_amiral' => 0, 'dm_defensive' => 0, 'dm_attack' => 0);
             $attackFleets[$this->_fleet['fleet_id']]['fleet'] = $this->_fleet;
             $attackFleets[$this->_fleet['fleet_id']]['user'] = $AttackerTechno;
             $attackFleets[$this->_fleet['fleet_id']]['detail'] = array();
             $temp = explode(';', $this->_fleet['fleet_array']);
             foreach ($temp as $temp2) {
                 $temp2 = explode(',', $temp2);
                 if ($temp2[0] < 100) {
                     continue;
                 }
                 if (!isset($attackFleets[$this->_fleet['fleet_id']]['detail'][$temp2[0]])) {
                     $attackFleets[$this->_fleet['fleet_id']]['detail'][$temp2[0]] = 0;
                 }
                 $attackFleets[$this->_fleet['fleet_id']]['detail'][$temp2[0]] += $temp2[1];
             }
             $defense = array();
             $defRowDef = explode(';', $DefenderFleetArray);
             foreach ($defRowDef as $Element) {
                 $Element = explode(',', $Element);
                 if ($Element[0] < 100) {
                     continue;
                 }
                 if (!isset($defense[$defRow['fleet_id']]['def'][$Element[0]])) {
                     $defense[0][$Element[0]] = 0;
                 }
                 $defense[0]['def'][$Element[0]] += $Element[1];
             }
             $defense[0]['user'] = $DefenderTechno;
             require_once 'calculateAttack.' . PHP_EXT;
             $start = microtime(true);
             $result = calculateAttack($attackFleets, $defense);
             $totaltime = microtime(true) - $start;
             foreach ($attackFleets as $fleetID => $attacker) {
                 $fleetArray = '';
                 $totalCount = 0;
                 foreach ($attacker['detail'] as $element => $amount) {
                     if ($amount) {
                         $fleetArray .= $element . ',' . $amount . ';';
                     }
                     $totalCount += $amount;
                 }
                 if ($totalCount <= 0) {
                     $this->KillFleet();
                 } else {
                     $this->UpdateFleet('fleet_array', substr($fleetArray, 0, -1));
                     $this->UpdateFleet('fleet_amount', $totalCount);
                 }
             }
             require_once 'GenerateReport.' . PHP_EXT;
             $raport = GenerateReport($result, $INFO);
             $rid = md5(microtime(true) . mt_rand(1, 100));
             file_put_contents(ROOT_PATH . 'raports/raport_' . $rid . '.php', '<?php' . "\n" . '$raport = ' . $raport . ';' . "\n" . '?>');
             $SQLQuery = "INSERT INTO " . RW . " SET `time` = '" . TIMESTAMP . "', `owners` = '" . $this->_fleet['fleet_owner'] . ",0', `rid` = '" . $rid . "', `raport` = '';";
             $db->query($SQLQuery);
             switch ($result['won']) {
                 case "r":
                     $ColorAtt = "red";
                     $ColorDef = "green";
                     break;
                 case "w":
                     $ColorAtt = "orange";
                     $ColorDef = "orange";
                 case "a":
                     $ColorAtt = "green";
                     $ColorDef = "red";
                     break;
             }
             $MessageAtt = sprintf('<a href="CombatReport.php?raport=%s" onclick="OpenPopup(\'CombatReport.php?raport=%s\', \'combat\', screen.width, screen.height);return false" target="combat"><center><font color="%s">%s %s</font></a><br><br><font color="%s">%s: %s</font> <font color="%s">%s: %s</font><br>%s %s:<font color="#adaead">%s</font> %s:<font color="#ef51ef">%s</font> %s:<font color="#f77542">%s</font><br>%s %s:<font color="#adaead">%s</font> %s:<font color="#ef51ef">%s</font><br></center>', $rid, $rid, $ColorAtt, $LNG['sys_mess_attack_report'], sprintf($LNG['sys_adress_planet'], $this->_fleet['fleet_end_galaxy'], $this->_fleet['fleet_end_system'], $this->_fleet['fleet_end_planet']), $ColorAtt, $LNG['sys_perte_attaquant'], pretty_number($result['lost']['att']), $ColorDef, $LNG['sys_perte_defenseur'], pretty_number($result['lost']['def']), $LNG['sys_gain'], $LNG['Metal'], pretty_number($steal['metal']), $LNG['Crystal'], pretty_number($steal['crystal']), $LNG['Deuterium'], pretty_number($steal['deuterium']), $LNG['sys_debris'], $LNG['Metal'], pretty_number($result['debree']['att'][0] + $result['debree']['def'][0]), $LNG['Crystal'], pretty_number($result['debree']['att'][1] + $result['debree']['def'][1]));
             SendSimpleMessage($this->_fleet['fleet_owner'], '', $this->_fleet['fleet_start_time'], 3, $LNG['sys_mess_tower'], $LNG['sys_mess_attack_report'], $MessageAtt);
             break;
         case 5:
             $this->KillFleet();
             $Message = $LNG['sys_expe_lost_fleet_' . mt_rand(1, 4)];
             break;
         case 6:
             $MoreTime = mt_rand(0, 100);
             if ($MoreTime < 75) {
                 $this->UpdateFleet('fleet_end_time', $this->_fleet['fleet_end_time'] - TIMESTAMP * mt_rand(1, 5) + TIMESTAMP);
                 $Message = $LNG['sys_expe_time_slow_' . mt_rand(1, 6)];
             } else {
                 $this->UpdateFleet('fleet_end_time', round($this->_fleet['fleet_end_stay'] + ($this->_fleet['fleet_end_time'] - $this->_fleet['fleet_end_stay']) / 2));
                 $Message = $LNG['sys_expe_time_fast_' . mt_rand(1, 3)];
             }
             break;
         default:
             $Message = $LNG['sys_expe_nothing_' . mt_rand(1, 8)];
             break;
     }
     SendSimpleMessage($this->_fleet['fleet_owner'], '', $this->_fleet['fleet_end_stay'], 15, $LNG['sys_mess_tower'], $LNG['sys_expe_report'], $Message);
     $this->UpdateFleet('fleet_mess', 1);
     $this->SaveFleet();
 }
Esempio n. 22
0
function RTUnionRange(RTRange $lhsRange, RTRange $rhsRange)
{
    $location = min($lhsRange->location, $rhsRange->location);
    return RTMakeRange($location, MAX(RTMaxRange($lhsRange), RTMaxRange($rhsRange)) - $location);
}
Esempio n. 23
0
$arrQuizzesTopic = $hldGlobal->fnFetchCourse();
if (is_array($arrQuizzesTopic) && count($arrQuizzesTopic) > 0) {
    foreach ($arrQuizzesTopic as $key => $value) {
        $hdlTpl->setVariable("topic", $value["cname"]);
        //Assigns topic
        $hdlTpl->setVariable("qid", $value["id"]);
        //Assigns id
        $hdlTpl->setVariable("site_name", SITE_NAME);
        //Assigns site name
        $intCheckQuiz = $hldGlobal->fnCheckQuizExist($value["id"], 0, $_SESSION["UID"]);
        $strTake = "";
        if ($intCheckQuiz) {
            $arrResult = $hldGlobal->fnFetchQuizResult($value["id"], 0, $_SESSION["UID"]);
            $arrAvg = explode(",", $arrResult[0]["percent"]);
            $arrDate = explode(",", $arrResult[0]["takendate"]);
            $intPercent = MAX($arrAvg);
            $arrKey = array_keys($arrAvg, $intPercent);
            $strTake .= "<table><tr><td>";
            $strTake .= number_format($intPercent) . "%";
            $strTake .= "</td></tr><tr><td>";
            $strTake .= $arrDate[$arrKey[0]];
            $strTake .= "</td></tr></table>";
            $hdlTpl->setVariable("quiz_take", "Re-take!");
        } else {
            $hdlTpl->setVariable("quiz_take", "Take now!");
        }
        $hdlTpl->setVariable("result", $strTake);
        //Assigns Take now
        $hdlTpl->parse("quiz_topic");
    }
}
Esempio n. 24
0
            $progName = IO_MIDI_GM::getProgramName($prog);
            echo " {$prog}({$progName})";
        }
        echo PHP_EOL;
        if ($noteOnTable[$channel] === $noteOffTable[$channel]) {
            echo "        NoteOn/OffCount: " . $noteOnTable[$channel];
        } else {
            echo "        NoteOnCount: " . $noteOnTable[$channel];
            echo "  NoteOffCount: " . $noteOffTable[$channel];
        }
        $noteKeyList = array_keys($noteKeyTable[$channel]);
        echo "  KeyRange: " . MIN($noteKeyList) . " <-> " . MAX($noteKeyList);
        echo PHP_EOL;
        if ($pitchbendTable[$channel] > 0) {
            $pitchbendRangeList = array_keys($pitchbendRangeTable[$channel]);
            echo "        PitchBendCount: " . $pitchbendTable[$channel];
            echo "  PitchBendRange: " . MIN($pitchbendRangeList) . " <-> " . MAX($pitchbendRangeList);
        } else {
            echo "        PitchBend: (none)";
        }
        echo PHP_EOL;
        if (count($controllerTypeTable) > 0) {
            $controllerTypeList = array_keys($controllerTypeTable[$channel]);
            sort($controllerTypeList);
            echo "        ControllerType: " . implode(' ', $controllerTypeList);
        } else {
            echo "        ControllerType: (none)";
        }
        echo PHP_EOL;
    }
}
Esempio n. 25
0
		showtableheader('qqgroup_feed_setting', '', '', 2);
		showsetting('qqgroup_usergroup_feed_list', '', '', '<select name="groupid[]" multiple="multiple" size="10">'.$groupselect.'</select>');
		showsubmit('settingsubmit');
		showtablefooter();
		showformfooter();

	}
} elseif($_GET['anchor'] == 'block') {

	$perpage = 10;
	$maxPage = 10;
	$page = intval($_GET['page']);
	$page = MAX($page, 1);
	$page = MIN($page, $maxPage);

	$prevPage = MAX($page - 1, 1);
	$nextPage = MIN($page + 1, $maxPage);

	if(submitcheck('setMiniportalThreadsSubmit')) {

		$topic = $_GET['topic'];
		$topic = processMiniportalTopicThread($topic);
		if(!$topic) {
			cpmsg('qqgroup_msg_deficiency', '', 'error');
		}

		$normal = $_GET['normal'];
		$normal = processMiniportalNormalThreads($normal);
		if(!$normal) {
			cpmsg('qqgroup_msg_deficiency', '', 'error');
		}
Esempio n. 26
0
function processMergePlayers()
{
    // This script will merge 2 player ID's, setting the first one as .  Use with EXTREME cation!!
    global $cfg;
    $connection = @mysql_connect($cfg->get('db_host'), $cfg->get('db_user'), $cfg->get('db_pass'));
    @mysql_select_db($cfg->get('db_name'), $connection) or die("Database Error: " . mysql_error());
    // Get PlayerID's
    $pids = array();
    $pids[0] = $_POST['target_pid'] ? $_POST['target_pid'] : 0;
    // Target PID
    $pids[1] = $_POST['source_pid'] ? $_POST['source_pid'] : 0;
    // Source PID
    // Check PID Values
    if ($pids[0] == 0 || $pids[1] == 0) {
        showLog("<font color='red'>ERROR:</font> Data input missing!");
        return;
    }
    if ($pids[0] == $pids[1]) {
        showLog("<font color='red'>ERROR:</font> Target &amp; Source are Identical!!");
        return;
    }
    // Check Players Exist
    foreach ($pids as $pid) {
        if (!is_numeric($pid)) {
            showLog("<font color='red'>ERROR:</font> PID ({$pid}) is not a valid player!");
            return;
        }
        $query = "SELECT id FROM player WHERE id = {$pid}";
        $result = mysql_query($query);
        if (mysql_num_rows($result) == 1) {
            $pids_exist = true;
        } else {
            showLog("<<font color='red'>ERROR:</font> PID ({$pid}) is not a valid player!");
            return;
        }
    }
    // We are still here, so everything must have checked out
    showLog("Merging Player Data...");
    // Note: PID1 -->> PID0.  PID0 becomes the primary and PID1 is removed!  Make sure you get this RIGHT!!!!
    // Merge Single-line data tables
    $DataTables = array('army', 'kits', 'vehicles', 'weapons', 'player');
    foreach ($DataTables as $DataTable) {
        showLog(" -> Merging {$DataTable} table...");
        $query = "SELECT * FROM {$DataTable} WHERE id = {$pids[1]}";
        $result = mysql_query($query);
        if (mysql_num_rows($result) == 1) {
            $fieldCount = mysql_num_fields($result);
            $row = mysql_fetch_row($result);
            // Build Update Query
            $query = "UPDATE {$DataTable} SET ";
            for ($i = 1; $i < $fieldCount; $i++) {
                if (mysql_field_type($result, $i) == 'int') {
                    if ($DataTable == 'player' && mysql_field_name($result, $i) == 'joined') {
                        $query .= "`" . mysql_field_name($result, $i) . "` = " . $row[$i] . ",\n";
                    } elseif ($DataTable == 'player' && mysql_field_name($result, $i) == 'lastonline') {
                        $query .= "`" . mysql_field_name($result, $i) . "` = `" . mysql_field_name($result, $i) . "`,\n";
                    } elseif ($DataTable == 'player' && mysql_field_name($result, $i) == 'rndscore') {
                        $query .= "`" . mysql_field_name($result, $i) . "` = (SELECT IF(" . $row[$i] . " > `" . mysql_field_name($result, $i) . "`, " . $row[$i] . ", `" . mysql_field_name($result, $i) . "`)),\n";
                    } else {
                        $query .= "`" . mysql_field_name($result, $i) . "` = `" . mysql_field_name($result, $i) . "` + " . $row[$i] . ",\n";
                    }
                }
            }
            $query = rtrim($query, ",\n") . "\nWHERE id = {$pids[0]};";
            // Update Data
            if (mysql_query($query)) {
                showLog("\t\tSuccess!");
                // Remove Old Data
                $query = "DELETE FROM `{$DataTable}` WHERE id = {$pids[1]};";
                if (mysql_query($query)) {
                    showLog(" -> Old Player Data ({$DataTable}) Removed.");
                } else {
                    showLog("\t\t<font color='red'>ERROR:</font> " . mysql_error());
                }
            } else {
                showLog("\t\t<font color='red'>ERROR:</font> " . mysql_error());
                return;
            }
        } else {
            showLog("\t\tNo Data");
        }
    }
    // Reset Unlocks
    showLog(" -> Reseting Unlocks for Player ({$pids[0]})...");
    $query = "UPDATE unlocks SET state = 'n' WHERE (id = {$pids[0]})";
    if (mysql_query($query)) {
        $query = "UPDATE player SET availunlocks = 0, usedunlocks = 0 WHERE id = {$pids[0]}";
        mysql_query($query) or die(mysql_error());
        showLog("\t\tSuccess!");
        // Remove Old Unlocks Data
        showLog(" -> Removing Old Unlocks for Player ({$pids[1]})...");
        $query = "DELETE FROM unlocks WHERE (id = {$pids[1]})";
        if (mysql_query($query)) {
            showLog("\t\tUnlocks Removed!");
        } else {
            showLog("\t\t<font color='red'>ERROR:</font> Unlocks Removal Failed!" . mysql_error());
        }
    } else {
        showLog("\t\t<font color='red'>ERROR:</font> " . mysql_error());
        return;
    }
    // Merge Awards Data
    showLog(" -> Merging Awards table...");
    $query = "SELECT * FROM awards WHERE id = {$pids[1]};";
    $result = mysql_query($query);
    if (mysql_num_rows($result)) {
        while ($rowsrc = mysql_fetch_array($result)) {
            // Check Awards exist
            if ($rowsrc['awd']) {
                $query = "SELECT * FROM awards WHERE id = {$pids[0]} AND awd = " . $rowsrc['awd'] . ";";
                $chkresult = mysql_query($query);
                if (mysql_num_rows($chkresult)) {
                    // Update Award
                    $rowdest = mysql_fetch_array($chkresult);
                    $query = "UPDATE `awards` SET\n";
                    switch ($rowsrc['awd']) {
                        case 2051902:
                            // Gold
                        // Gold
                        case 2051907:
                            // Silver
                        // Silver
                        case 2051919:
                            // Bronze
                            $query .= "`level` = `level` + " . $rowsrc['level'] . ",\n";
                            break;
                        default:
                            $query .= "level = " . MAX($rowsrc['level'], $rowdest['level']) . ",\n";
                    }
                    $query .= "earned = " . MIN($rowsrc['earned'], $rowdest['earned']) . ",\n";
                    $query .= "first = " . MIN($rowsrc['first'], $rowdest['first']) . "\n";
                    $query .= "WHERE id = {$pids[0]} AND `awd` = " . $rowsrc['awd'] . ";";
                    if (mysql_query($query)) {
                        showLog("\t\tAward {$rowsrc[awd]} Update Success!");
                    } else {
                        showLog("\t\t<font color='red'>ERROR:</font> Award {$rowsrc[awd]} Update Failed: " . mysql_error());
                    }
                } else {
                    // Insert Award
                    $query = "INSERT INTO `awards` SET\n";
                    $query .= "`id` = {$pids[0]},\n";
                    $query .= "`awd` = " . $rowsrc['awd'] . ",\n";
                    $query .= "`level` = " . $rowsrc['level'] . ",\n";
                    $query .= "`earned` = " . $rowsrc['earned'] . ",\n";
                    $query .= "`first` = " . $rowsrc['first'] . ";";
                    if (mysql_query($query)) {
                        showLog("\t\tAward {$rowsrc[awd]} Insert Success!");
                    } else {
                        showLog("\t\t<font color='red'>ERROR:</font> Award {$rowsrc[awd]} Insert Failed: " . mysql_error());
                    }
                }
            } else {
                showLog("\t\t<font color='red'>ERROR:</font> Err, that shouldn't have happend! :(");
            }
        }
        showLog("\t\tAwards Table Merged!");
        // Remove Old Awards Data
        showLog(" -> Removing Old Awards for Player ({$pids[1]})...");
        $query = "DELETE FROM awards WHERE (id = {$pids[1]})";
        if (mysql_query($query)) {
            showLog("\t\tSuccess!");
        } else {
            showLog("\t\t<font color='red'>ERROR:</font> " . mysql_error());
        }
    }
    // Merge Maps Data
    showLog(" -> Merging Maps table...");
    $query = "SELECT * FROM `maps` WHERE `id` = {$pids[1]};";
    $result = mysql_query($query);
    if (mysql_num_rows($result)) {
        while ($rowsrc = mysql_fetch_array($result)) {
            // Check Map exist
            if ($rowsrc['mapid'] >= 0) {
                $query = "SELECT * FROM `maps` WHERE `id`= {$pids[0]} AND `mapid` = " . $rowsrc['mapid'] . ";";
                $chkresult = mysql_query($query);
                if (mysql_num_rows($chkresult)) {
                    // Update Map Data
                    $rowdest = mysql_fetch_array($chkresult);
                    $query = "UPDATE `maps` SET\n";
                    $query .= "`time` = `time` + " . $rowsrc['time'] . ",\n";
                    $query .= "`win` = `win` + " . $rowsrc['win'] . ",\n";
                    $query .= "`loss` = `loss` + " . $rowsrc['loss'] . ",\n";
                    if ($rowsrc['best'] > $rowdest['best']) {
                        $query .= "`best` = " . $rowsrc['best'] . ",\n";
                    }
                    if ($rowsrc['worst'] < $rowdest['worst']) {
                        $query .= "`worst` = `worst` + " . $rowsrc['worst'] . "\n";
                    }
                    $query .= "WHERE id = {$pids[0]} AND `mapid` = " . $rowsrc['mapid'] . ";";
                    if (mysql_query($query)) {
                        showLog("\t\tMap {$rowsrc[mapid]} Update Success!");
                    } else {
                        showLog("\t\t<font color='red'>ERROR:</font> Map {$rowsrc[mapid]} Update Failed: " . mysql_error());
                    }
                } else {
                    // Insert Map Data
                    $query = "INSERT INTO `maps` SET\n";
                    $query .= "`id` = {$pids[0]},\n";
                    $query .= "`mapid` = " . $rowsrc['mapid'] . ",\n";
                    $query .= "`time` = " . $rowsrc['time'] . ",\n";
                    $query .= "`win` = " . $rowsrc['win'] . ",\n";
                    $query .= "`loss` = " . $rowsrc['loss'] . ",\n";
                    $query .= "`best` = " . $rowsrc['best'] . ",\n";
                    $query .= "`worst` = " . $rowsrc['worst'] . ";";
                    if (mysql_query($query)) {
                        showLog("\t\tMap {$rowsrc[mapid]} Insert Success!");
                    } else {
                        showLog("\t\t<font color='red'>ERROR:</font> Map {$rowsrc[mapid]} Insert Failed: " . mysql_error());
                    }
                }
            } else {
                showLog("\t\t<font color='red'>ERROR:</font> MapID Invalid!");
            }
        }
        showLog("\t\tDone!");
        // Remove Old Maps Data
        showLog(" -> Removing Old Maps for Player ({$pids[1]})...");
        $query = "DELETE FROM maps WHERE (id = {$pids[1]})";
        if (mysql_query($query)) {
            showLog("\t\tSuccess!");
        } else {
            showLog("\t\t<font color='red'>ERROR:</font> " . mysql_error());
        }
    }
    // Update Kills Data
    showLog(" -> Updating Kills Data...");
    $query = "SELECT * FROM kills WHERE attacker = {$pids[1]};";
    $result = mysql_query($query);
    if (mysql_num_rows($result)) {
        while ($rowsrc = mysql_fetch_array($result)) {
            // Check Kills exist
            if ($rowsrc['victim']) {
                $query = "SELECT * FROM kills WHERE attacker = {$pids[0]} AND victim = " . $rowsrc['victim'] . ";";
                $chkresult = mysql_query($query);
                if (mysql_num_rows($chkresult)) {
                    // Update Existing record
                    $query = "UPDATE `kills` SET\n";
                    $query .= "`count` = `count` + " . $rowsrc['count'] . "\n";
                    $query .= "WHERE attacker = {$pids[0]} AND victim = " . $rowsrc['victim'] . ";";
                    if (mysql_query($query)) {
                        // Success
                    } else {
                        showLog("\t\t<font color='red'>ERROR:</font> Kills data not updated: " . mysql_error());
                    }
                } else {
                    // Insert Kills
                    $query = "INSERT INTO `kills` SET\n";
                    $query .= "attacker = {$pids[0]},\n";
                    $query .= "victim = " . $rowsrc['victim'] . ",\n";
                    $query .= "`count` = " . $rowsrc['count'] . ";";
                    if (mysql_query($query)) {
                        // Success
                    } else {
                        showLog("\t\t<font color='red'>ERROR:</font> Kills data not inserted: " . mysql_error());
                    }
                }
            } else {
                showLog("<font color='red'>#</font>");
            }
        }
        showLog("\t\tKills Done!");
        // Remove Old Kills Data
        showLog(" -> Removing Old Kills for Player ({$pids[1]})...");
        $query = "DELETE FROM kills WHERE (attacker = {$pids[1]})";
        if (mysql_query($query)) {
            showLog("\t\tSuccess!");
        } else {
            showLog("\t\t<font color='red'>ERROR:</font> " . mysql_error());
        }
    }
    // Update Deaths Data
    showLog(" -> Updating Deaths Data...");
    $query = "SELECT * FROM kills WHERE victim = {$pids[1]};";
    $result = mysql_query($query);
    if (mysql_num_rows($result)) {
        while ($rowsrc = mysql_fetch_array($result)) {
            // Check Deaths exist
            if ($rowsrc['attacker']) {
                $query = "SELECT * FROM kills WHERE attacker = " . $rowsrc['attacker'] . " AND victim = {$pids[0]};;";
                $chkresult = mysql_query($query);
                if (mysql_num_rows($chkresult)) {
                    // Update Existing record
                    $query = "UPDATE `kills` SET\n";
                    $query .= "`count` = `count` + " . $rowsrc['count'] . "\n";
                    $query .= "WHERE attacker = " . $rowsrc['attacker'] . " AND victim = {$pids[0]};";
                    if (mysql_query($query)) {
                        // Success
                    } else {
                        showLog("\t\t<font color='red'>ERROR:</font> Kills data not updated: " . mysql_error());
                    }
                } else {
                    // Insert Deaths
                    $query = "INSERT INTO `kills` SET\n";
                    $query .= "attacker = " . $rowsrc['attacker'] . ",\n";
                    $query .= "victim = {$pids[0]},\n";
                    $query .= "`count` = " . $rowsrc['count'] . ";";
                    if (mysql_query($query)) {
                        // Success
                    } else {
                        showLog("\t\t<font color='red'>ERROR:</font> Kills data not inserted: " . mysql_error());
                    }
                }
            } else {
                showLog("<font color='red'>#</font>");
            }
        }
        showLog("\t\tDeaths Done!");
        // Remove Old Deaths Data
        showLog(" -> Removing Old Deaths for Player ({$pids[1]})...");
        $query = "DELETE FROM kills WHERE (victim = {$pids[1]})";
        if (mysql_query($query)) {
            showLog("\t\tSuccess!");
        } else {
            showLog("\t\t<font color='red'>ERROR:</font> " . mysql_error());
        }
    }
    showLog("Done! :)\n");
    // Close database connection
    @mysql_close($connection);
    //Validating Rank
    $_POST['selitems'] = array($pids[0]);
    processValidateRanks();
    // Ensure Old player does not exist
    $_POST['selitems'] = array($pids[1]);
    processDeletePlayers();
}
 $currentweek = $timenow > $course->startdate ? (int) (($timenow - $course->startdate) / $weekofseconds + 1) : 0;
 $currentweek = min($currentweek, $course->numsections);
 $strftimedateshort = " " . get_string("strftimedateshort");
 /// If the selected_week variable is 0, all weeks are selected.
 if ($selected_week == -1 && $currentweek == 0) {
     $selected_week = 0;
     $section = $selected_week;
     $numsections = $course->numsections;
 } else {
     if ($selected_week == -1) {
         if (isteacher($course->id) || !empty($course->activitytracking) && ($selected_week = $cobject->first_unfinished_section()) === false) {
             $selected_week = $currentweek;
         }
         $selected_week = $selected_week > $currentweek ? $currentweek : $selected_week;
         $section = $selected_week;
         $numsections = MAX($section, 1);
     } else {
         if ($selected_week != 0) {
             /// Teachers can select a future week; students can't.
             if ($selected_week > $currentweek && !$isteacher) {
                 $section = $currentweek;
             } else {
                 $section = $selected_week;
             }
             $numsections = $section;
         } else {
             $numsections = $course->numsections;
         }
     }
 }
 $selected_week = $selected_week < 0 ? 1 : $selected_week;
 public function syncAll()
 {
     $usrs = $this->Users->find('all');
     $success = 0;
     $error = 0;
     foreach ($usrs as $userAll) {
         $user = $this->Users->get($userAll->id);
         $atts = TableRegistry::get('Attendees');
         $attRef = $atts->find('all')->where(['user_attendee' => true, 'user_id' => $user->id]);
         $attName = $atts->find('all')->where(['firstname' => $user->firstname, 'lastname' => $user->lastname, 'user_id' => $user->id]);
         $count = MAX($attRef->count(), $attName->count());
         if ($count == 1) {
             if ($attRef->count() == 1) {
                 $att = $attRef->first();
             } else {
                 $att = $attName->first();
             }
         } else {
             $newAttendeeData = ['dateofbirth' => '1990-01-01'];
             $att = $atts->newEntity($newAttendeeData);
         }
         $attendeeData = ['user_id' => $user->id, 'firstname' => $user->firstname, 'lastname' => $user->lastname, 'address_1' => $user->address_1, 'address_2' => $user->address_2, 'city' => $user->city, 'county' => $user->county, 'user_attendee' => true, 'postcode' => $user->postcode, 'role_id' => $user->role_id, 'scoutgroup_id' => $user->scoutgroup_id, 'phone' => $user->phone];
         $att = $atts->patchEntity($att, $attendeeData);
         if ($atts->save($att)) {
             $success = $success + 1;
         } else {
             $error = $error + 1;
         }
     }
     $this->Flash->error('There were ' . $error . ' Syncronisation Errors.');
     $this->Flash->success($success . ' Users were Syncronised.');
     return $this->redirect(['prefix' => 'admin', 'controller' => 'Users', 'action' => 'index']);
 }
Esempio n. 29
0
 public function SourceTransparentColorMask(&$gdimg, $hexcolor, $min_limit = 5, $max_limit = 10)
 {
     $width = ImageSX($gdimg);
     $height = ImageSY($gdimg);
     if ($gdimg_mask = ImageCreateTrueColor($width, $height)) {
         $R = hexdec(substr($hexcolor, 0, 2));
         $G = hexdec(substr($hexcolor, 2, 2));
         $B = hexdec(substr($hexcolor, 4, 2));
         $targetPixel = array('red' => $R, 'green' => $G, 'blue' => $B);
         $cutoffRange = $max_limit - $min_limit;
         for ($x = 0; $x < $width; $x++) {
             for ($y = 0; $y < $height; $y++) {
                 $currentPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
                 $colorDiff = phpthumb_functions::PixelColorDifferencePercent($currentPixel, $targetPixel);
                 $grayLevel = min($cutoffRange, MAX(0, -$min_limit + $colorDiff)) * (255 / MAX(1, $cutoffRange));
                 $newColor = ImageColorAllocate($gdimg_mask, $grayLevel, $grayLevel, $grayLevel);
                 ImageSetPixel($gdimg_mask, $x, $y, $newColor);
             }
         }
         return $gdimg_mask;
     }
     return false;
 }
Esempio n. 30
0
 if ($tpcolonists == -1 && $transfer_colonists > $playerinfo['ship_colonists']) {
     $transfer_colonists = $playerinfo['ship_colonists'];
     echo "{$l_planet2_noten} {$l_colonists}. {$l_planet2_settr} {$transfer_colonists} {$l_colonists}.<br>\n";
 } elseif ($tpcolonists == 1 && $transfer_colonists > $planetinfo['colonists']) {
     $transfer_colonists = $planetinfo['colonists'];
     echo "{$l_planet2_losup} {$transfer_colonists} {$l_colonists}.<br>\n";
 }
 if ($tpcredits == -1 && $transfer_credits > $playerinfo['credits']) {
     $transfer_credits = $playerinfo['credits'];
     echo "{$l_planet2_noten} {$l_credits}. {$l_planet2_settr} {$transfer_credits} {$l_credits}.<br>\n";
 } elseif ($tpcredits == 1 && $transfer_credits > $planetinfo['credits']) {
     $transfer_credits = $planetinfo['credits'];
     echo "{$l_planet2_losup} {$transfer_credits} {$l_credits}.<br>\n";
 }
 if ($tpcredits == -1 && $planetinfo['base'] == 'N' && $transfer_credits + $planetinfo['credits'] > $max_credits_without_base) {
     $transfer_credits = MAX($max_credits_without_base - $planetinfo['credits'], 0);
     echo "{$l_planet2_baseexceeded} {$l_planet2_settr} {$transfer_credits} {$l_credits}.<br>\n";
 }
 if ($tptorps == -1 && $transfer_torps > $playerinfo['torps']) {
     $transfer_torps = $playerinfo['torps'];
     echo "{$l_planet2_noten} {$l_torps}. {$l_planet2_settr} {$transfer_torps} {$l_torps}.<br>\n";
 } elseif ($tptorps == 1 && $transfer_torps > $planetinfo['torps']) {
     $transfer_torps = $planetinfo['torps'];
     echo "{$l_planet2_losup} {$transfer_torps} {$l_torps}.<br>\n";
 }
 if ($tpfighters == -1 && $transfer_fighters > $playerinfo['ship_fighters']) {
     $transfer_fighters = $playerinfo['ship_fighters'];
     echo "{$l_planet2_noten} {$l_fighters}. {$l_planet2_settr} {$transfer_fighters} {$l_fighters}.<br>\n";
 } elseif ($tpfighters == 1 && $transfer_fighters > $planetinfo['fighters']) {
     $transfer_fighters = $planetinfo['fighters'];
     echo "{$l_planet2_losup} {$transfer_fighters} {$l_fighters}.<br>\n";