Creates a temporary filename for the lifetime of the script, and
(optionally) registers it to be deleted at request shutdown.
public static getTempFile ( string $prefix = 'Horde', boolean $delete = true, string $dir = '', boolean $secure = false, boolean $session_remove = false ) : string | ||
$prefix | string | Prefix to make the temporary name more recognizable. |
$delete | boolean | Delete the file at the end of the request? |
$dir | string | Directory to create the temporary file in. |
$secure | boolean | If deleting file, should we securely delete the file? |
$session_remove | boolean | Delete this file when session is destroyed? |
Résultat | string | Returns the full path-name to the temporary file or false if a temporary file could not be created. |
/** * Creates a temporary copy of a file. * * @param string $filename The name of the file to be copied. * * @return string The file name of the temporary copy or false * if the file couldn't be copied. */ function tmpFile($filename) { $tmp = Horde::getTempFile('luxor'); if (!@copy($this->toReal($filename), $tmp)) { return false; } return $tmp; }
public function send($number, $data, $time = null) { /* Create a temporary file. */ $filename = sprintf("%s.fax", Horde::getTempFile('hylax')); $fh = fopen($filename, "w"); fwrite($fh, $data); fclose($fh); return $this->createCallFile($filename); }
/** * Prepare the server configuration for the given environment. * * @param string $environment The name of the environment. * * @return NULL */ public function prepareKolabServerConfiguration($environment) { switch ($environment) { case self::ENVIRONMENT_FILE: /** Prepare a Kolab test server */ $config = new stdClass(); $config->driver = 'file'; $config->params = array('file' => Horde::getTempFile('fileTest'), 'basedn' => 'dc=example,dc=org', 'hashtype' => 'plain'); $this->world['injector'][$environment]->setInstance('Horde_Kolab_Server_Config', $config); break; default: return parent::prepareKolabServerConfiguration($environment); } }
/** */ protected function _changePassword($user, $oldpass, $newpass) { // Clean up user name in case evil characters are in it. $user = escapeshellcmd($user); $tmpfile = Horde::getTempFile('smbpasswd'); $this->_connect($user, $tmpfile); $this->_sendCommand($oldpass); $this->_sendCommand($newpass); $this->_sendCommand($newpass); $this->_disconnect(); $res = file($tmpfile); if (strstr($res[count($res) - 1], 'Password changed for user') === false) { throw new Passwd_Exception(strrchr(trim($res[count($res) - 2]), ':')); } }
/** */ protected function _changePassword($user, $oldpass, $newpass) { // Sanity checks. if (!@is_executable($this->_params['program'])) { throw new Passwd_Exception(sprintf(_("%s does not exist or is not executable."), $this->_params['program'])); } // Temporary logfile for error messages. $log = Horde::getTempFile('passwd'); // Open expect script for writing. $prog = 'LANG=C LC_ALL=C ' . $this->_params['program'] . ' -f ' . escapeshellarg($this->_params['script']) . ' -- ' . $this->_params['params'] . ' -log ' . escapeshellarg($log); $exp = @popen($prog, 'w'); @fwrite($exp, $user . "\n"); @fwrite($exp, $oldpass . "\n"); @fwrite($exp, $newpass . "\n"); if (@pclose($exp)) { $errormsg = implode(' ', @file($log)); @unlink($log); if ($errormsg) { throw new Passwd_Exception($errormsg); } } }
/** * Gets the upload and sets up the upload data array. Either * fetches an upload done with this submit or retrieves stored * upload info. * @param Horde_Variables $vars The form state to check this field for * @param Horde_Form_Variable $var The Form field object to check * */ function _getUpload(&$vars, &$var) { global $session; /* Don't bother with this function if already called and set * up vars. */ if (!empty($this->_img)) { return true; } /* Check if file has been uploaded. */ $varname = $var->getVarName(); try { $GLOBALS['browser']->wasFileUploaded($varname . '[new]'); $this->_uploaded = true; /* A file has been uploaded on this submit. Save to temp dir for * preview work. */ $this->_img['img']['type'] = $this->getUploadedFileType($varname . '[new]'); /* Get the other parts of the upload. */ Horde_Array::getArrayParts($varname . '[new]', $base, $keys); /* Get the temporary file name. */ $keys_path = array_merge(array($base, 'tmp_name'), $keys); $this->_img['img']['file'] = Horde_Array::getElement($_FILES, $keys_path); /* Get the actual file name. */ $keys_path = array_merge(array($base, 'name'), $keys); $this->_img['img']['name'] = Horde_Array::getElement($_FILES, $keys_path); /* Get the file size. */ $keys_path = array_merge(array($base, 'size'), $keys); $this->_img['img']['size'] = Horde_Array::getElement($_FILES, $keys_path); /* Get any existing values for the image upload field. */ $upload = $vars->get($var->getVarName()); if (!empty($upload['hash'])) { $upload['img'] = $session->get('horde', 'form/' . $upload['hash']); $session->remove('horde', 'form/' . $upload['hash']); } /* Get the temp file if already one uploaded, otherwise create a * new temporary file. */ if (!empty($upload['img']['file'])) { $tmp_file = Horde::getTempDir() . '/' . $upload['img']['file']; } else { $tmp_file = Horde::getTempFile('Horde', false); } /* Move the browser created temp file to the new temp file. */ move_uploaded_file($this->_img['img']['file'], $tmp_file); $this->_img['img']['file'] = basename($tmp_file); } catch (Horde_Browser_Exception $e) { $this->_uploaded = $e; /* File has not been uploaded. */ $upload = $vars->get($var->getVarName()); /* File is explicitly removed */ if ($vars->get('remove_' . $var->getVarName())) { $this->_img = null; $session->remove('horde', 'form/' . $upload['hash']); return; } if ($this->_uploaded->getCode() == 4 && !empty($upload['hash']) && $session->exists('horde', 'form/' . $upload['hash'])) { $this->_img['img'] = $session->get('horde', 'form/' . $upload['hash']); $session->remove('horde', 'form/' . $upload['hash']); if (isset($this->_img['error'])) { $this->_uploaded = PEAR::raiseError($this->_img['error']); } } } if (isset($this->_img['img'])) { $session->set('horde', 'form/' . $this->getRandomId(), $this->_img['img']); } }
$r->_name = $form2->getName(); $r->beginInactive($form2->getTitle()); $r->renderFormInactive($form2, $vars); $r->end(); echo '<br />'; $form3->preserve($vars); $r->_name = $form3->getName(); $r->beginInactive($form3->getTitle()); $r->renderFormInactive($form3, $vars); $r->end(); echo '<br />'; // Preserve an uploaded file if there was one. $form3->getInfo($vars, $info); if (!empty($info['newattachment']['name'])) { $file_name = $info['newattachment']['name']; $tmp_file_path = Horde::getTempFile('whups'); if (move_uploaded_file($info['newattachment']['tmp_name'], $tmp_file_path)) { $session->set('whups', 'deferred_attachment/' . $file_name, $tmp_file_path); $vars->set('deferred_attachment', $file_name); $form3->preserveVarByPost($vars, 'deferred_attachment'); } } // Render the 4th stage form. if ($formname != 'whups_form_ticket_createstepfour') { $form4->clearValidation(); } $r->_name = $form4->getName(); $r->beginActive($form4->getTitle()); $r->renderFormActive($form4, $vars); $r->submit(); $r->end();
/** * Writes attachment data to a temporary file. * * @return string Temporary file path. * * @throws IMP_Compose_Exception */ public function getTempFile() { if (isset($this->_tmpfile)) { return $this->_tmpfile; } $stream = $this->read(); $tmp = Horde::getTempFile('impatt'); $fd = fopen($tmp, 'w+'); while (!$stream->eof()) { fwrite($fd, $stream->substring(0, 8192)); } fclose($fd); $stream->close(); return $tmp; }
/** * Returns the value of the specified attribute. * * @param string $attribute The attribute to retrieve. * * @return mixed The value of $attribute, an array (for photo type) * or the empty string. */ public function getValue($attribute) { global $attributes, $injector; if (isset($this->attributes[$attribute]) && ($hooks = $injector->getInstance('Horde_Core_Hooks')) && $hooks->hookExists('decode_attribute', 'turba')) { try { return $hooks->callHook('decode_attribute', 'turba', array($attribute, $this->attributes[$attribute], $this)); } catch (Turba_Exception $e) { } } elseif (isset($this->driver->map[$attribute]) && is_array($this->driver->map[$attribute])) { $args = array(); foreach ($this->driver->map[$attribute]['fields'] as $field) { $args[] = $this->getValue($field); } return Turba::formatCompositeField($this->driver->map[$attribute]['format'], $args); } elseif (!isset($this->attributes[$attribute])) { if (isset($attributes[$attribute]) && $attributes[$attribute]['type'] == 'Turba:TurbaTags' && ($uid = $this->getValue('__uid'))) { $this->synchronizeTags($injector->getInstance('Turba_Tagger')->getTags($uid, 'contact')); } else { return null; } } elseif (isset($attributes[$attribute]) && $attributes[$attribute]['type'] == 'image') { return empty($this->attributes[$attribute]) ? null : array('load' => array('data' => $this->attributes[$attribute], 'file' => basename(Horde::getTempFile('horde_form_', false, '', false, true)))); } return $this->attributes[$attribute]; }
/** * Render a MIME Part. * * @param string $mime_id The MIME ID to render. * @param integer $mode One of the RENDER_ constants. * @param array $options Additional options: * - autodetect: (boolean) Attempt to auto-detect MIME type? * - mime_part: (Horde_Mime_Part) The MIME part to render. * - type: (string) Use this MIME type instead of the MIME type * identified in the MIME part. * * @return array See Horde_Mime_Viewer_Base::render(). The following * fields may also be present in addition to the fields * defined in Horde_Mime_Viewer_Base: * - attach: (boolean) Force display of this part as an attachment. * - js: (array) A list of javascript commands to run after the content * is displayed on screen. * - name: (string) Contains the MIME name information. * - wrap: (string) If present, indicates that this part, and all child * parts, will be wrapped in a DIV with the given class name. */ public function renderMIMEPart($mime_id, $mode, array $options = array()) { $this->_buildMessage(); $mime_part = empty($options['mime_part']) ? $this->getMimePart($mime_id) : $options['mime_part']; if (!$mime_part) { return array($mime_id => null); } if (!empty($options['autodetect']) && ($tempfile = Horde::getTempFile()) && ($fp = fopen($tempfile, 'w')) && !is_null($contents = $mime_part->getContents(array('stream' => true)))) { rewind($contents); while (!feof($contents)) { fwrite($fp, fread($contents, 65536)); } fclose($fp); $options['type'] = Horde_Mime_Magic::analyzeFile($tempfile, empty($GLOBALS['conf']['mime']['magic_db']) ? null : $GLOBALS['conf']['mime']['magic_db']); } $type = empty($options['type']) ? null : $options['type']; $viewer = $GLOBALS['injector']->getInstance('IMP_Factory_MimeViewer')->create($mime_part, array('contents' => $this, 'type' => $type)); switch ($mode) { case self::RENDER_INLINE: case self::RENDER_INLINE_AUTO: case self::RENDER_INLINE_DISP_NO: $textmode = 'inline'; $limit = $viewer->getConfigParam('limit_inline_size'); if ($limit && $mime_part->getBytes() > $limit) { $data = ''; $status = new IMP_Mime_Status($mime_part, array(_("This message part cannot be viewed because it is too large."), $this->linkView($mime_part, 'download_attach', _("Click to download the data.")))); $status->icon('alerts/warning.png', _("Warning")); if (method_exists($viewer, 'overLimitText')) { $data = $viewer->overLimitText(); $status->addText(_("The initial portion of this text part is displayed below.")); } return array($mime_id => array('data' => $data, 'name' => '', 'status' => $status, 'type' => 'text/html; charset=' . 'UTF-8')); } break; case self::RENDER_INFO: $textmode = 'info'; break; case self::RENDER_RAW: $textmode = 'raw'; break; case self::RENDER_RAW_FALLBACK: $textmode = $viewer->canRender('raw') ? 'raw' : 'full'; break; case self::RENDER_FULL: default: $textmode = 'full'; break; } $ret = $viewer->render($textmode); if (empty($ret)) { return $mode == self::RENDER_INLINE_AUTO ? $this->renderMIMEPart($mime_id, self::RENDER_INFO, $options) : array(); } if (!empty($ret[$mime_id]) && !isset($ret[$mime_id]['name'])) { $ret[$mime_id]['name'] = $mime_part->getName(true); } /* Don't show empty parts. */ if ($textmode == 'inline' && !is_null($ret[$mime_id]['data']) && !strlen($ret[$mime_id]['data']) && !isset($ret[$mime_id]['status'])) { $ret[$mime_id] = null; } return $ret; }
$r->_name = $form2->getName(); $r->beginInactive($form2->getTitle()); $r->renderFormInactive($form2, $vars); $r->end(); echo '<br />'; $form3->preserve($vars); $r->_name = $form3->getName(); $r->beginInactive($form3->getTitle()); $r->renderFormInactive($form3, $vars); $r->end(); echo '<br />'; // Preserve an uploaded file if there was one. $form3->getInfo($vars, $info); if (!empty($info['newattachment']['name'])) { $file_name = $info['newattachment']['name']; $tmp_file_path = Horde::getTempFile('whups', false); if (move_uploaded_file($info['newattachment']['tmp_name'], $tmp_file_path)) { $session->set('whups', 'deferred_attachment/' . $file_name, $tmp_file_path); $vars->set('deferred_attachment', $file_name); $form4->preserveVarByPost($vars, 'deferred_attachment'); } } // Render the 4th stage form. if ($formname != 'whups_form_ticket_createstepfour') { $form4->clearValidation(); } $r->_name = $form4->getName(); $r->beginActive($form4->getTitle()); $r->renderFormActive($form4, $vars); $r->submit(); $r->end();
/** * Returns the value of the specified attribute. * * @param string $attribute The attribute to retrieve. * * @return mixed The value of $attribute, an array (for photo type) * or the empty string. */ public function getValue($attribute) { global $attributes, $injector, $conf; if (isset($this->attributes[$attribute]) && ($hooks = $injector->getInstance('Horde_Core_Hooks')) && $hooks->hookExists('decode_attribute', 'turba')) { try { return $hooks->callHook('decode_attribute', 'turba', array($attribute, $this->attributes[$attribute], $this)); } catch (Turba_Exception $e) { } } elseif (isset($this->driver->map[$attribute]) && is_array($this->driver->map[$attribute])) { $args = array(); foreach ($this->driver->map[$attribute]['fields'] as $field) { $args[] = $this->getValue($field); } return Turba::formatCompositeField($this->driver->map[$attribute]['format'], $args); } elseif (isset($attributes[$attribute]) && $attributes[$attribute]['type'] == 'image') { // If there is no [$attribute], but we have a $attribute . '_orig', // then populate the $attribute data using default resizing config. if (empty($this->attributes[$attribute])) { if (!empty($this->attributes[$attribute . '_orig']) && (!empty($conf['photos']['height']) || !empty($conf['photos']['width']))) { // Do resizing $img = $injector->getInstance('Horde_Core_Factory_Image')->create(array('data' => $this->attributes[$attribute . '_orig'], 'type' => 'jpeg')); $img->resize($conf['photos']['width'], $conf['photos']['height']); $this->attributes[$attribute] = $img->raw(true); $this->store(); } } return empty($this->attributes[$attribute]) ? null : array('load' => array('data' => $this->attributes[$attribute], 'file' => basename(Horde::getTempFile('horde_form_', false, '', false, true)))); } elseif (!isset($this->attributes[$attribute])) { if (isset($attributes[$attribute]) && $attributes[$attribute]['type'] == 'Turba:TurbaTags' && ($uid = $this->getValue('__uid'))) { $this->synchronizeTags($injector->getInstance('Turba_Tagger')->getTags($uid, 'contact')); } else { return null; } } return $this->attributes[$attribute]; }
/** * Adds an attachment from Horde_Mime_Part data. * * @param Horde_Mime_Part $part The object that contains the attachment * data. * * @return IMP_Compose_Attachment Attachment object. * @throws IMP_Compose_Exception */ public function addAttachmentFromPart($part) { /* Extract the data from the Horde_Mime_Part. */ $atc_file = Horde::getTempFile('impatt'); $stream = $part->getContents(array('stream' => true)); rewind($stream); if (file_put_contents($atc_file, $stream) === false) { throw new IMP_Compose_Exception(sprintf(_("Could not attach %s to the message."), $part->getName())); } return $this->_addAttachment($atc_file, ftell($stream), $part->getName(true), $part->getType()); }
/** * Parse a MIME message and create a new ticket. * * @param string $text This is the full text of the MIME message. * @param array $info An array of information for the new ticket. * This should include: * - 'queue' => queue id * - 'type' => type id * - 'state' => state id * - 'priority' => priority id * - 'ticket' => ticket id (prevents creation * of new tickets) * @param string $auth_user This will be the Horde user that creates the * ticket. If null, we will try to deduce from * the message's From: header. We do NOT default * to $GLOBALS['registry']->getAuth(). * * @return Whups_Ticket Ticket. */ public static function processMail($text, array $info, $auth_user = null) { global $conf; $message = Horde_Mime_Part::parseMessage($text); if (preg_match("/^(.*?)\r?\n\r?\n/s", $text, $matches)) { $hdrText = $matches[1]; } else { $hdrText = $text; } $headers = Horde_Mime_Headers::parseHeaders($hdrText); // If this message was generated by Whups, don't process it. if ($headers->getValue('X-Whups-Generated')) { return true; } // Try to avoid bounces, auto-replies, and mailing list responses. $from = $headers->getValue('from'); if (strpos($headers->getValue('Content-Type'), 'multipart/report') !== false || stripos($from, 'mailer-daemon@') !== false || stripos($from, 'postmaster@') !== false || !is_null($headers->getValue('X-Failed-Recipients')) || !is_null($headers->getValue('X-Autoreply-Domain')) || $headers->getValue('Auto-Submitted') == 'auto-replied' || $headers->getValue('Precedence') == 'auto_reply' || $headers->getValue('X-Precedence') == 'auto_reply' || $headers->getValue('X-Auto-Response-Suppress') == 'All' || $headers->getValue('X-List-Administrivia') == 'Yes') { return true; } // Use the message subject as the ticket summary. $info['summary'] = trim($headers->getValue('subject')); if (empty($info['summary'])) { $info['summary'] = _("[No Subject]"); } // Format the message into a comment. $comment = _("Received message:") . "\n\n"; if (!empty($GLOBALS['conf']['mail']['include_headers'])) { foreach ($headers->toArray(array('nowrap' => true)) as $name => $vals) { if (!in_array(strtolower($name), array('subject', 'from', 'to', 'cc', 'date'))) { if (is_array($vals)) { foreach ($vals as $val) { $comment .= $name . ': ' . $val . "\n"; } } else { $comment .= $name . ': ' . $vals . "\n"; } } } $comment .= "\n"; } // Look for the body part. $body_id = $message->findBody(); if ($body_id) { $part = $message->getPart($body_id); $content = Horde_String::convertCharset($part->getContents(), $part->getCharset(), 'UTF-8'); switch ($part->getType()) { case 'text/plain': $comment .= $content; break; case 'text/html': $comment .= Horde_Text_Filter::filter($content, array('Html2text'), array(array('width' => 0))); break; default: $comment .= _("[ Could not render body of message. ]"); break; } } else { $comment .= _("[ Could not render body of message. ]"); } $info['comment'] = $comment . "\n"; // Try to determine the Horde user for creating the ticket. if (empty($auth_user)) { $tmp = new Horde_Mail_Rfc822_Address($from); $auth_user = self::_findAuthUser($tmp->bare_address); } $author = $auth_user; if (empty($auth_user) && !empty($info['default_auth'])) { $auth_user = $info['default_auth']; if (!empty($from)) { $info['user_email'] = $from; } } if (empty($auth_user) && !empty($conf['mail']['username'])) { $auth_user = $conf['mail']['username']; if (!empty($from)) { $info['user_email'] = $from; } } // Authenticate as the correct Horde user. if (!empty($auth_user) && $auth_user != $GLOBALS['registry']->getAuth()) { $GLOBALS['registry']->setAuth($auth_user, array()); } // Attach message. $attachments = array(); if (!empty($GLOBALS['conf']['mail']['attach_message'])) { $tmp_name = Horde::getTempFile('whups'); $fp = @fopen($tmp_name, 'wb'); if (!$fp) { throw new Whups_Exception(sprintf('Cannot open file %s for writing.', $tmp_name)); } fwrite($fp, $text); fclose($fp); $attachments[] = array('name' => _("Original Message") . '.eml', 'tmp_name' => $tmp_name); } // Extract attachments. $dl_list = array_slice(array_keys($message->contentTypeMap()), 1); foreach ($dl_list as $key) { $part = $message->getPart($key); if ($key == $body_id && $part->getType() == 'text/plain' || $part->getType() == 'multipart/alternative' || $part->getType() == 'multipart/mixed') { continue; } $tmp_name = Horde::getTempFile('whups'); $fp = @fopen($tmp_name, 'wb'); if (!$fp) { throw new Whups_Exception(sprintf('Cannot open file %s for writing.', $tmp_name)); } fwrite($fp, $part->getContents()); fclose($fp); $part_name = $part->getName(true); if (!$part_name) { $ptype = $part->getPrimaryType(); switch ($ptype) { case 'multipart': case 'application': $part_name = sprintf(_("%s part"), ucfirst($part->getSubType())); break; default: $part_name = sprintf(_("%s part"), ucfirst($ptype)); break; } if ($ext = Horde_Mime_Magic::mimeToExt($part->getType())) { $part_name .= '.' . $ext; } } $attachments[] = array('name' => $part_name, 'tmp_name' => $tmp_name); } // See if we can match this message to an existing ticket. if ($ticket = self::_findTicket($info)) { $ticket->change('comment', $info['comment']); $ticket->change('comment-email', $from); if ($attachments) { $ticket->change('attachments', $attachments); } $ticket->commit($author); } elseif (!empty($info['ticket'])) { // Didn't match an existing ticket though a ticket number had been // specified. throw new Whups_Exception(sprintf(_("Could not find ticket \"%s\"."), $info['ticket'])); } else { if (!empty($info['guess-queue'])) { // Try to guess the queue name for the new ticket from the // message subject. $queues = $GLOBALS['whups_driver']->getQueues(); foreach ($queues as $queueId => $queueName) { if (preg_match('/\\b' . preg_quote($queueName, '/') . '\\b/i', $info['summary'])) { $info['queue'] = $queueId; break; } } } $info['attachments'] = $attachments; // Create a new ticket. $ticket = Whups_Ticket::newTicket($info, $author); } }
/** * Constructor - Based on the information passed, loads an image, * determines the size and type, etc., and stores the information in * the various public properties. Any optional parameters not passed * in are calculated to the best of our ability. * * @param string $image Either raw image data or a filename * @param string $type Image MIME type (e.g. image/jpeg) * @param integer $height Height of the image in pixels * @param integer $width Width of the image in pixels */ function Klutz_Image($image, $type = null, $height = null, $width = null) { $argc = 1; if (!is_null($height)) { $argc++; $this->height = $height; } if (!is_null($width)) { $argc++; $this->width = $width; } if (!is_null($type)) { $argc++; $this->type = $type; } $image_info = @getimagesize($image); // if $image_info is false, then $image doesn't point to a file name if ($image_info === false) { $this->data = $image; // If we need to use getimagesize and we were passed data // write it to a tempfile so getimagesize will work. if ($argc < 4) { $tmpfile = Horde::getTempFile('klutz'); $fp = fopen($tmpfile, 'wb+'); fwrite($fp, $image); fclose($fp); $image_info = @getimagesize($tmpfile); // if $image_info is false, it's an invalid image... if ($image_info === false) { return null; } } } else { $this->file = $image; $this->lastmodified = filemtime($this->file); $this->data = file_get_contents($image); } if (is_null($this->height)) { $this->height = $image_info[KLUTZ_FLD_HEIGHT]; } if (is_null($this->width)) { $this->width = $image_info[KLUTZ_FLD_WIDTH]; } if (is_null($this->type)) { global $klutz; $this->type = $klutz->image_types[$image_info[KLUTZ_FLD_TYPE]]; } $this->size = ''; if (!empty($this->height)) { $this->size = ' height="' . $this->height . '"'; } if (!empty($this->width)) { $this->size .= ' width="' . $this->width . '"'; } }