Importing products from directory dump structure - php

I have the following directory structure of my database dump (total of: 18,042,482 products):
/home/nataliya/dump/10xxxxx/100xxxx/1000006/
/home/nataliya/dump/10xxxxx/100xxxx/1000007/
...
Where 1000006 and 1000007 are the product's id.
Each folder contains:
description.txt (text)
details.csv (name, oldprice, price)
images.csv (url, size)
How do I import them into MySQL, using PHP, as following:
id, name, oldprice, price, description (table `products`)
product_id, url, size (table `images`)
I apologize in advance if the question is not relative to this website, and thank everyone who wish to help me.
EDIT: Just to clarify, I'm asking only for a guidance, not for a full code example. Just the proper functions of PHP, which will make it with a good performance, since I'm talking about a directory with more than 30 million files.
EDIT: Here's what I've done for now:
<?php
function ArrayCSV($file) {
$fh = fopen($file, 'r');
while (!feof($fh) ) {
$result[] = fgetcsv($fh, 1024);
}
fclose($fh);
return $result[1];
}
$products = array();
$images = array();
foreach(scandir(dirname(__FILE__) . '/dump/') as $dir_global) {
if($dir_global != '.' && $dir_global != '..' && $dir_global != '.DS_Store') {
foreach(scandir(dirname(__FILE__) . '/dump/' . $dir_global) as $dir_local) {
if($dir_local != '.' && $dir_local != '..' && $dir_local != '.DS_Store') {
foreach(scandir(dirname(__FILE__) . '/dump/' . $dir_global . '/' . $dir_local) as $id) {
if($id != '.' && $id != '..' && $id != '.DS_Store') {
$dir = dirname(__FILE__) . '/dump/' . $dir_global . '/' . $dir_local . '/' . $id;
$product = ArrayCSV($dir . '/details.csv');
$image = ArrayCSV($dir . '/images.csv');
$products[] = array(
'id' => $id,
'name' => $product[0],
'oldprice' => $product[1],
'price' => $product[2],
'description' => file_get_contents($dir . '/description.txt')
);
$images[] = array(
'product_id' => $id,
'url' => $image[0],
'size' => $image[1]
);
}
}
}
}
}
}
try {
$DBH = new PDO("mysql:host=localhost;dbname=application", 'root', '');
$DBH->exec("SET NAMES utf8");
}
catch(PDOException $e) {
//
}
foreach($products as $product) {
$STH = $DBH->prepare("INSERT INTO products (id, name, oldprice, price, description) VALUES (:id, :name, :oldprice, :price, :description)");
$STH->execute($product);
}
foreach($images as $image) {
$STH = $DBH->prepare("INSERT INTO images (product_id, url, size) VALUES (:product_id, :url, :size)");
$STH->execute($image);
}
?>

I would suggest familiarizing yourself with the following function scandir() , file_get_contents() and finally, all the mysqli functions of PHP as they would be the key to what you'd need to do here.
Hope this helps!

Related

Problem with uploading multiple photos into database through pivot table

I am working on a cms for properties/ads in oop php for learning purposes. I am trying to upload multiple photos that are connected through pivot table with specific property but I am having trouble inserting those photos. I need when I insert property with two or more photos that those photos have diiferent ids in pivot table but the same id for property. I succeeded with one photo at the time, but with multiple I get errors:
Warning: explode() expects parameter 2 to be string, array given in
C:\xampp\htdocs\App\Models\Ad.php on line 177 when I var dump $tmp
variable I get null and
Warning: end() expects parameter 1 to be array, null given in
C:\xampp\htdocs\App\Models\Ad.php on line 179 when I var dump
$file_ext variable I get empty string
I am using three tables to do that. photos (name, extension, created_at, updated_at), property_photo (property_id, photo_id), properties (title, description, type_of_property, use_of_the_property, quadrature, location...). Here is my code:
Ad Model:
public function createAd($data, $pht)
{
if (isset($data['photoExtension'])) {
$this->photoExtension = preg_replace('~(?<=a)\w~', "", $data['photoExtension']);
}
$this->photoExtension = strtolower(strrchr( $pht, '.' ));
$this->db->query("INSERT INTO properties (title, description, type_of_property, use_of_the_property, quadrature, location, price, sales_clerk_info, booked, type_of_market, type_of_payment, status) VALUES (:title, :description, :type_of_property, :use_of_the_property, :quadrature, :location, :price, :sales_clerk_info, :booked, :type_of_market, :type_of_payment, :status) ");
$this->db->bind(':title', $data['title']);
$this->db->bind(':description', $data['description']);
$this->db->bind(':type_of_property', $data['type_of_property']);
$this->db->bind(':use_of_the_property', $data['use_of_the_property']);
$this->db->bind(':quadrature', $data['quadrature']);
$this->db->bind(':location', $data['location']);
$this->db->bind(':price', $data['price']);
$this->db->bind(':sales_clerk_info', $data['sales_clerk_info']);
$this->db->bind(':booked', $data['booked']);
$this->db->bind(':type_of_market', $data['type_of_market']);
$this->db->bind(':type_of_payment', $data['type_of_payment']);
$this->db->bind(':status','1');
$this->db->execute();
$property_last_id = $this->db->lastId();
$this->db->query('INSERT INTO photos (name, extension) VALUES (:name, :extension)');
$this->db->bind(':name', $pht);
$this->db->bind(':extension', $this->photoExtension, PDO::PARAM_STR );
$this->db->execute();
$photo_last_id = $this->db->lastId();
$this->db->query('INSERT INTO property_photo (property_id, photo_id) VALUES (:property_id, :photo_id)');
$this->db->bind(':property_id', $property_last_id);
$this->db->bind(':photo_id', $photo_last_id);
$this->db->execute();
return true;
}
public function photoValidate($file)
{
if (!empty($file['name'])) {
$file_name = $file['name'];
$file_size = $file['size'];
$file_tmp = $file['tmp_name'];
$file_type = $file['type'];
$file_error = $file['error'];
$random = sha1(microtime());
$tmp = explode('.', $file_name);
$new_photo_name = $random . '.' . $tmp[1];
$file_ext = strtolower(end($tmp));
//var_dump($tmp); null
//var_dump($file_ext); empty string
$photo_validate = '';
$extensions = ["jpeg", "jpg", "png"];
if (in_array($file_ext, $extensions) === false) {
return 'extension not allowed, please choose a JPEG or PNG file.';
} else {
if ($file_size > 2097152 || $file_error === 1) {
return 'File size must be less than 2 MB';
} else {
$value = true;
return $data = [$value, $file_tmp, $new_photo_name];
}
}
} else {
return false;
}
}
Ads Controller:
public function createAction()
{
$userinfo = $this->Auth->Auth(array('admin', 'moderator'));
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$data = [
'title' => trim($_POST['title']),
'description' => trim($_POST['description']),
'type_of_property' => trim($_POST['type_of_property']),
'use_of_the_property' => trim($_POST['use_of_the_property']),
'quadrature' => trim($_POST['quadrature']),
'location' => trim($_POST['location']),
'price' => trim($_POST['price']),
'sales_clerk_info' => trim($_POST['sales_clerk_info']),
'booked' => trim($_POST['booked']),
'type_of_market' => trim($_POST['type_of_market']),
'type_of_payment' => trim($_POST['type_of_payment']),
'title_err' => '',
'description_err' => '',
'type_of_property_err' => '',
'use_of_the_property_err' => '',
'quadrature_err' => '',
'location_err' => '',
'price_err' => '',
'sales_clerk_info_err' => '',
'booked_err' => '',
'type_of_market_err' => '',
'type_of_payment_err' => ''
];
if (empty($data['title'])) {
$data['title_err'] = 'Please enter your title!!!';
}
if (empty($data['description'])) {
$data['description_err'] = 'Please enter your description!!!';
}
if (empty($data['type_of_property'])) {
$data['type_of_property_err'] = 'Please select your type!!!';
}
if (empty($data['use_of_the_property'])) {
$data['use_of_the_property_err'] = 'Please enter use of the property!!!';
}
if (empty($data['quadrature'])) {
$data['quadrature_err'] = 'Please enter your quadrature!!!';
}
if (empty($data['location'])) {
$data['location_err'] = 'Please enter your location!!!';
}
if (empty($data['price'])) {
$data['price_err'] = 'Please enter your price!!!';
}
if (empty($data['sales_clerk_info'])) {
$data['sales_clerk_info_err'] = 'Please enter your info!!!';
}
if (empty($data['booked'])) {
$data['booked_err'] = 'Please select!!!';
}
if (empty($data['type_of_market'])) {
$data['type_of_market_err'] = 'Please select your type of market!!!';
}
if (empty($data['type_of_payment'])) {
$data['type_of_payment_err'] = 'Please select your type of payment!!!';
}
$photo_validate = $this->AdModel->photoValidate($_FILES['photo']);
if (empty($data['title_err']) && empty($data['description_err']) && empty($data['type_of_property_err']) && empty($data['use_of_the_property_err']) && empty($data['quadrature_err']) && empty($data['location_err']) && empty($data['price_err']) && empty($data['sales_clerk_info_err']) && empty($data['booked_err']) && empty($data['type_of_market_err']) && empty($data['type_of_payment_err']) && $photo_validate[0] === true) {
move_uploaded_file($photo_validate[1],"public/photos/".$photo_validate[2]);
if ($this->AdModel->createAd($data, $photo_validate[2])) {
redirect('ads/index');
} else {
if ($photo_validate === false) {
$photo_validate='Please select image';
} else {
if ($photo_validate[0] === true) {
$photo_validate='';
}
}
$data=[
'photo_validate'=>$photo_validate
];
die('Something went wrong!');
}
} else {
$this->view->render('ads/create', $data, $userinfo);
}
} else {
$data = [
'photo_validate'=>'',
'title' => '',
'description' => '',
'type_of_property' => '',
'use_of_the_property' => '',
'quadrature' => '',
'location' => '',
'price' => '',
'sales_clerk_info' => '',
'booked' => '',
'type_of_market_id' => '',
'type_of_payment' => '',
'title_err' => '',
'description_err' => '',
'type_of_property_err' => '',
'use_of_the_property_err' => '',
'quadrature_err' => '',
'location_err' => '',
'price_err' => '',
'sales_clerk_info_err' => '',
'booked_err' => '',
'type_of_market_err' => '',
'type_of_payment_err' => ''
];
$this->view->render('ads/create', $data, $userinfo);
}
}
create.php
<form action="/ads/create" method="POST" enctype="multipart/form-data">
<div class="form-group row">
<div class="col-sm-12">
<h5>Upload property image</h6>
<input type="file" name="photo[]" multiple class="form-control form-control-lg"/>
</div>
/div>
<div class="form-group">
<button type="submit" name="submit" class="form-control btn btn-primary">Submit</button>
</div>
</form>
Any help would be greatly appreciated.
Take a look at array format of $_FILES for multiple files inserting. This answer and this php documentation page will be useful for you.
You expected string in photoValidate() $file['name'] but there was an array, so you got an error.
The best and the simplest way is to use something like symfony http-foundation component.
Controller:
public function createAction()
{
$request = Request::createFromGlobals();
//...
$photo_validate = $this->AdModel->photoValidate($request->files->get('photo'));
//...
}
Also, this kind of validation is pretty messy. You can also use symfony validator component.

Upload files to user folder

I'm trying to create a new folder within the upload folder so that a user can upload file to there own folder.
Can I do this using PHP or do I need to a column "LONGBLOB" in MYSQL?
I've read that it's not good practice to store images in you database
<?php
header('Content-Type: application/json');
$succeeded = [];
$failed =[];
$uploaded = [];
$allowed = ['png', 'gif', 'jpg'];
if(!empty($_FILES["file"])) {
foreach ($_FILES['file']['name'] as $key => $name) {
if ($_FILES['file']['error'][$key] === 0) {
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() . '.' . $ext;
if (in_array($ext, $allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeeded[] = array(
'name' => $name,
'file' => $file
);
}else{
$failed[] = array(
'name' => $name);
}
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' => $failed ));
}
?>
Assuming you have the user's username or id in a session variable then that could be used as the basis for the new folder into which he/she would upload files.
Obiously that same username,id would have to be used when they wish to download the file. By storing a hash and the filepath you can generate links that do not reveal filename, folder path, owner etc as the db could check the ash and return the file and path when needed.
The following is an untested example of generating the user's own folder and using that in the upload process - hope it gives you some ideas / guidance.
<?php
$succeeded = [];
$failed =[];
$uploaded = [];
$allowed = ['png', 'gif', 'jpg'];
/*
generate a suitable name for the new folder,
remove characters which might be troublesome
*/
$userdir = str_replace(
array("'",'"','-'),
array('','','_'),
$_SESSION['username']
);
/*
new path into which the files are saved
It might be better to have the files
stored outside of the document root.
*/
$savepath = 'uploads/' . $userdir;
/* create the folder if it does not exist */
if( !file_exists( $savepath ) ) {
mkdir( $savepath );
chown( $savepath, $username );
chmod( $savepath, 0644 );
}
if( !empty( $_FILES["file"] ) ) {
foreach( $_FILES['file']['name'] as $key => $name ) {
if( $_FILES['file']['error'][$key] === 0 ) {
$temp = $_FILES['file']['tmp_name'][$key];
/*
is there anything to be gained by hashing the filename?
the hash would be the same for filenames with the same
name anyway.
If the file is large, calculating the hash of the file could
take some time...
*/
$ext = explode('.', $name);
$ext = strtolower( end( $ext ) );
$file = md5_file( $temp ) . time() . '.' . $ext;
/* generate a random hash to use in downloads */
$hash=uniqid( md5( date(DATE_COOKIE) ) );
/* here probably - store reference in db? Assign permissions based upon owner etc */
$sql='insert into `table` (`filename`,`username`,`uid`,`datetime`,`hash`) values (?,?,?,?,?);';
/* bind params and execute - not shown */
if ( in_array( $ext, $allowed ) === true && move_uploaded_file( $temp, "{$savepath}/{$file}") === true ) {
$succeeded[] = array( 'name' => $name, 'file' => $file );
}else{
$failed[] = array( 'name' => $name );
}
}
}
}
if (!empty($_POST['ajax'])) {
header('Content-Type: application/json');
echo json_encode(array(
'succeeded' => $succeeded,
'failed' => $failed ));
} else {
header( 'HTTP/1.1 404 Not Found', true, 404 );
}
?>

PHP search with multiple fields

I want to search data using ajax method with multiple fields search option (e.g. name, college, department, year, nationality e.t.c ). I have insert name for searching and rest of fields are empty than it went to foreach loop but this if (isset($_GET[$field]) && !empty($_GET['$field'])) condition not successful and went to else loop
$fields = array(
'name' => TRUE,
'gender' => TRUE,
'colf' => TRUE,
'deptf' => TRUE,
'natf' => TRUE,
'fstatusf' => TRUE,
'fyearf' => TRUE
);
foreach ($fields as $field => $like) {
if (isset($_GET[$field]) && !empty($_GET['$field'])) {
$value = $_GET[$field];
$search[] = $field . ( $like ? ('LIKE "%' . $value . '%"') : ('="' . $value . '"') );
}
}
if ($search) {
$sql = 'SELECT * FROM fmaf WHERE ' . implode(' or ' . $search);
}
else{
$sql="SELECT * FROM fmaf";
}
At last i have found the solution and thanks to cFreed and other who help me. My main concern is that if user want to search with one field only or more than 1 field in that case below answer is helpful for me and may be also for someone:
if (empty($_GET['name']) && empty($_GET['gender']) && empty($_GET['colf']) && empty($_GET['deptf']) && empty($_GET['natf']) && empty($_GET['fstatusf']) && empty($_GET['fyearf']))
{
$sql="select * from fmaf ";
}
else
{
$wheres = array();
$sql = "select * from fmaf where ";
if (isset($_GET['name']) and !empty($_GET['name']))
{
$wheres[] = "name like '%{$_GET['name']}%' ";
}
if (isset($_GET['gender']) and !empty($_GET['gender']))
{
$wheres[] = "gender = '{$_GET['gender']}'";
}
if (isset($_GET['colf']) and !empty($_GET['colf']))
{
$wheres[] = "college = '{$_GET['colf']}' ";
}
if (isset($_GET['deptf']) and !empty($_GET['deptf']))
{
$wheres[] = "department = '{$_GET['deptf']}' ";
}
if (isset($_GET['natf']) and !empty($_GET['natf']))
{
$wheres[] = "nationality = '{$_GET['natf']}' ";
}
if (isset($_GET['fstatusf']) and !empty($_GET['fstatusf']))
{
$wheres[] = "finalstatus = '{$_GET['fstatusf']}' ";
}
if (isset($_GET['fyearf']) and !empty($_GET['fyearf']))
{
$wheres[] = "fyear = '{$_GET['fyearf']}' ";
}
foreach ( $wheres as $where )
{
$sql .= $where . ' AND '; // you may want to make this an OR
}
$sql=rtrim($sql, "AND ");
}
You need to build the query depending on the request.
A toy example is this:
$sql = "select * from student where 1 = 1".(isset($name)?" AND name like '%$name%":"").(isset($country)?" AND country = '$country'":"").";";
You may use a simple way, being able to face any case, like this:
// define searchable fields, with option for LIKE|EQUAL (TRUE|FALSE)
$fields = [
'name' => TRUE,
'country' => TRUE,
'address' => TRUE,
'gender' => FALSE,
'state' => FALSE
];
foreach ($fields as $field => $like) {
if (isset($_GET[$field]) AND !empty($_GET['$field'])) {
$value = $_GET[$field];
// prepare WHERE condition item, depending on LIKE option
$search[] = $field . (
$like ? ('LIKE "%' . $value . '%"') : ('="' . $value . '"')
);
}
}
if ($search) {
$sql = 'SELECT * FROM student WHERE ' . implode(' AND ' . $search);
}

How import csv data in php mysql database with if else condition

I need to import csv data in database where my Product table have two columns code and price. I am importing data with this script, which find the product code and then update that product price -
function update_price()
{
$this->sma->checkPermissions('csv');
$this->load->helper('security');
$this->form_validation->set_rules('userfile', lang("upload_file"), 'xss_clean');
if ($this->form_validation->run() == true) {
if (isset($_FILES["userfile"])) {
$this->load->library('upload');
$config['upload_path'] = $this->digital_upload_path;
$config['allowed_types'] = 'csv';
$config['max_size'] = $this->allowed_file_size;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$error = $this->upload->display_errors();
$this->session->set_flashdata('error', $error);
redirect("products/update_price");
}
$csv = $this->upload->file_name;
$arrResult = array();
$handle = fopen($this->digital_upload_path . $csv, "r");
if ($handle) {
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
$arrResult[] = $row;
}
fclose($handle);
}
$titles = array_shift($arrResult);
$keys = array('code', 'price');
$final = array();
foreach ($arrResult as $key => $value) {
$final[] = array_combine($keys, $value);
}
$rw = 2;
foreach ($final as $csv_pr) {
if (!$this->products_model->getProductByCode(trim($csv_pr['code']))) {
$this->session->set_flashdata('message', lang("check_product_code") . " (" . $csv_pr['code'] . "). " . lang("code_x_exist") . " " . lang("line_no") . " " . $rw);
redirect("product/update_price");
}
$rw++;
}
}
}
if ($this->form_validation->run() == true && !empty($final)) {
$this->products_model->updatePrice($final);
$this->session->set_flashdata('message', lang("price_updated"));
redirect('products');
} else {
$this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
$this->data['userfile'] = array('name' => 'userfile',
'id' => 'userfile',
'type' => 'text',
'value' => $this->form_validation->set_value('userfile')
);
$bc = array(array('link' => base_url(), 'page' => lang('home')), array('link' => site_url('products'), 'page' => lang('products')), array('link' => '#', 'page' => lang('update_price_csv')));
$meta = array('page_title' => lang('update_price_csv'), 'bc' => $bc);
$this->page_construct('products/update_price', $meta, $this->data);
}
}
But here our product price update and replace old value , but i want check old value of price and
if old value is greater than uploaded value , then not replaced and
if old value is lower than uploaded value of price then update/replaced that value .
means in all condition our price is always maximum .
how we can do it ??? anyone help please ..
I think you should look inside the updatePrice method and modify a mysql query in it.
Mysql has a proper Update if statement.

Odd behavior with a PHP POST

So I'm seeing an odd behavior and I asked over on serverfault but it looks to be a code issue. The thing is this code works fine when I test locally with MAMP, once I put it on HostGator I get this oddness.
So the process is
Upload file;
Check the state of things;
Unzip the file;
Read in a data file;
Copy and thumbnail images;
dump data into database.
I know 1 to 5 happen as I can see the thumbnails. The oddness is I get an error from step 2 saying the file didn't upload. So it looks like the whole process is started over with "blank" POST data.
So, step 1 is this bit of code. It's called when my form is posted:
function action_upload() {
$ownerName = $this->request->post('ownerName', '');
$ownerEmail = $this->request->post('ownerEmail', '');
$ownerPhone = $this->request->post('ownerPhone', '');
$username = $this->request->post('username', '');
$password = $this->request->post('password', '');
$treeName = $this->request->post('treeName', '');
$error = $this->util->process_datafile($ownerName, $ownerEmail, $ownerPhone, $username, $password, false, $treeName);
if ($error != "") {
echo json_encode(array(
'error' => $error,
));
} else {
echo json_encode(array(
'gotoURL' => "/" . $treeName,
));
}
exit;
}
The action reads in some form fields and calls a function process_datafile that, well, processes the uploaded file. Below is that function, the error I'm recieving is from the 9th line, "No tree name provided". But I know it at some point gets past that error.
public function process_datafile($ownerName, $ownerEmail, $ownerPhone, $username, $password, $update, $treeName) {
// Make sure we have a tree name
if ($treeName != "") {
$this->scriptPath = dirname(__FILE__);
$this->treePath = dirname(dirname($this->scriptPath)) . "/assets/trees/" . $treeName . "/";
$this->tempFilePath = dirname(dirname($this->scriptPath)) . "/assets/temp/" . $this->guid() . "/";
} else {
return "No tree name provided";
}
// Check to make sure the tree is in the expect condition
$treeExists = false;
if (file_exists($this->treePath)) {
$treeExists = true;
}
if ($treeExists && !$update) {
return "Tree name already exists " . $this->treePath;
} else if (!$treeExists && $update) {
return "Tree does not exists";
}
// Make sure there are no upload errors
if ($_FILES['treeFile']['error'] == '1' || $_FILES['treeFile']['error'] == '2') {
return "File size to large, try to upload your tree without media.";
} else if ($_FILES['treeFile']['error'] != '0') {
return "File upload error: " . $_FILES['treeFile']['error'];
}
// Move the uploaded file
if (!file_exists($this->tempFilePath)) {
mkdir($this->tempFilePath, 0700, true);
}
$name = $_FILES["treeFile"]["name"];
$tempfile = $this->tempFilePath . $name;
copy($_FILES['treeFile']['tmp_name'], $tempfile);
// Make sure it is something we can deal with
$finfo = finfo_open(FILEINFO_MIME);
$fileparts = explode(";", finfo_file($finfo, $tempfile));
$ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
$filetype = $fileparts[0];
$valid = "text/plain,image/png";
if (($filetype != "text/plain" && $filetype != "application/zip") || ($ext != "ged" && $ext != "zip")) {
return "Only gedcom (.ged) or archive (.zip) files may be uploaded.";
}
$gedfile = $tempfile;
$archive_tmp = "";
if ($filetype == "application/zip" && $ext == "zip") {
$archive_tmp = $this->tempFilePath . "archive/";
if (!file_exists($archive_tmp)) {
mkdir($archive_tmp, 0700, true);
}
// Extract the archive
$zip = new \ZipArchive;
$res = $zip->open($tempfile);
if ($res === TRUE) {
$zip->extractTo($archive_tmp);
$zip->close();
} else {
$this->delTree($archive_tmp);
return "Error processing archive";
}
// Find the gedcom
$found = false;
$it = new \RecursiveDirectoryIterator($archive_tmp);
foreach(new \RecursiveIteratorIterator($it) as $file)
{
$file_ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (strtolower($file_ext) == "ged") {
$gedfile = $file;
$found = true;
}
}
if (!$found) {
$this->delTree($archive_tmp);
return "Could not find gedcom (.ged) file in archive.";
}
}
// Make the tree folder if needed
if (!file_exists($this->treePath)) {
mkdir($this->treePath, 0700, true);
}
$this->mediaPath = $this->treePath . "media/";
$this->delTree($this->mediaPath);
if (!file_exists($this->mediaPath)) {
mkdir($this->mediaPath, 0700, true);
}
if (file_exists($this->treePath . "tree.ged")) {
unlink($this->treePath . "tree.ged");
}
copy($gedfile, $this->treePath . "tree.ged");
// Deal with the database
if (!$this->create_database($ownerName, $ownerEmail, $ownerPhone, $username, $password, $update)) {
return "Could not open database";
}
// Process the gedcom
$this->process_gedcom($this->mediaPath, $archive_tmp);
// Remove the temp folder
$this->delTree($this->tempFilePath);
return "";
}
I know at some point it gets into the process_gedcom as that where the thumbnailing takes place... I also know it never gets to foreach ($ged->people as $person) as there are no entries in the database.
private function process_gedcom($mediaPath, $archivePath) {
// Insert statements
$personInsert = "INSERT INTO people (id, gender, first, last, middle, title, suffix) VALUES (:id, :gender, :first, :last, :middle, :title, :suffix)";
$nameInsert = "INSERT INTO names (personID, `type`, first, last) VALUES (:id, :type, :first, :last)";
$familyInsert = "INSERT INTO families (id, personAID, personBID) VALUES (:id, :personAID, :personBID)";
$childInsert = "INSERT INTO children (familyID, `type`, personID) VALUES (:familyID, :type, :personID)";
$eventInsert = "INSERT INTO events (personID, familyID, `type`, date, place, description) VALUES (:personID, :familyID, :type, :date, :place, :description)";
$factInsert = "INSERT INTO facts (personID, name, value) VALUES (:personID, :name, :value)";
$mediaInsert = "INSERT INTO media (id, file, `type`, title) VALUES (:id, :file, :type, :title)";
$peopleMediaInsert = "INSERT INTO people_media (mediaID, personID) VALUES (:mediaID, :personID)";
$familyMediaInsert = "INSERT INTO family_media (mediaID, familyID) VALUES (:mediaID, :familyID)";
// Load in the gedcom file
$ged = new \App\Gedcom();
$ged->import($this->treePath . "tree.ged", array($this, 'log'));
// Add objects to the database
foreach ($ged->objects as $obj) {
$file = $this->findFile($obj->getFilename(), $archivePath);
if ($file !== false) {
$finfo = finfo_open(FILEINFO_MIME);
$fileparts = explode(";", finfo_file($finfo, $file));
$filetype = $fileparts[0];
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
$hash = md5_file($file);
copy($file, $mediaPath . $hash . "." . $ext);
$this->makeThumb($mediaPath . $hash . "." . $ext, 200, 200, "thumb");
$this->makeThumb($mediaPath . $hash . "." . $ext, 1024, 768, "resized");
$this->database($mediaInsert, array(':id' => $obj->getId(),
':file' => $hash . "." . $ext,
':type' => $filetype,
':title' => $obj->getTitle()));
}
}
// Add people to the databsse
foreach ($ged->people as $person) {
$this->database($personInsert, array(':id' => $person->getId(),
':gender' => $person->getGender(),
':first' => $person->getFirstName(),
':last' => $person->getLastName(),
':middle' => $person->getMiddleName(),
':title' => $person->getTitleName(),
':suffix' => $person->getSuffixName()));
More data inserts...
What would cause things to restart as it looks like its calling process_datafile twice, once with valid inputs, the second time everything is '' blanks?

Categories