public function directoryForDropoff(&$claimID = NULL, &$claimDir = NULL) { if ($claimID) { if (is_dir($this->_dropboxDirectory . "/{$claimID}")) { $claimDir = $this->_dropboxDirectory . "/{$claimID}"; return TRUE; } } else { while (1) { $claimID = NSSGenerateCode(); // Is it already in the database? $this->database->DBListClaims($claimID, $extant); if (!$extant || count($extant) == 0) { // Make sure there's no directory hanging around: if (!file_exists($this->_dropboxDirectory . "/{$claimID}")) { if (mkdir($this->_dropboxDirectory . "/{$claimID}", 0700)) { $claimDir = $this->_dropboxDirectory . "/{$claimID}"; return TRUE; } $this->writeToLog("unable to create " . $this->_dropboxDirectory . "/{$claimID}"); break; } } } } return FALSE; }
private function initWithFormData() { global $NSSDROPBOX_URL; global $smarty; // Start off with the data from the form posting, overwriting it with // stored data as necessary. $senderName = paramPrepare($_POST['senderName']); $senderEmail = paramPrepare(strtolower($_POST['senderEmail'])); $senderOrganization = paramPrepare($_POST['senderOrganization']); // SLASH $note = stripslashes($_POST['note']); $note = $_POST['note']; $expiry = 0; // If they have a valid req key, then they don't need to be verified // or logged in. $reqSubject = ''; $req = ''; if ($_POST['req'] != '') { $dummy = ''; $recipName = ''; // Never actually use this $recipEmail = ''; // Never actually use this $req = preg_replace('/[^a-zA-Z0-9]/', '', $_POST['req']); if ($this->_dropbox->ReadReqData($req, $recipName, $recipEmail, $senderOrganization, $senderName, $senderEmail, $dummy, $reqSubject, $expiry)) { if ($expiry < time()) { $this->_dropbox->DeleteReqData($req); return $smarty->getConfigVariable('ErrorReadAuth'); } // It was a valid req key, so leave $req alone (and true). $reqSubject = trim($reqSubject); $this->_subject = $reqSubject; } else { // Invalid request code, so ignore them $req = FALSE; $reqSubject = ''; } } // It is not a request, or not a valid request if ($req == '') { // So now they must be authorized as it's not a request if (!$this->_dropbox->authorizedUser()) { $auth = $_POST['auth']; // JKF Get the above from the auth database // JKF Fail if it doesn't exist or it's a pickup auth not a dropoff $authdatares = $this->_dropbox->ReadAuthData($auth, $senderName, $senderEmail, $senderOrganization, $expiry); if (!$authdatares) { return $smarty->getConfigVariable('ErrorReadAuth'); } // If the email is blank (and name has no spaces) then it's a pickup. // In a pickup, the name is used as the sender's IP address. if (!preg_match('/ /', $senderName) && $senderEmail == '') { return $smarty->getConfigVariable('ErrorReadAuth'); } if ($expiry < time()) { $this->_dropbox->DeleteAuthData($auth); return $smarty->getConfigVariable('ErrorReadAuth'); } } else { // Logged-in user so just read their data $senderName = $this->_dropbox->authorizedUserData("displayName"); $senderOrganization = paramPrepare($_POST['senderOrganization']); $senderEmail = trim($this->_dropbox->authorizedUserData("mail")); } } // Erase the note if it is just white space. if (preg_match('/^\\s*$/', $note)) { $note = ""; } // Check the length of the note. $notelength = strlen($note); $maxlen = $this->_dropbox->maxnotelength(); if ($notelength > $maxlen) { return sprintf($smarty->getConfigVariable('ErrorNoteTooLong'), $notelength, $maxlen); } $confirmDelivery = $_POST['confirmDelivery'] ? TRUE : FALSE; $informRecipients = $_POST['informRecipients'] ? TRUE : FALSE; $recipients = array(); $recipIndex = -1; // <0 => no recipients found $arraykeys = array_keys($_POST); foreach ($arraykeys as $arraykey) { $matches = array(); if (preg_match('/^recipient_(\\d+)/', $arraykey, $matches)) { $recipIndex = $matches[1]; //while ( array_key_exists('recipient_'.$recipIndex,$_POST) ) { $recipName = paramPrepare($_POST['recipName_' . $recipIndex]); $recipEmail = paramPrepare($_POST['recipEmail_' . $recipIndex]); if ($recipName || $recipEmail) { // Take the email to purely lowercase for simplicity: $recipEmail = strtolower($recipEmail); // Just a username? We add an implicit "@domain.com" for these and validate them! $emailParts[1] = NULL; $emailParts[2] = NULL; if (preg_match('/\\@/', $recipEmail)) { // Has an @ sign so is an email address. Must be valid! if (!preg_match($this->_dropbox->validEmailRegexp(), $recipEmail, $emailParts)) { return sprintf($smarty->getConfigVariable('ErrorBadRecipient'), $recipEmail); } } else { // No @ sign so just stick default domain in right hand side $emailParts[1] = $recipEmail; $emailParts[2] = $this->_dropbox->defaultEmailDomain(); } $recipEmailDomain = $emailParts[2]; // Don't think this line is needed any more, but harmless $recipEmail = $emailParts[1] . "@" . $emailParts[2]; // Look at the recipient's email domain; un-authenticated users can only deliver // to the dropbox's domain: // JKF Changed checkRecipientDomain to return true if it's a local user if (!$this->_dropbox->authorizedUser() && !$this->_dropbox->checkRecipientDomain($recipEmail)) { return $smarty->getConfigVariable('ErrorWillNotSend'); } $recipients[] = array($recipName ? $recipName : "", $recipEmail); } else { if ($recipName && !$recipEmail) { return $smarty->getConfigVariable('ErrorNoEmail'); } } //$recipIndex++; } } // No recipients found? if ($recipIndex < 0) { return $smarty->getConfigVariable('ErrorNoEmail'); } // // Check for an uploaded CSV/TXT file containing addresses: // if ($_FILES['recipient_csv']['tmp_name']) { if ($_FILES['recipient_csv']['error'] != UPLOAD_ERR_OK) { $error = sprintf($smarty->getConfigVariable('ErrorWhileUploading'), $_FILES['recipient_csv']['name']); switch ($_FILES['recipient_csv']['error']) { case UPLOAD_ERR_INI_SIZE: $error .= $smarty->getConfigVariable('ErrorRecipientsTooBigForPHP'); break; case UPLOAD_ERR_FORM_SIZE: $error .= sprintf($smarty->getConfigVariable('ErrorRecipientsFileTooBig'), $this->_dropbox->maxBytesForFile()); break; case UPLOAD_ERR_PARTIAL: $error .= $smarty->getConfigVariable('ErrorRecipientsPartialUpload'); break; case UPLOAD_ERR_NO_FILE: $error .= $smarty->getConfigVariable('ErrorNoRecipientsFile'); break; case UPLOAD_ERR_NO_TMP_DIR: $error .= $smarty->getConfigVariable('ErrorNoTemp'); break; case UPLOAD_ERR_CANT_WRITE: $error .= $smarty->getConfigVariable('ErrorBadTemp'); break; } return $error; } // Parse the CSV/TXT file: if ($csv = fopen($_FILES['recipient_csv']['tmp_name'], 'r')) { while ($fields = fgetcsv($csv)) { if ($fields[0] !== NULL) { // Got one; figure out which field is an email address: foreach ($fields as $recipEmail) { // Take the email to purely lowercase for simplicity: $recipEmail = strtolower($recipEmail); // JKF Don't allow just usernames in CSV file! if (!preg_match($this->_dropbox->validEmailRegexp(), $recipEmail, $emailParts)) { continue; } $recipEmailDomain = $emailParts[2]; $recipEmail = $emailParts[1] . "@" . $emailParts[2]; // Look at the recipient's email domain; // un-authenticated users can only deliver to the dropbox's // domain: if (!$this->_dropbox->authorizedUser() && !$this->_dropbox->checkRecipientDomain($recipEmail)) { return $smarty->getConfigVariable('ErrorWillNotSend'); } // $recipients[] = array(( $recipName ? $recipName : "" ),$recipEmail); $recipients[] = array("", $recipEmail); } } } fclose($csv); } else { return $smarty->getConfigVariable('ErrorBadRecipientsFile'); } //$fileCount = count( array_keys($_FILES) ) - 1; //} else { // //$fileCount = count( array_keys($_FILES) ); // $fileCount = numberOfFiles(); } // If it's in response to a request, and the recipient override // is set, then zap the first recipient and replace with ours. $reqRecipient = $this->_dropbox->reqRecipient(); if ($req != '' && $reqRecipient != '') { $recipients[0][1] = $reqRecipient; } // Reduce the list of recipients to those with unique email addresses uniqueifyRecipients($recipients); // Confirm that all fields are present and accounted for: $fileCount = $this->numberOfFiles(); if ($fileCount == 0) { return $smarty->getConfigVariable('ErrorNoFiles'); } // Now make sure each file was uploaded successfully, isn't too large, // and that the total size of the upload isn't over capacity: $i = 1; $totalBytes = 0.0; $totalFiles = 0; // while ( $i <= $fileCount ) { while ($i <= $this->maxFilesKey) { $key = "file_" . $i; if (array_key_exists('file_select_' . $i, $_POST) && $_POST['file_select_' . $i] != "-1") { $totalFiles++; } elseif ($_FILES[$key]['name']) { if ($_FILES[$key]['error'] != UPLOAD_ERR_OK) { $error = sprintf($smarty->getConfigVariable('ErrorWhileUploading'), $_FILES[$key]['name']); switch ($_FILES[$key]['error']) { case UPLOAD_ERR_INI_SIZE: $error .= $smarty->getConfigVariable('ErrorTooBigForPHP'); break; case UPLOAD_ERR_FORM_SIZE: $error .= sprintf($smarty->getConfigVariable('ErrorFileTooBig'), $this->_dropbox->maxBytesForFile()); break; case UPLOAD_ERR_PARTIAL: $error .= $smarty->getConfigVariable('ErrorPartialUpload'); break; case UPLOAD_ERR_NO_FILE: $error .= $smarty->getConfigVariable('ErrorNoFile'); break; case UPLOAD_ERR_NO_TMP_DIR: $error .= $smarty->getConfigVariable('ErrorNoTemp'); break; case UPLOAD_ERR_CANT_WRITE: $error .= $smarty->getConfigVariable('ErrorBadTemp'); break; } return $error; } if (($bytes = $_FILES[$key]['size']) < 0) { // Grrr...stupid 32-bit nonsense. Convert to the positive // value float-wise: $bytes = ($bytes & 0x7fffffff) + 2147483648.0; } if ($bytes > $this->_dropbox->maxBytesForFile()) { return sprintf($smarty->getConfigVariable('ErrorNamedFileTooBig'), $_FILES[$key]['name'], NSSFormattedMemSize($this->_dropbox->maxBytesForFile())); } if (($totalBytes += $bytes) > $this->_dropbox->maxBytesForDropoff()) { return sprintf($smarty->getConfigVariable('ErrorDropoffTooBig'), $_FILES[$key]['name'], NSSFormattedMemSize($this->_dropbox->maxBytesForDropoff())); } // MyZendTo: If they don't have enough quota left, disallow it if (preg_match('/^[yYtT1]/', MYZENDTO)) { $QuotaLeft = $this->_dropbox->database->DBRemainingQuota($this->_dropbox->authorizedUser()); if ($totalBytes > $QuotaLeft) { return sprintf($smarty->getConfigVariable('ErrorDropoffQuota'), NSSFormattedMemSize($totalBytes - $QuotaLeft)); } } $totalFiles++; } $i++; } //if ( $totalBytes == 0 ) { if ($totalFiles == 0) { return $smarty->getConfigVariable('ErrorNoFiles'); } // JKF Start // // Call clamdscan on all the files, fail if they are infected // If the name of the scanner is set to '' or 'DISABLED' then skip this. $clamdscancmd = $this->_dropbox->clamdscan(); if ($clamdscancmd != 'DISABLED') { $ccfilecount = 1; $ccfilelist = ''; $foundsometoscan = FALSE; while ($ccfilecount <= $this->maxFilesKey) { // For every possible file, we only add it to the list of clamd // targets if it's not a library file (assumed clean), but it is // an uploaded file, and that file-slot in the form was used. $filekey = "file_" . $ccfilecount; $selectkey = "file_select_" . $ccfilecount; if (!(array_key_exists($selectkey, $_POST) && $_POST[$selectkey] != "-1") && array_key_exists($filekey, $_FILES) && array_key_exists('tmp_name', $_FILES[$filekey]) && $_FILES[$filekey]['tmp_name'] !== '') { // and is not blank $ccfilelist .= ' ' . $_FILES[$filekey]['tmp_name']; $foundsometoscan = TRUE; } $ccfilecount++; } if ($foundsometoscan) { // Don't do any of this if they uploaded nothing exec("/bin/chmod go+r " . $ccfilelist); // Need clamd to read them! $clamdinfected = 0; $clamdoutput = array(); $clamcmd = exec($clamdscancmd . $ccfilelist, $clamdoutput, $clamdinfected); if ($clamdinfected == 1) { return $smarty->getConfigVariable('ErrorVirusFound'); } if ($clamdinfected == 2) { return $smarty->getConfigVariable('ErrorVirusFailed'); } } } // // JKF End if (!$senderName) { return $smarty->getConfigVariable('ErrorSenderName'); } if (!$senderEmail) { return $smarty->getConfigVariable('ErrorSenderEmail'); } if (!preg_match($this->_dropbox->validEmailRegexp(), $senderEmail, $emailParts)) { return $smarty->getConfigVariable('ErrorSenderBadEmail'); } $senderEmail = $emailParts[1] . "@" . $emailParts[2]; // Invent a passcode and claim ID: $claimPasscode = NSSGenerateCode(); $claimID = NULL; $claimDir = NULL; if (!$this->_dropbox->directoryForDropoff($claimID, $claimDir)) { return $smarty->getConfigVariable('ErrorUniqueDir'); } // Insert into database: if ($this->_dropbox->database->DBStartTran()) { if ($dropoffID = $this->_dropbox->database->DBAddDropoff($claimID, $claimPasscode, $this->_dropbox->authorizedUser(), $senderName, $senderOrganization, $senderEmail, $_SERVER['REMOTE_ADDR'], $confirmDelivery, timestampForTime(time()), $note)) { // Add recipients: if (!$this->_dropbox->database->DBAddRecipients($recipients, $dropoffID)) { $this->_dropbox->database->DBRollbackTran(); return $smarty->getConfigVariable('ErrorStoreRecipients'); } // Process the files: $i = 1; $realFileCount = 0; $tplFiles = array(); // These are the file hashes we process in tpl. //while ( $i <= $fileCount ) { while ($i <= $this->maxFilesKey) { $key = "file_" . $i; $selectkey = 'file_select_' . $i; if (array_key_exists($selectkey, $_POST) && $_POST[$selectkey] != "-1") { // It's a library file. // Get the name of the library file they want (safely) // by removing all "../" elements and things like it $libraryfile = preg_replace('/\\.\\.[:\\/\\\\]/', '', $_POST[$selectkey]); $libraryfile = paramPrepare($libraryfile); // Generate a random filename (collisions are very unlikely) $tmpname = mt_rand(10000000, 99999999); // Link in the library file symlink($this->_dropbox->libraryDirectory() . '/' . $libraryfile, $claimDir . '/' . $tmpname); // Now strip off the possible subdirectory name as we only // want it in the symlink and not after that. $libraryfilesize = filesize($this->_dropbox->libraryDirectory() . '/' . $libraryfile); $libraryfile = trim(preg_replace('/^.*\\//', '', $libraryfile)); // We use this a few times $librarydesc = paramPrepare(trim($_POST["desc_" . $i])); // Add to database: if (!$this->_dropbox->database->DBAddFile1($dropoffID, $tmpname, $libraryfile, $libraryfilesize, "application/octet-stream", $librarydesc)) { // Exit gracefully -- dump database changes and remove the dropoff // directory: $this->_dropbox->writeToLog("error while adding dropoff library file to database for {$claimID}"); if (!rmdir_r($claimDir)) { $this->_dropbox->writeToLog("unable to remove {$claimDir} -- orphaned!!"); } if (!$this->_dropbox->database->DBRollbackTran()) { $this->_dropbox->writeToLog("failed to ROLLBACK after botched dropoff: {$claimID}"); $this->_dropbox->writeToLog("there may be orphans"); } return sprintf($smarty->getConfigVariable('ErrorNamedStore'), $libraryfile); } // That's right, one more file! $tplFiles[$realFileCount] = array(); $tplFiles[$realFileCount]['name'] = $libraryfile; $tplFiles[$realFileCount]['type'] = 'Library'; $tplFiles[$realFileCount]['size'] = NSSFormattedMemSize($libraryfilesize); $tplFiles[$realFileCount]['description'] = $librarydesc; $realFileCount++; // Update the description in the library index $this->_dropbox->database()->DBUpdateLibraryDescription($libraryfile, $librarydesc); } elseif ($_FILES[$key]['name']) { // It's an uploaded file $tmpname = basename($_FILES[$key]['tmp_name']); // Get file size from local copy, not what browser told us $bytes = filesize($_FILES[$key]['tmp_name']); if (!move_uploaded_file($_FILES[$key]['tmp_name'], $claimDir . "/" . $tmpname)) { // Exit gracefully -- dump database changes and remove the dropoff // directory: $this->_dropbox->writeToLog("error while storing dropoff files for {$claimID}"); if (!rmdir_r($claimDir)) { $this->_dropbox->writeToLog("unable to remove {$claimDir} -- orphaned!!"); } if (!$this->_dropbox->database->DBRollbackTran()) { $this->_dropbox->writeToLog("failed to ROLLBACK after botched dropoff: {$claimID}"); $this->_dropbox->writeToLog("there may be orphans"); } return sprintf($smarty->getConfigVariable('ErrorNamedDrop'), $_FILES[$key]['name']); } //if ( ($bytes = $_FILES[$key]['size']) < 0 ) { // // Grrr...stupid 32-bit nonsense. Convert to the positive // // value float-wise: // $bytes = ($bytes & 0x7FFFFFFF) + 2147483648.0; //} // Add to database: if (!$this->_dropbox->database->DBAddFile1($dropoffID, $tmpname, paramPrepare($_FILES[$key]['name']), $bytes, $_FILES[$key]['type'] ? $_FILES[$key]['type'] : "application/octet-stream", paramPrepare($_POST["desc_" . $i]))) { // Exit gracefully -- dump database changes and remove the dropoff // directory: $this->_dropbox->writeToLog("error while adding dropoff file to database for {$claimID}"); if (!rmdir_r($claimDir)) { $this->_dropbox->writeToLog("unable to remove {$claimDir} -- orphaned!!"); } if (!$this->_dropbox->database->DBRollbackTran()) { $this->_dropbox->writeToLog("failed to ROLLBACK after botched dropoff: {$claimID}"); $this->_dropbox->writeToLog("there may be orphans"); } return sprintf($smarty->getConfigVariable('ErrorNamedStore'), $_FILES[$key]['name']); } // That's right, one more file! $tplFiles[$realFileCount] = array(); $tplFiles[$realFileCount]['name'] = paramPrepare($_FILES[$key]['name']); $tplFiles[$realFileCount]['type'] = $_FILES[$key]['type']; // Get filesize from local copy, not browser $tplFiles[$i]['size'] = NSSFormattedMemSize($_FILES[$key]['size']); $tplFiles[$realFileCount]['size'] = NSSFormattedMemSize($bytes); $tplFiles[$realFileCount]['description'] = paramPrepare($_POST["desc_" . $i]); $realFileCount++; } $i++; } // Once we get here, it's time to commit the stuff to the database: $this->_dropbox->database->DBCommitTran(); $this->_dropoffID = $dropoffID; // At long last, fill-in the fields: $this->_claimID = $claimID; $this->_claimPasscode = $claimPasscode; $this->_claimDir = $claimDir; $this->_authorizedUser = $this->_dropbox->authorizedUser(); $this->_note = $note; $this->_senderName = $senderName; $this->_senderOrganization = $senderOrganization; $this->_senderEmail = $senderEmail; $this->_senderIP = $_SERVER['REMOTE_ADDR']; $senderIP = $_SERVER['REMOTE_ADDR']; $senderHost = gethostbyaddr($_SERVER['REMOTE_ADDR']); if ($senderHost != '') { $senderHost = '(' . $senderHost . ')'; } $this->_confirmDelivery = $confirmDelivery; $this->_informRecipients = $informRecipients; $this->_created = getdate(); $this->_recipients = $recipients; // This Drop-off request has been fulfilled, so kill the keys // to stop playback attacks. if ($req) { $this->_dropbox->DeleteReqData($req); } if ($auth) { $this->_dropbox->DeleteAuthData($auth); } // Work out the real email subject line. if ($reqSubject != '') { $emailSubject = $reqSubject; } else { if ($realFileCount == 1) { $emailSubject = sprintf($smarty->getConfigVariable('DropoffEmailSubject1'), $senderName); } else { $emailSubject = sprintf($smarty->getConfigVariable('DropoffEmailSubject2'), $senderName); } } // Construct the email notification and deliver: $smarty->assign('senderName', $senderName); $smarty->assign('senderOrg', $senderOrganization); $smarty->assign('senderEmail', $senderEmail); $smarty->assign('senderIP', $senderIP); $smarty->assign('senderHost', $senderHost); $smarty->assign('note', trim($note)); $smarty->assign('subject', $emailSubject); $smarty->assign('now', timestampForTime(time())); $smarty->assign('claimID', $claimID); $smarty->assign('claimPasscode', $claimPasscode); $smarty->assign('fileCount', $realFileCount); $smarty->assign('retainDays', $this->_dropbox->retainDays()); $smarty->assignByRef('files', $tplFiles); $emailTemplate = $smarty->fetch('dropoff_email.tpl'); // Update the address book entries for this user $this->_dropbox->updateAddressbook($recipients); // Inform all the recipients by email if they want me to if ($informRecipients) { // Do we want to Bcc the sender as well? $emailBcc = ''; if ($this->_dropbox->bccSender()) { // and don't forget to encode it if there are intl chars in it if (preg_match('/[^\\x00-\\x7f]/', $senderEmail)) { $emailBcc = "Bcc: =?UTF-8?B?" . base64_encode(html_entity_decode($senderEmail)) . "?=" . PHP_EOL; } else { $emailBcc = "Bcc: {$senderEmail}" . PHP_EOL; } } // Make the mail come from the sender, not ZendTo foreach ($recipients as $recipient) { // In MyZendTo, don't send email to myself if (preg_match('/^[yYtT1]/', MYZENDTO) && $senderEmail != $recipient[1] || preg_match('/^[^yYtT1]/', MYZENDTO)) { $emailContent = preg_replace('/__EMAILADDR__/', urlencode($recipient[1]), $emailTemplate); $success = $this->_dropbox->deliverEmail($recipient[1], $senderEmail, $emailSubject, $emailContent, $emailBcc); $emailBcc = ''; // Only Bcc the sender on the first email out if (!$success) { $this->_dropbox->writeToLog(sprintf("notification email not delivered successfully to %s for claimID {$claimID}", $recipient[1])); } else { $this->_dropbox->writeToLog(sprintf("notification email delivered successfully to %s for claimID {$claimID}", $recipient[1])); } } } } // Log our success: $this->_dropbox->writeToLog(sprintf("{$senderName} <{$senderEmail}> => {$claimID} [%s]", $realFileCount == 1 ? "1 file" : "{$realFileCount} files")); } else { return $smarty->getConfigVariable('ErrorAddDropoff'); } } else { return $smarty->getConfigVariable('ErrorBeginTransaction'); } return NULL; }