public function testExecuteNotReadable() { // If running as root you can always write, so this test should be // skipped when running as root. if (!ezcBaseFeatures::hasFunction("posix_getuid") || posix_getuid() == 0) { return; } copy($this->templateCompiledPath . "full-14862b79ceaf01443626bd5d564c53e2.php", $this->templateStorePath . "full-14862b79ceaf01443626bd5d564c53e2.php"); // This only works on Linux/Unix, what to do here on other platforms? $old = umask(0); chmod($this->templateStorePath . "full-14862b79ceaf01443626bd5d564c53e2.php", 0222); umask($old); $conf = new ezcTemplateCompiledCode('14862b79ceaf01443626bd5d564c53e2', $this->templateStorePath . 'full-14862b79ceaf01443626bd5d564c53e2.php'); self::assertTrue(file_exists($conf->path), "Compiled file <" . $conf->path . "> should exist."); self::assertSame(false, $conf->isValid(), "isValid() should return false."); }
/** * Checks if the email address $address is valid based on its MX records. * * Steps: * - the MX records are fetched for the domain part of $address, along with * their weights * - the MX records are sorted based on the weights * - for each MX record a connection is open * - a test mail (RCPT TO) is tried to be sent to $address * - if one test mail succeeds, then the address is valid, else invalid * * Set these values before calling this function, to ensure the MX record * checks work properly: * <code> * ezcMailTools::$mxValidateServer = 'your.mail.server'; // default 'smtp.ez.no' * ezcMailTools::$mxValidateAddress = '*****@*****.**'; // default '*****@*****.**' * </code> * * MX record checking does not work on Windows due to the lack of getmxrr() * and checkdnsrr() PHP functions. The ezcBaseFunctionalityNotSupportedException * is thrown in this case. * * @throws ezcBaseFunctionalityNotSupportedException * if getmxrr() or checkdnsrr() functions are missing (e.g. on Windows) * @param string $address * @return bool */ protected static function validateEmailAddressMx($address) { if (!ezcBaseFeatures::hasFunction('getmxrr') || !ezcBaseFeatures::hasFunction('checkdnsrr')) { throw new ezcBaseFunctionalityNotSupportedException('Checking DNS records', 'getmxrr() or checkdnsrr() missing'); } $timeoutOpen = 3; // for fsockopen() $timeoutConnection = 5; // for stream_set_timeout() list($local, $domain) = explode('@', $address); if (!empty($domain)) { if (getmxrr($domain, $hosts, $weights)) { for ($i = 0; $i < count($hosts); $i++) { $mx[$hosts[$i]] = $weights[$i]; } asort($mx); $mx = array_keys($mx); } elseif (checkdnsrr($domain, 'A')) { $mx[0] = gethostbyname($domain); } else { $mx = array(); } if (($numberOfMx = count($mx)) > 0) { $smtp = array("HELO " . self::$mxValidateServer, "MAIL FROM: <" . self::$mxValidateAddress . ">", "RCPT TO: <{$address}>", "QUIT"); for ($i = 0; $i < $numberOfMx; $i++) { if ($socket = @fsockopen($mx[$i], 25, $errno = 0, $errstr = 0, $timeoutOpen)) { $response = fgets($socket); stream_set_timeout($socket, $timeoutConnection); $meta = stream_get_meta_data($socket); if (!$meta['timed_out'] && !preg_match('/^2\\d\\d[ -]/', $response)) { return false; } foreach ($smtp as $command) { fputs($socket, "{$command}\r\n"); $response = fgets($socket, 4096); if (!$meta['timed_out'] && preg_match('/^5\\d\\d[ -]/', $response)) { return false; } } fclose($socket); return true; } elseif ($i === $numberOfMx - 1) { // none of the mail servers could be contacted return false; } } } else { // no mail servers found return false; } } }
/** * Set an option value * * @param string $propertyName * @param mixed $propertyValue * @throws ezcBasePropertyNotFoundException * If a property is not defined in this class * @return void */ public function __set($propertyName, $propertyValue) { switch ($propertyName) { case 'imageFormat': if (imagetypes() & $propertyValue) { $this->properties['imageFormat'] = (int) $propertyValue; } else { throw new ezcBaseValueException($propertyName, $propertyValue, 'Unsupported image type.'); } break; case 'jpegQuality': if (!is_numeric($propertyValue) || $propertyValue < 0 || $propertyValue > 100) { throw new ezcBaseValueException($propertyName, $propertyValue, '0 <= int <= 100'); } $this->properties['jpegQuality'] = (int) $propertyValue; break; case 'detail': if (!is_numeric($propertyValue) || $propertyValue < 1) { throw new ezcBaseValueException($propertyName, $propertyValue, 'int >= 1'); } $this->properties['detail'] = (int) $propertyValue; break; case 'supersampling': if (!is_numeric($propertyValue) || $propertyValue < 1) { throw new ezcBaseValueException($propertyName, $propertyValue, 'int >= 1'); } $this->properties['supersampling'] = (int) $propertyValue; break; case 'background': if ($propertyValue === false || is_file($propertyValue) && is_readable($propertyValue)) { $this->properties['background'] = realpath($propertyValue); } else { throw new ezcBaseValueException($propertyName, $propertyValue, 'readable file'); } break; case 'resampleFunction': if (ezcBaseFeatures::hasFunction($propertyValue)) { $this->properties['resampleFunction'] = $propertyValue; } else { throw new ezcBaseValueException($propertyName, $propertyValue, 'function'); } break; case 'forceNativeTTF': if (!is_bool($propertyValue)) { throw new ezcBaseValueException($propertyName, $propertyValue, 'bool'); } $this->properties['forceNativeTTF'] = (bool) $propertyValue; break; case 'imageMapResolution': if (!is_numeric($propertyValue) || $propertyValue < 1) { throw new ezcBaseValueException($propertyName, $propertyValue, 'int >= 1'); } $this->properties['imageMapResolution'] = (int) $propertyValue; break; default: parent::__set($propertyName, $propertyValue); break; } }
public function testRenderLabeledPieSegmentWithGleamAndShadowGD() { if (!ezcBaseFeatures::hasExtensionSupport('gd') && (ezcBaseFeatures::hasFunction('imagefttext') || ezcBaseFeatures::hasFunction('imagettftext'))) { $this->markTestSkipped('This test needs ext/gd with native ttf support or FreeType 2 support.'); } $filename = $this->tempDir . __FUNCTION__ . '.png'; $chart = new ezcGraphPieChart(); $chart->data['sample'] = new ezcGraphArrayDataSet(array('Mozilla' => 4375, 'IE' => 345, 'Opera' => 1204, 'wget' => 231, 'Safari' => 987)); $chart->options->font->path = dirname(__FILE__) . '/data/font.ttf'; $chart->data['sample']->highlight['Safari'] = true; $chart->data['sample']->color['Safari'] = '#000000'; $chart->data['sample']->highlight['IE'] = true; $chart->data['sample']->symbol['IE'] = ezcGraph::CIRCLE; $chart->data['sample']->symbol['Opera'] = ezcGraph::BULLET; $chart->data['sample']->symbol['wget'] = ezcGraph::DIAMOND; $chart->renderer = new ezcGraphRenderer3d(); $chart->renderer->options->pieChartShadowSize = 10; $chart->renderer->options->pieChartGleam = 0.5; $chart->renderer->options->dataBorder = false; $chart->renderer->options->pieChartHeight = 16; $chart->renderer->options->legendSymbolGleam = 0.5; $chart->renderer->options->pieChartOffset = 180; $chart->driver = new ezcGraphGdDriver(); $chart->render(500, 200, $filename); $this->assertImageSimilar($filename, $this->basePath . 'compare/' . __CLASS__ . '_' . __FUNCTION__ . '.png', 'Image does not look as expected.', 2000); }
/** * Serializes this header and appends it to the given ezcArchiveBlockFile $archiveFile. * * @param ezcArchiveBlockFile $archiveFile * @return void */ public function writeEncodedHeader(ezcArchiveBlockFile $archiveFile) { // Offset | Field size | Description // ---------------------------------- // 0 | 100 | Name of file // 100 | 8 | File mode // 108 | 8 | Owner user ID // 116 | 8 | Owner group ID // 124 | 12 | Length of file in bytes // 136 | 12 | Modify time of file // 148 | 8 | Checksum for header // 156 | 1 | Type flag. // 157 | 100 | Name of linked file // 257 | 6 | USTAR indicator. // 263 | 2 | USTAR version. // 265 | 32 | Owner user name. // 297 | 32 | Owner group name. // 329 | 8 | Major device number. // 337 | 8 | Minor device number. // 345 | 155 | Filename prefix. // 500 | 12 | NUL. if (ezcBaseFeatures::hasFunction('posix_getpwuid')) { $posixName = posix_getpwuid($this->userId); $posixGroup = posix_getgrgid($this->groupId); } else { $posixName['name'] = 'nobody'; $posixGroup['name'] = 'nogroup'; } $enc = pack("a100a8a8a8a12a12a8a1a100a6a2a32a32a8a8a155a12", $this->fileName, str_pad($this->fileMode, 7, "0", STR_PAD_LEFT), str_pad(decoct($this->userId), 7, "0", STR_PAD_LEFT), str_pad(decoct($this->groupId), 7, "0", STR_PAD_LEFT), str_pad(decoct($this->fileSize), 11, "0", STR_PAD_LEFT), str_pad(decoct($this->modificationTime), 11, "0", STR_PAD_LEFT), " ", $this->type, $this->linkName, "ustar", "00", $posixName["name"], $posixGroup["name"], sprintf("%07s", decoct($this->deviceMajorNumber)), sprintf("%07s", decoct($this->deviceMinorNumber)), $this->filePrefix, ""); $enc = $this->setChecksum($enc); $archiveFile->append($enc); }
/** * Checks wether the GD handler is available on the system. * * Returns if PHP's {@link getimagesize()} function is available. * * @return bool True is the handler is available. */ public function isAvailable() { return ezcBaseFeatures::hasFunction( 'getimagesize' ); }
/** * Render text depending of font type and available font extensions * * @param resource $image Image resource * @param string $text Text * @param int $type Font type * @param string $path Font path * @param ezcGraphColor $color Font color * @param ezcGraphCoordinate $position Position * @param float $size Textsize * @param ezcGraphRotation $rotation * * @return void */ protected function renderText($image, $text, $type, $path, ezcGraphColor $color, ezcGraphCoordinate $position, $size, ezcGraphRotation $rotation = null) { if ($rotation !== null) { // Rotation is relative to top left point of text and not relative // to the bounding coordinate system $rotation = new ezcGraphRotation($rotation->getRotation(), new ezcGraphCoordinate($rotation->getCenter()->x - $position->x, $rotation->getCenter()->y - $position->y)); } switch ($type) { case ezcGraph::PS_FONT: imagePsText($image, $text, $this->psFontRessources[$path], $size, $this->allocate($color), 1, $position->x + ($rotation === null ? 0 : $rotation->get(0, 2)), $position->y + ($rotation === null ? 0 : $rotation->get(1, 2)), 0, 0, $rotation === null ? 0 : -$rotation->getRotation(), 4); break; case ezcGraph::TTF_FONT: switch (true) { case ezcBaseFeatures::hasFunction('imagefttext') && !$this->options->forceNativeTTF: imageFtText($image, $size, $rotation === null ? 0 : -$rotation->getRotation(), $position->x + ($rotation === null ? 0 : $rotation->get(0, 2)), $position->y + ($rotation === null ? 0 : $rotation->get(1, 2)), $this->allocate($color), $path, $text); break; case ezcBaseFeatures::hasFunction('imagettftext'): imageTtfText($image, $size, $rotation === null ? 0 : -$rotation->getRotation(), $position->x + ($rotation === null ? 0 : $rotation->get(0, 2)), $position->y + ($rotation === null ? 0 : $rotation->get(1, 2)), $this->allocate($color), $path, $text); break; } break; } }
/** * Save an image file. * Saves a given open file. Can optionally save to a new file name. * * @see ezcImageHandler::load() * * @param string $image File reference created through load(). * @param string $newFile Filename to save the image to. * @param string $mime New MIME type, if differs from initial one. * @param ezcImageSaveOptions $options Save options. * @return void * * @throws ezcImageFileNotProcessableException * If the given file could not be saved with the given MIME type. * @throws ezcBaseFilePermissionException * If the desired file exists and is not writeable. * @throws ezcImageMimeTypeUnsupportedException * If the desired MIME type is not recognized * @throws ezcImageFileNameInvalidException * If an invalid character (", ', $) is found in the file name. */ public function save($image, $newFile = null, $mime = null, ezcImageSaveOptions $options = null) { $options = $options === null ? new ezcImageSaveOptions() : $options; if ($newFile !== null) { $this->checkFileName($newFile); } // Check is transparency must be converted if ($this->needsTransparencyConversion($this->getReferenceData($image, 'mime'), $mime) && $options->transparencyReplacementColor !== null) { $this->replaceTransparency($image, $options->transparencyReplacementColor); } $this->saveCommon($image, isset($newFile) ? $newFile : null, isset($mime) ? $mime : null); $saveFunction = $this->getSaveFunction($this->getReferenceData($image, 'mime')); $saveParams = array($this->getReferenceData($image, 'resource'), $this->getReferenceData($image, 'file')); switch ($saveFunction) { case "imagejpeg": if ($options->quality !== null) { $saveParams[] = $options->quality; } break; case "imagepng": if ($options->compression !== null) { $saveParams[] = $options->compression; } break; } if (!ezcBaseFeatures::hasFunction($saveFunction) || call_user_func_array($saveFunction, $saveParams) === false) { throw new ezcImageFileNotProcessableException($file, "Unable to save file '{$file}' of type '{$mime}'."); } }
public function testHasFunction2() { $this->assertEquals(false, ezcBaseFeatures::hasFunction('non_existent_function_in_php')); }
public function testDrawPSText() { if (!ezcBaseFeatures::hasFunction('imagepstext')) { $this->markTestSkipped('This test needs Type 1 font support within your gd extension.'); } $filename = $this->tempDir . __FUNCTION__ . '.png'; $this->driver->options->font->path = $this->basePath . 'ps_font.pfb'; $this->driver->drawTextBox('Fontfiletest', new ezcGraphCoordinate(10, 10), 150, 70, ezcGraph::LEFT); $this->driver->render($filename); $this->assertTrue(file_exists($filename), 'No image was generated.'); $this->assertImageSimilar($filename, $this->basePath . 'compare/' . __CLASS__ . '_' . __FUNCTION__ . '.png', 'Image does not look as expected.', 2000); }
public function testValidateEmailAddressMXThrowException() { if (ezcBaseFeatures::hasFunction('getmxrr') && ezcBaseFeatures::hasFunction('checkdnsrr')) { $this->markTestSkipped('This test works only if getmxrr() or checkdnsrr() support is missing'); } try { ezcMailTools::validateEmailAddress('*****@*****.**', true); $this->fail('Expected exception was not thrown.'); } catch (ezcBaseFunctionalityNotSupportedException $e) { $this->assertEquals('Checking DNS records is not supported. Reason: getmxrr() or checkdnsrr() missing.', $e->getMessage()); } }
/** * Extract the current entry to which the iterator points. * * Extract the current entry to which the iterator points, and return true if the current entry is extracted. * If the iterator doesn't point to a valid entry, this method returns false. * * True if the file is extracted correctly, otherwise false. * * @param string $target * The full path to which the target should be extracted. * @param bool $keepExisting * True if the file shouldn't be overwritten if they already exist. * For the opposite behaviour, false should be given. * * @throws ezcArchiveValueException if the archive contains invalid values. * @throws ezcBaseFileNotFoundException if the link cannot be found. * * @return bool */ public function extractCurrent($target, $keepExisting = false) { if ($this->file === null) { throw new ezcArchiveException("The archive is closed"); } if (!$this->valid()) { return false; } $isWindows = substr(php_uname('s'), 0, 7) == 'Windows' ? true : false; $entry = $this->current(); $type = $entry->getType(); $fileName = $target . DIRECTORY_SEPARATOR . $entry->getPath(); if ($type == ezcArchiveEntry::IS_LINK) { $linkName = $target . DIRECTORY_SEPARATOR . $entry->getLink(); if (!file_exists($linkName)) { throw new ezcBaseFileNotFoundException($linkName, "link", "Hard link could not be created."); } } $this->createDefaultDirectory($fileName); if (!$keepExisting || !is_link($fileName) && !file_exists($fileName)) { if ((file_exists($fileName) || is_link($fileName)) && !is_dir($fileName)) { unlink($fileName); } if (!file_exists($fileName)) { switch ($type) { case ezcArchiveEntry::IS_CHARACTER_DEVICE: if (ezcBaseFeatures::hasFunction('posix_mknod')) { posix_mknod($fileName, POSIX_S_IFCHR, $entry->getMajor(), $entry->getMinor()); } else { throw new ezcArchiveValueException($type); } break; case ezcArchiveEntry::IS_BLOCK_DEVICE: if (ezcBaseFeatures::hasFunction('posix_mknod')) { posix_mknod($fileName, POSIX_S_IFBLK, $entry->getMajor(), $entry->getMinor()); } else { throw new ezcArchiveValueException($type); } break; case ezcArchiveEntry::IS_FIFO: if (ezcBaseFeatures::hasFunction('posix_mknod')) { posix_mknod($fileName, POSIX_S_IFIFO); } else { throw new ezcArchiveValueException($type); } break; case ezcArchiveEntry::IS_SYMBOLIC_LINK: if ($isWindows) { // FIXME.. need to be sure that target file // already extracted before copying it to link destination. $sourcePath = dirname($fileName) . '/' . $entry->getLink(); $fileName = str_replace('/', '\\', $fileName); copy($sourcePath, $fileName); } else { symlink($entry->getLink(), $fileName); } break; case ezcArchiveEntry::IS_LINK: if ($isWindows) { copy($target . DIRECTORY_SEPARATOR . $entry->getLink(), $fileName); } else { link($target . DIRECTORY_SEPARATOR . $entry->getLink(), $fileName); } break; case ezcArchiveEntry::IS_DIRECTORY: $permissions = $entry->getPermissions(); if ($permissions === null || $permissions === false) { $permissions = '0777'; } mkdir($fileName, octdec($permissions), true); break; case ezcArchiveEntry::IS_FILE: $this->writeCurrentDataToFile($fileName); break; default: throw new ezcArchiveValueException($type); } if ($type == ezcArchiveEntry::IS_SYMBOLIC_LINK && ezcBaseFeatures::hasFunction('posix_geteuid') && posix_geteuid() == 0) { $user = $entry->getUserId(); $group = $entry->getGroupId(); @lchown($fileName, $user); @lchgrp($fileName, $group); } // Change the username and group if the filename exists and if // the intention is to keep it as a file. A zip archive // stores the symlinks in a file; thus don't change these. if (file_exists($fileName) && ($type == ezcArchiveEntry::IS_FILE || $type == ezcArchiveEntry::IS_DIRECTORY)) { $group = $entry->getGroupId(); $user = $entry->getUserId(); $time = $entry->getModificationTime(); $perms = octdec($entry->getPermissions()); if ($this->options && $this->options->extractCallback) { $this->options->extractCallback->{$type == ezcArchiveEntry::IS_DIRECTORY ? 'createDirectoryCallback' : 'createFileCallback'}($fileName, $perms, $user, $group); } if (ezcBaseFeatures::hasFunction('posix_geteuid') && posix_geteuid() === 0) { @chgrp($fileName, $group); @chown($fileName, $user); } if ($perms != false) { chmod($fileName, $perms); } touch($fileName, $time); } } return true; } return false; }
public function testSetDriver() { if (!ezcBaseFeatures::hasExtensionSupport('gd') && (ezcBaseFeatures::hasFunction('imagefttext') || ezcBaseFeatures::hasFunction('imagettftext'))) { $this->markTestSkipped('This test needs ext/gd with native ttf support or FreeType 2 support.'); } $pieChart = new ezcGraphPieChart(); $driver = $pieChart->driver = new ezcGraphGdDriver(); $this->assertSame($driver, $pieChart->driver); }
public function testAppendToCurrentFifo() { if (!$this->canWrite) { return; } if (!ezcBaseFeatures::hasFunction('posix_mknod')) { return; } $dir = $this->getTempDir(); posix_mknod("{$dir}/myfifo", POSIX_S_IFIFO); $fifo = "{$dir}/my_fifo.tar"; $bf = new ezcArchiveBlockFile($fifo, true); $archive = ezcArchive::getTarInstance($bf, $this->tarMimeFormat); $archive->appendToCurrent("{$dir}/myfifo", "{$dir}"); $archive->close(); // Do the same with gnu tar. exec("tar -cf {$dir}/gnutar.tar --format=" . $this->tarFormat . " -C {$dir}/ myfifo"); $this->assertEquals(file_get_contents("{$dir}/gnutar.tar"), file_get_contents($fifo)); unlink("{$dir}/myfifo"); }
/** * Test saving code to template file */ public function testSaveNonWriteable() { // If running as root you can always write, so this test should be // skipped when running as root. if (!ezcBaseFeatures::hasFunction("posix_getuid") || posix_getuid() == 0) { return; } copy($this->templatePath . "zhadum.ezt", $this->templateStorePath . "zhadum.ezt"); // This only works on Linux/Unix, what to do here on other platforms? $old = umask(0); chmod($this->templateStorePath . "zhadum.ezt", 0444); umask($old); $src = new ezcTemplateSourceCode($this->templateStorePath . "zhadum.ezt", "planet:zhadum.ezt", "I would not go there if I were you.\nJust a friendly advice.\n"); self::assertTrue(file_exists($this->templateStorePath . "zhadum.ezt"), 'Stored template file <' . $this->templateStorePath . 'zhadum.ezt> does not exist, cannot run save test.'); self::assertTrue(!is_writeable($this->templateStorePath . "zhadum.ezt"), 'Stored template file <' . $this->templateStorePath . 'zhadum.ezt> should not be writable, cannot run save test.'); try { $src->save(); self::fail("No exception thrown for non-writeable file"); } catch (ezcTemplateFileNotWriteableException $e) { } self::assertSame($this->templateStorePath . "zhadum.ezt", $src->stream, 'Property <stream> does not return correct value.'); self::assertSame("planet:zhadum.ezt", $src->resource, 'Property <resource> does not return correct value.'); self::assertSame("I would not go there if I were you.\nJust a friendly advice.\n", $src->code, 'Property <code> does not return correct value.'); self::assertSame("A planet far far away.\n{\$planet.name}\n", file_get_contents($src->stream), 'Original file does no longer contain the correct value.'); self::assertSame(true, file_exists($this->templateStorePath . "zhadum.ezt"), 'Stored template file <' . $this->templateStorePath . 'zhadum.ezt> does not exist after save()'); self::assertSame("A planet far far away.\n{\$planet.name}\n", file_get_contents($this->templateStorePath . "zhadum.ezt"), 'File <' . $this->templateStorePath . 'zhadum.ezt> does not contain the original source code, file was probably written to (which should not happen).'); // self::assertSame( null, $src->context, 'Property <context> does not return correct value.' ); }
/** * testConstructorErrorLocationNotWriteable * * @access public */ public function testConstructorErrorLocationNotWriteable() { // If running as root you can always write, so this test should be skipped when running as root. if (!ezcBaseFeatures::hasFunction("posix_getuid") || posix_getuid() == 0) { return; } // Produce "Location not writeable" exception if (($oldMode = fileperms($this->getTempDir())) === false) { throw new Exception('Could not determine old file permissions for location <' . $this->getTempDir() . '>.'); } if (chmod($this->getTempDir(), 00) === false) { throw new Exception('Could not change permissions for location <' . $this->getTempDir() . '> to 0000.'); } $exceptionThrown = false; try { $cache = new $this->storageClass($this->getTempDir()); } catch (ezcBaseFilePermissionException $e) { $exceptionThrown = true; } if (chmod($this->getTempDir(), $oldMode) === false) { throw new Exception('Could not change permissions for location <' . $this->getTempDir() . '> to ' . $oldMode . '.'); } if ($exceptionThrown === false) { $this->fail('Exception "Location not writeable" not thrown.'); } }