<?php
#   Start custom NBU parsing code here
#   Can also be used to show the use of embedded HTML_QuickForm
#   in Wordpress. This piece of code needs to be put in
#   a Template file to work.
#   Dick Visser <dick@tienhuis.nl>
#   $Id: nokia.php 182 2012-01-13 09:02:30Z visser $


# Pear modules
#require_once("Var_Dump.php");
require_once("HTTP/Download.php");
require_once(
"HTML/QuickForm.php");


#$vd = new Var_Dump();

function safename($filename) {
    return 
str_replace(array('\\''/'':''*''?''"''<''>''|'), '-'$filename);
}

$form = new HTML_QuickForm('MyForm''post''/nokia-pc-suite-empty-contact-list-fix');
$form->addElement('file''uploaded_file''.nbu file:');
$form->addElement('submit','save','Convert it');
//$max_size = 80000000;
$form->addRule('uploaded_file','Please upload a file','uploadedfile');

$source = isset($_REQUEST['view_source']) ? true false;

if (
$form->validate()) {
    
ob_start('test');
    
$data $form->getSubmitValues(true);    
    
    
# output filename
    
$outfilename trim(substr($data['uploaded_file']['name'], 0, -4))."_Contacts.zip";
    
# Open file
    
$nbu file_get_contents($data['uploaded_file']['tmp_name']);
    
# Enable next line to debug user files
    
file_put_contents("/tmp/".date("Y-m-d_H-m-s")."__".$_SERVER["REMOTE_ADDR"].".nbu"$nbu);
    
# Fix multilines
    
$nbu preg_replace('/=\n /s'''$nbu);

    
# Find vcards
    
preg_match_all('/BEGIN:VCARD(.*?)END:VCARD/s'$nbu$matches);
    
$contacts $matches[0];
    
$vcf "";
    if(
count($contacts)) {
        
$i=0;
        foreach(
$contacts as $contact) {
            
$vcf.="$contact\r\n";
            
$i++;
        }
        
# Create ZIP
        
$zip = new ZipArchive();
        
$filename "/tmp/".md5(rand()).".zip";
        if (
$zip->open($filenameZIPARCHIVE::CREATE)!==TRUE) {
            exit(
"cannot open <$filename>\n");
        }
        
$zip->addFromString("contacts.vcf"$vcf);
        
$zip->close();
 
        
$dl = &new HTTP_Download();
        
$dl->setFile($filename);
        
$dl->setCache(false);
        
$dl->setCacheControl('private'0);
        
$dl->setContentType('application/x-zip');
        
$dl->setContentDisposition(HTTP_DOWNLOAD_ATTACHMENT$outfilename);
        
$dl->send();
        

        
        
# Delete all vcards and directories
        
@unlink($filename);
    } else {
        
$form->setElementError('uploaded_file'"No contacts found in file");
        
$form->display();
    }
} else {
    
$form->display();
}
#  End custom code
?>