Issue with PHPWORD - php
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
Related
Big SQL Select Query in Laravel
I have table lids with under 430k entries. How can I do SELECT query faster, optimized because now this query working under 5-7 minutes. Heard something about Eloquent chunk in Laravel, but need clear PHP solution or with DB object. Maybe with 'for' construction to process 100-1000 entries at a time, smthng like this. Tried to do 'for' construction, but don't know how to do this optimized. Be gentle with me pls :) Want to know your opinion. How can i upgrade it? UPD: Did something like this $count = $db->doQuery("SELECT count(*) FROM `lids`"); // db - my custom object with Database connection $count = $count[0]['count(*)']; $hundreds = $count / 100; // get 'for' counts $start = 43; // id index starts from 43 in the table $end = 142; for ($index = 1; $index < $hundreds; $index++) { $leads = []; $leads = $db->doQuery("SELECT * FROM `lids` WHERE `id` BETWEEN " . $start . " AND " . $end . ""); // var_dump($leads); // die(); if (empty($leads)) { $start += 100; $end += 100; continue; } $uniques = []; foreach ($leads as $lead) { if (empty($lead['json_vars'])) continue; $vars = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']); // hot fix for charset, from DB comes string in utf8mb4 $json = json_decode($vars, true); if (!isset($json['ser']['HTTP_COOKIE']) || !str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue; $lead['json_vars'] = $json['ser']['HTTP_COOKIE']; // check for unique values if (!isset($uniques[$lead['id']]) || $uniques[$lead['id']]['phone'] != $lead['phone']) { $uniques[$lead['id']] = $lead; } } foreach ($uniques as $unique) { $lid = Lid::create($unique); } $start += 100; $end += 100; // here i get residue of entries if ($hundreds - $index < 1) { $leads = $db->doQuery("SELECT * FROM `lids` WHERE `id` IN(" . ($count - $hundreds * 100) . ", " . $count . ") AND WHERE "); foreach ($leads as $lead) { $json = json_decode(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']), true); if (!str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue; $lead['json_vars'] = $json['ser']['HTTP_COOKIE']; $lid = Lid::create($lead); } } } Upd2: $db = new Database(); $counter = 0; $scriptStart = date('d.m.Y H:i:s', strtotime('now')); $lastRemote = $db->lastId('lids'); $lastInner = Lid::all(['id'])->last(); $lastInner = $lastInner->id; $count = $lastRemote - $lastInner; if ($count < 0) { echo 'no new objects, canceled'; return false; } $start = $lastInner + 1; $end = $lastRemote; $fewEntries = false; if ($count < 500) { $fewEntries = true; $index = $lastInner; $hundreds = $lastRemote; } else { $index = 1; $hundreds = $count / 100; $end = $start + 99; } if ($fewEntries) { $leads = $db->itemsBetween('lids', 'id', [$start, $end]); $uniques = []; foreach ($leads as $lead) { if (empty($lead['json_vars'])) continue; $vars = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']); $json = json_decode($vars, true); if (!isset($json['ser']['HTTP_COOKIE']) || !str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue; $lead['json_vars'] = $json['ser']['HTTP_COOKIE']; if ( !isset($uniques[$lead['id']]) || $uniques[$lead['id']]['phone'] != $lead['phone'] && $uniques[$lead['id']]['ip'] != $lead['ip'] && $uniques[$lead['id']]['request_link'] != $lead['request_link'] ) { $uniques[$lead['id']] = $lead; } } foreach ($uniques as $unique) { $lid = Lid::create($unique); $counter++; } } else { for ($index; $index < $hundreds; $index++) { $leads = []; $leads = $db->itemsBetween('lids', 'id', [$start, $end]); // var_dump($leads); // die(); $uniques = []; foreach ($leads as $lead) { if (empty($lead['json_vars'])) continue; $vars = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']); $json = json_decode($vars, true); if (!isset($json['ser']['HTTP_COOKIE']) || !str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue; $lead['json_vars'] = $json['ser']['HTTP_COOKIE']; if ( !isset($uniques[$lead['id']]) || $uniques[$lead['id']]['phone'] != $lead['phone'] && $uniques[$lead['id']]['ip'] != $lead['ip'] && $uniques[$lead['id']]['request_link'] != $lead['request_link'] ) { $uniques[$lead['id']] = $lead; } } foreach ($uniques as $unique) { $lid = Lid::create($unique); $counter++; } $start += 100; $end += 100; } } $scriptEnd = date('d.m.Y H:i:s', strtotime('now')); echo 'added in table: ' . $counter . PHP_EOL; echo 'started at: ' . $scriptStart . PHP_EOL; echo 'ended at: ' . $scriptEnd . PHP_EOL;
Resolved my problem with optimization of my trash code XD $db = new Database(); $counter = 0; $scriptStart = date('d.m.Y H:i:s', strtotime('now')); $lastRemote = $db->lastId('lids'); $lastInner = Lid::all(['id'])->last(); $lastInner = $lastInner->id; $count = $lastRemote - $lastInner; if ($count < 0) { echo 'no new objects, canceled'; return false; } $start = $lastInner + 1; $end = $lastRemote; $fewEntries = false; if ($count < 500) { $fewEntries = true; $index = $lastInner; $hundreds = $lastRemote; } else { $index = 1; $hundreds = $count / 100; $end = $start + 99; } if ($fewEntries) { $leads = $db->itemsBetween('lids', 'id', [$start, $end]); $uniques = []; foreach ($leads as $lead) { if (empty($lead['json_vars'])) continue; $vars = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']); $json = json_decode($vars, true); if (!isset($json['ser']['HTTP_COOKIE']) || !str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue; $lead['json_vars'] = $json['ser']['HTTP_COOKIE']; if ( !isset($uniques[$lead['id']]) || $uniques[$lead['id']]['phone'] != $lead['phone'] && $uniques[$lead['id']]['ip'] != $lead['ip'] && $uniques[$lead['id']]['request_link'] != $lead['request_link'] ) { $uniques[$lead['id']] = $lead; } } foreach ($uniques as $unique) { $lid = Lid::create($unique); $counter++; } } else { for ($index; $index < $hundreds; $index++) { $leads = []; $leads = $db->itemsBetween('lids', 'id', [$start, $end]); // var_dump($leads); // die(); $uniques = []; foreach ($leads as $lead) { if (empty($lead['json_vars'])) continue; $vars = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']); $json = json_decode($vars, true); if (!isset($json['ser']['HTTP_COOKIE']) || !str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue; $lead['json_vars'] = $json['ser']['HTTP_COOKIE']; if ( !isset($uniques[$lead['id']]) || $uniques[$lead['id']]['phone'] != $lead['phone'] && $uniques[$lead['id']]['ip'] != $lead['ip'] && $uniques[$lead['id']]['request_link'] != $lead['request_link'] ) { $uniques[$lead['id']] = $lead; } } foreach ($uniques as $unique) { $lid = Lid::create($unique); $counter++; } $start += 100; $end += 100; } } $scriptEnd = date('d.m.Y H:i:s', strtotime('now')); echo 'added in table: ' . $counter . PHP_EOL; echo 'started at: ' . $scriptStart . PHP_EOL; echo 'ended at: ' . $scriptEnd . PHP_EOL;
Add multiple images to product in prestashop
I would like to add several images in my product, the problem is that I don't know how to do it, because for the moment I can only add one image via url! If someone has the solution or documentation, I would be interested! Thanks ! My code : $xml = simplexml_load_file('php://input'); $product = new Product($xml->id); $product->category = [2, 7]; $product->id_category_default = (int)$xml->id_category_default; //categories $product->name = $xml->name; //nom produit $product->price = $xml->price; //prix $product->unit_price = $xml->unit_price; //prix unitaire $product->wholesale_price = $xml->wholesale_price; //prix de gros $product->tax_rate = $xml->tax_rate; $product->ecotax = $xml->ecotax; $product->ean13 = $xml->ean13; //code barre $product->description = $xml->description; //description $product->description_short = $xml->description_short; //petite description $product->reference = $xml->reference; //reference $product->weight = $xml->weight; //poids $product->height = $xml->height; //hauteur $product->width = $xml->width; //largeur $product->depth = $xml->depth; //profondeur $product->minimal_quantity = (int)$xml->minimal_quantity; // $product->available_date = $xml->available_date; // $product->delivery_in_stock = $xml->delivery_in_stock; $product->delivery_out_stock = $xml->delivery_out_stock; $product->additional_shipping_cost = $xml->shipping_cost; $product->indexed = 1; $product->active = true; if ($xml->online_only == "true"){ $product->online_only = true; }else{ $product->online_only = false; } if ($xml->available_for_order == "true"){ $product->available_for_order = true; }else{ $product->available_for_order = false; } if ($xml->show_price == "true"){ $product->show_price = true; }else{ $product->show_price = false; } $product->save(); $product->updateCategories($product->category); $e = $product->getDefaultIdProductAttribute(); StockAvailable::setQuantity($product->id, $e, $xml->quantity); $image = new Image(); $image->id_product = $product->id; $image->position = Image::getHighestPosition($product->id) + 1; $image->cover = true; $image->save(); AdminImportControllerCore::copyImg((int)$product->id, (int)$image->id, $xml->urlImage, 'products', false);
$nb = count($xml->urlImage) - 1; $i = 0; $a = 1; while ($i <= $nb) { $image = new Image(); $image->id_product = $product->id; $image->position = Image::getHighestPosition($product->id) + $a++; if ($i >= 1){ $image->cover = false; }else{ $image->cover = true; } $image->image_format = 'jpg'; $image->save(); $this->copyImg((int)$product->id, (int)$image->id, $xml->urlImage[$i++], 'products', false); }
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);
How to split and count sms messages from file in 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++; }
Regarding pagination in cakephp 2.0 with order by
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'); }