Format AWS Transcribe Audio Identification - amazon-web-services

I've been searching for this solution, couldn't find anything reasonably to what AWS currently have on their UI, so came up with mine in laravel, and dropping it here to help anyone hopefully searching for this as well.

public function convertTextToSpeakers($response)
{
$segments = $response['results']['speaker_labels']['segments'];
$items = $response['results']['items'];
$result = [];
foreach ($items as $key => $item) {
if (!isset($item['start_time'])) {
$prev_item = $items[$key - 1];
if ($prev_item) {
$item['start_time'] = $prev_item['start_time'];
$item['end_time'] = $prev_item['end_time'];
$items[$key] = $item;
}
}
}
foreach ($segments as $key => $segment) {
$has_data = true;
$temp_key = $key;
while ($has_data) {
$temp_key++;
$next_segment = $segments[$temp_key] ?? null;
if ($next_segment && $next_segment['speaker_label'] == $segment['speaker_label']) {
$itemsData = array_merge($segment['items'], $next_segment['items']);
$segment['items'] = $itemsData;
unset($segments[$temp_key]);
$segments[$key] = $segment;
} else {
$has_data = false;
}
}
}
$items = collect($items);
$segments = collect($segments)->sortBy('start_time');
foreach ($segments as $segment) {
$text = '';
$segmentItems = collect($segment['items'])->sortBy('start_time');
foreach ($segmentItems as $seg_item) {
$words = $items->where('start_time', $seg_item['start_time'])
->where('end_time', $seg_item['end_time']);
foreach ($words as $word) {
$text .= $word['alternatives'][0]['content'];
}
$text .= " ";
}
$result[] = [
'speaker' => $segment['speaker_label'],
'text' => $text,
];
}
return $result;
}

Related

Export data from SP 2013 list to SQL database with comment versions

I'm trying to figure out a way to get comments from all item versions into one column in a sql table and view, but still unsuccessful.
I have listed the script I wrote below, but I can't add comments to it. Second script is light foreach loop which get comments history and add in new column in item, but this is not good solution if you have more than 10 000 items in SharePoint 2013 list.
Add-pssnapin microsoft.sharepoint.powershell
cls;
# env settings
#$env = "https://sharepoint.com/"
#$sqlConnectionString = "Server=servername\servername;Database=Database;User Id=UserID;Password=UserPassword;Timeout=15"
# settings
$webUrl = "$env"
$fromListUrl = "Lists/Name"
$fromViewName = "Sharepoint list view"
$targetTableName = "Target SQL table"
$targetViewName = "Target SQL View"
$targetPrimaryKey = "DBID"
$sourcePrimaryKey = "ID"
# script internal settings
$sqlDropTable = "DROP TABLE IF EXISTS [dbo].[{TABLENAME}]"
$sqlCreateTable = "IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[{TABLENAME}]') AND type in (N'U')) BEGIN CREATE TABLE [dbo].[{TABLENAME}]( [{PRIMARYKEY}] [int] IDENTITY(1,1) NOT NULL, CONSTRAINT [PK_{TABLENAME}_{PRIMARYKEY}] PRIMARY KEY CLUSTERED ([{PRIMARYKEY}] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] END"
$sqlCreateColumn = "IF COL_LENGTH('{TABLENAME}', '{COLUMN}') IS NULL BEGIN ALTER TABLE [dbo].[{TABLENAME}] ADD [{COLUMN}] {TYPE} END "
$sqlSelect = "SELECT $targetPrimaryKey,$sourcePrimaryKey FROM [dbo].[$targetTableName]"
$sqlInsert = "INSERT INTO [dbo].[$targetTableName]({COLUMNS}) VALUES ({VALUES})"
$sqlUpdate = "UPDATE [dbo].[$targetTableName] SET {COLUMNVALUES} WHERE [$sourcePrimaryKey] = {IDVALUE}"
$sqlCreateView = "IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[{VIEWNAME}]')) EXEC dbo.sp_executesql #statement = N'CREATE VIEW [dbo].[{VIEWNAME}] AS SELECT {COLUMNS} FROM [dbo].[{TABLENAME}]' "
$sqlDropView = "DROP VIEW IF EXISTS [dbo].[{VIEWNAME}]"
$commit = $true # false to dont make changes in shp (folders creation, files upload, log items)
$recreate = $false # true will erase target table and create new
# script variables
$wasError = $false # flag to see if script encountered any error
$connection = $null
function GetColumnFromField($field, $row)
{
$name = $field.InternalName
if([string]::IsNullOrEmpty($fieldTitle))
{
$name = $field.InternalName
}
if(($field.Type -eq "User" -or $field.Type -eq "Lookup") -and $field.hidden -eq $false)
{
$value1 = [DBNull]::Value
$value2 = [DBNull]::Value
if($row -ne $null)
{
$value = $row[$field.internalname]
if([string]::IsNullOrEmpty($value) -eq $false)
{
try
{
$lookup = New-Object Microsoft.SharePoint.SPFieldLookupValue($value)
$value1 = $lookup.LookupId
$value2 = $lookup.LookupValue
if ($value1 -eq $null) { $value1 = 0 }
if ($value2 -eq $null) { $value2 = [DBNull]::Value }
}
catch
{
$value1 = 0
$value2 = $value
}
}
}
$cols = #()
$cols += ,#("$($name)_ID", "int", $value1, "$($field.Title) ID")
$cols += ,#("$($name)_Value", "nvarchar(255)", $value2, "$($field.Title)")
return ,$cols
}
$type = "NVARCHAR(MAX)"
if($field.Type -eq "Integer" -or $field.Type -eq "Counter")
{
$type = "int"
}
elseif($field.Type -eq "Number")
{
$type = "float"
}
elseif($field.Type -eq "DateTime")
{
$type = "datetime"
}
elseif($field.Type -eq "Boolean")
{
$type = "bit"
}
elseif($field.Type -eq "Guid")
{
$type = "uniqueidentifier"
}
elseif($field.Type -eq "Text" -or $field.Type -eq "Choice")
{
$type = "nvarchar(255)"
}
elseif($field.Type -eq "Note")
{
$type = "nvarchar(MAX)"
}
$value = [DBNull]::Value
if($row -ne $null -and $row[$field.internalname] -ne $null)
{
if($field.Type -eq "Integer")
{
$value = $row[$field.internalname]
}
elseif($field.Type -eq "Number")
{
$value = $row[$field.internalname]
}
elseif($field.Type -eq "DateTime")
{
$value = [System.DateTime]$row[$field.internalname]
}
elseif($field.Type -eq "Boolean")
{
$value = $row[$field.internalname]
}
elseif($field.Type -eq "Guid")
{
$value = $row[$field.internalname]
}
elseif($field.Type -eq "Text")
{
$value = $row[$field.internalname].tostring()
}
elseif($field.Type -eq "Note")
{
$value = $row[$field.internalname].tostring()
}
else
{
$value = $row[$field.internalname].tostring()
}
if ($value -eq $null) { $value = [DBNull]::Value }
}
$cols = #()
$cols += ,#($name,$type,$value,"$($field.Title)")
return ,$cols
}
try
{
# connect to shp
write-host "Started $([DateTime]::Now.ToString()), web: $webUrl, listurl: $fromListUrl, view: $fromViewName, target: $targetTableName"
$web = get-spweb $webUrl
$list = $web.getlist($fromListUrl)
$view = $list.views[$fromViewName]
if (!$?) {throw "Could not open SHP connections."}
write-host "Connected to SHP list: $($list.title)"
# connect to sql
$connection = New-Object System.Data.SqlClient.SqlConnection $sqlConnectionString
$connection.Open()
if (!$?) {throw "Could not open SQL connections."}
write-host "Connected to SQL db: $($connection.Database)"
# recreate target table
if($recreate -eq $true)
{
$dropTableQuery = $sqlDropTable.replace("{TABLENAME}",$targetTableName)
$dropTableCommand = New-Object System.Data.SqlClient.SqlCommand $dropTableQuery, $connection
if($commit)
{
$dropTableCommand.ExecuteScalar()
}
$dropViewQuery = $sqlDropView.replace("{VIEWNAME}",$targetViewName)
$dropViewCommand = New-Object System.Data.SqlClient.SqlCommand $dropViewQuery, $connection
if($commit)
{
$dropViewCommand.ExecuteScalar()
}
}
# ensure target table
$syncTableQuery = $sqlCreateTable.replace("{TABLENAME}",$targetTableName).replace("{PRIMARYKEY}",$targetPrimaryKey)
$syncTableCommand = New-Object System.Data.SqlClient.SqlCommand $syncTableQuery, $connection
if($commit)
{
$syncTableCommand.ExecuteScalar()
}
# ensure sql table columns
$viewColumns = ""
$syncColumnsQuery = $sqlCreateColumn.replace("{TABLENAME}",$targetTableName).replace("{COLUMN}", $sourcePrimaryKey).replace("{TYPE}", "int")
for($c = 0; $c -lt $view.viewfields.count; $c++)
{
$field = $list.fields.getfieldbyinternalname($view.viewfields[$c])
$columns = GetColumnFromField -field $field -row $null
foreach($column in $columns)
{
if($column.internalname -eq "ID")
{
continue
}
write-host "Ensuring column: $($column[0]) - $($column[1])"
$syncColumnsQuery += $sqlCreateColumn.replace("{TABLENAME}",$targetTableName).replace("{COLUMN}", $column[0]).replace("{TYPE}", $column[1])
$viewColumns += "[$($column[0])] as [$($column[3])],"
}
}
$syncColumnsCommand = New-Object System.Data.SqlClient.SqlCommand $syncColumnsQuery, $connection
if($commit)
{
$syncColumnsCommand.ExecuteScalar()
}
write-host "Sql columns ensured"
# ensure sql view
if($false)
{
$createViewQuery = $sqlCreateView.replace("{TABLENAME}",$targetTableName).replace("{VIEWNAME}",$targetViewName).replace("{COLUMNS}", $viewColumns.trimend(','))
$createViewCommand = New-Object System.Data.SqlClient.SqlCommand $createViewQuery, $connection
if($commit)
{
$createViewCommand.ExecuteScalar()
}
}
# read data from sql
$imported = new-object System.Collections.Hashtable
$selectCommandQuery = $sqlSelect
$selectCommand = New-Object System.Data.SqlClient.SqlCommand $selectCommandQuery, $connection
$dr = $selectCommand.ExecuteReader()
if ($dr.HasRows)
{
while ($dr.Read())
{
$key = $dr[$sourcePrimaryKey]
$value = $dr[$targetPrimaryKey]
if($imported.containskey($key) -eq $false)
{
$imported.add($key,$value)
}
}
}
$dr.close()
write-host "Loaded already imported rows: $($imported.count)"
# read data from list
$query = new-object microsoft.sharepoint.spquery
$query.query = $view.Query
$query.ViewAttributes = "Scope='Recursive'";
#$query.RowLimit = 40
$data = $list.getitems($query)
write-host "Loaded sharepoint list items: $($data.count)"
write-host "Processing items count: $($data.count)"
foreach($row in $data)
{
$key = $row[$sourcePrimaryKey]
Write-host "Processing item: $key... " -nonewline
if($imported.containskey($key))
{
Write-host "Row found Sql ID: $($imported[$key])... " -for yellow -nonewline
# generate update query
$updateColumnValues = ""
foreach($fieldInternalName in $view.viewfields)
{
if($fieldInternalName -eq "ID")
{
continue
}
$field = $list.fields.getfieldbyinternalname($fieldInternalName)
$columns = GetColumnFromField -field $field -row $row
foreach($column in $columns)
{
#write-host "Updating value: $($column[0]) - $($column[1]) => $($column[2])"
$updateColumnValues += "[" + $column[0] + "] = #" + $column[0] + ","
}
}
Write-host "UpdateQuery generated... " -nonewline -for green
# execute insert query
$updateCommandQuery = $sqlUpdate.replace("{COLUMNVALUES}", $updateColumnValues.TrimEnd(',')).replace("{IDVALUE}", $key)
$updateCommand = New-Object System.Data.SqlClient.SqlCommand $updateCommandQuery, $connection
# add values to parameters
foreach($fieldInternalName in $view.viewfields)
{
if($fieldInternalName -eq "ID")
{
continue
}
$field = $list.fields.getfieldbyinternalname($fieldInternalName)
$columns = GetColumnFromField -field $field -row $row
foreach($column in $columns)
{
$param = $updateCommand.Parameters.AddWithValue("#" + $column[0], $column[2])
}
}
if($commit)
{
$updateCommand.ExecuteScalar()
}
Write-host "UpdateQuery executed" -for green
}
else
{
# generate insert query with parameters
$insertCommand_Part1 = "[" + $sourcePrimaryKey + "],"
$insertCommand_Part2 = $row[$sourcePrimaryKey].tostring() + ","
foreach($fieldInternalName in $view.viewfields)
{
if($fieldInternalName -eq "ID")
{
continue
}
$field = $list.fields.getfieldbyinternalname($fieldInternalName)
$columns = GetColumnFromField -field $field -row $row
foreach($column in $columns)
{
#write-host "Setting value: $($column[0]) - $($column[1]) => $($column[2])"
$insertCommand_Part1 += "[" + $column[0] + "],"
$insertCommand_Part2 += "#" + $column[0] + ","
}
}
Write-host "InsertQuery generated... " -nonewline -for green
# execute insert query
$insertCommandQuery = $sqlInsert.replace("{COLUMNS}", $insertCommand_Part1.TrimEnd(',')).replace("{VALUES}", $insertCommand_Part2.TrimEnd(','))
$insertCommand = New-Object System.Data.SqlClient.SqlCommand $insertCommandQuery, $connection
# add values to parameters
foreach($fieldInternalName in $view.viewfields)
{
if($fieldInternalName -eq "ID")
{
continue
}
$field = $list.fields.getfieldbyinternalname($fieldInternalName)
$columns = GetColumnFromField -field $field -row $row
foreach($column in $columns)
{
$param = $insertCommand.Parameters.AddWithValue("#" + $column[0], $column[2])
}
}
if($commit)
{
$insertCommand.ExecuteScalar()
}
Write-host "InsertQuery executed" -for green
}
}
}
catch
{
$wasError = $true
write-host "error occured" -for red
write-host "$([system.datetime]::now.tostring(""yyyy.MM.dd_HH.mm.ss.ffff"")) - error: $($_.Exception.Message) in script: $($_.fullname)"
write-host "$([system.datetime]::now.tostring(""yyyy.MM.dd_HH.mm.ss.ffff"")) - error details: $($_.Exception.tostring())"
write-host "$([system.datetime]::now.tostring(""yyyy.MM.dd_HH.mm.ss.ffff"")) - error stack: $($_.ScriptStackTrace)"
write-host "$([system.datetime]::now.tostring(""yyyy.MM.dd_HH.mm.ss.ffff"")) - error position: $($_.invocationinfo.positionmessage)"
}
if($connection -ne $null)
{
$connection.close()
}
if($wasError)
{
write-host "Script encountered error" -for red
}
else
{
write-host "No error occured" -for green
}
write-host "Finished $([DateTime]::Now.ToString())"
Foreach loop to get item versions and comments ->
foreach($item in $items){
foreach($version in $item.Versions)
{
if($item["ID"] -eq $($item.id)){
#$VersionData = "$($version['Odpoved'])"
if($VersionData -ne $null){
if($item['Export_Odpoved'] -ne $version['Odpoved']){
#write-host $version['Odpoved']
#write-host $VersionData.ToString();
$item["Export_Odpoved"] += $version['Odpoved']
#write-host $item["Export_Odpoved"]
$item.SystemUpdate()
write-host $item["ID"] "updated" -ForegroundColor Green
#write-host #$VersionData "||" $item["ID"] "updated" -ForegroundColor Green
} else{write-host "preskakujem ziadost, nakolko je korektne zmigrovana" $item["ID"] -ForegroundColor Yellow}
};
};
};
};
Any suggestions to make it work ? Thanks

laravel-filemanager, Sort by time default

I need load files order by "time DESC" when the iframe of laravel-filemanager is called.
Is posible? I read the code and see that we cant order by time DESC and the code dont have options to configure a default "sort_type"
https://github.com/UniSharp/laravel-filemanager
this is not good idea but it's work for me
i am change the code in vendor/unisharp/laravel-filemanager/public/js/script.js
var sort_type = 'alphabetic';
to
var sort_type = 'time';
if you want to sort date in desc order. change the code in
vendor/unisharp/laravel-filemanager/src/Controllers/ItemsController.php
public function getItems()
{
$currentPage = self::getCurrentPageFromRequest();
$perPage = $this->helper->getPaginationPerPage();
$items = array_merge($this->lfm->folders(), $this->lfm->files());
return [
'items' => array_map(function ($item) {
return $item->fill()->attributes;
}, array_slice($items, ($currentPage - 1) * $perPage, $perPage)),
'paginator' => [
'current_page' => $currentPage,
'total' => count($items),
'per_page' => $perPage,
],
'display' => $this->helper->getDisplayMode(),
'working_dir' => $this->lfm->path('working_dir'),
];
}
with
use Illuminate\Http\Request;
public function getItems(Request $request)
{
$currentPage = self::getCurrentPageFromRequest();
$perPage = $this->helper->getPaginationPerPage();
$files = $this->lfm->files();
if($request->sort_type=='time'){
$files = array_reverse($files);
}
$items = array_merge($this->lfm->folders(), $files);
return [
'items' => array_map(function ($item) {
return $item->fill()->attributes;
}, array_slice($items, ($currentPage - 1) * $perPage, $perPage)),
'paginator' => [
'current_page' => $currentPage,
'total' => count($items),
'per_page' => $perPage,
],
'display' => $this->helper->getDisplayMode(),
'working_dir' => $this->lfm->path('working_dir'),
];
}
i'm change the code in vendor/unisharp/laravel-filemanager/src/traits/LfmHelpers.php
and it's worked
public function sortFilesAndDirectories($arr_items, $sort_type)
{
if ($sort_type == 'time') {
$key_to_sort = 'updated';
} elseif ($sort_type == 'alphabetic') {
$key_to_sort = 'name';
} else {
$key_to_sort = 'updated';
}
return strcmp($a->{$key_to_sort}, $b->{$key_to_sort});
});
return $arr_items;
}
with
public function sortFilesAndDirectories($arr_items, $sort_type)
{
if ($sort_type == 'time') {
$key_to_sort = 'updated';
} elseif ($sort_type == 'alphabetic') {
$key_to_sort = 'name';
} else {
$key_to_sort = 'updated';
}
uasort($arr_items, function ($a, $b) use ($key_to_sort) {
if ( $a->$key_to_sort == $a->$key_to_sort )
return 0;
else if ( $a->$key_to_sort > $a->$key_to_sort)
return -1;
else
return 1;
});
return $arr_items;
}
LFM 1.8:
Also, you can use this method, if you don't want to change the LFM Src code.
First use this command to generate views :
php artisan vendor:publish --tag=lfm_view
Find this file:
ROOT/resources/views/vendor/laravel-filemanager/grid-view.blade.php
and change the cod according the follow:
#if((sizeof($files) > 0) || (sizeof($directories) > 0))
<div class="row">
<!-- -----------------------------------Begin of added block -->
<?php
$file_temp = [];
if($files != null){
foreach ($files as $key => $value) {
$file_temp[$value['updated']] = $value;
}
krsort($file_temp);
$file_temp1 = [];
$i = 0;
foreach ($file_temp as $key => $value) {
$file_temp1[$i] = $value;
$i+=1;
}
$files = $file_temp1;
}
?>
<!-- ---------------------------------------End of added block -->
#foreach($items as $item)
....
...
As you can see, the <?php ?> code block was added.You can use krsort() or ksort() as you want for descending or ascending.
In 2.3 I did next steps
php artisan vendor:publish --tag=lfm_view
Then you can find file
ROOT/resources/views/vendor/laravel-filemanager/grid-view.blade.php
And after incuding
<script>{!! \File::get(base_path('vendor/unisharp/laravel-filemanager/public/js/script.js')) !!}</script>
I added one line of js
sort_type = 'time';
But files sorts from the oldest to the newest. Thast's why I redefined routes and ItemsController

cart gets empty after adding a product and moving to checkout or cart in opencart

Im having a very strange problem. When i add a product to my shopping cart on top header it shows the cart details/products. But when i click on the cart or checkout it says my cart is empty. So each time when i add the product and move to checkout or cart it automatically becomes empty.
I have tried the site on firefox, chrome and in different PCs but still the same problem. But the weird part is when i run firebug and move to the console to see the calls, the site works perfectly. But when i close firebug and refresh the page or move the cart becomes empty again.
Can someone tell me what might the problem be?
Im using Opencart 1.5.4
Checkout controller function
public function index() {
// Validate cart has products and has stock.
if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
$this->redirect($this->url->link('checkout/cart'));
}
// Validate minimum quantity requirments.
$products = $this->cart->getProducts();
foreach ($products as $product) {
$product_total = 0;
foreach ($products as $product_2) {
if ($product_2['product_id'] == $product['product_id']) {
$product_total += $product_2['quantity'];
}
}
if ($product['minimum'] > $product_total) {
$this->redirect($this->url->link('checkout/cart'));
}
}
$this->language->load('checkout/checkout');
$this->document->setTitle($this->language->get('heading_title'));
$this->data['breadcrumbs'] = array();
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home'),
'separator' => false
);
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('text_cart'),
'href' => $this->url->link('checkout/cart'),
'separator' => $this->language->get('text_separator')
);
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('checkout/checkout', '', 'SSL'),
'separator' => $this->language->get('text_separator')
);
$this->data['heading_title'] = $this->language->get('heading_title');
$this->data['text_checkout_option'] = $this->language->get('text_checkout_option');
$this->data['text_checkout_account'] = $this->language->get('text_checkout_account');
$this->data['text_checkout_payment_address'] = $this->language->get('text_checkout_payment_address');
$this->data['text_checkout_shipping_address'] = $this->language->get('text_checkout_shipping_address');
$this->data['text_checkout_shipping_method'] = $this->language->get('text_checkout_shipping_method');
$this->data['text_checkout_payment_method'] = $this->language->get('text_checkout_payment_method');
$this->data['text_checkout_confirm'] = $this->language->get('text_checkout_confirm');
$this->data['text_modify'] = $this->language->get('text_modify');
$this->data['logged'] = $this->customer->isLogged();
$this->data['shipping_required'] = $this->cart->hasShipping();
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/checkout.tpl')) {
$this->template = $this->config->get('config_template') . '/template/checkout/checkout.tpl';
} else {
$this->template = 'default/template/checkout/checkout.tpl';
}
$this->children = array(
'common/column_left',
'common/column_right',
'common/content_top',
'common/content_bottom',
'common/footer',
'common/header'
);
$this->response->setOutput($this->render());
}
cart controller
public function index() {
$this->language->load('checkout/cart');
if (!isset($this->session->data['vouchers'])) {
$this->session->data['vouchers'] = array();
}
// Update
if (!empty($this->request->post['quantity'])) {
foreach ($this->request->post['quantity'] as $key => $value) {
$this->cart->update($key, $value);
}
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
unset($this->session->data['reward']);
$this->redirect($this->url->link('checkout/cart'));
}
// Remove
if (isset($this->request->get['remove'])) {
$this->cart->remove($this->request->get['remove']);
unset($this->session->data['vouchers'][$this->request->get['remove']]);
$this->session->data['success'] = $this->language->get('text_remove');
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
unset($this->session->data['reward']);
$this->redirect($this->url->link('checkout/cart'));
}
// Coupon
if (isset($this->request->post['coupon']) && $this->validateCoupon()) {
$this->session->data['coupon'] = $this->request->post['coupon'];
$this->session->data['success'] = $this->language->get('text_coupon');
$this->redirect($this->url->link('checkout/cart'));
}
// Voucher
if (isset($this->request->post['voucher']) && $this->validateVoucher()) {
$this->session->data['voucher'] = $this->request->post['voucher'];
$this->session->data['success'] = $this->language->get('text_voucher');
$this->redirect($this->url->link('checkout/cart'));
}
// Reward
if (isset($this->request->post['reward']) && $this->validateReward()) {
$this->session->data['reward'] = abs($this->request->post['reward']);
$this->session->data['success'] = $this->language->get('text_reward');
$this->redirect($this->url->link('checkout/cart'));
}
// Shipping
if (isset($this->request->post['shipping_method']) && $this->validateShipping()) {
$shipping = explode('.', $this->request->post['shipping_method']);
$this->session->data['shipping_method'] = $this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]];
$this->session->data['success'] = $this->language->get('text_shipping');
$this->redirect($this->url->link('checkout/cart'));
}
$this->document->setTitle($this->language->get('heading_title'));
$this->data['breadcrumbs'] = array();
$this->data['breadcrumbs'][] = array(
'href' => $this->url->link('common/home'),
'text' => $this->language->get('text_home'),
'separator' => false
);
$this->data['breadcrumbs'][] = array(
'href' => $this->url->link('checkout/cart'),
'text' => $this->language->get('heading_title'),
'separator' => $this->language->get('text_separator')
);
if ($this->cart->hasProducts() || !empty($this->session->data['vouchers'])) {
$points = $this->customer->getRewardPoints();
$points_total = 0;
foreach ($this->cart->getProducts() as $product) {
if ($product['points']) {
$points_total += $product['points'];
}
}
$this->data['heading_title'] = $this->language->get('heading_title');
$this->data['text_next'] = $this->language->get('text_next');
$this->data['text_next_choice'] = $this->language->get('text_next_choice');
$this->data['text_use_coupon'] = $this->language->get('text_use_coupon');
$this->data['text_use_voucher'] = $this->language->get('text_use_voucher');
$this->data['text_use_reward'] = sprintf($this->language->get('text_use_reward'), $points);
$this->data['text_shipping_estimate'] = $this->language->get('text_shipping_estimate');
$this->data['text_shipping_detail'] = $this->language->get('text_shipping_detail');
$this->data['text_shipping_method'] = $this->language->get('text_shipping_method');
$this->data['text_select'] = $this->language->get('text_select');
$this->data['text_none'] = $this->language->get('text_none');
$this->data['column_image'] = $this->language->get('column_image');
$this->data['column_name'] = $this->language->get('column_name');
$this->data['column_model'] = $this->language->get('column_model');
$this->data['column_quantity'] = $this->language->get('column_quantity');
$this->data['column_price'] = $this->language->get('column_price');
$this->data['column_total'] = $this->language->get('column_total');
$this->data['entry_coupon'] = $this->language->get('entry_coupon');
$this->data['entry_voucher'] = $this->language->get('entry_voucher');
$this->data['entry_reward'] = sprintf($this->language->get('entry_reward'), $points_total);
$this->data['entry_country'] = $this->language->get('entry_country');
$this->data['entry_zone'] = $this->language->get('entry_zone');
$this->data['entry_postcode'] = $this->language->get('entry_postcode');
$this->data['button_update'] = $this->language->get('button_update');
$this->data['button_remove'] = $this->language->get('button_remove');
$this->data['button_coupon'] = $this->language->get('button_coupon');
$this->data['button_voucher'] = $this->language->get('button_voucher');
$this->data['button_reward'] = $this->language->get('button_reward');
$this->data['button_quote'] = $this->language->get('button_quote');
$this->data['button_shipping'] = $this->language->get('button_shipping');
$this->data['button_shopping'] = $this->language->get('button_shopping');
$this->data['button_checkout'] = $this->language->get('button_checkout');
if (isset($this->error['warning'])) {
$this->data['error_warning'] = $this->error['warning'];
} elseif (!$this->cart->hasStock() && (!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning'))) {
$this->data['error_warning'] = $this->language->get('error_stock');
} else {
$this->data['error_warning'] = '';
}
if ($this->config->get('config_customer_price') && !$this->customer->isLogged()) {
$this->data['attention'] = sprintf($this->language->get('text_login'), $this->url->link('account/login'), $this->url->link('account/register'));
} else {
$this->data['attention'] = '';
}
if (isset($this->session->data['success'])) {
$this->data['success'] = $this->session->data['success'];
unset($this->session->data['success']);
} else {
$this->data['success'] = '';
}
$this->data['action'] = $this->url->link('checkout/cart');
if ($this->config->get('config_cart_weight')) {
$this->data['weight'] = $this->weight->format($this->cart->getWeight(), $this->config->get('config_weight_class_id'), $this->language->get('decimal_point'), $this->language->get('thousand_point'));
} else {
$this->data['weight'] = '';
}
$this->load->model('tool/image');
$this->data['products'] = array();
$products = $this->cart->getProducts();
foreach ($products as $product) {
$product_total = 0;
foreach ($products as $product_2) {
if ($product_2['product_id'] == $product['product_id']) {
$product_total += $product_2['quantity'];
}
}
if ($product['minimum'] > $product_total) {
$this->data['error_warning'] = sprintf($this->language->get('error_minimum'), $product['name'], $product['minimum']);
}
if ($product['image']) {
$image = $this->model_tool_image->resize($product['image'], $this->config->get('config_image_cart_width'), $this->config->get('config_image_cart_height'));
} else {
$image = '';
}
$option_data = array();
foreach ($product['option'] as $option) {
if ($option['type'] != 'file') {
$value = $option['option_value'];
} else {
$filename = $this->encryption->decrypt($option['option_value']);
$value = utf8_substr($filename, 0, utf8_strrpos($filename, '.'));
}
$option_data[] = array(
'name' => $option['name'],
'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
);
}
// Display prices
if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
$price = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
} else {
$price = false;
}
// Display prices
if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
$total = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity']);
} else {
$total = false;
}
$this->data['products'][] = array(
'key' => $product['key'],
'thumb' => $image,
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'quantity' => $product['quantity'],
'stock' => $product['stock'] ? true : !(!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')),
'reward' => ($product['reward'] ? sprintf($this->language->get('text_points'), $product['reward']) : ''),
'price' => $price,
'total' => $total,
'href' => $this->url->link('product/product', 'product_id=' . $product['product_id']),
'remove' => $this->url->link('checkout/cart', 'remove=' . $product['key'])
);
}
// Gift Voucher
$this->data['vouchers'] = array();
if (!empty($this->session->data['vouchers'])) {
foreach ($this->session->data['vouchers'] as $key => $voucher) {
$this->data['vouchers'][] = array(
'key' => $key,
'description' => $voucher['description'],
'amount' => $this->currency->format($voucher['amount']),
'remove' => $this->url->link('checkout/cart', 'remove=' . $key)
);
}
}
if (isset($this->request->post['next'])) {
$this->data['next'] = $this->request->post['next'];
} else {
$this->data['next'] = '';
}
$this->data['coupon_status'] = $this->config->get('coupon_status');
if (isset($this->request->post['coupon'])) {
$this->data['coupon'] = $this->request->post['coupon'];
} elseif (isset($this->session->data['coupon'])) {
$this->data['coupon'] = $this->session->data['coupon'];
} else {
$this->data['coupon'] = '';
}
$this->data['voucher_status'] = $this->config->get('voucher_status');
if (isset($this->request->post['voucher'])) {
$this->data['voucher'] = $this->request->post['voucher'];
} elseif (isset($this->session->data['voucher'])) {
$this->data['voucher'] = $this->session->data['voucher'];
} else {
$this->data['voucher'] = '';
}
$this->data['reward_status'] = ($points && $points_total && $this->config->get('reward_status'));
if (isset($this->request->post['reward'])) {
$this->data['reward'] = $this->request->post['reward'];
} elseif (isset($this->session->data['reward'])) {
$this->data['reward'] = $this->session->data['reward'];
} else {
$this->data['reward'] = '';
}
$this->data['shipping_status'] = $this->config->get('shipping_status') && $this->config->get('shipping_estimator') && $this->cart->hasShipping();
if (isset($this->request->post['country_id'])) {
$this->data['country_id'] = $this->request->post['country_id'];
} elseif (isset($this->session->data['shipping_country_id'])) {
$this->data['country_id'] = $this->session->data['shipping_country_id'];
} else {
$this->data['country_id'] = $this->config->get('config_country_id');
}
$this->load->model('localisation/country');
$this->data['countries'] = $this->model_localisation_country->getCountries();
if (isset($this->request->post['zone_id'])) {
$this->data['zone_id'] = $this->request->post['zone_id'];
} elseif (isset($this->session->data['shipping_zone_id'])) {
$this->data['zone_id'] = $this->session->data['shipping_zone_id'];
} else {
$this->data['zone_id'] = '';
}
if (isset($this->request->post['postcode'])) {
$this->data['postcode'] = $this->request->post['postcode'];
} elseif (isset($this->session->data['shipping_postcode'])) {
$this->data['postcode'] = $this->session->data['shipping_postcode'];
} else {
$this->data['postcode'] = '';
}
if (isset($this->request->post['shipping_method'])) {
$this->data['shipping_method'] = $this->request->post['shipping_method'];
} elseif (isset($this->session->data['shipping_method'])) {
$this->data['shipping_method'] = $this->session->data['shipping_method']['code'];
} else {
$this->data['shipping_method'] = '';
}
// Totals
$this->load->model('setting/extension');
$total_data = array();
$total = 0;
$taxes = $this->cart->getTaxes();
// Display prices
if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
$sort_order = array();
$results = $this->model_setting_extension->getExtensions('total');
foreach ($results as $key => $value) {
$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
}
array_multisort($sort_order, SORT_ASC, $results);
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('total/' . $result['code']);
$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
}
$sort_order = array();
foreach ($total_data as $key => $value) {
$sort_order[$key] = $value['sort_order'];
}
array_multisort($sort_order, SORT_ASC, $total_data);
}
}
$this->data['totals'] = $total_data;
$this->data['continue'] = $this->url->link('common/home');
$this->data['checkout'] = $this->url->link('checkout/checkout', '', 'SSL');
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/cart.tpl')) {
$this->template = $this->config->get('config_template') . '/template/checkout/cart.tpl';
} else {
$this->template = 'default/template/checkout/cart.tpl';
}
$this->children = array(
'common/column_left',
'common/column_right',
'common/content_bottom',
'common/content_top',
'common/footer',
'common/header'
);
$this->response->setOutput($this->render());
} else {
$this->data['heading_title'] = $this->language->get('heading_title');
$this->data['text_error'] = $this->language->get('text_empty');
$this->data['button_continue'] = $this->language->get('button_continue');
$this->data['continue'] = $this->url->link('common/home');
unset($this->session->data['success']);
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/error/not_found.tpl')) {
$this->template = $this->config->get('config_template') . '/template/error/not_found.tpl';
} else {
$this->template = 'default/template/error/not_found.tpl';
}
$this->children = array(
'common/column_left',
'common/column_right',
'common/content_top',
'common/content_bottom',
'common/footer',
'common/header'
);
$this->response->setOutput($this->render());
}
}
session library
class Session {
public $data = array();
public function __construct() {
if (!session_id()) {
ini_set('session.use_cookies', 'On');
ini_set('session.use_trans_sid', 'Off');
session_set_cookie_params(0, '/');
session_start();
}
$this->data =& $_SESSION;
}
function getId() {
return session_id();
}
}
It's extremely hard to say, where's the root of the problem. If you have any 3rd party extensions (VQMods), they can change original OpenCart code. In this case you should look in cached files, not original ones. That's for the start.

Error occurs with while Loop PHP / MySQL NuSOAP

I have created a PHP / MySQL based web service. I wrote client.php as mentioned here
and server.php as below:
<?php
require_once("lib/nusoap.php");
$host = $_SERVER['HTTP_HOST'];
$miURL = 'http://'.$host.'/WS-Demo';
$server = new nusoap_server();
$server->configureWSDL('L3M_WebService', $miURL);
$server->wsdl->schemaTargetNamespace=$miURL;
$server->register('getDemoData',
array('fldpara' => 'xsd:Array', 'tblpara' => 'xsd:Array', 'cndpara' => 'xsd:Array'),
array('return' => 'xsd:string'),
$miURL);
function decryptRJ256($string_to_decrypt)
{
$key = 'salt_key - I';
$iv = 'salt_key - II';
$string_to_decrypt = base64_decode($string_to_decrypt);
$rtn = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_decrypt, MCRYPT_MODE_CBC, $iv);
$rtn = rtrim($rtn, "\4");
return($rtn);
}
function encryptRJ256($string_to_encrypt)
{
$key = 'salt_key - I';
$iv = 'salt_key - II';
$rtn = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_encrypt, MCRYPT_MODE_CBC, $iv);
$rtn = base64_encode($rtn);
return($rtn);
}
function getDemoData($flds, $tbls, $cnds){
$mysqli = new mysqli("localhost", "root", "", "test");
for($i=0;$i< count($flds); $i++) {
$flds[$i] = decryptRJ256($flds[$i]);
}
for($i=0;$i< count($tbls); $i++) {
$tbls[$i] = decryptRJ256($tbls[$i]);
}
for($i=0;$i< count($cnds); $i++) {
$cnds[$i] = decryptRJ256($cnds[$i]);
}
if(! empty($flds)) {
$what = implode(", ", $flds);
} else {
$what = "*";
}
if(! empty($tbls)) {
$from = implode(", ", $tbls);
}else {
$err = 1;
}
if(! empty($cnds)) {
$cond = " WHERE ";
$cond .= $cnds[0] . " = '" . $cnds[1] . "'";
} else {
$cond = "";
}
$sql = "SELECT ".$what." FROM ".$from . $cond;
$rsGetData = $mysqli->query($sql);
$responseData = '<?xml version="1.0" encoding="UTF-8"?>
<L3MDataSets>';
while($rowGetData = $rsGetData->fetch_assoc()) {
$responseData .= '<L3DataSet>';
foreach($rowGetData as $k => $v) {
$responseData .= '<' . $k . '>' . $v . '</' . $k . '>';
}
$responseData .= '</L3DataSet>';
}
$responseData .= '</L3MDataSets>';
$responseData = encryptRJ256($responseData);
$responseString = new soapval('return', 'xsd:string', $responseData );
return $responseData;
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
From the Above code in the getDemoData function, if I remove the while loop, it gives the proper output. But when I put back the while loop it shows me output as "-Error: Response not of type text/xml: text/html" even if the SQL query is correct. I have copied and paste the generated SQL query which works in phpMyAdmin.

How to search a substring in PHP array using regExp

$array = array(
array('foo_test1','demo_test1'),
array('foo_test2','demo_test2'),
array('blah_test1','exp_test1'),
array('blah_test2','exp_test2'),
array('foo_test3','demo_test3')
)
How to get all subarray which contains foo substring with its value using php and regExp.
Expected Output:
$array = array(
array('foo_test1','demo_test1'),
array('foo_test2','demo_test2'),
array('foo_test3','demo_test3')
)
You should be able to do it with
preg_grep($pattern,$array)
$input = array( /* your array */ );
$output = array();
foreach ( $input as $data ) {
$len = length($data);
for ( $i = 0; $i < $len; ++$i ) {
if ( strpos($data[$i], 'foo') > -1 ) {
$output[] = $data;
break;
}
}
}
$array = array(
array('foo_test1','demo_test1'),
array('foo_test2','demo_test2'),
array('blah_test1','exp_test1'),
array('blah_test2','exp_test2'),
array('foo_test3','demo_test3')
);
$search = 'foo';
$res = array();
foreach ($array as $arr) {
foreach ($arr as $value) {
if (preg_match('~'.preg_quote($search,'~').'~',$value)) {
// if one of the values in that array
// has the search word in it...
$res[] = $arr; break;
// push it into the $res and break
// the inner foreach loop
}
}
}
print_r($res);