Error occurs with while Loop PHP / MySQL NuSOAP - web-services

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.

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

Format AWS Transcribe Audio Identification

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

Single Column Drop down instead of a two column drop down

Hi I am trying to make this two column drop down just a single column. I can't identify how to modify the code to do this. This is a custom them for open cart.
public function drawMenuItem($children, $level = 0, $columChunk = 0, $lang_id = 1,$setting) {
$lang_id = (int)$this->config->get('config_language_id');
$this->load->model('catalog/category');
$html = '<div class="itemMenu level' . $level . '">';
$countChildren = 0;
$ClassNoChildren = '';
foreach ($children as $child) {
$activeChildCat = $this->model_catalog_category->getCategories($child['category_id']);
$activeChildCat = $this->getCategoryByLevelMax($activeChildCat,$setting);
if ($activeChildCat) {
$countChildren++;
}
}
if ($countChildren == 0 && $columChunk == 1) {
$ClassNoChildren = ' nochild';
}
foreach ($children as $child) {
$info = $this->model_catalog_category->getCategory($child['category_id']);
$level = (int) $this->getCategoryLevelByCateId($child['category_id']);
$active = '';
//$currentCate = $this->getCurrentCategoriesId($lang_id);
$cate_id = (int) $child['category_id'];
// if (in_array($cate_id, $currentCate)) {
if ($this->haveCateChildren($cate_id, $lang_id)) {
$active = ' actParent';
} else {
$active = ' act';
}
//}
// --- format category name ---
$name = strip_tags($child['name']);
if (count($child) > 0) {
$parameters = null;
$link = $this->url->link('product/category', "path=".$child['category_id']);
$html.= '<a class="itemMenuName level' . $level . $active . $ClassNoChildren . '" href="' . $link . '"><span>' . $name .'</span></a>';
if($setting['hlevel'] > 2 && $level <= $setting['hlevel'] ) {
$activeChildren = $this->model_catalog_category->getCategories($child['category_id']);
$activeChildren = $this->getCategoryByLevelMax($activeChildren,$setting);
if (count($activeChildren) > 0) {
$html.= '<div class="itemSubMenu level' . $level . '">';
//$html.= $this->drawMenuItem($activeChildren, $level + 1);
$html.= $this->drawMenuItem($activeChildren, $level ,$columChunk, $lang_id,$setting);
$html.= '</div>';
}
}
}
}
$html.= '</div>';
return $html;
}
The columns are s which are floated left (float: left;) with CSS which makes them appear next to each other.
If you remove the "float: left;" in custommenu.css around line 75, it will display as you desire.

opencart custom download file error

i am looking to make download files in product page without login or registration in opencart as public download link, after doing the coding am not getting the right download file and also a unknow and unformatted file is downloaded. what i get screnshot
model file
public function getProductDownloads($product_id) {
$query = $this->db->query("SELECT d.download_id, d.filename, d.mask, dd.name FROM " . DB_PREFIX . "download d LEFT JOIN " . DB_PREFIX . "download_description dd USING ( download_id ) LEFT JOIN " . DB_PREFIX . "product_to_download p2d USING ( download_id ) WHERE p2d.product_id = '" . (int)$product_id . "'");
return $query->rows;
}
public function getDownload($download_id) {
$query = $this->db->query("SELECT d.filename, d.mask, dd.name FROM " . DB_PREFIX . "download d LEFT JOIN " . DB_PREFIX . "download_description dd ON (d.download_id = dd.download_id) where d.download_id AND dd.download_id = '" . (int)$download_id . "'");
return $query->rows;
}
controller file
$data['downloads'] = array();
$results = $this->model_catalog_product->getProductDownloads($this->request->get['product_id']);
foreach ($results as $result) {
$data['downloads'][] = array(
'filename' => $result['filename'],
'name' => $result['name'],
'href' => $this->url->link('product/product/download', 'download_id=' . $result['download_id'], 'SSL')
);
}
/*download*/
public function download() {
$this->load->model('catalog/product');
if (isset($this->request->get['download_id'])) {
$download_id = $this->request->get['download_id'];
} else {
$download_id = 0;
}
$download_info = $this->model_catalog_product->getDownload($download_id);
if ($download_info) {
$file = DIR_DOWNLOAD . $download_info['filename'];
$mask = basename($download_info['mask']);
if (!headers_sent()) {
if (file_exists($file)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . ($mask ? $mask : basename($file)) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
if (ob_get_level()) {
ob_end_clean();
}
readfile($file, 'rb');
exit();
} else {
exit('Error: Could not find file ' . $file . '!');
}
} else {
exit('Error: Headers already sent out!');
}
} else {
$this->response->redirect($this->url->link('common/home', '', 'SSL'));
}
}
}
view file
<?php foreach ($downloads as $download) { ?>
<?php echo $download['filename']; ?><br/>
<?php echo $download['name']; ?><br/>
download<br/>
<?php } ?>
You have to make some changes in controller file. I have changed your code. Just replace following code with download function. Hope this could help.
public function download() {
$this->load->model('catalog/product');
if (isset($this->request->get['download_id'])) {
$download_id = $this->request->get['download_id'];
} else {
$download_id = 0;
}
$download_info = $this->model_catalog_product->getDownload($download_id);
if ($download_info) {
$file = DIR_DOWNLOAD . $download_info[0]['filename'];
$mask = basename($download_info[0]['mask']);
if (!headers_sent()) {
if (file_exists($file)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . ($mask ? $mask : basename($file)) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
if (ob_get_level()) {
ob_end_clean();
}
readfile($file, 'rb');
exit();
} else {
exit('Error: Could not find file ' . $file . '!');
}
} else {
exit('Error: Headers already sent out!');
}
} else {
$this->response->redirect($this->url->link('common/home', '', 'SSL'));
}
}`

opencart site upgrade from version1.4.x to 1.5.x

I have upgrade my opencart site version 1.4.9.2 to version1.5.X,
I upgrade the database but don't know how to upgrade the files.
If there is any script regarding this please send me.
I use the script to update the table:-
<?php
# Upgrade Script Beta v2
// Run full install if config doesn't exist
if (!file_exists('../config.php')) {
header('Location: ./index.php');
exit;
}
set_error_handler("myErrorHandler");
// Configuration
require_once('../config.php');
// Startup
require_once(DIR_SYSTEM . 'startup.php');
// Get Path & Url
$errors = array();
$baseurl=(isset($_SERVER['HTTPS']) ? 'https' :'http'). '://' . $_SERVER['HTTP_HOST'] . str_replace('/install','',dirname($_SERVER['REQUEST_URI']));
chdir('..');
$basepath=getcwd();
chdir(dirname(__FILE__));
if (!$link = #mysql_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD)) {
$errors[] = 'Could not connect to the database server using the username and password provided.';
} else {
if (!#mysql_select_db(DB_DATABASE, $link)) {
$errors[] = 'The database could selected, check you have permissions, and check it exists on the server.';
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Installation</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>OpenCart 1.x Upgrade Script (BETA)</h1>
<div id="container">
<?php
function myErrorHandler($errno, $errstr, $errfile, $errline) {
echo "LINE $errline: [$errno] $errstr<br/>";
return;
}
if (empty($errors)) {
// Run upgrade script
$file='upgrade-14x-to-15x.no-opt.sql';
if (!file_exists($file)) {
$errors[] = 'Upgrade SQL file '.$file.' could not be found.';
} else {
mysql_query('set character set utf8', $link);
if ($sql=file($file)) {
$query = '';
foreach($sql as $line) {
// Hacks for compatibility (needs to be improved)
$line = str_replace("oc_", DB_PREFIX, $line);
$line = str_replace(" order ", " `order` ", $line);
$line = str_replace(" ssl ", " `ssl` ", $line);
$line = str_replace("NOT NULL DEFAULT ''", "NOT NULL", $line);
$line = str_replace("NOT NULL DEFAULT NULL", "NOT NULL", $line);
$line = str_replace("NOT NULL DEFAULT 0 COMMENT '' auto_increment", "NOT NULL COMMENT '' auto_increment", $line);
$line = trim($line);
//$line = str_replace(";", "", $line);
if ((substr(trim($line), 0, 2) == '--') || (substr(trim($line), 0, 1) == '#')) { continue; }
if (preg_match('/^ALTER TABLE (.+?) ADD PRIMARY KEY/', $line, $matches)) {
$res = mysql_query(sprintf("SHOW KEYS FROM %s",$matches[1]), $link);
$info = mysql_fetch_assoc(mysql_query(sprintf("SHOW KEYS FROM %s",$matches[1]), $link));
if ($info['Key_name'] == 'PRIMARY') { continue; }
}
if (preg_match('/^ALTER TABLE (.+?) ADD (.+?) /', $line, $matches)) {
if (mysql_num_rows(#mysql_query(sprintf("SHOW COLUMNS FROM %s LIKE '%s'", $matches[1],str_replace('`', '', $matches[2])), $link)) > 0) { continue; }
}
if (preg_match('/^ALTER TABLE (.+?) DROP (.+?) /', $line, $matches)) {
if (mysql_num_rows(#mysql_query(sprintf("SHOW COLUMNS FROM %s LIKE '%s'", $matches[1],str_replace('`', '', $matches[2])), $link)) <= 0) { continue; }
}
if (preg_match('/INNER JOIN (.+?) /', $line, $matches)) {
$xx = #mysql_query(sprintf("SHOW TABLES LIKE '%s'", str_replace('`', '', $matches[1])), $link);
if ($xx && mysql_num_rows($xx) <= 0) { continue; }
}
if (preg_match('/^DROP TABLE (.+?);/', $line, $matches)) {
if (preg_match('/^DROP TABLE IF EXISTS (.+?);/', $line, $matches2)) {
//if (mysql_num_rows(#mysql_query(sprintf("DESC %s", str_replace('`', '', $matches2[1])), $link)) <= 0) { continue; }
} else {
if (mysql_num_rows(#mysql_query(sprintf("SHOW TABLES LIKE '%s'", str_replace('`', '', $matches[1])), $link)) <= 0) { continue; }
}
}
if (strpos($line, 'ALTER TABLE') !== FALSE && strpos($line, 'DROP') !== FALSE && strpos($line, 'PRIMARY') === FALSE) {
$params = explode(' ', $line);
if ($params[3] == 'DROP') {
if (mysql_num_rows(#mysql_query("SHOW COLUMNS FROM $params[2] LIKE '$params[4]'", $link)) <= 0) { continue; }
}
}
if (preg_match('/^ALTER TABLE ([^\s]+) DEFAULT (.+?) /', $line, $matches)) {
if (mysql_num_rows(#mysql_query(sprintf("SHOW TABLES LIKE '%s'", str_replace('`', '', $matches[1])), $link)) <= 0) { continue; }
}
if (preg_match('/^ALTER TABLE (.+?) MODIFY (.+?) /', $line, $matches)) {
if (mysql_num_rows(#mysql_query(sprintf("SHOW COLUMNS FROM %s LIKE '%s'", $matches[1],str_replace('`', '', $matches[2])), $link)) <= 0) { continue; }
}
if (preg_match('/^ALTER TABLE (.+?) CHANGE (.+?) (.+?) /', $line, $matches)) {
if (mysql_num_rows(#mysql_query(sprintf("SHOW COLUMNS FROM %s LIKE '%s'", $matches[1],str_replace('`', '', $matches[2])), $link)) <= 0) {
continue;
}
// if it does exist, be sure the new name doesn't also exist. If so, then just delete it.
if (mysql_num_rows(#mysql_query(sprintf("SHOW COLUMNS FROM %s LIKE '%s'", $matches[1],str_replace('`', '', $matches[3])), $link)) > 0) {
#mysql_query(sprintf("ALTER TABLE %s DROP %s", $matches[1], str_replace('`', '', $matches[2])), $link); //Drop the column if it was supposed to be changed to a column that already exists
continue;
}
}
if (preg_match('/^DELETE FROM (.+?) WHERE (.+?) /', $line, $matches)) {
if (preg_match('~ WHERE (.*);$~', $line, $matches2)) {
if (preg_match_all('~`([^`]+)`~', $matches2[1], $matched)) {
$notfound = 0;
foreach ($matched[1] as $m) {
if (mysql_num_rows(#mysql_query(sprintf("SHOW COLUMNS FROM %s LIKE '%s'", $matches[1],str_replace('`', '', $m)), $link)) <= 0) {
$notfound++;
}
}
if ($notfound) { continue; }
}
}
}
if (preg_match('/^INSERT INTO (.+?) \(([^)]+)\) /', $line, $matches)) {
$parts = explode(",", str_replace("`", "", $matches[2]));
$notfound = 0;
foreach ($parts as $m) {
if (mysql_num_rows(#mysql_query(sprintf("SHOW COLUMNS FROM %s LIKE '%s'", $matches[1], trim($m)), $link)) <= 0) {
$notfound++;
}
}
if ($notfound) { continue; }
}
if (preg_match('/^INSERT INTO (.+?) \(([^)]+)\) SELECT ([^FROM]+) FROM `([^`]+)`/', $line, $matches)) {
$parts = explode(",", str_replace("`", "", $matches[3]));
$notfound = 0;
foreach ($parts as $m) {
if (mysql_num_rows(#mysql_query(sprintf("SHOW COLUMNS FROM %s LIKE '%s'", $matches[4], trim($m)), $link)) <= 0) {
$notfound++;
}
}
if ($notfound) { continue; }
}
//if (preg_match('/^ALTER TABLE (.+?) DEFAULT (.+?) /',$line,$matches)) {
// if (mysql_num_rows(#mysql_query(sprintf("SHOW COLUMNS FROM %s LIKE '%s'",$matches[1],str_replace('`','',$matches[2])), $link)) <= 0) { continue; }
//}
//if (preg_match('/^ALTER TABLE (.+?) ALTER (.+?) /',$line,$matches)) {
// if (mysql_num_rows(#mysql_query(sprintf("SHOW COLUMNS FROM %s LIKE '%s'",$matches[1],str_replace('`','',$matches[2])), $link)) <= 0) { continue; }
//}
if (!empty($line)) {
$query .= $line;
if (preg_match('/;\s*$/', $line)) {
if (mysql_query($query, $link) === false) {
$errors[] = 'Could not execute this query: ' . $query . ' ' . mysql_error($link);
}
$query = '';
}
}
}
}
}
}
// Check if there are any products associated with a store (pre-1.4.1)
$info = mysql_fetch_assoc(mysql_query("SELECT * FROM " . DB_PREFIX . "product_to_store", $link));
// If not, then add them all to the default
if (!$info) {
$resource = mysql_query("SELECT product_id FROM " . DB_PREFIX . "product", $link);
$data = array();
$i = 0;
while ($result = mysql_fetch_assoc($resource)) {
$data[$i] = $result;
$i++;
}
foreach ($data as $product) {
mysql_query("INSERT INTO " . DB_PREFIX . "product_to_store SET product_id = '".$product['product_id']."', store_id = '0'", $link);
}
}
// Check if there are any informations associated with a store (pre-1.4.1)
$info = mysql_fetch_assoc(mysql_query("SELECT * FROM " . DB_PREFIX . "information_to_store", $link));
// If not, then add them all to the default
if (!$info) {
$resource = mysql_query("SELECT information_id FROM " . DB_PREFIX . "information", $link);
$data = array();
$i = 0;
while ($result = mysql_fetch_assoc($resource)) {
$data[$i] = $result;
$i++;
}
foreach ($data as $information) {
mysql_query("INSERT INTO " . DB_PREFIX . "information_to_store SET information_id = '".$information['information_id']."', store_id = '0'", $link);
}
}
// Check if there are any categories associated with a store (pre-1.4.1)
$info = mysql_fetch_assoc(mysql_query("SELECT * FROM " . DB_PREFIX . "category_to_store", $link));
// If not, then add them all to the default
if (!$info) {
$resource = mysql_query("SELECT category_id FROM " . DB_PREFIX . "category", $link);
$data = array();
$i = 0;
while ($result = mysql_fetch_assoc($resource)) {
$data[$i] = $result;
$i++;
}
foreach ($data as $category) {
mysql_query("INSERT INTO " . DB_PREFIX . "category_to_store SET category_id = '".$category['category_id']."', store_id = '0'", $link);
}
}
// Check if there are any manufacturers associated with a store (pre-1.4.1)
$info = mysql_fetch_assoc(mysql_query("SELECT * FROM " . DB_PREFIX . "manufacturer_to_store", $link));
// If not, then add them all to the default
if (!$info) {
$resource = mysql_query("SELECT manufacturer_id FROM " . DB_PREFIX . "manufacturer", $link);
$data = array();
$i = 0;
while ($result = mysql_fetch_assoc($resource)) {
$data[$i] = $result;
$i++;
}
foreach ($data as $manufacturer) {
mysql_query("INSERT INTO " . DB_PREFIX . "manufacturer_to_store SET manufacturer_id = '".$manufacturer['manufacturer_id']."', store_id = '0'", $link);
}
}
######################################
# START 1.5.x UPGRADE CODE
######################################
/**
* Convert Store table to Setting table
*/
$sql = "SELECT * FROM " . DB_PREFIX . "store";
$resource = mysql_query($sql, $link);
if ($resource) {
if (is_resource($resource)) {
$i = 0;
$data = array();
while ($result = mysql_fetch_assoc($resource)) {
$data[$i] = $result;
$i++;
}
mysql_free_result($resource);
}
}
// Only run if coming from 1.4.x to 1.5.x. Skip if coming from another 1.5.x version
if ($data && isset($data[0]['zone_id'])) {
$storedata = array();
foreach ($data as $d) {
$storedata[$d['store_id']] = $d;
unset($storedata[$d['store_id']]['store_id']);
}
foreach ($storedata as $store_id => $value) {
// Verify the store id doesn't already exist
$qry = mysql_fetch_assoc(mysql_query("SELECT * FROM " . DB_PREFIX . "setting WHERE store_id = '" . (int)$store_id . "'", $link));
if ($qry) { continue; }
// New store fields
if (!isset($value['address'])) { $value['address'] = '' ;}
if (!isset($value['email'])) { $value['email'] = '' ;}
if (!isset($value['telephone'])) { $value['telephone'] = '' ;}
if (!isset($value['fax'])) { $value['fax'] = '' ;}
if (!isset($value['layout'])) { $value['layout'] = '' ;}
if (!isset($value['image_compare_height'])) { $value['image_compare_height'] = '' ;}
if (!isset($value['image_compare_width'])) { $value['image_compare_width'] = '' ;}
if (!isset($value['image_manufacturer_height'])) { $value['image_manufacturer_height'] = '' ;}
if (!isset($value['image_manufacturer_width'])) { $value['image_manufacturer_width'] = '' ;}
if (!isset($value['image_wishlist_height'])) { $value['image_wishlist_height'] = '' ;}
if (!isset($value['image_wishlist_width'])) { $value['image_wishlist_width'] = '' ;}
// special case
if (!isset($value['use_ssl'])) { $value['use_ssl'] = $value['ssl'] ;}
if (!isset($value['ssl'])) {
if ($value['use_ssl']) {
$value['ssl'] = str_replace('http://', 'https://', $value['url']);
} else {
$value['ssl'] = $value['url'];
}
mysql_query("INSERT INTO " . DB_PREFIX . "store SET `ssl` = '" . $value['ssl'] . "' WHERE store_id = '" . (int)$store_id . "', `group` = 'config'", $link);
}
foreach ($value as $k => $v) {
mysql_query("INSERT INTO " . DB_PREFIX . "setting SET `key` = 'config_" . $k . "', `value` = '" . $v . "', store_id = '" . (int)$store_id . "', `group` = 'config'", $link);
}
}
$sql = "ALTER TABLE `" . DB_PREFIX . "store`
DROP `title`,
DROP `meta_description`,
DROP `template`,
DROP `country_id`,
DROP `zone_id`,
DROP `language`,
DROP `currency`,
DROP `tax`,
DROP `customer_group_id`,
DROP `customer_price`,
DROP `customer_approval`,
DROP `guest_checkout`,
DROP `account_id`,
DROP `checkout_id`,
DROP `stock_display`,
DROP `stock_check`,
DROP `stock_checkout`,
DROP `order_status_id`,
DROP `logo`,
DROP `icon`,
DROP `image_thumb_width`,
DROP `image_thumb_height`,
DROP `image_popup_width`,
DROP `image_popup_height`,
DROP `image_category_width`,
DROP `image_category_height`,
DROP `image_product_width`,
DROP `image_product_height`,
DROP `image_additional_width`,
DROP `image_additional_height`,
DROP `image_related_width`,
DROP `image_related_height`,
DROP `image_cart_width`,
DROP `image_cart_height`,
DROP `catalog_limit`,
DROP `cart_weight`,
AUTO_INCREMENT=1;";
mysql_query($sql, $link);
}
/**
* Convert Options to Global Options
*/
/*
# Convert options over.. big job
ALTER TABLE `oc_order_option`
ADD `product_option_id` int(11) NOT NULL DEFAULT 0 COMMENT '' AFTER order_product_id,
ADD `type` varchar(32) NOT NULL DEFAULT '' COMMENT '' COLLATE utf8_bin AFTER value,
MODIFY `value` text NOT NULL DEFAULT '' COMMENT '' COLLATE utf8_bin,
DROP `price`,
DROP `prefix`;
ALTER TABLE `oc_product_option`
ADD `option_id` int(11) NOT NULL DEFAULT 0 COMMENT '' AFTER product_id,
ADD `option_value` text NOT NULL DEFAULT '' COMMENT '' COLLATE utf8_bin AFTER option_id,
ADD `required` int(1) NOT NULL DEFAULT 0 COMMENT '' AFTER option_value,
DROP `sort_order`;
DROP TABLE `oc_product_option_description`;
ALTER TABLE `oc_product_option_value`
ADD `option_id` int(11) NOT NULL DEFAULT 0 COMMENT '' AFTER product_id,
ADD `option_value_id` int(11) NOT NULL DEFAULT 0 COMMENT '' AFTER option_id,
ADD `price_prefix` varchar(1) NOT NULL DEFAULT '' COMMENT '' COLLATE utf8_bin AFTER price,
ADD `points` int(8) NOT NULL DEFAULT 0 COMMENT '' AFTER price_prefix,
ADD `points_prefix` varchar(1) NOT NULL DEFAULT '' COMMENT '' COLLATE utf8_bin AFTER points,
ADD `weight` decimal(15,8) NOT NULL DEFAULT '' COMMENT '' AFTER points_prefix,
ADD `weight_prefix` varchar(1) NOT NULL DEFAULT '' COMMENT '' COLLATE utf8_bin AFTER weight,
MODIFY `quantity` int(3) NOT NULL DEFAULT 0 COMMENT '',
ALTER `subtract` DROP DEFAULT,
DROP `prefix`,
DROP `sort_order`;
DROP TABLE `oc_product_option_value_description`;
write this back to the config.php
// HTTP
define('HTTP_SERVER', 'http://localhost/v150/');
define('HTTP_IMAGE', 'http://localhost/v150/image/');
define('HTTP_ADMIN', 'http://localhost/v150/admin/');
// HTTPS
define('HTTPS_SERVER', 'http://localhost/v150/');
define('HTTPS_IMAGE', 'http://localhost/v150/image/');
*/
if (!empty($errors)) { //has to be a separate if
?>
<p>The following errors occured:</p>
<?php foreach ($errors as $error) {?>
<div class="warning"><?php echo $error;?></div><br />
<?php } ?>
<p>The above errors occurred because the script could not properly determine the existing state of those db elements. Your store may not need those changes. Please post any errors on the forums to ensure that they can be addressed in future versions!</p>
</div>
<?php } else { ?>
<h2>SUCCESS!!! Click here to goto your store</h2>
<?php } ?>
<div class="center">OpenCart.com</div>
</body>
</html>
Please try this script. Instructions also available. http://forum.opencart.com/viewtopic.php?t=50292
I dont know a script that is able to update the Opencart files. You simply need to empty your FTP and upload the 1.5.x package. If you're using any (custom) modules, you'll need to re-install them. But be carefull, because modules developed for 1.4.x are not automatically compatible with 1.5.x.