public function handleResultEnded(&$result) { if (!$this->fixed) { return; } $f = new TempFile(); if ($this->args['add_field_names']) { $a = array(); foreach ($this->fieldNames as $i => $t) { if (isset($this->widths[$i])) { $a[] = str_pad($t, $this->widths[$i] + $this->spacing); } else { $a[] = $t; } } $f->write(implode($this->separator, $a) . $this->term); } fseek($this->file->file, 0); while (($a = fgets($this->file->file)) !== FALSE) { $a = explode("\t", $a); foreach ($a as $i => &$c) { if (isset($this->widths[$i])) { $c = str_pad($c, $this->widths[$i] + $this->spacing); } } $f->write(implode($this->separator, $a)); } $this->file->close(); unlink($this->file->name); $this->file = $f; }
/** Create a new properties object from a string source */ protected function newPropertiesFrom(string $source) : Properties { with($t = new TempFile()); $t->out()->write($source); $t->close(); return (new Properties())->load($t); }
public function testDestructShouldEraseFile() { $instance = new TempFile(); $fileName = $instance->getFileName(); $this->assertFileExists($fileName); unset($instance); $this->assertFileNotExists($fileName); }
/** * Upload by base64 encoded source * * @param ImageInterface $image Image entity * @param string $content Base64 source * @param array $options Upload options * * @return ImageInterface */ public function uploadBase64(ImageInterface $image, $content, array $options = []) { $this->tmpFile->create()->write(base64_decode($content)); try { $image = $this->upload($image, $this->tmpFile->getPath(), $options); } finally { $this->tmpFile->clear(); } return $image; }
/** * Deletes all temp files and resets the cache * Use this function to clean up the file system on exit * @return void */ public static function clear() { foreach (self::$tempFiles as $file) { unlink($file); } self::$tempFiles = array(); }
public function testClear() { $files = array('test1', 'test2'); $_files = array(); foreach ($files as $file) { $_files[] = TempFile::fileName($file); } TempFile::clear(); foreach ($_files as $file) { $this->assertFalse(file_exists($file)); } }
/** * Overridden version of `buildTestFuture` so that the unit test can be run * via `cscover`, which instruments assemblies and reports on code coverage. * * @param string Name of the test assembly. * @return array The future, output filename and coverage filename * stored in an array. */ protected function buildTestFuture($test_assembly) { if ($this->getEnableCoverage() === false) { return parent::buildTestFuture($test_assembly); } // FIXME: Can't use TempFile here as xUnit doesn't like // UNIX-style full paths. It sees the leading / as the // start of an option flag, even when quoted. $xunit_temp = Filesystem::readRandomCharacters(10) . '.results.xml'; if (file_exists($xunit_temp)) { unlink($xunit_temp); } $cover_temp = new TempFile(); $cover_temp->setPreserveFile(true); $xunit_cmd = $this->runtimeEngine; $xunit_args = null; if ($xunit_cmd === '') { $xunit_cmd = $this->testEngine; $xunit_args = csprintf('%s /xml %s', $test_assembly, $xunit_temp); } else { $xunit_args = csprintf('%s %s /xml %s', $this->testEngine, $test_assembly, $xunit_temp); } $assembly_dir = dirname($test_assembly); $assemblies_to_instrument = array(); foreach (Filesystem::listDirectory($assembly_dir) as $file) { if (substr($file, -4) == '.dll' || substr($file, -4) == '.exe') { if ($this->assemblyShouldBeInstrumented($file)) { $assemblies_to_instrument[] = $assembly_dir . DIRECTORY_SEPARATOR . $file; } } } if (count($assemblies_to_instrument) === 0) { return parent::buildTestFuture($test_assembly); } $future = new ExecFuture('%C -o %s -c %s -a %s -w %s %Ls', trim($this->runtimeEngine . ' ' . $this->coverEngine), $cover_temp, $xunit_cmd, $xunit_args, $assembly_dir, $assemblies_to_instrument); $future->setCWD(Filesystem::resolvePath($this->projectRoot)); return array($future, $assembly_dir . DIRECTORY_SEPARATOR . $xunit_temp, $cover_temp); }
private function getConfigPath($outputPath) { $doxyConfig = new DoxyConfig(); $doxyConfig->add('@INCLUDE', $this->configPath); $doxyConfig->add('OUTPUT_DIRECTORY', $outputPath); $doxyConfig->add('STRIP_FROM_PATH', $this->stripPaths); $doxyConfig->add('INPUT', $this->inputPaths); foreach ($this->otherOpts as $key => $value) { $doxyConfig->add($key, $value); } $this->primaryConfig = new TempFile(false); $doxyConfig->write($this->primaryConfig); return $this->primaryConfig->getPath(); }
public static function factory(Storage $storage, $row) { $tempfile = new TempFile($storage); $tempfile->setTempFileID($row["tempfileid"]); $tempfile->setTimestamp($row["timestamp"]); $tempfile->setUserID($row["userid"]); $tempfile->setFileID($row["fileid"]); return $tempfile; }
private function generateTempFile() { $tempfile = new TempFile($this->getStorage()); $file = new File($this->getStorage()); $file->setExportFilename("vpanel-chart-" . date("Y-m-d")); $file->save(); $tempfile->setFile($file); $tempfile->setTimestamp(time()); $tempfile->setUserID($this->getUserID()); $tempfile->save(); $this->tempfileids[] = $tempfile->getTempFileID(); return $tempfile; }
/** * Produce diff between the contents * * @param string left * @param string right */ protected function diff($left, $right) { with($templ = new TempFile(), $tempr = new TempFile(), $templ->open(FILE_MODE_WRITE), $tempr->open(FILE_MODE_WRITE)); $templ->write($left); $tempr->write($right); $templ->close(); $tempr->close(); // TODO: Implement "diff" in userland try { $p = new Process(sprintf('diff -u %s %s', $templ->getURI(), $tempr->getURI())); $p->in->close(); while (!$p->out->eof()) { $this->out->writeLine($p->out->readLine()); } $p->close(); } catch (IOException $e) { $this->err->writeLine('!=> Invocation of `diff` program failed.'); $templ->unlink(); $tempr->unlink(); return; } $templ->unlink(); $tempr->unlink(); }
/** * Commit the file (needs write access to repository) * * @param string comment */ public function commit($comment) { $f = new TempFile(); $f->open(FILE_MODE_WRITE); $f->writeLine($comment); $f->close(); $return = $this->_execute(sprintf('commit -F %s %s', $f->getURI(), $this->filename)); $f->unlink(); return $return; }
public function clearTemporaryFiles(array $attachments = array()) { foreach ($attachments as $attachment) { $type = $attachment['type']; if ($type === 'temp') { $file = 'uploads/protected/media/temp/' . $attachment['folder'] . '/' . $attachment['filename']; $folder = 'uploads/protected/media/temp/' . $attachment['folder']; if (file_exists($file)) { unlink($file); } // delete temp file if (file_exists($folder)) { rmdir($folder); } // delete temp folder TempFile::model()->deleteByPk($attachment['id']); } } }
} $srcCols = array(); $trgCols = array(); $trgType = array(); foreach ($ARGS['columns'] as $k => $v) { $trgCols[] = "`{$k}`"; $srcCols[] = $v[0]; $trgType[] = $v[1]; } if ($enc) { $re1 = "/(?:^|\\{$sep})(" . ($nul ? $nul . "|" : "") . "\\{$enc}(?:[^\\{$enc}\\\\]|\\{$enc}\\{$enc}|\\\\.)*\\{$enc})/"; $re2 = "/\\{$enc}\\{$enc}|\\\\{$enc}/"; } require_once __INC__ . '/mysql.php'; if ($toFile = $ARGS['to_file']) { $file = new TempFile(); } $sqlPrefix = "{$ARGS['cmd']} {$ARGS['table']} (" . implode(', ', $trgCols) . ") VALUES\n"; $rawLineCnt = $columnCnt = $dataLineCnt = 0; $sql = ''; while (($a = fgets($f)) !== FALSE) { if ($rawLineCnt++ < $off || !($a = trim($a, "\r\n"))) { continue; } if ($fen) { $a = mb_convert_encoding($a, 'UTF-8', $fen); } if ($enc) { preg_match_all($re1, $a, $m); $a = $m[1]; } else {
/** * Commit the file (needs write access to repository) * * @param string comment * @see http://www.cvshome.org/docs/manual/cvs_16.html#SEC124 */ public function commit($comment) { $f = new TempFile(); $f->open(FILE_MODE_WRITE); $f->writeLine($comment); $f->close(); $return = $this->_execute(sprintf('commit -F %s', $f->getURI())); // It seems CVS automatically removes the tmp-file after // reading it, so we don't need to do so (gives error). return $return; }
protected function didFailParse($message) { $context = 5; $min = max(0, $this->line - $context); $max = min($this->line + $context, count($this->text) - 1); $context = ''; for ($ii = $min; $ii <= $max; $ii++) { $context .= sprintf('%8.8s %6.6s %s', $ii == $this->line ? '>>> ' : '', $ii + 1, $this->text[$ii]); } $out = array(); $out[] = pht('Diff Parse Exception: %s', $message); if ($this->writeDiffOnFailure) { $temp = new TempFile(); $temp->setPreserveFile(true); Filesystem::writeFile($temp, $this->rawDiff); $out[] = pht('Raw input file was written to: %s', $temp); } $out[] = $context; $out = implode("\n\n", $out); throw new Exception($out); }
/** * This is the workhorse function that processes commands entered in the shell * @param string $command * @return void */ public function doCommand($command) { $this->inReadline = false; // detect ctl-d if ($command === NULL) { exit(0); } // no need to process empty commands if (trim($command) == '') { return; } // internal command parser $matches = array(); if (preg_match("/\\s*\\{$this->commandEscapeChar}([\\w\\?]+)\\s?(.*)/", trim($command), $matches)) { $internalCommand = $matches[1]; $argsString = $matches[2]; $args = array(); if (preg_match_all("/(?:([\\w]+)\\s?)/", $argsString, $matches)) { $args = $matches[1]; } if (isset($this->internalCommands[$internalCommand])) { $this->internalCommands[$internalCommand]->run($this, $args); } else { print "Command '{$internalCommand}' does not exist.\n"; } return; } // normal command if (!empty($command) and function_exists('readline_add_history')) { readline_add_history($command); readline_write_history($this->historyFile()); } $command = preg_replace('/^\\//', '$_', $command); // "/" as a command will just output the last result. $requires = unserialize(TempFile::readFromFile('requires')); if (!is_array($requires)) { $requires = array(); } $replacments = array('{$command}' => $command, '{$requires}' => var_export($requires, true), '{$requiresFile}' => TempFile::fileName('requires'), '{$stateFile}' => TempFile::fileName('state')); $parsedCommand = str_replace(array_keys($replacments), array_values($replacments), self::getTemplate('command')); try { $_ = $this->lastResult; TempFile::writeToFile('command', $parsedCommand); $result = NULL; $output = array(); $command_array = array($this->options[self::OPT_PHP_BIN], TempFile::fileName('command'), '2>&1'); $lastLine = exec(implode(' ', $command_array), $output, $result); if ($result != 0) { throw new Exception("Fatal error executing php: " . join("\n", $output)); } // boostrap requires environment of command $requires = unserialize(TempFile::readFromFile('requires')); foreach ($requires as $require) { if ($require === TempFile::fileName('command')) { continue; } require_once $require; } $lastState = unserialize(TempFile::readFromFile('state')); $this->lastResult = $lastState['_']; if ($lastState['__out']) { print $lastState['__out'] . "\n"; } else { if (is_object($this->lastResult) && !is_callable(array($this->lastResult, '__toString'))) { print_r($this->lastResult) . "\n"; } else { print $this->lastResult . "\n"; } } // after the eval, we might have new classes. Only update it if real readline is enabled if (!empty($this->autocompleteList)) { $this->autocompleteList = array_merge($this->autocompleteList, get_declared_classes()); } } catch (Exception $e) { print "Uncaught exception with command:\n" . $e->getMessage() . "\n"; } }
<?php /*--------------------------------------------------------------------* | Copyright (c) 2010-2013 Vayer Software Ltd. - All Rights Reserved. | *--------------------------------------------------------------------*/ $res = "--\n-- DbNinja v" . VERSION . " for MySQL\n-- Date: " . date("Y-m-d H:i:s") . " (UTC)\n--\n\n"; foreach ($ARGS['users'] as $i) { $u = "'" . addslashes($i['user']) . "'@'" . addslashes($i['host']) . "'"; if ($i['withDrop']) { $res .= "DROP USER {$u};\n"; } if ($i['withCreate']) { $res .= "CREATE USER {$u};\n"; } if ($i['withGrants'] && (!$i['withDrop'] || $i['withCreate'])) { $q = MySQLQuery::SimpleQuery($LINK, "SHOW GRANTS FOR {$u}", TRUE); if ($q === FALSE) { return $LINK->error; } $res .= $q[0][0] . ";\n"; } $res .= "\n"; } if ($ARGS['to_file']) { $f = new TempFile(); $f->write($res); } return array('result' => $ARGS['to_file'] ? $f->name : $res);
<?php /*--------------------------------------------------------------------* | Copyright (c) 2010-2013 Vayer Software Ltd. - All Rights Reserved. | *--------------------------------------------------------------------*/ require_once __INC__ . '/mysql.php'; require_once __INC__ . '/export_stuff.php'; date_default_timezone_set("UTC"); $q = MySQLQuery::SimpleQuery($LINK, 'SELECT VERSION()', TRUE); if ($q === FALSE) { return $LINK->error; } $file = new TempFile(NULL, 'UTF-8', $ARGS['file_encoding']); $db = $ARGS['db']; $disFKeys = $ARGS['tables_data'] && $ARGS['no_foreign_keys']; $file->write(getExportHeader($disFKeys, $q[0][0], $db)); function delimit(&$s) { if (strrchr($s, ";")) { $delim = "\$\$"; while (strstr($s, $delim)) { $delim .= $delim; } return "DELIMITER {$delim}\n\n{$s}{$delim}\n\nDELIMITER ;\n\n\n"; } return $s . ";\n\n\n"; } if ($ARGS['with_create_db']) { if ($ARGS['with_drop_db']) { $file->write("DROP DATABASE IF EXISTS `{$db}`;\n"); }
private function handleRequest($offset, $time) { Log::SetPrefix(sprintf("Thumbnail(%d): ", getmypid())); $hash = $this->getHash(); if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $hash) { header(getenv("SERVER_PROTOCOL") . " 304 Not Modified"); header("Content-Length: 0"); exit; } $cachedir = CACHE_DIR; umask(077); if (!is_dir($cachedir)) { Log::Info("Creating cache directory %s", $cachedir); @mkdir($cachedir); } $file = $cachedir . '/' . $this->getHash() . '-' . $offset; if (is_file($file)) { $lm = filemtime($file); header("Content-Type: image/jpeg"); header("Etag: \"" . $this->getHash() . "-" . $offset . "\""); header("Last-Modified: " . gmdate('D, d M Y H:i:s T', $lm)); header("Expires: " . gmdate('D, d M Y H:i:s T', $lm + 86400)); if (array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER) && $_SERVER['HTTP_IF_MODIFIED_SINCE']) { header(getenv("SERVER_PROTOCOL") . " 304 Not Modified"); header("Content-Length: 0"); Log::Debug("request already satisfied by HTTP_IF_MODIFIED_SINCE header, file=%s", $file); exit; } echo file_get_contents($file); exit; } $outdir = $cachedir . '/' . getmypid(); if (!is_dir($outdir)) { Log::Debug("Creating work directory %s", $outdir); mkdir($outdir, 0700); } $tempfile = new TempFile(".ts"); $infile = new File($this->stream, false); $infile->seek($offset); $data = $infile->read(1024 * 1024); $infile->close(); $tempfile->write($data); $cmd = sprintf("%s -nolirc -really-quiet -zoom -quiet -xy %d -vo jpeg:outdir=%s:maxfiles=2 -ao null %s -frames 2 &> /dev/null", MPLAYER, $this->width(), $outdir, escapeshellarg($tempfile->Filename())); $ts = microtime(true); Log::Debug("command=%s", $cmd); exec($cmd); $elapsed = microtime(true) - $ts; Log::Debug("command executed, duration=%.6f sec", $elapsed); $tempfile = $this->chooseBestImage($outdir); Log::Debug("using image %s", $tempfile); if (!is_file($tempfile)) { Log::Error("command failed, command was %s", $cmd); header("HTTP/1.0 404 not found"); exit; } $im = @imagecreatefromjpeg($tempfile); $timestring = sprintf("%02d:%02d:%02d", floor($time / 3600), floor($time % 3600 / 60), $time % 60); $this->writeTextAligned($im, self::ALIGN_LEFT, self::ALIGN_TOP, $timestring); ob_start(); imagejpeg($im, '', 60); $data = ob_get_contents(); ob_end_clean(); $this->cleanDirectory($outdir); if ($data != '') { Log::Debug("finished generation, Size=%d", strlen($data)); header("Content-Type: image/jpeg"); file_put_contents($file, $data); $lm = filemtime($file); header("Last-Modified: " . gmdate('D, d M Y H:i:s T', $lm)); header("Etag: \"" . $this->getHash() . "-" . $offset . "\""); header("Expires: " . gmdate('D, d M Y H:i:s T', $lm + 86400)); } else { Log::Error("oops, data is empty, should not happen"); } print $data; exit; }
/** * Remove a temp file and the temp folder that is in. */ public function actionRemoveTmpUpload() { if (isset($_POST['id'])) { $id = $_POST['id']; if (is_numeric($id)) { $tempFile = TempFile::model()->findByPk($id); if ($tempFile) { $folder = $tempFile->folder; $name = $tempFile->name; if (file_exists('uploads/media/temp/' . $folder . '/' . $name)) { unlink('uploads/media/temp/' . $folder . '/' . $name); } // delete file if (file_exists('uploads/media/temp/' . $folder)) { rmdir('uploads/media/temp/' . $folder); } // delete folder $tempFile->delete(); // delete database entry tracking temp file } } } }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionUpload() { $model = new Media(); if (isset($_POST['Media'])) { $temp = TempFile::model()->findByPk($_POST['TempFileId']); $userFolder = Yii::app()->user->name; // place uploaded files in a folder named with the username of the user that uploaded the file $userFolderPath = 'uploads/media/' . $userFolder; // if user folder doesn't exit, try to create it if (!(file_exists($userFolderPath) && is_dir($userFolderPath))) { if (!@mkdir('uploads/media/' . $userFolder, 0777, true)) { // make dir with edit permission // ERROR: Couldn't create user folder var_dump($userFolder); exit; } } rename($temp->fullpath(), $userFolderPath . '/' . $temp->name); // save media info $model->fileName = $temp->name; $model->createDate = time(); $model->lastUpdated = time(); $model->uploadedBy = Yii::app()->user->name; $model->associationType = $_POST['Media']['associationType']; $model->associationId = $_POST['Media']['associationId']; $model->private = $_POST['Media']['private']; $model->path; // File type setter is embedded in the magic getter for path $model->name = $_POST['Media']['name']; if (empty($model->name)) { $model->name = $model->fileName; } if ($_POST['Media']['description']) { $model->description = $_POST['Media']['description']; } /* uncomment when media module supports custom forms if(isset($_POST['x2ajax'])){ $ajaxErrors = $this->quickCreate ($model); if (!$ajaxErrors) { $this->createAttachmentAction ($model); } }else{*/ if ($model->save()) { $this->createAttachmentAction($model); $this->redirect(array('view', 'id' => $model->id)); } //} } /* uncomment when media module supports custom forms if(isset($_POST['x2ajax'])){ $this->renderInlineCreateForm ($model, isset ($ajaxErrors) ? $ajaxErrors : false); } else {*/ $this->render('upload', array('model' => $model)); //} }
public static function createTempFile($name) { // delete old temp files if they exist $old = time() - 86400; // 1 day old $oldTempFiles = TempFile::model()->findAll("createDate < {$old}"); foreach ($oldTempFiles as $oldTempFile) { $oldFolder = $oldTempFile->folder; $oldName = $oldTempFile->name; if (file_exists('uploads/protected/media/temp/' . $oldFolder . '/' . $oldName)) { unlink('uploads/protected/media/temp/' . $oldFolder . '/' . $oldName); } // delete file if (file_exists('uploads/protected/media/temp/' . $oldFolder)) { rmdir('uploads/protected/media/temp/' . $oldFolder); } // delete folder $oldTempFile->delete(); // delete database entry tracking temp file } // generate temp folder name $folder = substr(md5(rand()), 0, 10); // try to create temp folder if (!@mkdir('uploads/protected/media/temp/' . $folder, 0777, true)) { return false; } // couldn't create temp folder $tempFile = new TempFile(); // track temp file in database $tempFile->folder = $folder; $tempFile->name = $name; $tempFile->createDate = time(); if ($tempFile->save()) { return $tempFile; } else { return false; } }
/** * Perform the email delivery with PHPMailer. * * Any special authentication and security should take place in here. * * @param array $addresses This array must contain "to", "cc" and/or "bcc" * keys, and values must be arrays of recipients. Each recipient is expressed * as a 2-element array with the first element being the name, and the second * the email address. * @throws Exception * @return array */ public function deliverEmail($addresses, $subject, $message, $attachments = array()) { if (YII_DEBUG && self::DEBUG_EMAIL) { // Fake a successful send /**/ AuxLib::debugLog('Faking an email delivery to address(es): ' . var_export($addresses, 1)); return $this->status = $this->getDebugStatus(); } $phpMail = $this->mailer; try { $this->addEmailAddresses($phpMail, $addresses); $phpMail->Subject = $subject; // $phpMail->AltBody = $message; $phpMail->MsgHTML($message); // $phpMail->Body = $message; // add attachments, if any if ($attachments) { foreach ($attachments as $attachment) { $type = $attachment['type']; switch ($type) { case 'temp': // stored as a temp file? $file = 'uploads/media/temp/' . $attachment['folder'] . '/' . $attachment['filename']; if (file_exists($file)) { // check file exists if ($this->validateFileSize(filesize($file))) { $phpMail->AddAttachment($file); } } break; case 'media': // stored in media library $file = 'uploads/media/' . $attachment['folder'] . '/' . $attachment['filename']; if (file_exists($file)) { // check file exists if ($this->validateFileSize(filesize($file))) { $phpMail->AddAttachment($file); } } break; default: throw new CException('Invalid attachment type'); } } } $phpMail->Send(); // delete temp attachment files, if they exist if ($attachments) { foreach ($attachments as $attachment) { $type = $attachment['type']; if ($type === 'temp') { $file = 'uploads/media/temp/' . $attachment['folder'] . '/' . $attachment['filename']; $folder = 'uploads/media/temp/' . $attachment['folder']; if (file_exists($file)) { unlink($file); } // delete temp file if (file_exists($folder)) { rmdir($folder); } // delete temp folder TempFile::model()->deleteByPk($attachment['id']); } } } $this->status['code'] = '200'; $this->status['exception'] = null; $this->status['message'] = Yii::t('app', 'Email Sent!'); } catch (phpmailerException $e) { // Catch PHPMailer specific exceptions for pretty error printing $this->status['code'] = '500'; $this->status['exception'] = $e; $this->status['message'] = $phpMail->ErrorInfo . " " . $e->getFile() . " L" . $e->getLine(); } catch (Exception $e) { $this->status['code'] = '500'; $this->status['exception'] = $e; $this->status['message'] = $e->getMessage() . " " . $e->getFile() . " L" . $e->getLine(); } return $this->status; }
public function run() { if (Yii::app()->user->isGuest) { Yii::app()->controller->redirect(Yii::app()->controller->createUrl('/site/login')); } $this->attachBehaviors($this->behaviors); // Safety net of handlers - they ensure that errors can be caught and seen easily: $scenario = 'custom'; if (empty($this->model)) { $model = new InlineEmail(); } else { $model = $this->model; } if (isset($_POST['contactFlag'])) { $model->contactFlag = $_POST['contactFlag']; } $makeEvent = isset($_GET['skipEvent']) ? !(bool) $_GET['skipEvent'] : 1; // Check to see if the user is requesting a new template if (isset($_GET['template'])) { $scenario = 'template'; } $model->setScenario($scenario); $attachments = array(); if (isset($_POST['InlineEmail'])) { // This could indicate either a template change or a form submission. $model->attributes = $_POST['InlineEmail']; // Prepare attachments that may have been uploaded on-the-fly (?) $mediaLibraryUsed = false; // is there an attachment from the media library? if (isset($_POST['AttachmentFiles'], $_POST['AttachmentFiles']['id'], $_POST['AttachmentFiles']['types'])) { $ids = $_POST['AttachmentFiles']['id']; $types = $_POST['AttachmentFiles']['types']; $attachments = array(); for ($i = 0; $i < count($ids); $i++) { $type = $types[$i]; switch ($type) { case 'temp': // attachment is a temp file $tempFile = TempFile::model()->findByPk($ids[$i]); $attachments[] = array('filename' => $tempFile->name, 'folder' => $tempFile->folder, 'type' => $type, 'id' => $tempFile->id); break; case 'media': // attachment is from media library $mediaLibraryUsed = true; $media = Media::model()->findByPk($ids[$i]); $attachments[] = array('filename' => $media->fileName, 'folder' => $media->uploadedBy, 'type' => $type, 'id' => $media->id); break; default: throw new CException('Invalid attachment type: ' . $type); } } } $model->attachments = $attachments; // Validate/prepare the body, and send if no problems occur: $sendStatus = array_fill_keys(array('code', 'message'), ''); $failed = false; $message = ''; $postReplace = isset($_GET['postReplace']) ? $_GET['postReplace'] : 0; if (isset($_GET['loadTemplate'])) { // A special override for when it's not possible to include the template in $_POST $model->template = $_GET['loadTemplate']; } if ($model->prepareBody($postReplace)) { if ($scenario != 'template') { // Sending the email, not merely requesting a template change // // First check that the user has permission to use the // specified credentials: if ($model->credId != Credentials::LEGACY_ID) { if (!Yii::app()->user->checkAccess('CredentialsSelect', array('model' => $model->credentials))) { $this->respond(Yii::t('app', 'Did not send email because you do not have ' . 'permission to use the specified credentials.'), 1); } } $sendStatus = $model->send($makeEvent); // $sendStatus = array('code'=>'200','message'=>'sent (testing)'); $failed = $sendStatus['code'] != '200'; $message = $sendStatus['message']; } else { if ($model->modelName == 'Quote' && empty($model->template)) { // Fill in the gap with the default / "semi-legacy" quotes view $model->message = $this->controller->renderPartial('application.modules.quotes.views.quotes.print', array('model' => $model->targetModel, 'email' => true), true); // Add a linebreak at the beginning for user-entered notes in the email: $model->insertInBody('<br />', 1); } } } // Populate response data: $modelHasErrors = $model->hasErrors(); $failed = $failed || $modelHasErrors; $response = array('scenario' => $scenario, 'sendStatus' => $sendStatus, 'attributes' => $model->attributes, 'modelErrors' => $model->errors, 'modelHasErrors' => $modelHasErrors, 'modelErrorHtml' => CHtml::errorSummary($model, Yii::t('app', "Please fix the following errors:"), null, array('style' => 'margin-bottom: 5px;'))); if ($scenario == 'template') { // There's a chance the inline email form is switching gears into // quote mode, in which case we need to include templates and // insertable attributes for setting it all up properly: $response['insertableAttributes'] = $model->insertableAttributes; $templates = array(0 => Yii::t('docs', 'Custom Message')) + Docs::getEmailTemplates($model->modelName == 'Quote' ? 'quote' : 'email', $_POST['associationType']); $response['templateList'] = array(); foreach ($templates as $id => $templateName) { $response['templateList'][] = array('id' => $id, 'name' => $templateName); } } $this->mergeResponse($response); $this->respond($message, $failed); } else { $this->respond(Yii::t('app', 'Inline email model missing from the request to the server.'), true); } }
/** * Returns a frame from the movie as an ffmpeg_frame object. * Returns false if the frame was not found. * @access public * @return mixed boolean | ffmpeg_frame */ public function getFrame($frame_number = null) { // check that we have video. if ($this->hasVideo() === false) { return false; } // check that the frame number is not less than or equal to 0 as the argument is not // zero indexed and cannot get a negative rframe number. if ($frame_number <= 0) { return false; } // update the current frame index if ($frame_number === null) { $this->_frame_index += 1; $frame_number = $this->_frame_index; } else { // zero indexed $frame_number -= 1; $this->_frame_index = $frame_number; } // check the frame required exists in the video if ($frame_number > $this->getFrameCount()) { return false; } // get the timecode of the frame to extract; $timecode = Timecode::parseTimecode($frame_number, '%fn', $this->getFrameRate()); // get the temp directory for the output. $config = Config::getInstance(); $temp = new TempFile($config->temp_directory); $output_path = $temp->file(false, 'png'); // perform the extraction $output = $this->_toolkit->extractFrame($timecode)->save($output_path, null, Media::OVERWRITE_UNIQUE); // then convert the image to GD resource and tidy the temp file. $gd_img = $output->toGdImage(); unlink($output->getOutput()->getMediaPath()); // return the ffmpeg_frame object. require_once dirname(__FILE__) . 'ffmpeg_frame.php'; return new ffmpeg_frame($gd_img, $timecode->getTimecode('%sf.%ms')); }
} else { $pageSize = $cellSize = $dataSize = $rowsAmnt = 0; } $a = new MySQLQuery($c, $req['limited'] ? new QueryResultJSONWriter($pageSize) : NULL, $cellSize, $dataSize, $rowsAmnt); if (is_array($q)) { $aff = 0; for ($i = 0; $i < count($q); $i++) { $r = $a->query($q[$i], $p[$i], $req['flags']); $aff += $r['affectedRows']; } $a = array('affectedRows' => $aff); } else { $a = $a->query($q, $p, $req['flags']); } if ($req['toFile'] && $a['results']) { $f = new TempFile(); $f->write($a['results'][0]['data'][0][0]); $a = array('file' => $f->name, 'alias' => 'cell-' . date('Ymd-His') . '.data'); } respond($a); break; case 'get_query_result': $f = $req['file'] . '-' . $req['result'] . '-' . $req['page']; if (($s = file_get_contents($f)) === FALSE) { respondError("Can't read file: {$f}"); } respond($s); break; case 'kill_query_result': array_walk(glob($req['file'] . '-*'), create_function('&$v, $k', 'unlink($v);')); break;
/** * Perform the email delivery with PHPMailer. * * Any special authentication and security should take place in here. * * @param array $addresses This array must contain "to", "cc" and/or "bcc" * keys, and values must be arrays of recipients. Each recipient is expressed * as a 2-element array with the first element being the name, and the second * the email address. * @throws Exception * @return array */ public function deliverEmail($addresses, $subject, $message, $attachments = array()) { if (YII_DEBUG && self::DEBUG_EMAIL) { // Fake a successful send /**/ AuxLib::debugLog('Faking an email delivery to address(es): ' . var_export($addresses, 1)); return $this->status = $this->getDebugStatus(); } try { $phpMail = $this->mailer; } catch (phpmailerException $e) { // escalate error to force campaigns to halt $escalated = new phpmailerException($e->getMessage(), PHPMailer::STOP_CRITICAL); $this->status['code'] = '500'; $this->status['exception'] = $escalated; $this->status['message'] = $e->getMessage(); return $this->status; } // attempt smpt connect before attempting to send so that we can escalate exception // severity if connection fails. Ideally we would be able to detect exactly the type of // exception that PHPMailer throws but unfortunately the only way at the time of this // writing would be to use its translated exception messages (brittle). if ($this->credentials) { try { $phpMail->smtpConnect(); } catch (phpmailerException $e) { $escalated = new phpmailerException($e->getMessage(), PHPMailer::STOP_CRITICAL); $this->status['code'] = '500'; $this->status['exception'] = $escalated; $this->status['message'] = $phpMail->ErrorInfo . " " . $e->getFile() . " L" . $e->getLine(); return $this->status; } } try { $this->addEmailAddresses($phpMail, $addresses); $phpMail->Subject = $subject; // $phpMail->AltBody = $message; $phpMail->MsgHTML($message); // $phpMail->Body = $message; // add attachments, if any if ($attachments) { foreach ($attachments as $attachment) { $type = $attachment['type']; switch ($type) { case 'temp': // stored as a temp file? $file = 'uploads/media/temp/' . $attachment['folder'] . '/' . $attachment['filename']; if (file_exists($file)) { // check file exists if ($this->validateFileSize(filesize($file))) { $phpMail->AddAttachment($file); } } break; case 'media': // stored in media library $file = 'uploads/media/' . $attachment['folder'] . '/' . $attachment['filename']; if (file_exists($file)) { // check file exists if ($this->validateFileSize(filesize($file))) { $phpMail->AddAttachment($file); } } break; default: throw new CException('Invalid attachment type'); } } } $phpMail->Send(); // delete temp attachment files, if they exist if ($attachments) { foreach ($attachments as $attachment) { $type = $attachment['type']; if ($type === 'temp') { $file = 'uploads/media/temp/' . $attachment['folder'] . '/' . $attachment['filename']; $folder = 'uploads/media/temp/' . $attachment['folder']; if (file_exists($file)) { unlink($file); } // delete temp file if (file_exists($folder)) { rmdir($folder); } // delete temp folder TempFile::model()->deleteByPk($attachment['id']); } } } $this->status['code'] = '200'; $this->status['exception'] = null; $this->status['message'] = Yii::t('app', 'Email Sent!'); } catch (phpmailerException $e) { // Catch PHPMailer specific exceptions for pretty error printing $this->status['code'] = '500'; $this->status['exception'] = $e; $this->status['message'] = $phpMail->ErrorInfo . " " . $e->getFile() . " L" . $e->getLine(); } catch (Exception $e) { $this->status['code'] = '500'; $this->status['exception'] = $e; $this->status['message'] = $e->getMessage() . " " . $e->getFile() . " L" . $e->getLine(); } return $this->status; }