Add multiple images to product in prestashop - php

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);
}

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

Web scraping publication from a google scholar profile via simplehtmldom PHP

I'm trying to scrape publication from a google scholar profile,but i have no idea how to scrape every publication from a profile, i know the maximum publication the profile page can show is 100 per page from this question :
Google Scholar profile scrape PHP
I just want to know how to apply the url to my php code so that i can get every publication from a profile and insert them to a array
I am able to put every publication in a single page to a array with this code:
<?php
set_time_limit(0);
include 'simple_html_dom.php';
$data = json_decode(file_get_contents('php://input'),true);
$scholarID = $data["gScholarID"];
$kodeDosen = $data["kodeDosen"];
$page = 1;
$offset = ($page - 1)* 100;
$cStart = 0+$offset;
$profile = 'https://scholar.google.com/citations?user='.$scholarID.'&hl=en&cstart='.$cStart.'&view_op=list_works&pagesize=100';
$html = file_get_html($profile);
$table = $html->find('#gsc_a_t',0);
$rowData = array();
foreach($table->find('tr.gsc_a_tr') as $row){
$paperjudul = $row->find('td.gsc_a_t a', 0)->plaintext;
$paper['kodeDosen'] = $kodeDosen;
$paper['judul'] = $paperjudul;
$cited = $row->find('td.gsc_a_c', 0)->plaintext;
if($cited === ''){
$cited = 0;
}
$cited = preg_replace('/[\*]+/', '', $cited);
$paper['citedBy'] = $cited;
$paper['namaJurnal'] = $row->find('td.gsc_a_t .gs_gray', 1)->plaintext;
if($paper['namaJurnal'] === ''){
$paper['namaJurnal'] = 'n/a';
}
$paper['periode'] = $row->find('td.gsc_a_y', 0)->plaintext;
if($paper['periode'] === ' '){
$paper['periode'] = 'n/a';
}
$paper['status'] = 'Published';
$rowData[] = $paper;
}
print_r($rowData);
?>
I just want to know how to apply this code to multiple pages to get all publication from a google scholar profile
I found a method that works, first, i create a loop that searches the web page for an indication that the page has no publication to show and inserts the url that contains the publication which i then loop to scrape the publication within the url.
This is the code that i used:
<?php
set_time_limit(0);
include 'simple_html_dom.php';
include 'connectdb.php';
$scholarID = $_GET["gScholarID"];
$kodeDosen = $_GET["kodeDosen"];
$page = 1;
$finalPage = false;
$sqlTest = 'INSERT INTO tbl_publikasi(kodeDosen,jenis,namaJurnal,judul,status,tipePublikasi,periode,tahun,citedCount) VALUES ';
$response = array();
while (!$finalPage) {
$offset = ($page - 1)* 100;
$cStart = 0+$offset;
$profile = 'https://scholar.google.com/citations?user='.$scholarID.'&hl=en&cstart='.$cStart.'&view_op=list_works&pagesize=100';
$html = file_get_html($profile);
if(is_object($html)){
$empty = $html->find('td.gsc_a_e',0);
if($empty){
$finalPage = true;
unset($html);
}
else{
$urlArray[] = $profile;
$page++;
}
}
else{
$response['success'] = 0;
$response['message'] = "URL tidak valid ";
}
}
if($finalPage){
foreach ($urlArray as $urlPublikasi) {
$html = file_get_html($urlPublikasi);
$table = $html->find('#gsc_a_t',0);
$rowData = array();
if($table){
foreach($table->find('tr.gsc_a_tr') as $row){
$paper['kodeDosen'] = $kodeDosen;
$paperjudul = $row->find('td.gsc_a_t a', 0)->plaintext;
$paper['judul'] = $paperjudul;
$cited = $row->find('td.gsc_a_c', 0)->plaintext;
if($cited === ''){
$cited = 0;
}
$cited = preg_replace('/[\*]+/', '', $cited);
$paper['citedBy'] = trim($cited);
$paper['jenis'] = 'Scholar';
$paper['namaJurnal'] = $row->find('td.gsc_a_t .gs_gray', 1)->plaintext;
if($paper['namaJurnal'] === ''){
$paper['namaJurnal'] = 'n/a';
}
$paper['periode'] = 'n/a';
$paper['tahun'] = $row->find('td.gsc_a_y', 0)->plaintext;
if($paper['tahun'] === ' '){
$paper['tahun'] = '0000';
}
$paper['tipePublikasi'] = 'Scholar';
$paper['status'] = 'Published';
$rowData[] = $paper;
}
foreach ($rowData as $paperValue) {
$judul = $paperValue['judul'];
$jenis = $paperValue['jenis'];
$citedCount = $paperValue['citedBy'];
$namaJurnal = $paperValue['namaJurnal'];
$periode = $paperValue['periode'];
$tahun = $paperValue['tahun'];
$status = $paperValue['status'];
$tipePublikasi = $paperValue['tipePublikasi'];
$sqlTest .= "('".$kodeDosen."','".$jenis."','".$namaJurnal."','".$judul."','".$status."','".$tipePublikasi."','".$periode."','".trim($tahun)."','".$citedCount."'),";
}
$query = rtrim($sqlTest, ',');
$query .= "ON DUPLICATE KEY UPDATE idPublikasi=LAST_INSERT_ID(idPublikasi), kodeDosen = VALUES(kodeDosen), jenis = VALUES(jenis),
namaJurnal=VALUES(namaJurnal),status=VALUES(status),
tipePublikasi = VALUES(tipePublikasi),periode=VALUES(periode),tahun = VALUES(tahun),citedCount = VALUES(citedCount)";
}
else{
$response['success'] = 0;
$response['message'] = "Tabel Publikasi tidak ditemukan ";
}
}
if (mysqli_query($conn, $query)) {
$response['success'] = 1;
$response['message'] = "Array Uploaded Successfully";
}
else {
$response['success'] = 0;
$response['message'] = "Array Upload Failed, Alasan : ".mysqli_error($conn);
}
}
else{
$response['success'] = 0;
$response['message'] = "Gagal ditemukan ";
}
echo json_encode($response);
?>

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';
}
}
}

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

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

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++;
}

Categories