How to split and count sms messages from file in PHP - php

I have problem that my sms messages are imported with csv, then it is checked if number is ok and how long sms is. My problem is that if text messages is longer then 160 it still enters 1 in databse. But it should start counting, if it is less or equal than 160, it is 1 messages, if it is more than 160 but less or equal than 320 it is two messages and if it is more then it is 3 messages.
Page code is here:
<?php
$link = #mysql_connect("localhost", "admin", "") or die("Error: Database offline.");
mysql_select_db("database", $link);
mysql_query("SET NAMES 'utf8' ", $link);
function detect_type($smstext) {
$type = 0;
$dec_codes = array();
for ($i = 0; $i < strlen($smstext); $i++) {
$symbol = substr($smstext,$i,1);
if (!in_array(ord($symbol), $dec_codes)) { $type = 1; }
}
return $type;
}
$result_array = array();
$unic_numbers = array();
$fp = file_get_contents($_FILES['filename']['tmp_name']);
$fp = str_replace("\r\n", "\n", $fp);
$fp = str_replace("\r", "\n", $fp);
$fp = str_replace("\t", "", $fp);
$rows = explode("\n", $fp);
$imported_rows = 0;
$duplicate_rows = 0;
$error_rows = 0;
$long_rows = 0;
for ($i = 0; $i < sizeof($rows); $i++) {
$data = explode(";", $rows[$i]);
$data[1] = sms_formatNumbers($data[1]); // formating number
$userid = 78;
if(strlen($data[1]) > 9){
if($unic_numbers[$data[1]] != true ){ // unic number check
$unic_numbers[$data[1]] = true;
$imported_rows++;
$fullSMS = iconv("ISO-8859-1","UTF-8", trim($data[2])." ".trim($data[3])." ".trim($data[4]));
if(strlen($fullSMS) > 164){
$long_rows++;
}
if($_POST['action'] == 'send'){
// SMS TEXT
$smstext = str_replace("õ", "ò", $fullSMS);
$smstext = str_replace("Õ", "ò", $smstext);
$type = detect_type($smstext);
// servicegroup
$char2 = substr($data[1], 0, 2);
$char3 = substr($data[1], 0, 3);
$c1 = mysql_query("SELECT * FROM zone_info WHERE country_code = '".$char2."'", $link);
$c2 = mysql_query("SELECT * FROM zone_info WHERE country_code = '".$char3."'", $link);
if (mysql_num_rows($c1) == 1) {
$r = mysql_fetch_array($c1);
$price = $r['price'];
$z = mysql_query("SELECT * FROM zone WHERE id = ".$r['up']."", $link);
$zone = mysql_fetch_array($z);
$zone_id = $zone['id'];
$servicegroup = $zone['servicegroup'];
} else if (mysql_num_rows($c2) == 1) {
$r = mysql_fetch_array($c2);
$price = $r['price'];
$z = mysql_query("SELECT * FROM zone WHERE id = ".$r['up']."", $link);
$zone = mysql_fetch_array($z);
$zone_id = $zone['id'];
$servicegroup = $zone['servicegroup'];
}
require_once("../scripts/number.class.php");
$receiver = "00".$data[1];
$obj = new NumberClass($receiver);
$operator = $obj -> operator_code;
$country = $obj -> code;
$operator_name = $obj -> operator_name;
if(strlen($operator) > 0) {
$er = mysql_query("SELECT * FROM zone_exception WHERE country = ".$country." AND operator = ".$operator."", $link);
if (mysql_num_rows($er) == 1) {
$erand = mysql_fetch_array($er);
$price = $erand['price'];
$servicegroup = $erand['servicegroup'];
}
} else $operator_name = "-";
if ($operator_name == "-") { $servicegroup = $servicegroup; }
else {
if ($operator_name == " First Operator") $servicegroup = "90";
else if ($operator_name == "Second Operator") $servicegroup = "91";
else if ($operator_name == "Third Operator") $servicegroup = "92";
else $servicegroup = $servicegroup;
}
require_once("../core/init.mini.inc.php");
$servicegroup = UserBasedRerouting($receiver, $userid, $operator_name, $servicegroup);
$client_type ='corporative';
$sender = $data[0];
$zone_id = 11;
$client_sms_id = '0';
$client_want_report = '0';
$client_report_url = '';
$amount = 1;
$dt_delaysend = '1970-01-01 00:00:00';
$SMSsent = 0;
$SMStotal = 1;
$smstext_old = $smstext;
while($SMSsent < $SMStotal){
$sql = mysql_query("insert into sms_queue (user_id,client_type,dt_entered,sender,receiver,operator,smstext,sms_type,zone_id,client_sms_id,client_want_report,client_report_url,sms_price,amount,servicegroup,dt_delaysend) values ('$userid','$client_type','".date('Y-m-d H:i:s')."','$sender','$receiver','$operator_name','$smstext',0,'$zone_id','$client_sms_id','$client_want_report','$client_report_url','$price','$amount','$servicegroup','$dt_delaysend')", $link);
$SMSsent++;
}
}
}else{
$duplicate_rows ++;
}
}else{
$error_rows++;
}
}
$result_array['success'] = true;
$result_array['long_sms'] = $long_rows;
$result_array['send_sms'] = $imported_rows;
$result_array['error_sms'] = $error_rows;
$result_array['duplicate_sms'] = $duplicate_rows;
$result_array['action'] = $_POST['action'];
echo json_encode($result_array);
function sms_formatNumbers($number){
$number = (int)$number;
$start_code = (int)substr($number,0,4);
if($start_code < 3780 or $start_code == 3785 or $start_code > 3789){
return $number;
}else{
return '';
}
}
?>
Can someone help me out with that?
Thank you

Try
if(strlen($fullSMS) > 164){
$long_rows = ceil(strlen($fullSMS)/160);
}
instead of
if(strlen($fullSMS) > 164){
$long_rows++;
}

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

PHP Error 500 Internal Server Error in Codeigniter 3 When large Transaction

I have a problem when execute large transaction in Codeigniter 3.
I create transaction for migrating old data like below:
// Controller
public function migrate_document_get()
{
$this->benchmark->mark('code_start');
$data = $this->Delivery_order_model->read_data_class_from_stock();
foreach ($data as $obj) {
$parameters = $this->Delivery_order_model->read_data_for_do($obj->class_no);
$this->Delivery_order_model->create_data($parameters);
}
$this->benchmark->mark('code_end');
$data['message'] = "Finish migrate document DO";
$data['execution_time'] = round($this->benchmark->elapsed_time('code_start', 'code_end')) . " seconds";
$this->response($data, REST_Controller::HTTP_OK);
}
// Model
function create_data($data)
{
$error = array();
$affected_rows = 0;
$this->mysql->trans_start();
foreach ($data as $row) {
$sql_insert_product = "";
$class_no = $row['class_no'];
$article_vendor = $row['article_vendor'];
$style = $row['style'];
$sku_promo = $row['sku_promo'];
$retail = $row['retail'];
$unique_id = $this->generate_unique_id($class_no, $article_vendor, $style, $sku_promo, $retail);
$sku_no = $class_no . $unique_id . $style . $sku_promo . $retail;
$article_no = $class_no . $style . $sku_promo . $retail;
$res_field = $unique_id . $style . $sku_promo;
$format = array();
$format['dept_no'] = $row['dept_no'];
$format['class_no'] = $class_no;
$format['sku_no'] = $sku_no;
if (!empty($row['ref_no'])) {
$format['ref_no'] = $row['ref_no'];
}
$format['article_vendor'] = $article_vendor;
$format['article_no'] = $article_no;
$format['res_field'] = $res_field;
$format['style'] = $style;
$format['category_no'] = $row['category_no'];
$format['size_no'] = $row['size_no'];
$format['color_no'] = $row['color_no'];
$format['material_no'] = $row['material_no'];
$format['unique_id'] = $unique_id;
$format['sku_promo'] = $sku_promo;
if (!empty($row['exp_promo']) and $row['sku_promo'] != "00") {
$format['exp_promo'] = date('Y-m-d', strtotime(str_replace('/', '-', str_replace("'", "", $row['exp_promo']))));
}
$format['season_code'] = date('ym');
$format['retail'] = $retail;
$format['tag_type'] = $row['tag_type'];
if (!empty($row['image'])) {
$format['image'] = $row['image'];
}
$format['time_create'] = date('Y-m-d H:i:s');
$sql_insert_product = $this->mysql->insert_ignore_string("msr_product", $format);
// Transaction 1 -> INSERT msr_product
$this->mysql->query($sql_insert_product);
$sql_insert_do = "";
$format_doc = "DO" . $class_no . date('Ymd');
$do_id = $this->generate_do_id($format_doc);
$doc_no = $format_doc . $do_id;
$store_no = $row['store_no'];
// INSERT msr_do
$format_insert = array();
$format_insert['do_no'] = $doc_no;
$format_insert['store_no'] = $store_no;
$format_insert['sku_no'] = $sku_no;
$format_insert['do_date1'] = date('Y-m-d', strtotime(date('Ymd')));
$format_insert['do_date2'] = date('Y-m-d', strtotime('60 day', strtotime(date('Ymd'))));
$format_insert['do_status'] = 1;
$format_insert['user_input'] = $row['nik'];
$format_insert['ts_input'] = date('Y-m-d H:i:s');
$format_insert['status_item'] = 0;
$format_insert['qty_store'] = $row['qty'];
$format_update['qty_store'] = "qty_store + " . $row['qty'];
$sql_insert_do = $this->mysql->insert_on_duplicate_update_string("msr_do", $format_insert, $format_update, true, false);
// Transaction 2 -> INSERT msr_do
$this->mysql->query($sql_insert_do);
$affected_rows += $this->mysql->affected_rows();
}
$this->mysql->trans_complete();
if ($this->mysql->trans_status() === FALSE) {
$error = $this->mysql->error();
$error['sql_product'] = $sql_insert_product;
$error['sql_do'] = $sql_insert_do;
}
return $this->commonutil->format_output($affected_rows, $error);
}
When I execute method above in loop,
I facing an issue with error 500 internal server error.
but when I execute method like below one by one, not in the loop it's running normally.
// Controller
public function create_post()
{
$this->benchmark->mark('code_start');
$parameters = $this->post();
if (!empty($parameters)) {
$validate_param = $this->validate_parameter_create($parameters[0]);
if ($validate_param->run() == TRUE) {
$save = $this->Delivery_order_model->create_data($parameters);
if (!empty($save) and $save['total_affected'] > 0) {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_OK;
$output['error'] = false;
$output['message'] = "Success create delivery order list.";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_OK);
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_NOT_MODIFIED;
$output['error'] = true;
$output['error_detail'] = $save['error'];
$output['message'] = "Failed create delivery order list!";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_NOT_MODIFIED);
}
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_UNPROCESSABLE_ENTITY;
$output['error'] = true;
$output['error_detail'] = $validate_param->error_array();
$output['message'] = "Required JSON Array! [{.....}]";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_UNPROCESSABLE_ENTITY;
$output['error'] = true;
$output['message'] = "Required parameters!";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
}
// Model
function create_data($data)
{
$error = array();
$affected_rows = 0;
$this->mysql->trans_start();
foreach ($data as $row) {
$sql_insert_product = "";
$class_no = $row['class_no'];
$article_vendor = $row['article_vendor'];
$style = $row['style'];
$sku_promo = $row['sku_promo'];
$retail = $row['retail'];
$unique_id = $this->generate_unique_id($class_no, $article_vendor, $style, $sku_promo, $retail);
$sku_no = $class_no . $unique_id . $style . $sku_promo . $retail;
$article_no = $class_no . $style . $sku_promo . $retail;
$res_field = $unique_id . $style . $sku_promo;
$format = array();
$format['dept_no'] = $row['dept_no'];
$format['class_no'] = $class_no;
$format['sku_no'] = $sku_no;
if (!empty($row['ref_no'])) {
$format['ref_no'] = $row['ref_no'];
}
$format['article_vendor'] = $article_vendor;
$format['article_no'] = $article_no;
$format['res_field'] = $res_field;
$format['style'] = $style;
$format['category_no'] = $row['category_no'];
$format['size_no'] = $row['size_no'];
$format['color_no'] = $row['color_no'];
$format['material_no'] = $row['material_no'];
$format['unique_id'] = $unique_id;
$format['sku_promo'] = $sku_promo;
if (!empty($row['exp_promo']) and $row['sku_promo'] != "00") {
$format['exp_promo'] = date('Y-m-d', strtotime(str_replace('/', '-', str_replace("'", "", $row['exp_promo']))));
}
$format['season_code'] = date('ym');
$format['retail'] = $retail;
$format['tag_type'] = $row['tag_type'];
if (!empty($row['image'])) {
$format['image'] = $row['image'];
}
$format['time_create'] = date('Y-m-d H:i:s');
$sql_insert_product = $this->mysql->insert_ignore_string("msr_product", $format);
// Transaction 1 -> INSERT msr_product
$this->mysql->query($sql_insert_product);
$sql_insert_do = "";
$format_doc = "DO" . $class_no . date('Ymd');
$do_id = $this->generate_do_id($format_doc);
$doc_no = $format_doc . $do_id;
$store_no = $row['store_no'];
// INSERT msr_do
$format_insert = array();
$format_insert['do_no'] = $doc_no;
$format_insert['store_no'] = $store_no;
$format_insert['sku_no'] = $sku_no;
$format_insert['do_date1'] = date('Y-m-d', strtotime(date('Ymd')));
$format_insert['do_date2'] = date('Y-m-d', strtotime('60 day', strtotime(date('Ymd'))));
$format_insert['do_status'] = 1;
$format_insert['user_input'] = $row['nik'];
$format_insert['ts_input'] = date('Y-m-d H:i:s');
$format_insert['status_item'] = 0;
$format_insert['qty_store'] = $row['qty'];
$format_update['qty_store'] = "qty_store + " . $row['qty'];
$sql_insert_do = $this->mysql->insert_on_duplicate_update_string("msr_do", $format_insert, $format_update, true, false);
// Transaction 2 -> INSERT msr_do
$this->mysql->query($sql_insert_do);
$affected_rows += $this->mysql->affected_rows();
}
$this->mysql->trans_complete();
if ($this->mysql->trans_status() === FALSE) {
$error = $this->mysql->error();
$error['sql_product'] = $sql_insert_product;
$error['sql_do'] = $sql_insert_do;
}
return $this->commonutil->format_output($affected_rows, $error);
}
I already resizing on DB temp space
and I already check the method it's running normally
what's wrong with that, please give me some advice.

Does not display the result of parsing

Good afternoon, please help me. At me when parsing the result of parsing is not displayed.
link my php file https://dropmefiles.com/cv4Q2
Please correct where I was wrong. Or help to rewrite a little code so that it displays the result of the parser.
Already tried all the options, it does not work in any way. My knowledge here is not enough.
1 file
part 1
function getForecastXML($cid='579432') {
$cid = "579432";
$hoffset = "4";
$appid= "d86ad74d22ce9cc528d8baee65acd408";
$lang= "ru";
$days = array();
$xml = #file_get_contents("http://api.openweathermap.org/data/2.5/forecast?id=$cid&mode=xml&appid=$appid&lang=$lang&type=like");
if ($xml===false) { return;} else {
$xml = simplexml_load_string($xml);
$cityname = (string)$xml->location->name;
$weekdays[0] = "Воскресенье";
$weekdays[1] = "Понедельник";
$weekdays[2] = "Вторник";
$weekdays[3] = "Среда";
$weekdays[4] = "Четверг";
$weekdays[5] = "Пятница";
$weekdays[6] = "Суббота";
if (count($xml->forecast->time)>0){
foreach ($xml->forecast->time as $fpart) {
$forecast = array();
$attr = $fpart->attributes();
$forecast['t']['min'] = (string)round(($fpart->temperature->attributes()->min)-273,15,PHP_ROUND_HALF_UP);
$forecast['t']['min'] = $forecast['t']['min'] > 0 ? "+".$forecast['t']['min'] : $forecast['t']['min'];
$forecast['t']['max'] = (string)round(($fpart->temperature->attributes()->max)-273,15,PHP_ROUND_HALF_UP);
$forecast['t']['max'] = $forecast['t']['max'] > 0 ? "+".$forecast['t']['max'] : $forecast['t']['max'];
$forecast['p']['min'] = (string)round($fpart->pressure->attributes()->value,0,PHP_ROUND_HALF_UP);
// $forecast['p']['max'] = (string)$fpart->PRESSURE->attributes()->max;
$forecast['w']['min'] = (string)round($fpart->windSpeed->attributes()->mps,0,PHP_ROUND_HALF_UP);
//$forecast['w']['max'] = (string)$fpart->WIND->attributes()->max;
//$forecast['w']['rumb'] = (string)$fpart->WIND->attributes()->direction;
$forecast['h']['min'] = (string)$fpart->humidity->attributes()->value;
//$forecast['h']['max'] = (string)$fpart->RELWET->attributes()->max;
$forecast['symb'] = (string)$fpart->symbol->attributes()->name;
$forecast['pict'] = (string)$fpart->symbol->attributes()->var;
$date = date('c',strtotime($hoffset.' hours',strtotime($attr['from'])));
$hour = date('H',strtotime($date));
$forecast['timestamp'] =strtotime($date);
$date = strtotime($date);
$dayofweek = date('w',$date);
$date = $weekdays[$dayofweek]." ".date('d.m',$date);
if ($forecast['timestamp'] > time()){
$days[$date][$hour] = $forecast;
}
}
} else {$days=array();}
}
//return array($cityname,$days);
return [$cityname => $days];
//echo [$cityname => $days];
}
part 2
$outputData = array();
if (count($this->forecast) > 0) {
foreach ($this->forecast as $date => $daypart) {
$outputData[] = $date;
foreach ($daypart as $dp => $data) {
$outputData[] = str_pad($dp, 2, '0', STR_PAD_LEFT);
$outputData[] = $data['symb'];
$outputData[] = $data['t']['min'];
$outputData[] = $data['t']['max'];
if (($data['p']['min']) > 0) {
$outputData[] = "Давление " . round($data['p']['min'] * 0.75006375541921) . "мм. рт. ст.";
}
}
}
} else {
$outputData[] = "В данный момент информация о погоде отсутствует";
}
echo implode(' ', $outputData);

Unable to maintain Session in Laravel

I'm using Laravel 5.3 and facing problems regarding the session which is not being preserved when I hit the URL with query string(UTM Querystring). It works fine without querystring and maintains the session.
mywebsite.com/booking (Works fine)
mywebsite.com/booking?utm_source=affiliate&utm_medium=mailer&utm_campaign=Ad2click (Destroys session as well cookies)
Wondering, what could be the reason?
public function bookProduct(Request $request){
$zone = $request->zone;
$records = Zone::where('zone_name',$zone)->get();
foreach($records as $record){
$zone_id = $record->id;
}
if ( Session::get('LAST_ACTIVITY') && (time() - Session::get('LAST_ACTIVITY') > 1200 )){
echo 'expired';
}
else{
$CheckOTP = Session::get('otp');
/* Check if User Entered OTP Matches System Generated OTP */
if ( $CheckOTP == $request->get_otp ) {
/* Create new Customer */
$recordCount = Customer::where('email', $request->customer_email)->orWhere('contact_number',$request->customer_contact_no)->count();
if( $recordCount > 0 ){
Customer::where('contact_number', $request->customer_contact_no)->update(['door_number' => $request->customer_pickup_door_no, 'building_name' => $request->customer_pickup_building_name, 'street_name' => $request->customer_pickup_street_name, 'area' => $request->customer_pickup_area, 'landmark' => $request->customer_pickup_landmark, 'pincode' => $request->customer_pickup_pincode, 'city'=>$request->customer_city]);
}
if($recordCount == 0 || $recordCount == ""){
$customer = new Customer;
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
$randomPass = implode($pass);
$password = Hash::make('a');
$customer->customer_name = $request->customer_name;
$customer->email = $request->customer_email;
$customer->contact_number = $request->customer_contact_no;
$customer->password = $password;
$customer->door_number = $request->customer_pickup_door_no;
//$customer->street_name = $request->customer_pickup_street_name;
//$customer->building_name = $request->customer_pickup_building_name;
$customer->area = $request->customer_pickup_area;
$customer->landmark = $request->customer_pickup_landmark;
$customer->pincode = $request->customer_pickup_pincode;
$customer->city = $request->customer_city;
$customer->save();
$id = $customer->id;
$measurement = new Measurement;
$measurement->customer_id = $id;
$address = $request->customer_pickup_door_no .",".$request->customer_pickup_area .",".$request->customer_pickup_landmark .",". $request->customer_city.",". $request->customer_pickup_pincode;
$measurement->save();
$datas = $this->create_customer($request->customer_contact_no,$request->customer_name, $request->customer_email,$address,$request->customer_pickup_pincode);
$this->save_customers($request->customer_contact_no);
}
else{
$address = $request->customer_pickup_door_no .",".$request->customer_pickup_area .",".$request->customer_pickup_landmark .",". $request->customer_city.",". $request->customer_pickup_pincode;
$datas = $this->create_customer($request->customer_contact_no,$request->customer_name, $request->customer_email,$address,$request->customer_pickup_pincode);
$this->save_customers($request->customer_contact_no);
$fetchCustomer = Customer::where('email', $request->customer_email)->orWhere('contact_number',$request->customer_contact_no)->get();
foreach( $fetchCustomer as $customerId ){
$id = $customerId->id;
}
}
/* Store New Booking */
/* Pickup address same as shipping address*/
if( $request->duplicate_address == 'on'){
$request->customer_shipping_door_no = $request->customer_pickup_door_no;
//$request->customer_shipping_street_name = $request->customer_pickup_street_name;
//$request->customer_shipping_building_name = $request->customer_pickup_building_name;
$request->customer_shipping_area = $request->customer_pickup_area;
$request->customer_shipping_landmark = $request->customer_pickup_landmark;
$request->customer_shipping_pincode = $request->customer_pickup_pincode;
}
$booking = new Booking;
$booking->customer_id = $id;
$booking->look_id = Session::get("lookIds");
$booking->time_slot_id = $request->slot;
$booking->booking_date = strtr($request->booking_date, '/', '-');
$booking->booking_date = date('Y-m-d', strtotime($booking->booking_date));
$booking->door_number = $request->customer_shipping_door_no;
//$booking->street_name = $request->customer_shipping_street_name;
//$booking->building_name = $request->customer_shipping_building_name;
$booking->landmark = $request->customer_shipping_landmark;
$booking->pincode = $request->customer_shipping_pincode;
$booking->city = $request->customer_city;
$booking->area = $request->customer_shipping_area;
$booking->fabric_availability = $request->fabric_material;
$booking->otp = $CheckOTP;
$booking->http_user_agent = $_SERVER['HTTP_USER_AGENT'];
$zones = Zone::where('zone_name',$request->zone)->get();
foreach( $zones as $zone){
$booking->zone_id = $zone->id;
}
/* Fetch Latitude & Longitude from address */
//$address = $request->customer_pickup_door_no.' ,'.$request->customer_pickup_street_name.' ,'.$request->customer_pickup_building_name.' ,'.$request->customer_pickup_landmark;
$address = $request->customer_pickup_door_no.' ,'.$request->customer_pickup_landmark.' ,'.$request->customer_shipping_area;
$prepAddr = str_replace(' ','+',$address);
$geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
if( $output->status != "ZERO_RESULTS" ){
$latitude = $output->results[0]->geometry->location->lat;
$longitude = $output->results[0]->geometry->location->lng;
}
else{
$booking->latitude = "";
$booking->longitude = "";
}
$lastId = Booking::max('id');
$lastId = $lastId+1;
$booking->booking_id = 'BK'.date("ymd").str_pad($lastId, 4, '0', STR_PAD_LEFT);
$checkCouponApply = $request->check_coupon_apply;
if($checkCouponApply == '1'){
$couponCode = $request->discount_coupon;
$booking->coupon_code = $request->discount_coupon;
$getDiscountPercentage = Discount::where('coupon_code',$couponCode)->pluck('coupon_percentage');
$getDiscountPercentage = $getDiscountPercentage[0];
Discount::where('coupon_code',$booking->coupon_code)->decrement('remaining_user_count');
}
$booking->save();
Session::set('bookingId', $booking->id);
if($request->trouser > 0 && $request->shirt > 0){
Session::set('productBought', 'Shirt & Trouser');
}
else if($request->trouser>0){
Session::set('productBought', 'Trouser');
}
else if($request->shirt>0){
Session::set('productBought', 'Shirt');
}
/* Store products data for Booking */
$trouserRecord = Categories::where('category_name','Trouser')->pluck('id');
$shirtRecord = Categories::where('category_name','Shirt')->pluck('id');
$trouserPrice = ProductPrice::where('zone_id',$zone_id)
->where('category_id',$trouserRecord[0])
->pluck('price');
$shirtPrice = ProductPrice::where('zone_id',$zone_id)
->where('category_id',$shirtRecord[0])
->pluck('price');
$shirtUnitPrice = $shirtPrice[0];
$trouserUnitPrice = $trouserPrice[0];
$products = array('trouser' => array('count' => $request->trouser, 'category' => $trouserRecord[0], 'price'=>$trouserPrice[0], 'unit_price'=>$trouserUnitPrice), 'shirt' => array('count' => $request->shirt, 'category' => $shirtRecord[0], 'price'=>$shirtPrice[0], 'unit_price'=>$shirtUnitPrice));
foreach($products as $product){
for($i=0;$i<$product['count'];$i++){
$subBooking = new SubBooking;
//Calculate tax tmount for each lined up product and save relavant data
$subBooking->booking_id = $booking->id;
if($product['category'] == '3'){
$subBooking->category_name = 'Shirt';
}
else if($product['category'] == '4'){
$subBooking->category_name = 'Trouser';
}
$setTaxes = Tax::all();
foreach($setTaxes as $taxes){
$tax[$taxes->tax_type] = $product['unit_price']*($taxes->percentage/100);
$tax[$taxes->tax_type.'Percentage'] = $taxes->percentage;
}
$subBooking->service_tax = $tax['Service Tax'];
$subBooking->service_tax_percentage = $tax['Service TaxPercentage'];
$subBooking->swachh_bharat = $tax['Swachh Bharat'];
$subBooking->swachh_bharat_percentage = $tax['Swachh BharatPercentage'];
$subBooking->krishi_kalyan = $tax['Krishi Kalyan'];
$subBooking->krishi_kalyan_percentage = $tax['Krishi KalyanPercentage'];
$subBooking->category_id = $product['category'];
$subBooking->unit_price = $product['unit_price'];
$subBooking->unit_price = $product['unit_price'];
$subBooking->quantity = 1;
$subBooking->save();
}
}
if($subBooking){
$this->storeReportingData('new');
}
$email = $request->customer_email;
$booking_date_new = date("d M Y", strtotime($booking->booking_date));
$time_slot_data = TimeSlot::where('id',$booking->time_slot_id)->first();
$start = date("g:i a", strtotime($time_slot_data['start']));
$end = date("g:i a", strtotime($time_slot_data['end']));
$msg = "Thank you for booking with us. Your booking ref number is: $booking->booking_id and our appointment with you is on $booking_date_new ($start - $end).";
$action = 'New Booking';
$description = "Booking has been created";
$this->saveLog($booking->id, $action, $description);
Session::forget('lookIds');
$contact_no = $request->customer_contact_no;;
$urlapi = "https://api-in.bsmart.in/api/v3/sendsms/plain?";
$user = "USER";
$password = "SECRET";
$senderid = "SENDER_ID";
$pin = mt_rand(1000, 9999);
$msg_order_confirmation = urlencode("$msg");
$msg2 = "Dear Customer, Please spare 45 minutes of your valuable time with our stylists for a perfect styling experience.";
$sms_url = $urlapi."User=".$user."&Password=".$password."&Sender=".$senderid."&GSM=91".$contact_no."&SMSText=".$msg_order_confirmation;
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sms_url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);
$email_message = $msg." ".$msg2;
//$this->sendEmail($email,$email_message);
$this->sendSMS($contact_no,$msg2);
$sub_bookings = SubBooking::where('booking_id',$booking->id)->where('quantity','<>', 0)->get();
$data = array();
foreach($sub_bookings as $sub_booking){
$quantity = $sub_booking->quantity;
$category_data = Categories::where('id',$sub_booking->category_id)->first();
$category_name = $category_data['category_name'];
$data[] = array('quantity'=>$quantity,'category_name'=>$category_name);
}
$appointment_date = date("d M Y", strtotime($booking->booking_date));
$time_slot_data = TimeSlot::where('id',$booking->time_slot_id)->first();
$start = date("g:i a", strtotime($time_slot_data['start']));
$end = date("g:i a", strtotime($time_slot_data['end']));
$customer_data = Customer::where('id',$booking->customer_id)->first();
$customer_name = $customer_data['customer_name'];
$email_data = array('email'=>$email,'customer_name'=>$customer_name,'from'=>'notifications-noreply#raymondcustomtailoring.com','from_name'=>'Raymond','appointment_date'=>$appointment_date,'appointment_id'=>$booking->booking_id,'customer_name'=>$customer_name,'address'=>$address,'pincode'=>$request->customer_shipping_pincode,'data'=>$data,'start'=>$start,'end'=>$end);
/*Mail::send(['html'=>'confirm'],$email_data, function( $message ) use ($email_data)
{
$message->to( $email_data['email'] )->from($email_data['from'],$email_data['from_name'] )->subject($email_data['appointment_id'].' Appointment Confirmed');
});*/
//return $booking->id;
}
else{
echo 'mismatched';
}
}
}

Insert Url last 2 characters in database php

I am trying to insert last 2 chararcters of Url into my database.When i insert everytime it takes some number like "2147483647".How to insert the correct last 2 chararcters of Url.
'$array = json_decode(stripslashes($_POST['data']));
for($i = 0, $l = sizeof($array); $i < $l; $i++){
$obj = $array[$i];
if($obj->{'leaf'} == true){
$leaf = 1;
} else{
$leaf = 0;
}
if($obj->{'parentId'} == null){
$parentID = 'null';
} else{
$parentID = $obj->{'parentId'};
}
if($obj->{'Duration'}==''){
$duration = 0;
} else{
$duration = $obj->{'Duration'};
}
$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$gantt_id = substr(strrchr($url, '='), 1);
/*if($obj->{'gantt_id'}==null){
$gantt_id = 0;
} else{
$gantt_id = $obj->{'gantt_id'};
}
*/
$q = 'INSERT INTO j_gantt_tasks SET Name = "'.$obj->{'Name'}.'", StartDate = "'.$obj->{'StartDate'}.'", EndDate = "'.$obj->{'EndDate'}.'",
Duration = "'.$obj->{'Duration'}.'", DurationUnit = "'.$obj->{'DurationUnit'}.'", PercentDone = "'.$obj->{'PercentDone'}.'", Cls = "'.$obj->{'Cls'}.'", gantt_id="'.$gantt_id.'",
parentId = "'.$obj->{'parentId'}.'"';
$r = mysql_query($q);
if(!$r){
echo db_error($q);
}
$obj->{'id'} = mysql_insert_id();
}
echo json_encode($array);'
give a try to substring
$url = (!empty($_SERVER['HTTPS'])) ?
"https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] :
"http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$last2 = substring($url,-2);

Categories