Regarding pagination in cakephp 2.0 with order by - php

How to deal with order by with different models.For e.g. i have an CareseekerJob model which is in association(belongsTO) with city,state,category and user model.I am doing searching and want to sort the job with price but it is taking by default paging of job table.
Please refer the code:-
$searchdata = array();
$conditioncat = '';
$conditionsearch = '';
if(!empty($categories) && $categories!='-1')
{
$conditioncat = 'CareseekerJob.category_id IN ('.$categories.') ';
}
if($categories == '-1')
{
$conditionserv = '(1 = 1) ';
}
$conditionserv = '';
if(!empty($services) && $services!='-1')
{
$serviceses = explode(',',$services);
$servicename = '';
$con = '(1 = 1) AND '; $i='0';
$servicename = '';
foreach($serviceses as $key=>$value)
{ $i++;
$servicedata = $this->Service->find('first',array('conditions'=>array('Service.id'=>$value)));
$servicename = $servicedata['Service']['name'];
$con .= '(CareseekerJob.services LIKE "%'.$servicename.'%")' ;
if(count($serviceses) == $i){
$con .= ' ';
}else{
$con .= ' OR ';
}
}
$conditionserv = $con;
}
if($services == '-1')
{
$conditionserv = '(1 = 1) ';
}
$conditiontime = '';
if($timingess != '1')
{
$start = '';
$end = '';
if($timingess == 'morning')
{
$start = date('H:i:s',strtotime('00:00:00'));
$end = date('H:i:s',strtotime('11:59:00'));
}
elseif($timingess == 'afternoon')
{
$start = date('H:i:s',strtotime('11:59:00'));
$end = date('H:i:s',strtotime('16:00:00'));
}
elseif($timingess == 'evening')
{
$start = date('H:i:s',strtotime('16:00:00'));
$end = date('H:i:s',strtotime('20:00:00'));
}
elseif($timingess == 'night')
{
$start = date('H:i:s',strtotime('20:00:00'));
$end = date('H:i:s',strtotime('23:59:00'));
}
elseif($timingess == 'morning,afternoon')
{
$start = date('H:i:s',strtotime('00:00:00'));
$end = date('H:i:s',strtotime('16:00:00'));
}
elseif($timingess == 'morning,evening')
{
$start = date('H:i:s',strtotime('00:00:00'));
$end = date('H:i:s',strtotime('20:00:00'));
}
elseif($timingess == 'morning,afternoon,evening')
{
$start = date('H:i:s',strtotime('00:00:00'));
$end = date('H:i:s',strtotime('20:00:00'));
}
elseif($timingess == 'morning,afternoon,evening,night')
{
$start = date('H:i:s',strtotime('00:00:00'));
$end = date('H:i:s',strtotime('23:59:00'));
}
$conditiontime = "( TIME(CareseekerJob.starttime) >= TIME('".$start."') and TIME(CareseekerJob.starttime) <= TIME('".$end."') ) ";
}
if($timingess == '1')
{
$conditiontime = '(1 = 1) ';
}
$conditionsearch = "";
$conditionZip = "";
if($searchtext != 1)
{
if(is_numeric($searchtext))
{
$url1 = "https://maps.googleapis.com/maps/api/geocode/xml?address=" . $searchtext . "&sensor=false";
$details = simplexml_load_file($url1);
if ($details->status == 'OK') {
$sourceLat = $details->result->geometry->location->lat;
$sourceLon = $details->result->geometry->location->lng;
$radiusKm = 160.934;
$proximity = $this->Radiussearch->mathGeoProximity($sourceLat, $sourceLon, $radiusKm);
$latmin=min($proximity["latitudeMin"],$proximity["latitudeMax"]);
$latmax=max($proximity["latitudeMin"],$proximity["latitudeMax"]);
$lonmin=min($proximity["longitudeMin"],$proximity["longitudeMax"]);
$lonmax=max($proximity["longitudeMin"],$proximity["longitudeMax"]);
$conditionZip=array("CareseekerJob.lat BETWEEN ? AND ?" => array(number_format(min($proximity["latitudeMin"],$proximity["latitudeMax"]), 12, ".", ""), number_format(max($proximity["latitudeMin"],$proximity["latitudeMax"]), 12, ".", "")),"CareseekerJob.long BETWEEN ? AND ?"=> array(number_format(max($proximity["longitudeMin"],$proximity["longitudeMax"]), 12, ".", ""),number_format(min($proximity["longitudeMin"],$proximity["longitudeMax"]), 12, ".", "")));
}
$conditionsearch = '(1 = 1)';
}
else{
$conditionsearch= array('OR'=>array('CareseekerJob.title LIKE'=>'%'.$searchtext.'%','CareseekerJob.zipcode'=>$searchtext));
}
}else{
$conditionZip = '(1 = 1)';
$conditionsearch = '(1 = 1)';
}
if($sort =='recent' )
{
$condition= array('CareseekerJob.job_status'=>'jobactive','CareseekerJob.is_deleted'=>0,'CareseekerJob.status'=>'active');
$this->paginate = array(
'conditions' => array('AND'=>array($condition,$conditioncat,$conditiontime,$conditionserv,$conditionsearch,$conditionZip)),
'limit' => 4,
'order' => array(
'CareseekerJob.id' => 'desc'
)
);
$searchdata = $this->paginate('CareseekerJob');
}
elseif($sort =='distance' )
{
$condition= array('CareseekerJob.job_status'=>'jobactive','CareseekerJob.is_deleted'=>0,'CareseekerJob.status'=>'active');
$this->paginate = array(
'conditions' => array('AND'=>array($condition,$conditioncat,$conditiontime,$conditionserv,$conditionsearch,$conditionZip)),
'limit' => 4,
'order' => array(
'CareseekerJob.lat' => 'desc'
),
);
$searchdata = $this->paginate('CareseekerJob');
}elseif($sort =='price')
{
$condition= array('CareseekerJob.job_status'=>'jobactive','CareseekerJob.is_deleted'=>0,'CareseekerJob.status'=>'active');
$this->paginate = array(
'conditions' => array('AND'=>array($condition,$conditioncat,$conditiontime,$conditionserv,$conditionsearch,$conditionZip)),
'limit' => 4,
'order' => array(
'CareseekerJob.rate' => 'desc'
)
);
$searchdata = $this->paginate('CareseekerJob');
}

Related

Issue with PHPWORD

I am using draftjs and phpword. FRom draftjs had a json objects using that i am constructing a word file. After that i am trying to merge the target file and template file which already stored. After merge the template using converting both source and target file into XML format by using this writing the target file filled with the contents stored in source document.
I got the unusual XML formatting fromthe source file.
generate.php
<?php
$listFormatNumOL = 1;
$listFormatNumUL = 1;
function makeWordStrings($section, $decoded, $demographics, $calledSnapshot, $tabSize, $defaultIndent){
$removeBlanks = 0;
$lineStays = 0;
$allBlanks = array();
$blanksCondition = array();
foreach($decoded['blocks'] AS $k=>$v){
$styles = array();
$offset = array();
$breakOffset = array();
$breakOffset[0] = 1;
$text = $v['text'];
$breakOffset[mb_strlen($text)] = 1;
foreach($v['inlineStyleRanges'] AS $l=>$m){
$breakOffset[$m['offset']] = 1;
$breakOffset[$m['offset'] + $m['length']] = 1;
}
$breakOffset = array_keys($breakOffset);
sort($breakOffset);
for($i=1; $i<sizeof($breakOffset); $i++){
foreach($v['inlineStyleRanges'] AS $l=>$m){
if($m['offset'] <= $breakOffset[$i-1] && ($m['offset']+$m['length']) >= $breakOffset[$i]){
if(!isset($styles[$breakOffset[$i-1]]))
$styles[$breakOffset[$i-1]] = array();
$wer = getStyle($m['style']);
$styles[$breakOffset[$i-1]][$wer[0]] = $wer[1];
$offset[$breakOffset[$i-1]] = $breakOffset[$i] - $breakOffset[$i-1];
}
}
}
ksort($offset);
$strarr = array();
if($text == "*****PAGE BREAK - TYPE FROM NEXT LINE*****"){
$section -> addPageBreak();
continue;
}
if($text == '{{content}}'){
$newindent = $defaultIndent;
foreach($v['data'] AS $l=>$m){
foreach($m AS $x=>$y){
if($x == 'indentation')
$newindent += intval($y>0?$y:0);
}
}
makeWordStrings($section, $calledSnapshot, $demographics, '', $tabSize, $newindent);
continue;
}
if(mb_stripos($text, '([[') === 0){
$removeBlanks = 1;
$lineStays = 1;
}
else if(mb_stripos($text, '[[') === 0){
$removeBlanks = 1;
}
if(!empty($offset))
{
$it = 0;
foreach($offset AS $l=>$m){
$strarr[$it] = mb_substr($text, $it, $l-$it);
$strarr[$l] = mb_substr($text, $l, $m);
$it = $l + $m;
}
$strarr[$it] = mb_substr($text, $it);
}
else{
$strarr[0] = $text;
}
$paragraphStyles = array('lineHeight'=>1, 'indentation'=>array('left'=>intval(ceil($tabSize * $defaultIndent * 15 * 48 / 1.27))));
foreach($v['data'] AS $l=>$m){
foreach($m AS $x=>$y){
if($x == 'lineHeight')
$paragraphStyles['lineHeight'] = $y;
else if($x == 'indentation'){
$paragraphStyles['indentation']['left'] = intval(ceil($tabSize * ($y + $defaultIndent) * 15 * 48 / 1.27));
}
else if($x == 'hanging'){
$paragraphStyles['indentation']['hanging'] = intval(ceil($tabSize * $y * 15 * 48 / 1.27));
$paragraphStyles['indentation']['left'] = intval(ceil($tabSize * ($y + $defaultIndent) * 15 * 48 / 1.27));
}
else if($x == 'textAlign')
{
switch($y){
case 'left':
$paragraphStyles['alignment'] = 'left';
break;
case 'right':
$paragraphStyles['alignment'] = 'right';
break;
case 'center':
$paragraphStyles['alignment'] = 'center';
break;
case 'justify':
$paragraphStyles['alignment'] = 'both';
break;
}
}
}
}
if($lineStays == 1){
array_push($blanksCondition, convertKeysToValues($text, $demographics)[1]);
array_push($allBlanks, array($v, $strarr, $paragraphStyles, $offset, $styles));
}
else if($removeBlanks == 1){
$bg = convertKeysToValues($text, $demographics);
if($bg[1] == 0){
$section = addToDoc($section, $v, $strarr, $paragraphStyles, $demographics, $offset, $styles, $decoded, $tabSize, $defaultIndent);
}
}
else
$section = addToDoc($section, $v, $strarr, $paragraphStyles, $demographics, $offset, $styles, $decoded, $tabSize, $defaultIndent);
$removeBlanks = 0;
if(mb_stripos($text, ']])') + 3 == mb_strlen($text)){
if(!in_array(0, $blanksCondition))
{
foreach($allBlanks AS $n=>$m){
$section = addToDoc($section, $m[0], array(''), $m[2], $demographics, array(), $m[4], $decoded, $tabSize, $defaultIndent);
}
}
else{
foreach($allBlanks AS $n=>$m){
if($blanksCondition[$n] == 0){
$section = addToDoc($section, $m[0], $m[1], $m[2], $demographics, $m[3], $m[4], $decoded, $tabSize, $defaultIndent);
}
}
}
$lineStays = 0;
$allBlanks = array();
$blanksCondition = array();
}
}
}
function str_split_unicode($str, $l = 0) {
if ($l > 0) {
$ret = array();
$len = mb_strlen($str, "UTF-8");
for ($i = 0; $i < $len; $i += $l) {
$ret[] = mb_substr($str, $i, $l, "UTF-8");
}
return $ret;
}
return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}
function addToDoc($section, $v, $strarr, $paragraphStyles, $demographics, $offset, $styles, $decoded, $tabSize, $defaultIndent){
global $phpWord;
global $listFormatNumOL, $listFormatNumUL;
$moveahead = 1;
$newindent = $defaultIndent;
foreach($v['data'] AS $l=>$m){
foreach($m AS $x=>$y){
if($x == 'indentation')
$newindent += intval($y>0?$y:0);
}
}
$phpWord->addNumberingStyle(
'ordered_list-'.$listFormatNumOL,
array(
'type' => 'singleLevel',
'levels' => array(
array('format' => 'decimal', 'text' => '%1.', 'left' => 360, 'hanging' => 360, 'tabPos' => 360),
array('format' => 'upperLetter', 'text' => '%2.', 'left' => 720, 'hanging' => 360, 'tabPos' => 720),
),
)
);
$predefinedMultilevel = array('listType' => \PhpOffice\PhpWord\Style\ListItem::TYPE_BULLET_FILLED);
foreach($v['entityRanges'] AS $t=>$h){
if($decoded['entityMap'][$h['key']]['type'] == 'TABLE')
{
$moveahead = 0;
$tabledata = $decoded['entityMap'][$h['key']]['data'];
$table = $section->addTable(array('borderSize' => 6, 'borderColor' => '999999', 'indent'=> new PhpOffice\PhpWord\ComplexType\TblWidth(ceil($tabSize * $newindent * 15 * 48 / 1.27)), 'width'=>100*50 - ceil($tabSize * $newindent * 15 * 48 * 20 / (50 * 1.27)), 'unit'=>\PhpOffice\PhpWord\Style\Table::WIDTH_PERCENT, 'layout'=>PhpOffice\PhpWord\Style\Table::LAYOUT_FIXED));
foreach($tabledata['table'] AS $z=>$p){
$table->addRow();
foreach($p AS $t=>$f){
$celltr = $table->addCell();
$celltr = makeWordStrings($celltr, json_decode($f, true), $demographics, '', $tabSize, 0);
}
}
}
}
if($moveahead){
if($v['type'] == 'unstyled'){
$listFormatNumUL++;
$listFormatNumOL++;
if(sizeof($strarr)==1 && $strarr[0]==''){
$erstyle = array();
foreach($v['inlineStyleRanges'] AS $l=>$m){
$wer = getStyle($m['style']);
$erstyle[$wer[0]] = $wer[1];
}
if(!empty($erstyle))
{
$section->addTextBreak(1, $erstyle, $paragraphStyles);
}
else
$section->addTextBreak(1, null, $paragraphStyles);
}
else{
$startOffset = 0;
$comments = array();
foreach($v['entityRanges'] AS $t=>$h){
if($decoded['entityMap'][$h['key']]['type'] == 'COMMENT')
{
$commentdata = $decoded['entityMap'][$h['key']]['data'];
foreach($commentdata['comment'] AS $z=>$p){
$comm = new \PhpOffice\PhpWord\Element\Comment($p['user'], new \DateTime(), 'my_initials');
$comm->addText($p['comment']);
array_push($comments, array('start'=>$h['offset'], 'end'=>$h['offset']+$h['length'] - 1, 'comm'=>$comm));
}
}
}
$textrun = $section->addTextRun($paragraphStyles);
$strarr = afterClearingExtraSpaces($strarr, $demographics);
foreach($strarr AS $l=>$m){
$democonv = $m;
if(mb_strlen($democonv) > 0){
$supbreak = explode('<sup>', $democonv);
if(sizeof($supbreak) > 1){
$newst = $styles[$l];
$newst['superScript'] = true;
$textrun->addText($supbreak[0], $styles[$l], array('tabs' => array(new \PhpOffice\PhpWord\Style\Tab('left', 1550))));
$textrun->addText($supbreak[1], $newst, array('tabs' => array(new \PhpOffice\PhpWord\Style\Tab('left', 1550))));
$textrun->addText($supbreak[2], $styles[$l], array('tabs' => array(new \PhpOffice\PhpWord\Style\Tab('left', 1550))));
}
else{
$breakstring = str_split_unicode($democonv, 1);
$nextcapital = 1;
foreach($breakstring AS $z=>$p){
if(!isset($offset[$l])){
$retext = xmlEntities($p);
if($retext == "\n")
$textToComment = $textrun->addTextBreak();
else
$textToComment = $textrun->addText($retext, null, array('tabs' => array(new \PhpOffice\PhpWord\Style\Tab('left', 1550))));
}
else{
$retext = xmlEntities($nextcapital?convertToProperCase($p, $styles[$l]):$p);
if($retext == "\n")
$textToComment = $textrun->addTextBreak();
else
$textToComment = $textrun->addText($retext, $styles[$l], array('tabs' => array(new \PhpOffice\PhpWord\Style\Tab('left', 1550))));
}
foreach($comments AS $q=>$w){
if($w['start'] == $z+$startOffset+$q)
$w['comm']->setStartElement($textToComment);
if($w['end'] == $z+$startOffset-$q)
$w['comm']->setEndElement($textToComment);
}
if($p == ' ')
$nextcapital = 1;
else
$nextcapital = 0;
}
$startOffset += sizeof($breakstring);
}
}
}
foreach($comments AS $q=>$w){
$phpWord->addComment($w['comm']);
}
}
}
if($v['type'] == 'unordered-list-item'){
$listFormatNumUL++;
$tempPS = $paragraphStyles;
unset($tempPS['indentation']);
$listItemRun = $section->addListItemRun($v['depth'], $predefinedMultilevel, $tempPS);
if(sizeof($strarr)==1 && $strarr[0]==''){
$erstyle = array();
foreach($v['inlineStyleRanges'] AS $l=>$m){
$wer = getStyle($m['style']);
$erstyle[$wer[0]] = $wer[1];
}
if(!empty($erstyle))
$listItemRun->addText("", $erstyle);
else
$listItemRun->addText("");
}
else{
$startOffset = 0;
$comments = array();
foreach($v['entityRanges'] AS $t=>$h){
if($decoded['entityMap'][$h['key']]['type'] == 'COMMENT')
{
$commentdata = $decoded['entityMap'][$h['key']]['data'];
foreach($commentdata['comment'] AS $z=>$p){
$comm = new \PhpOffice\PhpWord\Element\Comment($p['user'], new \DateTime(), 'my_initials');
$comm->addText($p['comment']);
array_push($comments, array('start'=>$h['offset'], 'end'=>$h['offset']+$h['length'] - 1, 'comm'=>$comm));
}
}
}
$strarr = afterClearingExtraSpaces($strarr, $demographics);
foreach($strarr AS $l=>$m){
$democonv = $m;
if(mb_strlen($democonv) > 0){
$breakstring = str_split_unicode($democonv, 1);
$nextcapital = 1;
foreach($breakstring AS $z=>$p){
if(!isset($offset[$l])){
$retext = xmlEntities($p);
if($retext == "\n")
$textToComment = $listItemRun->addTextBreak();
else
$textToComment = $listItemRun->addText($retext, null, array('tabs' => array(new \PhpOffice\PhpWord\Style\Tab('left', 1550))));
}
else{
$retext = xmlEntities($nextcapital?convertToProperCase($p, $styles[$l]):$p);
if($retext == "\n")
$textToComment = $listItemRun->addTextBreak();
else
$textToComment = $listItemRun->addText($retext, $styles[$l], array('tabs' => array(new \PhpOffice\PhpWord\Style\Tab('left', 1550))));
}
foreach($comments AS $q=>$w){
if($w['start'] == $z+$startOffset+$q)
$w['comm']->setStartElement($textToComment);
if($w['end'] == $z+$startOffset-$q)
$w['comm']->setEndElement($textToComment);
}
if($p == ' ')
$nextcapital = 1;
else
$nextcapital = 0;
}
$startOffset += sizeof($breakstring);
}
}
foreach($comments AS $q=>$w){
$phpWord->addComment($w['comm']);
}
}
}
if($v['type'] == 'ordered-list-item'){
$listFormatNumUL++;
$tempPS = $paragraphStyles;
unset($tempPS['indentation']);
$listItemRun = $section->addListItemRun($v['depth'], 'ordered_list-'.$listFormatNumOL, $tempPS);
if(sizeof($strarr)==1 && $strarr[0]==''){
$erstyle = array();
foreach($v['inlineStyleRanges'] AS $l=>$m){
$wer = getStyle($m['style']);
$erstyle[$wer[0]] = $wer[1];
}
if(!empty($erstyle))
$listItemRun->addText("", $erstyle);
else
$listItemRun->addText("");
}
else{
$startOffset = 0;
$comments = array();
foreach($v['entityRanges'] AS $t=>$h){
if($decoded['entityMap'][$h['key']]['type'] == 'COMMENT')
{
$commentdata = $decoded['entityMap'][$h['key']]['data'];
foreach($commentdata['comment'] AS $z=>$p){
$comm = new \PhpOffice\PhpWord\Element\Comment($p['user'], new \DateTime(), 'my_initials');
$comm->addText($p['comment']);
array_push($comments, array('start'=>$h['offset'], 'end'=>$h['offset']+$h['length'] - 1, 'comm'=>$comm));
}
}
}
$strarr = afterClearingExtraSpaces($strarr, $demographics);
foreach($strarr AS $l=>$m){
$democonv = $m;
if(mb_strlen($democonv) > 0){
$breakstring = str_split_unicode($democonv, 1);
$nextcapital = 1;
foreach($breakstring AS $z=>$p){
if(!isset($offset[$l])){
$retext = xmlEntities($p);
if($retext == "\n"){
$textToComment = $listItemRun->addTextBreak();
}
else
$textToComment = $listItemRun->addText($retext, null, array('tabs' => array(new \PhpOffice\PhpWord\Style\Tab('left', 1550))));
}
else{
$retext = xmlEntities($nextcapital?convertToProperCase($p, $styles[$l]):$p);
if($retext == "\n"){
$textToComment = $listItemRun->addTextBreak();
}
else
$textToComment = $listItemRun->addText($retext, $styles[$l], array('tabs' => array(new \PhpOffice\PhpWord\Style\Tab('left', 1550))));
}
foreach($comments AS $q=>$w){
if($w['start'] == $z+$startOffset+$q)
$w['comm']->setStartElement($textToComment);
if($w['end'] == $z+$startOffset-$q)
$w['comm']->setEndElement($textToComment);
}
if($p == ' ')
$nextcapital = 1;
else
$nextcapital = 0;
}
$startOffset += sizeof($breakstring);
}
}
foreach($comments AS $q=>$w){
$phpWord->addComment($w['comm']);
}
}
}
}
return $section;
}
$phpWord = null;
function generateTranscriptionTaskWordFile($tid, $storageDirectory, $whichPart, $includeNoName=0){
global $dbc;
global $phpWord;
$query = mysqli_query($dbc, "SELECT name, dictator_id FROM task WHERE id=$tid LIMIT 1");
$filename = null;
$dict_id = 0;
while($query && $result = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$filename = stripcslashes($result['name']);
$dict_id = mysqli_fetch_array(mysqli_query($dbc, "SELECT name FROM users WHERE id=".$result['dictator_id']." AND users.access IN (2,12) LIMIT 1"), MYSQLI_ASSOC);
$dict_id = $dict_id['name'];
}
if($dict_id && mb_strlen($dict_id) > 0){
if($whichPart == 'ALL')
$query = mysqli_query($dbc, "SELECT id, file_part_number, snapshot, template_id FROM task_history WHERE id IN (SELECT MAX(id) AS id FROM task_history WHERE task_id=$tid GROUP BY file_part_number)");
else
$query = mysqli_query($dbc, "SELECT id, file_part_number, snapshot, template_id FROM task_history WHERE id IN (SELECT MAX(id) AS id FROM task_history WHERE task_id=$tid GROUP BY file_part_number) AND file_part_number IN (".implode(',', $whichPart).")");
$rcnt = 0;
$wordFilesArray = array();
while($query && $result = mysqli_fetch_array($query, MYSQLI_ASSOC))
{
$rcnt++;
if($result['template_id']){
$newquery = mysqli_query($dbc, "SELECT snapshot, header from template_history WHERE template_id=".$result['template_id']." ORDER BY id DESC LIMIT 1");
$newresult = mysqli_fetch_array($newquery, MYSQLI_ASSOC);
$tabSize = mysqli_fetch_array(mysqli_query($dbc, "SELECT tabsize FROM template WHERE id=".$result['template_id']), MYSQLI_ASSOC)['tabsize'];
$demographics_query = mysqli_query($dbc, "SELECT template_demo_val.value AS value, template_demo.demo_key AS keyu, template_demo.demo_name AS keyn, template_demo.demo_type AS type FROM template_demo_val INNER JOIN template_demo ON template_demo_val.tempdemo_id=template_demo.id WHERE template_demo_val.task_id=$tid AND template_demo_val.part_num=".$result['file_part_number']."");
$demographics = array();
while($demographics_query && $newres = mysqli_fetch_array($demographics_query, MYSQLI_ASSOC)){
$demographics[$newres['keyu']] = array('value'=>$newres['value'], 'type'=>$newres['type'], 'name'=>$newres['keyn']);
}
if(!empty($newresult['header']) && !empty($result['snapshot']))
{
\PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true);
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
if(!empty($result['snapshot']))
{
$decoded = json_decode($result['snapshot'], true);
for($i = sizeof($decoded['blocks']) - 1; $i>= 0; $i--){
if($decoded['blocks'][$i]['text'] != '')
break;
else{
array_pop($decoded['blocks']);
}
}
makeWordStrings($section, json_decode($result['snapshot'], true), $demographics, $decoded, $tabSize, 0);
}
$newfilename = $filename;
if(mysqli_num_rows($query) > 1){
if($result['file_part_number'] > 1)
$newfilename .= '_'.(strlen($result['file_part_number']-1)==1?'0'.($result['file_part_number']-1):($result['file_part_number']-1));
}
$phpWord->save(WITHOUTTEMPLATE."$newfilename.docx", 'Word2007');
$templateFile = TEMPLATES.$newresult['header'];
$generatedFile = WITHOUTTEMPLATE."$newfilename.docx";
$targetFile = $storageDirectory.($includeNoName==1?"":"$newfilename.docx");
copy($templateFile, $targetFile);
$targetZip = new ZipArchive();
if ($targetZip->open($targetFile, ZipArchive::CREATE) !== true) {
return false;
}
$targetDocument = $targetZip->getFromName('word/document.xml');
$targetRelationsDocument = $targetZip->getFromName('word/_rels/document.xml.rels');
$targetCorePropsDocument = $targetZip->getFromName('docProps/core.xml');
$targetCustomPropsDocument = $targetZip->getFromName('docProps/custom.xml');
$targetContentTypesDocument = $targetZip->getFromName('[Content_Types].xml');
$targetContentTypesDocuments = $targetZip->getFromName('word/numbering.xml');
$targetDom = new DOMDocument();
$targetDom->loadXML($targetDocument);
$targetCorePropsDom = new DOMDocument();
$targetCorePropsDom->loadXML($targetCorePropsDocument);
$targetContentTypesDom = new DOMDocument();
$targetContentTypesDom->loadXML($targetContentTypesDocument);
$targetXPath = new \DOMXPath($targetDom);
$targetXPath->registerNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
$sourceZip = new \ZipArchive();
$sourceZip->open($generatedFile, ZipArchive::CREATE);
$sourceDocument = $sourceZip->getFromName('word/document.xml');
$sourceRelationsDocument = $sourceZip->getFromName('word/_rels/document.xml.rels');
$sourceContentTypesDocument = $sourceZip->getFromName('[Content_Types].xml');
$sourceContentTypesDocuments = $sourceZip->getFromName('word/numbering.xml');
$sourceDom = new DOMDocument();
$sourceDom->loadXML($sourceDocument);
$sourceRelationsDom = new DOMDocument();
$sourceRelationsDom->loadXML($sourceRelationsDocument);
$sourceContentTypes = new DOMDocument();
$sourceContentTypes->loadXML($sourceContentTypesDocument);
$sourceXPath = new \DOMXPath($sourceDom);
$sourceXPath->registerNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
$sourceRelationsXPath = new \DOMXPath($sourceRelationsDom);
$replacementMarkerNode = $targetXPath->query('//w:p[contains(translate(normalize-space(), " ", ""),"$CONTENT$")]')[0];
$sourceNodes = $sourceXPath->query('//w:document//w:body/*[not(self::w:sectPr)]');
$relationsArr = array();
$startId = 700;
$ifThereAreComments = 0;
$ifThereAreNumber = 0;
for ($i = 0; $i < $sourceZip->numFiles; $i++) {
if(strpos($sourceZip->getNameIndex($i), 'media') > 0 || strpos($sourceZip->getNameIndex($i), 'comments.xml') > 0){
if(strpos($sourceZip->getNameIndex($i), 'comments.xml') > 0)
$ifThereAreComments = 1;
$imagefile = $sourceZip->getFromName($sourceZip->getNameIndex($i));
$temp = fopen(TEMPORARYFILES.substr(bin2hex(random_bytes(5)),0, 5), "w");
fwrite($temp, $imagefile);
fseek($temp, 0);
$targetZip -> addFile(stream_get_meta_data($temp)['uri'], $sourceZip->getNameIndex($i));
}
if(strpos($sourceZip->getNameIndex($i), 'numbering.xml') > 0){
$ifThereAreNumber = 1;
}
}
foreach ($sourceNodes as $sourceNode) {
$checkifImage = $sourceNode -> getElementsByTagNameNS ("urn:schemas-microsoft-com:vml", 'imagedata');
foreach($checkifImage AS $t)
{
$rid = $t->getAttribute('r:id');
$relationsArr[$rid] = array('id'=>'rId'.$startId, 'media'=>'');
$t->setAttribute('r:id', $relationsArr[$rid]['id']);
$startId++;
}
$imported = $replacementMarkerNode->ownerDocument->importNode($sourceNode, true);
$inserted = $replacementMarkerNode->parentNode->insertBefore($imported, $replacementMarkerNode);
}
$replacementMarkerNode->parentNode->removeChild($replacementMarkerNode);
$targetZip->addFromString('word/document.xml', $targetDom->saveXML());
$getSourceRelationsTree = $sourceRelationsDom -> getElementsByTagName('Relationship');
foreach($getSourceRelationsTree AS $t){
$rid = $t->getAttribute('Id');
if(isset($relationsArr[$rid])){
$relationsArr[$rid]['media'] = $t->getAttribute('Target');
}
}
if($ifThereAreComments){
$targetRelationsDom = new DOMDocument();
$targetRelationsDom->loadXML($targetRelationsDocument);
$parentDom = $targetRelationsDom->getElementsByTagName('Relationships');
$relationsElement = $targetRelationsDom->createElement("Relationship");
$domAttribute = $targetRelationsDom->createAttribute('Id');
$domAttribute->value = 'rId1000';
$relationsElement->appendChild($domAttribute);
$domAttribute = $targetRelationsDom->createAttribute('Target');
$domAttribute->value = 'comments.xml';
$relationsElement->appendChild($domAttribute);
$domAttribute = $targetRelationsDom->createAttribute('Type');
$domAttribute->value = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments";
$relationsElement->appendChild($domAttribute);
$parentDom[0]->appendChild($relationsElement);
$targetZip->addFromString('word/_rels/document.xml.rels', $targetRelationsDom->saveXML());
$parentDom = $targetContentTypesDom->getElementsByTagName('Types');
$relationsElement = $targetContentTypesDom->createElement("Override");
$domAttribute = $targetContentTypesDom->createAttribute('PartName');
$domAttribute->value = '/word/comments.xml';
$relationsElement->appendChild($domAttribute);
$domAttribute = $targetContentTypesDom->createAttribute('ContentType');
$domAttribute->value = 'application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml';
$relationsElement->appendChild($domAttribute);
$parentDom[0]->appendChild($relationsElement);
$targetZip->addFromString('[Content_Types].xml', $targetContentTypesDom->saveXML());
}
if(!empty($relationsArr)){
$targetRelationsDom = new DOMDocument();
$targetRelationsDom->loadXML($targetRelationsDocument);
$parentDom = $targetRelationsDom -> getElementsByTagName('Relationships');
foreach($relationsArr AS $t){
$relationsElement = $targetRelationsDom->createElement("Relationship");
$domAttribute = $targetRelationsDom->createAttribute('Id');
$domAttribute->value = $t['id'];
$relationsElement->appendChild($domAttribute);
$domAttribute = $targetRelationsDom->createAttribute('Target');
$domAttribute->value = $t['media'];
$relationsElement->appendChild($domAttribute);
$domAttribute = $targetRelationsDom->createAttribute('Type');
$domAttribute->value = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
$relationsElement->appendChild($domAttribute);
$parentDom[0]->appendChild($relationsElement);
}
$targetZip->addFromString('word/_rels/document.xml.rels', $targetRelationsDom->saveXML());
}
$parentDom = $targetCorePropsDom -> getElementsByTagNameNS("http://schemas.openxmlformats.org/package/2006/metadata/core-properties", 'coreProperties');
$toRem = $parentDom[0]->getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", 'title')->Item(0);
$relationsElement = $targetCorePropsDom->createElement("dc:title", isset($demographics['{{title}}'])?$demographics['{{title}}']['value']:null);
$parentDom[0]->appendChild($relationsElement);
$toRem->parentNode->removeChild($toRem);
$toRem = $parentDom[0]->getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", 'subject')->Item(0);
$relationsElement = $targetCorePropsDom->createElement("dc:subject", $dict_id);
$parentDom[0]->appendChild($relationsElement);
$toRem->parentNode->removeChild($toRem);
$targetZip->addFromString('docProps/core.xml', $targetCorePropsDom->saveXML());
$targetZip->close();
$wordFilesArray[$result['file_part_number']] = $targetFile;
}
}
}
return array('r' => 1, 'd'=>array('totFileParts'=>$rcnt, 'wordFiles'=>$wordFilesArray));
}
return array('r'=>0, 'e'=>'INVALID_ACTIVITY');
}
So sorry about the dumb question due to each words were encoded in UTF-8 by function and passing inside the loop it looks unusual

Can't set new product's quantity and supplier from a prestashop module

I write a prestashop module which allows adding new products. I have a problem: in table 'ps_products' it saves all the information with success but when I open added product in admin panel catalog-> products, the quantity is 0 and no supplier is selected. Here is my code:
$message = '';
$erori = false;
$arr = array();
$feats = array();
$imgs = array();
$arr['nume_produs'] = Tools::getValue('pr_name');
$arr['pr_pret_ach'] = Tools::getValue('pr_pret_ach');
$arr['pr_pret_angro'] = Tools::getValue('pr_pret_angro');
$arr['pr_supp'] = explode("=", Tools::getValue('pr_supp'));
$arr['pr_refer'] = Tools::getValue('pr_refer');
$arr['pr_manuf'] = Tools::getValue('pr_manuf');
$arr['pr_short_desc'] = Tools::getValue('pr_short_desc');
$arr['proxy'] = Tools::getValue('proxy');
$res = yamarketsync::update_proxy($arr['proxy']);
$arr['categorii'] = Tools::getValue('categoryBox');
if(Tools::getValue('active') == 1) $arr['activ'] = true;
else $arr['activ'] = false;
$product = new Product();
$langId = (int) (Configuration::get('PS_LANG_DEFAULT'));
$name_ro = Tools::getValue('pr_name_ro');
if(Tools::getValue('pr_name_ru') != '')$name_ru = Tools::getValue('pr_name_ru'); else $name_ru = $name_ro;
if(Tools::getValue('pr_name_en') != '')$name_en = Tools::getValue('pr_name_en'); else $name_en = $name_ro;
if(Tools::getValue('pr_name_uk') != '')$name_uk = Tools::getValue('pr_name_uk'); else $name_uk = $name_ro;
$s_desc_ro = Tools::getValue('pr_short_desc_ro');
if(Tools::getValue('pr_short_desc_ru') != '')$s_desc_ru = Tools::getValue('pr_short_desc_ru'); else $s_desc_ru = $s_desc_ro;
if(Tools::getValue('pr_short_desc_en') != '')$s_desc_en = Tools::getValue('pr_short_desc_en'); else $s_desc_en = $s_desc_ro;
if(Tools::getValue('pr_short_desc_uk') != '')$s_desc_uk = Tools::getValue('pr_short_desc_uk'); else $s_desc_uk = $s_desc_ro;
$desc_ro = Tools::getValue('pr_desc_ro');
if(Tools::getValue('pr_desc_ru') != '')$desc_ru = Tools::getValue('pr_desc_ru'); else $desc_ru = $desc_ro;
if(Tools::getValue('pr_desc_en') != '')$desc_en = Tools::getValue('pr_desc_en'); else $desc_en = $desc_ro;
if(Tools::getValue('pr_desc_uk') != '')$desc_uk = Tools::getValue('pr_desc_uk'); else $desc_uk = $desc_ro;
$product->id_supplier = $arr['pr_supp'][0];
$product->supplier_name = $arr['pr_supp'][1];
$product->id_manufacturer = Tools::getValue('pr_manuf');
$product->description_short = array('4' => $s_desc_ro, '3' => $s_desc_ru, '1' => $s_desc_en,'5' => $s_desc_uk);
$product->description = array('4' => $desc_ro, '3' => $desc_ru, '1' => $desc_en,'5' => $desc_uk);
$product->quantity = Tools::getValue('pr_cant');
$product->name = array('4' => $name_ro, '3' => $name_ru, '1' => $name_en,'5' => $name_uk);
$product->price = Tools::getValue('pr_pret_ach');
$product->wholesale_price = Tools::getValue('pr_pret_angro');
$product->active = $arr['activ'];
$product->id_category_default= $arr['categorii'][0];
$product->category=$arr['categorii'];
$product->reference = $arr['pr_refer'];
$product->link_rewrite = array('4' => Tools::link_rewrite($name_ro),'3' => Tools::link_rewrite($name_ru),'1' => Tools::link_rewrite($name_en),'5' => Tools::link_rewrite($name_uk));
$res = $product->add();
if(!$res) $erori = true;
//adaugam features
$num = Tools::getValue('feat_num');
$i=0;
$id_product = (int)$product->id;
while($i <= $num){
if( Tools::getValue('feat_name-'.$i) !='' && Tools::getValue('feat_value-'.$i) != ''){
if(!yamarketsync::exista_deja_asociere(Tools::getValue('ya_feature_name-'.$i), Tools::getValue('feat_name-'.$i) )){
yamarketsync::save_asociere(Tools::getValue('ya_feature_name-'.$i), Tools::getValue('feat_name-'.$i) );
}
$rezultat = Product::addFeatureProductImport($id_product, Tools::getValue('feat_name-'.$i), Tools::getValue('feat_value-'.$i));
if(!$rezultat) $erori = true;
}
$feats[$i]['name'] = Tools::getValue('feat_name-'.$i);
$feats[$i]['value'] = Tools::getValue('feat_value-'.$i);
$i++;
}
$i=0;
$num = Tools::getValue('img_num');
while($i < $num){
$imgs[$i] = Tools::getValue('image-'.$i);
$img = new Image();
$img->id_product = $product->id;
$img->add();
$rezultat = AdminImportController::copyImg2($product->id, $img->id, $imgs[$i]);
if(!$rezultat) $erori = true;
$i++;
}
if($erori == true) return $this->displayError($this->l('Au aparut erori in timpul salvarii.'));
else return $this->displayConfirmation($this->l('Modificarile au fost salvate.'));
My friend, add this to complete update product quantity:
StockAvailable::setQuantity((int)$product->id, 0, $product->quantity, $this->context->shop->id)

Pagination can not back to prev number

I have pagination, and my pagination is working fine if I click next number.
View :
1 2 >
if I am clicking on 2 it goes on second page and shows proper result.but if I want to come back on 1 than its not redirect to page 1. here is my controller code:
public function index($date_start = 'all', $date_end = 'all', $title = 'all', $cid = 0, $skpd = 'all', $offset = NULL)
{
if($_POST)
{
$filter = array(
($this->input->post('filter_date_start') == '') ? 'all' : $this->input->post('filter_date_start'),
($this->input->post('filter_date_end') == '') ? 'all' : $this->input->post('filter_date_end'),
($this->input->post('filter_title') == '') ? 'all' : $this->input->post('filter_title'),
($this->input->post('filter_kategori') == 0) ? 0 : $this->input->post('filter_kategori'),
($this->input->post('filter_skpd') == '') ? 'all' : $this->input->post('filter_skpd')
);
$url = implode('/', $filter);
redirect('document/index'.$url);
}
//echo urldecode($title);
$this->load->model('News_model');
$this->load->library('pagination');
$data['title'] = 'Informasi Publik';
$param_document = array('status' => 1);
if(!empty($tid)) $param_document['tid'] = $tid;
if($date_start != 'all') $param_document['date_start'] = $date_start;
if($date_end != 'all') $param_document['date_end'] = $date_end;
if(!empty($cid)) $param_document['cid'] = $cid;
if($title != 'all') $param_document['title'] = urldecode($title);
if($skpd != 'all') $param_document['skpd'] = $skpd;
$params_total = $param_document;
$param_document_berkala = $param_document;
$param_document_serta_merta = $param_document;
$param_document_setiap_saat = $param_document;
$param_document_dikecualikan = $param_document;
$param_document['limit'] = 10;
$param_document['offset'] = $offset;
$data['document'] = $this->Document_model->get($param_document);
//dimodif cara urang
$data['bijilkategori'] = $this->Document_model->tampil();
// get document download count
foreach($data['document'] as $i => $row)
{
$document_transaction = $this->Document_model->get_transaction(array('did' => $row['document_id']));
$data['document'][$i]['download_count'] = empty($document_transaction) ? 0 : $document_transaction[0]['count'];
}
/*
$config['base_url'] = site_url('document/index/'.
(empty($tid) ? 0 : $tid).'/'.$date_start.'/'.$date_end.'/'.
$title.'/'.(empty($cid) ? 0 : $cid).'/'.$skpd
);
*/
$config['base_url'] = site_url('document/index/'.
$date_start.'/'.$date_end.'/'.
$title.'/'.(empty($cid) ? 0 : $cid).'/'.$skpd
);
$config['total_rows'] = count($this->Document_model->get($params_total));
$config['uri_segment'] = 9;
$this->pagination->initialize($config);
$data['main'] = 'document/document_indeks';
$data['kategori'] = $this->get_category();
$data['type'] = $this->get_type(TRUE);
$data['filter_kategori'] = $cid;
//dihidden ku urang
//$data['filter_type'] = $tid;
$data['filter_date_start'] = ($date_start == 'all') ? '' : $date_start;
$data['filter_date_end'] = ($date_end == 'all') ? '' : $date_end;
$data['filter_title'] = ($title == 'all') ? '' : $title;
$data['filter_author'] = ($skpd == 'all') ? '' : $skpd;
$param_document_berkala['tid'] = 1;
$param_document_serta_merta['tid'] = 2;
$param_document_setiap_saat['tid'] = 3;
$param_document_dikecualikan['tid'] = 4;
$data['total_record'] = count($this->Document_model->get($params_total));
$data['total_record_berkala'] = count($this->Document_model->get($param_document_berkala));
$data['total_record_serta_merta'] = count($this->Document_model->get($param_document_serta_merta));
$data['total_record_setiap_saat'] = count($this->Document_model->get($param_document_setiap_saat));
$data['total_record_dikecualikan'] = count($this->Document_model->get($param_document_dikecualikan));
$this->load->view('layout', $data);
}
Model:
public function get($params = array())
{
if(isset($params['fields']))
{
$this->db->select($params['fields']);
}
else
{
$this->db->select('*');
}
if(isset($params['id']))
{
$this->db->where('document.document_id', $params['id']);
}
elseif(isset($params['code']))
{
$this->db->where('document_code', $params['code']);
}
elseif(isset($params['date_start']) AND isset($params['date_end']))
{
$this->db->where('document_date >=', $params['date_start'].' 00:00:00');
$this->db->where('document_date <=', $params['date_end'].' 23:59:59');
}
elseif(isset($params['tid']))
{
$this->db->where('type_id', $params['tid']);
}
elseif(isset($params['cid']))
{
$this->db->where('document.category_id', $params['cid']);
}
elseif(isset($params['uid']))
{
$this->db->where('user_id', $params['uid']);
}
elseif(isset($params['sid']))
{
$this->db->where('document.skpd_id', $params['sid']);
}
if(isset($params['title']))
{
$this->db->like('document_title', $params['title']);
}
if(isset($params['author']))
{
$this->db->like('document_author', $params['author']);
}
elseif(isset($params['date']))
{
$this->db->where('document_date', $params['date']);
}
if(isset($params['dsid']))
{
$this->db->where('document_skpd_id', $params['dsid']);
}
if(isset($params['status']))
{
$this->db->where('document_is_published', $params['status']);
}
if(isset($params['document_sync']))
{
$this->db->where('document_sync', $params['document_sync']);
}
if(isset($params['sync']))
{
$this->db->reset_query();
$this->db->select('document.*');
$this->db->where('document_sync', $params['sync']);
}
if(isset($params['limit']))
{
if(!isset($params['offset']))
{
$params['offset'] = NULL;
}
$this->db->limit($params['limit'], $params['offset']);
}
if(isset($params['order_by']))
{
$this->db->order_by($params['order_by'], 'desc');
}
else
{
$this->db->order_by('document_date', 'desc');
}
$this->db->select('document.document_id');
$this->db->join('user_desktop', 'user_desktop.user_desktop_id = document.operator_id');
$this->db->join('(SELECT document_id, MAX(document_file_id) AS document_file_max_id FROM document_file GROUP BY document_id) AS document_file_max', 'document.document_id = document_file_max.document_id', 'left', FALSE);
$this->db->join('document_file', 'document_file.document_file_id = document_file_max.document_file_max_id', 'left');
$this->db->join('document_type', 'document_type.document_type_id = document.type_id');
$this->db->join('document_form', 'document_form.document_form_id = document.form_id');
$this->db->join('document_category', 'document_category.category_id = document.category_id');
$this->db->join('skpd', 'skpd.skpd_id = document.skpd_id');
$res = $this->db->get('document');
if(isset($params['id']))
{
return $res->row_array();
}
else
{
return $res->result_array();
}
}
Please master how to fix it ? whst is problem on my pagination
Please try this :
$config['base_url'] = site_url('document/index/'.
$date_start.'/'.$date_end.'/'.
$title.'/'.(empty($cid) ? 0 : $cid).'/'.$skpd.'/'
);
$config['uri_segment'] = 8;
in your base_url you missed out / at the end and codeigniter places offset for pagination. Hence, uri_segment would be 8.

How To Delete The Top 100 Rows From a CSV File With PHP

I have a php script running on a regular basis that processes the top 100 rows of a CSV file. When it is done I want it to delete the processed rows from the CSV file.
I have tried the below code, but it does not delete anything. I am not sure the best way to state the condition in PHP and am not sure what to put for the $id. I set the number of rows at 5 for testing purposes. Likely have somy syntax wrong.
Any suggestions? Tips?
function delete_line($id)
{
if($id)
{
$file_handle = fopen("file.csv", "w+");
$myCsv = array();
while (!feof($file_handle) )
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($id != $line_of_text[0])
{
fputcsv($file_handle, $line_of_text);
}
}
fclose($file_handle);
}
}
$in = fopen( 'file.csv', 'r');
$out = fopen( 'file.csv', 'w');
// Check whether they opened
while( $row = fgetcsv( $in, $cnt)){
fputcsv( $out, $row);
}
fclose( $in); fclose( $out);
Whole script is here...
<?php
require_once('wp-config.php');
$siteurl = get_site_url();
//print_r($_FILES);
//if($_FILES['file']['tmp_name']) {
//$upload = ABSPATH . 'file.csv';
//move_uploaded_file($_FILES['file']['tmp_name'], $upload);
//}
function clearer($str) {
//$str = iconv("UTF-8", "UTF-8//IGNORE", $str);
$str = utf8_encode($str);
$str = str_replace("’", "'", $str);
$str = str_replace("–", "-", $str);
return htmlspecialchars($str);
}
//file read
if(file_exists("file.csv")) $csv_lines = file("file.csv");
if(is_array($csv_lines)) {
$cnt = 5;
for($i = 0; $i < $cnt; $i++) {
$line = $csv_lines[$i];
$line = trim($line);
$first_char = true;
$col_num = 0;
$length = strlen($line);
for($b = 0; $b < $length; $b++) {
if($skip_char != true) {
$process = true;
if($first_char == true) {
if($line[$b] == '"') {
$terminator = '",';
$process = false;
}else
$terminator = ',';
$first_char = false;
}
if($line[$b] == '"'){
$next_char = $line[$b + 1];
if($next_char == '"')
$skip_char = true;
elseif($next_char == ',') {
if($terminator == '",') {
$first_char = true;
$process = false;
$skip_char = true;
}
}
}
if($process == true){
if($line[$b] == ',') {
if($terminator == ',') {
$first_char = true;
$process = false;
}
}
}
if($process == true)
$column .= $line[$b];
if($b == ($length - 1)) {
$first_char = true;
}
if($first_char == true) {
$values[$i][$col_num] = $column;
$column = '';
$col_num++;
}
}
else
$skip_char = false;
}
}
$values = array_values($values);
//print_r($values);
/*************************************************/
if(is_array($values)) {
//file.csv read
for($i = 0; $i < count($values); $i++) {
unset($post);
//check duplicate
//$wpdb->show_errors();
$wpdb->query("SELECT `ID` FROM `" . $wpdb->prefix . "posts`
WHERE `post_title` = '".clearer($values[$i][0])."' AND `post_status` = 'publish'");
//echo $wpdb->num_rows;
if($values[$i][0] != "Name" && $values[$i][0] != "" && $wpdb->num_rows == 0) {
$post['name'] = clearer($values[$i][0]);
$post['Address'] = clearer($values[$i][1]);
$post['City'] = clearer($values[$i][2]);
$post['Categories'] = $values[$i][3];
$post['Tags'] = $values[$i][4];
$post['Top_image'] = $values[$i][5];
$post['Body_text'] = clearer($values[$i][6]);
//details
for($k = 7; $k <= 56; $k++) {
$values[$i][$k] != '' ? $post['details'] .= "<em>".clearer($values[$i][$k])."</em>\r\n" : '';
}
//cats
$categoryes = explode(";", $post['Categories']);
foreach($categoryes AS $category_name) {
$term = term_exists($category_name, 'category');
if (is_array($term)) {
//category exist
$cats[] = $term['term_id'];
}else{
//add category
wp_insert_term( $category_name, 'category' );
$term = term_exists($category_name, 'category');
$cats[] = $term['term_id'];
}
}
//top image
if($post['Top_image'] != "") {
$im_name = md5($post['Top_image']).'.jpg';
$im = #imagecreatefromjpeg($post['Top_image']);
if ($im) {
imagejpeg($im, ABSPATH.'images/'.$im_name);
$post['topimage'] = '<img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" />';
}
}
//bottom images
for($k = 57; $k <= 76; $k++) {
if($values[$i][$k] != '') {
$im_name = md5($values[$i][$k]).'.jpg';
$im = #imagecreatefromjpeg($values[$i][$k]);
if ($im) {
imagejpeg($im, ABSPATH.'images/'.$im_name);
$post['images'] .= '<img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" />';
}
}
}
$post = array_map( 'stripslashes_deep', $post );
//print_r($post);
//post created
$my_post = array (
'post_title' => $post['name'],
'post_content' => '
<em>Address: '.$post['Address'].'</em>
'.$post['topimage'].'
'.$post['Body_text'].'
<!--more-->
'.$post['details'].'
'.$post['images'].'
',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => $cats
);
unset($cats);
//add post
//echo "ID:" .
$postid = wp_insert_post($my_post); //post ID
//tags
wp_set_post_tags( $postid, str_replace(';',',',$post['Tags']), true ); //tags
echo $post['name']. ' - added. ';
//google coords
$address = preg_replace("!\((.*?)\)!si", " ", $post['Address']).', '.$post['City'];
$json = json_decode(file_get_contents('http://hicon.by/temp/googlegeo.php?address='.urlencode($address)));
//print_r($json);
if($json->status == "OK") {
//нашло адрес
$google['status'] = $json->status;
$params = $json->results[0]->address_components;
if(is_array($params)) {
foreach($params AS $id => $p) {
if($p->types[0] == 'locality') $google['locality_name'] = $p->short_name;
if($p->types[0] == 'administrative_area_level_2') $google['sub_admin_code'] = $p->short_name;
if($p->types[0] == 'administrative_area_level_1') $google['admin_code'] = $p->short_name;
if($p->types[0] == 'country') $google['country_code'] = $p->short_name;
if($p->types[0] == 'postal_code') $google['postal_code'] = $p->short_name;
}
}
$google['address'] = $json->results[0]->formatted_address;
$google['location']['lat'] = $json->results[0]->geometry->location->lat;
$google['location']['lng'] = $json->results[0]->geometry->location->lng;
//print_r($params);
//print_r($google);
//insert into DB
$insert_code = $wpdb->insert( $wpdb->prefix . 'geo_mashup_locations',
array( 'lat' => $google['location']['lat'], 'lng' => $google['location']['lng'], 'address' => $google['address'],
'saved_name' => $post['name'], 'postal_code' => $google['postal_code'],
'country_code' => $google['country_code'], 'admin_code' => $google['admin_code'],
'sub_admin_code' => $google['sub_admin_code'], 'locality_name' => $google['locality_name'] ),
array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
);
if($insert_code) {
$google_code_id = $wpdb->insert_id;
$geo_date = date( 'Y-m-d H:i:s' );
$wpdb->insert(
$wpdb->prefix . 'geo_mashup_location_relationships',
array( 'object_name' => 'post', 'object_id' => $postid, 'location_id' => $google_code_id, 'geo_date' => $geo_date ),
array( '%s', '%s', '%s', '%s' )
);
}else{
//can't insert data
}
echo ' address added.<br />';
}else{
//echo $json->status;
}
}
} //$values end (for)
}
}else{
//not found file.csv
echo 'not found file.csv';
}
function delete_line($id)
{
if($id)
{
$file_handle = fopen("file.csv", "w+");
$myCsv = array();
while (!feof($file_handle) )
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($id != $line_of_text[0])
{
fputcsv($file_handle, $line_of_text);
}
}
fclose($file_handle);
}
}
$in = fopen( 'file.csv', 'r');
$out = fopen( 'file.csv', 'w');
// Check whether they opened
while( $row = fgetcsv( $in, $cnt)){
fputcsv( $out, $row);
}
fclose( $in); fclose( $out);
?>
Update
I tried one of the answer codes and got a server error. Code below, thoughts?
<?php
require_once('wp-config.php');
$siteurl = get_site_url();
//print_r($_FILES);
//if($_FILES['file']['tmp_name']) {
//$upload = ABSPATH . 'file.csv';
//move_uploaded_file($_FILES['file']['tmp_name'], $upload);
//}
function clearer($str) {
//$str = iconv("UTF-8", "UTF-8//IGNORE", $str);
$str = utf8_encode($str);
$str = str_replace("’", "'", $str);
$str = str_replace("–", "-", $str);
return htmlspecialchars($str);
}
//file read
if(file_exists("file.csv")) $csv_lines = file("file.csv");
if(is_array($csv_lines)) {
$cnt = 5;
for($i = 0; $i < $cnt; $i++) {
$line = $csv_lines[$i];
$line = trim($line);
$first_char = true;
$col_num = 0;
$length = strlen($line);
for($b = 0; $b < $length; $b++) {
if($skip_char != true) {
$process = true;
if($first_char == true) {
if($line[$b] == '"') {
$terminator = '",';
$process = false;
}else
$terminator = ',';
$first_char = false;
}
if($line[$b] == '"'){
$next_char = $line[$b + 1];
if($next_char == '"')
$skip_char = true;
elseif($next_char == ',') {
if($terminator == '",') {
$first_char = true;
$process = false;
$skip_char = true;
}
}
}
if($process == true){
if($line[$b] == ',') {
if($terminator == ',') {
$first_char = true;
$process = false;
}
}
}
if($process == true)
$column .= $line[$b];
if($b == ($length - 1)) {
$first_char = true;
}
if($first_char == true) {
$values[$i][$col_num] = $column;
$column = '';
$col_num++;
}
}
else
$skip_char = false;
}
}
$values = array_values($values);
//print_r($values);
/*************************************************/
if(is_array($values)) {
//file.csv read
for($i = 0; $i < count($values); $i++) {
unset($post);
//check duplicate
//$wpdb->show_errors();
$wpdb->query("SELECT `ID` FROM `" . $wpdb->prefix . "posts`
WHERE `post_title` = '".clearer($values[$i][0])."' AND `post_status` = 'publish'");
//echo $wpdb->num_rows;
if($values[$i][0] != "Name" && $values[$i][0] != "" && $wpdb->num_rows == 0) {
$post['name'] = clearer($values[$i][0]);
$post['Address'] = clearer($values[$i][1]);
$post['City'] = clearer($values[$i][2]);
$post['Categories'] = $values[$i][3];
$post['Tags'] = $values[$i][4];
$post['Top_image'] = $values[$i][5];
$post['Body_text'] = clearer($values[$i][6]);
//details
for($k = 7; $k <= 56; $k++) {
$values[$i][$k] != '' ? $post['details'] .= "<em>".clearer($values[$i][$k])."</em>\r\n" : '';
}
//cats
$categoryes = explode(";", $post['Categories']);
foreach($categoryes AS $category_name) {
$term = term_exists($category_name, 'category');
if (is_array($term)) {
//category exist
$cats[] = $term['term_id'];
}else{
//add category
wp_insert_term( $category_name, 'category' );
$term = term_exists($category_name, 'category');
$cats[] = $term['term_id'];
}
}
//top image
if($post['Top_image'] != "") {
$im_name = md5($post['Top_image']).'.jpg';
$im = #imagecreatefromjpeg($post['Top_image']);
if ($im) {
imagejpeg($im, ABSPATH.'images/'.$im_name);
$post['topimage'] = '<img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" />';
}
}
//bottom images
for($k = 57; $k <= 76; $k++) {
if($values[$i][$k] != '') {
$im_name = md5($values[$i][$k]).'.jpg';
$im = #imagecreatefromjpeg($values[$i][$k]);
if ($im) {
imagejpeg($im, ABSPATH.'images/'.$im_name);
$post['images'] .= '<img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" />';
}
}
}
$post = array_map( 'stripslashes_deep', $post );
//print_r($post);
//post created
$my_post = array (
'post_title' => $post['name'],
'post_content' => '
<em>Address: '.$post['Address'].'</em>
'.$post['topimage'].'
'.$post['Body_text'].'
<!--more-->
'.$post['details'].'
'.$post['images'].'
',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => $cats
);
unset($cats);
//add post
//echo "ID:" .
$postid = wp_insert_post($my_post); //post ID
//tags
wp_set_post_tags( $postid, str_replace(';',',',$post['Tags']), true ); //tags
echo $post['name']. ' - added. ';
//google coords
$address = preg_replace("!\((.*?)\)!si", " ", $post['Address']).', '.$post['City'];
$json = json_decode(file_get_contents('http://hicon.by/temp/googlegeo.php?address='.urlencode($address)));
//print_r($json);
if($json->status == "OK") {
//нашло адрес
$google['status'] = $json->status;
$params = $json->results[0]->address_components;
if(is_array($params)) {
foreach($params AS $id => $p) {
if($p->types[0] == 'locality') $google['locality_name'] = $p->short_name;
if($p->types[0] == 'administrative_area_level_2') $google['sub_admin_code'] = $p->short_name;
if($p->types[0] == 'administrative_area_level_1') $google['admin_code'] = $p->short_name;
if($p->types[0] == 'country') $google['country_code'] = $p->short_name;
if($p->types[0] == 'postal_code') $google['postal_code'] = $p->short_name;
}
}
$google['address'] = $json->results[0]->formatted_address;
$google['location']['lat'] = $json->results[0]->geometry->location->lat;
$google['location']['lng'] = $json->results[0]->geometry->location->lng;
//print_r($params);
//print_r($google);
//insert into DB
$insert_code = $wpdb->insert( $wpdb->prefix . 'geo_mashup_locations',
array( 'lat' => $google['location']['lat'], 'lng' => $google['location']['lng'], 'address' => $google['address'],
'saved_name' => $post['name'], 'postal_code' => $google['postal_code'],
'country_code' => $google['country_code'], 'admin_code' => $google['admin_code'],
'sub_admin_code' => $google['sub_admin_code'], 'locality_name' => $google['locality_name'] ),
array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
);
if($insert_code) {
$google_code_id = $wpdb->insert_id;
$geo_date = date( 'Y-m-d H:i:s' );
$wpdb->insert(
$wpdb->prefix . 'geo_mashup_location_relationships',
array( 'object_name' => 'post', 'object_id' => $postid, 'location_id' => $google_code_id, 'geo_date' => $geo_date ),
array( '%s', '%s', '%s', '%s' )
);
}else{
//can't insert data
}
echo ' address added.<br />';
}else{
//echo $json->status;
}
}
} //$values end (for)
}
}else{
//not found file.csv
echo 'not found file.csv';
}
function csv_delete_rows($filename='file.csv', $startrow=1, $endrow=5, $inner=false) {
$status = 0;
//check if file exists
if (file_exists($filename)) {
//end execution for invalid startrow or endrow
if ($startrow < 0 || $endrow < 0 || $startrow > 0 && $endrow > 0 && $startrow > $endrow) {
die('Invalid startrow or endrow value');
}
$updatedcsv = array();
$count = 0;
//open file to read contents
$fp = fopen($filename, "r");
//loop to read through csv contents
while ($csvcontents = fgetcsv($fp)) {
$count++;
if ($startrow > 0 && $endrow > 0) {
//delete rows inside startrow and endrow
if ($inner) {
$status = 1;
if ($count >= $startrow && $count <= $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
//delete rows outside startrow and endrow
else {
$status = 2;
if ($count < $startrow || $count > $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
}
else if ($startrow == 0 && $endrow > 0) {
$status = 3;
if ($count <= $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
else if ($endrow == 0 && $startrow > 0) {
$status = 4;
if ($count >= $startrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
else if ($startrow == 0 && $endrow == 0) {
$status = 5;
} else {
$status = 6;
}
}//end while
if ($status < 5) {
$finalcsvfile = implode("\n", $updatedcsv);
fclose($fp);
$fp = fopen($filename, "w");
fwrite($fp, $finalcsvfile);
}
fclose($fp);
return $status;
} else {
die('File does not exist');
}
}
?>
<html>
<body>
<form enctype="multipart/form-data" method="post">
CSV: <input name="file" type="file" />
<input type="submit" value="Send File" />
</form>
</body>
</html>
Here is php code for that:
$input = explode("\n", file_get_contents("file.csv"));
foreach ($input as $line) {
// process all lines.
}
// This function removes first 100 elements.
// More info:
// http://php.net/manual/en/function.array-slice.php
$output = array_slice($input, 100);
file_put_contents("out.csv", implode("\n", $output));
Note, if csv file contains header you have to remove first element from array $input.
I used this script in the passed written by Joby Joseph:
function csv_delete_rows($filename=NULL, $startrow=0, $endrow=0, $inner=true) {
$status = 0;
//check if file exists
if (file_exists($filename)) {
//end execution for invalid startrow or endrow
if ($startrow < 0 || $endrow < 0 || $startrow > 0 && $endrow > 0 && $startrow > $endrow) {
die('Invalid startrow or endrow value');
}
$updatedcsv = array();
$count = 0;
//open file to read contents
$fp = fopen($filename, "r");
//loop to read through csv contents
while ($csvcontents = fgetcsv($fp)) {
$count++;
if ($startrow > 0 && $endrow > 0) {
//delete rows inside startrow and endrow
if ($inner) {
$status = 1;
if ($count >= $startrow && $count <= $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
//delete rows outside startrow and endrow
else {
$status = 2;
if ($count < $startrow || $count > $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
}
else if ($startrow == 0 && $endrow > 0) {
$status = 3;
if ($count <= $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
else if ($endrow == 0 && $startrow > 0) {
$status = 4;
if ($count >= $startrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
else if ($startrow == 0 && $endrow == 0) {
$status = 5;
} else {
$status = 6;
}
}//end while
if ($status < 5) {
$finalcsvfile = implode("\n", $updatedcsv);
fclose($fp);
$fp = fopen($filename, "w");
fwrite($fp, $finalcsvfile);
}
fclose($fp);
return $status;
} else {
die('File does not exist');
}
}
The function accepts 4 parameters:
filename (string): Path to csv file. Eg: myfile.csv
startRow (int): First row in delete area
endRow (int): Last row in delete area
inner (boolean): decide whether rows deleted are from inner area or outer area
Now Let us consider various cases. I have a csv file with me named ‘test.csv’. Here is the screenshot of the same.
Example 1:
$status = csv_delete_rows('test.csv', 3, 5, true);
will delete the red part of:
Example 2:
$status = csv_delete_rows('test.csv', 3, 5, false);
will delete the red part of:
Example 3:
Like in your situation, if you want to delete the first 100 rows, use this:
$status = csv_delete_rows('test.csv', 0, 100);

mysql query and cookies

newbies should be encouraged. rather discouraging
I am new an having problems in understanding docs of php.
can someone give the exact code steps for my future reference to :
I want to run this query:
$query = $this->db->query("SELECT tracking_code FROM " . DB_PREFIX . "customer WHERE language_id = '" . (int)$this->customer->getId() . "'");
(I know it will return only one value) and 1. if "if tacking named cookie exists, delete it or replace it and set a cookie named "tracking" for one year with the value returned by that query. How can i do it?
I know little about php . but i get the feeling that i have no reference to db in that confirm.php . it doesnot extends model, nor i know would $this work here or not
the file iam working on is.
<?php
class ControllerCheckoutConfirm extends Controller {
public function index() {
$redirect = '';
if ($this->cart->hasShipping()) {
// Validate if shipping address has been set.
$this->load->model('account/address');
if ($this->customer->isLogged() && isset($this->session->data['shipping_address_id'])) {
$shipping_address = $this->model_account_address->getAddress($this->session->data['shipping_address_id']);
} elseif (isset($this->session->data['guest'])) {
$shipping_address = $this->session->data['guest']['shipping'];
}
if (empty($shipping_address)) {
$redirect = $this->url->link('checkout/checkout', '', 'SSL');
}
// Validate if shipping method has been set.
if (!isset($this->session->data['shipping_method'])) {
$redirect = $this->url->link('checkout/checkout', '', 'SSL');
}
} else {
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
}
// Validate if payment address has been set.
$this->load->model('account/address');
if ($this->customer->isLogged() && isset($this->session->data['payment_address_id'])) {
$payment_address = $this->model_account_address->getAddress($this->session->data['payment_address_id']);
} elseif (isset($this->session->data['guest'])) {
$payment_address = $this->session->data['guest']['payment'];
}
if (empty($payment_address)) {
$redirect = $this->url->link('checkout/checkout', '', 'SSL');
}
// Validate if payment method has been set.
if (!isset($this->session->data['payment_method'])) {
$redirect = $this->url->link('checkout/checkout', '', 'SSL');
}
// Validate cart has products and has stock.
if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
$redirect = $this->url->link('checkout/cart');
}
// Validate minimum quantity requirments.
$products = $this->cart->getProducts();
foreach ($products as $product) {
$product_total = 0;
foreach ($products as $product_2) {
if ($product_2['product_id'] == $product['product_id']) {
$product_total += $product_2['quantity'];
}
}
if ($product['minimum'] > $product_total) {
$redirect = $this->url->link('checkout/cart');
break;
}
}
if (!$redirect) {
$total_data = array();
$total = 0;
$taxes = $this->cart->getTaxes();
$this->load->model('setting/extension');
$sort_order = array();
$results = $this->model_setting_extension->getExtensions('total');
foreach ($results as $key => $value) {
$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
}
array_multisort($sort_order, SORT_ASC, $results);
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('total/' . $result['code']);
$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
}
}
$sort_order = array();
foreach ($total_data as $key => $value) {
$sort_order[$key] = $value['sort_order'];
}
array_multisort($sort_order, SORT_ASC, $total_data);
$this->language->load('checkout/checkout');
$data = array();
$data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
$data['store_id'] = $this->config->get('config_store_id');
$data['store_name'] = $this->config->get('config_name');
if ($data['store_id']) {
$data['store_url'] = $this->config->get('config_url');
} else {
$data['store_url'] = HTTP_SERVER;
}
if ($this->customer->isLogged()) {
$data['customer_id'] = $this->customer->getId();
$data['customer_group_id'] = $this->customer->getCustomerGroupId();
$data['firstname'] = $this->customer->getFirstName();
$data['lastname'] = $this->customer->getLastName();
$data['email'] = $this->customer->getEmail();
$data['telephone'] = $this->customer->getTelephone();
$data['fax'] = $this->customer->getFax();
$this->load->model('account/address');
$payment_address = $this->model_account_address->getAddress($this->session->data['payment_address_id']);
} elseif (isset($this->session->data['guest'])) {
$data['customer_id'] = 0;
$data['customer_group_id'] = $this->session->data['guest']['customer_group_id'];
$data['firstname'] = $this->session->data['guest']['firstname'];
$data['lastname'] = $this->session->data['guest']['lastname'];
$data['email'] = $this->session->data['guest']['email'];
$data['telephone'] = $this->session->data['guest']['telephone'];
$data['fax'] = $this->session->data['guest']['fax'];
$payment_address = $this->session->data['guest']['payment'];
}
$data['payment_firstname'] = $payment_address['firstname'];
$data['payment_lastname'] = $payment_address['lastname'];
$data['payment_company'] = $payment_address['company'];
$data['payment_company_id'] = $payment_address['company_id'];
$data['payment_tax_id'] = $payment_address['tax_id'];
$data['payment_address_1'] = $payment_address['address_1'];
$data['payment_address_2'] = $payment_address['address_2'];
$data['payment_city'] = $payment_address['city'];
$data['payment_postcode'] = $payment_address['postcode'];
$data['payment_zone'] = $payment_address['zone'];
$data['payment_zone_id'] = $payment_address['zone_id'];
$data['payment_country'] = $payment_address['country'];
$data['payment_country_id'] = $payment_address['country_id'];
$data['payment_address_format'] = $payment_address['address_format'];
if (isset($this->session->data['payment_method']['title'])) {
$data['payment_method'] = $this->session->data['payment_method']['title'];
} else {
$data['payment_method'] = '';
}
if (isset($this->session->data['payment_method']['code'])) {
$data['payment_code'] = $this->session->data['payment_method']['code'];
} else {
$data['payment_code'] = '';
}
if ($this->cart->hasShipping()) {
if ($this->customer->isLogged()) {
$this->load->model('account/address');
$shipping_address = $this->model_account_address->getAddress($this->session->data['shipping_address_id']);
} elseif (isset($this->session->data['guest'])) {
$shipping_address = $this->session->data['guest']['shipping'];
}
$data['shipping_firstname'] = $shipping_address['firstname'];
$data['shipping_lastname'] = $shipping_address['lastname'];
$data['shipping_company'] = $shipping_address['company'];
$data['shipping_address_1'] = $shipping_address['address_1'];
$data['shipping_address_2'] = $shipping_address['address_2'];
$data['shipping_city'] = $shipping_address['city'];
$data['shipping_postcode'] = $shipping_address['postcode'];
$data['shipping_zone'] = $shipping_address['zone'];
$data['shipping_zone_id'] = $shipping_address['zone_id'];
$data['shipping_country'] = $shipping_address['country'];
$data['shipping_country_id'] = $shipping_address['country_id'];
$data['shipping_address_format'] = $shipping_address['address_format'];
if (isset($this->session->data['shipping_method']['title'])) {
$data['shipping_method'] = $this->session->data['shipping_method']['title'];
} else {
$data['shipping_method'] = '';
}
if (isset($this->session->data['shipping_method']['code'])) {
$data['shipping_code'] = $this->session->data['shipping_method']['code'];
} else {
$data['shipping_code'] = '';
}
} else {
$data['shipping_firstname'] = '';
$data['shipping_lastname'] = '';
$data['shipping_company'] = '';
$data['shipping_address_1'] = '';
$data['shipping_address_2'] = '';
$data['shipping_city'] = '';
$data['shipping_postcode'] = '';
$data['shipping_zone'] = '';
$data['shipping_zone_id'] = '';
$data['shipping_country'] = '';
$data['shipping_country_id'] = '';
$data['shipping_address_format'] = '';
$data['shipping_method'] = '';
$data['shipping_code'] = '';
}
$product_data = array();
foreach ($this->cart->getProducts() as $product) {
$option_data = array();
foreach ($product['option'] as $option) {
if ($option['type'] != 'file') {
$value = $option['option_value'];
} else {
$value = $this->encryption->decrypt($option['option_value']);
}
$option_data[] = array(
'product_option_id' => $option['product_option_id'],
'product_option_value_id' => $option['product_option_value_id'],
'option_id' => $option['option_id'],
'option_value_id' => $option['option_value_id'],
'name' => $option['name'],
'value' => $value,
'type' => $option['type']
);
}
$product_data[] = array(
'product_id' => $product['product_id'],
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'download' => $product['download'],
'quantity' => $product['quantity'],
'subtract' => $product['subtract'],
'price' => $product['price'],
'total' => $product['total'],
'tax' => $this->tax->getTax($product['price'], $product['tax_class_id']),
'reward' => $product['reward']
);
}
// Gift Voucher
$voucher_data = array();
if (!empty($this->session->data['vouchers'])) {
foreach ($this->session->data['vouchers'] as $voucher) {
$voucher_data[] = array(
'description' => $voucher['description'],
'code' => substr(md5(mt_rand()), 0, 10),
'to_name' => $voucher['to_name'],
'to_email' => $voucher['to_email'],
'from_name' => $voucher['from_name'],
'from_email' => $voucher['from_email'],
'voucher_theme_id' => $voucher['voucher_theme_id'],
'message' => $voucher['message'],
'amount' => $voucher['amount']
);
}
}
$data['products'] = $product_data;
$data['vouchers'] = $voucher_data;
$data['totals'] = $total_data;
$data['comment'] = $this->session->data['comment'];
$data['total'] = $total;
$query = $this->db->query("SELECT affiliate_code FROM " . DB_PREFIX . "customer WHERE language_id = '" . (int)$this->customer->getId() . "'");
//set cookie $query->rows;
if (isset($this->request->cookie['tracking'])) {
$this->load->model('affiliate/affiliate');
$affiliate_info = $this->model_affiliate_affiliate->getAffiliateByCode($this->request->cookie['tracking']);
$subtotal = $this->cart->getSubTotal();
if ($affiliate_info) {
$data['affiliate_id'] = $affiliate_info['affiliate_id'];
$data['commission'] = ($subtotal / 100) * $affiliate_info['commission'];
} else {
$data['affiliate_id'] = 0;
$data['commission'] = 0;
}
} else {
$data['affiliate_id'] = 0;
$data['commission'] = 0;
}
$data['language_id'] = $this->config->get('config_language_id');
$data['currency_id'] = $this->currency->getId();
$data['currency_code'] = $this->currency->getCode();
$data['currency_value'] = $this->currency->getValue($this->currency->getCode());
$data['ip'] = $this->request->server['REMOTE_ADDR'];
if (!empty($this->request->server['HTTP_X_FORWARDED_FOR'])) {
$data['forwarded_ip'] = $this->request->server['HTTP_X_FORWARDED_FOR'];
} elseif(!empty($this->request->server['HTTP_CLIENT_IP'])) {
$data['forwarded_ip'] = $this->request->server['HTTP_CLIENT_IP'];
} else {
$data['forwarded_ip'] = '';
}
if (isset($this->request->server['HTTP_USER_AGENT'])) {
$data['user_agent'] = $this->request->server['HTTP_USER_AGENT'];
} else {
$data['user_agent'] = '';
}
if (isset($this->request->server['HTTP_ACCEPT_LANGUAGE'])) {
$data['accept_language'] = $this->request->server['HTTP_ACCEPT_LANGUAGE'];
} else {
$data['accept_language'] = '';
}
$this->load->model('checkout/order');
$this->session->data['order_id'] = $this->model_checkout_order->addOrder($data);
$this->data['column_name'] = $this->language->get('column_name');
$this->data['column_model'] = $this->language->get('column_model');
$this->data['column_quantity'] = $this->language->get('column_quantity');
$this->data['column_price'] = $this->language->get('column_price');
$this->data['column_total'] = $this->language->get('column_total');
$this->data['products'] = array();
foreach ($this->cart->getProducts() as $product) {
$option_data = array();
foreach ($product['option'] as $option) {
if ($option['type'] != 'file') {
$value = $option['option_value'];
} else {
$filename = $this->encryption->decrypt($option['option_value']);
$value = utf8_substr($filename, 0, utf8_strrpos($filename, '.'));
}
$option_data[] = array(
'name' => $option['name'],
'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
);
}
$this->data['products'][] = array(
'product_id' => $product['product_id'],
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'quantity' => $product['quantity'],
'subtract' => $product['subtract'],
'price' => $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax'))),
'total' => $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity']),
'href' => $this->url->link('product/product', 'product_id=' . $product['product_id'])
);
}
// Gift Voucher
$this->data['vouchers'] = array();
if (!empty($this->session->data['vouchers'])) {
foreach ($this->session->data['vouchers'] as $voucher) {
$this->data['vouchers'][] = array(
'description' => $voucher['description'],
'amount' => $this->currency->format($voucher['amount'])
);
}
}
$this->data['totals'] = $total_data;
$this->data['payment'] = $this->getChild('payment/' . $this->session->data['payment_method']['code']);
} else {
$this->data['redirect'] = $redirect;
}
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/confirm.tpl')) {
$this->template = $this->config->get('config_template') . '/template/checkout/confirm.tpl';
} else {
$this->template = 'default/template/checkout/confirm.tpl';
}
$this->response->setOutput($this->render());
}
}
?>
It can be done this way .
<?php
$query = $this->db->query("SELECT tracking_code FROM " . DB_PREFIX . "customer WHERE language_id = '" . (int)$this->customer->getId() . "'");
if(isset($_COOKIE['tracking'])){
setcookie('tracking', '', time()-1);
sleep(1); // sleep for 1 sec
setcookie('tracking', '$query->row["tracking_code"]', time()+60*60*24*30*12);
}else{
setcookie('tracking', '$query->row["tracking_code"]', time()+60*60*24*30*12);
}
?>
So in the if condition ,if your cookie named tracking is set than it will delete it with 1 sec and and apply you new value from $query . I hope this will work .

Categories