This Knowledge Tree script was available, at one time, on forge.knowledgetree.com, but apparently that domain isn't around anymore, so I am making the script available here. I believe it was called bulkupload.php. Enjoy...
<?
/**
*
*
*
* KnowledgeTree Open Source Edition
* Document Management Made Simple
* Copyright (C) 2004 - 2008 The Jam Warehouse Software (Pty) Limited
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* You can contact The Jam Warehouse Software (Pty) Limited, Unit 1, Tramber Place,
* Blake Street, Observatory, 7925 South Africa. or email info@knowledgetree.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* KnowledgeTree" logo and retain the original copyright notice. If the display of the
* logo is not reasonably feasible for technical reasons, the Appropriate Legal Notices
* must display the words "Powered by KnowledgeTree" and retain the original
* copyright notice.
* Contributor( s): ______________________________________
*
*/
/*
Introduction
============
VERSION: 0.3 (compatible with KnowledgeTree 3.5.x)
The purpose of this script is to perform a bulk import of data files as well as of any corresponding metadata.
Metadata files are created in the following .ini file format:
[fieldset_1]
fieldname="fieldvalue"
[fieldset_2]
fieldname="fieldvalue"
NOTE: the double quotes must be present!
There may be issues if there are double quotes in the metadata fieldvalues.
Have not tested yet how it will work.
The fieldsets and fields don't have to be created prior to running this script. This script will
create them.
Note: This script is based on 3.3.1 version of the database.
Note: Documents are not indexed at this time.
*/
/********************** EDITABLE CONFIGURATION ************************/
/**
* METADATA_EXTENSION is the extension for the file in which metadata should be found. Don't include a period (.) in this definition.
*
*/
define('METADATA_EXTENSION', 'meta');
/**
* The following are the connection variables to connect to the database.
*
*/
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', 'yourpassword');
define('DB_NAME', 'dms');
/**
* EXEC_FIRST is a bat file/program that is executed before the script is ran, leave empty
* prevent execution.
*
*/
define('EXEC_FIRST','');
/**
* TARGET_KT_FOLDER is the 'root' folder into which the source will be imported.
*
*/
$thismonth = date("Y/m-M/");
define('TARGET_KT_FOLDER',$thismonth);
/**
* This is the username to which all documents will be linked during the import process.
*
*/
define('KT_USER', 'admin');
/**
* This is the document type all documents will be assigned with
*
*/
define('DOCUMENT_TYPE','YourDocType');
/**
* DOCUMENT_ROOT is the directory where KnowledgeTree stores the documents.
*
*/
define('DOCUMENT_ROOT', 'C:/Program Files/Zend/ktdms/var/Documents');
/**
* SOURCE_FOLDER is the source folder from which documents will be imported.
*
*/
define('SOURCE_FOLDER', 'C:/Documents/pdf');
/**
* SOURCE_METADATA_FOLDER is the folder in which metadata should be stored. The structure should be
* the same as SOURCE_FOLDER, except all files must have a METADATA_EXTENSION as an extension. This
* may be blank if the meta data file is in the same directory as the file.
*
*/
define('SOURCE_METADATA_FOLDER','C:/Documents/meta');
/**
* MAX_FILES_PER_FOLDER is the number of files in each subfolder in the DOCUMENT_ROOT.
*
*/
define('MAX_FILES_PER_FOLDER', 100);
/**
* FLUSH_INTERVAL is the number of files that must be imported before a period (.) is displayed as part
* of the progress indication.
*
*/
define('FLUSH_INTERVAL', MAX_FILES_PER_FOLDER);
/**
* COPY_FILES must import files. Options are 'copy', 'move','none', false. False is the same as 'none'.
*
*/
define('COPY_FILES', 'copy');
/**
* IMPORT_DATA must update the data structures in the database.
*
*/
define('IMPORT_DATA', true);
/**
* IMPORT_METADATA must update the metadata data structures in the database. This is dependant on IMPORT_DATA.
*
*/
define('IMPORT_METADATA', true);
/**
* IGNORE_IMPORTED to ignore files that are seen to be in the database.
*
*/
define('IGNORE_IMPORTED', true);
/********************** START OF SCRIPT ************************/
if(EXEC_FIRST != ''){
echo "Running executable <br />";
exec(EXEC_FIRST);
echo "waiting 5 seconds <br />";
sleep(5);
}
$ignoreNames= array('.','..');
connect(DB_HOST, DB_USER, DB_PASS,DB_NAME);
if (!is_dir(SOURCE_FOLDER))
{
die('Specify a folder to import.');
}
// we want our script to be able to run un-interrupted
set_time_limit(0);
if (PHP_VERSION > 5.1)
{
// get rid of stupid warning...
date_default_timezone_set('Africa/Johannesburg');
}
define('IMPORT_DATETIME',date('Y-m-d H:i:s'));
define('STORAGE_PAD_LENGTH',strlen(MAX_FILES_PER_FOLDER)-1);
define('KT_USER_ID',get_user_id(KT_USER));
$total_files = get_total_docs();
$filetypes = get_mime_types();
if (!in_array(COPY_FILES,array('move','copy','none', false)))
{
die('Please select a value copy method');
}
//find document type
echo "Looking up document type<br />";
$sql = "SELECT * FROM document_types_lookup WHERE name = '".mysql_real_escape_string(DOCUMENT_TYPE)."'";
$res = mysql_query($sql) or die(mysql_error()."<br />".$sql);
if(mysql_num_rows($res) != 1){
die("Can't find document type ".DOCUMENT_TYPE);
}
$res = mysql_fetch_assoc($res);
$typeId = $res['id'];
if(!is_numeric($typeId)){
die("Can't find document type id");
}
$const_doc_type_id = $typeId;
//if (SOURCE_FOLDER == SOURCE_METADATA_FOLDER)
//{
// die('The repository and metadata directories should be different.');
//}
$num_files=0;
$num_dirs=0;
$num_metadata=0;
$targetKtFolderId = find_folder(TARGET_KT_FOLDER);
echo "targetKTFOLDERID: $targetKtFolderId";
if ($targetKtFolderId == false)
{
$targetKtFolderId = mkdir_recursive(TARGET_KT_FOLDER);
}
$fieldsets=array();
$start = time();
print 'start ' . date('Y-m-d H:i:s') . "\n";
import_folder(SOURCE_FOLDER, SOURCE_METADATA_FOLDER, $targetKtFolderId);
$end = time();
print "\n" . 'end ' . date('Y-m-d H:i:s') . "\n";
$diff = $end - $start;
$hours= floor($diff /3600);
$minutes = floor($diff / 60);
$seconds = floor($diff % 60);
print "time: $hours hours $minutes minutes $seconds seconds\n";
print "num files: $num_files\n";
print "num dirs: $num_dirs\n";
print "num metadata: $num_metadata\n";
flush();
die('done');
/**
* This connects us to the database.
*
* @param string $db_host
* @param string $db_user
* @param string $db_pass
* @param string $db_name
*/
function connect($db_host, $db_user, $db_pass,$db_name)
{
mysql_connect($db_host, $db_user, $db_pass) || die('Cannot connect to database host');
mysql_select_db($db_name) || die('Cannot connect to database');
}
/**
* This returns a count of the number of documents in KnowledgeTree - including deleted, archived, etc.
*
* @return int
*/
function get_total_docs()
{
$sql = 'select count(*) from document_content_version';
$rs = mysql_query($sql);
list($total_files) = mysql_fetch_row($rs);
mysql_free_result($rs);
return $total_files;
}
/**
* This loads all mime types from the database.
*
* @return int
*/
function get_mime_types()
{
$filetypes =array();
$sql = 'select id, filetypes from mime_types';
$rs = mysql_query($sql);
while($row= mysql_fetch_assoc($rs))
{
$filetypes[$row['filetypes']] = $row['id'];
}
mysql_free_result($rs);
return $filetypes;
}
/**
* This looks up the user id.
*
* @param string $username
* @return int
*/
function get_user_id($username)
{
$sql = "SELECT id FROM users WHERE username='$username'";
$rs = mysql_query($sql);
if (mysql_num_rows($rs) == 0)
{
die('User not found.');
}
list($user_id) = mysql_fetch_row($rs);
mysql_free_result($rs);
return $user_id;
}
/**
* This recursively iterates a folder structure importing documents into the system.
*
* @param string $folder This is the full path to the folder that should be imported.
* @param string $metadataFolder This is the full path to the folder containing metadata.
* @param int $parent_id This is the parent folder id.
*/
function import_folder($folder, $metadataFolder, $parent_id)
{
global $ignoreNames,$num_files,$num_dirs,$num_metadata;
$folder_info=get_folder_info($parent_id);
$num_dirs++;
if ($dh = opendir($folder))
{
while (($file = readdir($dh)) !== false)
{
if (in_array($file, $ignoreNames))
{
continue;
}
$fullpath = $folder . '/' . $file;
if ($metadataFolder != '')
{
$metadata_fullpath = $metadataFolder . '/' . $file;
}
else
{
$metadata_fullpath='';
}
if (is_dir($fullpath))
{
$new_parent_id = mkdir_recursive($file, $parent_id);
import_folder($fullpath, $metadata_fullpath, $new_parent_id );
continue;
}
if ($metadataFolder == '')
{
$ext = file_extension($file);
if ($ext == METADATA_EXTENSION)
{
continue;
}
}
import_document($file, $parent_id, $fullpath, $metadata_fullpath, $folder_info);
}
closedir($dh);
}
unset($dh);
}
/**
* Extract the file extension from a filename.
*
* @param string $filename
* @return string
*/
function file_extension($filename)
{
$pos = strrpos($filename,'.');
if ($pos === false)
{
return '';
}
return substr($filename,$pos+1);
}
/**
* This imports a document into KnowledgeTree.
*
* @param string $documentname This is the filename only.
* @param int $folder_id This is the folder the file will belong to.
* @param string $fullpath This is the full path to the file on the file system.
* @param string $metadata_fullpath This is the full path to the file containing metadata on the file system.
* @param array $folder_info This is information around the folder.
*/
function import_document($documentname, $folder_id,$fullpath, $metadata_fullpath, $folder_info)
{
global $num_files, $total_files, $filetypes, $const_doc_type_id;
$escaped_documentname=addslashes($documentname);
$escaped_folder_info=mysql_real_escape_string($folder_info['full_path']);
$importedAlready=false;
if (IGNORE_IMPORTED)
{
$sql = 'SELECT D.id FROM document_content_version DCV INNER JOIN documents D ON DCV.document_id=D.id
WHERE DCV.filename=\''.$escaped_documentname.'\' AND D.full_path=\''.$escaped_folder_info.'\' AND D.status_id=1';
$rs = mysql_query($sql);
if (mysql_num_rows($rs) > 0)
{
list($document_id) = mysql_fetch_row($rs);
$importedAlready=true;
}
mysql_free_result($rs);
}
if ($importedAlready)
{
return;
}
$sum = $total_files + $num_files;
$content_version_id = get_zseq('document_content_version');
$storage_path = get_storage_path($content_version_id);
$filesize = filesize($fullpath);
$full_storage_path=DOCUMENT_ROOT . '/' . $storage_path;
if(is_file($full_storage_path)){
$sql = mysql_query("SELECT * FROM document_content_version WHERE storage_path = '".$storage_path."'") or die(mysql_error());
if(mysql_num_rows($sql) == 0){
die($full_storage_path." already exists but does not has a database entry. Please delete the file on the filesystem.");
}else{
die("Storage path already exists in database, aborting.");
}
}
switch (COPY_FILES)
{
case false:
case 'none':
$copied=true;
break;
case 'copy':
print "copy $fullpath to $full_storage_path\n";
$copied = copy($fullpath,$full_storage_path) || ($filesize == 0 && is_file($full_storage_path));
break;
case 'move':
$copied = rename($fullpath,$full_storage_path);
break;
default:
die('An unexpected COPY method was detected.');
}
if (!$copied)
{
print "Problem copying '$fullpath' to '$full_storage_path'\n";
return;
}
if ($num_files % FLUSH_INTERVAL == 0)
{
print '.';
flush();
}
$ext = file_extension($fullpath);
$mime_id=$filetypes['pdf'];
if (in_array("$ext", $filetypes))
{
$mime_id=$filetypes["$ext"];
}
if (IMPORT_DATA)
{
$document_id=get_zseq('documents');
$metadata_version_id = get_zseq('document_metadata_version');
//Adding the document deadbeef
$array = array(
'creator_id'=>KT_USER_ID,
'modified'=>IMPORT_DATETIME,
'folder_id'=>$folder_id,
'is_checked_out'=>0,
'parent_folder_ids'=>$folder_info['full_folder_ids'],
'full_path'=>mysql_real_escape_string($folder_info['full_path']),
'status_id'=>1,
'created'=>IMPORT_DATETIME,
'permission_object_id'=>$folder_info['permission_object_id'],
'permission_lookup_id'=>$folder_info['permission_lookup_id'],
'metadata_version'=>0,
// 'metadata_version_id'=>null,
'modified_user_id'=>KT_USER_ID,
'owner_id'=>KT_USER_ID,
'immutable'=>0,
);
auto_insert('documents',$array,$document_id);
$storage_path = mysql_real_escape_string($storage_path);
$array = array(
'document_id'=>$document_id,
'filename'=>$escaped_documentname,
'size'=>$filesize,
'mime_id'=>$mime_id,
'major_version'=>0,
'minor_version'=>1,
'storage_path'=>$storage_path,
);
auto_insert('document_content_version',$array,$content_version_id);
$array = array(
'document_id'=>$document_id,
'content_version_id'=>$content_version_id,
'document_type_id'=> $const_doc_type_id,
'name'=>$escaped_documentname,
'description'=>$escaped_documentname,
'status_id'=>1,
'metadata_version'=>0,
'version_created'=>IMPORT_DATETIME,
'version_creator_id'=>KT_USER_ID,
);
auto_insert('document_metadata_version',$array,$metadata_version_id);
update_documents($document_id,$metadata_version_id);
//Philip
$num_files++;
if ($metadata_fullpath == '')
{
$metadata_fullpath = $fullpath . '.' . METADATA_EXTENSION;
echo "MetaData Full Path: ".$metadata_fullpath."\r\n";
}
else
{
$metadata_fullpath .= '.' . METADATA_EXTENSION;
echo "MetaData Full Path: ".$metadata_fullpath."\r\n";
}
if (IMPORT_METADATA && is_file($metadata_fullpath))
{
import_metadata($metadata_fullpath, $document_id,$metadata_version_id);
}
}
}
/**
* This imports a metadata file into KnowledgeTree.
*
* @param string $metadata_fullpath
* @param int $document_id
* @param int $metadata_version_id
*/
function import_metadata($metadata_fullpath, $document_id,$metadata_version_id)
{
// file was checked above for existance, so won't duplicate
global $num_metadata;
$num_metadata++;
$fp = fopen($metadata_fullpath,'rt');
$content = fread($fp, filesize($metadata_fullpath));
fclose($fp);
echo "Importing MetaData...\r\n";
$num_matches=preg_match_all("/\[\s*(.*)\s*\]\s*((.*)=\"([^\"]*)\"\s*)*/",$content,$matches);
if ($num_matches !== false)
{
$fieldsets_found = $matches[0];
echo "Fieldsets found: ".$fieldsets_found."\r\n";
foreach($fieldsets_found as $found)
{
preg_match("/\[\s*(.*)\s*\]/",$found, $match);
$fieldset_name = $match[1];
$fieldset_id = resolve_fieldset($fieldset_name);
echo "Fieldset Name: ".$fieldset_name."\r\n";
echo "Fieldset ID: ".$fieldset_id."\r\n";
$num_fields = preg_match_all("/(.*)=\"([^\"]*)\"/",$found, $match_fields);
echo "Number of Fields: ".$num_fields."\r\n";
for($i=0;$i<$num_fields;$i++)
{
$fieldname = $match_fields[1][$i];
echo "FieldName: ".$fieldname."\r\n";
$fieldvalue = $match_fields[2][$i];
echo "FieldValue: ".$fieldvalue."\r\n";
$field_id = resolve_field($fieldset_id, $fieldname);
echo "FieldID: ".$field_id."\r\n";
store_field_value($field_id, $metadata_version_id,$fieldvalue);
}
}
}
}
/**
* This resolves the fieldset id for a given fieldset.
*
* @param string $fieldsetname
* @return int
*/
function resolve_fieldset($fieldsetname)
{
global $fieldsets;
if (array_key_exists($fieldsetname, $fieldsets))
{
return $fieldsets[$fieldsetname];
}
$sql = "select id from fieldsets where name='$fieldsetname'";
$rs = mysql_query($sql);
if (mysql_num_rows($rs) != 0)
{
list($fieldset_id) = mysql_fetch_row($rs);
mysql_free_result($rs);
}
else
{
$namespace='local/fieldsets/' . str_replace(' ','', $fieldsetname);
$array = array(
'name'=>$fieldsetname,
'namespace'=>$namespace,
'mandatory'=>0,
'is_generic'=>0,
'is_complex'=>0,
'is_complete'=>0,
'is_system'=>0,
'description'=>'',
);
$fieldset_id = auto_insert('fieldsets',$array);
}
$fieldsets[$fieldsetname] = $fieldset_id;
$fieldsets[$fieldset_id] = array(
'name'=>$fieldsetname,
'fields'=>array()
);
return $fieldset_id;
}
/**
* This returns the field id for a given field in a fieldset.
*
* @param int $fieldset_id
* @param string $fieldname
* @return int
*/
function resolve_field($fieldset_id, $fieldname)
{
global $fieldsets;
if (array_key_exists($fieldname, $fieldsets[$fieldset_id]['fields']))
{
return $fieldsets[$fieldset_id]['fields'][$fieldname];
}
$sql = "select id from document_fields where name='$fieldname' and parent_fieldset=$fieldset_id";
$rs = mysql_query($sql);
if (mysql_num_rows($rs) != 0)
{
list($field_id) = mysql_fetch_row($rs);
mysql_free_result($rs);
}
else
{
$array = array(
'name'=>$fieldname,
'data_type'=>'STRING',
'is_generic'=>0,
'has_lookup'=>0,
'has_lookuptree'=>0,
'parent_fieldset'=>$fieldset_id,
'is_mandatory'=>0,
'description'=>'',
);
$field_id = auto_insert('document_fields',$array);
}
$fieldsets[$fieldset_id]['fields'][$fieldname]=$field_id;
$fieldsets[$fieldset_id]['fields'][$field_id]=$fieldname;
return $field_id;
}
/**
* This stores some metadata value in the database.
*
* @param int $fieldid
* @param int $metadata_version_id
* @param string $fieldvalue
*/
function store_field_value($fieldid, $metadata_version_id,$fieldvalue)
{
$array = array(
'document_field_id'=>$fieldid,
'value'=>$fieldvalue,
'metadata_version_id'=>$metadata_version_id,
);
auto_insert('document_fields_link',$array);
}
/**
* This generates an auto number for the sequence on a given table.
*
* @param string $tablename
* @return int
*/
function get_zseq2($tablename, $update=true)
{
$sql = "SELECT id from $tablename ORDER BY id DESC LIMIT 1";
$rs = mysql_query($sql);
list($id) = mysql_fetch_row($rs);
mysql_free_result($rs);
return $id+1;
}
/**
* This generates an auto number for the sequence on a given table.
*
* @param string $tablename
* @return int
*/
function get_zseq($tablename, $update=true)
{
$sql = "SELECT id from $tablename ORDER BY id DESC LIMIT 1";
$rs = mysql_query($sql);
list($id) = mysql_fetch_row($rs);
mysql_free_result($rs);
if ($update)
{
$sql = "UPDATE zseq_$tablename SET id=id+1";
$rs=mysql_query($sql);
return $id+1;
}
else return $id;
}
function update_documents($document_id,$metadata_version_id)
{
$sql = "update documents set metadata_version_id=$metadata_version_id where id=$document_id";
mysql_query($sql);
}
/**
* This returns information about a folder, such as permission information.
*
* @param int $folder_id
* @return array
*/
function get_folder_info($folder_id)
{
$sql = "SELECT parent_folder_ids, permission_lookup_id, permission_object_id,name,full_path FROM folders WHERE id=$folder_id";
$rs = mysql_query($sql);
$row = mysql_fetch_assoc($rs);
mysql_free_result($rs);
$row['path'] = $row['full_path'];
$row['full_path'] .= '/' . $row['name'];
if (substr($row['full_path'],0,1) == '/')
$row['full_path'] = substr($row['full_path'],1);
if (is_null($row['parent_folder_ids']))
$parent_folder_ids=array();
else
$parent_folder_ids = explode(',',$row['parent_folder_ids']);
$parent_folder_ids[] = $folder_id;
$parent_folder_ids = implode(',',$parent_folder_ids);
$row['full_folder_ids'] = $parent_folder_ids;
return $row;
}
/**
* This creates folders recursively in KnowledgeTree. The foldername must either be full and parentid is null
* or the foldername is relative to parentid.
*
* @param string $foldername This is the folder name.
* @param int $parent_id Optional. This is the id of the parent folder.
* @return int This is the id of the new folder
*/
function mkdir_recursive($foldername, $parent_id=null)
{
//global $user_id;
$escaped_foldername=mysql_real_escape_string($foldername);
$id = find_folder($escaped_foldername,$parent_id);
if ($id !== false)
{
return $id;
}
$name=basename($foldername);
$dirname=dirname($foldername);
if (is_null($parent_id))
{
$parent_id=find_folder($dirname);
if ($parent_id == false)
{
$parent_id = mkdir_recursive($dirname);
}
}
$parent_info = get_folder_info($parent_id);
$dirname = $parent_info['full_path'];
if (substr($dirname,0,1) == '/')
$dirname=substr($dirname,1);
if (substr($dirname,0,11) != 'Root Folder')
$dirname = 'Root Folder/' . $dirname;
$dirname=str_replace('//','/',$dirname);
$parent_folder_ids = $parent_info['full_folder_ids'];
$name= mysql_real_escape_string($name);
$dirname = mysql_real_escape_string($dirname);
$parent_folder_ids = mysql_real_escape_string($parent_folder_ids);
$array=array(
'name'=>$name,
'description'=>$name,
'parent_id'=>$parent_id,
'creator_id'=>KT_USER_ID,
'is_public'=>0,
'parent_folder_ids'=>$parent_folder_ids,
'full_path'=>$dirname,
'permission_lookup_id'=>$parent_info['permission_lookup_id'],
'permission_object_id'=>$parent_info['permission_object_id'],
'restrict_document_types'=>0,
'owner_id'=>KT_USER_ID,
);
$new_folderid=auto_insert2('folders',$array);
return $new_folderid;
}
/**
* This does a database insert based on a table name and the fields in an associative array.
*
* @param string $table This is the tablename.
* @param array $array This is the associative array of functions.
* @param int $id This is the id that should be used. An id should not be created by the function.
* @return int This is the id of the element returned.
*/
function auto_insert2($table, $array, $id=null)
{
if (is_null($id))
{
$id = get_zseq2($table);
}
$array['id'] = $id;
if (0)
{
// if we want to, we can force escaping of fields.
foreach($array as $k=>$v)
{
$array[$k] = mysql_escape_string($v);
}
}
$sql = "INSERT INTO $table (" . implode(',', array_keys($array)). ') VALUES (\''.
implode('\',\'',array_values($array))
.'\')';
$rs = mysql_query($sql);
if ($rs === false)
{
$err= mysql_error();
print "$err \n";
print "$sql \n";
var_dump($array);
}
return $id;
}
/**
* This does a database insert based on a table name and the fields in an associative array.
*
* @param string $table This is the tablename.
* @param array $array This is the associative array of functions.
* @param int $id This is the id that should be used. An id should not be created by the function.
* @return int This is the id of the element returned.
*/
function auto_insert($table, $array, $id=null)
{
if (is_null($id))
{
$id = get_zseq($table);
}
$array['id'] = $id;
if (0)
{
// if we want to, we can force escaping of fields.
foreach($array as $k=>$v)
{
$array[$k] = mysql_escape_string($v);
}
}
$sql = "INSERT INTO $table (" . implode(',', array_keys($array)). ') VALUES (\''.
implode('\',\'',array_values($array))
.'\')';
$rs = mysql_query($sql);
if ($rs === false)
{
$err= mysql_error();
print "$err \n";
print "$sql \n";
var_dump($array);
}
return $id;
}
/**
* This returns the folder id for a given foldername. Either a full foldername must be provided
* or a foldername and the parent folder id. If the foldername does not include 'Root Folder/', it
* will be added, but only in the case where only the foldername is provided.
*
* @param string $foldername
* @param int $parent_id Optional.
* @return int
*/
function find_folder($foldername, $parent_id=null)
{
if (is_null($parent_id))
{
if ( substr($foldername,0,1) != '/')
{
$foldername = substr($foldername,1);
}
if ( substr($foldername,0,11) != 'Root Folder')
{
$foldername = 'Root Folder/' . $foldername;
}
$name=basename($foldername);
$dirname=dirname($foldername);
$dirname = str_replace('\\','/',$dirname);
$dirname = str_replace('//','/',$dirname);
if ($dirname == '/')
$dirname='Root Folder';
if ($dirname == '.')
{
$dirname=$name;
$name='';
}
if ($name == '' && $dirname=='Root Folder')
{
return 1;
}
else {
if(strpos($dirname,"/") === false){
$sql = "SELECT id FROM folders WHERE full_path='$name' AND name='$name'";
}else{
if(substr($dirname,0,12)=="Root Folder/"){
$dirname = substr($dirname,12)."/".$name;
}
$dirname = mysql_real_escape_string($dirname);
$sql = "SELECT id FROM folders WHERE full_path='$dirname' AND name='$name'";
}
}
}
else
{
$foldername = mysql_real_escape_string($foldername);
$sql = "SELECT id FROM folders WHERE parent_id=$parent_id AND name='$foldername'";
}
$fp = fopen('D:\CofC\errorlog.txt', 'a');
fwrite($fp, "foldername: $foldername name: $name dirname:$dirname sql:$sql");
fclose($fp);
$rs = mysql_query($sql);
if (mysql_num_rows($rs) == 0)
return false;
list($folder_id) = mysql_fetch_row($rs);
mysql_free_result($rs);
return $folder_id;
}
function get_storage_path($iId)
{
$str = (string)$iId;
if (strlen($str) < 4)
{
$str = sprintf('%s%s', str_repeat('0', 4 - strlen($str)), $str);
}
if (strlen($str) % 2 == 1)
{
$str = sprintf('0%s', $str);
}
$str = substr($str, 0, -2);
$dir = preg_replace('#(\d\d)(\d\d)#', '\1/\2', $str);
$sDocumentRoot = DOCUMENT_ROOT;
$path = "";
foreach(split('/', $dir) as $sDirPart)
{
$path = sprintf('%s/%s', $path, $sDirPart);
$createPath = sprintf('%s%s', $sDocumentRoot, $path);
if (!is_dir($createPath)) {
$res = @mkdir($createPath);
if ($res === false) {
print "Could not create directory for storage: $createPath\n";
}
}
}
return sprintf("%s/%d", $dir, $iId);
}
?>