From 82eca852adb59906c72ba416974e83589d4d9f01 Mon Sep 17 00:00:00 2001 From: hexstudy Date: Wed, 10 Dec 2014 15:13:34 +0000 Subject: [PATCH 1/3] git-svn-id: https://msi/svn/firstRepo/Service/trunk@18 0f545695-f87b-41b6-9a03-7f16563b5454 From 4f363403ca20f95a0766e4494c81ebb293a3baa6 Mon Sep 17 00:00:00 2001 From: hexstudy Date: Wed, 10 Dec 2014 15:14:03 +0000 Subject: [PATCH 2/3] git-svn-id: https://msi/svn/firstRepo/Service/trunk@19 0f545695-f87b-41b6-9a03-7f16563b5454 --- .htaccess | 12 + MySqlClass.php | 89 + .../Exception/ImageWorkshopLayerException.php | 22 + .../Exception/ImageWorkshopLibException.php | 22 + PHPImageWorkshop/Core/ImageWorkshopLayer.php | 1904 +++++++++++++++++ PHPImageWorkshop/Core/ImageWorkshopLib.php | 299 +++ .../Exception/ImageWorkshopBaseException.php | 38 + .../Exception/ImageWorkshopException.php | 22 + PHPImageWorkshop/ImageWorkshop.php | 168 ++ Slim/Environment.php | 224 ++ Slim/Exception/Pass.php | 49 + Slim/Exception/Stop.php | 47 + Slim/Helper/Set.php | 246 +++ Slim/Http/Cookies.php | 91 + Slim/Http/Headers.php | 104 + Slim/Http/Request.php | 617 ++++++ Slim/Http/Response.php | 512 +++++ Slim/Http/Util.php | 434 ++++ Slim/Log.php | 349 +++ Slim/LogWriter.php | 75 + Slim/Middleware.php | 114 + Slim/Middleware/ContentTypes.php | 174 ++ Slim/Middleware/Flash.php | 212 ++ Slim/Middleware/MethodOverride.php | 94 + Slim/Middleware/PrettyExceptions.php | 116 + Slim/Middleware/SessionCookie.php | 210 ++ Slim/Route.php | 465 ++++ Slim/Router.php | 257 +++ Slim/Slim.php | 1412 ++++++++++++ Slim/View.php | 282 +++ config.inc.php | 8 + image.php | 103 + include.php | 31 + management.php | 165 ++ profile.php | 111 + ricette.php | 178 ++ serviceapp.php | 16 + utility.php | 78 + 38 files changed, 9350 insertions(+) create mode 100644 .htaccess create mode 100644 MySqlClass.php create mode 100644 PHPImageWorkshop/Core/Exception/ImageWorkshopLayerException.php create mode 100644 PHPImageWorkshop/Core/Exception/ImageWorkshopLibException.php create mode 100644 PHPImageWorkshop/Core/ImageWorkshopLayer.php create mode 100644 PHPImageWorkshop/Core/ImageWorkshopLib.php create mode 100644 PHPImageWorkshop/Exception/ImageWorkshopBaseException.php create mode 100644 PHPImageWorkshop/Exception/ImageWorkshopException.php create mode 100644 PHPImageWorkshop/ImageWorkshop.php create mode 100644 Slim/Environment.php create mode 100644 Slim/Exception/Pass.php create mode 100644 Slim/Exception/Stop.php create mode 100644 Slim/Helper/Set.php create mode 100644 Slim/Http/Cookies.php create mode 100644 Slim/Http/Headers.php create mode 100644 Slim/Http/Request.php create mode 100644 Slim/Http/Response.php create mode 100644 Slim/Http/Util.php create mode 100644 Slim/Log.php create mode 100644 Slim/LogWriter.php create mode 100644 Slim/Middleware.php create mode 100644 Slim/Middleware/ContentTypes.php create mode 100644 Slim/Middleware/Flash.php create mode 100644 Slim/Middleware/MethodOverride.php create mode 100644 Slim/Middleware/PrettyExceptions.php create mode 100644 Slim/Middleware/SessionCookie.php create mode 100644 Slim/Route.php create mode 100644 Slim/Router.php create mode 100644 Slim/Slim.php create mode 100644 Slim/View.php create mode 100644 config.inc.php create mode 100644 image.php create mode 100644 include.php create mode 100644 management.php create mode 100644 profile.php create mode 100644 ricette.php create mode 100644 serviceapp.php create mode 100644 utility.php diff --git a/.htaccess b/.htaccess new file mode 100644 index 0000000..0189d10 --- /dev/null +++ b/.htaccess @@ -0,0 +1,12 @@ + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^(.*)$ serviceapp.php [QSA,L] + + + + Allow from *.gruppolapastamadre.it + + +Header set Access-Control-Allow-Origin *.gruppolapastamadre.it +Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT" \ No newline at end of file diff --git a/MySqlClass.php b/MySqlClass.php new file mode 100644 index 0000000..26eebe3 --- /dev/null +++ b/MySqlClass.php @@ -0,0 +1,89 @@ +attiva) + { + $this->connessione = mysql_connect($this->nomehost,$this->nomeuser,$this->password); + if ($this->connessione == FALSE) + die(mysql_error()); + mysql_select_db($this->mydb, $this->connessione) or die ("Errore nella selezione del database. Verificare i parametri nel file config.inc.php"); + $this->attiva = true; + } + else{ + return true; + } + + } + + public function executeQuery($queryStr) + { + $this->connetti(); + + if (!$res = mysql_query($queryStr, $this->connessione)) die(mysql_error()); + return true; + return false; + } + + public function insertRecord($queryStr) + { + $this->connetti(); + + if (!$res = mysql_query($queryStr, $this->connessione)) die(mysql_error()); + return mysql_insert_id(); + } + + public function queryToObject($queryStr) + { + $this->connetti(); + + $sth = mysql_query($queryStr, $this->connessione) or die(mysql_error()); + + $rows = array(); + while($r = mysql_fetch_assoc($sth)) { + array_push($rows,array_map('utf8_encode', $r)); + } + mysql_free_result($sth); + return $rows; + } + + // funzione per la chiusura della connessione + public function disconnetti() + { + if($this->attiva) + { + if(mysql_close($this->connessione)) + { + $this->attiva = false; + return true; + } + else + { + return false; + } + } + } + + public function __destruct() + { + $this->disconnetti(); + } + } +?> \ No newline at end of file diff --git a/PHPImageWorkshop/Core/Exception/ImageWorkshopLayerException.php b/PHPImageWorkshop/Core/Exception/ImageWorkshopLayerException.php new file mode 100644 index 0000000..eac77ca --- /dev/null +++ b/PHPImageWorkshop/Core/Exception/ImageWorkshopLayerException.php @@ -0,0 +1,22 @@ +width = imagesx($image); + $this->height = imagesy($image); + $this->image = $image; + $this->layers = $this->layerLevels = $this->layerPositions = array(); + $this->clearStack(); + } + + /** + * Clone method: use it if you want to reuse an existing ImageWorkshop object in another variable + * This is important because img resource var references all the same image in PHP. + * Example: $b = clone $a; (never do $b = $a;) + */ + public function __clone() + { + $this->createNewVarFromBackgroundImage(); + } + + // Superimpose a sublayer + // ========================================================= + + /** + * Add an existing ImageWorkshop sublayer and set it in the stack at a given level + * Return an array containing the generated sublayer id in the stack and its corrected level: + * array("layerLevel" => integer, "id" => integer) + * + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param integer $layerLevel + * @param ImageWorkshop $layer + * @param integer $positionX + * @param integer $positionY + * @param string $position + * + * @return array + */ + public function addLayer($layerLevel, $layer, $positionX = 0, $positionY = 0, $position = 'LT') + { + return $this->indexLayer($layerLevel, $layer, $positionX, $positionY, $position); + } + + /** + * Add an existing ImageWorkshop sublayer and set it in the stack at the highest level + * Return an array containing the generated sublayer id in the stack and the highest level: + * array("layerLevel" => integer, "id" => integer) + * + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param ImageWorkshop $layer + * @param integer $positionX + * @param integer $positionY + * @param string $position + * + * @return array + */ + public function addLayerOnTop($layer, $positionX = 0, $positionY = 0, $position = 'LT') + { + return $this->indexLayer($this->highestLayerLevel + 1, $layer, $positionX, $positionY, $position); + } + + /** + * Add an existing ImageWorkshop sublayer and set it in the stack at level 1 + * Return an array containing the generated sublayer id in the stack and level 1: + * array("layerLevel" => integer, "id" => integer) + * + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param ImageWorkshop $layer + * @param integer $positionX + * @param integer $positionY + * @param string $position + * + * @return array + */ + public function addLayerBelow($layer, $positionX = 0, $positionY = 0, $position = 'LT') + { + return $this->indexLayer(1, $layer, $positionX, $positionY, $position); + } + + // Move a sublayer inside the stack + // ========================================================= + + /** + * Move a sublayer on the top of a group stack + * Return new sublayer level if success or false otherwise + * + * @param integer $layerId + * @return mixed + */ + public function moveTop($layerId) + { + return $this->moveTo($layerId, $this->highestLayerLevel, false); + } + + /** + * Move a sublayer to the level 1 of a group stack + * Return new sublayer level if success or false otherwise + * + * @param integer $layerId + * @param integer $level + * + * @return mixed + */ + public function moveBottom($layerId) + { + return $this->moveTo($layerId, 1, true); + } + + /** + * Move a sublayer to the level $level of a group stack + * Return new sublayer level if success or false if layer isn't found + * + * Set $insertUnderTargetedLayer true if you want to move the sublayer under the other sublayer at the targeted level, + * or false to insert it on the top of the other sublayer at the targeted level + * + * @param integer $layerId + * @param integer $level + * @param boolean $insertUnderTargetedLayer + * + * @return mixed + */ + public function moveTo($layerId, $level, $insertUnderTargetedLayer = true) + { + // if the sublayer exists in stack + if ($this->isLayerInIndex($layerId)) { + + $layerOldLevel = $this->getLayerLevel($layerId); + + if ($level < 1) { + $level = 1; + $insertUnderTargetedLayer = true; + } + + if ($level > $this->highestLayerLevel) { + + $level = $this->highestLayerLevel; + $insertUnderTargetedLayer = false; + } + + // Not the same level than the current level + if ($layerOldLevel != $level) { + + $isUnderAndNewLevelHigher = $isUnderAndNewLevelLower = $isOnTopAndNewLevelHigher = $isOnTopAndNewLevelLower = false; + + if ($insertUnderTargetedLayer) { // Under level + + if ($level > $layerOldLevel) { // new level higher + + $incrementorStartingValue = $layerOldLevel; + $stopLoopWhenSmallerThan = $level; + $isUnderAndNewLevelHigher = true; + + } else { // new level lower + + $incrementorStartingValue = $level; + $stopLoopWhenSmallerThan = $layerOldLevel; + $isUnderAndNewLevelLower = true; + } + + } else { // on the top + + if ($level > $layerOldLevel) { // new level higher + + $incrementorStartingValue = $layerOldLevel; + $stopLoopWhenSmallerThan = $level; + $isOnTopAndNewLevelHigher = true; + + } else { // new level lower + + $incrementorStartingValue = $level; + $stopLoopWhenSmallerThan = $layerOldLevel; + $isOnTopAndNewLevelLower = true; + } + } + + ksort($this->layerLevels); + $layerLevelsTmp = $this->layerLevels; + + if ($isOnTopAndNewLevelLower) { + $level++; + } + + for ($i = $incrementorStartingValue; $i < $stopLoopWhenSmallerThan; $i++) { + + if ($isUnderAndNewLevelHigher || $isOnTopAndNewLevelHigher) { + + $this->layerLevels[$i] = $layerLevelsTmp[$i + 1]; + + } else { + + $this->layerLevels[$i + 1] = $layerLevelsTmp[$i]; + } + } + + unset($layerLevelsTmp); + + if ($isUnderAndNewLevelHigher) { + $level--; + } + + $this->layerLevels[$level] = $layerId; + + return $level; + + } else { + return $level; + } + } + + return false; + } + + /** + * Move up a sublayer in the stack (level +1) + * Return new sublayer level if success, false otherwise + * + * @param integer $layerId + * + * @return mixed + */ + public function moveUp($layerId) + { + if ($this->isLayerInIndex($layerId)) { // if the sublayer exists in the stack + $layerOldLevel = $this->getLayerLevel($layerId); + return $this->moveTo($layerId, $layerOldLevel + 1, false); + } + + return false; + } + + /** + * Move down a sublayer in the stack (level -1) + * Return new sublayer level if success, false otherwise + * + * @param integer $layerId + * + * @return mixed + */ + public function moveDown($layerId) + { + if ($this->isLayerInIndex($layerId)) { // if the sublayer exists in the stack + $layerOldLevel = $this->getLayerLevel($layerId); + return $this->moveTo($layerId, $layerOldLevel - 1, true); + } + + return false; + } + + // Merge layers + // ========================================================= + + /** + * Merge a sublayer with another sublayer below it in the stack + * Note: the result layer will conserve the given id + * Return true if success or false if layer isn't found or doesn't have a layer under it in the stack + * + * @param integer $layerId + * + * @return boolean + */ + public function mergeDown($layerId) + { + // if the layer exists in document + if ($this->isLayerInIndex($layerId)) { + + $layerLevel = $this->getLayerLevel($layerId); + $layerPositions = $this->getLayerPositions($layerId); + $layer = $this->getLayer($layerId); + $layerWidth = $layer->getWidth(); + $layerHeight = $layer->getHeight(); + $layerPositionX = $this->layerPositions[$layerId]['x']; + $layerPositionY = $this->layerPositions[$layerId]['y']; + + if ($layerLevel > 1) { + + $underLayerId = $this->layerLevels[$layerLevel - 1]; + $underLayer = $this->getLayer($underLayerId); + $underLayerWidth = $underLayer->getWidth(); + $underLayerHeight = $underLayer->getHeight(); + $underLayerPositionX = $this->layerPositions[$underLayerId]['x']; + $underLayerPositionY = $this->layerPositions[$underLayerId]['y']; + + $totalWidthLayer = $layerWidth + $layerPositionX; + $totalHeightLayer = $layerHeight + $layerPositionY; + + $totalWidthUnderLayer = $underLayerWidth + $underLayerPositionX; + $totalHeightUnderLayer = $underLayerHeight + $underLayerPositionY; + + $minLayerPositionX = $layerPositionX; + + if ($layerPositionX > $underLayerPositionX) { + $minLayerPositionX = $underLayerPositionX; + } + + $minLayerPositionY = $layerPositionY; + + if ($layerPositionY > $underLayerPositionY) { + $minLayerPositionY = $underLayerPositionY; + } + + if ($totalWidthLayer > $totalWidthUnderLayer) { + $layerTmpWidth = $totalWidthLayer - $minLayerPositionX; + } else { + $layerTmpWidth = $totalWidthUnderLayer - $minLayerPositionX; + } + + if ($totalHeightLayer > $totalHeightUnderLayer) { + $layerTmpHeight = $totalHeightLayer - $minLayerPositionY; + } else { + $layerTmpHeight = $totalHeightUnderLayer - $minLayerPositionY; + } + + $layerTmp = ImageWorkshop::initVirginLayer($layerTmpWidth, $layerTmpHeight); + + $layerTmp->addLayer(1, $underLayer, $underLayerPositionX - $minLayerPositionX, $underLayerPositionY - $minLayerPositionY); + $layerTmp->addLayer(2, $layer, $layerPositionX - $minLayerPositionX, $layerPositionY - $minLayerPositionY); + + // Update layers + $layerTmp->mergeAll(); + $this->layers[$underLayerId] = clone $layerTmp; + $this->changePosition($underLayerId, $minLayerPositionX, $minLayerPositionX); + + } else { + + $layerTmp = ImageWorkshop::initFromResourceVar($this->image); + $layerTmp->addLayer(1, $layer, $layerPositionX, $layerPositionY); + + $this->image = $layerTmp->getResult(); // Update background image + } + + unset($layerTmp); + $this->remove($layerId); // Remove the merged layer from the stack + + return true; + } + + return false; + } + + /** + * Merge sublayers in the stack on the layer background + */ + public function mergeAll() + { + $this->image = $this->getResult(); + $this->clearStack(); + } + + /** + * Paste an image on the layer + * You can specify the position left (in pixels) and the position top (in pixels) of the added image relatives to the layer + * Otherwise, it will be set at 0 and 0 + * + * @param string $unit Use one of `UNIT_*` constants, "UNIT_PIXEL" by default + * @param resource $image + * @param integer $positionX + * @param integer $positionY + */ + public function pasteImage($unit = self::UNIT_PIXEL, $image, $positionX = 0, $positionY = 0) + { + if ($unit == self::UNIT_PERCENT) { + + $positionX = round(($positionX / 100) * $this->width); + $positionY = round(($positionY / 100) * $this->height); + } + + imagecopy($this->image, $image, $positionX, $positionY, 0, 0, $image->getWidth(), $image->getHeight()); + } + + // Change sublayer positions + // ========================================================= + + /** + * Change the position of a sublayer for new positions + * + * @param integer $layerId + * @param integer $newPosX + * @param integer $newPosY + * + * @return boolean + */ + public function changePosition($layerId, $newPosX = null, $newPosY = null) + { + // if the sublayer exists in the stack + if ($this->isLayerInIndex($layerId)) { + + if ($newPosX !== null) { + $this->layerPositions[$layerId]['x'] = $newPosX; + } + + if ($newPosY !== null) { + $this->layerPositions[$layerId]['y'] = $newPosY; + } + + return true; + } + + return false; + } + + /** + * Apply a translation on a sublayer that change its positions + * + * @param integer $layerId + * @param integer $addedPosX + * @param integer $addedPosY + * + * @return mixed (array of new positions or false if fail) + */ + public function applyTranslation($layerId, $addedPosX = null, $addedPosY = null) + { + // if the sublayer exists in the stack + if ($this->isLayerInIndex($layerId)) { + + if ($addedPosX !== null) { + $this->layerPositions[$layerId]['x'] += $addedPosX; + } + + if ($addedPosY !== null) { + $this->layerPositions[$layerId]['y'] += $addedPosY; + } + + return $this->layerPositions[$layerId]; + } + + return false; + } + + // Removing sublayers + // ========================================================= + + /** + * Delete a layer (return true if success, false if no sublayer is found) + * + * @param integer $layerId + * + * @return boolean + */ + public function remove($layerId) + { + // if the layer exists in document + if ($this->isLayerInIndex($layerId)) { + + $layerToDeleteLevel = $this->getLayerLevel($layerId); + + // delete + $this->layers[$layerId]->delete(); + unset($this->layers[$layerId]); + unset($this->layerLevels[$layerToDeleteLevel]); + unset($this->layerPositions[$layerId]); + + // One or plural layers are sub of the deleted layer + if (array_key_exists(($layerToDeleteLevel + 1), $this->layerLevels)) { + + ksort($this->layerLevels); + + $layerLevelsTmp = $this->layerLevels; + + $maxOldestLevel = 1; + foreach ($layerLevelsTmp as $levelTmp => $layerIdTmp) { + + if ($levelTmp > $layerToDeleteLevel) { + $this->layerLevels[($levelTmp - 1)] = $layerIdTmp; + } + + $maxOldestLevel++; + } + unset($layerLevelsTmp); + unset($this->layerLevels[$maxOldestLevel]); + } + + $this->highestLayerLevel--; + + return true; + } + + return false; + } + + /** + * Reset the layer stack + * + * @boolean $deleteSubImgVar Delete sublayers image resource var + */ + public function clearStack($deleteSubImgVar = true) + { + if ($deleteSubImgVar) { + foreach ($this->layers as $layer) { + $layer->delete(); + } + } + + unset($this->layers); + unset($this->layerLevels); + unset($this->layerPositions); + + $this->lastLayerId = 0; + $this->layers = array(); + $this->layerLevels = array(); + $this->layerPositions = array(); + $this->highestLayerLevel = 0; + } + + // Perform an action + // ========================================================= + + /** + * Resize the layer by specifying pixel + * + * @param integer $newWidth + * @param integer $newHeight + * @param boolean $converseProportion + * @param integer $positionX + * @param integer $positionY + * @param string $position + * + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * $positionX, $positionY, $position can be ignored unless you choose a new width AND a new height AND to conserve proportion. + */ + public function resizeInPixel($newWidth = null, $newHeight = null, $converseProportion = false, $positionX = 0, $positionY = 0, $position = 'MM') + { + $this->resize(self::UNIT_PIXEL, $newWidth, $newHeight, $converseProportion, $positionX, $positionY, $position); + } + + /** + * Resize the layer by specifying a percent + * + * @param float $percentWidth + * @param float $percentHeight + * @param boolean $converseProportion + * @param integer $positionX + * @param integer $positionY + * @param string $position + * + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * $positionX, $positionY, $position can be ignored unless you choose a new width AND a new height AND to conserve proportion. + */ + public function resizeInPercent($percentWidth = null, $percentHeight = null, $converseProportion = false, $positionX = 0, $positionY = 0, $position = 'MM') + { + $this->resize(self::UNIT_PERCENT, $percentWidth, $percentHeight, $converseProportion, $positionX, $positionY, $position); + } + + /** + * Resize the layer to fit a bounding box by specifying pixel + * + * @param integer $width + * @param integer $height + * @param boolean $converseProportion + */ + public function resizeToFit($width, $height, $converseProportion = false) + { + if ($this->getWidth() <= $width && $this->getHeight() <= $height) { + return; + } + + if (!$converseProportion) { + $width = min($width, $this->getWidth()); + $height = min($height, $this->getHeight()); + } + + $this->resize(self::UNIT_PIXEL, $width, $height, $converseProportion ? 2 : false); + } + + /** + * Resize the layer + * + * @param string $unit Use one of `UNIT_*` constants, "UNIT_PIXEL" by default + * @param mixed $newWidth (integer or float) + * @param mixed $newHeight (integer or float) + * @param boolean $converseProportion + * @param mixed $positionX (integer or float) + * @param mixed $positionY (integer or float) + * @param string $position + * + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * $positionX, $positionY, $position can be ignored unless you choose a new width AND a new height AND to conserve proportion. + */ + public function resize($unit = self::UNIT_PIXEL, $newWidth = null, $newHeight = null, $converseProportion = false, $positionX = 0, $positionY = 0, $position = 'MM') + { + if (is_numeric($newWidth) || is_numeric($newHeight)) { + + if ($unit == self::UNIT_PERCENT) { + + if ($newWidth) { + $newWidth = round(($newWidth / 100) * $this->width); + } + + if ($newHeight) { + $newHeight = round(($newHeight / 100) * $this->height); + } + } + + if (is_numeric($newWidth) && $newWidth <= 0) { + $newWidth = 1; + } + + if (is_numeric($newHeight) && $newHeight <= 0) { + $newHeight = 1; + } + + if ($converseProportion) { // Proportion are conserved + + if ($newWidth && $newHeight) { // Proportions + $newWidth + $newHeight + + if ($this->getWidth() > $this->getHeight()) { + + $this->resizeInPixel($newWidth, null, true); + + if ($this->getHeight() > $newHeight) { + $this->resizeInPixel(null, $newHeight, true); + } + + } else { + + $this->resizeInPixel(null, $newHeight, true); + + if ($this->getWidth() > $newWidth) { + $this->resizeInPixel($newWidth, null, true); + } + } + + if ($converseProportion !== 2 && ($this->getWidth() != $newWidth || $this->getHeight() != $newHeight)) { + + $layerTmp = ImageWorkshop::initVirginLayer($newWidth, $newHeight); + + $layerTmp->addLayer(1, $this, $positionX, $positionY, $position); + + // Reset part of stack + + unset($this->image); + unset($this->layerLevels); + unset($this->layerPositions); + unset($this->layers); + + // Update current object + + $this->width = $layerTmp->getWidth(); + $this->height = $layerTmp->getHeight(); + $this->layerLevels = $layerTmp->layers[1]->getLayerLevels(); + $this->layerPositions = $layerTmp->layers[1]->getLayerPositions(); + $this->layers = $layerTmp->layers[1]->getLayers(); + $this->lastLayerId = $layerTmp->layers[1]->getLastLayerId(); + $this->highestLayerLevel = $layerTmp->layers[1]->getHighestLayerLevel(); + + $translations = $layerTmp->getLayerPositions(1); + + foreach ($this->layers as $id => $layer) { + $this->applyTranslation($id, $translations['x'], $translations['y']); + } + + $layerTmp->layers[1]->clearStack(false); + $this->image = $layerTmp->getResult(); + unset($layerTmp); + } + + return; + + } elseif ($newWidth) { + + $widthResizePercent = $newWidth / ($this->width / 100); + $newHeight = round(($widthResizePercent / 100) * $this->height); + $heightResizePercent = $widthResizePercent; + + } elseif ($newHeight) { + + $heightResizePercent = $newHeight / ($this->height / 100); + $newWidth = round(($heightResizePercent / 100) * $this->width); + $widthResizePercent = $heightResizePercent; + } + + } elseif (($newWidth && !$newHeight) || (!$newWidth && $newHeight)) { // New width OR new height is given + + if ($newWidth) { + + $widthResizePercent = $newWidth / ($this->width / 100); + $heightResizePercent = 100; + $newHeight = $this->height; + + } else { + + $heightResizePercent = $newHeight / ($this->height / 100); + $widthResizePercent = 100; + $newWidth = $this->width; + } + + } else { // New width AND new height are given + + $widthResizePercent = $newWidth / ($this->width / 100); + $heightResizePercent = $newHeight / ($this->height / 100); + } + + // Update the layer positions in the stack + + foreach ($this->layerPositions as $layerId => $layerPosition) { + + $newPosX = round(($widthResizePercent / 100) * $layerPosition['x']); + $newPosY = round(($heightResizePercent / 100) * $layerPosition['y']); + + $this->changePosition($layerId, $newPosX, $newPosY); + } + + // Resize layers in the stack + + $layers = $this->layers; + + foreach ($layers as $key => $layer) { + $layer->resizeInPercent($widthResizePercent, $heightResizePercent); + $this->layers[$key] = $layer; + } + + $this->resizeBackground($newWidth, $newHeight); // Resize the layer + } + } + + /** + * Resize the layer by its largest side by specifying pixel + * + * @param integer $newLargestSideWidth + * @param boolean $converseProportion + */ + public function resizeByLargestSideInPixel($newLargestSideWidth, $converseProportion = false) + { + $this->resizeByLargestSide(self::UNIT_PIXEL, $newLargestSideWidth, $converseProportion); + } + + /** + * Resize the layer by its largest side by specifying percent + * + * @param integer $newLargestSideWidth percent + * @param boolean $converseProportion + */ + public function resizeByLargestSideInPercent($newLargestSideWidth, $converseProportion = false) + { + $this->resizeByLargestSide(self::UNIT_PERCENT, $newLargestSideWidth, $converseProportion); + } + + /** + * Resize the layer by its largest side + * + * @param string $unit + * @param integer $newLargestSideWidth percent + * @param boolean $converseProportion + */ + public function resizeByLargestSide($unit = self::UNIT_PIXEL, $newLargestSideWidth, $converseProportion = false) + { + if ($unit == self::UNIT_PERCENT) { + $newLargestSideWidth = round(($newLargestSideWidth / 100) * $this->getLargestSideWidth()); + } + + if ($this->getWidth() > $this->getHeight()) { + $this->resizeInPixel($newLargestSideWidth, null, $converseProportion); + } else { + $this->resizeInPixel(null, $newLargestSideWidth, $converseProportion); + } + } + + /** + * Resize the layer by its narrow side by specifying pixel + * + * @param integer $newNarrowSideWidth + * @param boolean $converseProportion + */ + public function resizeByNarrowSideInPixel($newNarrowSideWidth, $converseProportion = false) + { + $this->resizeByNarrowSide(self::UNIT_PIXEL, $newNarrowSideWidth, $converseProportion); + } + + /** + * Resize the layer by its narrow side by specifying percent + * + * @param integer $newNarrowSideWidth percent + * @param boolean $converseProportion + */ + public function resizeByNarrowSideInPercent($newNarrowSideWidth, $converseProportion = false) + { + $this->resizeByNarrowSide(self::UNIT_PERCENT, $newNarrowSideWidth, $converseProportion); + } + + /** + * Resize the layer by its narrow side + * + * @param string $unit + * @param integer $newNarrowSideWidth + * @param boolean $converseProportion + */ + public function resizeByNarrowSide($unit = self::UNIT_PIXEL, $newNarrowSideWidth, $converseProportion = false) + { + if ($unit == self::UNIT_PERCENT) { + $newNarrowSideWidth = round(($newNarrowSideWidth / 100) * $this->getNarrowSideWidth()); + } + + if ($this->getWidth() < $this->getHeight()) { + $this->resizeInPixel($newNarrowSideWidth, null, $converseProportion); + } else { + $this->resizeInPixel(null, $newNarrowSideWidth, $converseProportion); + } + } + + /** + * Crop the document by specifying pixels + * + * $backgroundColor: can be set transparent (The script will be longer to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param integer $width + * @param integer $height + * @param integer $positionX + * @param integer $positionY + * @param string $position + */ + public function cropInPixel($width = 0, $height = 0, $positionX = 0, $positionY = 0, $position = 'LT') + { + $this->crop(self::UNIT_PIXEL, $width, $height, $positionX, $positionY, $position); + } + + /** + * Crop the document by specifying percent + * + * $backgroundColor can be set transparent (but script could be long to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param float $percentWidth + * @param float $percentHeight + * @param float $positionXPercent + * @param float $positionYPercent + * @param string $position + */ + public function cropInPercent($percentWidth = 0, $percentHeight = 0, $positionXPercent = 0, $positionYPercent = 0, $position = 'LT') + { + $this->crop(self::UNIT_PERCENT, $percentWidth, $percentHeight, $positionXPercent, $positionYPercent, $position); + } + + /** + * Crop the document + * + * $backgroundColor can be set transparent (but script could be long to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param string $unit + * @param mixed $width (integer or float) + * @param mixed $height (integer or float) + * @param mixed $positionX (integer or float) + * @param mixed $positionY (integer or float) + * @param string $position + */ + public function crop($unit = self::UNIT_PIXEL, $width = 0, $height = 0, $positionX = 0, $positionY = 0, $position = 'LT') + { + if ($width < 0 || $height < 0) { + throw new ImageWorkshopLayerException('You can\'t use negative $width or $height for "'.__METHOD__.'" method.', static::ERROR_NEGATIVE_NUMBER_USED); + } + + if ($unit == self::UNIT_PERCENT) { + + $width = round(($width / 100) * $this->width); + $height = round(($height / 100) * $this->height); + + $positionX = round(($positionX / 100) * $this->width); + $positionY = round(($positionY / 100) * $this->height); + } + + if (($width != $this->width || $positionX == 0) || ($height != $this->height || $positionY == 0)) { + + if ($width == 0) { + $width = 1; + } + + if ($height == 0) { + $height = 1; + } + + $layerTmp = ImageWorkshop::initVirginLayer($width, $height); + $layerClone = ImageWorkshop::initVirginLayer($this->width, $this->height); + + imagedestroy($layerClone->image); + $layerClone->image = $this->image; + + $layerTmp->addLayer(1, $layerClone, -$positionX, -$positionY, $position); + + $newPos = $layerTmp->getLayerPositions(); + $layerNewPosX = $newPos[1]['x']; + $layerNewPosY = $newPos[1]['y']; + + // update the layer + $this->width = $layerTmp->getWidth(); + $this->height = $layerTmp->getHeight(); + $this->image = $layerTmp->getResult(); + unset($layerTmp); + unset($layerClone); + + $this->updateLayerPositionsAfterCropping($layerNewPosX, $layerNewPosY); + } + } + + /** + * Crop the document to a specific aspect ratio by specifying a shift in pixel + * + * $backgroundColor: can be set transparent (The script will be longer to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param integer $width + * @param integer $height + * @param integer $positionX + * @param integer $positionY + * @param string $position + */ + public function cropToAspectRatioInPixel($width = 0, $height = 0, $positionX = 0, $positionY = 0, $position = 'LT') + { + $this->cropToAspectRatio(self::UNIT_PIXEL, $width, $height, $positionX, $positionY, $position); + } + + /** + * Crop the document to a specific aspect ratio by specifying a shift in percent + * + * $backgroundColor can be set transparent (but script could be long to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param integer $width + * @param integer $height + * @param float $positionXPercent + * @param float $positionYPercent + * @param string $position + */ + public function cropToAspectRatioInPercent($width = 0, $height = 0, $positionXPercent = 0, $positionYPercent = 0, $position = 'LT') + { + $this->cropToAspectRatio(self::UNIT_PERCENT, $width, $height, $positionXPercent, $positionYPercent, $position); + } + + /** + * Crop the document to a specific aspect ratio + * + * $backgroundColor can be set transparent (but script could be long to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param string $unit + * @param integer $width (integer or float) + * @param integer $height (integer or float) + * @param mixed $positionX (integer or float) + * @param mixed $positionY (integer or float) + * @param string $position + */ + public function cropToAspectRatio($unit = self::UNIT_PIXEL, $width = 0, $height = 0, $positionX = 0, $positionY = 0, $position = 'LT') + { + if ($width < 0 || $height < 0) { + throw new ImageWorkshopLayerException('You can\'t use negative $width or $height for "'.__METHOD__.'" method.', static::ERROR_NEGATIVE_NUMBER_USED); + } + + if ($width == 0) { + $width = 1; + } + + if ($height == 0) { + $height = 1; + } + + if ($this->width / $this->height <= $width / $height) { + $newWidth = $this->width; + $newHeight = round($height * ($this->width / $width)); + } else { + $newWidth = round($width * ($this->height / $height)); + $newHeight = $this->height; + } + + if ($unit == self::UNIT_PERCENT) { + $positionX = round(($positionX / 100) * ($this->width - $newWidth)); + $positionY = round(($positionY / 100) * ($this->height - $newHeight)); + } + + $this->cropInPixel($newWidth, $newHeight, $positionX, $positionY, $position); + } + + /** + * Crop the maximum possible from left top ("LT"), "RT"... by specifying a shift in pixel + * + * $backgroundColor can be set transparent (but script could be long to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param integer $width + * @param integer $height + * @param integer $positionX + * @param integer $positionY + * @param string $position + */ + public function cropMaximumInPixel($positionX = 0, $positionY = 0, $position = 'LT') + { + $this->cropMaximum(self::UNIT_PIXEL, $positionX, $positionY, $position); + } + + /** + * Crop the maximum possible from left top ("LT"), "RT"... by specifying a shift in percent + * + * $backgroundColor can be set transparent (but script could be long to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param integer $width + * @param integer $height + * @param integer $positionXPercent + * @param integer $positionYPercent + * @param string $position + */ + public function cropMaximumInPercent($positionXPercent = 0, $positionYPercent = 0, $position = 'LT') + { + $this->cropMaximum(self::UNIT_PERCENT, $positionXPercent, $positionYPercent, $position); + } + + /** + * Crop the maximum possible from left top + * + * $backgroundColor can be set transparent (but script could be long to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param string $unit + * @param integer $width + * @param integer $height + * @param integer $positionX + * @param integer $positionY + * @param string $position + */ + public function cropMaximum($unit = self::UNIT_PIXEL, $positionX = 0, $positionY = 0, $position = 'LT') + { + $narrowSide = $this->getNarrowSideWidth(); + + if ($unit == self::UNIT_PERCENT) { + $positionX = round(($positionX / 100) * $this->width); + $positionY = round(($positionY / 100) * $this->height); + } + + $this->cropInPixel($narrowSide, $narrowSide, $positionX, $positionY, $position); + } + + /** + * Rotate the layer (in degree) + * + * @param float $degrees + */ + public function rotate($degrees) + { + if ($degrees != 0) { + + if ($degrees < -360 || $degrees > 360) { + $degrees = $degrees % 360; + } + + if ($degrees < 0 && $degrees >= -360) { + $degrees = 360 + $degrees; + } + + // Rotate the layer background image + $imageRotated = imagerotate($this->image, -$degrees, -1); + imagealphablending($imageRotated, true); + imagesavealpha($imageRotated, true); + + unset($this->image); + + $this->image = $imageRotated; + + $oldWidth = $this->width; + $oldHeight = $this->height; + + $this->width = imagesx($this->image); + $this->height = imagesy($this->image); + + foreach ($this->layers as $layerId => $layer) { + + $layerSelfOldCenterPosition = array( + 'x' => $layer->width / 2, + 'y' => $layer->height / 2, + ); + + $smallImageCenter = array( + 'x' => $layerSelfOldCenterPosition['x'] + $this->layerPositions[$layerId]['x'], + 'y' => $layerSelfOldCenterPosition['y'] + $this->layerPositions[$layerId]['y'], + ); + + $this->layers[$layerId]->rotate($degrees); + + $ro = sqrt(pow($smallImageCenter['x'], 2) + pow($smallImageCenter['y'], 2)); + + $teta = (acos($smallImageCenter['x'] / $ro)) * 180 / pi(); + + $a = $ro * cos(($teta + $degrees) * pi() / 180); + $b = $ro * sin(($teta + $degrees) * pi() / 180); + + if ($degrees > 0 && $degrees <= 90) { + + $newPositionX = $a - ($this->layers[$layerId]->width / 2) + $oldHeight * sin(($degrees * pi()) / 180); + $newPositionY = $b - ($this->layers[$layerId]->height / 2); + + } elseif ($degrees > 90 && $degrees <= 180) { + + $newPositionX = $a - ($this->layers[$layerId]->width / 2) + $this->width; + $newPositionY = $b - ($this->layers[$layerId]->height / 2) + $oldHeight * (-cos(($degrees) * pi() / 180)); + + } elseif ($degrees > 180 && $degrees <= 270) { + + $newPositionX = $a - ($this->layers[$layerId]->width / 2) + $oldWidth * (-cos(($degrees) * pi() / 180)); + $newPositionY = $b - ($this->layers[$layerId]->height / 2) + $this->height; + + } else { + + $newPositionX = $a - ($this->layers[$layerId]->width / 2); + $newPositionY = $b - ($this->layers[$layerId]->height / 2) + $oldWidth * (-sin(($degrees) * pi() / 180)); + } + + $this->layerPositions[$layerId] = array( + 'x' => $newPositionX, + 'y' => $newPositionY, + ); + } + } + } + + /** + * Change the opacity of the layer + * $recursive: apply it on sublayers + * + * @param integer $opacity + * @param boolean $recursive + */ + public function opacity($opacity, $recursive = true) + { + if ($recursive) { + + $layers = $this->layers; + + foreach ($layers as $key => $layer) { + $layer->opacity($opacity, true); + $this->layers[$key] = $layer; + } + } + + $transparentImage = ImageWorkshopLib::generateImage($this->getWidth(), $this->getHeight()); + + ImageWorkshopLib::imageCopyMergeAlpha($transparentImage, $this->image, 0, 0, 0, 0, $this->getWidth(), $this->getHeight(), $opacity); + + unset($this->image); + $this->image = $transparentImage; + unset($transparentImage); + } + + /** + * Apply a filter on the layer + * Be careful: some filters can damage transparent images, use it sparingly ! (A good pratice is to use mergeAll on your layer before applying a filter) + * + * @param int $filterType (http://www.php.net/manual/en/function.imagefilter.php) + * @param int $arg1 + * @param int $arg2 + * @param int $arg3 + * @param int $arg4 + * @param boolean $recursive + */ + public function applyFilter($filterType, $arg1 = null, $arg2 = null, $arg3 = null, $arg4 = null, $recursive = false) + { + if ($filterType == IMG_FILTER_COLORIZE) { + imagefilter($this->image, $filterType, $arg1, $arg2, $arg3, $arg4); + } elseif ($filterType == IMG_FILTER_BRIGHTNESS || $filterType == IMG_FILTER_CONTRAST || $filterType == IMG_FILTER_SMOOTH) { + imagefilter($this->image, $filterType, $arg1); + } elseif ($filterType == IMG_FILTER_PIXELATE) { + imagefilter($this->image, $filterType, $arg1, $arg2); + } else { + imagefilter($this->image, $filterType); + } + + if ($recursive) { + + $layers = $this->layers; + + foreach($layers as $layerId => $layer) { + $this->layers[$layerId]->applyFilter($filterType, $arg1, $arg2, $arg3, $arg4, true); + } + } + } + + /** + * Apply horizontal or vertical flip (Transformation) + * + * @param string $type + */ + public function flip($type = 'horizontal') + { + $layers = $this->layers; + + foreach ($layers as $key => $layer) { + + $layer->flip($type); + $this->layers[$key] = $layer; + } + + $temp = ImageWorkshopLib::generateImage($this->width, $this->height); + + if ($type == 'horizontal') { + + imagecopyresampled($temp, $this->image, 0, 0, $this->width - 1, 0, $this->width, $this->height, -$this->width, $this->height); + $this->image = $temp; + + foreach ($this->layerPositions as $layerId => $layerPositions) { + + $this->changePosition($layerId, $this->width - $this->layers[$layerId]->getWidth() - $layerPositions['x'], $layerPositions['y']); + } + + } elseif ($type == 'vertical') { + + imagecopyresampled($temp, $this->image, 0, 0, 0, $this->height - 1, $this->width, $this->height, $this->width, -$this->height); + $this->image = $temp; + + foreach ($this->layerPositions as $layerId => $layerPositions) { + + $this->changePosition($layerId, $layerPositions['x'], $this->height - $this->layers[$layerId]->getHeight() - $layerPositions['y']); + } + } + + unset($temp); + } + + /** + * Add a text on the background image of the layer using a default font registered in GD + * + * @param string $text + * @param integer $font + * @param string $color + * @param integer $positionX + * @param integer $positionY + * @param string $align + */ + public function writeText($text, $font = 1, $color = 'ffffff', $positionX = 0, $positionY = 0, $align = 'horizontal') + { + $RGBTextColor = ImageWorkshopLib::convertHexToRGB($color); + $textColor = imagecolorallocate($this->image, $RGBTextColor['R'], $RGBTextColor['G'], $RGBTextColor['B']); + + if ($align == 'horizontal') { + imagestring($this->image, $font, $positionX, $positionY, $text, $textColor); + } else { + imagestringup($this->image, $font, $positionX, $positionY, $text, $textColor); + } + } + + /** + * Add a text on the background image of the layer using a font localized at $fontPath + * Return the text coordonates + * + * @param string $text + * @param integer $fontPath + * @param integer $fontSize + * @param string $color + * @param integer $positionX + * @param integer $positionY + * @param integer $fontRotation + * + * @return array + */ + public function write($text, $fontPath, $fontSize = 13, $color = 'ffffff', $positionX = 0, $positionY = 0, $fontRotation = 0) + { + if (!file_exists($fontPath)) { + throw new ImageWorkshopLayerException('Can\'t find a font file at this path : "'.$fontPath.'".', static::ERROR_FONT_NOT_FOUND); + } + + $RGBTextColor = ImageWorkshopLib::convertHexToRGB($color); + $textColor = imagecolorallocate($this->image, $RGBTextColor['R'], $RGBTextColor['G'], $RGBTextColor['B']); + + return imagettftext($this->image, $fontSize, $fontRotation, $positionX, $positionY, $textColor, $fontPath, $text); + } + + // Manage the result + // ========================================================= + + /** + * Return a merged resource image + * + * $backgroundColor is really usefull if you want to save a JPG or GIF, because the transparency of the background + * would be remove for a colored background, so you should choose a color like "ffffff" (white) + * + * @param string $backgroundColor + * + * @return resource + */ + public function getResult($backgroundColor = null) + { + $imagesToMerge = array(); + ksort($this->layerLevels); + + foreach ($this->layerLevels as $layerLevel => $layerId) { + + $imagesToMerge[$layerLevel] = $this->layers[$layerId]->getResult(); + + // Layer positions + if ($this->layerPositions[$layerId]['x'] != 0 || $this->layerPositions[$layerId]['y'] != 0) { + + $virginLayoutImageTmp = ImageWorkshopLib::generateImage($this->width, $this->height); + ImageWorkshopLib::mergeTwoImages($virginLayoutImageTmp, $imagesToMerge[$layerLevel], $this->layerPositions[$layerId]['x'], $this->layerPositions[$layerId]['y'], 0, 0); + $imagesToMerge[$layerLevel] = $virginLayoutImageTmp; + unset($virginLayoutImageTmp); + } + } + + $iterator = 1; + $mergedImage = $this->image; + ksort($imagesToMerge); + + foreach ($imagesToMerge as $imageLevel => $image) { + ImageWorkshopLib::mergeTwoImages($mergedImage, $image); + $iterator++; + } + + $opacity = 127; + + if ($backgroundColor && $backgroundColor != 'transparent') { + $opacity = 0; + } + + $backgroundImage = ImageWorkshopLib::generateImage($this->width, $this->height, $backgroundColor, $opacity); + ImageWorkshopLib::mergeTwoImages($backgroundImage, $mergedImage); + $mergedImage = $backgroundImage; + unset($backgroundImage); + + return $mergedImage; + } + + /** + * Save the resulting image at the specified path + * + * $backgroundColor is really usefull if you want to save a JPG or GIF, because the transparency of the background + * would be remove for a colored background, so you should choose a color like "ffffff" (white) + * + * If the file already exists, it will be override ! + * + * $imageQuality is useless for GIF + * + * Ex: $folder = __DIR__."/../web/images/2012" + * $imageName = "butterfly.jpg" + * $createFolders = true + * $imageQuality = 95 + * $backgroundColor = "ffffff" + * + * @param string $folder + * @param string $imageName + * @param boolean $createFolders + * @param string $backgroundColor + * @param integer $imageQuality + * @param boolean $interlace + */ + public function save($folder, $imageName, $createFolders = true, $backgroundColor = null, $imageQuality = 75, $interlace = false) + { + if (!is_file($folder)) { + + if (is_dir($folder) || $createFolders) { + + // Creating the folders if they don't exist + if (!is_dir($folder) && $createFolders) { + $oldUmask = umask(0); + mkdir($folder, 0777, true); + umask($oldUmask); + chmod($folder, 0777); + } + + $extension = explode('.', $imageName); + $extension = strtolower($extension[count($extension) - 1]); + + $filename = $folder.'/'.$imageName; + + if (($extension == 'jpg' || $extension == 'jpeg' || $extension == 'gif') && (!$backgroundColor || $backgroundColor == 'transparent')) { + $backgroundColor = 'ffffff'; + } + + $image = $this->getResult($backgroundColor); + + imageinterlace($image, (int) $interlace); + + if ($extension == 'jpg' || $extension == 'jpeg') { + + imagejpeg($image, $filename, $imageQuality); + unset($image); + + } elseif ($extension == 'gif') { + + imagegif($image, $filename); + unset($image); + + } elseif ($extension == 'png') { + + $imageQuality = $imageQuality / 10; + $imageQuality -= 1; + + imagepng($image, $filename, $imageQuality); + unset($image); + } + } + } + } + + // Checkers + // ========================================================= + + /** + * Check if a sublayer exists in the stack for a given id + * + * @param integer $layerId + * + * @return boolean + */ + public function isLayerInIndex($layerId) + { + if (array_key_exists($layerId, $this->layers)) { + return true; + } + + return false; + } + + // Getter / Setter + // ========================================================= + + /** + * Return the narrow side width of the layer + * + * @return integer + */ + public function getNarrowSideWidth() + { + $narrowSideWidth = $this->getWidth(); + + if ($this->getHeight() < $narrowSideWidth) { + $narrowSideWidth = $this->getHeight(); + } + + return $narrowSideWidth; + } + + /** + * Return the largest side width of the layer + * + * @return integer + */ + public function getLargestSideWidth() + { + $largestSideWidth = $this->getWidth(); + + if ($this->getHeight() > $largestSideWidth) { + $largestSideWidth = $this->getHeight(); + } + + return $largestSideWidth; + } + + /** + * Get the level of a sublayer + * Return sublayer level if success or false if layer isn't found + * + * @param integer $layerId + * + * @return mixed (integer or boolean) + */ + public function getLayerLevel($layerId) + { + if ($this->isLayerInIndex($layerId)) { // if the layer exists in document + return array_search($layerId, $this->layerLevels); + } + + return false; + } + + /** + * Get a sublayer in the stack + * Don't forget to use clone method: $b = clone $a->getLayer(3); + * + * @param integer $layerId + * + * @return ImageWorkshop + */ + public function getLayer($layerId) + { + return $this->layers[$layerId]; + } + + /** + * Getter width + * + * @return integer + */ + public function getWidth() + { + return $this->width; + } + + /** + * Getter height + * + * @return integer + */ + public function getHeight() + { + return $this->height; + } + + /** + * Getter image + * + * @return resource + */ + public function getImage() + { + return $this->image; + } + + /** + * Getter layers + * + * @return array + */ + public function getLayers() + { + return $this->layers; + } + + /** + * Getter layerLevels + * + * @return array + */ + public function getLayerLevels() + { + return $this->layerLevels; + } + + /** + * Getter layerPositions + * + * Get all the positions of the sublayers, + * or when specifying $layerId, get the position of this sublayer + * + * @param integer $layerId + * + * @return mixed (array or boolean) + */ + public function getLayerPositions($layerId = null) + { + if (!$layerId) { + + return $this->layerPositions; + + } elseif ($this->isLayerInIndex($layerId)) { // if the sublayer exists in the stack + + return $this->layerPositions[$layerId]; + } + + return false; + } + + /** + * Getter highestLayerLevel + * + * @return array + */ + public function getHighestLayerLevel() + { + return $this->highestLayerLevel; + } + + /** + * Getter lastLayerId + * + * @return array + */ + public function getLastLayerId() + { + return $this->lastLayerId; + } + + // Internals + // ========================================================= + + /** + * Delete the current object + */ + public function delete() + { + imagedestroy($this->image); + $this->clearStack(); + } + + /** + * Create a new background image var from the old background image var + */ + public function createNewVarFromBackgroundImage() + { + $virginImage = ImageWorkshopLib::generateImage($this->getWidth(), $this->getHeight()); // New background image + + ImageWorkshopLib::mergeTwoImages($virginImage, $this->image, 0, 0, 0, 0); + unset($this->image); + + $this->image = $virginImage; + unset($virginImage); + + $layers = $this->layers; + + foreach($layers as $layerId => $layer) { + $this->layers[$layerId] = clone $this->layers[$layerId]; + } + } + + /** + * Index a sublayer in the layer stack + * Return an array containing the generated sublayer id and its final level: + * array("layerLevel" => integer, "id" => integer) + * + * @param integer $layerLevel + * @param ImageWorkshopLayer $layer + * @param integer $positionX + * @param integer $positionY + * @param string $position + * + * @return array + */ + protected function indexLayer($layerLevel, $layer, $positionX = 0, $positionY = 0, $position) + { + // Choose an id for the added layer + $layerId = $this->lastLayerId + 1; + + // Clone $layer to duplicate image resource var + $layer = clone $layer; + + // Add the layer in the stack + $this->layers[$layerId] = $layer; + + // Add the layer positions in the main layer + $this->layerPositions[$layerId] = ImageWorkshopLib::calculatePositions($this->getWidth(), $this->getHeight(), $layer->getWidth(), $layer->getHeight(), $positionX, $positionY, $position); + + // Update the lastLayerId of the workshop + $this->lastLayerId = $layerId; + + // Add the layer level in the stack + $layerLevel = $this->indexLevelInDocument($layerLevel, $layerId); + + return array( + 'layerLevel' => $layerLevel, + 'id' => $layerId, + ); + } + + /** + * Index a layer level and update the layers levels in the document + * Return the corrected level of the layer + * + * @param integer $layerLevel + * @param integer $layerId + * + * @return integer + */ + protected function indexLevelInDocument($layerLevel, $layerId) + { + if (array_key_exists($layerLevel, $this->layerLevels)) { // Level already exists + + ksort($this->layerLevels); // All layers after this level and the layer which have this level are updated + $layerLevelsTmp = $this->layerLevels; + + foreach ($layerLevelsTmp as $levelTmp => $layerIdTmp) { + if ($levelTmp >= $layerLevel) { + $this->layerLevels[$levelTmp + 1] = $layerIdTmp; + } + } + + unset($layerLevelsTmp); + + } else { // Level isn't taken + if ($this->highestLayerLevel < $layerLevel) { // If given level is too high, proceed adjustement + $layerLevel = $this->highestLayerLevel + 1; + } + } + + $this->layerLevels[$layerLevel] = $layerId; + $this->highestLayerLevel = max(array_flip($this->layerLevels)); // Update $highestLayerLevel + + return $layerLevel; + } + + /** + * Update the positions of layers in the stack after cropping + * + * @param integer $positionX + * @param integer $positionY + */ + public function updateLayerPositionsAfterCropping($positionX, $positionY) + { + foreach ($this->layers as $layerId => $layer) { + + $oldLayerPosX = $this->layerPositions[$layerId]['x']; + $oldLayerPosY = $this->layerPositions[$layerId]['y']; + + $newLayerPosX = $oldLayerPosX + $positionX; + $newLayerPosY = $oldLayerPosY + $positionY; + + $this->changePosition($layerId, $newLayerPosX, $newLayerPosY); + } + } + + /** + * Resize the background of a layer + * + * @param integer $newWidth + * @param integer $newHeight + */ + public function resizeBackground($newWidth, $newHeight) + { + $oldWidth = $this->width; + $oldHeight = $this->height; + + $this->width = $newWidth; + $this->height = $newHeight; + + $virginLayoutImage = ImageWorkshopLib::generateImage($this->width, $this->height); + + imagecopyresampled($virginLayoutImage, $this->image, 0, 0, 0, 0, $this->width, $this->height, $oldWidth, $oldHeight); + + unset($this->image); + $this->image = $virginLayoutImage; + } + + // Deprecated, don't use anymore + // ========================================================= + + /** + * @deprecated + */ + public function resizeInPourcent($percentWidth = null, $percentHeight = null, $converseProportion = false, $positionX = 0, $positionY = 0, $position = 'MM') + { + throw new ImageWorkshopLayerException('Method resizeInPourcent() was renamed resizeInPercent(). Use resizeInPercent() instead.', static::METHOD_DEPRECATED); + } + + /** + * @deprecated + */ + public function resizeByLargestSideInPourcent($newLargestSideWidth, $converseProportion = false) + { + throw new ImageWorkshopLayerException('Method resizeByLargestSideInPourcent() was renamed resizeByLargestSideInPercent(). Use resizeByLargestSideInPercent() instead.', static::METHOD_DEPRECATED); + } + + /** + * @deprecated + */ + public function resizeByNarrowSideInPourcent($newNarrowSideWidth, $converseProportion = false) + { + throw new ImageWorkshopLayerException('Method resizeByNarrowSideInPourcent() was renamed resizeByNarrowSideInPercent(). Use resizeByNarrowSideInPercent() instead.', static::METHOD_DEPRECATED); + } + + /** + * @deprecated + */ + public function cropInPourcent($percentWidth = 0, $percentHeight = 0, $positionXPercent = 0, $positionYPercent = 0, $position = 'LT') + { + throw new ImageWorkshopLayerException('Method cropInPourcent() was renamed cropInPercent(). Use cropInPercent() instead.', static::METHOD_DEPRECATED); + } + + /** + * @deprecated + */ + public function cropMaximumInPourcent($positionXPercent = 0, $positionYPercent = 0, $position = 'LT') + { + throw new ImageWorkshopLayerException('Method cropMaximumInPourcent() was renamed cropMaximumInPercent(). Use cropMaximumInPercent() instead.', static::METHOD_DEPRECATED); + } +} diff --git a/PHPImageWorkshop/Core/ImageWorkshopLib.php b/PHPImageWorkshop/Core/ImageWorkshopLib.php new file mode 100644 index 0000000..ed928ee --- /dev/null +++ b/PHPImageWorkshop/Core/ImageWorkshopLib.php @@ -0,0 +1,299 @@ + $layerPositionX, + 'y' => $layerPositionY, + ); + } + + /** + * Convert Hex color to RGB color format + * + * @param string $hex + * + * @return array + */ + public static function convertHexToRGB($hex) + { + return array( + 'R' => (int) base_convert(substr($hex, 0, 2), 16, 10), + 'G' => (int) base_convert(substr($hex, 2, 2), 16, 10), + 'B' => (int) base_convert(substr($hex, 4, 2), 16, 10), + ); + } + + /** + * Generate a new image resource var + * + * @param integer $width + * @param integer $height + * @param string $color + * @param integer $opacity + * + * @return resource + */ + public static function generateImage($width = 100, $height = 100, $color = 'ffffff', $opacity = 127) + { + $RGBColors = ImageWorkshopLib::convertHexToRGB($color); + + $image = imagecreatetruecolor($width, $height); + imagesavealpha($image, true); + $color = imagecolorallocatealpha($image, $RGBColors['R'], $RGBColors['G'], $RGBColors['B'], $opacity); + imagefill($image, 0, 0, $color); + + return $image; + } + + /** + * Return dimension of a text + * + * @param $fontSize + * @param $fontAngle + * @param $fontFile + * @param $text + * + * @return array or boolean + */ + public static function getTextBoxDimension($fontSize, $fontAngle, $fontFile, $text) + { + if (!file_exists($fontFile)) { + throw new ImageWorkshopLibException('Can\'t find a font file at this path : "'.$fontFile.'".', static::ERROR_FONT_NOT_FOUND); + } + + $box = imagettfbbox($fontSize, $fontAngle, $fontFile, $text); + + if (!$box) { + + return false; + } + + $minX = min(array($box[0], $box[2], $box[4], $box[6])); + $maxX = max(array($box[0], $box[2], $box[4], $box[6])); + $minY = min(array($box[1], $box[3], $box[5], $box[7])); + $maxY = max(array($box[1], $box[3], $box[5], $box[7])); + $width = ($maxX - $minX); + $height = ($maxY - $minY); + $left = abs($minX) + $width; + $top = abs($minY) + $height; + + // to calculate the exact bounding box, we write the text in a large image + $img = @imagecreatetruecolor($width << 2, $height << 2); + $white = imagecolorallocate($img, 255, 255, 255); + $black = imagecolorallocate($img, 0, 0, 0); + imagefilledrectangle($img, 0, 0, imagesx($img), imagesy($img), $black); + + // for ensure that the text is completely in the image + imagettftext($img, $fontSize, $fontAngle, $left, $top, $white, $fontFile, $text); + + // start scanning (0=> black => empty) + $rleft = $w4 = $width<<2; + $rright = 0; + $rbottom = 0; + $rtop = $h4 = $height<<2; + + for ($x = 0; $x < $w4; $x++) { + + for ($y = 0; $y < $h4; $y++) { + + if (imagecolorat($img, $x, $y)) { + + $rleft = min($rleft, $x); + $rright = max($rright, $x); + $rtop = min($rtop, $y); + $rbottom = max($rbottom, $y); + } + } + } + + imagedestroy($img); + + return array( + 'left' => $left - $rleft, + 'top' => $top - $rtop, + 'width' => $rright - $rleft + 1, + 'height' => $rbottom - $rtop + 1, + ); + } + + /** + * Copy an image on another one and converse transparency + * + * @param resource $destImg + * @param resource $srcImg + * @param integer $destX + * @param integer $destY + * @param integer $srcX + * @param integer $srcY + * @param integer $srcW + * @param integer $srcH + * @param integer $pct + */ + public static function imageCopyMergeAlpha(&$destImg, &$srcImg, $destX, $destY, $srcX, $srcY, $srcW, $srcH, $pct = 0) + { + $destX = (int) $destX; + $destY = (int) $destY; + $srcX = (int) $srcX; + $srcY = (int) $srcY; + $srcW = (int) $srcW; + $srcH = (int) $srcH; + $pct = (int) $pct; + $destW = imageSX($destImg); + $destH = imageSY($destImg); + + for ($y = 0; $y < $srcH + $srcY; $y++) { + + for ($x = 0; $x < $srcW + $srcX; $x++) { + + if ($x + $destX >= 0 && $x + $destX < $destW && $x + $srcX >= 0 && $x + $srcX < $srcW && $y + $destY >= 0 && $y + $destY < $destH && $y + $srcY >= 0 && $y + $srcY < $srcH) { + + $destPixel = imageColorsForIndex($destImg, imageColorat($destImg, $x + $destX, $y + $destY)); + $srcImgColorat = imageColorat($srcImg, $x + $srcX, $y + $srcY); + + if ($srcImgColorat >= 0) { + + $srcPixel = imageColorsForIndex($srcImg, $srcImgColorat); + + $srcAlpha = 1 - ($srcPixel['alpha'] / 127); + $destAlpha = 1 - ($destPixel['alpha'] / 127); + $opacity = $srcAlpha * $pct / 100; + + if ($destAlpha >= $opacity) { + $alpha = $destAlpha; + } + + if ($destAlpha < $opacity) { + $alpha = $opacity; + } + + if ($alpha > 1) { + $alpha = 1; + } + + if ($opacity > 0) { + + $destRed = round((($destPixel['red'] * $destAlpha * (1 - $opacity)))); + $destGreen = round((($destPixel['green'] * $destAlpha * (1 - $opacity)))); + $destBlue = round((($destPixel['blue'] * $destAlpha * (1 - $opacity)))); + $srcRed = round((($srcPixel['red'] * $opacity))); + $srcGreen = round((($srcPixel['green'] * $opacity))); + $srcBlue = round((($srcPixel['blue'] * $opacity))); + $red = round(($destRed + $srcRed ) / ($destAlpha * (1 - $opacity) + $opacity)); + $green = round(($destGreen + $srcGreen) / ($destAlpha * (1 - $opacity) + $opacity)); + $blue = round(($destBlue + $srcBlue ) / ($destAlpha * (1 - $opacity) + $opacity)); + + if ($red > 255) { + $red = 255; + } + + if ($green > 255) { + $green = 255; + } + + if ($blue > 255) { + $blue = 255; + } + + $alpha = round((1 - $alpha) * 127); + $color = imageColorAllocateAlpha($destImg, $red, $green, $blue, $alpha); + imageSetPixel($destImg, $x + $destX, $y + $destY, $color); + } + } + } + } + } + } + + /** + * Merge two image var + * + * @param resource $destinationImage + * @param resource $sourceImage + * @param integer $destinationPosX + * @param integer $destinationPosY + * @param integer $sourcePosX + * @param integer $sourcePosY + */ + public static function mergeTwoImages(&$destinationImage, $sourceImage, $destinationPosX = 0, $destinationPosY = 0, $sourcePosX = 0, $sourcePosY = 0) + { + imageCopy($destinationImage, $sourceImage, $destinationPosX, $destinationPosY, $sourcePosX, $sourcePosY, imageSX($sourceImage), imageSY($sourceImage)); + } +} \ No newline at end of file diff --git a/PHPImageWorkshop/Exception/ImageWorkshopBaseException.php b/PHPImageWorkshop/Exception/ImageWorkshopBaseException.php new file mode 100644 index 0000000..81ed653 --- /dev/null +++ b/PHPImageWorkshop/Exception/ImageWorkshopBaseException.php @@ -0,0 +1,38 @@ +code}]: {$this->message}\n"; + } +} \ No newline at end of file diff --git a/PHPImageWorkshop/Exception/ImageWorkshopException.php b/PHPImageWorkshop/Exception/ImageWorkshopException.php new file mode 100644 index 0000000..c2efa97 --- /dev/null +++ b/PHPImageWorkshop/Exception/ImageWorkshopException.php @@ -0,0 +1,22 @@ +write($text, $fontPath, $fontSize, $fontColor, $textDimensions['left'], $textDimensions['top'], $textRotation); + + return $layer; + } + + /** + * Initialize a new virgin layer + * + * @param integer $width + * @param integer $height + * @param string $backgroundColor + * + * @return ImageWorkshopLayer + */ + public static function initVirginLayer($width = 100, $height = 100, $backgroundColor = null) + { + $opacity = 0; + + if (!$backgroundColor || $backgroundColor == 'transparent') { + $opacity = 127; + $backgroundColor = 'ffffff'; + } + + return new ImageWorkshopLayer(ImageWorkshopLib::generateImage($width, $height, $backgroundColor, $opacity)); + } + + /** + * Initialize a layer from a resource image var + * + * @param \resource $image + * + * @return ImageWorkshopLayer + */ + public static function initFromResourceVar($image) + { + return new ImageWorkshopLayer($image); + } + + /** + * Initialize a layer from a string (obtains with file_get_contents, cURL...) + * + * This not recommanded to initialize JPEG string with this method, GD displays bugs ! + * + * @param string $imageString + * + * @return ImageWorkshopLayer + */ + public static function initFromString($imageString) + { + if (!$image = @imageCreateFromString($imageString)) { + throw new ImageWorkshopException('Can\'t generate an image from the given string.', static::ERROR_CREATE_IMAGE_FROM_STRING); + } + + return new ImageWorkshopLayer($image); + } +} \ No newline at end of file diff --git a/Slim/Environment.php b/Slim/Environment.php new file mode 100644 index 0000000..a15e1e4 --- /dev/null +++ b/Slim/Environment.php @@ -0,0 +1,224 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim; + +/** + * Environment + * + * This class creates and returns a key/value array of common + * environment variables for the current HTTP request. + * + * This is a singleton class; derived environment variables will + * be common across multiple Slim applications. + * + * This class matches the Rack (Ruby) specification as closely + * as possible. More information available below. + * + * @package Slim + * @author Josh Lockhart + * @since 1.6.0 + */ +class Environment implements \ArrayAccess, \IteratorAggregate +{ + /** + * @var array + */ + protected $properties; + + /** + * @var \Slim\Environment + */ + protected static $environment; + + /** + * Get environment instance (singleton) + * + * This creates and/or returns an environment instance (singleton) + * derived from $_SERVER variables. You may override the global server + * variables by using `\Slim\Environment::mock()` instead. + * + * @param bool $refresh Refresh properties using global server variables? + * @return \Slim\Environment + */ + public static function getInstance($refresh = false) + { + if (is_null(self::$environment) || $refresh) { + self::$environment = new self(); + } + + return self::$environment; + } + + /** + * Get mock environment instance + * + * @param array $userSettings + * @return \Slim\Environment + */ + public static function mock($userSettings = array()) + { + $defaults = array( + 'REQUEST_METHOD' => 'GET', + 'SCRIPT_NAME' => '', + 'PATH_INFO' => '', + 'QUERY_STRING' => '', + 'SERVER_NAME' => 'localhost', + 'SERVER_PORT' => 80, + 'ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + 'ACCEPT_LANGUAGE' => 'en-US,en;q=0.8', + 'ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', + 'USER_AGENT' => 'Slim Framework', + 'REMOTE_ADDR' => '127.0.0.1', + 'slim.url_scheme' => 'http', + 'slim.input' => '', + 'slim.errors' => @fopen('php://stderr', 'w') + ); + self::$environment = new self(array_merge($defaults, $userSettings)); + + return self::$environment; + } + + /** + * Constructor (private access) + * + * @param array|null $settings If present, these are used instead of global server variables + */ + private function __construct($settings = null) + { + if ($settings) { + $this->properties = $settings; + } else { + $env = array(); + + //The HTTP request method + $env['REQUEST_METHOD'] = $_SERVER['REQUEST_METHOD']; + + //The IP + $env['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR']; + + // Server params + $scriptName = $_SERVER['SCRIPT_NAME']; // <-- "/foo/index.php" + $requestUri = $_SERVER['REQUEST_URI']; // <-- "/foo/bar?test=abc" or "/foo/index.php/bar?test=abc" + $queryString = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : ''; // <-- "test=abc" or "" + + // Physical path + if (strpos($requestUri, $scriptName) !== false) { + $physicalPath = $scriptName; // <-- Without rewriting + } else { + $physicalPath = str_replace('\\', '', dirname($scriptName)); // <-- With rewriting + } + $env['SCRIPT_NAME'] = rtrim($physicalPath, '/'); // <-- Remove trailing slashes + + // Virtual path + $env['PATH_INFO'] = substr_replace($requestUri, '', 0, strlen($physicalPath)); // <-- Remove physical path + $env['PATH_INFO'] = str_replace('?' . $queryString, '', $env['PATH_INFO']); // <-- Remove query string + $env['PATH_INFO'] = '/' . ltrim($env['PATH_INFO'], '/'); // <-- Ensure leading slash + + // Query string (without leading "?") + $env['QUERY_STRING'] = $queryString; + + //Name of server host that is running the script + $env['SERVER_NAME'] = $_SERVER['SERVER_NAME']; + + //Number of server port that is running the script + $env['SERVER_PORT'] = $_SERVER['SERVER_PORT']; + + //HTTP request headers (retains HTTP_ prefix to match $_SERVER) + $headers = \Slim\Http\Headers::extract($_SERVER); + foreach ($headers as $key => $value) { + $env[$key] = $value; + } + + //Is the application running under HTTPS or HTTP protocol? + $env['slim.url_scheme'] = empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off' ? 'http' : 'https'; + + //Input stream (readable one time only; not available for multipart/form-data requests) + $rawInput = @file_get_contents('php://input'); + if (!$rawInput) { + $rawInput = ''; + } + $env['slim.input'] = $rawInput; + + //Error stream + $env['slim.errors'] = @fopen('php://stderr', 'w'); + + $this->properties = $env; + } + } + + /** + * Array Access: Offset Exists + */ + public function offsetExists($offset) + { + return isset($this->properties[$offset]); + } + + /** + * Array Access: Offset Get + */ + public function offsetGet($offset) + { + if (isset($this->properties[$offset])) { + return $this->properties[$offset]; + } else { + return null; + } + } + + /** + * Array Access: Offset Set + */ + public function offsetSet($offset, $value) + { + $this->properties[$offset] = $value; + } + + /** + * Array Access: Offset Unset + */ + public function offsetUnset($offset) + { + unset($this->properties[$offset]); + } + + /** + * IteratorAggregate + * + * @return \ArrayIterator + */ + public function getIterator() + { + return new \ArrayIterator($this->properties); + } +} diff --git a/Slim/Exception/Pass.php b/Slim/Exception/Pass.php new file mode 100644 index 0000000..99d95c2 --- /dev/null +++ b/Slim/Exception/Pass.php @@ -0,0 +1,49 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Exception; + +/** + * Pass Exception + * + * This Exception will cause the Router::dispatch method + * to skip the current matching route and continue to the next + * matching route. If no subsequent routes are found, a + * HTTP 404 Not Found response will be sent to the client. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class Pass extends \Exception +{ +} diff --git a/Slim/Exception/Stop.php b/Slim/Exception/Stop.php new file mode 100644 index 0000000..a251851 --- /dev/null +++ b/Slim/Exception/Stop.php @@ -0,0 +1,47 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Exception; + +/** + * Stop Exception + * + * This Exception is thrown when the Slim application needs to abort + * processing and return control flow to the outer PHP script. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class Stop extends \Exception +{ +} diff --git a/Slim/Helper/Set.php b/Slim/Helper/Set.php new file mode 100644 index 0000000..9538b69 --- /dev/null +++ b/Slim/Helper/Set.php @@ -0,0 +1,246 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Helper; + +class Set implements \ArrayAccess, \Countable, \IteratorAggregate +{ + /** + * Key-value array of arbitrary data + * @var array + */ + protected $data = array(); + + /** + * Constructor + * @param array $items Pre-populate set with this key-value array + */ + public function __construct($items = array()) + { + $this->replace($items); + } + + /** + * Normalize data key + * + * Used to transform data key into the necessary + * key format for this set. Used in subclasses + * like \Slim\Http\Headers. + * + * @param string $key The data key + * @return mixed The transformed/normalized data key + */ + protected function normalizeKey($key) + { + return $key; + } + + /** + * Set data key to value + * @param string $key The data key + * @param mixed $value The data value + */ + public function set($key, $value) + { + $this->data[$this->normalizeKey($key)] = $value; + } + + /** + * Get data value with key + * @param string $key The data key + * @param mixed $default The value to return if data key does not exist + * @return mixed The data value, or the default value + */ + public function get($key, $default = null) + { + if ($this->has($key)) { + $isInvokable = is_object($this->data[$this->normalizeKey($key)]) && method_exists($this->data[$this->normalizeKey($key)], '__invoke'); + + return $isInvokable ? $this->data[$this->normalizeKey($key)]($this) : $this->data[$this->normalizeKey($key)]; + } + + return $default; + } + + /** + * Add data to set + * @param array $items Key-value array of data to append to this set + */ + public function replace($items) + { + foreach ($items as $key => $value) { + $this->set($key, $value); // Ensure keys are normalized + } + } + + /** + * Fetch set data + * @return array This set's key-value data array + */ + public function all() + { + return $this->data; + } + + /** + * Fetch set data keys + * @return array This set's key-value data array keys + */ + public function keys() + { + return array_keys($this->data); + } + + /** + * Does this set contain a key? + * @param string $key The data key + * @return boolean + */ + public function has($key) + { + return array_key_exists($this->normalizeKey($key), $this->data); + } + + /** + * Remove value with key from this set + * @param string $key The data key + */ + public function remove($key) + { + unset($this->data[$this->normalizeKey($key)]); + } + + /** + * Property Overloading + */ + + public function __get($key) + { + return $this->get($key); + } + + public function __set($key, $value) + { + $this->set($key, $value); + } + + public function __isset($key) + { + return $this->has($key); + } + + public function __unset($key) + { + return $this->remove($key); + } + + /** + * Clear all values + */ + public function clear() + { + $this->data = array(); + } + + /** + * Array Access + */ + + public function offsetExists($offset) + { + return $this->has($offset); + } + + public function offsetGet($offset) + { + return $this->get($offset); + } + + public function offsetSet($offset, $value) + { + $this->set($offset, $value); + } + + public function offsetUnset($offset) + { + $this->remove($offset); + } + + /** + * Countable + */ + + public function count() + { + return count($this->data); + } + + /** + * IteratorAggregate + */ + + public function getIterator() + { + return new \ArrayIterator($this->data); + } + + /** + * Ensure a value or object will remain globally unique + * @param string $key The value or object name + * @param Closure The closure that defines the object + * @return mixed + */ + public function singleton($key, $value) + { + $this->set($key, function ($c) use ($value) { + static $object; + + if (null === $object) { + $object = $value($c); + } + + return $object; + }); + } + + /** + * Protect closure from being directly invoked + * @param Closure $callable A closure to keep from being invoked and evaluated + * @return Closure + */ + public function protect(\Closure $callable) + { + return function () use ($callable) { + return $callable; + }; + } +} diff --git a/Slim/Http/Cookies.php b/Slim/Http/Cookies.php new file mode 100644 index 0000000..cf13801 --- /dev/null +++ b/Slim/Http/Cookies.php @@ -0,0 +1,91 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Http; + +class Cookies extends \Slim\Helper\Set +{ + /** + * Default cookie settings + * @var array + */ + protected $defaults = array( + 'value' => '', + 'domain' => null, + 'path' => null, + 'expires' => null, + 'secure' => false, + 'httponly' => false + ); + + /** + * Set cookie + * + * The second argument may be a single scalar value, in which case + * it will be merged with the default settings and considered the `value` + * of the merged result. + * + * The second argument may also be an array containing any or all of + * the keys shown in the default settings above. This array will be + * merged with the defaults shown above. + * + * @param string $key Cookie name + * @param mixed $value Cookie settings + */ + public function set($key, $value) + { + if (is_array($value)) { + $cookieSettings = array_replace($this->defaults, $value); + } else { + $cookieSettings = array_replace($this->defaults, array('value' => $value)); + } + parent::set($key, $cookieSettings); + } + + /** + * Remove cookie + * + * Unlike \Slim\Helper\Set, this will actually *set* a cookie with + * an expiration date in the past. This expiration date will force + * the client-side cache to remove its cookie with the given name + * and settings. + * + * @param string $key Cookie name + * @param array $settings Optional cookie settings + */ + public function remove($key, $settings = array()) + { + $settings['value'] = ''; + $settings['expires'] = time() - 86400; + $this->set($key, array_replace($this->defaults, $settings)); + } +} diff --git a/Slim/Http/Headers.php b/Slim/Http/Headers.php new file mode 100644 index 0000000..1704b80 --- /dev/null +++ b/Slim/Http/Headers.php @@ -0,0 +1,104 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Http; + + /** + * HTTP Headers + * + * @package Slim + * @author Josh Lockhart + * @since 1.6.0 + */ +class Headers extends \Slim\Helper\Set +{ + /******************************************************************************** + * Static interface + *******************************************************************************/ + + /** + * Special-case HTTP headers that are otherwise unidentifiable as HTTP headers. + * Typically, HTTP headers in the $_SERVER array will be prefixed with + * `HTTP_` or `X_`. These are not so we list them here for later reference. + * + * @var array + */ + protected static $special = array( + 'CONTENT_TYPE', + 'CONTENT_LENGTH', + 'PHP_AUTH_USER', + 'PHP_AUTH_PW', + 'PHP_AUTH_DIGEST', + 'AUTH_TYPE' + ); + + /** + * Extract HTTP headers from an array of data (e.g. $_SERVER) + * @param array $data + * @return array + */ + public static function extract($data) + { + $results = array(); + foreach ($data as $key => $value) { + $key = strtoupper($key); + if (strpos($key, 'X_') === 0 || strpos($key, 'HTTP_') === 0 || in_array($key, static::$special)) { + if ($key === 'HTTP_CONTENT_LENGTH') { + continue; + } + $results[$key] = $value; + } + } + + return $results; + } + + /******************************************************************************** + * Instance interface + *******************************************************************************/ + + /** + * Transform header name into canonical form + * @param string $key + * @return string + */ + protected function normalizeKey($key) + { + $key = strtolower($key); + $key = str_replace(array('-', '_'), ' ', $key); + $key = preg_replace('#^http #', '', $key); + $key = ucwords($key); + $key = str_replace(' ', '-', $key); + + return $key; + } +} diff --git a/Slim/Http/Request.php b/Slim/Http/Request.php new file mode 100644 index 0000000..735484b --- /dev/null +++ b/Slim/Http/Request.php @@ -0,0 +1,617 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Http; + +/** + * Slim HTTP Request + * + * This class provides a human-friendly interface to the Slim environment variables; + * environment variables are passed by reference and will be modified directly. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class Request +{ + const METHOD_HEAD = 'HEAD'; + const METHOD_GET = 'GET'; + const METHOD_POST = 'POST'; + const METHOD_PUT = 'PUT'; + const METHOD_PATCH = 'PATCH'; + const METHOD_DELETE = 'DELETE'; + const METHOD_OPTIONS = 'OPTIONS'; + const METHOD_OVERRIDE = '_METHOD'; + + /** + * @var array + */ + protected static $formDataMediaTypes = array('application/x-www-form-urlencoded'); + + /** + * Application Environment + * @var \Slim\Environment + */ + protected $env; + + /** + * HTTP Headers + * @var \Slim\Http\Headers + */ + public $headers; + + /** + * HTTP Cookies + * @var \Slim\Helper\Set + */ + public $cookies; + + /** + * Constructor + * @param \Slim\Environment $env + */ + public function __construct(\Slim\Environment $env) + { + $this->env = $env; + $this->headers = new \Slim\Http\Headers(\Slim\Http\Headers::extract($env)); + $this->cookies = new \Slim\Helper\Set(\Slim\Http\Util::parseCookieHeader($env['HTTP_COOKIE'])); + } + + /** + * Get HTTP method + * @return string + */ + public function getMethod() + { + return $this->env['REQUEST_METHOD']; + } + + /** + * Is this a GET request? + * @return bool + */ + public function isGet() + { + return $this->getMethod() === self::METHOD_GET; + } + + /** + * Is this a POST request? + * @return bool + */ + public function isPost() + { + return $this->getMethod() === self::METHOD_POST; + } + + /** + * Is this a PUT request? + * @return bool + */ + public function isPut() + { + return $this->getMethod() === self::METHOD_PUT; + } + + /** + * Is this a PATCH request? + * @return bool + */ + public function isPatch() + { + return $this->getMethod() === self::METHOD_PATCH; + } + + /** + * Is this a DELETE request? + * @return bool + */ + public function isDelete() + { + return $this->getMethod() === self::METHOD_DELETE; + } + + /** + * Is this a HEAD request? + * @return bool + */ + public function isHead() + { + return $this->getMethod() === self::METHOD_HEAD; + } + + /** + * Is this a OPTIONS request? + * @return bool + */ + public function isOptions() + { + return $this->getMethod() === self::METHOD_OPTIONS; + } + + /** + * Is this an AJAX request? + * @return bool + */ + public function isAjax() + { + if ($this->params('isajax')) { + return true; + } elseif (isset($this->headers['X_REQUESTED_WITH']) && $this->headers['X_REQUESTED_WITH'] === 'XMLHttpRequest') { + return true; + } else { + return false; + } + } + + /** + * Is this an XHR request? (alias of Slim_Http_Request::isAjax) + * @return bool + */ + public function isXhr() + { + return $this->isAjax(); + } + + /** + * Fetch GET and POST data + * + * This method returns a union of GET and POST data as a key-value array, or the value + * of the array key if requested; if the array key does not exist, NULL is returned, + * unless there is a default value specified. + * + * @param string $key + * @param mixed $default + * @return array|mixed|null + */ + public function params($key = null, $default = null) + { + $union = array_merge($this->get(), $this->post()); + if ($key) { + return isset($union[$key]) ? $union[$key] : $default; + } + + return $union; + } + + /** + * Fetch GET data + * + * This method returns a key-value array of data sent in the HTTP request query string, or + * the value of the array key if requested; if the array key does not exist, NULL is returned. + * + * @param string $key + * @param mixed $default Default return value when key does not exist + * @return array|mixed|null + */ + public function get($key = null, $default = null) + { + if (!isset($this->env['slim.request.query_hash'])) { + $output = array(); + if (function_exists('mb_parse_str') && !isset($this->env['slim.tests.ignore_multibyte'])) { + mb_parse_str($this->env['QUERY_STRING'], $output); + } else { + parse_str($this->env['QUERY_STRING'], $output); + } + $this->env['slim.request.query_hash'] = Util::stripSlashesIfMagicQuotes($output); + } + if ($key) { + if (isset($this->env['slim.request.query_hash'][$key])) { + return $this->env['slim.request.query_hash'][$key]; + } else { + return $default; + } + } else { + return $this->env['slim.request.query_hash']; + } + } + + /** + * Fetch POST data + * + * This method returns a key-value array of data sent in the HTTP request body, or + * the value of a hash key if requested; if the array key does not exist, NULL is returned. + * + * @param string $key + * @param mixed $default Default return value when key does not exist + * @return array|mixed|null + * @throws \RuntimeException If environment input is not available + */ + public function post($key = null, $default = null) + { + if (!isset($this->env['slim.input'])) { + throw new \RuntimeException('Missing slim.input in environment variables'); + } + if (!isset($this->env['slim.request.form_hash'])) { + $this->env['slim.request.form_hash'] = array(); + if ($this->isFormData() && is_string($this->env['slim.input'])) { + $output = array(); + if (function_exists('mb_parse_str') && !isset($this->env['slim.tests.ignore_multibyte'])) { + mb_parse_str($this->env['slim.input'], $output); + } else { + parse_str($this->env['slim.input'], $output); + } + $this->env['slim.request.form_hash'] = Util::stripSlashesIfMagicQuotes($output); + } else { + $this->env['slim.request.form_hash'] = Util::stripSlashesIfMagicQuotes($_POST); + } + } + if ($key) { + if (isset($this->env['slim.request.form_hash'][$key])) { + return $this->env['slim.request.form_hash'][$key]; + } else { + return $default; + } + } else { + return $this->env['slim.request.form_hash']; + } + } + + /** + * Fetch PUT data (alias for \Slim\Http\Request::post) + * @param string $key + * @param mixed $default Default return value when key does not exist + * @return array|mixed|null + */ + public function put($key = null, $default = null) + { + return $this->post($key, $default); + } + + /** + * Fetch PATCH data (alias for \Slim\Http\Request::post) + * @param string $key + * @param mixed $default Default return value when key does not exist + * @return array|mixed|null + */ + public function patch($key = null, $default = null) + { + return $this->post($key, $default); + } + + /** + * Fetch DELETE data (alias for \Slim\Http\Request::post) + * @param string $key + * @param mixed $default Default return value when key does not exist + * @return array|mixed|null + */ + public function delete($key = null, $default = null) + { + return $this->post($key, $default); + } + + /** + * Fetch COOKIE data + * + * This method returns a key-value array of Cookie data sent in the HTTP request, or + * the value of a array key if requested; if the array key does not exist, NULL is returned. + * + * @param string $key + * @return array|string|null + */ + public function cookies($key = null) + { + if ($key) { + return $this->cookies->get($key); + } + + return $this->cookies; + // if (!isset($this->env['slim.request.cookie_hash'])) { + // $cookieHeader = isset($this->env['COOKIE']) ? $this->env['COOKIE'] : ''; + // $this->env['slim.request.cookie_hash'] = Util::parseCookieHeader($cookieHeader); + // } + // if ($key) { + // if (isset($this->env['slim.request.cookie_hash'][$key])) { + // return $this->env['slim.request.cookie_hash'][$key]; + // } else { + // return null; + // } + // } else { + // return $this->env['slim.request.cookie_hash']; + // } + } + + /** + * Does the Request body contain parsed form data? + * @return bool + */ + public function isFormData() + { + $method = isset($this->env['slim.method_override.original_method']) ? $this->env['slim.method_override.original_method'] : $this->getMethod(); + + return ($method === self::METHOD_POST && is_null($this->getContentType())) || in_array($this->getMediaType(), self::$formDataMediaTypes); + } + + /** + * Get Headers + * + * This method returns a key-value array of headers sent in the HTTP request, or + * the value of a hash key if requested; if the array key does not exist, NULL is returned. + * + * @param string $key + * @param mixed $default The default value returned if the requested header is not available + * @return mixed + */ + public function headers($key = null, $default = null) + { + if ($key) { + return $this->headers->get($key, $default); + } + + return $this->headers; + // if ($key) { + // $key = strtoupper($key); + // $key = str_replace('-', '_', $key); + // $key = preg_replace('@^HTTP_@', '', $key); + // if (isset($this->env[$key])) { + // return $this->env[$key]; + // } else { + // return $default; + // } + // } else { + // $headers = array(); + // foreach ($this->env as $key => $value) { + // if (strpos($key, 'slim.') !== 0) { + // $headers[$key] = $value; + // } + // } + // + // return $headers; + // } + } + + /** + * Get Body + * @return string + */ + public function getBody() + { + return $this->env['slim.input']; + } + + /** + * Get Content Type + * @return string|null + */ + public function getContentType() + { + return $this->headers->get('CONTENT_TYPE'); + } + + /** + * Get Media Type (type/subtype within Content Type header) + * @return string|null + */ + public function getMediaType() + { + $contentType = $this->getContentType(); + if ($contentType) { + $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); + + return strtolower($contentTypeParts[0]); + } + + return null; + } + + /** + * Get Media Type Params + * @return array + */ + public function getMediaTypeParams() + { + $contentType = $this->getContentType(); + $contentTypeParams = array(); + if ($contentType) { + $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); + $contentTypePartsLength = count($contentTypeParts); + for ($i = 1; $i < $contentTypePartsLength; $i++) { + $paramParts = explode('=', $contentTypeParts[$i]); + $contentTypeParams[strtolower($paramParts[0])] = $paramParts[1]; + } + } + + return $contentTypeParams; + } + + /** + * Get Content Charset + * @return string|null + */ + public function getContentCharset() + { + $mediaTypeParams = $this->getMediaTypeParams(); + if (isset($mediaTypeParams['charset'])) { + return $mediaTypeParams['charset']; + } + + return null; + } + + /** + * Get Content-Length + * @return int + */ + public function getContentLength() + { + return $this->headers->get('CONTENT_LENGTH', 0); + } + + /** + * Get Host + * @return string + */ + public function getHost() + { + if (isset($this->env['HTTP_HOST'])) { + if (strpos($this->env['HTTP_HOST'], ':') !== false) { + $hostParts = explode(':', $this->env['HTTP_HOST']); + + return $hostParts[0]; + } + + return $this->env['HTTP_HOST']; + } + + return $this->env['SERVER_NAME']; + } + + /** + * Get Host with Port + * @return string + */ + public function getHostWithPort() + { + return sprintf('%s:%s', $this->getHost(), $this->getPort()); + } + + /** + * Get Port + * @return int + */ + public function getPort() + { + return (int)$this->env['SERVER_PORT']; + } + + /** + * Get Scheme (https or http) + * @return string + */ + public function getScheme() + { + return $this->env['slim.url_scheme']; + } + + /** + * Get Script Name (physical path) + * @return string + */ + public function getScriptName() + { + return $this->env['SCRIPT_NAME']; + } + + /** + * LEGACY: Get Root URI (alias for Slim_Http_Request::getScriptName) + * @return string + */ + public function getRootUri() + { + return $this->getScriptName(); + } + + /** + * Get Path (physical path + virtual path) + * @return string + */ + public function getPath() + { + return $this->getScriptName() . $this->getPathInfo(); + } + + /** + * Get Path Info (virtual path) + * @return string + */ + public function getPathInfo() + { + return $this->env['PATH_INFO']; + } + + /** + * LEGACY: Get Resource URI (alias for Slim_Http_Request::getPathInfo) + * @return string + */ + public function getResourceUri() + { + return $this->getPathInfo(); + } + + /** + * Get URL (scheme + host [ + port if non-standard ]) + * @return string + */ + public function getUrl() + { + $url = $this->getScheme() . '://' . $this->getHost(); + if (($this->getScheme() === 'https' && $this->getPort() !== 443) || ($this->getScheme() === 'http' && $this->getPort() !== 80)) { + $url .= sprintf(':%s', $this->getPort()); + } + + return $url; + } + + /** + * Get IP + * @return string + */ + public function getIp() + { + $keys = array('X_FORWARDED_FOR', 'HTTP_X_FORWARDED_FOR', 'CLIENT_IP', 'REMOTE_ADDR'); + foreach ($keys as $key) { + if (isset($this->env[$key])) { + return $this->env[$key]; + } + } + + return $this->env['REMOTE_ADDR']; + } + + /** + * Get Referrer + * @return string|null + */ + public function getReferrer() + { + return $this->headers->get('HTTP_REFERER'); + } + + /** + * Get Referer (for those who can't spell) + * @return string|null + */ + public function getReferer() + { + return $this->getReferrer(); + } + + /** + * Get User Agent + * @return string|null + */ + public function getUserAgent() + { + return $this->headers->get('HTTP_USER_AGENT'); + } +} diff --git a/Slim/Http/Response.php b/Slim/Http/Response.php new file mode 100644 index 0000000..c55d647 --- /dev/null +++ b/Slim/Http/Response.php @@ -0,0 +1,512 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Http; + +/** + * Response + * + * This is a simple abstraction over top an HTTP response. This + * provides methods to set the HTTP status, the HTTP headers, + * and the HTTP body. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class Response implements \ArrayAccess, \Countable, \IteratorAggregate +{ + /** + * @var int HTTP status code + */ + protected $status; + + /** + * @var \Slim\Http\Headers + */ + public $headers; + + /** + * @var \Slim\Http\Cookies + */ + public $cookies; + + /** + * @var string HTTP response body + */ + protected $body; + + /** + * @var int Length of HTTP response body + */ + protected $length; + + /** + * @var array HTTP response codes and messages + */ + protected static $messages = array( + //Informational 1xx + 100 => '100 Continue', + 101 => '101 Switching Protocols', + //Successful 2xx + 200 => '200 OK', + 201 => '201 Created', + 202 => '202 Accepted', + 203 => '203 Non-Authoritative Information', + 204 => '204 No Content', + 205 => '205 Reset Content', + 206 => '206 Partial Content', + //Redirection 3xx + 300 => '300 Multiple Choices', + 301 => '301 Moved Permanently', + 302 => '302 Found', + 303 => '303 See Other', + 304 => '304 Not Modified', + 305 => '305 Use Proxy', + 306 => '306 (Unused)', + 307 => '307 Temporary Redirect', + //Client Error 4xx + 400 => '400 Bad Request', + 401 => '401 Unauthorized', + 402 => '402 Payment Required', + 403 => '403 Forbidden', + 404 => '404 Not Found', + 405 => '405 Method Not Allowed', + 406 => '406 Not Acceptable', + 407 => '407 Proxy Authentication Required', + 408 => '408 Request Timeout', + 409 => '409 Conflict', + 410 => '410 Gone', + 411 => '411 Length Required', + 412 => '412 Precondition Failed', + 413 => '413 Request Entity Too Large', + 414 => '414 Request-URI Too Long', + 415 => '415 Unsupported Media Type', + 416 => '416 Requested Range Not Satisfiable', + 417 => '417 Expectation Failed', + 418 => '418 I\'m a teapot', + 422 => '422 Unprocessable Entity', + 423 => '423 Locked', + //Server Error 5xx + 500 => '500 Internal Server Error', + 501 => '501 Not Implemented', + 502 => '502 Bad Gateway', + 503 => '503 Service Unavailable', + 504 => '504 Gateway Timeout', + 505 => '505 HTTP Version Not Supported' + ); + + /** + * Constructor + * @param string $body The HTTP response body + * @param int $status The HTTP response status + * @param \Slim\Http\Headers|array $headers The HTTP response headers + */ + public function __construct($body = '', $status = 200, $headers = array()) + { + $this->setStatus($status); + $this->headers = new \Slim\Http\Headers(array('Content-Type' => 'text/html')); + $this->headers->replace($headers); + $this->cookies = new \Slim\Http\Cookies(); + $this->write($body); + } + + public function getStatus() + { + return $this->status; + } + + public function setStatus($status) + { + $this->status = (int)$status; + } + + /** + * DEPRECATION WARNING! Use `getStatus` or `setStatus` instead. + * + * Get and set status + * @param int|null $status + * @return int + */ + public function status($status = null) + { + if (!is_null($status)) { + $this->status = (int) $status; + } + + return $this->status; + } + + /** + * DEPRECATION WARNING! Access `headers` property directly. + * + * Get and set header + * @param string $name Header name + * @param string|null $value Header value + * @return string Header value + */ + public function header($name, $value = null) + { + if (!is_null($value)) { + $this->headers->set($name, $value); + } + + return $this->headers->get($name); + } + + /** + * DEPRECATION WARNING! Access `headers` property directly. + * + * Get headers + * @return \Slim\Http\Headers + */ + public function headers() + { + return $this->headers; + } + + public function getBody() + { + return $this->body; + } + + public function setBody($content) + { + $this->write($content, true); + } + + /** + * DEPRECATION WARNING! use `getBody` or `setBody` instead. + * + * Get and set body + * @param string|null $body Content of HTTP response body + * @return string + */ + public function body($body = null) + { + if (!is_null($body)) { + $this->write($body, true); + } + + return $this->body; + } + + /** + * Append HTTP response body + * @param string $body Content to append to the current HTTP response body + * @param bool $replace Overwrite existing response body? + * @return string The updated HTTP response body + */ + public function write($body, $replace = false) + { + if ($replace) { + $this->body = $body; + } else { + $this->body .= (string)$body; + } + $this->length = strlen($this->body); + + return $this->body; + } + + public function getLength() + { + return $this->length; + } + + /** + * DEPRECATION WARNING! Use `getLength` or `write` or `body` instead. + * + * Get and set length + * @param int|null $length + * @return int + */ + public function length($length = null) + { + if (!is_null($length)) { + $this->length = (int) $length; + } + + return $this->length; + } + + /** + * Finalize + * + * This prepares this response and returns an array + * of [status, headers, body]. This array is passed to outer middleware + * if available or directly to the Slim run method. + * + * @return array[int status, array headers, string body] + */ + public function finalize() + { + // Prepare response + if (in_array($this->status, array(204, 304))) { + $this->headers->remove('Content-Type'); + $this->headers->remove('Content-Length'); + $this->setBody(''); + } + + return array($this->status, $this->headers, $this->body); + } + + /** + * DEPRECATION WARNING! Access `cookies` property directly. + * + * Set cookie + * + * Instead of using PHP's `setcookie()` function, Slim manually constructs the HTTP `Set-Cookie` + * header on its own and delegates this responsibility to the `Slim_Http_Util` class. This + * response's header is passed by reference to the utility class and is directly modified. By not + * relying on PHP's native implementation, Slim allows middleware the opportunity to massage or + * analyze the raw header before the response is ultimately delivered to the HTTP client. + * + * @param string $name The name of the cookie + * @param string|array $value If string, the value of cookie; if array, properties for + * cookie including: value, expire, path, domain, secure, httponly + */ + public function setCookie($name, $value) + { + // Util::setCookieHeader($this->header, $name, $value); + $this->cookies->set($name, $value); + } + + /** + * DEPRECATION WARNING! Access `cookies` property directly. + * + * Delete cookie + * + * Instead of using PHP's `setcookie()` function, Slim manually constructs the HTTP `Set-Cookie` + * header on its own and delegates this responsibility to the `Slim_Http_Util` class. This + * response's header is passed by reference to the utility class and is directly modified. By not + * relying on PHP's native implementation, Slim allows middleware the opportunity to massage or + * analyze the raw header before the response is ultimately delivered to the HTTP client. + * + * This method will set a cookie with the given name that has an expiration time in the past; this will + * prompt the HTTP client to invalidate and remove the client-side cookie. Optionally, you may + * also pass a key/value array as the second argument. If the "domain" key is present in this + * array, only the Cookie with the given name AND domain will be removed. The invalidating cookie + * sent with this response will adopt all properties of the second argument. + * + * @param string $name The name of the cookie + * @param array $settings Properties for cookie including: value, expire, path, domain, secure, httponly + */ + public function deleteCookie($name, $settings = array()) + { + $this->cookies->remove($name, $settings); + // Util::deleteCookieHeader($this->header, $name, $value); + } + + /** + * Redirect + * + * This method prepares this response to return an HTTP Redirect response + * to the HTTP client. + * + * @param string $url The redirect destination + * @param int $status The redirect HTTP status code + */ + public function redirect ($url, $status = 302) + { + $this->setStatus($status); + $this->headers->set('Location', $url); + } + + /** + * Helpers: Empty? + * @return bool + */ + public function isEmpty() + { + return in_array($this->status, array(201, 204, 304)); + } + + /** + * Helpers: Informational? + * @return bool + */ + public function isInformational() + { + return $this->status >= 100 && $this->status < 200; + } + + /** + * Helpers: OK? + * @return bool + */ + public function isOk() + { + return $this->status === 200; + } + + /** + * Helpers: Successful? + * @return bool + */ + public function isSuccessful() + { + return $this->status >= 200 && $this->status < 300; + } + + /** + * Helpers: Redirect? + * @return bool + */ + public function isRedirect() + { + return in_array($this->status, array(301, 302, 303, 307)); + } + + /** + * Helpers: Redirection? + * @return bool + */ + public function isRedirection() + { + return $this->status >= 300 && $this->status < 400; + } + + /** + * Helpers: Forbidden? + * @return bool + */ + public function isForbidden() + { + return $this->status === 403; + } + + /** + * Helpers: Not Found? + * @return bool + */ + public function isNotFound() + { + return $this->status === 404; + } + + /** + * Helpers: Client error? + * @return bool + */ + public function isClientError() + { + return $this->status >= 400 && $this->status < 500; + } + + /** + * Helpers: Server Error? + * @return bool + */ + public function isServerError() + { + return $this->status >= 500 && $this->status < 600; + } + + /** + * DEPRECATION WARNING! ArrayAccess interface will be removed from \Slim\Http\Response. + * Iterate `headers` or `cookies` properties directly. + */ + + /** + * Array Access: Offset Exists + */ + public function offsetExists($offset) + { + return isset($this->headers[$offset]); + } + + /** + * Array Access: Offset Get + */ + public function offsetGet($offset) + { + return $this->headers[$offset]; + } + + /** + * Array Access: Offset Set + */ + public function offsetSet($offset, $value) + { + $this->headers[$offset] = $value; + } + + /** + * Array Access: Offset Unset + */ + public function offsetUnset($offset) + { + unset($this->headers[$offset]); + } + + /** + * DEPRECATION WARNING! Countable interface will be removed from \Slim\Http\Response. + * Call `count` on `headers` or `cookies` properties directly. + * + * Countable: Count + */ + public function count() + { + return count($this->headers); + } + + /** + * DEPRECATION WARNING! IteratorAggregate interface will be removed from \Slim\Http\Response. + * Iterate `headers` or `cookies` properties directly. + * + * Get Iterator + * + * This returns the contained `\Slim\Http\Headers` instance which + * is itself iterable. + * + * @return \Slim\Http\Headers + */ + public function getIterator() + { + return $this->headers->getIterator(); + } + + /** + * Get message for HTTP status code + * @param int $status + * @return string|null + */ + public static function getMessageForCode($status) + { + if (isset(self::$messages[$status])) { + return self::$messages[$status]; + } else { + return null; + } + } +} diff --git a/Slim/Http/Util.php b/Slim/Http/Util.php new file mode 100644 index 0000000..dafedb3 --- /dev/null +++ b/Slim/Http/Util.php @@ -0,0 +1,434 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Http; + +/** + * Slim HTTP Utilities + * + * This class provides useful methods for handling HTTP requests. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class Util +{ + /** + * Strip slashes from string or array + * + * This method strips slashes from its input. By default, this method will only + * strip slashes from its input if magic quotes are enabled. Otherwise, you may + * override the magic quotes setting with either TRUE or FALSE as the send argument + * to force this method to strip or not strip slashes from its input. + * + * @param array|string $rawData + * @param bool $overrideStripSlashes + * @return array|string + */ + public static function stripSlashesIfMagicQuotes($rawData, $overrideStripSlashes = null) + { + $strip = is_null($overrideStripSlashes) ? get_magic_quotes_gpc() : $overrideStripSlashes; + if ($strip) { + return self::stripSlashes($rawData); + } else { + return $rawData; + } + } + + /** + * Strip slashes from string or array + * @param array|string $rawData + * @return array|string + */ + protected static function stripSlashes($rawData) + { + return is_array($rawData) ? array_map(array('self', 'stripSlashes'), $rawData) : stripslashes($rawData); + } + + /** + * Encrypt data + * + * This method will encrypt data using a given key, vector, and cipher. + * By default, this will encrypt data using the RIJNDAEL/AES 256 bit cipher. You + * may override the default cipher and cipher mode by passing your own desired + * cipher and cipher mode as the final key-value array argument. + * + * @param string $data The unencrypted data + * @param string $key The encryption key + * @param string $iv The encryption initialization vector + * @param array $settings Optional key-value array with custom algorithm and mode + * @return string + */ + public static function encrypt($data, $key, $iv, $settings = array()) + { + if ($data === '' || !extension_loaded('mcrypt')) { + return $data; + } + + //Merge settings with defaults + $defaults = array( + 'algorithm' => MCRYPT_RIJNDAEL_256, + 'mode' => MCRYPT_MODE_CBC + ); + $settings = array_merge($defaults, $settings); + + //Get module + $module = mcrypt_module_open($settings['algorithm'], '', $settings['mode'], ''); + + //Validate IV + $ivSize = mcrypt_enc_get_iv_size($module); + if (strlen($iv) > $ivSize) { + $iv = substr($iv, 0, $ivSize); + } + + //Validate key + $keySize = mcrypt_enc_get_key_size($module); + if (strlen($key) > $keySize) { + $key = substr($key, 0, $keySize); + } + + //Encrypt value + mcrypt_generic_init($module, $key, $iv); + $res = @mcrypt_generic($module, $data); + mcrypt_generic_deinit($module); + + return $res; + } + + /** + * Decrypt data + * + * This method will decrypt data using a given key, vector, and cipher. + * By default, this will decrypt data using the RIJNDAEL/AES 256 bit cipher. You + * may override the default cipher and cipher mode by passing your own desired + * cipher and cipher mode as the final key-value array argument. + * + * @param string $data The encrypted data + * @param string $key The encryption key + * @param string $iv The encryption initialization vector + * @param array $settings Optional key-value array with custom algorithm and mode + * @return string + */ + public static function decrypt($data, $key, $iv, $settings = array()) + { + if ($data === '' || !extension_loaded('mcrypt')) { + return $data; + } + + //Merge settings with defaults + $defaults = array( + 'algorithm' => MCRYPT_RIJNDAEL_256, + 'mode' => MCRYPT_MODE_CBC + ); + $settings = array_merge($defaults, $settings); + + //Get module + $module = mcrypt_module_open($settings['algorithm'], '', $settings['mode'], ''); + + //Validate IV + $ivSize = mcrypt_enc_get_iv_size($module); + if (strlen($iv) > $ivSize) { + $iv = substr($iv, 0, $ivSize); + } + + //Validate key + $keySize = mcrypt_enc_get_key_size($module); + if (strlen($key) > $keySize) { + $key = substr($key, 0, $keySize); + } + + //Decrypt value + mcrypt_generic_init($module, $key, $iv); + $decryptedData = @mdecrypt_generic($module, $data); + $res = rtrim($decryptedData, "\0"); + mcrypt_generic_deinit($module); + + return $res; + } + + /** + * Serialize Response cookies into raw HTTP header + * @param \Slim\Http\Headers $headers The Response headers + * @param \Slim\Http\Cookies $cookies The Response cookies + * @param array $config The Slim app settings + */ + public static function serializeCookies(\Slim\Http\Headers &$headers, \Slim\Http\Cookies $cookies, array $config) + { + if ($config['cookies.encrypt']) { + foreach ($cookies as $name => $settings) { + if (is_string($settings['expires'])) { + $expires = strtotime($settings['expires']); + } else { + $expires = (int) $settings['expires']; + } + + $settings['value'] = static::encodeSecureCookie( + $settings['value'], + $expires, + $config['cookies.secret_key'], + $config['cookies.cipher'], + $config['cookies.cipher_mode'] + ); + static::setCookieHeader($headers, $name, $settings); + } + } else { + foreach ($cookies as $name => $settings) { + static::setCookieHeader($headers, $name, $settings); + } + } + } + + /** + * Encode secure cookie value + * + * This method will create the secure value of an HTTP cookie. The + * cookie value is encrypted and hashed so that its value is + * secure and checked for integrity when read in subsequent requests. + * + * @param string $value The insecure HTTP cookie value + * @param int $expires The UNIX timestamp at which this cookie will expire + * @param string $secret The secret key used to hash the cookie value + * @param int $algorithm The algorithm to use for encryption + * @param int $mode The algorithm mode to use for encryption + * @return string + */ + public static function encodeSecureCookie($value, $expires, $secret, $algorithm, $mode) + { + $key = hash_hmac('sha1', (string) $expires, $secret); + $iv = self::getIv($expires, $secret); + $secureString = base64_encode( + self::encrypt( + $value, + $key, + $iv, + array( + 'algorithm' => $algorithm, + 'mode' => $mode + ) + ) + ); + $verificationString = hash_hmac('sha1', $expires . $value, $key); + + return implode('|', array($expires, $secureString, $verificationString)); + } + + /** + * Decode secure cookie value + * + * This method will decode the secure value of an HTTP cookie. The + * cookie value is encrypted and hashed so that its value is + * secure and checked for integrity when read in subsequent requests. + * + * @param string $value The secure HTTP cookie value + * @param string $secret The secret key used to hash the cookie value + * @param int $algorithm The algorithm to use for encryption + * @param int $mode The algorithm mode to use for encryption + * @return bool|string + */ + public static function decodeSecureCookie($value, $secret, $algorithm, $mode) + { + if ($value) { + $value = explode('|', $value); + if (count($value) === 3 && ((int) $value[0] === 0 || (int) $value[0] > time())) { + $key = hash_hmac('sha1', $value[0], $secret); + $iv = self::getIv($value[0], $secret); + $data = self::decrypt( + base64_decode($value[1]), + $key, + $iv, + array( + 'algorithm' => $algorithm, + 'mode' => $mode + ) + ); + $verificationString = hash_hmac('sha1', $value[0] . $data, $key); + if ($verificationString === $value[2]) { + return $data; + } + } + } + + return false; + } + + /** + * Set HTTP cookie header + * + * This method will construct and set the HTTP `Set-Cookie` header. Slim + * uses this method instead of PHP's native `setcookie` method. This allows + * more control of the HTTP header irrespective of the native implementation's + * dependency on PHP versions. + * + * This method accepts the Slim_Http_Headers object by reference as its + * first argument; this method directly modifies this object instead of + * returning a value. + * + * @param array $header + * @param string $name + * @param string $value + */ + public static function setCookieHeader(&$header, $name, $value) + { + //Build cookie header + if (is_array($value)) { + $domain = ''; + $path = ''; + $expires = ''; + $secure = ''; + $httponly = ''; + if (isset($value['domain']) && $value['domain']) { + $domain = '; domain=' . $value['domain']; + } + if (isset($value['path']) && $value['path']) { + $path = '; path=' . $value['path']; + } + if (isset($value['expires'])) { + if (is_string($value['expires'])) { + $timestamp = strtotime($value['expires']); + } else { + $timestamp = (int) $value['expires']; + } + if ($timestamp !== 0) { + $expires = '; expires=' . gmdate('D, d-M-Y H:i:s e', $timestamp); + } + } + if (isset($value['secure']) && $value['secure']) { + $secure = '; secure'; + } + if (isset($value['httponly']) && $value['httponly']) { + $httponly = '; HttpOnly'; + } + $cookie = sprintf('%s=%s%s', urlencode($name), urlencode((string) $value['value']), $domain . $path . $expires . $secure . $httponly); + } else { + $cookie = sprintf('%s=%s', urlencode($name), urlencode((string) $value)); + } + + //Set cookie header + if (!isset($header['Set-Cookie']) || $header['Set-Cookie'] === '') { + $header['Set-Cookie'] = $cookie; + } else { + $header['Set-Cookie'] = implode("\n", array($header['Set-Cookie'], $cookie)); + } + } + + /** + * Delete HTTP cookie header + * + * This method will construct and set the HTTP `Set-Cookie` header to invalidate + * a client-side HTTP cookie. If a cookie with the same name (and, optionally, domain) + * is already set in the HTTP response, it will also be removed. Slim uses this method + * instead of PHP's native `setcookie` method. This allows more control of the HTTP header + * irrespective of PHP's native implementation's dependency on PHP versions. + * + * This method accepts the Slim_Http_Headers object by reference as its + * first argument; this method directly modifies this object instead of + * returning a value. + * + * @param array $header + * @param string $name + * @param array $value + */ + public static function deleteCookieHeader(&$header, $name, $value = array()) + { + //Remove affected cookies from current response header + $cookiesOld = array(); + $cookiesNew = array(); + if (isset($header['Set-Cookie'])) { + $cookiesOld = explode("\n", $header['Set-Cookie']); + } + foreach ($cookiesOld as $c) { + if (isset($value['domain']) && $value['domain']) { + $regex = sprintf('@%s=.*domain=%s@', urlencode($name), preg_quote($value['domain'])); + } else { + $regex = sprintf('@%s=@', urlencode($name)); + } + if (preg_match($regex, $c) === 0) { + $cookiesNew[] = $c; + } + } + if ($cookiesNew) { + $header['Set-Cookie'] = implode("\n", $cookiesNew); + } else { + unset($header['Set-Cookie']); + } + + //Set invalidating cookie to clear client-side cookie + self::setCookieHeader($header, $name, array_merge(array('value' => '', 'path' => null, 'domain' => null, 'expires' => time() - 100), $value)); + } + + /** + * Parse cookie header + * + * This method will parse the HTTP request's `Cookie` header + * and extract cookies into an associative array. + * + * @param string + * @return array + */ + public static function parseCookieHeader($header) + { + $cookies = array(); + $header = rtrim($header, "\r\n"); + $headerPieces = preg_split('@\s*[;,]\s*@', $header); + foreach ($headerPieces as $c) { + $cParts = explode('=', $c, 2); + if (count($cParts) === 2) { + $key = urldecode($cParts[0]); + $value = urldecode($cParts[1]); + if (!isset($cookies[$key])) { + $cookies[$key] = $value; + } + } + } + + return $cookies; + } + + /** + * Generate a random IV + * + * This method will generate a non-predictable IV for use with + * the cookie encryption + * + * @param int $expires The UNIX timestamp at which this cookie will expire + * @param string $secret The secret key used to hash the cookie value + * @return string Hash + */ + private static function getIv($expires, $secret) + { + $data1 = hash_hmac('sha1', 'a'.$expires.'b', $secret); + $data2 = hash_hmac('sha1', 'z'.$expires.'y', $secret); + + return pack("h*", $data1.$data2); + } +} diff --git a/Slim/Log.php b/Slim/Log.php new file mode 100644 index 0000000..d872e87 --- /dev/null +++ b/Slim/Log.php @@ -0,0 +1,349 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim; + +/** + * Log + * + * This is the primary logger for a Slim application. You may provide + * a Log Writer in conjunction with this Log to write to various output + * destinations (e.g. a file). This class provides this interface: + * + * debug( mixed $object, array $context ) + * info( mixed $object, array $context ) + * notice( mixed $object, array $context ) + * warning( mixed $object, array $context ) + * error( mixed $object, array $context ) + * critical( mixed $object, array $context ) + * alert( mixed $object, array $context ) + * emergency( mixed $object, array $context ) + * log( mixed $level, mixed $object, array $context ) + * + * This class assumes only that your Log Writer has a public `write()` method + * that accepts any object as its one and only argument. The Log Writer + * class may write or send its argument anywhere: a file, STDERR, + * a remote web API, etc. The possibilities are endless. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class Log +{ + const EMERGENCY = 1; + const ALERT = 2; + const CRITICAL = 3; + const FATAL = 3; //DEPRECATED replace with CRITICAL + const ERROR = 4; + const WARN = 5; + const NOTICE = 6; + const INFO = 7; + const DEBUG = 8; + + /** + * @var array + */ + protected static $levels = array( + self::EMERGENCY => 'EMERGENCY', + self::ALERT => 'ALERT', + self::CRITICAL => 'CRITICAL', + self::ERROR => 'ERROR', + self::WARN => 'WARNING', + self::NOTICE => 'NOTICE', + self::INFO => 'INFO', + self::DEBUG => 'DEBUG' + ); + + /** + * @var mixed + */ + protected $writer; + + /** + * @var bool + */ + protected $enabled; + + /** + * @var int + */ + protected $level; + + /** + * Constructor + * @param mixed $writer + */ + public function __construct($writer) + { + $this->writer = $writer; + $this->enabled = true; + $this->level = self::DEBUG; + } + + /** + * Is logging enabled? + * @return bool + */ + public function getEnabled() + { + return $this->enabled; + } + + /** + * Enable or disable logging + * @param bool $enabled + */ + public function setEnabled($enabled) + { + if ($enabled) { + $this->enabled = true; + } else { + $this->enabled = false; + } + } + + /** + * Set level + * @param int $level + * @throws \InvalidArgumentException If invalid log level specified + */ + public function setLevel($level) + { + if (!isset(self::$levels[$level])) { + throw new \InvalidArgumentException('Invalid log level'); + } + $this->level = $level; + } + + /** + * Get level + * @return int + */ + public function getLevel() + { + return $this->level; + } + + /** + * Set writer + * @param mixed $writer + */ + public function setWriter($writer) + { + $this->writer = $writer; + } + + /** + * Get writer + * @return mixed + */ + public function getWriter() + { + return $this->writer; + } + + /** + * Is logging enabled? + * @return bool + */ + public function isEnabled() + { + return $this->enabled; + } + + /** + * Log debug message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function debug($object, $context = array()) + { + return $this->log(self::DEBUG, $object, $context); + } + + /** + * Log info message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function info($object, $context = array()) + { + return $this->log(self::INFO, $object, $context); + } + + /** + * Log notice message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function notice($object, $context = array()) + { + return $this->log(self::NOTICE, $object, $context); + } + + /** + * Log warning message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function warning($object, $context = array()) + { + return $this->log(self::WARN, $object, $context); + } + + /** + * DEPRECATED for function warning + * Log warning message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function warn($object, $context = array()) + { + return $this->log(self::WARN, $object, $context); + } + + /** + * Log error message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function error($object, $context = array()) + { + return $this->log(self::ERROR, $object, $context); + } + + /** + * Log critical message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function critical($object, $context = array()) + { + return $this->log(self::CRITICAL, $object, $context); + } + + /** + * DEPRECATED for function critical + * Log fatal message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function fatal($object, $context = array()) + { + return $this->log(self::CRITICAL, $object, $context); + } + + /** + * Log alert message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function alert($object, $context = array()) + { + return $this->log(self::ALERT, $object, $context); + } + + /** + * Log emergency message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function emergency($object, $context = array()) + { + return $this->log(self::EMERGENCY, $object, $context); + } + + /** + * Log message + * @param mixed $level + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + * @throws \InvalidArgumentException If invalid log level + */ + public function log($level, $object, $context = array()) + { + if (!isset(self::$levels[$level])) { + throw new \InvalidArgumentException('Invalid log level supplied to function'); + } else if ($this->enabled && $this->writer && $level <= $this->level) { + $message = (string)$object; + if (count($context) > 0) { + if (isset($context['exception']) && $context['exception'] instanceof \Exception) { + $message .= ' - ' . $context['exception']; + unset($context['exception']); + } + $message = $this->interpolate($message, $context); + } + return $this->writer->write($message, $level); + } else { + return false; + } + } + + /** + * DEPRECATED for function log + * Log message + * @param mixed $object The object to log + * @param int $level The message level + * @return int|bool + */ + protected function write($object, $level) + { + return $this->log($level, $object); + } + + /** + * Interpolate log message + * @param mixed $message The log message + * @param array $context An array of placeholder values + * @return string The processed string + */ + protected function interpolate($message, $context = array()) + { + $replace = array(); + foreach ($context as $key => $value) { + $replace['{' . $key . '}'] = $value; + } + return strtr($message, $replace); + } +} diff --git a/Slim/LogWriter.php b/Slim/LogWriter.php new file mode 100644 index 0000000..5e44e2f --- /dev/null +++ b/Slim/LogWriter.php @@ -0,0 +1,75 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim; + +/** + * Log Writer + * + * This class is used by Slim_Log to write log messages to a valid, writable + * resource handle (e.g. a file or STDERR). + * + * @package Slim + * @author Josh Lockhart + * @since 1.6.0 + */ +class LogWriter +{ + /** + * @var resource + */ + protected $resource; + + /** + * Constructor + * @param resource $resource + * @throws \InvalidArgumentException If invalid resource + */ + public function __construct($resource) + { + if (!is_resource($resource)) { + throw new \InvalidArgumentException('Cannot create LogWriter. Invalid resource handle.'); + } + $this->resource = $resource; + } + + /** + * Write message + * @param mixed $message + * @param int $level + * @return int|bool + */ + public function write($message, $level = null) + { + return fwrite($this->resource, (string) $message . PHP_EOL); + } +} diff --git a/Slim/Middleware.php b/Slim/Middleware.php new file mode 100644 index 0000000..be23100 --- /dev/null +++ b/Slim/Middleware.php @@ -0,0 +1,114 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim; + +/** + * Middleware + * + * @package Slim + * @author Josh Lockhart + * @since 1.6.0 + */ +abstract class Middleware +{ + /** + * @var \Slim\Slim Reference to the primary application instance + */ + protected $app; + + /** + * @var mixed Reference to the next downstream middleware + */ + protected $next; + + /** + * Set application + * + * This method injects the primary Slim application instance into + * this middleware. + * + * @param \Slim\Slim $application + */ + final public function setApplication($application) + { + $this->app = $application; + } + + /** + * Get application + * + * This method retrieves the application previously injected + * into this middleware. + * + * @return \Slim\Slim + */ + final public function getApplication() + { + return $this->app; + } + + /** + * Set next middleware + * + * This method injects the next downstream middleware into + * this middleware so that it may optionally be called + * when appropriate. + * + * @param \Slim|\Slim\Middleware + */ + final public function setNextMiddleware($nextMiddleware) + { + $this->next = $nextMiddleware; + } + + /** + * Get next middleware + * + * This method retrieves the next downstream middleware + * previously injected into this middleware. + * + * @return \Slim\Slim|\Slim\Middleware + */ + final public function getNextMiddleware() + { + return $this->next; + } + + /** + * Call + * + * Perform actions specific to this middleware and optionally + * call the next downstream middleware. + */ + abstract public function call(); +} diff --git a/Slim/Middleware/ContentTypes.php b/Slim/Middleware/ContentTypes.php new file mode 100644 index 0000000..08049db --- /dev/null +++ b/Slim/Middleware/ContentTypes.php @@ -0,0 +1,174 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Middleware; + + /** + * Content Types + * + * This is middleware for a Slim application that intercepts + * the HTTP request body and parses it into the appropriate + * PHP data structure if possible; else it returns the HTTP + * request body unchanged. This is particularly useful + * for preparing the HTTP request body for an XML or JSON API. + * + * @package Slim + * @author Josh Lockhart + * @since 1.6.0 + */ +class ContentTypes extends \Slim\Middleware +{ + /** + * @var array + */ + protected $contentTypes; + + /** + * Constructor + * @param array $settings + */ + public function __construct($settings = array()) + { + $defaults = array( + 'application/json' => array($this, 'parseJson'), + 'application/xml' => array($this, 'parseXml'), + 'text/xml' => array($this, 'parseXml'), + 'text/csv' => array($this, 'parseCsv') + ); + $this->contentTypes = array_merge($defaults, $settings); + } + + /** + * Call + */ + public function call() + { + $mediaType = $this->app->request()->getMediaType(); + if ($mediaType) { + $env = $this->app->environment(); + $env['slim.input_original'] = $env['slim.input']; + $env['slim.input'] = $this->parse($env['slim.input'], $mediaType); + } + $this->next->call(); + } + + /** + * Parse input + * + * This method will attempt to parse the request body + * based on its content type if available. + * + * @param string $input + * @param string $contentType + * @return mixed + */ + protected function parse ($input, $contentType) + { + if (isset($this->contentTypes[$contentType]) && is_callable($this->contentTypes[$contentType])) { + $result = call_user_func($this->contentTypes[$contentType], $input); + if ($result) { + return $result; + } + } + + return $input; + } + + /** + * Parse JSON + * + * This method converts the raw JSON input + * into an associative array. + * + * @param string $input + * @return array|string + */ + protected function parseJson($input) + { + if (function_exists('json_decode')) { + $result = json_decode($input, true); + if ($result) { + return $result; + } + } + } + + /** + * Parse XML + * + * This method creates a SimpleXMLElement + * based upon the XML input. If the SimpleXML + * extension is not available, the raw input + * will be returned unchanged. + * + * @param string $input + * @return \SimpleXMLElement|string + */ + protected function parseXml($input) + { + if (class_exists('SimpleXMLElement')) { + try { + $backup = libxml_disable_entity_loader(true); + $result = new \SimpleXMLElement($input); + libxml_disable_entity_loader($backup); + return $result; + } catch (\Exception $e) { + // Do nothing + } + } + + return $input; + } + + /** + * Parse CSV + * + * This method parses CSV content into a numeric array + * containing an array of data for each CSV line. + * + * @param string $input + * @return array + */ + protected function parseCsv($input) + { + $temp = fopen('php://memory', 'rw'); + fwrite($temp, $input); + fseek($temp, 0); + $res = array(); + while (($data = fgetcsv($temp)) !== false) { + $res[] = $data; + } + fclose($temp); + + return $res; + } +} diff --git a/Slim/Middleware/Flash.php b/Slim/Middleware/Flash.php new file mode 100644 index 0000000..96f685e --- /dev/null +++ b/Slim/Middleware/Flash.php @@ -0,0 +1,212 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Middleware; + + /** + * Flash + * + * This is middleware for a Slim application that enables + * Flash messaging between HTTP requests. This allows you + * set Flash messages for the current request, for the next request, + * or to retain messages from the previous request through to + * the next request. + * + * @package Slim + * @author Josh Lockhart + * @since 1.6.0 + */ +class Flash extends \Slim\Middleware implements \ArrayAccess, \IteratorAggregate, \Countable +{ + /** + * @var array + */ + protected $settings; + + /** + * @var array + */ + protected $messages; + + /** + * Constructor + * @param array $settings + */ + public function __construct($settings = array()) + { + $this->settings = array_merge(array('key' => 'slim.flash'), $settings); + $this->messages = array( + 'prev' => array(), //flash messages from prev request (loaded when middleware called) + 'next' => array(), //flash messages for next request + 'now' => array() //flash messages for current request + ); + } + + /** + * Call + */ + public function call() + { + //Read flash messaging from previous request if available + $this->loadMessages(); + + //Prepare flash messaging for current request + $env = $this->app->environment(); + $env['slim.flash'] = $this; + $this->next->call(); + $this->save(); + } + + /** + * Now + * + * Specify a flash message for a given key to be shown for the current request + * + * @param string $key + * @param string $value + */ + public function now($key, $value) + { + $this->messages['now'][(string) $key] = $value; + } + + /** + * Set + * + * Specify a flash message for a given key to be shown for the next request + * + * @param string $key + * @param string $value + */ + public function set($key, $value) + { + $this->messages['next'][(string) $key] = $value; + } + + /** + * Keep + * + * Retain flash messages from the previous request for the next request + */ + public function keep() + { + foreach ($this->messages['prev'] as $key => $val) { + $this->messages['next'][$key] = $val; + } + } + + /** + * Save + */ + public function save() + { + $_SESSION[$this->settings['key']] = $this->messages['next']; + } + + /** + * Load messages from previous request if available + */ + public function loadMessages() + { + if (isset($_SESSION[$this->settings['key']])) { + $this->messages['prev'] = $_SESSION[$this->settings['key']]; + } + } + + /** + * Return array of flash messages to be shown for the current request + * + * @return array + */ + public function getMessages() + { + return array_merge($this->messages['prev'], $this->messages['now']); + } + + /** + * Array Access: Offset Exists + */ + public function offsetExists($offset) + { + $messages = $this->getMessages(); + + return isset($messages[$offset]); + } + + /** + * Array Access: Offset Get + */ + public function offsetGet($offset) + { + $messages = $this->getMessages(); + + return isset($messages[$offset]) ? $messages[$offset] : null; + } + + /** + * Array Access: Offset Set + */ + public function offsetSet($offset, $value) + { + $this->now($offset, $value); + } + + /** + * Array Access: Offset Unset + */ + public function offsetUnset($offset) + { + unset($this->messages['prev'][$offset], $this->messages['now'][$offset]); + } + + /** + * Iterator Aggregate: Get Iterator + * @return \ArrayIterator + */ + public function getIterator() + { + $messages = $this->getMessages(); + + return new \ArrayIterator($messages); + } + + /** + * Countable: Count + */ + public function count() + { + return count($this->getMessages()); + } + + + +} diff --git a/Slim/Middleware/MethodOverride.php b/Slim/Middleware/MethodOverride.php new file mode 100644 index 0000000..7fa3bb0 --- /dev/null +++ b/Slim/Middleware/MethodOverride.php @@ -0,0 +1,94 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Middleware; + + /** + * HTTP Method Override + * + * This is middleware for a Slim application that allows traditional + * desktop browsers to submit pseudo PUT and DELETE requests by relying + * on a pre-determined request parameter. Without this middleware, + * desktop browsers are only able to submit GET and POST requests. + * + * This middleware is included automatically! + * + * @package Slim + * @author Josh Lockhart + * @since 1.6.0 + */ +class MethodOverride extends \Slim\Middleware +{ + /** + * @var array + */ + protected $settings; + + /** + * Constructor + * @param array $settings + */ + public function __construct($settings = array()) + { + $this->settings = array_merge(array('key' => '_METHOD'), $settings); + } + + /** + * Call + * + * Implements Slim middleware interface. This method is invoked and passed + * an array of environment variables. This middleware inspects the environment + * variables for the HTTP method override parameter; if found, this middleware + * modifies the environment settings so downstream middleware and/or the Slim + * application will treat the request with the desired HTTP method. + * + * @return array[status, header, body] + */ + public function call() + { + $env = $this->app->environment(); + if (isset($env['HTTP_X_HTTP_METHOD_OVERRIDE'])) { + // Header commonly used by Backbone.js and others + $env['slim.method_override.original_method'] = $env['REQUEST_METHOD']; + $env['REQUEST_METHOD'] = strtoupper($env['HTTP_X_HTTP_METHOD_OVERRIDE']); + } elseif (isset($env['REQUEST_METHOD']) && $env['REQUEST_METHOD'] === 'POST') { + // HTML Form Override + $req = new \Slim\Http\Request($env); + $method = $req->post($this->settings['key']); + if ($method) { + $env['slim.method_override.original_method'] = $env['REQUEST_METHOD']; + $env['REQUEST_METHOD'] = strtoupper($method); + } + } + $this->next->call(); + } +} diff --git a/Slim/Middleware/PrettyExceptions.php b/Slim/Middleware/PrettyExceptions.php new file mode 100644 index 0000000..8a56442 --- /dev/null +++ b/Slim/Middleware/PrettyExceptions.php @@ -0,0 +1,116 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Middleware; + +/** + * Pretty Exceptions + * + * This middleware catches any Exception thrown by the surrounded + * application and displays a developer-friendly diagnostic screen. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class PrettyExceptions extends \Slim\Middleware +{ + /** + * @var array + */ + protected $settings; + + /** + * Constructor + * @param array $settings + */ + public function __construct($settings = array()) + { + $this->settings = $settings; + } + + /** + * Call + */ + public function call() + { + try { + $this->next->call(); + } catch (\Exception $e) { + $log = $this->app->getLog(); // Force Slim to append log to env if not already + $env = $this->app->environment(); + $env['slim.log'] = $log; + $env['slim.log']->error($e); + $this->app->contentType('text/html'); + $this->app->response()->status(500); + $this->app->response()->body($this->renderBody($env, $e)); + } + } + + /** + * Render response body + * @param array $env + * @param \Exception $exception + * @return string + */ + protected function renderBody(&$env, $exception) + { + $title = 'Slim Application Error'; + $code = $exception->getCode(); + $message = $exception->getMessage(); + $file = $exception->getFile(); + $line = $exception->getLine(); + $trace = str_replace(array('#', '\n'), array('
#', '
'), $exception->getTraceAsString()); + $html = sprintf('

%s

', $title); + $html .= '

The application could not run because of the following error:

'; + $html .= '

Details

'; + $html .= sprintf('
Type: %s
', get_class($exception)); + if ($code) { + $html .= sprintf('
Code: %s
', $code); + } + if ($message) { + $html .= sprintf('
Message: %s
', $message); + } + if ($file) { + $html .= sprintf('
File: %s
', $file); + } + if ($line) { + $html .= sprintf('
Line: %s
', $line); + } + if ($trace) { + $html .= '

Trace

'; + $html .= sprintf('
%s
', $trace); + } + + return sprintf("%s%s", $title, $html); + } +} diff --git a/Slim/Middleware/SessionCookie.php b/Slim/Middleware/SessionCookie.php new file mode 100644 index 0000000..a467475 --- /dev/null +++ b/Slim/Middleware/SessionCookie.php @@ -0,0 +1,210 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Middleware; + +/** + * Session Cookie + * + * This class provides an HTTP cookie storage mechanism + * for session data. This class avoids using a PHP session + * and instead serializes/unserializes the $_SESSION global + * variable to/from an HTTP cookie. + * + * You should NEVER store sensitive data in a client-side cookie + * in any format, encrypted (with cookies.encrypt) or not. If you + * need to store sensitive user information in a session, you should + * rely on PHP's native session implementation, or use other middleware + * to store session data in a database or alternative server-side cache. + * + * Because this class stores serialized session data in an HTTP cookie, + * you are inherently limited to 4 Kb. If you attempt to store + * more than this amount, serialization will fail. + * + * @package Slim + * @author Josh Lockhart + * @since 1.6.0 + */ +class SessionCookie extends \Slim\Middleware +{ + /** + * @var array + */ + protected $settings; + + /** + * Constructor + * + * @param array $settings + */ + public function __construct($settings = array()) + { + $defaults = array( + 'expires' => '20 minutes', + 'path' => '/', + 'domain' => null, + 'secure' => false, + 'httponly' => false, + 'name' => 'slim_session', + ); + $this->settings = array_merge($defaults, $settings); + if (is_string($this->settings['expires'])) { + $this->settings['expires'] = strtotime($this->settings['expires']); + } + + /** + * Session + * + * We must start a native PHP session to initialize the $_SESSION superglobal. + * However, we won't be using the native session store for persistence, so we + * disable the session cookie and cache limiter. We also set the session + * handler to this class instance to avoid PHP's native session file locking. + */ + ini_set('session.use_cookies', 0); + session_cache_limiter(false); + session_set_save_handler( + array($this, 'open'), + array($this, 'close'), + array($this, 'read'), + array($this, 'write'), + array($this, 'destroy'), + array($this, 'gc') + ); + } + + /** + * Call + */ + public function call() + { + $this->loadSession(); + $this->next->call(); + $this->saveSession(); + } + + /** + * Load session + */ + protected function loadSession() + { + if (session_id() === '') { + session_start(); + } + + $value = $this->app->getCookie($this->settings['name']); + + if ($value) { + try { + $_SESSION = unserialize($value); + } catch (\Exception $e) { + $this->app->getLog()->error('Error unserializing session cookie value! ' . $e->getMessage()); + } + } else { + $_SESSION = array(); + } + } + + /** + * Save session + */ + protected function saveSession() + { + $value = serialize($_SESSION); + + if (strlen($value) > 4096) { + $this->app->getLog()->error('WARNING! Slim\Middleware\SessionCookie data size is larger than 4KB. Content save failed.'); + } else { + $this->app->setCookie( + $this->settings['name'], + $value, + $this->settings['expires'], + $this->settings['path'], + $this->settings['domain'], + $this->settings['secure'], + $this->settings['httponly'] + ); + } + // session_destroy(); + } + + /******************************************************************************** + * Session Handler + *******************************************************************************/ + + /** + * @codeCoverageIgnore + */ + public function open($savePath, $sessionName) + { + return true; + } + + /** + * @codeCoverageIgnore + */ + public function close() + { + return true; + } + + /** + * @codeCoverageIgnore + */ + public function read($id) + { + return ''; + } + + /** + * @codeCoverageIgnore + */ + public function write($id, $data) + { + return true; + } + + /** + * @codeCoverageIgnore + */ + public function destroy($id) + { + return true; + } + + /** + * @codeCoverageIgnore + */ + public function gc($maxlifetime) + { + return true; + } +} diff --git a/Slim/Route.php b/Slim/Route.php new file mode 100644 index 0000000..99b47a1 --- /dev/null +++ b/Slim/Route.php @@ -0,0 +1,465 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim; + +/** + * Route + * @package Slim + * @author Josh Lockhart, Thomas Bley + * @since 1.0.0 + */ +class Route +{ + /** + * @var string The route pattern (e.g. "/books/:id") + */ + protected $pattern; + + /** + * @var mixed The route callable + */ + protected $callable; + + /** + * @var array Conditions for this route's URL parameters + */ + protected $conditions = array(); + + /** + * @var array Default conditions applied to all route instances + */ + protected static $defaultConditions = array(); + + /** + * @var string The name of this route (optional) + */ + protected $name; + + /** + * @var array Key-value array of URL parameters + */ + protected $params = array(); + + /** + * @var array value array of URL parameter names + */ + protected $paramNames = array(); + + /** + * @var array key array of URL parameter names with + at the end + */ + protected $paramNamesPath = array(); + + /** + * @var array HTTP methods supported by this Route + */ + protected $methods = array(); + + /** + * @var array[Callable] Middleware to be run before only this route instance + */ + protected $middleware = array(); + + /** + * @var bool Whether or not this route should be matched in a case-sensitive manner + */ + protected $caseSensitive; + + /** + * Constructor + * @param string $pattern The URL pattern (e.g. "/books/:id") + * @param mixed $callable Anything that returns TRUE for is_callable() + * @param bool $caseSensitive Whether or not this route should be matched in a case-sensitive manner + */ + public function __construct($pattern, $callable, $caseSensitive = true) + { + $this->setPattern($pattern); + $this->setCallable($callable); + $this->setConditions(self::getDefaultConditions()); + $this->caseSensitive = $caseSensitive; + } + + /** + * Set default route conditions for all instances + * @param array $defaultConditions + */ + public static function setDefaultConditions(array $defaultConditions) + { + self::$defaultConditions = $defaultConditions; + } + + /** + * Get default route conditions for all instances + * @return array + */ + public static function getDefaultConditions() + { + return self::$defaultConditions; + } + + /** + * Get route pattern + * @return string + */ + public function getPattern() + { + return $this->pattern; + } + + /** + * Set route pattern + * @param string $pattern + */ + public function setPattern($pattern) + { + $this->pattern = $pattern; + } + + /** + * Get route callable + * @return mixed + */ + public function getCallable() + { + return $this->callable; + } + + /** + * Set route callable + * @param mixed $callable + * @throws \InvalidArgumentException If argument is not callable + */ + public function setCallable($callable) + { + $matches = array(); + if (is_string($callable) && preg_match('!^([^\:]+)\:([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)$!', $callable, $matches)) { + $class = $matches[1]; + $method = $matches[2]; + $callable = function() use ($class, $method) { + static $obj = null; + if ($obj === null) { + $obj = new $class; + } + return call_user_func_array(array($obj, $method), func_get_args()); + }; + } + + if (!is_callable($callable)) { + throw new \InvalidArgumentException('Route callable must be callable'); + } + + $this->callable = $callable; + } + + /** + * Get route conditions + * @return array + */ + public function getConditions() + { + return $this->conditions; + } + + /** + * Set route conditions + * @param array $conditions + */ + public function setConditions(array $conditions) + { + $this->conditions = $conditions; + } + + /** + * Get route name + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Set route name + * @param string $name + */ + public function setName($name) + { + $this->name = (string)$name; + } + + /** + * Get route parameters + * @return array + */ + public function getParams() + { + return $this->params; + } + + /** + * Set route parameters + * @param array $params + */ + public function setParams($params) + { + $this->params = $params; + } + + /** + * Get route parameter value + * @param string $index Name of URL parameter + * @return string + * @throws \InvalidArgumentException If route parameter does not exist at index + */ + public function getParam($index) + { + if (!isset($this->params[$index])) { + throw new \InvalidArgumentException('Route parameter does not exist at specified index'); + } + + return $this->params[$index]; + } + + /** + * Set route parameter value + * @param string $index Name of URL parameter + * @param mixed $value The new parameter value + * @throws \InvalidArgumentException If route parameter does not exist at index + */ + public function setParam($index, $value) + { + if (!isset($this->params[$index])) { + throw new \InvalidArgumentException('Route parameter does not exist at specified index'); + } + $this->params[$index] = $value; + } + + /** + * Add supported HTTP method(s) + */ + public function setHttpMethods() + { + $args = func_get_args(); + $this->methods = $args; + } + + /** + * Get supported HTTP methods + * @return array + */ + public function getHttpMethods() + { + return $this->methods; + } + + /** + * Append supported HTTP methods + */ + public function appendHttpMethods() + { + $args = func_get_args(); + $this->methods = array_merge($this->methods, $args); + } + + /** + * Append supported HTTP methods (alias for Route::appendHttpMethods) + * @return \Slim\Route + */ + public function via() + { + $args = func_get_args(); + $this->methods = array_merge($this->methods, $args); + + return $this; + } + + /** + * Detect support for an HTTP method + * @param string $method + * @return bool + */ + public function supportsHttpMethod($method) + { + return in_array($method, $this->methods); + } + + /** + * Get middleware + * @return array[Callable] + */ + public function getMiddleware() + { + return $this->middleware; + } + + /** + * Set middleware + * + * This method allows middleware to be assigned to a specific Route. + * If the method argument `is_callable` (including callable arrays!), + * we directly append the argument to `$this->middleware`. Else, we + * assume the argument is an array of callables and merge the array + * with `$this->middleware`. Each middleware is checked for is_callable() + * and an InvalidArgumentException is thrown immediately if it isn't. + * + * @param Callable|array[Callable] + * @return \Slim\Route + * @throws \InvalidArgumentException If argument is not callable or not an array of callables. + */ + public function setMiddleware($middleware) + { + if (is_callable($middleware)) { + $this->middleware[] = $middleware; + } elseif (is_array($middleware)) { + foreach ($middleware as $callable) { + if (!is_callable($callable)) { + throw new \InvalidArgumentException('All Route middleware must be callable'); + } + } + $this->middleware = array_merge($this->middleware, $middleware); + } else { + throw new \InvalidArgumentException('Route middleware must be callable or an array of callables'); + } + + return $this; + } + + /** + * Matches URI? + * + * Parse this route's pattern, and then compare it to an HTTP resource URI + * This method was modeled after the techniques demonstrated by Dan Sosedoff at: + * + * http://blog.sosedoff.com/2009/09/20/rails-like-php-url-router/ + * + * @param string $resourceUri A Request URI + * @return bool + */ + public function matches($resourceUri) + { + //Convert URL params into regex patterns, construct a regex for this route, init params + $patternAsRegex = preg_replace_callback( + '#:([\w]+)\+?#', + array($this, 'matchesCallback'), + str_replace(')', ')?', (string)$this->pattern) + ); + if (substr($this->pattern, -1) === '/') { + $patternAsRegex .= '?'; + } + + $regex = '#^' . $patternAsRegex . '$#'; + + if ($this->caseSensitive === false) { + $regex .= 'i'; + } + + //Cache URL params' names and values if this route matches the current HTTP request + if (!preg_match($regex, $resourceUri, $paramValues)) { + return false; + } + foreach ($this->paramNames as $name) { + if (isset($paramValues[$name])) { + if (isset($this->paramNamesPath[$name])) { + $this->params[$name] = explode('/', urldecode($paramValues[$name])); + } else { + $this->params[$name] = urldecode($paramValues[$name]); + } + } + } + + return true; + } + + /** + * Convert a URL parameter (e.g. ":id", ":id+") into a regular expression + * @param array $m URL parameters + * @return string Regular expression for URL parameter + */ + protected function matchesCallback($m) + { + $this->paramNames[] = $m[1]; + if (isset($this->conditions[$m[1]])) { + return '(?P<' . $m[1] . '>' . $this->conditions[$m[1]] . ')'; + } + if (substr($m[0], -1) === '+') { + $this->paramNamesPath[$m[1]] = 1; + + return '(?P<' . $m[1] . '>.+)'; + } + + return '(?P<' . $m[1] . '>[^/]+)'; + } + + /** + * Set route name + * @param string $name The name of the route + * @return \Slim\Route + */ + public function name($name) + { + $this->setName($name); + + return $this; + } + + /** + * Merge route conditions + * @param array $conditions Key-value array of URL parameter conditions + * @return \Slim\Route + */ + public function conditions(array $conditions) + { + $this->conditions = array_merge($this->conditions, $conditions); + + return $this; + } + + /** + * Dispatch route + * + * This method invokes the route object's callable. If middleware is + * registered for the route, each callable middleware is invoked in + * the order specified. + * + * @return bool + */ + public function dispatch() + { + foreach ($this->middleware as $mw) { + call_user_func_array($mw, array($this)); + } + + $return = call_user_func_array($this->getCallable(), array_values($this->getParams())); + return ($return === false) ? false : true; + } +} diff --git a/Slim/Router.php b/Slim/Router.php new file mode 100644 index 0000000..b0e7a60 --- /dev/null +++ b/Slim/Router.php @@ -0,0 +1,257 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim; + +/** + * Router + * + * This class organizes, iterates, and dispatches \Slim\Route objects. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class Router +{ + /** + * @var Route The current route (most recently dispatched) + */ + protected $currentRoute; + + /** + * @var array Lookup hash of all route objects + */ + protected $routes; + + /** + * @var array Lookup hash of named route objects, keyed by route name (lazy-loaded) + */ + protected $namedRoutes; + + /** + * @var array Array of route objects that match the request URI (lazy-loaded) + */ + protected $matchedRoutes; + + /** + * @var array Array containing all route groups + */ + protected $routeGroups; + + /** + * Constructor + */ + public function __construct() + { + $this->routes = array(); + $this->routeGroups = array(); + } + + /** + * Get Current Route object or the first matched one if matching has been performed + * @return \Slim\Route|null + */ + public function getCurrentRoute() + { + if ($this->currentRoute !== null) { + return $this->currentRoute; + } + + if (is_array($this->matchedRoutes) && count($this->matchedRoutes) > 0) { + return $this->matchedRoutes[0]; + } + + return null; + } + + /** + * Return route objects that match the given HTTP method and URI + * @param string $httpMethod The HTTP method to match against + * @param string $resourceUri The resource URI to match against + * @param bool $reload Should matching routes be re-parsed? + * @return array[\Slim\Route] + */ + public function getMatchedRoutes($httpMethod, $resourceUri, $reload = false) + { + if ($reload || is_null($this->matchedRoutes)) { + $this->matchedRoutes = array(); + foreach ($this->routes as $route) { + if (!$route->supportsHttpMethod($httpMethod) && !$route->supportsHttpMethod("ANY")) { + continue; + } + + if ($route->matches($resourceUri)) { + $this->matchedRoutes[] = $route; + } + } + } + + return $this->matchedRoutes; + } + + /** + * Add a route object to the router + * @param \Slim\Route $route The Slim Route + */ + public function map(\Slim\Route $route) + { + list($groupPattern, $groupMiddleware) = $this->processGroups(); + + $route->setPattern($groupPattern . $route->getPattern()); + $this->routes[] = $route; + + + foreach ($groupMiddleware as $middleware) { + $route->setMiddleware($middleware); + } + } + + /** + * A helper function for processing the group's pattern and middleware + * @return array Returns an array with the elements: pattern, middlewareArr + */ + protected function processGroups() + { + $pattern = ""; + $middleware = array(); + foreach ($this->routeGroups as $group) { + $k = key($group); + $pattern .= $k; + if (is_array($group[$k])) { + $middleware = array_merge($middleware, $group[$k]); + } + } + return array($pattern, $middleware); + } + + /** + * Add a route group to the array + * @param string $group The group pattern (ie. "/books/:id") + * @param array|null $middleware Optional parameter array of middleware + * @return int The index of the new group + */ + public function pushGroup($group, $middleware = array()) + { + return array_push($this->routeGroups, array($group => $middleware)); + } + + /** + * Removes the last route group from the array + * @return bool True if successful, else False + */ + public function popGroup() + { + return (array_pop($this->routeGroups) !== null); + } + + /** + * Get URL for named route + * @param string $name The name of the route + * @param array $params Associative array of URL parameter names and replacement values + * @throws \RuntimeException If named route not found + * @return string The URL for the given route populated with provided replacement values + */ + public function urlFor($name, $params = array()) + { + if (!$this->hasNamedRoute($name)) { + throw new \RuntimeException('Named route not found for name: ' . $name); + } + $search = array(); + foreach ($params as $key => $value) { + $search[] = '#:' . preg_quote($key, '#') . '\+?(?!\w)#'; + } + $pattern = preg_replace($search, $params, $this->getNamedRoute($name)->getPattern()); + + //Remove remnants of unpopulated, trailing optional pattern segments, escaped special characters + return preg_replace('#\(/?:.+\)|\(|\)|\\\\#', '', $pattern); + } + + /** + * Add named route + * @param string $name The route name + * @param \Slim\Route $route The route object + * @throws \RuntimeException If a named route already exists with the same name + */ + public function addNamedRoute($name, \Slim\Route $route) + { + if ($this->hasNamedRoute($name)) { + throw new \RuntimeException('Named route already exists with name: ' . $name); + } + $this->namedRoutes[(string) $name] = $route; + } + + /** + * Has named route + * @param string $name The route name + * @return bool + */ + public function hasNamedRoute($name) + { + $this->getNamedRoutes(); + + return isset($this->namedRoutes[(string) $name]); + } + + /** + * Get named route + * @param string $name + * @return \Slim\Route|null + */ + public function getNamedRoute($name) + { + $this->getNamedRoutes(); + if ($this->hasNamedRoute($name)) { + return $this->namedRoutes[(string) $name]; + } else { + return null; + } + } + + /** + * Get named routes + * @return \ArrayIterator + */ + public function getNamedRoutes() + { + if (is_null($this->namedRoutes)) { + $this->namedRoutes = array(); + foreach ($this->routes as $route) { + if ($route->getName() !== null) { + $this->addNamedRoute($route->getName(), $route); + } + } + } + + return new \ArrayIterator($this->namedRoutes); + } +} diff --git a/Slim/Slim.php b/Slim/Slim.php new file mode 100644 index 0000000..cb8ef66 --- /dev/null +++ b/Slim/Slim.php @@ -0,0 +1,1412 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim; + +// Ensure mcrypt constants are defined even if mcrypt extension is not loaded +if (!extension_loaded('mcrypt')) { + define('MCRYPT_MODE_CBC', 0); + define('MCRYPT_RIJNDAEL_256', 0); +} + +/** + * Slim + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + * + * @property \Slim\Environment $environment + * @property \Slim\Http\Response $response + * @property \Slim\Http\Request $request + * @property \Slim\Router $router + */ +class Slim +{ + /** + * @const string + */ + const VERSION = '2.4.2'; + + /** + * @var \Slim\Helper\Set + */ + public $container; + + /** + * @var array[\Slim] + */ + protected static $apps = array(); + + /** + * @var string + */ + protected $name; + + /** + * @var array + */ + protected $middleware; + + /** + * @var mixed Callable to be invoked if application error + */ + protected $error; + + /** + * @var mixed Callable to be invoked if no matching routes are found + */ + protected $notFound; + + /** + * @var array + */ + protected $hooks = array( + 'slim.before' => array(array()), + 'slim.before.router' => array(array()), + 'slim.before.dispatch' => array(array()), + 'slim.after.dispatch' => array(array()), + 'slim.after.router' => array(array()), + 'slim.after' => array(array()) + ); + + /******************************************************************************** + * PSR-0 Autoloader + * + * Do not use if you are using Composer to autoload dependencies. + *******************************************************************************/ + + /** + * Slim PSR-0 autoloader + */ + public static function autoload($className) + { + $thisClass = str_replace(__NAMESPACE__.'\\', '', __CLASS__); + + $baseDir = __DIR__; + + if (substr($baseDir, -strlen($thisClass)) === $thisClass) { + $baseDir = substr($baseDir, 0, -strlen($thisClass)); + } + + $className = ltrim($className, '\\'); + $fileName = $baseDir; + $namespace = ''; + if ($lastNsPos = strripos($className, '\\')) { + $namespace = substr($className, 0, $lastNsPos); + $className = substr($className, $lastNsPos + 1); + $fileName .= str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; + } + $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; + + if (file_exists($fileName)) { + require $fileName; + } + } + + /** + * Register Slim's PSR-0 autoloader + */ + public static function registerAutoloader() + { + spl_autoload_register(__NAMESPACE__ . "\\Slim::autoload"); + } + + /******************************************************************************** + * Instantiation and Configuration + *******************************************************************************/ + + /** + * Constructor + * @param array $userSettings Associative array of application settings + */ + public function __construct(array $userSettings = array()) + { + // Setup IoC container + $this->container = new \Slim\Helper\Set(); + $this->container['settings'] = array_merge(static::getDefaultSettings(), $userSettings); + + // Default environment + $this->container->singleton('environment', function ($c) { + return \Slim\Environment::getInstance(); + }); + + // Default request + $this->container->singleton('request', function ($c) { + return new \Slim\Http\Request($c['environment']); + }); + + // Default response + $this->container->singleton('response', function ($c) { + return new \Slim\Http\Response(); + }); + + // Default router + $this->container->singleton('router', function ($c) { + return new \Slim\Router(); + }); + + // Default view + $this->container->singleton('view', function ($c) { + $viewClass = $c['settings']['view']; + $templatesPath = $c['settings']['templates.path']; + + $view = ($viewClass instanceOf \Slim\View) ? $viewClass : new $viewClass; + $view->setTemplatesDirectory($templatesPath); + return $view; + }); + + // Default log writer + $this->container->singleton('logWriter', function ($c) { + $logWriter = $c['settings']['log.writer']; + + return is_object($logWriter) ? $logWriter : new \Slim\LogWriter($c['environment']['slim.errors']); + }); + + // Default log + $this->container->singleton('log', function ($c) { + $log = new \Slim\Log($c['logWriter']); + $log->setEnabled($c['settings']['log.enabled']); + $log->setLevel($c['settings']['log.level']); + $env = $c['environment']; + $env['slim.log'] = $log; + + return $log; + }); + + // Default mode + $this->container['mode'] = function ($c) { + $mode = $c['settings']['mode']; + + if (isset($_ENV['SLIM_MODE'])) { + $mode = $_ENV['SLIM_MODE']; + } else { + $envMode = getenv('SLIM_MODE'); + if ($envMode !== false) { + $mode = $envMode; + } + } + + return $mode; + }; + + // Define default middleware stack + $this->middleware = array($this); + $this->add(new \Slim\Middleware\Flash()); + $this->add(new \Slim\Middleware\MethodOverride()); + + // Make default if first instance + if (is_null(static::getInstance())) { + $this->setName('default'); + } + } + + public function __get($name) + { + return $this->container[$name]; + } + + public function __set($name, $value) + { + $this->container[$name] = $value; + } + + public function __isset($name) + { + return isset($this->container[$name]); + } + + public function __unset($name) + { + unset($this->container[$name]); + } + + /** + * Get application instance by name + * @param string $name The name of the Slim application + * @return \Slim\Slim|null + */ + public static function getInstance($name = 'default') + { + return isset(static::$apps[$name]) ? static::$apps[$name] : null; + } + + /** + * Set Slim application name + * @param string $name The name of this Slim application + */ + public function setName($name) + { + $this->name = $name; + static::$apps[$name] = $this; + } + + /** + * Get Slim application name + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Get default application settings + * @return array + */ + public static function getDefaultSettings() + { + return array( + // Application + 'mode' => 'development', + // Debugging + 'debug' => true, + // Logging + 'log.writer' => null, + 'log.level' => \Slim\Log::DEBUG, + 'log.enabled' => true, + // View + 'templates.path' => './templates', + 'view' => '\Slim\View', + // Cookies + 'cookies.encrypt' => false, + 'cookies.lifetime' => '20 minutes', + 'cookies.path' => '/', + 'cookies.domain' => null, + 'cookies.secure' => false, + 'cookies.httponly' => false, + // Encryption + 'cookies.secret_key' => 'CHANGE_ME', + 'cookies.cipher' => MCRYPT_RIJNDAEL_256, + 'cookies.cipher_mode' => MCRYPT_MODE_CBC, + // HTTP + 'http.version' => '1.1', + // Routing + 'routes.case_sensitive' => true + ); + } + + /** + * Configure Slim Settings + * + * This method defines application settings and acts as a setter and a getter. + * + * If only one argument is specified and that argument is a string, the value + * of the setting identified by the first argument will be returned, or NULL if + * that setting does not exist. + * + * If only one argument is specified and that argument is an associative array, + * the array will be merged into the existing application settings. + * + * If two arguments are provided, the first argument is the name of the setting + * to be created or updated, and the second argument is the setting value. + * + * @param string|array $name If a string, the name of the setting to set or retrieve. Else an associated array of setting names and values + * @param mixed $value If name is a string, the value of the setting identified by $name + * @return mixed The value of a setting if only one argument is a string + */ + public function config($name, $value = null) + { + $c = $this->container; + + if (is_array($name)) { + if (true === $value) { + $c['settings'] = array_merge_recursive($c['settings'], $name); + } else { + $c['settings'] = array_merge($c['settings'], $name); + } + } elseif (func_num_args() === 1) { + return isset($c['settings'][$name]) ? $c['settings'][$name] : null; + } else { + $settings = $c['settings']; + $settings[$name] = $value; + $c['settings'] = $settings; + } + } + + /******************************************************************************** + * Application Modes + *******************************************************************************/ + + /** + * Get application mode + * + * This method determines the application mode. It first inspects the $_ENV + * superglobal for key `SLIM_MODE`. If that is not found, it queries + * the `getenv` function. Else, it uses the application `mode` setting. + * + * @return string + */ + public function getMode() + { + return $this->mode; + } + + /** + * Configure Slim for a given mode + * + * This method will immediately invoke the callable if + * the specified mode matches the current application mode. + * Otherwise, the callable is ignored. This should be called + * only _after_ you initialize your Slim app. + * + * @param string $mode + * @param mixed $callable + * @return void + */ + public function configureMode($mode, $callable) + { + if ($mode === $this->getMode() && is_callable($callable)) { + call_user_func($callable); + } + } + + /******************************************************************************** + * Logging + *******************************************************************************/ + + /** + * Get application log + * @return \Slim\Log + */ + public function getLog() + { + return $this->log; + } + + /******************************************************************************** + * Routing + *******************************************************************************/ + + /** + * Add GET|POST|PUT|PATCH|DELETE route + * + * Adds a new route to the router with associated callable. This + * route will only be invoked when the HTTP request's method matches + * this route's method. + * + * ARGUMENTS: + * + * First: string The URL pattern (REQUIRED) + * In-Between: mixed Anything that returns TRUE for `is_callable` (OPTIONAL) + * Last: mixed Anything that returns TRUE for `is_callable` (REQUIRED) + * + * The first argument is required and must always be the + * route pattern (ie. '/books/:id'). + * + * The last argument is required and must always be the callable object + * to be invoked when the route matches an HTTP request. + * + * You may also provide an unlimited number of in-between arguments; + * each interior argument must be callable and will be invoked in the + * order specified before the route's callable is invoked. + * + * USAGE: + * + * Slim::get('/foo'[, middleware, middleware, ...], callable); + * + * @param array (See notes above) + * @return \Slim\Route + */ + protected function mapRoute($args) + { + $pattern = array_shift($args); + $callable = array_pop($args); + $route = new \Slim\Route($pattern, $callable, $this->settings['routes.case_sensitive']); + $this->router->map($route); + if (count($args) > 0) { + $route->setMiddleware($args); + } + + return $route; + } + + /** + * Add generic route without associated HTTP method + * @see mapRoute() + * @return \Slim\Route + */ + public function map() + { + $args = func_get_args(); + + return $this->mapRoute($args); + } + + /** + * Add GET route + * @see mapRoute() + * @return \Slim\Route + */ + public function get() + { + $args = func_get_args(); + + return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_GET, \Slim\Http\Request::METHOD_HEAD); + } + + /** + * Add POST route + * @see mapRoute() + * @return \Slim\Route + */ + public function post() + { + $args = func_get_args(); + + return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_POST); + } + + /** + * Add PUT route + * @see mapRoute() + * @return \Slim\Route + */ + public function put() + { + $args = func_get_args(); + + return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_PUT); + } + + /** + * Add PATCH route + * @see mapRoute() + * @return \Slim\Route + */ + public function patch() + { + $args = func_get_args(); + + return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_PATCH); + } + + /** + * Add DELETE route + * @see mapRoute() + * @return \Slim\Route + */ + public function delete() + { + $args = func_get_args(); + + return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_DELETE); + } + + /** + * Add OPTIONS route + * @see mapRoute() + * @return \Slim\Route + */ + public function options() + { + $args = func_get_args(); + + return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_OPTIONS); + } + + /** + * Route Groups + * + * This method accepts a route pattern and a callback all Route + * declarations in the callback will be prepended by the group(s) + * that it is in + * + * Accepts the same parameters as a standard route so: + * (pattern, middleware1, middleware2, ..., $callback) + */ + public function group() + { + $args = func_get_args(); + $pattern = array_shift($args); + $callable = array_pop($args); + $this->router->pushGroup($pattern, $args); + if (is_callable($callable)) { + call_user_func($callable); + } + $this->router->popGroup(); + } + + /* + * Add route for any HTTP method + * @see mapRoute() + * @return \Slim\Route + */ + public function any() + { + $args = func_get_args(); + + return $this->mapRoute($args)->via("ANY"); + } + + /** + * Not Found Handler + * + * This method defines or invokes the application-wide Not Found handler. + * There are two contexts in which this method may be invoked: + * + * 1. When declaring the handler: + * + * If the $callable parameter is not null and is callable, this + * method will register the callable to be invoked when no + * routes match the current HTTP request. It WILL NOT invoke the callable. + * + * 2. When invoking the handler: + * + * If the $callable parameter is null, Slim assumes you want + * to invoke an already-registered handler. If the handler has been + * registered and is callable, it is invoked and sends a 404 HTTP Response + * whose body is the output of the Not Found handler. + * + * @param mixed $callable Anything that returns true for is_callable() + */ + public function notFound ($callable = null) + { + if (is_callable($callable)) { + $this->notFound = $callable; + } else { + ob_start(); + if (is_callable($this->notFound)) { + call_user_func($this->notFound); + } else { + call_user_func(array($this, 'defaultNotFound')); + } + $this->halt(404, ob_get_clean()); + } + } + + /** + * Error Handler + * + * This method defines or invokes the application-wide Error handler. + * There are two contexts in which this method may be invoked: + * + * 1. When declaring the handler: + * + * If the $argument parameter is callable, this + * method will register the callable to be invoked when an uncaught + * Exception is detected, or when otherwise explicitly invoked. + * The handler WILL NOT be invoked in this context. + * + * 2. When invoking the handler: + * + * If the $argument parameter is not callable, Slim assumes you want + * to invoke an already-registered handler. If the handler has been + * registered and is callable, it is invoked and passed the caught Exception + * as its one and only argument. The error handler's output is captured + * into an output buffer and sent as the body of a 500 HTTP Response. + * + * @param mixed $argument Callable|\Exception + */ + public function error($argument = null) + { + if (is_callable($argument)) { + //Register error handler + $this->error = $argument; + } else { + //Invoke error handler + $this->response->status(500); + $this->response->body(''); + $this->response->write($this->callErrorHandler($argument)); + $this->stop(); + } + } + + /** + * Call error handler + * + * This will invoke the custom or default error handler + * and RETURN its output. + * + * @param \Exception|null $argument + * @return string + */ + protected function callErrorHandler($argument = null) + { + ob_start(); + if (is_callable($this->error)) { + call_user_func_array($this->error, array($argument)); + } else { + call_user_func_array(array($this, 'defaultError'), array($argument)); + } + + return ob_get_clean(); + } + + /******************************************************************************** + * Application Accessors + *******************************************************************************/ + + /** + * Get a reference to the Environment object + * @return \Slim\Environment + */ + public function environment() + { + return $this->environment; + } + + /** + * Get the Request object + * @return \Slim\Http\Request + */ + public function request() + { + return $this->request; + } + + /** + * Get the Response object + * @return \Slim\Http\Response + */ + public function response() + { + return $this->response; + } + + /** + * Get the Router object + * @return \Slim\Router + */ + public function router() + { + return $this->router; + } + + /** + * Get and/or set the View + * + * This method declares the View to be used by the Slim application. + * If the argument is a string, Slim will instantiate a new object + * of the same class. If the argument is an instance of View or a subclass + * of View, Slim will use the argument as the View. + * + * If a View already exists and this method is called to create a + * new View, data already set in the existing View will be + * transferred to the new View. + * + * @param string|\Slim\View $viewClass The name or instance of a \Slim\View subclass + * @return \Slim\View + */ + public function view($viewClass = null) + { + if (!is_null($viewClass)) { + $existingData = is_null($this->view) ? array() : $this->view->getData(); + if ($viewClass instanceOf \Slim\View) { + $this->view = $viewClass; + } else { + $this->view = new $viewClass(); + } + $this->view->appendData($existingData); + $this->view->setTemplatesDirectory($this->config('templates.path')); + } + + return $this->view; + } + + /******************************************************************************** + * Rendering + *******************************************************************************/ + + /** + * Render a template + * + * Call this method within a GET, POST, PUT, PATCH, DELETE, NOT FOUND, or ERROR + * callable to render a template whose output is appended to the + * current HTTP response body. How the template is rendered is + * delegated to the current View. + * + * @param string $template The name of the template passed into the view's render() method + * @param array $data Associative array of data made available to the view + * @param int $status The HTTP response status code to use (optional) + */ + public function render($template, $data = array(), $status = null) + { + if (!is_null($status)) { + $this->response->status($status); + } + $this->view->appendData($data); + $this->view->display($template); + } + + /******************************************************************************** + * HTTP Caching + *******************************************************************************/ + + /** + * Set Last-Modified HTTP Response Header + * + * Set the HTTP 'Last-Modified' header and stop if a conditional + * GET request's `If-Modified-Since` header matches the last modified time + * of the resource. The `time` argument is a UNIX timestamp integer value. + * When the current request includes an 'If-Modified-Since' header that + * matches the specified last modified time, the application will stop + * and send a '304 Not Modified' response to the client. + * + * @param int $time The last modified UNIX timestamp + * @throws \InvalidArgumentException If provided timestamp is not an integer + */ + public function lastModified($time) + { + if (is_integer($time)) { + $this->response->headers->set('Last-Modified', gmdate('D, d M Y H:i:s T', $time)); + if ($time === strtotime($this->request->headers->get('IF_MODIFIED_SINCE'))) { + $this->halt(304); + } + } else { + throw new \InvalidArgumentException('Slim::lastModified only accepts an integer UNIX timestamp value.'); + } + } + + /** + * Set ETag HTTP Response Header + * + * Set the etag header and stop if the conditional GET request matches. + * The `value` argument is a unique identifier for the current resource. + * The `type` argument indicates whether the etag should be used as a strong or + * weak cache validator. + * + * When the current request includes an 'If-None-Match' header with + * a matching etag, execution is immediately stopped. If the request + * method is GET or HEAD, a '304 Not Modified' response is sent. + * + * @param string $value The etag value + * @param string $type The type of etag to create; either "strong" or "weak" + * @throws \InvalidArgumentException If provided type is invalid + */ + public function etag($value, $type = 'strong') + { + //Ensure type is correct + if (!in_array($type, array('strong', 'weak'))) { + throw new \InvalidArgumentException('Invalid Slim::etag type. Expected "strong" or "weak".'); + } + + //Set etag value + $value = '"' . $value . '"'; + if ($type === 'weak') { + $value = 'W/'.$value; + } + $this->response['ETag'] = $value; + + //Check conditional GET + if ($etagsHeader = $this->request->headers->get('IF_NONE_MATCH')) { + $etags = preg_split('@\s*,\s*@', $etagsHeader); + if (in_array($value, $etags) || in_array('*', $etags)) { + $this->halt(304); + } + } + } + + /** + * Set Expires HTTP response header + * + * The `Expires` header tells the HTTP client the time at which + * the current resource should be considered stale. At that time the HTTP + * client will send a conditional GET request to the server; the server + * may return a 200 OK if the resource has changed, else a 304 Not Modified + * if the resource has not changed. The `Expires` header should be used in + * conjunction with the `etag()` or `lastModified()` methods above. + * + * @param string|int $time If string, a time to be parsed by `strtotime()`; + * If int, a UNIX timestamp; + */ + public function expires($time) + { + if (is_string($time)) { + $time = strtotime($time); + } + $this->response->headers->set('Expires', gmdate('D, d M Y H:i:s T', $time)); + } + + /******************************************************************************** + * HTTP Cookies + *******************************************************************************/ + + /** + * Set HTTP cookie to be sent with the HTTP response + * + * @param string $name The cookie name + * @param string $value The cookie value + * @param int|string $time The duration of the cookie; + * If integer, should be UNIX timestamp; + * If string, converted to UNIX timestamp with `strtotime`; + * @param string $path The path on the server in which the cookie will be available on + * @param string $domain The domain that the cookie is available to + * @param bool $secure Indicates that the cookie should only be transmitted over a secure + * HTTPS connection to/from the client + * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol + */ + public function setCookie($name, $value, $time = null, $path = null, $domain = null, $secure = null, $httponly = null) + { + $settings = array( + 'value' => $value, + 'expires' => is_null($time) ? $this->config('cookies.lifetime') : $time, + 'path' => is_null($path) ? $this->config('cookies.path') : $path, + 'domain' => is_null($domain) ? $this->config('cookies.domain') : $domain, + 'secure' => is_null($secure) ? $this->config('cookies.secure') : $secure, + 'httponly' => is_null($httponly) ? $this->config('cookies.httponly') : $httponly + ); + $this->response->cookies->set($name, $settings); + } + + /** + * Get value of HTTP cookie from the current HTTP request + * + * Return the value of a cookie from the current HTTP request, + * or return NULL if cookie does not exist. Cookies created during + * the current request will not be available until the next request. + * + * @param string $name + * @param bool $deleteIfInvalid + * @return string|null + */ + public function getCookie($name, $deleteIfInvalid = true) + { + // Get cookie value + $value = $this->request->cookies->get($name); + + // Decode if encrypted + if ($this->config('cookies.encrypt')) { + $value = \Slim\Http\Util::decodeSecureCookie( + $value, + $this->config('cookies.secret_key'), + $this->config('cookies.cipher'), + $this->config('cookies.cipher_mode') + ); + if ($value === false && $deleteIfInvalid) { + $this->deleteCookie($name); + } + } + + return $value; + } + + /** + * DEPRECATION WARNING! Use `setCookie` with the `cookies.encrypt` app setting set to `true`. + * + * Set encrypted HTTP cookie + * + * @param string $name The cookie name + * @param mixed $value The cookie value + * @param mixed $expires The duration of the cookie; + * If integer, should be UNIX timestamp; + * If string, converted to UNIX timestamp with `strtotime`; + * @param string $path The path on the server in which the cookie will be available on + * @param string $domain The domain that the cookie is available to + * @param bool $secure Indicates that the cookie should only be transmitted over a secure + * HTTPS connection from the client + * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol + */ + public function setEncryptedCookie($name, $value, $expires = null, $path = null, $domain = null, $secure = false, $httponly = false) + { + $this->setCookie($name, $value, $expires, $path, $domain, $secure, $httponly); + } + + /** + * DEPRECATION WARNING! Use `getCookie` with the `cookies.encrypt` app setting set to `true`. + * + * Get value of encrypted HTTP cookie + * + * Return the value of an encrypted cookie from the current HTTP request, + * or return NULL if cookie does not exist. Encrypted cookies created during + * the current request will not be available until the next request. + * + * @param string $name + * @param bool $deleteIfInvalid + * @return string|bool + */ + public function getEncryptedCookie($name, $deleteIfInvalid = true) + { + return $this->getCookie($name, $deleteIfInvalid); + } + + /** + * Delete HTTP cookie (encrypted or unencrypted) + * + * Remove a Cookie from the client. This method will overwrite an existing Cookie + * with a new, empty, auto-expiring Cookie. This method's arguments must match + * the original Cookie's respective arguments for the original Cookie to be + * removed. If any of this method's arguments are omitted or set to NULL, the + * default Cookie setting values (set during Slim::init) will be used instead. + * + * @param string $name The cookie name + * @param string $path The path on the server in which the cookie will be available on + * @param string $domain The domain that the cookie is available to + * @param bool $secure Indicates that the cookie should only be transmitted over a secure + * HTTPS connection from the client + * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol + */ + public function deleteCookie($name, $path = null, $domain = null, $secure = null, $httponly = null) + { + $settings = array( + 'domain' => is_null($domain) ? $this->config('cookies.domain') : $domain, + 'path' => is_null($path) ? $this->config('cookies.path') : $path, + 'secure' => is_null($secure) ? $this->config('cookies.secure') : $secure, + 'httponly' => is_null($httponly) ? $this->config('cookies.httponly') : $httponly + ); + $this->response->cookies->remove($name, $settings); + } + + /******************************************************************************** + * Helper Methods + *******************************************************************************/ + + /** + * Get the absolute path to this Slim application's root directory + * + * This method returns the absolute path to the Slim application's + * directory. If the Slim application is installed in a public-accessible + * sub-directory, the sub-directory path will be included. This method + * will always return an absolute path WITH a trailing slash. + * + * @return string + */ + public function root() + { + return rtrim($_SERVER['DOCUMENT_ROOT'], '/') . rtrim($this->request->getRootUri(), '/') . '/'; + } + + /** + * Clean current output buffer + */ + protected function cleanBuffer() + { + if (ob_get_level() !== 0) { + ob_clean(); + } + } + + /** + * Stop + * + * The thrown exception will be caught in application's `call()` method + * and the response will be sent as is to the HTTP client. + * + * @throws \Slim\Exception\Stop + */ + public function stop() + { + throw new \Slim\Exception\Stop(); + } + + /** + * Halt + * + * Stop the application and immediately send the response with a + * specific status and body to the HTTP client. This may send any + * type of response: info, success, redirect, client error, or server error. + * If you need to render a template AND customize the response status, + * use the application's `render()` method instead. + * + * @param int $status The HTTP response status + * @param string $message The HTTP response body + */ + public function halt($status, $message = '') + { + $this->cleanBuffer(); + $this->response->status($status); + $this->response->body($message); + $this->stop(); + } + + /** + * Pass + * + * The thrown exception is caught in the application's `call()` method causing + * the router's current iteration to stop and continue to the subsequent route if available. + * If no subsequent matching routes are found, a 404 response will be sent to the client. + * + * @throws \Slim\Exception\Pass + */ + public function pass() + { + $this->cleanBuffer(); + throw new \Slim\Exception\Pass(); + } + + /** + * Set the HTTP response Content-Type + * @param string $type The Content-Type for the Response (ie. text/html) + */ + public function contentType($type) + { + $this->response->headers->set('Content-Type', $type); + } + + /** + * Set the HTTP response status code + * @param int $code The HTTP response status code + */ + public function status($code) + { + $this->response->setStatus($code); + } + + /** + * Get the URL for a named route + * @param string $name The route name + * @param array $params Associative array of URL parameters and replacement values + * @throws \RuntimeException If named route does not exist + * @return string + */ + public function urlFor($name, $params = array()) + { + return $this->request->getRootUri() . $this->router->urlFor($name, $params); + } + + /** + * Redirect + * + * This method immediately redirects to a new URL. By default, + * this issues a 302 Found response; this is considered the default + * generic redirect response. You may also specify another valid + * 3xx status code if you want. This method will automatically set the + * HTTP Location header for you using the URL parameter. + * + * @param string $url The destination URL + * @param int $status The HTTP redirect status code (optional) + */ + public function redirect($url, $status = 302) + { + $this->response->redirect($url, $status); + $this->halt($status); + } + + /******************************************************************************** + * Flash Messages + *******************************************************************************/ + + /** + * Set flash message for subsequent request + * @param string $key + * @param mixed $value + */ + public function flash($key, $value) + { + if (isset($this->environment['slim.flash'])) { + $this->environment['slim.flash']->set($key, $value); + } + } + + /** + * Set flash message for current request + * @param string $key + * @param mixed $value + */ + public function flashNow($key, $value) + { + if (isset($this->environment['slim.flash'])) { + $this->environment['slim.flash']->now($key, $value); + } + } + + /** + * Keep flash messages from previous request for subsequent request + */ + public function flashKeep() + { + if (isset($this->environment['slim.flash'])) { + $this->environment['slim.flash']->keep(); + } + } + + /******************************************************************************** + * Hooks + *******************************************************************************/ + + /** + * Assign hook + * @param string $name The hook name + * @param mixed $callable A callable object + * @param int $priority The hook priority; 0 = high, 10 = low + */ + public function hook($name, $callable, $priority = 10) + { + if (!isset($this->hooks[$name])) { + $this->hooks[$name] = array(array()); + } + if (is_callable($callable)) { + $this->hooks[$name][(int) $priority][] = $callable; + } + } + + /** + * Invoke hook + * @param string $name The hook name + * @param mixed $hookArg (Optional) Argument for hooked functions + */ + public function applyHook($name, $hookArg = null) + { + if (!isset($this->hooks[$name])) { + $this->hooks[$name] = array(array()); + } + if (!empty($this->hooks[$name])) { + // Sort by priority, low to high, if there's more than one priority + if (count($this->hooks[$name]) > 1) { + ksort($this->hooks[$name]); + } + foreach ($this->hooks[$name] as $priority) { + if (!empty($priority)) { + foreach ($priority as $callable) { + call_user_func($callable, $hookArg); + } + } + } + } + } + + /** + * Get hook listeners + * + * Return an array of registered hooks. If `$name` is a valid + * hook name, only the listeners attached to that hook are returned. + * Else, all listeners are returned as an associative array whose + * keys are hook names and whose values are arrays of listeners. + * + * @param string $name A hook name (Optional) + * @return array|null + */ + public function getHooks($name = null) + { + if (!is_null($name)) { + return isset($this->hooks[(string) $name]) ? $this->hooks[(string) $name] : null; + } else { + return $this->hooks; + } + } + + /** + * Clear hook listeners + * + * Clear all listeners for all hooks. If `$name` is + * a valid hook name, only the listeners attached + * to that hook will be cleared. + * + * @param string $name A hook name (Optional) + */ + public function clearHooks($name = null) + { + if (!is_null($name) && isset($this->hooks[(string) $name])) { + $this->hooks[(string) $name] = array(array()); + } else { + foreach ($this->hooks as $key => $value) { + $this->hooks[$key] = array(array()); + } + } + } + + /******************************************************************************** + * Middleware + *******************************************************************************/ + + /** + * Add middleware + * + * This method prepends new middleware to the application middleware stack. + * The argument must be an instance that subclasses Slim_Middleware. + * + * @param \Slim\Middleware + */ + public function add(\Slim\Middleware $newMiddleware) + { + if(in_array($newMiddleware, $this->middleware)) { + $middleware_class = get_class($newMiddleware); + throw new \RuntimeException("Circular Middleware setup detected. Tried to queue the same Middleware instance ({$middleware_class}) twice."); + } + $newMiddleware->setApplication($this); + $newMiddleware->setNextMiddleware($this->middleware[0]); + array_unshift($this->middleware, $newMiddleware); + } + + /******************************************************************************** + * Runner + *******************************************************************************/ + + /** + * Run + * + * This method invokes the middleware stack, including the core Slim application; + * the result is an array of HTTP status, header, and body. These three items + * are returned to the HTTP client. + */ + public function run() + { + set_error_handler(array('\Slim\Slim', 'handleErrors')); + + //Apply final outer middleware layers + if ($this->config('debug')) { + //Apply pretty exceptions only in debug to avoid accidental information leakage in production + $this->add(new \Slim\Middleware\PrettyExceptions()); + } + + //Invoke middleware and application stack + $this->middleware[0]->call(); + + //Fetch status, header, and body + list($status, $headers, $body) = $this->response->finalize(); + + // Serialize cookies (with optional encryption) + \Slim\Http\Util::serializeCookies($headers, $this->response->cookies, $this->settings); + + //Send headers + if (headers_sent() === false) { + //Send status + if (strpos(PHP_SAPI, 'cgi') === 0) { + header(sprintf('Status: %s', \Slim\Http\Response::getMessageForCode($status))); + } else { + header(sprintf('HTTP/%s %s', $this->config('http.version'), \Slim\Http\Response::getMessageForCode($status))); + } + + //Send headers + foreach ($headers as $name => $value) { + $hValues = explode("\n", $value); + foreach ($hValues as $hVal) { + header("$name: $hVal", false); + } + } + } + + //Send body, but only if it isn't a HEAD request + if (!$this->request->isHead()) { + echo $body; + } + + $this->applyHook('slim.after'); + + restore_error_handler(); + } + + /** + * Call + * + * This method finds and iterates all route objects that match the current request URI. + */ + public function call() + { + try { + if (isset($this->environment['slim.flash'])) { + $this->view()->setData('flash', $this->environment['slim.flash']); + } + $this->applyHook('slim.before'); + ob_start(); + $this->applyHook('slim.before.router'); + $dispatched = false; + $matchedRoutes = $this->router->getMatchedRoutes($this->request->getMethod(), $this->request->getResourceUri()); + foreach ($matchedRoutes as $route) { + try { + $this->applyHook('slim.before.dispatch'); + $dispatched = $route->dispatch(); + $this->applyHook('slim.after.dispatch'); + if ($dispatched) { + break; + } + } catch (\Slim\Exception\Pass $e) { + continue; + } + } + if (!$dispatched) { + $this->notFound(); + } + $this->applyHook('slim.after.router'); + $this->stop(); + } catch (\Slim\Exception\Stop $e) { + $this->response()->write(ob_get_clean()); + } catch (\Exception $e) { + if ($this->config('debug')) { + throw $e; + } else { + try { + $this->error($e); + } catch (\Slim\Exception\Stop $e) { + // Do nothing + } + } + } + } + + /******************************************************************************** + * Error Handling and Debugging + *******************************************************************************/ + + /** + * Convert errors into ErrorException objects + * + * This method catches PHP errors and converts them into \ErrorException objects; + * these \ErrorException objects are then thrown and caught by Slim's + * built-in or custom error handlers. + * + * @param int $errno The numeric type of the Error + * @param string $errstr The error message + * @param string $errfile The absolute path to the affected file + * @param int $errline The line number of the error in the affected file + * @return bool + * @throws \ErrorException + */ + public static function handleErrors($errno, $errstr = '', $errfile = '', $errline = '') + { + if (!($errno & error_reporting())) { + return; + } + + throw new \ErrorException($errstr, $errno, 0, $errfile, $errline); + } + + /** + * Generate diagnostic template markup + * + * This method accepts a title and body content to generate an HTML document layout. + * + * @param string $title The title of the HTML template + * @param string $body The body content of the HTML template + * @return string + */ + protected static function generateTemplateMarkup($title, $body) + { + return sprintf("%s

%s

%s", $title, $title, $body); + } + + /** + * Default Not Found handler + */ + protected function defaultNotFound() + { + echo static::generateTemplateMarkup('404 Page Not Found', '

The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.

Visit the Home Page'); + } + + /** + * Default Error handler + */ + protected function defaultError($e) + { + $this->getLog()->error($e); + echo self::generateTemplateMarkup('Error', '

A website error has occurred. The website administrator has been notified of the issue. Sorry for the temporary inconvenience.

'); + } +} diff --git a/Slim/View.php b/Slim/View.php new file mode 100644 index 0000000..1a3973b --- /dev/null +++ b/Slim/View.php @@ -0,0 +1,282 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim; + +/** + * View + * + * The view is responsible for rendering a template. The view + * should subclass \Slim\View and implement this interface: + * + * public render(string $template); + * + * This method should render the specified template and return + * the resultant string. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class View +{ + /** + * Data available to the view templates + * @var \Slim\Helper\Set + */ + protected $data; + + /** + * Path to templates base directory (without trailing slash) + * @var string + */ + protected $templatesDirectory; + + /** + * Constructor + */ + public function __construct() + { + $this->data = new \Slim\Helper\Set(); + } + + /******************************************************************************** + * Data methods + *******************************************************************************/ + + /** + * Does view data have value with key? + * @param string $key + * @return boolean + */ + public function has($key) + { + return $this->data->has($key); + } + + /** + * Return view data value with key + * @param string $key + * @return mixed + */ + public function get($key) + { + return $this->data->get($key); + } + + /** + * Set view data value with key + * @param string $key + * @param mixed $value + */ + public function set($key, $value) + { + $this->data->set($key, $value); + } + + /** + * Set view data value as Closure with key + * @param string $key + * @param mixed $value + */ + public function keep($key, Closure $value) + { + $this->data->keep($key, $value); + } + + /** + * Return view data + * @return array + */ + public function all() + { + return $this->data->all(); + } + + /** + * Replace view data + * @param array $data + */ + public function replace(array $data) + { + $this->data->replace($data); + } + + /** + * Clear view data + */ + public function clear() + { + $this->data->clear(); + } + + /******************************************************************************** + * Legacy data methods + *******************************************************************************/ + + /** + * DEPRECATION WARNING! This method will be removed in the next major point release + * + * Get data from view + */ + public function getData($key = null) + { + if (!is_null($key)) { + return isset($this->data[$key]) ? $this->data[$key] : null; + } else { + return $this->data->all(); + } + } + + /** + * DEPRECATION WARNING! This method will be removed in the next major point release + * + * Set data for view + */ + public function setData() + { + $args = func_get_args(); + if (count($args) === 1 && is_array($args[0])) { + $this->data->replace($args[0]); + } elseif (count($args) === 2) { + // Ensure original behavior is maintained. DO NOT invoke stored Closures. + if (is_object($args[1]) && method_exists($args[1], '__invoke')) { + $this->data->set($args[0], $this->data->protect($args[1])); + } else { + $this->data->set($args[0], $args[1]); + } + } else { + throw new \InvalidArgumentException('Cannot set View data with provided arguments. Usage: `View::setData( $key, $value );` or `View::setData([ key => value, ... ]);`'); + } + } + + /** + * DEPRECATION WARNING! This method will be removed in the next major point release + * + * Append data to view + * @param array $data + */ + public function appendData($data) + { + if (!is_array($data)) { + throw new \InvalidArgumentException('Cannot append view data. Expected array argument.'); + } + $this->data->replace($data); + } + + /******************************************************************************** + * Resolve template paths + *******************************************************************************/ + + /** + * Set the base directory that contains view templates + * @param string $directory + * @throws \InvalidArgumentException If directory is not a directory + */ + public function setTemplatesDirectory($directory) + { + $this->templatesDirectory = rtrim($directory, DIRECTORY_SEPARATOR); + } + + /** + * Get templates base directory + * @return string + */ + public function getTemplatesDirectory() + { + return $this->templatesDirectory; + } + + /** + * Get fully qualified path to template file using templates base directory + * @param string $file The template file pathname relative to templates base directory + * @return string + */ + public function getTemplatePathname($file) + { + return $this->templatesDirectory . DIRECTORY_SEPARATOR . ltrim($file, DIRECTORY_SEPARATOR); + } + + /******************************************************************************** + * Rendering + *******************************************************************************/ + + /** + * Display template + * + * This method echoes the rendered template to the current output buffer + * + * @param string $template Pathname of template file relative to templates directory + * @param array $data Any additonal data to be passed to the template. + */ + public function display($template, $data = null) + { + echo $this->fetch($template, $data); + } + + /** + * Return the contents of a rendered template file + * + * @param string $template The template pathname, relative to the template base directory + * @param array $data Any additonal data to be passed to the template. + * @return string The rendered template + */ + public function fetch($template, $data = null) + { + return $this->render($template, $data); + } + + /** + * Render a template file + * + * NOTE: This method should be overridden by custom view subclasses + * + * @param string $template The template pathname, relative to the template base directory + * @param array $data Any additonal data to be passed to the template. + * @return string The rendered template + * @throws \RuntimeException If resolved template pathname is not a valid file + */ + protected function render($template, $data = null) + { + $templatePathname = $this->getTemplatePathname($template); + if (!is_file($templatePathname)) { + throw new \RuntimeException("View cannot render `$template` because the template does not exist"); + } + + $data = array_merge($this->data->all(), (array) $data); + extract($data); + ob_start(); + require $templatePathname; + + return ob_get_clean(); + } +} diff --git a/config.inc.php b/config.inc.php new file mode 100644 index 0000000..0251c1a --- /dev/null +++ b/config.inc.php @@ -0,0 +1,8 @@ +get('/photos/thumbnail/:imageID(/:createImgTag)', function ($imageID, $createImgTag = 0) use ($app) { + $mysqlconnetion = new MysqlClass; + + $retObj = $mysqlconnetion->queryToObject("select type_format, image_thumbnail from immagini where id=" . $imageID, false); + $mysqlconnetion->disconnetti(); + + if($createImgTag) + echo ''; + else + { + $app->contentType($retObj["type_format"]); + echo $retObj['image_thumbnail']; + } +}); + +$app->get('/photos/:imageID(/:createImgTag)', function ($imageID, $createImgTag = 0) use ($app) { + $mysqlconnetion = new MysqlClass; + + $retObj = $mysqlconnetion->queryToObject("select type_format, image from immagini where id=" . $imageID, false); + $mysqlconnetion->disconnetti(); + + if($createImgTag) + echo ''; +}); + +$app->put('/photos/publish/:imageID', function ($imageID) use ($app) { + $mysqlconnetion = new MysqlClass; + + $query = "update immagini set published = 1, published_date = NOW() where ProfiloID = " . $imageID; + $mysqlconnetion->disconnetti(); + $mysqlconnetion->insertRecord($query); + $mysqlconnetion->disconnetti(); +}); + +$app->post('/photos', function () use ($app) { + $idRicette = $app->request()->post('ricetta_id'); + $profileID = $app->request()->post('keyStore'); + $imageFileName = $_FILES['image']["tmp_name"]; + + $layer = ImageWorkshop::initFromPath($imageFileName); + $layer->resizeByLargestSideInPixel(640, true); + + $layer->save(dirname($imageFileName), basename($imageFileName)); + + $imgData = addslashes(file_get_contents($imageFileName)); + + $layer->resizeByLargestSideInPixel(300, true); + + $layer->save(dirname($imageFileName), basename($imageFileName)); + + $ThumbImageData = addslashes(file_get_contents($imageFileName)); + +// istanza della classe + $mysqlconnetion = new MysqlClass; +//$mysqlconneti on->connetti(); + $query = "insert into immagini(id_ricette, type_format, image_thumbnail, image, from_profile_id, uploaded_date) " . + "values(" . $idRicette . ", '" . image_type_to_mime_type($image->image_type) . + "', '" . $ThumbImageData . "', '" . $imgData . "', '" . $profileID . "', NOW())"; + $newID = $mysqlconnetion->insertRecord($query); + $mysqlconnetion->disconnetti(); + + echo $newID; +}); + +$app->put('/photos/:imageID', function ($imageID) use ($app) { + $imageFileName = $_FILES['image']["tmp_name"]; + + $layer = ImageWorkshop::initFromPath($imageFileName); + $layer->resizeByLargestSideInPixel(640, true); + + $layer->save(dirname($imageFileName), basename($imageFileName)); + + $imgData = addslashes(file_get_contents($imageFileName)); + + $layer->resizeByLargestSideInPixel(300, true); + + $layer->save(dirname($imageFileName), basename($imageFileName)); + + $ThumbImageData = addslashes(file_get_contents($imageFileName)); + +// istanza della classe + $mysqlconnetion = new MysqlClass; +//$mysqlconneti on->connetti(); + $query = "update immagini set (type_format = '" . image_type_to_mime_type($image->image_type) . "', " . + "image_thumbnail = '" . $ThumbImageData . "', " . + "image = '" . $imgData . "' where id=" . $imageID; + + $newID = $mysqlconnetion->insertRecord($query); + $mysqlconnetion->disconnetti(); + + return $newID; +}); diff --git a/include.php b/include.php new file mode 100644 index 0000000..b400eb4 --- /dev/null +++ b/include.php @@ -0,0 +1,31 @@ +hook('slim.before.router', function () use ($app, $allowedHost) { + $currentRefererRequest = $app->request()->getReferer(); + $currentRefererRequest = substr(substr($currentRefererRequest, 7), 0, strpos(substr($currentRefererRequest, 7), '/')); + if(!in_array($currentRefererRequest, $allowedHost)) + { + $app->halt(500, "Generic error occurred"); + } + + $currentHostRequest = $app->request()->getHost(); + if(!in_array($currentHostRequest, $allowedHost)) + { + $app->halt(403, "Request arrive from host not allowed " . $currentHostRequest ); + } +}); + + +?> \ No newline at end of file diff --git a/management.php b/management.php new file mode 100644 index 0000000..e4165ae --- /dev/null +++ b/management.php @@ -0,0 +1,165 @@ +get('/categories', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + //$mysqlconneti on->connetti(); + $retObj = $mysqlconnetion->queryToObject("select ID as category_id, NAME as name from categorie order by name"); + $mysqlconnetion->disconnetti(); + + returnJsonWithDecode($app, $callbackFn, $retObj); +}); + +$app->get('/typeingredients', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $retObj = $mysqlconnetion->queryToObject("select ID as tipo_ingredienti_id, name from tipo_ingredienti order by name"); + $mysqlconnetion->disconnetti(); + + returnJsonWithDecode($app, $callbackFn, $retObj); +}); + +$app->get('/typeqtys', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $retObj = $mysqlconnetion->queryToObject("select ID as tipo_quantita_id, name from tipo_quantita"); + $mysqlconnetion->disconnetti(); + + returnJsonWithDecode($app, $callbackFn, $retObj); +}); + +$app->get('/categoryitems/:catID', function ($categoryID) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $query = "select ID as ricetta_id, titolo, autore, valutazione, difficolta from ricette where ID_CATEGORIA = " . $categoryID . " order by titolo, autore"; + $retObj = $mysqlconnetion->queryToObject($query); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retObj); +}); + +$app->get('/ricetta/body/:itemID', function ($itemID) use ($app) { + $callbackFn = $app->request()->get('callback'); + // istanza della classe + $mysqlconnetion = new MysqlClass; + $query = "SELECT id_categoria, categorie.name AS categoria_name, ricette.ID AS ricetta_id, titolo, procedimento, autore, link_fonte, link_youtube, valutazione, difficolta FROM ricette INNER JOIN categorie ON categorie.ID = ricette.id_categoria WHERE ricette.ID = " . $itemID; + $retObj = $mysqlconnetion->queryToObject($query); + + $query2 = "select ingredienti.id_tipo_ingredienti, tipo_ingredienti.name as nome_ingrediente, quantita, ingredienti.id_tipo_quantita, tipo_quantita.Name as unita, note, posizione from ingredienti " . + "inner join tipo_ingredienti on ingredienti.ID_TIPO_INGREDIENTI = tipo_ingredienti.ID " . + "left outer join tipo_quantita on ingredienti.ID_TIPO_QUANTITA = tipo_quantita.ID " . + "where ingredienti.ID_RICETTE = " . $itemID . " order by ingredienti.posizione"; + + $retObj2 = $mysqlconnetion->queryToObject($query2); + + $retObj[0]["titolo"] = html_entity_decode($retObj[0]["titolo"],ENT_COMPAT | ENT_HTML401,'ISO-8859-1'); + $retObj[0]["procedimento"] = html_entity_decode($retObj[0]["procedimento"],ENT_COMPAT | ENT_HTML401,'ISO-8859-1'); + $retObj[0]["ingredienti"] = $retObj2; + + $mysqlconnetion->disconnetti(); + returnJson($app, $callbackFn, $retObj); +}); + +$app->post('/typeingredients', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $json_data_body = json_decode($app->request()->post('bodydata')); + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $query = "insert into tipo_ingredienti(Name) values ('" . $json_data_body->name . "')"; + + $retNewID = $mysqlconnetion->insertRecord($query); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retNewID); +}); + +$app->post('/ricetta/body', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $json_data_body = json_decode($app->request()->post('bodydata')); + $retValue["result"] = true; + $retValue["message"] = ""; + $mysqlconnetion = new MysqlClass; + // istanza della classe + try { + $retNewID = 0; + if ($json_data_body->ricettaID != "") { + $query = "update ricette SET ID_CATEGORIA = " . $json_data_body->categoria_id . + ", titolo = '" . htmlentities($json_data_body->titolo, null, "UTF-8") . + "', procedimento = '" . str_replace("'", "''", htmlentities($json_data_body->preparazione, null, "UTF-8")) . + "', autore = '" . str_replace("'", "''", $json_data_body->autore) . + "', link_fonte = '" . $json_data_body->linkFonte . + "', Link_youtube = '" . $json_data_body->linkVideo . + "', Difficolta = '" . $json_data_body->difficolta . + "' where ID = " . $json_data_body->ricettaID; + + $mysqlconnetion->executeQuery($query); + $queryDelete = "DELETE FROM ingredienti where ID_RICETTE = " . $json_data_body->ricettaID; + $mysqlconnetion->executeQuery($queryDelete); + $retNewID = $json_data_body->ricettaID; + } else { + + $query = "insert into ricette(ID_CATEGORIA, titolo, procedimento, autore, link_fonte, Link_youtube,Difficolta) values (" . + $json_data_body->categoria_id . ",'" . htmlentities($json_data_body->titolo, null, "UTF-8") . "','" . str_replace("'", "''", htmlentities($json_data_body->preparazione, null, "UTF-8")) . + "','" . str_replace("'", "''", $json_data_body->autore) . "','" . + $json_data_body->linkFonte . "','" . $json_data_body->linkVideo . "', " . $json_data_body->difficolta . ")"; + + $retNewID = $mysqlconnetion->insertRecord($query); + } + + $pos = 0; + foreach ($json_data_body->ingredienti as $arr) { + $note = ""; + if ($arr->note != "") { + $note = str_replace("'", "''", htmlentities($arr->note)); + } + + $query = "insert into ingredienti(ID_TIPO_INGREDIENTI, ID_RICETTE, Quantita, ID_TIPO_QUANTITA, Note, Posizione) values (" . + $arr->ingrediente_id . "," . $retNewID . "," . ($arr->quantita == "" ? "0" : $arr->quantita) . "," . ($arr->tipo_quantita_id == "" ? "NULL" : $arr->tipo_quantita_id) . ",'" . $note . "'," . $pos . ")"; + + $mysqlconnetion->insertRecord($query); + $pos = $pos + 1; + } + + $retValue["message"] = "Ricetta inserita con successo"; + } catch (Exception $e) { + $retValue["message"] = $e->getMessage(); + } + + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retValue); +}); + +$app->get('/photos/', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + + $query = "SELECT * from ( SELECT id as ricetta_id, `titolo`,`autore`, ". + " (select COUNT(*) from immagini where immagini.id_ricette = `ricette`.id) as num_img,". + " (select COUNT(*) from immagini where immagini.id_ricette = `ricette`.id and immagini.published = 1) as num_img_pub". + " FROM `ricette`". + " ) as tmp". + " WHERE tmp.num_img> 0"; + + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $retObj = $mysqlconnetion->queryToObject($query); + $mysqlconnetion->disconnetti(); + returnJson($app, $callbackFn, $retObj); +}); + +$app->get('/ricetta/:itemID/photos', function ($itemID) use ($app) { + $callbackFn = $app->request()->get('callback'); + + $query = "SELECT id as id_photo, type_format, from_profile_id, uploaded_date, profilo.Name as profile_name, published from immagini" . + " INNER JOIN profilo ON profilo.ProfiloID = immagini.from_profile_id". + " WHERE id_ricette = " . $itemID; + + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $retObj = $mysqlconnetion->queryToObject($query); + $mysqlconnetion->disconnetti(); + returnJson($app, $callbackFn, $retObj); +}); \ No newline at end of file diff --git a/profile.php b/profile.php new file mode 100644 index 0000000..43b2044 --- /dev/null +++ b/profile.php @@ -0,0 +1,111 @@ +get('/profile/:keyStore/ricetta/:ricetta_id', function ($keyStore, $ricetta_id) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + $query = "select COUNT(*) as Exist FROM blocco_note where ricetta_id = " . $ricetta_id . " AND ProfiloID = '" . $keyStore . "'"; + $retObj = $mysqlconnetion->queryToObject($query); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retObj[0]["Exist"]); +}); + +$app->post('/profile/ricetta', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $json_data_body = json_decode($app->request()->post('dataPair')); + $mysqlconnetion = new MysqlClass; + $query = "insert into blocco_note(ricetta_id, ProfiloID) values (" . $json_data_body->ricetta_id . ", '" . $json_data_body->keyStore . "')"; + $retNewID = $mysqlconnetion->insertRecord($query); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retNewID); +}); + +$app->delete('/profile/:keyStore/ricetta/:ricetta_id', function ($keyStore, $ricetta_id) use ($app) { + //$callbackFn = $app->request()->params('callback'); + $mysqlconnetion = new MysqlClass; + $query = "delete from blocco_note where ricetta_id = " . $ricetta_id . " AND ProfiloID = '" . $keyStore . "'"; + + $retNewID = $mysqlconnetion->insertRecord($query); + $mysqlconnetion->disconnetti(); + + echo $retNewID; + //returnJson($app, $callbackFn, $retNewID); +}); + +$app->delete('/profile/:keyStore/ricette', function ($keyStore) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + $query = "delete from blocco_note where ProfiloID = '" . $keyStore . "'"; + + $retNewID = $mysqlconnetion->insertRecord($query); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retNewID); +}); + +$app->get('/profile/:keyStore/ricette', function ($keyStore) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + $query = "select ID as ricetta_id, titolo, autore, valutazione, difficolta from ricette" . + " INNER JOIN blocco_note ON blocco_note.ricetta_id = ricette.id" . + " where blocco_note.ProfiloID = '" . $keyStore . "' order by titolo, autore"; + $retObj = $mysqlconnetion->queryToObject($query); + $mysqlconnetion->disconnetti(); + + foreach ($retObj as $ele) { + $ele["titolo"] = html_entity_decode($ele["titolo"]); + } + + returnJson($app, $callbackFn, $retObj); +}); + +$app->get('/profile/:keyStore', function ($keyStore) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + $query = "select ProfiloID, TipoAccesso, RisultatiRicerca, TemaUI, Name, Gender, 0 as NumRicette from profilo" . + " where ProfiloID = '" . $keyStore . "'"; + $retObj = $mysqlconnetion->queryToObject($query); + + $query = "update profilo set PenultimoAccesso = UltimoAccesso, UltimoAccesso = NOW() where ProfiloID = '" . $keyStore . "'"; + $mysqlconnetion->insertRecord($query); + + $query = "SELECT COUNT( * ) as NumRicette FROM ricette WHERE data_creazione > ( SELECT PenultimoAccesso FROM profilo " . + "WHERE `ProfiloID` = '" . $keyStore . "' )"; + + $retObj2 = $mysqlconnetion->queryToObject($query); + + $retObj[0]["NumRicette"] = $retObj2[0]["NumRicette"]; + + returnJson($app, $callbackFn, $retObj); +}); + +$app->post('/profile', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $json_data_body = json_decode($app->request()->post('dataPair')); + $mysqlconnetion = new MysqlClass; + $query = "insert into profilo(ProfiloID, Name, Email, Gender, TipoAccesso, RisultatiRicerca, TemaUI, UltimoAccesso, CreatoIl) values ('" . $json_data_body->keyStore . "', '" . $json_data_body->name . "', '" . $json_data_body->email . "', '" . $json_data_body->gender . "', '" . $json_data_body->type . "', '" . $json_data_body->risRic . "', '" . $json_data_body->tema . "', NOW(), NOW())"; + + $retNewID = $mysqlconnetion->insertRecord($query); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retNewID); +}); + +$app->put('/profile', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $json_data_body = json_decode($app->request()->post('dataPair')); + $mysqlconnetion = new MysqlClass; + $query = "update profilo set RisultatiRicerca = '" . $json_data_body->risRic . "', TemaUI = '" . $json_data_body->tema . "' where ProfiloID = '" . $json_data_body->keyStore . "'"; + + $retNewID = $mysqlconnetion->insertRecord($query); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retNewID); +}); + +?> diff --git a/ricette.php b/ricette.php new file mode 100644 index 0000000..cd3d887 --- /dev/null +++ b/ricette.php @@ -0,0 +1,178 @@ +get('/categories', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + //$mysqlconneti on->connetti(); + $retObj = $mysqlconnetion->queryToObject("select ID as category_id, NAME as name from categorie order by name"); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retObj); +}); + +$app->get('/typeingredients', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $retObj = $mysqlconnetion->queryToObject("select ID as tipo_ingredienti_id, name from tipo_ingredienti order by name"); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retObj); +}); + +$app->get('/typeqtys', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $retObj = $mysqlconnetion->queryToObject("select ID as tipo_quantita_id, name from tipo_quantita"); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retObj); +}); + +$app->get('/categoryitems/:catID', function ($categoryID) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $query = "select ID as ricetta_id, titolo, autore, valutazione, difficolta from ricette where ID_CATEGORIA = " . $categoryID . " order by titolo, autore"; + $retObj = $mysqlconnetion->queryToObject($query); + $mysqlconnetion->disconnetti(); + + foreach ($retObj as $ele) { + $ele["titolo"] = html_entity_decode($ele["titolo"], ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'); + } + + returnJson($app, $callbackFn, $retObj); +}); + +$app->get('/categoryitems/:categoryID/mostvote(/:numItems)', function ($categoryID, $numItems = 10) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $query = "select ID as ricetta_id, titolo, autore from ricette where ID_CATEGORIA = " . $categoryID . " order by Valutazione desc, titolo, autore LIMIT " . $numItems; + $retObj = $mysqlconnetion->queryToObject($query); + $mysqlconnetion->disconnetti(); + + foreach ($retObj as $ele) { + $ele["titolo"] = html_entity_decode($ele["titolo"], ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'); + } + + returnJson($app, $callbackFn, $retObj); +}); + +$app->get('/categoryitems/:categoryID/lastinserted(/:numItems)', function ($categoryID, $numItems = 10) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $query = "select ID as ricetta_id, titolo, autore from ricette where ID_CATEGORIA = " . $categoryID . " order by Data_creazione desc, titolo, autore LIMIT " . $numItems; + $retObj = $mysqlconnetion->queryToObject($query); + $mysqlconnetion->disconnetti(); + + foreach ($retObj as $ele) { + $ele["titolo"] = html_entity_decode($ele["titolo"], ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'); + } + + returnJson($app, $callbackFn, $retObj); +}); + +$app->get('/categoryitems/search/:numItems(/:categoryId(/:difficolta(/:titolo)))', + function ($numItems = 10, $categoryId = 0, $difficolta = 0, $titolo = "") use ($app) { + $callbackFn = $app->request()->get('callback'); + //$filterItem = json_decode($app->request()->post('post')); + $mysqlconnetion = new MysqlClass; + $query = "select ricette.ID as ricetta_id, categorie.name AS categoria_name, titolo, autore, valutazione, difficolta from ricette" + . " INNER JOIN categorie ON categorie.ID = ricette.id_categoria" + . " where 1 = 1"; + if ($categoryId > 0) { + $query = $query . " AND ID_CATEGORIA = " . $categoryId; + } + if ($titolo != null && $titolo != "") { + foreach (explode(" ", $titolo) as $ele) + $query = $query . " AND titolo like '%" . $ele . "%'"; + } + if ($difficolta > 0) { + $query = $query . " AND difficolta = " . $difficolta; + } + $query = $query . " order by titolo, autore LIMIT " . $numItems; + $retObj = $mysqlconnetion->queryToObject($query); + $mysqlconnetion->disconnetti(); + + foreach ($retObj as $ele) { + $ele["titolo"] = html_entity_decode($ele["titolo"], ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'); + } + returnJson($app, $callbackFn, $retObj); +}); + +$app->get('/ricetta/body/:itemID', function ($itemID) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + + $query = "UPDATE ricette Set valutazione = valutazione + 1 WHERE ricette.ID = " . $itemID; + $mysqlconnetion->executeQuery($query); + + $query = "SELECT id_categoria, categorie.name AS categoria_name, ricette.ID AS ricetta_id, titolo, procedimento, autore, link_fonte, link_youtube, valutazione FROM ricette INNER JOIN categorie ON categorie.ID = ricette.id_categoria WHERE ricette.ID = " . $itemID; + $retObj = $mysqlconnetion->queryToObject($query); + + $query2 = "select ingredienti.id_tipo_ingredienti, tipo_ingredienti.name as nome_ingrediente, quantita, ingredienti.id_tipo_quantita, tipo_quantita.Name as unita, note, posizione from ingredienti " . + "inner join tipo_ingredienti on ingredienti.ID_TIPO_INGREDIENTI = tipo_ingredienti.ID " . + "left outer join tipo_quantita on ingredienti.ID_TIPO_QUANTITA = tipo_quantita.ID " . + "where ingredienti.ID_RICETTE = " . $itemID . " order by ingredienti.posizione"; + + $retObj2 = $mysqlconnetion->queryToObject($query2); + + $retObj[0]["titolo"] = html_entity_decode($retObj[0]["titolo"], ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'); + $retObj[0]["procedimento"] = html_entity_decode($retObj[0]["procedimento"], ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'); + $retObj[0]["ingredienti"] = $retObj2; + + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retObj); +}); + +$app->get('/ricetta/header/:itemID', function ($itemID) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + $query = "UPDATE ricette Set valutazione = valutazione + 1 WHERE ricette.ID = " . $itemID; + $mysqlconnetion->executeQuery($query); + $query = "SELECT id_categoria, categorie.name AS categoria_name, ricette.ID AS ricetta_id, titolo, procedimento, autore, link_fonte, link_youtube, valutazione FROM ricette INNER JOIN categorie ON categorie.ID = ricette.id_categoria WHERE ricette.ID = " . $itemID; + $retObj = $mysqlconnetion->queryToObject($query); + $retObj[0]["titolo"] = html_entity_decode($retObj[0]["titolo"], ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'); + $retObj[0]["procedimento"] = html_entity_decode($retObj[0]["procedimento"], ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'); + $data = $retObj[0]["link_youtube"]; + $output = array(); + if ($data != "") { + $d = explode(";", $data); + $index = 0; + foreach ($d as $ele) { + $obj["VideoID"] = $ele; + $output[$index] = $obj; + $index++; + } + } + $retObj[0]["link_youtube"] = $output; + $mysqlconnetion->disconnetti(); + returnJson($app, $callbackFn, $retObj); +}); + +$app->get('/ricetta/ingredienti/:itemID', function ($itemID) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + $query2 = "select ingredienti.id_tipo_ingredienti, tipo_ingredienti.name as nome_ingrediente, quantita, ingredienti.id_tipo_quantita, tipo_quantita.Name as unita, note, posizione from ingredienti " . + "inner join tipo_ingredienti on ingredienti.ID_TIPO_INGREDIENTI = tipo_ingredienti.ID " . + "left outer join tipo_quantita on ingredienti.ID_TIPO_QUANTITA = tipo_quantita.ID " . + "where ingredienti.ID_RICETTE = " . $itemID . " order by ingredienti.posizione"; + + $retObj2 = $mysqlconnetion->queryToObject($query2); + + //$retObj[0]["titolo"] = html_entity_decode($retObj[0]["titolo"]); + //$retObj[0]["procedimento"] = html_entity_decode($retObj[0]["procedimento"]); + //$retObj[0]["ingredienti"] = $retObj2; + + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retObj2); +}); +?> diff --git a/serviceapp.php b/serviceapp.php new file mode 100644 index 0000000..0857f4b --- /dev/null +++ b/serviceapp.php @@ -0,0 +1,16 @@ +group('/api', function () use ($app) { + include "./ricette.php"; + include "./profile.php"; + include "./image.php"; +}); + +$app->group('/backend', function () use ($app) { + include "./management.php"; +}); +//include "./image.php"; + +$app->run(); \ No newline at end of file diff --git a/utility.php b/utility.php new file mode 100644 index 0000000..76caec5 --- /dev/null +++ b/utility.php @@ -0,0 +1,78 @@ += '300000') { + return false; + } + + /* step through inArray */ + foreach ($inArray as $key => $val) { + if (is_array($val)) { + /* recurse on array elements */ + $newArray[$key] = utf8json($val); + } else { + /* encode string values */ + $newArray[$key] = utf8_encode($val); + } + } + /* return utf8 encoded array */ + return $newArray; + } + /* return utf8 encoded array */ + return $inArray; +} + +function returnJsonWithDecode($app, $callbackFn, $retObj) { + if ($callbackFn) { + $app->contentType('application/javascript; Charset=UTF-8'); + echo $callbackFn . "(" . html_entity_decode(json_encode(utf8json($retObj)), ENT_COMPAT | ENT_HTML401, 'ISO-8859-1') . ")"; + } else { + $app->contentType('application/x-json; Charset=UTF-8'); + echo html_entity_decode(json_encode(utf8json($retObj)), ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'); + } +} + +function returnJson($app, $callbackFn, $retObj) { + if ($callbackFn) { + $app->contentType('application/javascript; Charset=UTF-8'); + echo $callbackFn . "(" . (json_encode(utf8json($retObj))) . ")"; + } else { + $app->contentType('application/x-json; Charset=UTF-8'); + echo (json_encode(utf8json($retObj))); + } +} + +function makeThumbnail($im) { + $final_width_of_image = 300; + $ox = imagesx($im); + $oy = imagesy($im); + + $nx = $final_width_of_image; + $ny = floor($oy * ($final_width_of_image / $ox)); + + $nm = imagecreatetruecolor($nx, $ny); + + imagecopyresized($nm, $im, 0, 0, 0, 0, $nx, $ny, $ox, $oy); + + return $nm; +} + +function getContentFromResources($res) { + ob_start(); //Start output buffer. + imagejpeg($res); //This will normally output the image, but because of ob_start(), it won't. + $contents = ob_get_contents(); //Instead, output above is saved to $contents + ob_end_clean(); //End the output buffer. + + return $contents; +} + +?> From f7d8f47f575f4424bcebcca424af7e2ecfb5b95e Mon Sep 17 00:00:00 2001 From: hexstudy Date: Wed, 10 Dec 2014 15:19:03 +0000 Subject: [PATCH 3/3] git-svn-id: https://msi/svn/firstRepo/Service/trunk@23 0f545695-f87b-41b6-9a03-7f16563b5454 --- .htaccess | 24 +- DropBoxPhp/DropboxClient.php | 681 +++ DropBoxPhp/OAuthSimple.php | 532 +++ DropBoxPhp/sample-form.php | 85 + DropBoxPhp/sample.php | 133 + DropBoxPhp/test_download_Apps | 1 + DropBoxPhp/tokens/access.token | 1 + MySqlClass.php | 174 +- .../Exception/ImageWorkshopLayerException.php | 42 +- .../Exception/ImageWorkshopLibException.php | 42 +- PHPImageWorkshop/Core/ImageWorkshopLayer.php | 3808 ++++++++--------- PHPImageWorkshop/Core/ImageWorkshopLib.php | 596 +-- .../Exception/ImageWorkshopBaseException.php | 74 +- .../Exception/ImageWorkshopException.php | 42 +- PHPImageWorkshop/ImageWorkshop.php | 334 +- config.inc.php | 18 +- image.php | 261 +- include.php | 5 +- management.php | 328 +- mdbTester.php | 53 + myDropBoxObj.php | 78 + nbproject/private/config.properties | 0 nbproject/private/private.properties | 9 + nbproject/private/private.xml | 7 + nbproject/project.properties | 7 + nbproject/project.xml | 9 + profile.php | 222 +- ricette.php | 24 +- serviceapp.php | 30 +- utility.php | 165 +- 30 files changed, 4732 insertions(+), 3053 deletions(-) create mode 100644 DropBoxPhp/DropboxClient.php create mode 100644 DropBoxPhp/OAuthSimple.php create mode 100644 DropBoxPhp/sample-form.php create mode 100644 DropBoxPhp/sample.php create mode 100644 DropBoxPhp/test_download_Apps create mode 100644 DropBoxPhp/tokens/access.token create mode 100644 mdbTester.php create mode 100644 myDropBoxObj.php create mode 100644 nbproject/private/config.properties create mode 100644 nbproject/private/private.properties create mode 100644 nbproject/private/private.xml create mode 100644 nbproject/project.properties create mode 100644 nbproject/project.xml diff --git a/.htaccess b/.htaccess index 0189d10..5332f1b 100644 --- a/.htaccess +++ b/.htaccess @@ -1,12 +1,12 @@ - - RewriteEngine On - RewriteCond %{REQUEST_FILENAME} !-f - RewriteRule ^(.*)$ serviceapp.php [QSA,L] - - - - Allow from *.gruppolapastamadre.it - - -Header set Access-Control-Allow-Origin *.gruppolapastamadre.it -Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT" \ No newline at end of file + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^(.*)$ serviceapp.php [QSA,L] + + + +# Allow from app.gruppolapastamadre.it + + +#Header set Access-Control-Allow-Origin "app.gruppolapastamadre.it" +#Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT" \ No newline at end of file diff --git a/DropBoxPhp/DropboxClient.php b/DropBoxPhp/DropboxClient.php new file mode 100644 index 0000000..426dbfe --- /dev/null +++ b/DropBoxPhp/DropboxClient.php @@ -0,0 +1,681 @@ + + * @copyright Fabian Schlieper 2012 + * @version 1.7 + * @license See LICENSE + * + */ + +require_once(dirname(__FILE__)."/OAuthSimple.php"); + +class DropboxClient { + + const API_URL = "https://api.dropbox.com/1/"; + const API_CONTENT_URL = "https://api-content.dropbox.com/1/"; + + const BUFFER_SIZE = 4096; + + const MAX_UPLOAD_CHUNK_SIZE = 150000000; // 150MB + + const UPLOAD_CHUNK_SIZE = 4000000; // 4MB + + private $appParams; + private $consumerToken; + + private $requestToken; + private $accessToken; + + private $locale; + private $rootPath; + + private $useCurl; + + function __construct ($app_params, $locale = "en"){ + $this->appParams = $app_params; + if(empty($app_params['app_key'])) + throw new DropboxException("App Key is empty!"); + + $this->consumerToken = array('t' => $this->appParams['app_key'], 's' => $this->appParams['app_secret']); + $this->locale = $locale; + $this->rootPath = empty($app_params['app_full_access']) ? "sandbox" : "dropbox"; + + $this->requestToken = null; + $this->accessToken = null; + + $this->useCurl = function_exists('curl_init'); + } + + /** + * Sets whether to use cURL if its available or PHP HTTP wrappers otherwise + * + * @access public + * @return boolean Whether to actually use cURL (always false if not installed) + */ + public function SetUseCUrl($use_it) + { + return ($this->useCurl = ($use_it && function_exists('curl_init'))); + } + + // ################################################## + // Authorization + + /** + * Step 1 of authentication process. Retrieves a request token or returns a previously retrieved one. + * + * @access public + * @param boolean $get_new_token Optional (default false). Wether to retrieve a new request token. + * @return array Request Token array. + */ + public function GetRequestToken($get_new_token=false) + { + if(!empty($this->requestToken) && !$get_new_token) + return $this->requestToken; + + $rt = $this->authCall("oauth/request_token"); + if(empty($rt) || empty($rt['oauth_token'])) + throw new DropboxException('Could not get request token!'); + + return ($this->requestToken = array('t'=>$rt['oauth_token'], 's'=>$rt['oauth_token_secret'])); + } + + /** + * Step 2. Returns a URL the user must be redirected to in order to connect the app to their Dropbox account + * + * @access public + * @param string $return_url URL users are redirected after authorization + * @return string URL + */ + public function BuildAuthorizeUrl($return_url) + { + $rt = $this->GetRequestToken(); + if(empty($rt) || empty($rt['t'])) throw new DropboxException('Request Token Invalid ('.print_r($rt,true).').'); + return "https://www.dropbox.com/1/oauth/authorize?oauth_token=".$rt['t']."&oauth_callback=".urlencode($return_url); + } + + /** + * Step 3. Acquires an access token. This is the final step of authentication. + * + * @access public + * @param array $request_token Optional. The previously retrieved request token. This parameter can only be skipped if the DropboxClient object has been (de)serialized. + * @return array Access Token array. + */ + public function GetAccessToken($request_token = null) + { + if(!empty($this->accessToken)) return $this->accessToken; + + if(empty($request_token)) $request_token = $this->requestToken; + if(empty($request_token)) throw new DropboxException('Request token required!'); + + $at = $this->authCall("oauth/access_token", $request_token); + if(empty($at)) + throw new DropboxException(sprintf('Could not get access token! (request token: %s)', $request_token['t'])); + + return ($this->accessToken = array('t'=>$at['oauth_token'], 's'=>$at['oauth_token_secret'])); + } + + /** + * Sets a previously retrieved (and stored) access token. + * + * @access public + * @param string|object $token The Access Token + * @return none + */ + public function SetAccessToken($token) + { + if(empty($token['t']) || empty($token['s'])) throw new DropboxException('Passed invalid access token.'); + $this->accessToken = $token; + } + + /** + * Checks if an access token has been set. + * + * @access public + * @return boolean Authorized or not + */ + public function IsAuthorized() + { + if(empty($this->accessToken)) return false; + return true; + } + + + // ################################################## + // API Functions + + + /** + * Retrieves information about the user's account. + * + * @access public + * @return object Account info object. See https://www.dropbox.com/developers/reference/api#account-info + */ + public function GetAccountInfo() + { + return $this->apiCall("account/info", "GET"); + } + + + /** + * Get file list of a dropbox folder. + * + * @access public + * @param string|object $dropbox_path Dropbox path of the folder + * @return array An array with metadata of files/folders keyed by paths + */ + public function GetFiles($dropbox_path='', $recursive=false, $include_deleted=false) + { + if(is_object($dropbox_path) && !empty($dropbox_path->path)) $dropbox_path = $dropbox_path->path; + return $this->getFileTree($dropbox_path, $include_deleted, $recursive ? 1000 : 0); + } + + /** + * Get file or folder metadata + * + * @access public + * @param $dropbox_path string Dropbox path of the file or folder + */ + public function GetMetadata($dropbox_path, $include_deleted=false, $rev=null) + { + if(is_object($dropbox_path) && !empty($dropbox_path->path)) $dropbox_path = $dropbox_path->path; + return $this->apiCall("metadata/$this->rootPath/$dropbox_path", "GET", compact('include_deleted','rev')); + } + + /** + * Download a file to the webserver + * + * @access public + * @param string|object $dropbox_file Dropbox path or metadata object of the file to download. + * @param string $dest_path Local path for destination + * @param string $rev Optional. The revision of the file to retrieve. This defaults to the most recent revision. + * @param callback $progress_changed_callback Optional. Callback that will be called during download with 2 args: 1. bytes loaded, 2. file size + * @return object Dropbox file metadata + */ + public function DownloadFile($dropbox_file, $dest_path='', $rev=null, $progress_changed_callback = null) + { + if(is_object($dropbox_file) && !empty($dropbox_file->path)) + $dropbox_file = $dropbox_file->path; + + if(empty($dest_path)) $dest_path = basename($dropbox_file); + + $url = $this->cleanUrl(self::API_CONTENT_URL."/files/$this->rootPath/$dropbox_file") + . (!empty($rev) ? ('?'.http_build_query(array('rev' => $rev),'','&')) : ''); + $context = $this->createRequestContext($url, "GET"); + + $fh = @fopen($dest_path, 'wb'); // write binary + if($fh === false) { + @fclose($rh); + throw new DropboxException("Could not create file $dest_path !"); + } + + if($this->useCurl) { + curl_setopt($context, CURLOPT_BINARYTRANSFER, true); + curl_setopt($context, CURLOPT_RETURNTRANSFER, true); + curl_setopt($context, CURLOPT_FILE, $fh); + $response_headers = array(); + self::execCurlAndClose($context, $response_headers); + fclose($fh); + $meta = self::getMetaFromHeaders($response_headers, true); + $bytes_loaded = filesize($dest_path); + } else { + $rh = @fopen($url, 'rb', false, $context); // read binary + if($rh === false) + throw new DropboxException("HTTP request to $url failed!"); + + + // get file meta from HTTP header + $s_meta = stream_get_meta_data($rh); + $meta = self::getMetaFromHeaders($s_meta['wrapper_data'], true); + $bytes_loaded = 0; + while (!feof($rh)) { + if(($s=fwrite($fh, fread($rh, self::BUFFER_SIZE))) === false) { + @fclose($rh); + @fclose($fh); + throw new DropboxException("Writing to file $dest_path failed!'"); + } + $bytes_loaded += $s; + if(!empty($progress_changed_callback)) { + call_user_func($progress_changed_callback, $bytes_loaded, $meta->bytes); + } + } + + fclose($rh); + fclose($fh); + } + + if($meta->bytes != $bytes_loaded) + throw new DropboxException("Download size mismatch! (header:{$meta->bytes} vs actual:{$bytes_loaded}; curl:{$this->useCurl})"); + + return $meta; + } + + /** + * Upload a file to dropbox + * + * @access public + * @param $src_file string Local file to upload + * @param $dropbox_path string Dropbox path for destination + * @return object Dropbox file metadata + */ + public function UploadFile($src_file, $dropbox_path='', $overwrite=true, $parent_rev=null) + { + if(empty($dropbox_path)) $dropbox_path = basename($src_file); + elseif(is_object($dropbox_path) && !empty($dropbox_path->path)) $dropbox_path = $dropbox_path->path; + + // make sure the dropbox_path is not a dir. if it is, append baseneme of $src_file + $dropbox_bn = basename($dropbox_path); + if(strpos($dropbox_bn,'.') === false) { // check if ext. is missing -> could be a directory! + try { + $meta = $this->GetMetadata($dropbox_path); + if($meta && $meta->is_dir) + $dropbox_path = $dropbox_path . '/'. basename($src_file); + } catch(Exception $e) {} + } + + $file_size = filesize($src_file); + + if($file_size > self::MAX_UPLOAD_CHUNK_SIZE) + { + $fh = fopen($src_file,'rb'); + if($fh === false) + throw new DropboxException(); + + $upload_id = null; + $offset = 0; + + + while(!feof($fh)) { + $url = $this->cleanUrl(self::API_CONTENT_URL."/chunked_upload").'?'.http_build_query(compact('upload_id', 'offset'),'','&'); + + if($this->useCurl) { + $context = $this->createRequestContext($url, "PUT"); + curl_setopt($context, CURLOPT_BINARYTRANSFER, true); + curl_setopt($context, CURLOPT_PUT, 1); + curl_setopt($context, CURLOPT_INFILE, $fh); + $chunk_size = min(self::UPLOAD_CHUNK_SIZE, $file_size - $offset); + $offset += $chunk_size; + curl_setopt($context, CURLOPT_INFILESIZE, $chunk_size); + $response = json_decode(self::execCurlAndClose($context)); + + fseek($fh,$offset); + if($offset >= $file_size) + break; + } else { + $content = fread($fh, self::UPLOAD_CHUNK_SIZE); + + $context = $this->createRequestContext($url, "PUT", $content); + $offset += strlen($content); + unset($content); + + $response = json_decode(file_get_contents($url, false, $context)); + } + unset($context); + + self::checkForError($response); + + if(empty($upload_id)) { + $upload_id = $response->upload_id; + if(empty($upload_id)) throw new DropboxException("Upload ID empty!"); + } + } + + @fclose($fh); + + $this->useCurl = $prev_useCurl; + + return $this->apiCall("commit_chunked_upload/$this->rootPath/$dropbox_path", "POST", compact('overwrite','parent_rev','upload_id'), true); + } + + $query = http_build_query(array_merge(compact('overwrite', 'parent_rev'), array('locale' => $this->locale)),'','&'); + $url = $this->cleanUrl(self::API_CONTENT_URL."/files_put/$this->rootPath/$dropbox_path")."?$query"; + + if($this->useCurl) { + $context = $this->createRequestContext($url, "PUT"); + curl_setopt($context, CURLOPT_BINARYTRANSFER, true); + $fh = fopen($src_file, 'rb'); + curl_setopt($context, CURLOPT_PUT, 1); + curl_setopt($context, CURLOPT_INFILE, $fh); // file pointer + curl_setopt($context, CURLOPT_INFILESIZE, filesize($src_file)); + $meta = json_decode(self::execCurlAndClose($context)); + fclose($fh); + return self::checkForError($meta); + } else { + $content = file_get_contents($src_file); + if(strlen($content) == 0) + throw new DropboxException("Could not read file $src_file or file is empty!"); + + $context = $this->createRequestContext($url, "PUT", $content); + + return self::checkForError(json_decode(file_get_contents($url, false, $context))); + } + } + + /** + * Get thumbnail for a specified image + * + * @access public + * @param $dropbox_file string Path to the image + * @param $format string Image format of the thumbnail (jpeg or png) + * @param $size string Thumbnail size (xs, s, m, l, xl) + * @return mime/* Returns the thumbnail as binary image data + */ + public function GetThumbnail($dropbox_file, $size = 's', $format = 'jpeg', $echo = false) + { + if(is_object($dropbox_file) && !empty($dropbox_file->path)) $dropbox_file = $dropbox_file->path; + $url = $this->cleanUrl(self::API_CONTENT_URL."thumbnails/$this->rootPath/$dropbox_file") + . '?' . http_build_query(array('format' => $format, 'size' => $size),'','&'); + $context = $this->createRequestContext($url, "GET"); + + if($this->useCurl) { + curl_setopt($context, CURLOPT_BINARYTRANSFER, true); + curl_setopt($context, CURLOPT_RETURNTRANSFER, true); + } + + $thumb = $this->useCurl ? self::execCurlAndClose($context) : file_get_contents($url, NULL, $context); + + if($echo) { + header('Content-type: image/'.$format); + echo $thumb; + unset($thumb); + return; + } + + return $thumb; + } + + + function GetLink($dropbox_file, $preview=true, $short=true, &$expires=null) + { + if(is_object($dropbox_file) && !empty($dropbox_file->path)) $dropbox_file = $dropbox_file->path; + $url = $this->apiCall(($preview?"shares":"media")."/$this->rootPath/$dropbox_file", "POST", array('locale' => null, 'short_url'=> $preview ? $short : null)); + $expires = strtotime($url->expires); + return $url->url; + } + + function Delta($cursor) + { + return $this->apiCall("delta", "POST", compact('cursor')); + } + + function GetRevisions($dropbox_file, $rev_limit=10) + { + if(is_object($dropbox_file) && !empty($dropbox_file->path)) $dropbox_file = $dropbox_file->path; + return $this->apiCall("revisions/$this->rootPath/$dropbox_file", "GET", compact('rev_limit')); + } + + function Restore($dropbox_file, $rev) + { + if(is_object($dropbox_file) && !empty($dropbox_file->path)) $dropbox_file = $dropbox_file->path; + return $this->apiCall("restore/$this->rootPath/$dropbox_file", "POST", compact('rev')); + } + + function Search($path, $query, $file_limit=1000, $include_deleted=false) + { + return $this->apiCall("search/$this->rootPath/$path", "POST", compact('query','file_limit','include_deleted')); + } + + function GetCopyRef($dropbox_file, &$expires=null) + { + if(is_object($dropbox_file) && !empty($dropbox_file->path)) $dropbox_file = $dropbox_file->path; + $ref = $this->apiCall("copy_ref/$this->rootPath/$dropbox_file", "GET", array('locale' => null)); + $expires = strtotime($ref->expires); + return $ref->copy_ref; + } + + + function Copy($from_path, $to_path, $copy_ref=false) + { + if(is_object($from_path) && !empty($from_path->path)) $from_path = $from_path->path; + return $this->apiCall("fileops/copy", "POST", array('root'=> $this->rootPath, ($copy_ref ? 'from_copy_ref' : 'from_path') => $from_path, 'to_path' => $to_path)); + } + + /** + * Creates a new folder in the DropBox + * + * @access public + * @param $path string The path to the new folder to create + * @return object Dropbox folder metadata + */ + function CreateFolder($path) + { + return $this->apiCall("fileops/create_folder", "POST", array('root'=> $this->rootPath, 'path' => $path)); + } + + /** + * Delete file or folder + * + * @access public + * @param $path mixed The path or metadata of the file/folder to be deleted. + * @return object Dropbox metadata of deleted file or folder + */ + function Delete($path) + { + if(is_object($path) && !empty($path->path)) $path = $path->path; + return $this->apiCall("fileops/delete", "POST", array('locale' =>null, 'root'=> $this->rootPath, 'path' => $path)); + } + + function Move($from_path, $to_path) + { + if(is_object($from_path) && !empty($from_path->path)) $from_path = $from_path->path; + return $this->apiCall("fileops/move", "POST", array('root'=> $this->rootPath, 'from_path' => $from_path, 'to_path' => $to_path)); + } + + function getFileTree($path="", $include_deleted = false, $max_depth = 0, $depth=0) + { + static $files; + if($depth == 0) $files = array(); + + $dir = $this->apiCall("metadata/$this->rootPath/$path", "GET", compact('include_deleted')); + + if(empty($dir) || !is_object($dir)) return false; + + if(!empty($dir->error)) throw new DropboxException($dir->error); + + foreach($dir->contents as $item) + { + $files[trim($item->path,'/')] = $item; + if($item->is_dir && $depth < $max_depth) + { + $this->getFileTree($item->path, $include_deleted, $max_depth, $depth+1); + } + } + + return $files; + } + + function createCurl($url, $http_context) + { + $ch = curl_init($url); + + $curl_opts = array( + CURLOPT_HEADER => false, // exclude header from output + //CURLOPT_MUTE => true, // no output! + CURLOPT_RETURNTRANSFER => true, // but return! + CURLOPT_SSL_VERIFYPEER => false, + ); + + $curl_opts[CURLOPT_CUSTOMREQUEST] = $http_context['method']; + + if(!empty($http_context['content'])) { + $curl_opts[CURLOPT_POSTFIELDS] =& $http_context['content']; + if(defined("CURLOPT_POSTFIELDSIZE")) + $curl_opts[CURLOPT_POSTFIELDSIZE] = strlen($http_context['content']); + } + + $curl_opts[CURLOPT_HTTPHEADER] = array_map('trim',explode("\n",$http_context['header'])); + + curl_setopt_array($ch, $curl_opts); + return $ch; + } + + static private $_curlHeadersRef; + static function _curlHeaderCallback($ch, $header) + { + self::$_curlHeadersRef[] = trim($header); + return strlen($header); + } + + static function &execCurlAndClose($ch, &$out_response_headers = null) + { + if(is_array($out_response_headers)) { + self::$_curlHeadersRef =& $out_response_headers; + curl_setopt($ch, CURLOPT_HEADERFUNCTION, array(__CLASS__, '_curlHeaderCallback')); + } + $res = curl_exec($ch); + $err_no = curl_errno($ch); + $err_str = curl_error($ch); + curl_close($ch); + if($err_no || $res === false) { + throw new DropboxException("cURL-Error ($err_no): $err_str"); + } + + return $res; + } + + private function createRequestContext($url, $method, &$content=null, $oauth_token=-1) + { + if($oauth_token === -1) + $oauth_token = $this->accessToken; + + $method = strtoupper($method); + $http_context = array('method'=>$method, 'header'=> ''); + + $oauth = new OAuthSimple($this->consumerToken['t'],$this->consumerToken['s']); + + if(empty($oauth_token) && !empty($this->accessToken)) + $oauth_token = $this->accessToken; + + if(!empty($oauth_token)) { + $oauth->setParameters(array('oauth_token' => $oauth_token['t'])); + $oauth->signatures(array('oauth_secret'=>$oauth_token['s'])); + } + + if(!empty($content)) { + $post_vars = ($method != "PUT" && preg_match("/^[a-z][a-z0-9_]*=/i", substr($content, 0, 32))); + $http_context['header'] .= "Content-Length: ".strlen($content)."\r\n"; + $http_context['header'] .= "Content-Type: application/".($post_vars?"x-www-form-urlencoded":"octet-stream")."\r\n"; + $http_context['content'] =& $content; + if($method == "POST" && $post_vars) + $oauth->setParameters($content); + } elseif($method == "POST") { + // make sure that content-length is always set when post request (otherwise some wrappers fail!) + $http_context['content'] = ""; + $http_context['header'] .= "Content-Length: 0\r\n"; + } + + + // check for query vars in url and add them to oauth parameters (and remove from path) + $path = $url; + $query = strrchr($url,'?'); + if(!empty($query)) { + $oauth->setParameters(substr($query,1)); + $path = substr($url, 0, -strlen($query)); + } + + + $signed = $oauth->sign(array( + 'action' => $method, + 'path'=> $path)); + //print_r($signed); + + $http_context['header'] .= "Authorization: ".$signed['header']."\r\n"; + + return $this->useCurl ? $this->createCurl($url, $http_context) : stream_context_create(array('http'=>$http_context)); + } + + private function authCall($path, $request_token=null) + { + $url = $this->cleanUrl(self::API_URL.$path); + $dummy = null; + $context = $this->createRequestContext($url, "POST", $dummy, $request_token); + + $contents = $this->useCurl ? self::execCurlAndClose($context) : file_get_contents($url, false, $context); + $data = array(); + parse_str($contents, $data); + return $data; + } + + private static function checkForError($resp) + { + if(!empty($resp->error)) + throw new DropboxException($resp->error); + return $resp; + } + + + private function apiCall($path, $method, $params=array(), $content_call=false) + { + $url = $this->cleanUrl(($content_call ? self::API_CONTENT_URL : self::API_URL).$path); + $content = http_build_query(array_merge(array('locale'=>$this->locale), $params),'','&'); + + if($method == "GET") { + $url .= "?".$content; + $content = null; + } + + $context = $this->createRequestContext($url, $method, $content); + $json = $this->useCurl ? self::execCurlAndClose($context) : file_get_contents($url, false, $context); + //if($json === false) +// throw new DropboxException(); + $resp = json_decode($json); + return self::checkForError($resp); + } + + + private static function getMetaFromHeaders(&$header_array, $throw_on_error=false) + { + $obj = json_decode(substr(@array_shift(array_filter($header_array, create_function('$s', 'return stripos($s, "x-dropbox-metadata:") === 0;'))), 20)); + if($throw_on_error && (empty($obj)||!is_object($obj))) + throw new DropboxException("Could not retrieve meta data from header data: ".print_r($header_array,true)); + if($throw_on_error) + self::checkForError ($obj); + return $obj; + } + + + function cleanUrl($url) { + $p = substr($url,0,8); + $url = str_replace('//','/', str_replace('\\','/',substr($url,8))); + $url = rawurlencode($url); + $url = str_replace('%2F', '/', $url); + return $p.$url; + } +} + +class DropboxException extends Exception { + + public function __construct($err = null, $isDebug = FALSE) + { + if(is_null($err)) { + $el = error_get_last(); + $this->message = $el['message']; + $this->file = $el['file']; + $this->line = $el['line']; + } else + $this->message = $err; + self::log_error($err); + if ($isDebug) + { + self::display_error($err, TRUE); + } + } + + public static function log_error($err) + { + error_log($err, 0); + } + + public static function display_error($err, $kill = FALSE) + { + print_r($err); + if ($kill === FALSE) + { + die(); + } + } +} diff --git a/DropBoxPhp/OAuthSimple.php b/DropBoxPhp/OAuthSimple.php new file mode 100644 index 0000000..130123b --- /dev/null +++ b/DropBoxPhp/OAuthSimple.php @@ -0,0 +1,532 @@ + + * @copyright unitedHeroes.net 2011 + * @version 1.3 + * @license See OAuthSimple_license.txt + * + */ + +class OAuthSimple { + private $_secrets; + private $_default_signature_method; + private $_action; + private $_nonce_chars; + + /** + * Constructor + * + * @access public + * @param api_key (String) The API Key (sometimes referred to as the consumer key) This value is usually supplied by the site you wish to use. + * @param shared_secret (String) The shared secret. This value is also usually provided by the site you wish to use. + * @return OAuthSimple (Object) + */ + function __construct ($APIKey = "", $sharedSecret=""){ + + if (!empty($APIKey)) + { + $this->_secrets['consumer_key'] = $APIKey; + } + + if (!empty($sharedSecret)) + { + $this->_secrets['shared_secret'] = $sharedSecret; + } + + $this->_default_signature_method = "HMAC-SHA1"; + $this->_action = "GET"; + $this->_nonce_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + + return $this; + } + + /** + * Reset the parameters and URL + * + * @access public + * @return OAuthSimple (Object) + */ + public function reset() { + $this->_parameters = Array(); + $this->path = NULL; + $this->sbs = NULL; + + return $this; + } + + /** + * Set the parameters either from a hash or a string + * + * @access public + * @param(string, object) List of parameters for the call, this can either be a URI string (e.g. "foo=bar&gorp=banana" or an object/hash) + * @return OAuthSimple (Object) + */ + public function setParameters ($parameters=Array()) { + + if (is_string($parameters)) + { + $parameters = $this->_parseParameterString($parameters); + } + if (empty($this->_parameters)) + { + $this->_parameters = $parameters; + } + else if (!empty($parameters)) + { + $this->_parameters = array_merge($this->_parameters,$parameters); + } + if (empty($this->_parameters['oauth_nonce'])) + { + $this->_getNonce(); + } + if (empty($this->_parameters['oauth_timestamp'])) + { + $this->_getTimeStamp(); + } + if (empty($this->_parameters['oauth_consumer_key'])) + { + $this->_getApiKey(); + } + if (empty($this->_parameters['oauth_token'])) + { + $this->_getAccessToken(); + } + if (empty($this->_parameters['oauth_signature_method'])) + { + $this->setSignatureMethod(); + } + if (empty($this->_parameters['oauth_version'])) + { + $this->_parameters['oauth_version']="1.0"; + } + + return $this; + } + + /** + * Convenience method for setParameters + * + * @access public + * @see setParameters + */ + public function setQueryString ($parameters) + { + return $this->setParameters($parameters); + } + + /** + * Set the target URL (does not include the parameters) + * + * @param path (String) the fully qualified URI (excluding query arguments) (e.g "http://example.org/foo") + * @return OAuthSimple (Object) + */ + public function setURL ($path) + { + if (empty($path)) + { + throw new OAuthSimpleException('No path specified for OAuthSimple.setURL'); + } + $this->_path=$path; + + return $this; + } + + /** + * Convenience method for setURL + * + * @param path (String) + * @see setURL + */ + public function setPath ($path) + { + return $this->_path=$path; + } + + /** + * Set the "action" for the url, (e.g. GET,POST, DELETE, etc.) + * + * @param action (String) HTTP Action word. + * @return OAuthSimple (Object) + */ + public function setAction ($action) + { + if (empty($action)) + { + $action = 'GET'; + } + $action = strtoupper($action); + if (preg_match('/[^A-Z]/',$action)) + { + throw new OAuthSimpleException('Invalid action specified for OAuthSimple.setAction'); + } + $this->_action = $action; + + return $this; + } + + /** + * Set the signatures (as well as validate the ones you have) + * + * @param signatures (object) object/hash of the token/signature pairs {api_key:, shared_secret:, oauth_token: oauth_secret:} + * @return OAuthSimple (Object) + */ + public function signatures ($signatures) + { + if (!empty($signatures) && !is_array($signatures)) + { + throw new OAuthSimpleException('Must pass dictionary array to OAuthSimple.signatures'); + } + if (!empty($signatures)) + { + if (empty($this->_secrets)) + { + $this->_secrets=Array(); + } + $this->_secrets=array_merge($this->_secrets,$signatures); + } + if (isset($this->_secrets['api_key'])) + { + $this->_secrets['consumer_key'] = $this->_secrets['api_key']; + } + if (isset($this->_secrets['access_token'])) + { + $this->_secrets['oauth_token'] = $this->_secrets['access_token']; + } + if (isset($this->_secrets['access_secret'])) + { + $this->_secrets['oauth_secret'] = $this->_secrets['access_secret']; + } + if (isset($this->_secrets['access_token_secret'])) + { + $this->_secrets['oauth_secret'] = $this->_secrets['access_token_secret']; + } + if (empty($this->_secrets['consumer_key'])) + { + throw new OAuthSimpleException('Missing required consumer_key in OAuthSimple.signatures'); + } + if (empty($this->_secrets['shared_secret'])) + { + throw new OAuthSimpleException('Missing requires shared_secret in OAuthSimple.signatures'); + } + if (!empty($this->_secrets['oauth_token']) && empty($this->_secrets['oauth_secret'])) + { + throw new OAuthSimpleException('Missing oauth_secret for supplied oauth_token in OAuthSimple.signatures'); + } + + return $this; + } + + public function setTokensAndSecrets($signatures) + { + return $this->signatures($signatures); + } + + /** + * Set the signature method (currently only Plaintext or SHA-MAC1) + * + * @param method (String) Method of signing the transaction (only PLAINTEXT and SHA-MAC1 allowed for now) + * @return OAuthSimple (Object) + */ + public function setSignatureMethod ($method="") + { + if (empty($method)) + { + $method = $this->_default_signature_method; + } + $method = strtoupper($method); + switch($method) + { + case 'PLAINTEXT': + case 'HMAC-SHA1': + $this->_parameters['oauth_signature_method']=$method; + break; + default: + throw new OAuthSimpleException ("Unknown signing method $method specified for OAuthSimple.setSignatureMethod"); + break; + } + + return $this; + } + + /** sign the request + * + * note: all arguments are optional, provided you've set them using the + * other helper functions. + * + * @param args (Array) hash of arguments for the call {action, path, parameters (array), method, signatures (array)} all arguments are optional. + * @return (Array) signed values + */ + public function sign($args=array()) + { + if (!empty($args['action'])) + { + $this->setAction($args['action']); + } + if (!empty($args['path'])) + { + $this->setPath($args['path']); + } + if (!empty($args['method'])) + { + $this->setSignatureMethod($args['method']); + } + if (!empty($args['signatures'])) + { + $this->signatures($args['signatures']); + } + if (empty($args['parameters'])) + { + $args['parameters']=array(); + } + $this->setParameters($args['parameters']); + $normParams = $this->_normalizedParameters(); + $this->_parameters['oauth_signature'] = $this->_generateSignature($normParams); + + return Array ( + 'parameters' => $this->_parameters, + 'signature' => self::_oauthEscape($this->_parameters['oauth_signature']), + 'signed_url' => $this->_path . '?' . $this->_normalizedParameters(), + 'header' => $this->getHeaderString(), + 'sbs'=> $this->sbs + ); + } + + /** + * Return a formatted "header" string + * + * NOTE: This doesn't set the "Authorization: " prefix, which is required. + * It's not set because various set header functions prefer different + * ways to do that. + * + * @param args (Array) + * @return $result (String) + */ + public function getHeaderString ($args=array()) + { + if (empty($this->_parameters['oauth_signature'])) + { + $this->sign($args); + } + $result = 'OAuth '; + + foreach ($this->_parameters as $pName => $pValue) + { + if (strpos($pName,'oauth_') !== 0 || $pName == 'oauth_token_secret2') + { + continue; + } + if (is_array($pValue)) + { + foreach ($pValue as $val) + { + $result .= $pName .'="' . self::_oauthEscape($val) . '", '; + } + } + else + { + $result .= $pName . '="' . self::_oauthEscape($pValue) . '", '; + } + } + + return preg_replace('/, $/','',$result); + } + + private function _parseParameterString ($paramString) + { + $elements = explode('&',$paramString); + $result = array(); + foreach ($elements as $element) + { + list ($key,$token) = explode('=',$element); + if ($token) + { + $token = urldecode($token); + } + if (!empty($result[$key])) + { + if (!is_array($result[$key])) + { + $result[$key] = array($result[$key],$token); + } + else + { + array_push($result[$key],$token); + } + } + else + $result[$key]=$token; + } + return $result; + } + + + private static function _oauthEscape($string) + { + if ($string === 0) { return 0; } + if ($string == '0') { return '0'; } + if (strlen($string) == 0) { return ''; } + if (is_array($string)) { + throw new OAuthSimpleException('Array passed to _oauthEscape'); + } + $string = rawurlencode($string); + + $string = str_replace('+','%20',$string); + $string = str_replace('!','%21',$string); + $string = str_replace('*','%2A',$string); + $string = str_replace('\'','%27',$string); + $string = str_replace('(','%28',$string); + $string = str_replace(')','%29',$string); + + return $string; + } + + private function _getNonce($length=5) + { + $result = ''; + $cLength = strlen($this->_nonce_chars); + for ($i=0; $i < $length; $i++) + { + $rnum = rand(0,$cLength); + $result .= substr($this->_nonce_chars,$rnum,1); + } + $result = md5($result); + $this->_parameters['oauth_nonce'] = $result; + + return $result; + } + + private function _getApiKey() + { + if (empty($this->_secrets['consumer_key'])) + { + throw new OAuthSimpleException('No consumer_key set for OAuthSimple'); + } + $this->_parameters['oauth_consumer_key']=$this->_secrets['consumer_key']; + + return $this->_parameters['oauth_consumer_key']; + } + + private function _getAccessToken() + { + if (!isset($this->_secrets['oauth_secret'])) + { + return ''; + } + if (!isset($this->_secrets['oauth_token'])) + { + throw new OAuthSimpleException('No access token (oauth_token) set for OAuthSimple.'); + } + $this->_parameters['oauth_token'] = $this->_secrets['oauth_token']; + + return $this->_parameters['oauth_token']; + } + + private function _getTimeStamp() + { + return $this->_parameters['oauth_timestamp'] = time(); + } + + private function _normalizedParameters() + { + $normalized_keys = array(); + $return_array = array(); + + foreach ( $this->_parameters as $paramName=>$paramValue) { + if (!preg_match('/\w+_secret/',$paramName) OR (strpos($paramValue, '@') !== 0 && !file_exists(substr($paramValue, 1))) ) + { + if (is_array($paramValue)) + { + $normalized_keys[self::_oauthEscape($paramName)] = array(); + foreach($paramValue as $item) + { + array_push($normalized_keys[self::_oauthEscape($paramName)], self::_oauthEscape($item)); + } + } + else + { + $normalized_keys[self::_oauthEscape($paramName)] = self::_oauthEscape($paramValue); + } + } + } + + ksort($normalized_keys); + + foreach($normalized_keys as $key=>$val) + { + if (is_array($val)) + { + sort($val); + foreach($val as $element) + { + array_push($return_array, $key . "=" . $element); + } + } + else + { + array_push($return_array, $key .'='. $val); + } + + } + + return join("&", $return_array); + } + + + private function _generateSignature () + { + $secretKey = ''; + if(isset($this->_secrets['shared_secret'])) + { + $secretKey = self::_oauthEscape($this->_secrets['shared_secret']); + } + + $secretKey .= '&'; + if(isset($this->_secrets['oauth_secret'])) + { + $secretKey .= self::_oauthEscape($this->_secrets['oauth_secret']); + } + + switch($this->_parameters['oauth_signature_method']) + { + case 'PLAINTEXT': + return urlencode($secretKey);; + case 'HMAC-SHA1': + $this->sbs = self::_oauthEscape($this->_action).'&'.self::_oauthEscape($this->_path).'&'.self::_oauthEscape($this->_normalizedParameters()); + + return base64_encode(hash_hmac('sha1',$this->sbs,$secretKey,TRUE)); + default: + throw new OAuthSimpleException('Unknown signature method for OAuthSimple'); + break; + } + } +} + +class OAuthSimpleException extends Exception { + + public function __construct($err, $isDebug = FALSE) + { + self::log_error($err); + if ($isDebug) + { + self::display_error($err, TRUE); + } + } + + public static function log_error($err) + { + error_log($err, 0); + } + + public static function display_error($err, $kill = FALSE) + { + print_r($err); + if ($kill === FALSE) + { + die(); + } + } +} diff --git a/DropBoxPhp/sample-form.php b/DropBoxPhp/sample-form.php new file mode 100644 index 0000000..c439f63 --- /dev/null +++ b/DropBoxPhp/sample-form.php @@ -0,0 +1,85 @@ + "ft0zodv89xx804e", + 'app_secret' => "ut43sn7m9wufy3s", + 'app_full_access' => true, +),'it'); + +handle_dropbox_auth($dropbox); // see below + +// if there is no upload, show the form +if(empty($_FILES['the_upload'])) { +?> +
+

+ + +

+

+
+"; + echo "\r\n\r\nUploading $upload_name:\r\n"; + $meta = $dropbox->UploadFile($_FILES["the_upload"]["tmp_name"], $upload_name); + print_r($meta); + echo "\r\n done!"; + echo ""; +} + + +// ================================================================================ +// store_token, load_token, delete_token are SAMPLE functions! please replace with your own! +function store_token($token, $name) +{ + file_put_contents("tokens/$name.token", serialize($token)); +} + +function load_token($name) +{ + if(!file_exists("tokens/$name.token")) return null; + return @unserialize(@file_get_contents("tokens/$name.token")); +} + +function delete_token($name) +{ + @unlink("tokens/$name.token"); +} +// ================================================================================ + +function handle_dropbox_auth($dropbox) +{ + // first try to load existing access token + $access_token = load_token("access"); + if(!empty($access_token)) { + $dropbox->SetAccessToken($access_token); + } + elseif(!empty($_GET['auth_callback'])) // are we coming from dropbox's auth page? + { + // then load our previosly created request token + $request_token = load_token($_GET['oauth_token']); + if(empty($request_token)) die('Request token not found!'); + + // get & store access token, the request token is not needed anymore + $access_token = $dropbox->GetAccessToken($request_token); + store_token($access_token, "access"); + delete_token($_GET['oauth_token']); + } + + // checks if access token is required + if(!$dropbox->IsAuthorized()) + { + // redirect user to dropbox auth page + $return_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']."?auth_callback=1"; + $auth_url = $dropbox->BuildAuthorizeUrl($return_url); + $request_token = $dropbox->GetRequestToken(); + store_token($request_token, $request_token['t']); + die("Authentication required. Click here."); + } +} \ No newline at end of file diff --git a/DropBoxPhp/sample.php b/DropBoxPhp/sample.php new file mode 100644 index 0000000..393023b --- /dev/null +++ b/DropBoxPhp/sample.php @@ -0,0 +1,133 @@ + + * @copyright Fabian Schlieper 2012 + * @version 1.1 + * @license See license.txt + * + */ + + +// these 2 lines are just to enable error reporting and disable output buffering (don't include this in you application!) +error_reporting(E_ALL); +enable_implicit_flush(); +// -- end of unneeded stuff + +// if there are many files in your Dropbox it can take some time, so disable the max. execution time +set_time_limit(0); + +require_once("DropboxClient.php"); + +// you have to create an app at https://www.dropbox.com/developers/apps and enter details below: +$dropbox = new DropboxClient(array( + 'app_key' => "ft0zodv89xx804e", + 'app_secret' => "ut43sn7m9wufy3s", + 'app_full_access' => true, +),'it'); + + +// first try to load existing access token +$access_token = load_token("access"); +if(!empty($access_token)) { + $dropbox->SetAccessToken($access_token); + echo "loaded access token:"; + print_r($access_token); +} +elseif(!empty($_GET['auth_callback'])) // are we coming from dropbox's auth page? +{ + // then load our previosly created request token + $request_token = load_token($_GET['oauth_token']); + if(empty($request_token)) die('Request token not found!'); + + // get & store access token, the request token is not needed anymore + $access_token = $dropbox->GetAccessToken($request_token); + store_token($access_token, "access"); + delete_token($_GET['oauth_token']); +} + +// checks if access token is required +if(!$dropbox->IsAuthorized()) +{ + // redirect user to dropbox auth page + $return_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']."?auth_callback=1"; + $auth_url = $dropbox->BuildAuthorizeUrl($return_url); + $request_token = $dropbox->GetRequestToken(); + store_token($request_token, $request_token['t']); + die("Authentication required. Click here."); +} + +echo "
";
+echo "Account:\r\n";
+print_r($dropbox->GetAccountInfo());
+
+$files = $dropbox->GetFiles("",false);
+
+echo "\r\n\r\nFiles:\r\n";
+print_r(array_keys($files));
+
+if(!empty($files)) {
+	$file = reset($files);
+	$test_file = "test_download_".basename($file->path);
+	
+	echo "\r\n\r\nMeta data of $file->path:\r\n";
+	print_r($dropbox->GetMetadata($file->path));
+	
+	echo "\r\n\r\nDownloading $file->path:\r\n";
+	print_r($dropbox->DownloadFile($file, $test_file));
+		
+	echo "\r\n\r\nUploading $test_file:\r\n";
+	print_r($dropbox->UploadFile($test_file));
+	echo "\r\n done!";	
+	
+	echo "\r\n\r\nRevisions of $test_file:\r\n";	
+	print_r($dropbox->GetRevisions($test_file));
+}
+	
+echo "\r\n\r\nSearching for JPG files:\r\n";	
+$jpg_files = $dropbox->Search("/", ".jpg", 5);
+if(empty($jpg_files))
+	echo "Nothing found.";
+else {
+	print_r($jpg_files);
+	$jpg_file = reset($jpg_files);
+
+	echo "\r\n\r\nThumbnail of $jpg_file->path:\r\n";	
+	$img_data = base64_encode($dropbox->GetThumbnail($jpg_file->path));
+	echo "\"Generating";
+}
+
+
+function store_token($token, $name)
+{
+	if(!file_put_contents("tokens/$name.token", serialize($token)))
+		die('
Could not store token! Make sure that the directory `tokens` exists and is writable!'); +} + +function load_token($name) +{ + if(!file_exists("tokens/$name.token")) return null; + return @unserialize(@file_get_contents("tokens/$name.token")); +} + +function delete_token($name) +{ + @unlink("tokens/$name.token"); +} + + + + + +function enable_implicit_flush() +{ + @apache_setenv('no-gzip', 1); + @ini_set('zlib.output_compression', 0); + @ini_set('implicit_flush', 1); + for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); } + ob_implicit_flush(1); + echo ""; +} \ No newline at end of file diff --git a/DropBoxPhp/test_download_Apps b/DropBoxPhp/test_download_Apps new file mode 100644 index 0000000..d538cda --- /dev/null +++ b/DropBoxPhp/test_download_Apps @@ -0,0 +1 @@ +{"error": "File not found"} \ No newline at end of file diff --git a/DropBoxPhp/tokens/access.token b/DropBoxPhp/tokens/access.token new file mode 100644 index 0000000..42b3ffc --- /dev/null +++ b/DropBoxPhp/tokens/access.token @@ -0,0 +1 @@ +a:2:{s:1:"t";s:16:"2lfmugdr7rp3yp2q";s:1:"s";s:15:"i3nrl13aduhhufw";} \ No newline at end of file diff --git a/MySqlClass.php b/MySqlClass.php index 26eebe3..663a5fc 100644 --- a/MySqlClass.php +++ b/MySqlClass.php @@ -1,89 +1,87 @@ -attiva) - { - $this->connessione = mysql_connect($this->nomehost,$this->nomeuser,$this->password); - if ($this->connessione == FALSE) - die(mysql_error()); - mysql_select_db($this->mydb, $this->connessione) or die ("Errore nella selezione del database. Verificare i parametri nel file config.inc.php"); - $this->attiva = true; - } - else{ - return true; - } - - } - - public function executeQuery($queryStr) - { - $this->connetti(); - - if (!$res = mysql_query($queryStr, $this->connessione)) die(mysql_error()); - return true; - return false; - } - - public function insertRecord($queryStr) - { - $this->connetti(); - - if (!$res = mysql_query($queryStr, $this->connessione)) die(mysql_error()); - return mysql_insert_id(); - } - - public function queryToObject($queryStr) - { - $this->connetti(); - - $sth = mysql_query($queryStr, $this->connessione) or die(mysql_error()); - - $rows = array(); - while($r = mysql_fetch_assoc($sth)) { - array_push($rows,array_map('utf8_encode', $r)); - } - mysql_free_result($sth); - return $rows; - } - - // funzione per la chiusura della connessione - public function disconnetti() - { - if($this->attiva) - { - if(mysql_close($this->connessione)) - { - $this->attiva = false; - return true; - } - else - { - return false; - } - } - } - - public function __destruct() - { - $this->disconnetti(); - } - } +attiva) { + $this->connessione = mysqli_connect($this->nomehost, $this->nomeuser, $this->password); + if ($this->connessione == FALSE) + die(mysqli_error()); + mysqli_select_db($this->connessione, $this->mydb) or die("Errore nella selezione del database. Verificare i parametri nel file config.inc.php"); + $this->attiva = true; + } + else { + return true; + } + } + + public function executeQuery($queryStr) { + $this->connetti(); + + if (!$res = mysqli_query($this->connessione, $queryStr)) + die(mysqli_error()); + return true; + } + + public function insertRecord($queryStr) { + $this->connetti(); + + if (!$res = mysqli_query($this->connessione, $queryStr)) + die(mysqli_error()); + return mysqli_insert_id($this->connessione); + } + + public function queryToObject($queryStr, $encode = true) { + $this->connetti(); + + $sth = mysqli_query($this->connessione, $queryStr) or die(mysqli_error()); + + if($encode){ + $rows = array(); + while ($r = mysqli_fetch_assoc($sth)) { + array_push($rows, array_map('utf8_encode', $r)); + } + mysqli_free_result($sth); + return $rows; + } + else + { + return mysqli_fetch_array($sth); + } + } + + // funzione per la chiusura della connessione + public function disconnetti() { + if ($this->attiva) { + if (mysqli_close($this->connessione)) { + $this->attiva = false; + return true; + } else { + return false; + } + } + } + + public function __destruct() { + $this->disconnetti(); + } + +} + ?> \ No newline at end of file diff --git a/PHPImageWorkshop/Core/Exception/ImageWorkshopLayerException.php b/PHPImageWorkshop/Core/Exception/ImageWorkshopLayerException.php index eac77ca..34c1562 100644 --- a/PHPImageWorkshop/Core/Exception/ImageWorkshopLayerException.php +++ b/PHPImageWorkshop/Core/Exception/ImageWorkshopLayerException.php @@ -1,22 +1,22 @@ -width = imagesx($image); - $this->height = imagesy($image); - $this->image = $image; - $this->layers = $this->layerLevels = $this->layerPositions = array(); - $this->clearStack(); - } - - /** - * Clone method: use it if you want to reuse an existing ImageWorkshop object in another variable - * This is important because img resource var references all the same image in PHP. - * Example: $b = clone $a; (never do $b = $a;) - */ - public function __clone() - { - $this->createNewVarFromBackgroundImage(); - } - - // Superimpose a sublayer - // ========================================================= - - /** - * Add an existing ImageWorkshop sublayer and set it in the stack at a given level - * Return an array containing the generated sublayer id in the stack and its corrected level: - * array("layerLevel" => integer, "id" => integer) - * - * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html - * - * @param integer $layerLevel - * @param ImageWorkshop $layer - * @param integer $positionX - * @param integer $positionY - * @param string $position - * - * @return array - */ - public function addLayer($layerLevel, $layer, $positionX = 0, $positionY = 0, $position = 'LT') - { - return $this->indexLayer($layerLevel, $layer, $positionX, $positionY, $position); - } - - /** - * Add an existing ImageWorkshop sublayer and set it in the stack at the highest level - * Return an array containing the generated sublayer id in the stack and the highest level: - * array("layerLevel" => integer, "id" => integer) - * - * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html - * - * @param ImageWorkshop $layer - * @param integer $positionX - * @param integer $positionY - * @param string $position - * - * @return array - */ - public function addLayerOnTop($layer, $positionX = 0, $positionY = 0, $position = 'LT') - { - return $this->indexLayer($this->highestLayerLevel + 1, $layer, $positionX, $positionY, $position); - } - - /** - * Add an existing ImageWorkshop sublayer and set it in the stack at level 1 - * Return an array containing the generated sublayer id in the stack and level 1: - * array("layerLevel" => integer, "id" => integer) - * - * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html - * - * @param ImageWorkshop $layer - * @param integer $positionX - * @param integer $positionY - * @param string $position - * - * @return array - */ - public function addLayerBelow($layer, $positionX = 0, $positionY = 0, $position = 'LT') - { - return $this->indexLayer(1, $layer, $positionX, $positionY, $position); - } - - // Move a sublayer inside the stack - // ========================================================= - - /** - * Move a sublayer on the top of a group stack - * Return new sublayer level if success or false otherwise - * - * @param integer $layerId - * @return mixed - */ - public function moveTop($layerId) - { - return $this->moveTo($layerId, $this->highestLayerLevel, false); - } - - /** - * Move a sublayer to the level 1 of a group stack - * Return new sublayer level if success or false otherwise - * - * @param integer $layerId - * @param integer $level - * - * @return mixed - */ - public function moveBottom($layerId) - { - return $this->moveTo($layerId, 1, true); - } - - /** - * Move a sublayer to the level $level of a group stack - * Return new sublayer level if success or false if layer isn't found - * - * Set $insertUnderTargetedLayer true if you want to move the sublayer under the other sublayer at the targeted level, - * or false to insert it on the top of the other sublayer at the targeted level - * - * @param integer $layerId - * @param integer $level - * @param boolean $insertUnderTargetedLayer - * - * @return mixed - */ - public function moveTo($layerId, $level, $insertUnderTargetedLayer = true) - { - // if the sublayer exists in stack - if ($this->isLayerInIndex($layerId)) { - - $layerOldLevel = $this->getLayerLevel($layerId); - - if ($level < 1) { - $level = 1; - $insertUnderTargetedLayer = true; - } - - if ($level > $this->highestLayerLevel) { - - $level = $this->highestLayerLevel; - $insertUnderTargetedLayer = false; - } - - // Not the same level than the current level - if ($layerOldLevel != $level) { - - $isUnderAndNewLevelHigher = $isUnderAndNewLevelLower = $isOnTopAndNewLevelHigher = $isOnTopAndNewLevelLower = false; - - if ($insertUnderTargetedLayer) { // Under level - - if ($level > $layerOldLevel) { // new level higher - - $incrementorStartingValue = $layerOldLevel; - $stopLoopWhenSmallerThan = $level; - $isUnderAndNewLevelHigher = true; - - } else { // new level lower - - $incrementorStartingValue = $level; - $stopLoopWhenSmallerThan = $layerOldLevel; - $isUnderAndNewLevelLower = true; - } - - } else { // on the top - - if ($level > $layerOldLevel) { // new level higher - - $incrementorStartingValue = $layerOldLevel; - $stopLoopWhenSmallerThan = $level; - $isOnTopAndNewLevelHigher = true; - - } else { // new level lower - - $incrementorStartingValue = $level; - $stopLoopWhenSmallerThan = $layerOldLevel; - $isOnTopAndNewLevelLower = true; - } - } - - ksort($this->layerLevels); - $layerLevelsTmp = $this->layerLevels; - - if ($isOnTopAndNewLevelLower) { - $level++; - } - - for ($i = $incrementorStartingValue; $i < $stopLoopWhenSmallerThan; $i++) { - - if ($isUnderAndNewLevelHigher || $isOnTopAndNewLevelHigher) { - - $this->layerLevels[$i] = $layerLevelsTmp[$i + 1]; - - } else { - - $this->layerLevels[$i + 1] = $layerLevelsTmp[$i]; - } - } - - unset($layerLevelsTmp); - - if ($isUnderAndNewLevelHigher) { - $level--; - } - - $this->layerLevels[$level] = $layerId; - - return $level; - - } else { - return $level; - } - } - - return false; - } - - /** - * Move up a sublayer in the stack (level +1) - * Return new sublayer level if success, false otherwise - * - * @param integer $layerId - * - * @return mixed - */ - public function moveUp($layerId) - { - if ($this->isLayerInIndex($layerId)) { // if the sublayer exists in the stack - $layerOldLevel = $this->getLayerLevel($layerId); - return $this->moveTo($layerId, $layerOldLevel + 1, false); - } - - return false; - } - - /** - * Move down a sublayer in the stack (level -1) - * Return new sublayer level if success, false otherwise - * - * @param integer $layerId - * - * @return mixed - */ - public function moveDown($layerId) - { - if ($this->isLayerInIndex($layerId)) { // if the sublayer exists in the stack - $layerOldLevel = $this->getLayerLevel($layerId); - return $this->moveTo($layerId, $layerOldLevel - 1, true); - } - - return false; - } - - // Merge layers - // ========================================================= - - /** - * Merge a sublayer with another sublayer below it in the stack - * Note: the result layer will conserve the given id - * Return true if success or false if layer isn't found or doesn't have a layer under it in the stack - * - * @param integer $layerId - * - * @return boolean - */ - public function mergeDown($layerId) - { - // if the layer exists in document - if ($this->isLayerInIndex($layerId)) { - - $layerLevel = $this->getLayerLevel($layerId); - $layerPositions = $this->getLayerPositions($layerId); - $layer = $this->getLayer($layerId); - $layerWidth = $layer->getWidth(); - $layerHeight = $layer->getHeight(); - $layerPositionX = $this->layerPositions[$layerId]['x']; - $layerPositionY = $this->layerPositions[$layerId]['y']; - - if ($layerLevel > 1) { - - $underLayerId = $this->layerLevels[$layerLevel - 1]; - $underLayer = $this->getLayer($underLayerId); - $underLayerWidth = $underLayer->getWidth(); - $underLayerHeight = $underLayer->getHeight(); - $underLayerPositionX = $this->layerPositions[$underLayerId]['x']; - $underLayerPositionY = $this->layerPositions[$underLayerId]['y']; - - $totalWidthLayer = $layerWidth + $layerPositionX; - $totalHeightLayer = $layerHeight + $layerPositionY; - - $totalWidthUnderLayer = $underLayerWidth + $underLayerPositionX; - $totalHeightUnderLayer = $underLayerHeight + $underLayerPositionY; - - $minLayerPositionX = $layerPositionX; - - if ($layerPositionX > $underLayerPositionX) { - $minLayerPositionX = $underLayerPositionX; - } - - $minLayerPositionY = $layerPositionY; - - if ($layerPositionY > $underLayerPositionY) { - $minLayerPositionY = $underLayerPositionY; - } - - if ($totalWidthLayer > $totalWidthUnderLayer) { - $layerTmpWidth = $totalWidthLayer - $minLayerPositionX; - } else { - $layerTmpWidth = $totalWidthUnderLayer - $minLayerPositionX; - } - - if ($totalHeightLayer > $totalHeightUnderLayer) { - $layerTmpHeight = $totalHeightLayer - $minLayerPositionY; - } else { - $layerTmpHeight = $totalHeightUnderLayer - $minLayerPositionY; - } - - $layerTmp = ImageWorkshop::initVirginLayer($layerTmpWidth, $layerTmpHeight); - - $layerTmp->addLayer(1, $underLayer, $underLayerPositionX - $minLayerPositionX, $underLayerPositionY - $minLayerPositionY); - $layerTmp->addLayer(2, $layer, $layerPositionX - $minLayerPositionX, $layerPositionY - $minLayerPositionY); - - // Update layers - $layerTmp->mergeAll(); - $this->layers[$underLayerId] = clone $layerTmp; - $this->changePosition($underLayerId, $minLayerPositionX, $minLayerPositionX); - - } else { - - $layerTmp = ImageWorkshop::initFromResourceVar($this->image); - $layerTmp->addLayer(1, $layer, $layerPositionX, $layerPositionY); - - $this->image = $layerTmp->getResult(); // Update background image - } - - unset($layerTmp); - $this->remove($layerId); // Remove the merged layer from the stack - - return true; - } - - return false; - } - - /** - * Merge sublayers in the stack on the layer background - */ - public function mergeAll() - { - $this->image = $this->getResult(); - $this->clearStack(); - } - - /** - * Paste an image on the layer - * You can specify the position left (in pixels) and the position top (in pixels) of the added image relatives to the layer - * Otherwise, it will be set at 0 and 0 - * - * @param string $unit Use one of `UNIT_*` constants, "UNIT_PIXEL" by default - * @param resource $image - * @param integer $positionX - * @param integer $positionY - */ - public function pasteImage($unit = self::UNIT_PIXEL, $image, $positionX = 0, $positionY = 0) - { - if ($unit == self::UNIT_PERCENT) { - - $positionX = round(($positionX / 100) * $this->width); - $positionY = round(($positionY / 100) * $this->height); - } - - imagecopy($this->image, $image, $positionX, $positionY, 0, 0, $image->getWidth(), $image->getHeight()); - } - - // Change sublayer positions - // ========================================================= - - /** - * Change the position of a sublayer for new positions - * - * @param integer $layerId - * @param integer $newPosX - * @param integer $newPosY - * - * @return boolean - */ - public function changePosition($layerId, $newPosX = null, $newPosY = null) - { - // if the sublayer exists in the stack - if ($this->isLayerInIndex($layerId)) { - - if ($newPosX !== null) { - $this->layerPositions[$layerId]['x'] = $newPosX; - } - - if ($newPosY !== null) { - $this->layerPositions[$layerId]['y'] = $newPosY; - } - - return true; - } - - return false; - } - - /** - * Apply a translation on a sublayer that change its positions - * - * @param integer $layerId - * @param integer $addedPosX - * @param integer $addedPosY - * - * @return mixed (array of new positions or false if fail) - */ - public function applyTranslation($layerId, $addedPosX = null, $addedPosY = null) - { - // if the sublayer exists in the stack - if ($this->isLayerInIndex($layerId)) { - - if ($addedPosX !== null) { - $this->layerPositions[$layerId]['x'] += $addedPosX; - } - - if ($addedPosY !== null) { - $this->layerPositions[$layerId]['y'] += $addedPosY; - } - - return $this->layerPositions[$layerId]; - } - - return false; - } - - // Removing sublayers - // ========================================================= - - /** - * Delete a layer (return true if success, false if no sublayer is found) - * - * @param integer $layerId - * - * @return boolean - */ - public function remove($layerId) - { - // if the layer exists in document - if ($this->isLayerInIndex($layerId)) { - - $layerToDeleteLevel = $this->getLayerLevel($layerId); - - // delete - $this->layers[$layerId]->delete(); - unset($this->layers[$layerId]); - unset($this->layerLevels[$layerToDeleteLevel]); - unset($this->layerPositions[$layerId]); - - // One or plural layers are sub of the deleted layer - if (array_key_exists(($layerToDeleteLevel + 1), $this->layerLevels)) { - - ksort($this->layerLevels); - - $layerLevelsTmp = $this->layerLevels; - - $maxOldestLevel = 1; - foreach ($layerLevelsTmp as $levelTmp => $layerIdTmp) { - - if ($levelTmp > $layerToDeleteLevel) { - $this->layerLevels[($levelTmp - 1)] = $layerIdTmp; - } - - $maxOldestLevel++; - } - unset($layerLevelsTmp); - unset($this->layerLevels[$maxOldestLevel]); - } - - $this->highestLayerLevel--; - - return true; - } - - return false; - } - - /** - * Reset the layer stack - * - * @boolean $deleteSubImgVar Delete sublayers image resource var - */ - public function clearStack($deleteSubImgVar = true) - { - if ($deleteSubImgVar) { - foreach ($this->layers as $layer) { - $layer->delete(); - } - } - - unset($this->layers); - unset($this->layerLevels); - unset($this->layerPositions); - - $this->lastLayerId = 0; - $this->layers = array(); - $this->layerLevels = array(); - $this->layerPositions = array(); - $this->highestLayerLevel = 0; - } - - // Perform an action - // ========================================================= - - /** - * Resize the layer by specifying pixel - * - * @param integer $newWidth - * @param integer $newHeight - * @param boolean $converseProportion - * @param integer $positionX - * @param integer $positionY - * @param string $position - * - * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html - * - * $positionX, $positionY, $position can be ignored unless you choose a new width AND a new height AND to conserve proportion. - */ - public function resizeInPixel($newWidth = null, $newHeight = null, $converseProportion = false, $positionX = 0, $positionY = 0, $position = 'MM') - { - $this->resize(self::UNIT_PIXEL, $newWidth, $newHeight, $converseProportion, $positionX, $positionY, $position); - } - - /** - * Resize the layer by specifying a percent - * - * @param float $percentWidth - * @param float $percentHeight - * @param boolean $converseProportion - * @param integer $positionX - * @param integer $positionY - * @param string $position - * - * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html - * - * $positionX, $positionY, $position can be ignored unless you choose a new width AND a new height AND to conserve proportion. - */ - public function resizeInPercent($percentWidth = null, $percentHeight = null, $converseProportion = false, $positionX = 0, $positionY = 0, $position = 'MM') - { - $this->resize(self::UNIT_PERCENT, $percentWidth, $percentHeight, $converseProportion, $positionX, $positionY, $position); - } - - /** - * Resize the layer to fit a bounding box by specifying pixel - * - * @param integer $width - * @param integer $height - * @param boolean $converseProportion - */ - public function resizeToFit($width, $height, $converseProportion = false) - { - if ($this->getWidth() <= $width && $this->getHeight() <= $height) { - return; - } - - if (!$converseProportion) { - $width = min($width, $this->getWidth()); - $height = min($height, $this->getHeight()); - } - - $this->resize(self::UNIT_PIXEL, $width, $height, $converseProportion ? 2 : false); - } - - /** - * Resize the layer - * - * @param string $unit Use one of `UNIT_*` constants, "UNIT_PIXEL" by default - * @param mixed $newWidth (integer or float) - * @param mixed $newHeight (integer or float) - * @param boolean $converseProportion - * @param mixed $positionX (integer or float) - * @param mixed $positionY (integer or float) - * @param string $position - * - * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html - * - * $positionX, $positionY, $position can be ignored unless you choose a new width AND a new height AND to conserve proportion. - */ - public function resize($unit = self::UNIT_PIXEL, $newWidth = null, $newHeight = null, $converseProportion = false, $positionX = 0, $positionY = 0, $position = 'MM') - { - if (is_numeric($newWidth) || is_numeric($newHeight)) { - - if ($unit == self::UNIT_PERCENT) { - - if ($newWidth) { - $newWidth = round(($newWidth / 100) * $this->width); - } - - if ($newHeight) { - $newHeight = round(($newHeight / 100) * $this->height); - } - } - - if (is_numeric($newWidth) && $newWidth <= 0) { - $newWidth = 1; - } - - if (is_numeric($newHeight) && $newHeight <= 0) { - $newHeight = 1; - } - - if ($converseProportion) { // Proportion are conserved - - if ($newWidth && $newHeight) { // Proportions + $newWidth + $newHeight - - if ($this->getWidth() > $this->getHeight()) { - - $this->resizeInPixel($newWidth, null, true); - - if ($this->getHeight() > $newHeight) { - $this->resizeInPixel(null, $newHeight, true); - } - - } else { - - $this->resizeInPixel(null, $newHeight, true); - - if ($this->getWidth() > $newWidth) { - $this->resizeInPixel($newWidth, null, true); - } - } - - if ($converseProportion !== 2 && ($this->getWidth() != $newWidth || $this->getHeight() != $newHeight)) { - - $layerTmp = ImageWorkshop::initVirginLayer($newWidth, $newHeight); - - $layerTmp->addLayer(1, $this, $positionX, $positionY, $position); - - // Reset part of stack - - unset($this->image); - unset($this->layerLevels); - unset($this->layerPositions); - unset($this->layers); - - // Update current object - - $this->width = $layerTmp->getWidth(); - $this->height = $layerTmp->getHeight(); - $this->layerLevels = $layerTmp->layers[1]->getLayerLevels(); - $this->layerPositions = $layerTmp->layers[1]->getLayerPositions(); - $this->layers = $layerTmp->layers[1]->getLayers(); - $this->lastLayerId = $layerTmp->layers[1]->getLastLayerId(); - $this->highestLayerLevel = $layerTmp->layers[1]->getHighestLayerLevel(); - - $translations = $layerTmp->getLayerPositions(1); - - foreach ($this->layers as $id => $layer) { - $this->applyTranslation($id, $translations['x'], $translations['y']); - } - - $layerTmp->layers[1]->clearStack(false); - $this->image = $layerTmp->getResult(); - unset($layerTmp); - } - - return; - - } elseif ($newWidth) { - - $widthResizePercent = $newWidth / ($this->width / 100); - $newHeight = round(($widthResizePercent / 100) * $this->height); - $heightResizePercent = $widthResizePercent; - - } elseif ($newHeight) { - - $heightResizePercent = $newHeight / ($this->height / 100); - $newWidth = round(($heightResizePercent / 100) * $this->width); - $widthResizePercent = $heightResizePercent; - } - - } elseif (($newWidth && !$newHeight) || (!$newWidth && $newHeight)) { // New width OR new height is given - - if ($newWidth) { - - $widthResizePercent = $newWidth / ($this->width / 100); - $heightResizePercent = 100; - $newHeight = $this->height; - - } else { - - $heightResizePercent = $newHeight / ($this->height / 100); - $widthResizePercent = 100; - $newWidth = $this->width; - } - - } else { // New width AND new height are given - - $widthResizePercent = $newWidth / ($this->width / 100); - $heightResizePercent = $newHeight / ($this->height / 100); - } - - // Update the layer positions in the stack - - foreach ($this->layerPositions as $layerId => $layerPosition) { - - $newPosX = round(($widthResizePercent / 100) * $layerPosition['x']); - $newPosY = round(($heightResizePercent / 100) * $layerPosition['y']); - - $this->changePosition($layerId, $newPosX, $newPosY); - } - - // Resize layers in the stack - - $layers = $this->layers; - - foreach ($layers as $key => $layer) { - $layer->resizeInPercent($widthResizePercent, $heightResizePercent); - $this->layers[$key] = $layer; - } - - $this->resizeBackground($newWidth, $newHeight); // Resize the layer - } - } - - /** - * Resize the layer by its largest side by specifying pixel - * - * @param integer $newLargestSideWidth - * @param boolean $converseProportion - */ - public function resizeByLargestSideInPixel($newLargestSideWidth, $converseProportion = false) - { - $this->resizeByLargestSide(self::UNIT_PIXEL, $newLargestSideWidth, $converseProportion); - } - - /** - * Resize the layer by its largest side by specifying percent - * - * @param integer $newLargestSideWidth percent - * @param boolean $converseProportion - */ - public function resizeByLargestSideInPercent($newLargestSideWidth, $converseProportion = false) - { - $this->resizeByLargestSide(self::UNIT_PERCENT, $newLargestSideWidth, $converseProportion); - } - - /** - * Resize the layer by its largest side - * - * @param string $unit - * @param integer $newLargestSideWidth percent - * @param boolean $converseProportion - */ - public function resizeByLargestSide($unit = self::UNIT_PIXEL, $newLargestSideWidth, $converseProportion = false) - { - if ($unit == self::UNIT_PERCENT) { - $newLargestSideWidth = round(($newLargestSideWidth / 100) * $this->getLargestSideWidth()); - } - - if ($this->getWidth() > $this->getHeight()) { - $this->resizeInPixel($newLargestSideWidth, null, $converseProportion); - } else { - $this->resizeInPixel(null, $newLargestSideWidth, $converseProportion); - } - } - - /** - * Resize the layer by its narrow side by specifying pixel - * - * @param integer $newNarrowSideWidth - * @param boolean $converseProportion - */ - public function resizeByNarrowSideInPixel($newNarrowSideWidth, $converseProportion = false) - { - $this->resizeByNarrowSide(self::UNIT_PIXEL, $newNarrowSideWidth, $converseProportion); - } - - /** - * Resize the layer by its narrow side by specifying percent - * - * @param integer $newNarrowSideWidth percent - * @param boolean $converseProportion - */ - public function resizeByNarrowSideInPercent($newNarrowSideWidth, $converseProportion = false) - { - $this->resizeByNarrowSide(self::UNIT_PERCENT, $newNarrowSideWidth, $converseProportion); - } - - /** - * Resize the layer by its narrow side - * - * @param string $unit - * @param integer $newNarrowSideWidth - * @param boolean $converseProportion - */ - public function resizeByNarrowSide($unit = self::UNIT_PIXEL, $newNarrowSideWidth, $converseProportion = false) - { - if ($unit == self::UNIT_PERCENT) { - $newNarrowSideWidth = round(($newNarrowSideWidth / 100) * $this->getNarrowSideWidth()); - } - - if ($this->getWidth() < $this->getHeight()) { - $this->resizeInPixel($newNarrowSideWidth, null, $converseProportion); - } else { - $this->resizeInPixel(null, $newNarrowSideWidth, $converseProportion); - } - } - - /** - * Crop the document by specifying pixels - * - * $backgroundColor: can be set transparent (The script will be longer to execute) - * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html - * - * @param integer $width - * @param integer $height - * @param integer $positionX - * @param integer $positionY - * @param string $position - */ - public function cropInPixel($width = 0, $height = 0, $positionX = 0, $positionY = 0, $position = 'LT') - { - $this->crop(self::UNIT_PIXEL, $width, $height, $positionX, $positionY, $position); - } - - /** - * Crop the document by specifying percent - * - * $backgroundColor can be set transparent (but script could be long to execute) - * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html - * - * @param float $percentWidth - * @param float $percentHeight - * @param float $positionXPercent - * @param float $positionYPercent - * @param string $position - */ - public function cropInPercent($percentWidth = 0, $percentHeight = 0, $positionXPercent = 0, $positionYPercent = 0, $position = 'LT') - { - $this->crop(self::UNIT_PERCENT, $percentWidth, $percentHeight, $positionXPercent, $positionYPercent, $position); - } - - /** - * Crop the document - * - * $backgroundColor can be set transparent (but script could be long to execute) - * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html - * - * @param string $unit - * @param mixed $width (integer or float) - * @param mixed $height (integer or float) - * @param mixed $positionX (integer or float) - * @param mixed $positionY (integer or float) - * @param string $position - */ - public function crop($unit = self::UNIT_PIXEL, $width = 0, $height = 0, $positionX = 0, $positionY = 0, $position = 'LT') - { - if ($width < 0 || $height < 0) { - throw new ImageWorkshopLayerException('You can\'t use negative $width or $height for "'.__METHOD__.'" method.', static::ERROR_NEGATIVE_NUMBER_USED); - } - - if ($unit == self::UNIT_PERCENT) { - - $width = round(($width / 100) * $this->width); - $height = round(($height / 100) * $this->height); - - $positionX = round(($positionX / 100) * $this->width); - $positionY = round(($positionY / 100) * $this->height); - } - - if (($width != $this->width || $positionX == 0) || ($height != $this->height || $positionY == 0)) { - - if ($width == 0) { - $width = 1; - } - - if ($height == 0) { - $height = 1; - } - - $layerTmp = ImageWorkshop::initVirginLayer($width, $height); - $layerClone = ImageWorkshop::initVirginLayer($this->width, $this->height); - - imagedestroy($layerClone->image); - $layerClone->image = $this->image; - - $layerTmp->addLayer(1, $layerClone, -$positionX, -$positionY, $position); - - $newPos = $layerTmp->getLayerPositions(); - $layerNewPosX = $newPos[1]['x']; - $layerNewPosY = $newPos[1]['y']; - - // update the layer - $this->width = $layerTmp->getWidth(); - $this->height = $layerTmp->getHeight(); - $this->image = $layerTmp->getResult(); - unset($layerTmp); - unset($layerClone); - - $this->updateLayerPositionsAfterCropping($layerNewPosX, $layerNewPosY); - } - } - - /** - * Crop the document to a specific aspect ratio by specifying a shift in pixel - * - * $backgroundColor: can be set transparent (The script will be longer to execute) - * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html - * - * @param integer $width - * @param integer $height - * @param integer $positionX - * @param integer $positionY - * @param string $position - */ - public function cropToAspectRatioInPixel($width = 0, $height = 0, $positionX = 0, $positionY = 0, $position = 'LT') - { - $this->cropToAspectRatio(self::UNIT_PIXEL, $width, $height, $positionX, $positionY, $position); - } - - /** - * Crop the document to a specific aspect ratio by specifying a shift in percent - * - * $backgroundColor can be set transparent (but script could be long to execute) - * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html - * - * @param integer $width - * @param integer $height - * @param float $positionXPercent - * @param float $positionYPercent - * @param string $position - */ - public function cropToAspectRatioInPercent($width = 0, $height = 0, $positionXPercent = 0, $positionYPercent = 0, $position = 'LT') - { - $this->cropToAspectRatio(self::UNIT_PERCENT, $width, $height, $positionXPercent, $positionYPercent, $position); - } - - /** - * Crop the document to a specific aspect ratio - * - * $backgroundColor can be set transparent (but script could be long to execute) - * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html - * - * @param string $unit - * @param integer $width (integer or float) - * @param integer $height (integer or float) - * @param mixed $positionX (integer or float) - * @param mixed $positionY (integer or float) - * @param string $position - */ - public function cropToAspectRatio($unit = self::UNIT_PIXEL, $width = 0, $height = 0, $positionX = 0, $positionY = 0, $position = 'LT') - { - if ($width < 0 || $height < 0) { - throw new ImageWorkshopLayerException('You can\'t use negative $width or $height for "'.__METHOD__.'" method.', static::ERROR_NEGATIVE_NUMBER_USED); - } - - if ($width == 0) { - $width = 1; - } - - if ($height == 0) { - $height = 1; - } - - if ($this->width / $this->height <= $width / $height) { - $newWidth = $this->width; - $newHeight = round($height * ($this->width / $width)); - } else { - $newWidth = round($width * ($this->height / $height)); - $newHeight = $this->height; - } - - if ($unit == self::UNIT_PERCENT) { - $positionX = round(($positionX / 100) * ($this->width - $newWidth)); - $positionY = round(($positionY / 100) * ($this->height - $newHeight)); - } - - $this->cropInPixel($newWidth, $newHeight, $positionX, $positionY, $position); - } - - /** - * Crop the maximum possible from left top ("LT"), "RT"... by specifying a shift in pixel - * - * $backgroundColor can be set transparent (but script could be long to execute) - * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html - * - * @param integer $width - * @param integer $height - * @param integer $positionX - * @param integer $positionY - * @param string $position - */ - public function cropMaximumInPixel($positionX = 0, $positionY = 0, $position = 'LT') - { - $this->cropMaximum(self::UNIT_PIXEL, $positionX, $positionY, $position); - } - - /** - * Crop the maximum possible from left top ("LT"), "RT"... by specifying a shift in percent - * - * $backgroundColor can be set transparent (but script could be long to execute) - * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html - * - * @param integer $width - * @param integer $height - * @param integer $positionXPercent - * @param integer $positionYPercent - * @param string $position - */ - public function cropMaximumInPercent($positionXPercent = 0, $positionYPercent = 0, $position = 'LT') - { - $this->cropMaximum(self::UNIT_PERCENT, $positionXPercent, $positionYPercent, $position); - } - - /** - * Crop the maximum possible from left top - * - * $backgroundColor can be set transparent (but script could be long to execute) - * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html - * - * @param string $unit - * @param integer $width - * @param integer $height - * @param integer $positionX - * @param integer $positionY - * @param string $position - */ - public function cropMaximum($unit = self::UNIT_PIXEL, $positionX = 0, $positionY = 0, $position = 'LT') - { - $narrowSide = $this->getNarrowSideWidth(); - - if ($unit == self::UNIT_PERCENT) { - $positionX = round(($positionX / 100) * $this->width); - $positionY = round(($positionY / 100) * $this->height); - } - - $this->cropInPixel($narrowSide, $narrowSide, $positionX, $positionY, $position); - } - - /** - * Rotate the layer (in degree) - * - * @param float $degrees - */ - public function rotate($degrees) - { - if ($degrees != 0) { - - if ($degrees < -360 || $degrees > 360) { - $degrees = $degrees % 360; - } - - if ($degrees < 0 && $degrees >= -360) { - $degrees = 360 + $degrees; - } - - // Rotate the layer background image - $imageRotated = imagerotate($this->image, -$degrees, -1); - imagealphablending($imageRotated, true); - imagesavealpha($imageRotated, true); - - unset($this->image); - - $this->image = $imageRotated; - - $oldWidth = $this->width; - $oldHeight = $this->height; - - $this->width = imagesx($this->image); - $this->height = imagesy($this->image); - - foreach ($this->layers as $layerId => $layer) { - - $layerSelfOldCenterPosition = array( - 'x' => $layer->width / 2, - 'y' => $layer->height / 2, - ); - - $smallImageCenter = array( - 'x' => $layerSelfOldCenterPosition['x'] + $this->layerPositions[$layerId]['x'], - 'y' => $layerSelfOldCenterPosition['y'] + $this->layerPositions[$layerId]['y'], - ); - - $this->layers[$layerId]->rotate($degrees); - - $ro = sqrt(pow($smallImageCenter['x'], 2) + pow($smallImageCenter['y'], 2)); - - $teta = (acos($smallImageCenter['x'] / $ro)) * 180 / pi(); - - $a = $ro * cos(($teta + $degrees) * pi() / 180); - $b = $ro * sin(($teta + $degrees) * pi() / 180); - - if ($degrees > 0 && $degrees <= 90) { - - $newPositionX = $a - ($this->layers[$layerId]->width / 2) + $oldHeight * sin(($degrees * pi()) / 180); - $newPositionY = $b - ($this->layers[$layerId]->height / 2); - - } elseif ($degrees > 90 && $degrees <= 180) { - - $newPositionX = $a - ($this->layers[$layerId]->width / 2) + $this->width; - $newPositionY = $b - ($this->layers[$layerId]->height / 2) + $oldHeight * (-cos(($degrees) * pi() / 180)); - - } elseif ($degrees > 180 && $degrees <= 270) { - - $newPositionX = $a - ($this->layers[$layerId]->width / 2) + $oldWidth * (-cos(($degrees) * pi() / 180)); - $newPositionY = $b - ($this->layers[$layerId]->height / 2) + $this->height; - - } else { - - $newPositionX = $a - ($this->layers[$layerId]->width / 2); - $newPositionY = $b - ($this->layers[$layerId]->height / 2) + $oldWidth * (-sin(($degrees) * pi() / 180)); - } - - $this->layerPositions[$layerId] = array( - 'x' => $newPositionX, - 'y' => $newPositionY, - ); - } - } - } - - /** - * Change the opacity of the layer - * $recursive: apply it on sublayers - * - * @param integer $opacity - * @param boolean $recursive - */ - public function opacity($opacity, $recursive = true) - { - if ($recursive) { - - $layers = $this->layers; - - foreach ($layers as $key => $layer) { - $layer->opacity($opacity, true); - $this->layers[$key] = $layer; - } - } - - $transparentImage = ImageWorkshopLib::generateImage($this->getWidth(), $this->getHeight()); - - ImageWorkshopLib::imageCopyMergeAlpha($transparentImage, $this->image, 0, 0, 0, 0, $this->getWidth(), $this->getHeight(), $opacity); - - unset($this->image); - $this->image = $transparentImage; - unset($transparentImage); - } - - /** - * Apply a filter on the layer - * Be careful: some filters can damage transparent images, use it sparingly ! (A good pratice is to use mergeAll on your layer before applying a filter) - * - * @param int $filterType (http://www.php.net/manual/en/function.imagefilter.php) - * @param int $arg1 - * @param int $arg2 - * @param int $arg3 - * @param int $arg4 - * @param boolean $recursive - */ - public function applyFilter($filterType, $arg1 = null, $arg2 = null, $arg3 = null, $arg4 = null, $recursive = false) - { - if ($filterType == IMG_FILTER_COLORIZE) { - imagefilter($this->image, $filterType, $arg1, $arg2, $arg3, $arg4); - } elseif ($filterType == IMG_FILTER_BRIGHTNESS || $filterType == IMG_FILTER_CONTRAST || $filterType == IMG_FILTER_SMOOTH) { - imagefilter($this->image, $filterType, $arg1); - } elseif ($filterType == IMG_FILTER_PIXELATE) { - imagefilter($this->image, $filterType, $arg1, $arg2); - } else { - imagefilter($this->image, $filterType); - } - - if ($recursive) { - - $layers = $this->layers; - - foreach($layers as $layerId => $layer) { - $this->layers[$layerId]->applyFilter($filterType, $arg1, $arg2, $arg3, $arg4, true); - } - } - } - - /** - * Apply horizontal or vertical flip (Transformation) - * - * @param string $type - */ - public function flip($type = 'horizontal') - { - $layers = $this->layers; - - foreach ($layers as $key => $layer) { - - $layer->flip($type); - $this->layers[$key] = $layer; - } - - $temp = ImageWorkshopLib::generateImage($this->width, $this->height); - - if ($type == 'horizontal') { - - imagecopyresampled($temp, $this->image, 0, 0, $this->width - 1, 0, $this->width, $this->height, -$this->width, $this->height); - $this->image = $temp; - - foreach ($this->layerPositions as $layerId => $layerPositions) { - - $this->changePosition($layerId, $this->width - $this->layers[$layerId]->getWidth() - $layerPositions['x'], $layerPositions['y']); - } - - } elseif ($type == 'vertical') { - - imagecopyresampled($temp, $this->image, 0, 0, 0, $this->height - 1, $this->width, $this->height, $this->width, -$this->height); - $this->image = $temp; - - foreach ($this->layerPositions as $layerId => $layerPositions) { - - $this->changePosition($layerId, $layerPositions['x'], $this->height - $this->layers[$layerId]->getHeight() - $layerPositions['y']); - } - } - - unset($temp); - } - - /** - * Add a text on the background image of the layer using a default font registered in GD - * - * @param string $text - * @param integer $font - * @param string $color - * @param integer $positionX - * @param integer $positionY - * @param string $align - */ - public function writeText($text, $font = 1, $color = 'ffffff', $positionX = 0, $positionY = 0, $align = 'horizontal') - { - $RGBTextColor = ImageWorkshopLib::convertHexToRGB($color); - $textColor = imagecolorallocate($this->image, $RGBTextColor['R'], $RGBTextColor['G'], $RGBTextColor['B']); - - if ($align == 'horizontal') { - imagestring($this->image, $font, $positionX, $positionY, $text, $textColor); - } else { - imagestringup($this->image, $font, $positionX, $positionY, $text, $textColor); - } - } - - /** - * Add a text on the background image of the layer using a font localized at $fontPath - * Return the text coordonates - * - * @param string $text - * @param integer $fontPath - * @param integer $fontSize - * @param string $color - * @param integer $positionX - * @param integer $positionY - * @param integer $fontRotation - * - * @return array - */ - public function write($text, $fontPath, $fontSize = 13, $color = 'ffffff', $positionX = 0, $positionY = 0, $fontRotation = 0) - { - if (!file_exists($fontPath)) { - throw new ImageWorkshopLayerException('Can\'t find a font file at this path : "'.$fontPath.'".', static::ERROR_FONT_NOT_FOUND); - } - - $RGBTextColor = ImageWorkshopLib::convertHexToRGB($color); - $textColor = imagecolorallocate($this->image, $RGBTextColor['R'], $RGBTextColor['G'], $RGBTextColor['B']); - - return imagettftext($this->image, $fontSize, $fontRotation, $positionX, $positionY, $textColor, $fontPath, $text); - } - - // Manage the result - // ========================================================= - - /** - * Return a merged resource image - * - * $backgroundColor is really usefull if you want to save a JPG or GIF, because the transparency of the background - * would be remove for a colored background, so you should choose a color like "ffffff" (white) - * - * @param string $backgroundColor - * - * @return resource - */ - public function getResult($backgroundColor = null) - { - $imagesToMerge = array(); - ksort($this->layerLevels); - - foreach ($this->layerLevels as $layerLevel => $layerId) { - - $imagesToMerge[$layerLevel] = $this->layers[$layerId]->getResult(); - - // Layer positions - if ($this->layerPositions[$layerId]['x'] != 0 || $this->layerPositions[$layerId]['y'] != 0) { - - $virginLayoutImageTmp = ImageWorkshopLib::generateImage($this->width, $this->height); - ImageWorkshopLib::mergeTwoImages($virginLayoutImageTmp, $imagesToMerge[$layerLevel], $this->layerPositions[$layerId]['x'], $this->layerPositions[$layerId]['y'], 0, 0); - $imagesToMerge[$layerLevel] = $virginLayoutImageTmp; - unset($virginLayoutImageTmp); - } - } - - $iterator = 1; - $mergedImage = $this->image; - ksort($imagesToMerge); - - foreach ($imagesToMerge as $imageLevel => $image) { - ImageWorkshopLib::mergeTwoImages($mergedImage, $image); - $iterator++; - } - - $opacity = 127; - - if ($backgroundColor && $backgroundColor != 'transparent') { - $opacity = 0; - } - - $backgroundImage = ImageWorkshopLib::generateImage($this->width, $this->height, $backgroundColor, $opacity); - ImageWorkshopLib::mergeTwoImages($backgroundImage, $mergedImage); - $mergedImage = $backgroundImage; - unset($backgroundImage); - - return $mergedImage; - } - - /** - * Save the resulting image at the specified path - * - * $backgroundColor is really usefull if you want to save a JPG or GIF, because the transparency of the background - * would be remove for a colored background, so you should choose a color like "ffffff" (white) - * - * If the file already exists, it will be override ! - * - * $imageQuality is useless for GIF - * - * Ex: $folder = __DIR__."/../web/images/2012" - * $imageName = "butterfly.jpg" - * $createFolders = true - * $imageQuality = 95 - * $backgroundColor = "ffffff" - * - * @param string $folder - * @param string $imageName - * @param boolean $createFolders - * @param string $backgroundColor - * @param integer $imageQuality - * @param boolean $interlace - */ - public function save($folder, $imageName, $createFolders = true, $backgroundColor = null, $imageQuality = 75, $interlace = false) - { - if (!is_file($folder)) { - - if (is_dir($folder) || $createFolders) { - - // Creating the folders if they don't exist - if (!is_dir($folder) && $createFolders) { - $oldUmask = umask(0); - mkdir($folder, 0777, true); - umask($oldUmask); - chmod($folder, 0777); - } - - $extension = explode('.', $imageName); - $extension = strtolower($extension[count($extension) - 1]); - - $filename = $folder.'/'.$imageName; - - if (($extension == 'jpg' || $extension == 'jpeg' || $extension == 'gif') && (!$backgroundColor || $backgroundColor == 'transparent')) { - $backgroundColor = 'ffffff'; - } - - $image = $this->getResult($backgroundColor); - - imageinterlace($image, (int) $interlace); - - if ($extension == 'jpg' || $extension == 'jpeg') { - - imagejpeg($image, $filename, $imageQuality); - unset($image); - - } elseif ($extension == 'gif') { - - imagegif($image, $filename); - unset($image); - - } elseif ($extension == 'png') { - - $imageQuality = $imageQuality / 10; - $imageQuality -= 1; - - imagepng($image, $filename, $imageQuality); - unset($image); - } - } - } - } - - // Checkers - // ========================================================= - - /** - * Check if a sublayer exists in the stack for a given id - * - * @param integer $layerId - * - * @return boolean - */ - public function isLayerInIndex($layerId) - { - if (array_key_exists($layerId, $this->layers)) { - return true; - } - - return false; - } - - // Getter / Setter - // ========================================================= - - /** - * Return the narrow side width of the layer - * - * @return integer - */ - public function getNarrowSideWidth() - { - $narrowSideWidth = $this->getWidth(); - - if ($this->getHeight() < $narrowSideWidth) { - $narrowSideWidth = $this->getHeight(); - } - - return $narrowSideWidth; - } - - /** - * Return the largest side width of the layer - * - * @return integer - */ - public function getLargestSideWidth() - { - $largestSideWidth = $this->getWidth(); - - if ($this->getHeight() > $largestSideWidth) { - $largestSideWidth = $this->getHeight(); - } - - return $largestSideWidth; - } - - /** - * Get the level of a sublayer - * Return sublayer level if success or false if layer isn't found - * - * @param integer $layerId - * - * @return mixed (integer or boolean) - */ - public function getLayerLevel($layerId) - { - if ($this->isLayerInIndex($layerId)) { // if the layer exists in document - return array_search($layerId, $this->layerLevels); - } - - return false; - } - - /** - * Get a sublayer in the stack - * Don't forget to use clone method: $b = clone $a->getLayer(3); - * - * @param integer $layerId - * - * @return ImageWorkshop - */ - public function getLayer($layerId) - { - return $this->layers[$layerId]; - } - - /** - * Getter width - * - * @return integer - */ - public function getWidth() - { - return $this->width; - } - - /** - * Getter height - * - * @return integer - */ - public function getHeight() - { - return $this->height; - } - - /** - * Getter image - * - * @return resource - */ - public function getImage() - { - return $this->image; - } - - /** - * Getter layers - * - * @return array - */ - public function getLayers() - { - return $this->layers; - } - - /** - * Getter layerLevels - * - * @return array - */ - public function getLayerLevels() - { - return $this->layerLevels; - } - - /** - * Getter layerPositions - * - * Get all the positions of the sublayers, - * or when specifying $layerId, get the position of this sublayer - * - * @param integer $layerId - * - * @return mixed (array or boolean) - */ - public function getLayerPositions($layerId = null) - { - if (!$layerId) { - - return $this->layerPositions; - - } elseif ($this->isLayerInIndex($layerId)) { // if the sublayer exists in the stack - - return $this->layerPositions[$layerId]; - } - - return false; - } - - /** - * Getter highestLayerLevel - * - * @return array - */ - public function getHighestLayerLevel() - { - return $this->highestLayerLevel; - } - - /** - * Getter lastLayerId - * - * @return array - */ - public function getLastLayerId() - { - return $this->lastLayerId; - } - - // Internals - // ========================================================= - - /** - * Delete the current object - */ - public function delete() - { - imagedestroy($this->image); - $this->clearStack(); - } - - /** - * Create a new background image var from the old background image var - */ - public function createNewVarFromBackgroundImage() - { - $virginImage = ImageWorkshopLib::generateImage($this->getWidth(), $this->getHeight()); // New background image - - ImageWorkshopLib::mergeTwoImages($virginImage, $this->image, 0, 0, 0, 0); - unset($this->image); - - $this->image = $virginImage; - unset($virginImage); - - $layers = $this->layers; - - foreach($layers as $layerId => $layer) { - $this->layers[$layerId] = clone $this->layers[$layerId]; - } - } - - /** - * Index a sublayer in the layer stack - * Return an array containing the generated sublayer id and its final level: - * array("layerLevel" => integer, "id" => integer) - * - * @param integer $layerLevel - * @param ImageWorkshopLayer $layer - * @param integer $positionX - * @param integer $positionY - * @param string $position - * - * @return array - */ - protected function indexLayer($layerLevel, $layer, $positionX = 0, $positionY = 0, $position) - { - // Choose an id for the added layer - $layerId = $this->lastLayerId + 1; - - // Clone $layer to duplicate image resource var - $layer = clone $layer; - - // Add the layer in the stack - $this->layers[$layerId] = $layer; - - // Add the layer positions in the main layer - $this->layerPositions[$layerId] = ImageWorkshopLib::calculatePositions($this->getWidth(), $this->getHeight(), $layer->getWidth(), $layer->getHeight(), $positionX, $positionY, $position); - - // Update the lastLayerId of the workshop - $this->lastLayerId = $layerId; - - // Add the layer level in the stack - $layerLevel = $this->indexLevelInDocument($layerLevel, $layerId); - - return array( - 'layerLevel' => $layerLevel, - 'id' => $layerId, - ); - } - - /** - * Index a layer level and update the layers levels in the document - * Return the corrected level of the layer - * - * @param integer $layerLevel - * @param integer $layerId - * - * @return integer - */ - protected function indexLevelInDocument($layerLevel, $layerId) - { - if (array_key_exists($layerLevel, $this->layerLevels)) { // Level already exists - - ksort($this->layerLevels); // All layers after this level and the layer which have this level are updated - $layerLevelsTmp = $this->layerLevels; - - foreach ($layerLevelsTmp as $levelTmp => $layerIdTmp) { - if ($levelTmp >= $layerLevel) { - $this->layerLevels[$levelTmp + 1] = $layerIdTmp; - } - } - - unset($layerLevelsTmp); - - } else { // Level isn't taken - if ($this->highestLayerLevel < $layerLevel) { // If given level is too high, proceed adjustement - $layerLevel = $this->highestLayerLevel + 1; - } - } - - $this->layerLevels[$layerLevel] = $layerId; - $this->highestLayerLevel = max(array_flip($this->layerLevels)); // Update $highestLayerLevel - - return $layerLevel; - } - - /** - * Update the positions of layers in the stack after cropping - * - * @param integer $positionX - * @param integer $positionY - */ - public function updateLayerPositionsAfterCropping($positionX, $positionY) - { - foreach ($this->layers as $layerId => $layer) { - - $oldLayerPosX = $this->layerPositions[$layerId]['x']; - $oldLayerPosY = $this->layerPositions[$layerId]['y']; - - $newLayerPosX = $oldLayerPosX + $positionX; - $newLayerPosY = $oldLayerPosY + $positionY; - - $this->changePosition($layerId, $newLayerPosX, $newLayerPosY); - } - } - - /** - * Resize the background of a layer - * - * @param integer $newWidth - * @param integer $newHeight - */ - public function resizeBackground($newWidth, $newHeight) - { - $oldWidth = $this->width; - $oldHeight = $this->height; - - $this->width = $newWidth; - $this->height = $newHeight; - - $virginLayoutImage = ImageWorkshopLib::generateImage($this->width, $this->height); - - imagecopyresampled($virginLayoutImage, $this->image, 0, 0, 0, 0, $this->width, $this->height, $oldWidth, $oldHeight); - - unset($this->image); - $this->image = $virginLayoutImage; - } - - // Deprecated, don't use anymore - // ========================================================= - - /** - * @deprecated - */ - public function resizeInPourcent($percentWidth = null, $percentHeight = null, $converseProportion = false, $positionX = 0, $positionY = 0, $position = 'MM') - { - throw new ImageWorkshopLayerException('Method resizeInPourcent() was renamed resizeInPercent(). Use resizeInPercent() instead.', static::METHOD_DEPRECATED); - } - - /** - * @deprecated - */ - public function resizeByLargestSideInPourcent($newLargestSideWidth, $converseProportion = false) - { - throw new ImageWorkshopLayerException('Method resizeByLargestSideInPourcent() was renamed resizeByLargestSideInPercent(). Use resizeByLargestSideInPercent() instead.', static::METHOD_DEPRECATED); - } - - /** - * @deprecated - */ - public function resizeByNarrowSideInPourcent($newNarrowSideWidth, $converseProportion = false) - { - throw new ImageWorkshopLayerException('Method resizeByNarrowSideInPourcent() was renamed resizeByNarrowSideInPercent(). Use resizeByNarrowSideInPercent() instead.', static::METHOD_DEPRECATED); - } - - /** - * @deprecated - */ - public function cropInPourcent($percentWidth = 0, $percentHeight = 0, $positionXPercent = 0, $positionYPercent = 0, $position = 'LT') - { - throw new ImageWorkshopLayerException('Method cropInPourcent() was renamed cropInPercent(). Use cropInPercent() instead.', static::METHOD_DEPRECATED); - } - - /** - * @deprecated - */ - public function cropMaximumInPourcent($positionXPercent = 0, $positionYPercent = 0, $position = 'LT') - { - throw new ImageWorkshopLayerException('Method cropMaximumInPourcent() was renamed cropMaximumInPercent(). Use cropMaximumInPercent() instead.', static::METHOD_DEPRECATED); - } -} +width = imagesx($image); + $this->height = imagesy($image); + $this->image = $image; + $this->layers = $this->layerLevels = $this->layerPositions = array(); + $this->clearStack(); + } + + /** + * Clone method: use it if you want to reuse an existing ImageWorkshop object in another variable + * This is important because img resource var references all the same image in PHP. + * Example: $b = clone $a; (never do $b = $a;) + */ + public function __clone() + { + $this->createNewVarFromBackgroundImage(); + } + + // Superimpose a sublayer + // ========================================================= + + /** + * Add an existing ImageWorkshop sublayer and set it in the stack at a given level + * Return an array containing the generated sublayer id in the stack and its corrected level: + * array("layerLevel" => integer, "id" => integer) + * + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param integer $layerLevel + * @param ImageWorkshop $layer + * @param integer $positionX + * @param integer $positionY + * @param string $position + * + * @return array + */ + public function addLayer($layerLevel, $layer, $positionX = 0, $positionY = 0, $position = 'LT') + { + return $this->indexLayer($layerLevel, $layer, $positionX, $positionY, $position); + } + + /** + * Add an existing ImageWorkshop sublayer and set it in the stack at the highest level + * Return an array containing the generated sublayer id in the stack and the highest level: + * array("layerLevel" => integer, "id" => integer) + * + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param ImageWorkshop $layer + * @param integer $positionX + * @param integer $positionY + * @param string $position + * + * @return array + */ + public function addLayerOnTop($layer, $positionX = 0, $positionY = 0, $position = 'LT') + { + return $this->indexLayer($this->highestLayerLevel + 1, $layer, $positionX, $positionY, $position); + } + + /** + * Add an existing ImageWorkshop sublayer and set it in the stack at level 1 + * Return an array containing the generated sublayer id in the stack and level 1: + * array("layerLevel" => integer, "id" => integer) + * + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param ImageWorkshop $layer + * @param integer $positionX + * @param integer $positionY + * @param string $position + * + * @return array + */ + public function addLayerBelow($layer, $positionX = 0, $positionY = 0, $position = 'LT') + { + return $this->indexLayer(1, $layer, $positionX, $positionY, $position); + } + + // Move a sublayer inside the stack + // ========================================================= + + /** + * Move a sublayer on the top of a group stack + * Return new sublayer level if success or false otherwise + * + * @param integer $layerId + * @return mixed + */ + public function moveTop($layerId) + { + return $this->moveTo($layerId, $this->highestLayerLevel, false); + } + + /** + * Move a sublayer to the level 1 of a group stack + * Return new sublayer level if success or false otherwise + * + * @param integer $layerId + * @param integer $level + * + * @return mixed + */ + public function moveBottom($layerId) + { + return $this->moveTo($layerId, 1, true); + } + + /** + * Move a sublayer to the level $level of a group stack + * Return new sublayer level if success or false if layer isn't found + * + * Set $insertUnderTargetedLayer true if you want to move the sublayer under the other sublayer at the targeted level, + * or false to insert it on the top of the other sublayer at the targeted level + * + * @param integer $layerId + * @param integer $level + * @param boolean $insertUnderTargetedLayer + * + * @return mixed + */ + public function moveTo($layerId, $level, $insertUnderTargetedLayer = true) + { + // if the sublayer exists in stack + if ($this->isLayerInIndex($layerId)) { + + $layerOldLevel = $this->getLayerLevel($layerId); + + if ($level < 1) { + $level = 1; + $insertUnderTargetedLayer = true; + } + + if ($level > $this->highestLayerLevel) { + + $level = $this->highestLayerLevel; + $insertUnderTargetedLayer = false; + } + + // Not the same level than the current level + if ($layerOldLevel != $level) { + + $isUnderAndNewLevelHigher = $isUnderAndNewLevelLower = $isOnTopAndNewLevelHigher = $isOnTopAndNewLevelLower = false; + + if ($insertUnderTargetedLayer) { // Under level + + if ($level > $layerOldLevel) { // new level higher + + $incrementorStartingValue = $layerOldLevel; + $stopLoopWhenSmallerThan = $level; + $isUnderAndNewLevelHigher = true; + + } else { // new level lower + + $incrementorStartingValue = $level; + $stopLoopWhenSmallerThan = $layerOldLevel; + $isUnderAndNewLevelLower = true; + } + + } else { // on the top + + if ($level > $layerOldLevel) { // new level higher + + $incrementorStartingValue = $layerOldLevel; + $stopLoopWhenSmallerThan = $level; + $isOnTopAndNewLevelHigher = true; + + } else { // new level lower + + $incrementorStartingValue = $level; + $stopLoopWhenSmallerThan = $layerOldLevel; + $isOnTopAndNewLevelLower = true; + } + } + + ksort($this->layerLevels); + $layerLevelsTmp = $this->layerLevels; + + if ($isOnTopAndNewLevelLower) { + $level++; + } + + for ($i = $incrementorStartingValue; $i < $stopLoopWhenSmallerThan; $i++) { + + if ($isUnderAndNewLevelHigher || $isOnTopAndNewLevelHigher) { + + $this->layerLevels[$i] = $layerLevelsTmp[$i + 1]; + + } else { + + $this->layerLevels[$i + 1] = $layerLevelsTmp[$i]; + } + } + + unset($layerLevelsTmp); + + if ($isUnderAndNewLevelHigher) { + $level--; + } + + $this->layerLevels[$level] = $layerId; + + return $level; + + } else { + return $level; + } + } + + return false; + } + + /** + * Move up a sublayer in the stack (level +1) + * Return new sublayer level if success, false otherwise + * + * @param integer $layerId + * + * @return mixed + */ + public function moveUp($layerId) + { + if ($this->isLayerInIndex($layerId)) { // if the sublayer exists in the stack + $layerOldLevel = $this->getLayerLevel($layerId); + return $this->moveTo($layerId, $layerOldLevel + 1, false); + } + + return false; + } + + /** + * Move down a sublayer in the stack (level -1) + * Return new sublayer level if success, false otherwise + * + * @param integer $layerId + * + * @return mixed + */ + public function moveDown($layerId) + { + if ($this->isLayerInIndex($layerId)) { // if the sublayer exists in the stack + $layerOldLevel = $this->getLayerLevel($layerId); + return $this->moveTo($layerId, $layerOldLevel - 1, true); + } + + return false; + } + + // Merge layers + // ========================================================= + + /** + * Merge a sublayer with another sublayer below it in the stack + * Note: the result layer will conserve the given id + * Return true if success or false if layer isn't found or doesn't have a layer under it in the stack + * + * @param integer $layerId + * + * @return boolean + */ + public function mergeDown($layerId) + { + // if the layer exists in document + if ($this->isLayerInIndex($layerId)) { + + $layerLevel = $this->getLayerLevel($layerId); + $layerPositions = $this->getLayerPositions($layerId); + $layer = $this->getLayer($layerId); + $layerWidth = $layer->getWidth(); + $layerHeight = $layer->getHeight(); + $layerPositionX = $this->layerPositions[$layerId]['x']; + $layerPositionY = $this->layerPositions[$layerId]['y']; + + if ($layerLevel > 1) { + + $underLayerId = $this->layerLevels[$layerLevel - 1]; + $underLayer = $this->getLayer($underLayerId); + $underLayerWidth = $underLayer->getWidth(); + $underLayerHeight = $underLayer->getHeight(); + $underLayerPositionX = $this->layerPositions[$underLayerId]['x']; + $underLayerPositionY = $this->layerPositions[$underLayerId]['y']; + + $totalWidthLayer = $layerWidth + $layerPositionX; + $totalHeightLayer = $layerHeight + $layerPositionY; + + $totalWidthUnderLayer = $underLayerWidth + $underLayerPositionX; + $totalHeightUnderLayer = $underLayerHeight + $underLayerPositionY; + + $minLayerPositionX = $layerPositionX; + + if ($layerPositionX > $underLayerPositionX) { + $minLayerPositionX = $underLayerPositionX; + } + + $minLayerPositionY = $layerPositionY; + + if ($layerPositionY > $underLayerPositionY) { + $minLayerPositionY = $underLayerPositionY; + } + + if ($totalWidthLayer > $totalWidthUnderLayer) { + $layerTmpWidth = $totalWidthLayer - $minLayerPositionX; + } else { + $layerTmpWidth = $totalWidthUnderLayer - $minLayerPositionX; + } + + if ($totalHeightLayer > $totalHeightUnderLayer) { + $layerTmpHeight = $totalHeightLayer - $minLayerPositionY; + } else { + $layerTmpHeight = $totalHeightUnderLayer - $minLayerPositionY; + } + + $layerTmp = ImageWorkshop::initVirginLayer($layerTmpWidth, $layerTmpHeight); + + $layerTmp->addLayer(1, $underLayer, $underLayerPositionX - $minLayerPositionX, $underLayerPositionY - $minLayerPositionY); + $layerTmp->addLayer(2, $layer, $layerPositionX - $minLayerPositionX, $layerPositionY - $minLayerPositionY); + + // Update layers + $layerTmp->mergeAll(); + $this->layers[$underLayerId] = clone $layerTmp; + $this->changePosition($underLayerId, $minLayerPositionX, $minLayerPositionX); + + } else { + + $layerTmp = ImageWorkshop::initFromResourceVar($this->image); + $layerTmp->addLayer(1, $layer, $layerPositionX, $layerPositionY); + + $this->image = $layerTmp->getResult(); // Update background image + } + + unset($layerTmp); + $this->remove($layerId); // Remove the merged layer from the stack + + return true; + } + + return false; + } + + /** + * Merge sublayers in the stack on the layer background + */ + public function mergeAll() + { + $this->image = $this->getResult(); + $this->clearStack(); + } + + /** + * Paste an image on the layer + * You can specify the position left (in pixels) and the position top (in pixels) of the added image relatives to the layer + * Otherwise, it will be set at 0 and 0 + * + * @param string $unit Use one of `UNIT_*` constants, "UNIT_PIXEL" by default + * @param resource $image + * @param integer $positionX + * @param integer $positionY + */ + public function pasteImage($unit = self::UNIT_PIXEL, $image, $positionX = 0, $positionY = 0) + { + if ($unit == self::UNIT_PERCENT) { + + $positionX = round(($positionX / 100) * $this->width); + $positionY = round(($positionY / 100) * $this->height); + } + + imagecopy($this->image, $image, $positionX, $positionY, 0, 0, $image->getWidth(), $image->getHeight()); + } + + // Change sublayer positions + // ========================================================= + + /** + * Change the position of a sublayer for new positions + * + * @param integer $layerId + * @param integer $newPosX + * @param integer $newPosY + * + * @return boolean + */ + public function changePosition($layerId, $newPosX = null, $newPosY = null) + { + // if the sublayer exists in the stack + if ($this->isLayerInIndex($layerId)) { + + if ($newPosX !== null) { + $this->layerPositions[$layerId]['x'] = $newPosX; + } + + if ($newPosY !== null) { + $this->layerPositions[$layerId]['y'] = $newPosY; + } + + return true; + } + + return false; + } + + /** + * Apply a translation on a sublayer that change its positions + * + * @param integer $layerId + * @param integer $addedPosX + * @param integer $addedPosY + * + * @return mixed (array of new positions or false if fail) + */ + public function applyTranslation($layerId, $addedPosX = null, $addedPosY = null) + { + // if the sublayer exists in the stack + if ($this->isLayerInIndex($layerId)) { + + if ($addedPosX !== null) { + $this->layerPositions[$layerId]['x'] += $addedPosX; + } + + if ($addedPosY !== null) { + $this->layerPositions[$layerId]['y'] += $addedPosY; + } + + return $this->layerPositions[$layerId]; + } + + return false; + } + + // Removing sublayers + // ========================================================= + + /** + * Delete a layer (return true if success, false if no sublayer is found) + * + * @param integer $layerId + * + * @return boolean + */ + public function remove($layerId) + { + // if the layer exists in document + if ($this->isLayerInIndex($layerId)) { + + $layerToDeleteLevel = $this->getLayerLevel($layerId); + + // delete + $this->layers[$layerId]->delete(); + unset($this->layers[$layerId]); + unset($this->layerLevels[$layerToDeleteLevel]); + unset($this->layerPositions[$layerId]); + + // One or plural layers are sub of the deleted layer + if (array_key_exists(($layerToDeleteLevel + 1), $this->layerLevels)) { + + ksort($this->layerLevels); + + $layerLevelsTmp = $this->layerLevels; + + $maxOldestLevel = 1; + foreach ($layerLevelsTmp as $levelTmp => $layerIdTmp) { + + if ($levelTmp > $layerToDeleteLevel) { + $this->layerLevels[($levelTmp - 1)] = $layerIdTmp; + } + + $maxOldestLevel++; + } + unset($layerLevelsTmp); + unset($this->layerLevels[$maxOldestLevel]); + } + + $this->highestLayerLevel--; + + return true; + } + + return false; + } + + /** + * Reset the layer stack + * + * @boolean $deleteSubImgVar Delete sublayers image resource var + */ + public function clearStack($deleteSubImgVar = true) + { + if ($deleteSubImgVar) { + foreach ($this->layers as $layer) { + $layer->delete(); + } + } + + unset($this->layers); + unset($this->layerLevels); + unset($this->layerPositions); + + $this->lastLayerId = 0; + $this->layers = array(); + $this->layerLevels = array(); + $this->layerPositions = array(); + $this->highestLayerLevel = 0; + } + + // Perform an action + // ========================================================= + + /** + * Resize the layer by specifying pixel + * + * @param integer $newWidth + * @param integer $newHeight + * @param boolean $converseProportion + * @param integer $positionX + * @param integer $positionY + * @param string $position + * + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * $positionX, $positionY, $position can be ignored unless you choose a new width AND a new height AND to conserve proportion. + */ + public function resizeInPixel($newWidth = null, $newHeight = null, $converseProportion = false, $positionX = 0, $positionY = 0, $position = 'MM') + { + $this->resize(self::UNIT_PIXEL, $newWidth, $newHeight, $converseProportion, $positionX, $positionY, $position); + } + + /** + * Resize the layer by specifying a percent + * + * @param float $percentWidth + * @param float $percentHeight + * @param boolean $converseProportion + * @param integer $positionX + * @param integer $positionY + * @param string $position + * + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * $positionX, $positionY, $position can be ignored unless you choose a new width AND a new height AND to conserve proportion. + */ + public function resizeInPercent($percentWidth = null, $percentHeight = null, $converseProportion = false, $positionX = 0, $positionY = 0, $position = 'MM') + { + $this->resize(self::UNIT_PERCENT, $percentWidth, $percentHeight, $converseProportion, $positionX, $positionY, $position); + } + + /** + * Resize the layer to fit a bounding box by specifying pixel + * + * @param integer $width + * @param integer $height + * @param boolean $converseProportion + */ + public function resizeToFit($width, $height, $converseProportion = false) + { + if ($this->getWidth() <= $width && $this->getHeight() <= $height) { + return; + } + + if (!$converseProportion) { + $width = min($width, $this->getWidth()); + $height = min($height, $this->getHeight()); + } + + $this->resize(self::UNIT_PIXEL, $width, $height, $converseProportion ? 2 : false); + } + + /** + * Resize the layer + * + * @param string $unit Use one of `UNIT_*` constants, "UNIT_PIXEL" by default + * @param mixed $newWidth (integer or float) + * @param mixed $newHeight (integer or float) + * @param boolean $converseProportion + * @param mixed $positionX (integer or float) + * @param mixed $positionY (integer or float) + * @param string $position + * + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * $positionX, $positionY, $position can be ignored unless you choose a new width AND a new height AND to conserve proportion. + */ + public function resize($unit = self::UNIT_PIXEL, $newWidth = null, $newHeight = null, $converseProportion = false, $positionX = 0, $positionY = 0, $position = 'MM') + { + if (is_numeric($newWidth) || is_numeric($newHeight)) { + + if ($unit == self::UNIT_PERCENT) { + + if ($newWidth) { + $newWidth = round(($newWidth / 100) * $this->width); + } + + if ($newHeight) { + $newHeight = round(($newHeight / 100) * $this->height); + } + } + + if (is_numeric($newWidth) && $newWidth <= 0) { + $newWidth = 1; + } + + if (is_numeric($newHeight) && $newHeight <= 0) { + $newHeight = 1; + } + + if ($converseProportion) { // Proportion are conserved + + if ($newWidth && $newHeight) { // Proportions + $newWidth + $newHeight + + if ($this->getWidth() > $this->getHeight()) { + + $this->resizeInPixel($newWidth, null, true); + + if ($this->getHeight() > $newHeight) { + $this->resizeInPixel(null, $newHeight, true); + } + + } else { + + $this->resizeInPixel(null, $newHeight, true); + + if ($this->getWidth() > $newWidth) { + $this->resizeInPixel($newWidth, null, true); + } + } + + if ($converseProportion !== 2 && ($this->getWidth() != $newWidth || $this->getHeight() != $newHeight)) { + + $layerTmp = ImageWorkshop::initVirginLayer($newWidth, $newHeight); + + $layerTmp->addLayer(1, $this, $positionX, $positionY, $position); + + // Reset part of stack + + unset($this->image); + unset($this->layerLevels); + unset($this->layerPositions); + unset($this->layers); + + // Update current object + + $this->width = $layerTmp->getWidth(); + $this->height = $layerTmp->getHeight(); + $this->layerLevels = $layerTmp->layers[1]->getLayerLevels(); + $this->layerPositions = $layerTmp->layers[1]->getLayerPositions(); + $this->layers = $layerTmp->layers[1]->getLayers(); + $this->lastLayerId = $layerTmp->layers[1]->getLastLayerId(); + $this->highestLayerLevel = $layerTmp->layers[1]->getHighestLayerLevel(); + + $translations = $layerTmp->getLayerPositions(1); + + foreach ($this->layers as $id => $layer) { + $this->applyTranslation($id, $translations['x'], $translations['y']); + } + + $layerTmp->layers[1]->clearStack(false); + $this->image = $layerTmp->getResult(); + unset($layerTmp); + } + + return; + + } elseif ($newWidth) { + + $widthResizePercent = $newWidth / ($this->width / 100); + $newHeight = round(($widthResizePercent / 100) * $this->height); + $heightResizePercent = $widthResizePercent; + + } elseif ($newHeight) { + + $heightResizePercent = $newHeight / ($this->height / 100); + $newWidth = round(($heightResizePercent / 100) * $this->width); + $widthResizePercent = $heightResizePercent; + } + + } elseif (($newWidth && !$newHeight) || (!$newWidth && $newHeight)) { // New width OR new height is given + + if ($newWidth) { + + $widthResizePercent = $newWidth / ($this->width / 100); + $heightResizePercent = 100; + $newHeight = $this->height; + + } else { + + $heightResizePercent = $newHeight / ($this->height / 100); + $widthResizePercent = 100; + $newWidth = $this->width; + } + + } else { // New width AND new height are given + + $widthResizePercent = $newWidth / ($this->width / 100); + $heightResizePercent = $newHeight / ($this->height / 100); + } + + // Update the layer positions in the stack + + foreach ($this->layerPositions as $layerId => $layerPosition) { + + $newPosX = round(($widthResizePercent / 100) * $layerPosition['x']); + $newPosY = round(($heightResizePercent / 100) * $layerPosition['y']); + + $this->changePosition($layerId, $newPosX, $newPosY); + } + + // Resize layers in the stack + + $layers = $this->layers; + + foreach ($layers as $key => $layer) { + $layer->resizeInPercent($widthResizePercent, $heightResizePercent); + $this->layers[$key] = $layer; + } + + $this->resizeBackground($newWidth, $newHeight); // Resize the layer + } + } + + /** + * Resize the layer by its largest side by specifying pixel + * + * @param integer $newLargestSideWidth + * @param boolean $converseProportion + */ + public function resizeByLargestSideInPixel($newLargestSideWidth, $converseProportion = false) + { + $this->resizeByLargestSide(self::UNIT_PIXEL, $newLargestSideWidth, $converseProportion); + } + + /** + * Resize the layer by its largest side by specifying percent + * + * @param integer $newLargestSideWidth percent + * @param boolean $converseProportion + */ + public function resizeByLargestSideInPercent($newLargestSideWidth, $converseProportion = false) + { + $this->resizeByLargestSide(self::UNIT_PERCENT, $newLargestSideWidth, $converseProportion); + } + + /** + * Resize the layer by its largest side + * + * @param string $unit + * @param integer $newLargestSideWidth percent + * @param boolean $converseProportion + */ + public function resizeByLargestSide($unit = self::UNIT_PIXEL, $newLargestSideWidth, $converseProportion = false) + { + if ($unit == self::UNIT_PERCENT) { + $newLargestSideWidth = round(($newLargestSideWidth / 100) * $this->getLargestSideWidth()); + } + + if ($this->getWidth() > $this->getHeight()) { + $this->resizeInPixel($newLargestSideWidth, null, $converseProportion); + } else { + $this->resizeInPixel(null, $newLargestSideWidth, $converseProportion); + } + } + + /** + * Resize the layer by its narrow side by specifying pixel + * + * @param integer $newNarrowSideWidth + * @param boolean $converseProportion + */ + public function resizeByNarrowSideInPixel($newNarrowSideWidth, $converseProportion = false) + { + $this->resizeByNarrowSide(self::UNIT_PIXEL, $newNarrowSideWidth, $converseProportion); + } + + /** + * Resize the layer by its narrow side by specifying percent + * + * @param integer $newNarrowSideWidth percent + * @param boolean $converseProportion + */ + public function resizeByNarrowSideInPercent($newNarrowSideWidth, $converseProportion = false) + { + $this->resizeByNarrowSide(self::UNIT_PERCENT, $newNarrowSideWidth, $converseProportion); + } + + /** + * Resize the layer by its narrow side + * + * @param string $unit + * @param integer $newNarrowSideWidth + * @param boolean $converseProportion + */ + public function resizeByNarrowSide($unit = self::UNIT_PIXEL, $newNarrowSideWidth, $converseProportion = false) + { + if ($unit == self::UNIT_PERCENT) { + $newNarrowSideWidth = round(($newNarrowSideWidth / 100) * $this->getNarrowSideWidth()); + } + + if ($this->getWidth() < $this->getHeight()) { + $this->resizeInPixel($newNarrowSideWidth, null, $converseProportion); + } else { + $this->resizeInPixel(null, $newNarrowSideWidth, $converseProportion); + } + } + + /** + * Crop the document by specifying pixels + * + * $backgroundColor: can be set transparent (The script will be longer to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param integer $width + * @param integer $height + * @param integer $positionX + * @param integer $positionY + * @param string $position + */ + public function cropInPixel($width = 0, $height = 0, $positionX = 0, $positionY = 0, $position = 'LT') + { + $this->crop(self::UNIT_PIXEL, $width, $height, $positionX, $positionY, $position); + } + + /** + * Crop the document by specifying percent + * + * $backgroundColor can be set transparent (but script could be long to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param float $percentWidth + * @param float $percentHeight + * @param float $positionXPercent + * @param float $positionYPercent + * @param string $position + */ + public function cropInPercent($percentWidth = 0, $percentHeight = 0, $positionXPercent = 0, $positionYPercent = 0, $position = 'LT') + { + $this->crop(self::UNIT_PERCENT, $percentWidth, $percentHeight, $positionXPercent, $positionYPercent, $position); + } + + /** + * Crop the document + * + * $backgroundColor can be set transparent (but script could be long to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param string $unit + * @param mixed $width (integer or float) + * @param mixed $height (integer or float) + * @param mixed $positionX (integer or float) + * @param mixed $positionY (integer or float) + * @param string $position + */ + public function crop($unit = self::UNIT_PIXEL, $width = 0, $height = 0, $positionX = 0, $positionY = 0, $position = 'LT') + { + if ($width < 0 || $height < 0) { + throw new ImageWorkshopLayerException('You can\'t use negative $width or $height for "'.__METHOD__.'" method.', static::ERROR_NEGATIVE_NUMBER_USED); + } + + if ($unit == self::UNIT_PERCENT) { + + $width = round(($width / 100) * $this->width); + $height = round(($height / 100) * $this->height); + + $positionX = round(($positionX / 100) * $this->width); + $positionY = round(($positionY / 100) * $this->height); + } + + if (($width != $this->width || $positionX == 0) || ($height != $this->height || $positionY == 0)) { + + if ($width == 0) { + $width = 1; + } + + if ($height == 0) { + $height = 1; + } + + $layerTmp = ImageWorkshop::initVirginLayer($width, $height); + $layerClone = ImageWorkshop::initVirginLayer($this->width, $this->height); + + imagedestroy($layerClone->image); + $layerClone->image = $this->image; + + $layerTmp->addLayer(1, $layerClone, -$positionX, -$positionY, $position); + + $newPos = $layerTmp->getLayerPositions(); + $layerNewPosX = $newPos[1]['x']; + $layerNewPosY = $newPos[1]['y']; + + // update the layer + $this->width = $layerTmp->getWidth(); + $this->height = $layerTmp->getHeight(); + $this->image = $layerTmp->getResult(); + unset($layerTmp); + unset($layerClone); + + $this->updateLayerPositionsAfterCropping($layerNewPosX, $layerNewPosY); + } + } + + /** + * Crop the document to a specific aspect ratio by specifying a shift in pixel + * + * $backgroundColor: can be set transparent (The script will be longer to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param integer $width + * @param integer $height + * @param integer $positionX + * @param integer $positionY + * @param string $position + */ + public function cropToAspectRatioInPixel($width = 0, $height = 0, $positionX = 0, $positionY = 0, $position = 'LT') + { + $this->cropToAspectRatio(self::UNIT_PIXEL, $width, $height, $positionX, $positionY, $position); + } + + /** + * Crop the document to a specific aspect ratio by specifying a shift in percent + * + * $backgroundColor can be set transparent (but script could be long to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param integer $width + * @param integer $height + * @param float $positionXPercent + * @param float $positionYPercent + * @param string $position + */ + public function cropToAspectRatioInPercent($width = 0, $height = 0, $positionXPercent = 0, $positionYPercent = 0, $position = 'LT') + { + $this->cropToAspectRatio(self::UNIT_PERCENT, $width, $height, $positionXPercent, $positionYPercent, $position); + } + + /** + * Crop the document to a specific aspect ratio + * + * $backgroundColor can be set transparent (but script could be long to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param string $unit + * @param integer $width (integer or float) + * @param integer $height (integer or float) + * @param mixed $positionX (integer or float) + * @param mixed $positionY (integer or float) + * @param string $position + */ + public function cropToAspectRatio($unit = self::UNIT_PIXEL, $width = 0, $height = 0, $positionX = 0, $positionY = 0, $position = 'LT') + { + if ($width < 0 || $height < 0) { + throw new ImageWorkshopLayerException('You can\'t use negative $width or $height for "'.__METHOD__.'" method.', static::ERROR_NEGATIVE_NUMBER_USED); + } + + if ($width == 0) { + $width = 1; + } + + if ($height == 0) { + $height = 1; + } + + if ($this->width / $this->height <= $width / $height) { + $newWidth = $this->width; + $newHeight = round($height * ($this->width / $width)); + } else { + $newWidth = round($width * ($this->height / $height)); + $newHeight = $this->height; + } + + if ($unit == self::UNIT_PERCENT) { + $positionX = round(($positionX / 100) * ($this->width - $newWidth)); + $positionY = round(($positionY / 100) * ($this->height - $newHeight)); + } + + $this->cropInPixel($newWidth, $newHeight, $positionX, $positionY, $position); + } + + /** + * Crop the maximum possible from left top ("LT"), "RT"... by specifying a shift in pixel + * + * $backgroundColor can be set transparent (but script could be long to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param integer $width + * @param integer $height + * @param integer $positionX + * @param integer $positionY + * @param string $position + */ + public function cropMaximumInPixel($positionX = 0, $positionY = 0, $position = 'LT') + { + $this->cropMaximum(self::UNIT_PIXEL, $positionX, $positionY, $position); + } + + /** + * Crop the maximum possible from left top ("LT"), "RT"... by specifying a shift in percent + * + * $backgroundColor can be set transparent (but script could be long to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param integer $width + * @param integer $height + * @param integer $positionXPercent + * @param integer $positionYPercent + * @param string $position + */ + public function cropMaximumInPercent($positionXPercent = 0, $positionYPercent = 0, $position = 'LT') + { + $this->cropMaximum(self::UNIT_PERCENT, $positionXPercent, $positionYPercent, $position); + } + + /** + * Crop the maximum possible from left top + * + * $backgroundColor can be set transparent (but script could be long to execute) + * $position: http://phpimageworkshop.com/doc/22/corners-positions-schema-of-an-image.html + * + * @param string $unit + * @param integer $width + * @param integer $height + * @param integer $positionX + * @param integer $positionY + * @param string $position + */ + public function cropMaximum($unit = self::UNIT_PIXEL, $positionX = 0, $positionY = 0, $position = 'LT') + { + $narrowSide = $this->getNarrowSideWidth(); + + if ($unit == self::UNIT_PERCENT) { + $positionX = round(($positionX / 100) * $this->width); + $positionY = round(($positionY / 100) * $this->height); + } + + $this->cropInPixel($narrowSide, $narrowSide, $positionX, $positionY, $position); + } + + /** + * Rotate the layer (in degree) + * + * @param float $degrees + */ + public function rotate($degrees) + { + if ($degrees != 0) { + + if ($degrees < -360 || $degrees > 360) { + $degrees = $degrees % 360; + } + + if ($degrees < 0 && $degrees >= -360) { + $degrees = 360 + $degrees; + } + + // Rotate the layer background image + $imageRotated = imagerotate($this->image, -$degrees, -1); + imagealphablending($imageRotated, true); + imagesavealpha($imageRotated, true); + + unset($this->image); + + $this->image = $imageRotated; + + $oldWidth = $this->width; + $oldHeight = $this->height; + + $this->width = imagesx($this->image); + $this->height = imagesy($this->image); + + foreach ($this->layers as $layerId => $layer) { + + $layerSelfOldCenterPosition = array( + 'x' => $layer->width / 2, + 'y' => $layer->height / 2, + ); + + $smallImageCenter = array( + 'x' => $layerSelfOldCenterPosition['x'] + $this->layerPositions[$layerId]['x'], + 'y' => $layerSelfOldCenterPosition['y'] + $this->layerPositions[$layerId]['y'], + ); + + $this->layers[$layerId]->rotate($degrees); + + $ro = sqrt(pow($smallImageCenter['x'], 2) + pow($smallImageCenter['y'], 2)); + + $teta = (acos($smallImageCenter['x'] / $ro)) * 180 / pi(); + + $a = $ro * cos(($teta + $degrees) * pi() / 180); + $b = $ro * sin(($teta + $degrees) * pi() / 180); + + if ($degrees > 0 && $degrees <= 90) { + + $newPositionX = $a - ($this->layers[$layerId]->width / 2) + $oldHeight * sin(($degrees * pi()) / 180); + $newPositionY = $b - ($this->layers[$layerId]->height / 2); + + } elseif ($degrees > 90 && $degrees <= 180) { + + $newPositionX = $a - ($this->layers[$layerId]->width / 2) + $this->width; + $newPositionY = $b - ($this->layers[$layerId]->height / 2) + $oldHeight * (-cos(($degrees) * pi() / 180)); + + } elseif ($degrees > 180 && $degrees <= 270) { + + $newPositionX = $a - ($this->layers[$layerId]->width / 2) + $oldWidth * (-cos(($degrees) * pi() / 180)); + $newPositionY = $b - ($this->layers[$layerId]->height / 2) + $this->height; + + } else { + + $newPositionX = $a - ($this->layers[$layerId]->width / 2); + $newPositionY = $b - ($this->layers[$layerId]->height / 2) + $oldWidth * (-sin(($degrees) * pi() / 180)); + } + + $this->layerPositions[$layerId] = array( + 'x' => $newPositionX, + 'y' => $newPositionY, + ); + } + } + } + + /** + * Change the opacity of the layer + * $recursive: apply it on sublayers + * + * @param integer $opacity + * @param boolean $recursive + */ + public function opacity($opacity, $recursive = true) + { + if ($recursive) { + + $layers = $this->layers; + + foreach ($layers as $key => $layer) { + $layer->opacity($opacity, true); + $this->layers[$key] = $layer; + } + } + + $transparentImage = ImageWorkshopLib::generateImage($this->getWidth(), $this->getHeight()); + + ImageWorkshopLib::imageCopyMergeAlpha($transparentImage, $this->image, 0, 0, 0, 0, $this->getWidth(), $this->getHeight(), $opacity); + + unset($this->image); + $this->image = $transparentImage; + unset($transparentImage); + } + + /** + * Apply a filter on the layer + * Be careful: some filters can damage transparent images, use it sparingly ! (A good pratice is to use mergeAll on your layer before applying a filter) + * + * @param int $filterType (http://www.php.net/manual/en/function.imagefilter.php) + * @param int $arg1 + * @param int $arg2 + * @param int $arg3 + * @param int $arg4 + * @param boolean $recursive + */ + public function applyFilter($filterType, $arg1 = null, $arg2 = null, $arg3 = null, $arg4 = null, $recursive = false) + { + if ($filterType == IMG_FILTER_COLORIZE) { + imagefilter($this->image, $filterType, $arg1, $arg2, $arg3, $arg4); + } elseif ($filterType == IMG_FILTER_BRIGHTNESS || $filterType == IMG_FILTER_CONTRAST || $filterType == IMG_FILTER_SMOOTH) { + imagefilter($this->image, $filterType, $arg1); + } elseif ($filterType == IMG_FILTER_PIXELATE) { + imagefilter($this->image, $filterType, $arg1, $arg2); + } else { + imagefilter($this->image, $filterType); + } + + if ($recursive) { + + $layers = $this->layers; + + foreach($layers as $layerId => $layer) { + $this->layers[$layerId]->applyFilter($filterType, $arg1, $arg2, $arg3, $arg4, true); + } + } + } + + /** + * Apply horizontal or vertical flip (Transformation) + * + * @param string $type + */ + public function flip($type = 'horizontal') + { + $layers = $this->layers; + + foreach ($layers as $key => $layer) { + + $layer->flip($type); + $this->layers[$key] = $layer; + } + + $temp = ImageWorkshopLib::generateImage($this->width, $this->height); + + if ($type == 'horizontal') { + + imagecopyresampled($temp, $this->image, 0, 0, $this->width - 1, 0, $this->width, $this->height, -$this->width, $this->height); + $this->image = $temp; + + foreach ($this->layerPositions as $layerId => $layerPositions) { + + $this->changePosition($layerId, $this->width - $this->layers[$layerId]->getWidth() - $layerPositions['x'], $layerPositions['y']); + } + + } elseif ($type == 'vertical') { + + imagecopyresampled($temp, $this->image, 0, 0, 0, $this->height - 1, $this->width, $this->height, $this->width, -$this->height); + $this->image = $temp; + + foreach ($this->layerPositions as $layerId => $layerPositions) { + + $this->changePosition($layerId, $layerPositions['x'], $this->height - $this->layers[$layerId]->getHeight() - $layerPositions['y']); + } + } + + unset($temp); + } + + /** + * Add a text on the background image of the layer using a default font registered in GD + * + * @param string $text + * @param integer $font + * @param string $color + * @param integer $positionX + * @param integer $positionY + * @param string $align + */ + public function writeText($text, $font = 1, $color = 'ffffff', $positionX = 0, $positionY = 0, $align = 'horizontal') + { + $RGBTextColor = ImageWorkshopLib::convertHexToRGB($color); + $textColor = imagecolorallocate($this->image, $RGBTextColor['R'], $RGBTextColor['G'], $RGBTextColor['B']); + + if ($align == 'horizontal') { + imagestring($this->image, $font, $positionX, $positionY, $text, $textColor); + } else { + imagestringup($this->image, $font, $positionX, $positionY, $text, $textColor); + } + } + + /** + * Add a text on the background image of the layer using a font localized at $fontPath + * Return the text coordonates + * + * @param string $text + * @param integer $fontPath + * @param integer $fontSize + * @param string $color + * @param integer $positionX + * @param integer $positionY + * @param integer $fontRotation + * + * @return array + */ + public function write($text, $fontPath, $fontSize = 13, $color = 'ffffff', $positionX = 0, $positionY = 0, $fontRotation = 0) + { + if (!file_exists($fontPath)) { + throw new ImageWorkshopLayerException('Can\'t find a font file at this path : "'.$fontPath.'".', static::ERROR_FONT_NOT_FOUND); + } + + $RGBTextColor = ImageWorkshopLib::convertHexToRGB($color); + $textColor = imagecolorallocate($this->image, $RGBTextColor['R'], $RGBTextColor['G'], $RGBTextColor['B']); + + return imagettftext($this->image, $fontSize, $fontRotation, $positionX, $positionY, $textColor, $fontPath, $text); + } + + // Manage the result + // ========================================================= + + /** + * Return a merged resource image + * + * $backgroundColor is really usefull if you want to save a JPG or GIF, because the transparency of the background + * would be remove for a colored background, so you should choose a color like "ffffff" (white) + * + * @param string $backgroundColor + * + * @return resource + */ + public function getResult($backgroundColor = null) + { + $imagesToMerge = array(); + ksort($this->layerLevels); + + foreach ($this->layerLevels as $layerLevel => $layerId) { + + $imagesToMerge[$layerLevel] = $this->layers[$layerId]->getResult(); + + // Layer positions + if ($this->layerPositions[$layerId]['x'] != 0 || $this->layerPositions[$layerId]['y'] != 0) { + + $virginLayoutImageTmp = ImageWorkshopLib::generateImage($this->width, $this->height); + ImageWorkshopLib::mergeTwoImages($virginLayoutImageTmp, $imagesToMerge[$layerLevel], $this->layerPositions[$layerId]['x'], $this->layerPositions[$layerId]['y'], 0, 0); + $imagesToMerge[$layerLevel] = $virginLayoutImageTmp; + unset($virginLayoutImageTmp); + } + } + + $iterator = 1; + $mergedImage = $this->image; + ksort($imagesToMerge); + + foreach ($imagesToMerge as $imageLevel => $image) { + ImageWorkshopLib::mergeTwoImages($mergedImage, $image); + $iterator++; + } + + $opacity = 127; + + if ($backgroundColor && $backgroundColor != 'transparent') { + $opacity = 0; + } + + $backgroundImage = ImageWorkshopLib::generateImage($this->width, $this->height, $backgroundColor, $opacity); + ImageWorkshopLib::mergeTwoImages($backgroundImage, $mergedImage); + $mergedImage = $backgroundImage; + unset($backgroundImage); + + return $mergedImage; + } + + /** + * Save the resulting image at the specified path + * + * $backgroundColor is really usefull if you want to save a JPG or GIF, because the transparency of the background + * would be remove for a colored background, so you should choose a color like "ffffff" (white) + * + * If the file already exists, it will be override ! + * + * $imageQuality is useless for GIF + * + * Ex: $folder = __DIR__."/../web/images/2012" + * $imageName = "butterfly.jpg" + * $createFolders = true + * $imageQuality = 95 + * $backgroundColor = "ffffff" + * + * @param string $folder + * @param string $imageName + * @param boolean $createFolders + * @param string $backgroundColor + * @param integer $imageQuality + * @param boolean $interlace + */ + public function save($folder, $imageName, $createFolders = true, $backgroundColor = null, $imageQuality = 75, $interlace = false) + { + if (!is_file($folder)) { + + if (is_dir($folder) || $createFolders) { + + // Creating the folders if they don't exist + if (!is_dir($folder) && $createFolders) { + $oldUmask = umask(0); + mkdir($folder, 0777, true); + umask($oldUmask); + chmod($folder, 0777); + } + + $extension = explode('.', $imageName); + $extension = strtolower($extension[count($extension) - 1]); + + $filename = $folder.'/'.$imageName; + + if (($extension == 'jpg' || $extension == 'jpeg' || $extension == 'gif') && (!$backgroundColor || $backgroundColor == 'transparent')) { + $backgroundColor = 'ffffff'; + } + + $image = $this->getResult($backgroundColor); + + imageinterlace($image, (int) $interlace); + + if ($extension == 'jpg' || $extension == 'jpeg') { + + imagejpeg($image, $filename, $imageQuality); + unset($image); + + } elseif ($extension == 'gif') { + + imagegif($image, $filename); + unset($image); + + } elseif ($extension == 'png') { + + $imageQuality = $imageQuality / 10; + $imageQuality -= 1; + + imagepng($image, $filename, $imageQuality); + unset($image); + } + } + } + } + + // Checkers + // ========================================================= + + /** + * Check if a sublayer exists in the stack for a given id + * + * @param integer $layerId + * + * @return boolean + */ + public function isLayerInIndex($layerId) + { + if (array_key_exists($layerId, $this->layers)) { + return true; + } + + return false; + } + + // Getter / Setter + // ========================================================= + + /** + * Return the narrow side width of the layer + * + * @return integer + */ + public function getNarrowSideWidth() + { + $narrowSideWidth = $this->getWidth(); + + if ($this->getHeight() < $narrowSideWidth) { + $narrowSideWidth = $this->getHeight(); + } + + return $narrowSideWidth; + } + + /** + * Return the largest side width of the layer + * + * @return integer + */ + public function getLargestSideWidth() + { + $largestSideWidth = $this->getWidth(); + + if ($this->getHeight() > $largestSideWidth) { + $largestSideWidth = $this->getHeight(); + } + + return $largestSideWidth; + } + + /** + * Get the level of a sublayer + * Return sublayer level if success or false if layer isn't found + * + * @param integer $layerId + * + * @return mixed (integer or boolean) + */ + public function getLayerLevel($layerId) + { + if ($this->isLayerInIndex($layerId)) { // if the layer exists in document + return array_search($layerId, $this->layerLevels); + } + + return false; + } + + /** + * Get a sublayer in the stack + * Don't forget to use clone method: $b = clone $a->getLayer(3); + * + * @param integer $layerId + * + * @return ImageWorkshop + */ + public function getLayer($layerId) + { + return $this->layers[$layerId]; + } + + /** + * Getter width + * + * @return integer + */ + public function getWidth() + { + return $this->width; + } + + /** + * Getter height + * + * @return integer + */ + public function getHeight() + { + return $this->height; + } + + /** + * Getter image + * + * @return resource + */ + public function getImage() + { + return $this->image; + } + + /** + * Getter layers + * + * @return array + */ + public function getLayers() + { + return $this->layers; + } + + /** + * Getter layerLevels + * + * @return array + */ + public function getLayerLevels() + { + return $this->layerLevels; + } + + /** + * Getter layerPositions + * + * Get all the positions of the sublayers, + * or when specifying $layerId, get the position of this sublayer + * + * @param integer $layerId + * + * @return mixed (array or boolean) + */ + public function getLayerPositions($layerId = null) + { + if (!$layerId) { + + return $this->layerPositions; + + } elseif ($this->isLayerInIndex($layerId)) { // if the sublayer exists in the stack + + return $this->layerPositions[$layerId]; + } + + return false; + } + + /** + * Getter highestLayerLevel + * + * @return array + */ + public function getHighestLayerLevel() + { + return $this->highestLayerLevel; + } + + /** + * Getter lastLayerId + * + * @return array + */ + public function getLastLayerId() + { + return $this->lastLayerId; + } + + // Internals + // ========================================================= + + /** + * Delete the current object + */ + public function delete() + { + imagedestroy($this->image); + $this->clearStack(); + } + + /** + * Create a new background image var from the old background image var + */ + public function createNewVarFromBackgroundImage() + { + $virginImage = ImageWorkshopLib::generateImage($this->getWidth(), $this->getHeight()); // New background image + + ImageWorkshopLib::mergeTwoImages($virginImage, $this->image, 0, 0, 0, 0); + unset($this->image); + + $this->image = $virginImage; + unset($virginImage); + + $layers = $this->layers; + + foreach($layers as $layerId => $layer) { + $this->layers[$layerId] = clone $this->layers[$layerId]; + } + } + + /** + * Index a sublayer in the layer stack + * Return an array containing the generated sublayer id and its final level: + * array("layerLevel" => integer, "id" => integer) + * + * @param integer $layerLevel + * @param ImageWorkshopLayer $layer + * @param integer $positionX + * @param integer $positionY + * @param string $position + * + * @return array + */ + protected function indexLayer($layerLevel, $layer, $positionX = 0, $positionY = 0, $position) + { + // Choose an id for the added layer + $layerId = $this->lastLayerId + 1; + + // Clone $layer to duplicate image resource var + $layer = clone $layer; + + // Add the layer in the stack + $this->layers[$layerId] = $layer; + + // Add the layer positions in the main layer + $this->layerPositions[$layerId] = ImageWorkshopLib::calculatePositions($this->getWidth(), $this->getHeight(), $layer->getWidth(), $layer->getHeight(), $positionX, $positionY, $position); + + // Update the lastLayerId of the workshop + $this->lastLayerId = $layerId; + + // Add the layer level in the stack + $layerLevel = $this->indexLevelInDocument($layerLevel, $layerId); + + return array( + 'layerLevel' => $layerLevel, + 'id' => $layerId, + ); + } + + /** + * Index a layer level and update the layers levels in the document + * Return the corrected level of the layer + * + * @param integer $layerLevel + * @param integer $layerId + * + * @return integer + */ + protected function indexLevelInDocument($layerLevel, $layerId) + { + if (array_key_exists($layerLevel, $this->layerLevels)) { // Level already exists + + ksort($this->layerLevels); // All layers after this level and the layer which have this level are updated + $layerLevelsTmp = $this->layerLevels; + + foreach ($layerLevelsTmp as $levelTmp => $layerIdTmp) { + if ($levelTmp >= $layerLevel) { + $this->layerLevels[$levelTmp + 1] = $layerIdTmp; + } + } + + unset($layerLevelsTmp); + + } else { // Level isn't taken + if ($this->highestLayerLevel < $layerLevel) { // If given level is too high, proceed adjustement + $layerLevel = $this->highestLayerLevel + 1; + } + } + + $this->layerLevels[$layerLevel] = $layerId; + $this->highestLayerLevel = max(array_flip($this->layerLevels)); // Update $highestLayerLevel + + return $layerLevel; + } + + /** + * Update the positions of layers in the stack after cropping + * + * @param integer $positionX + * @param integer $positionY + */ + public function updateLayerPositionsAfterCropping($positionX, $positionY) + { + foreach ($this->layers as $layerId => $layer) { + + $oldLayerPosX = $this->layerPositions[$layerId]['x']; + $oldLayerPosY = $this->layerPositions[$layerId]['y']; + + $newLayerPosX = $oldLayerPosX + $positionX; + $newLayerPosY = $oldLayerPosY + $positionY; + + $this->changePosition($layerId, $newLayerPosX, $newLayerPosY); + } + } + + /** + * Resize the background of a layer + * + * @param integer $newWidth + * @param integer $newHeight + */ + public function resizeBackground($newWidth, $newHeight) + { + $oldWidth = $this->width; + $oldHeight = $this->height; + + $this->width = $newWidth; + $this->height = $newHeight; + + $virginLayoutImage = ImageWorkshopLib::generateImage($this->width, $this->height); + + imagecopyresampled($virginLayoutImage, $this->image, 0, 0, 0, 0, $this->width, $this->height, $oldWidth, $oldHeight); + + unset($this->image); + $this->image = $virginLayoutImage; + } + + // Deprecated, don't use anymore + // ========================================================= + + /** + * @deprecated + */ + public function resizeInPourcent($percentWidth = null, $percentHeight = null, $converseProportion = false, $positionX = 0, $positionY = 0, $position = 'MM') + { + throw new ImageWorkshopLayerException('Method resizeInPourcent() was renamed resizeInPercent(). Use resizeInPercent() instead.', static::METHOD_DEPRECATED); + } + + /** + * @deprecated + */ + public function resizeByLargestSideInPourcent($newLargestSideWidth, $converseProportion = false) + { + throw new ImageWorkshopLayerException('Method resizeByLargestSideInPourcent() was renamed resizeByLargestSideInPercent(). Use resizeByLargestSideInPercent() instead.', static::METHOD_DEPRECATED); + } + + /** + * @deprecated + */ + public function resizeByNarrowSideInPourcent($newNarrowSideWidth, $converseProportion = false) + { + throw new ImageWorkshopLayerException('Method resizeByNarrowSideInPourcent() was renamed resizeByNarrowSideInPercent(). Use resizeByNarrowSideInPercent() instead.', static::METHOD_DEPRECATED); + } + + /** + * @deprecated + */ + public function cropInPourcent($percentWidth = 0, $percentHeight = 0, $positionXPercent = 0, $positionYPercent = 0, $position = 'LT') + { + throw new ImageWorkshopLayerException('Method cropInPourcent() was renamed cropInPercent(). Use cropInPercent() instead.', static::METHOD_DEPRECATED); + } + + /** + * @deprecated + */ + public function cropMaximumInPourcent($positionXPercent = 0, $positionYPercent = 0, $position = 'LT') + { + throw new ImageWorkshopLayerException('Method cropMaximumInPourcent() was renamed cropMaximumInPercent(). Use cropMaximumInPercent() instead.', static::METHOD_DEPRECATED); + } +} diff --git a/PHPImageWorkshop/Core/ImageWorkshopLib.php b/PHPImageWorkshop/Core/ImageWorkshopLib.php index ed928ee..c650218 100644 --- a/PHPImageWorkshop/Core/ImageWorkshopLib.php +++ b/PHPImageWorkshop/Core/ImageWorkshopLib.php @@ -1,299 +1,299 @@ - $layerPositionX, - 'y' => $layerPositionY, - ); - } - - /** - * Convert Hex color to RGB color format - * - * @param string $hex - * - * @return array - */ - public static function convertHexToRGB($hex) - { - return array( - 'R' => (int) base_convert(substr($hex, 0, 2), 16, 10), - 'G' => (int) base_convert(substr($hex, 2, 2), 16, 10), - 'B' => (int) base_convert(substr($hex, 4, 2), 16, 10), - ); - } - - /** - * Generate a new image resource var - * - * @param integer $width - * @param integer $height - * @param string $color - * @param integer $opacity - * - * @return resource - */ - public static function generateImage($width = 100, $height = 100, $color = 'ffffff', $opacity = 127) - { - $RGBColors = ImageWorkshopLib::convertHexToRGB($color); - - $image = imagecreatetruecolor($width, $height); - imagesavealpha($image, true); - $color = imagecolorallocatealpha($image, $RGBColors['R'], $RGBColors['G'], $RGBColors['B'], $opacity); - imagefill($image, 0, 0, $color); - - return $image; - } - - /** - * Return dimension of a text - * - * @param $fontSize - * @param $fontAngle - * @param $fontFile - * @param $text - * - * @return array or boolean - */ - public static function getTextBoxDimension($fontSize, $fontAngle, $fontFile, $text) - { - if (!file_exists($fontFile)) { - throw new ImageWorkshopLibException('Can\'t find a font file at this path : "'.$fontFile.'".', static::ERROR_FONT_NOT_FOUND); - } - - $box = imagettfbbox($fontSize, $fontAngle, $fontFile, $text); - - if (!$box) { - - return false; - } - - $minX = min(array($box[0], $box[2], $box[4], $box[6])); - $maxX = max(array($box[0], $box[2], $box[4], $box[6])); - $minY = min(array($box[1], $box[3], $box[5], $box[7])); - $maxY = max(array($box[1], $box[3], $box[5], $box[7])); - $width = ($maxX - $minX); - $height = ($maxY - $minY); - $left = abs($minX) + $width; - $top = abs($minY) + $height; - - // to calculate the exact bounding box, we write the text in a large image - $img = @imagecreatetruecolor($width << 2, $height << 2); - $white = imagecolorallocate($img, 255, 255, 255); - $black = imagecolorallocate($img, 0, 0, 0); - imagefilledrectangle($img, 0, 0, imagesx($img), imagesy($img), $black); - - // for ensure that the text is completely in the image - imagettftext($img, $fontSize, $fontAngle, $left, $top, $white, $fontFile, $text); - - // start scanning (0=> black => empty) - $rleft = $w4 = $width<<2; - $rright = 0; - $rbottom = 0; - $rtop = $h4 = $height<<2; - - for ($x = 0; $x < $w4; $x++) { - - for ($y = 0; $y < $h4; $y++) { - - if (imagecolorat($img, $x, $y)) { - - $rleft = min($rleft, $x); - $rright = max($rright, $x); - $rtop = min($rtop, $y); - $rbottom = max($rbottom, $y); - } - } - } - - imagedestroy($img); - - return array( - 'left' => $left - $rleft, - 'top' => $top - $rtop, - 'width' => $rright - $rleft + 1, - 'height' => $rbottom - $rtop + 1, - ); - } - - /** - * Copy an image on another one and converse transparency - * - * @param resource $destImg - * @param resource $srcImg - * @param integer $destX - * @param integer $destY - * @param integer $srcX - * @param integer $srcY - * @param integer $srcW - * @param integer $srcH - * @param integer $pct - */ - public static function imageCopyMergeAlpha(&$destImg, &$srcImg, $destX, $destY, $srcX, $srcY, $srcW, $srcH, $pct = 0) - { - $destX = (int) $destX; - $destY = (int) $destY; - $srcX = (int) $srcX; - $srcY = (int) $srcY; - $srcW = (int) $srcW; - $srcH = (int) $srcH; - $pct = (int) $pct; - $destW = imageSX($destImg); - $destH = imageSY($destImg); - - for ($y = 0; $y < $srcH + $srcY; $y++) { - - for ($x = 0; $x < $srcW + $srcX; $x++) { - - if ($x + $destX >= 0 && $x + $destX < $destW && $x + $srcX >= 0 && $x + $srcX < $srcW && $y + $destY >= 0 && $y + $destY < $destH && $y + $srcY >= 0 && $y + $srcY < $srcH) { - - $destPixel = imageColorsForIndex($destImg, imageColorat($destImg, $x + $destX, $y + $destY)); - $srcImgColorat = imageColorat($srcImg, $x + $srcX, $y + $srcY); - - if ($srcImgColorat >= 0) { - - $srcPixel = imageColorsForIndex($srcImg, $srcImgColorat); - - $srcAlpha = 1 - ($srcPixel['alpha'] / 127); - $destAlpha = 1 - ($destPixel['alpha'] / 127); - $opacity = $srcAlpha * $pct / 100; - - if ($destAlpha >= $opacity) { - $alpha = $destAlpha; - } - - if ($destAlpha < $opacity) { - $alpha = $opacity; - } - - if ($alpha > 1) { - $alpha = 1; - } - - if ($opacity > 0) { - - $destRed = round((($destPixel['red'] * $destAlpha * (1 - $opacity)))); - $destGreen = round((($destPixel['green'] * $destAlpha * (1 - $opacity)))); - $destBlue = round((($destPixel['blue'] * $destAlpha * (1 - $opacity)))); - $srcRed = round((($srcPixel['red'] * $opacity))); - $srcGreen = round((($srcPixel['green'] * $opacity))); - $srcBlue = round((($srcPixel['blue'] * $opacity))); - $red = round(($destRed + $srcRed ) / ($destAlpha * (1 - $opacity) + $opacity)); - $green = round(($destGreen + $srcGreen) / ($destAlpha * (1 - $opacity) + $opacity)); - $blue = round(($destBlue + $srcBlue ) / ($destAlpha * (1 - $opacity) + $opacity)); - - if ($red > 255) { - $red = 255; - } - - if ($green > 255) { - $green = 255; - } - - if ($blue > 255) { - $blue = 255; - } - - $alpha = round((1 - $alpha) * 127); - $color = imageColorAllocateAlpha($destImg, $red, $green, $blue, $alpha); - imageSetPixel($destImg, $x + $destX, $y + $destY, $color); - } - } - } - } - } - } - - /** - * Merge two image var - * - * @param resource $destinationImage - * @param resource $sourceImage - * @param integer $destinationPosX - * @param integer $destinationPosY - * @param integer $sourcePosX - * @param integer $sourcePosY - */ - public static function mergeTwoImages(&$destinationImage, $sourceImage, $destinationPosX = 0, $destinationPosY = 0, $sourcePosX = 0, $sourcePosY = 0) - { - imageCopy($destinationImage, $sourceImage, $destinationPosX, $destinationPosY, $sourcePosX, $sourcePosY, imageSX($sourceImage), imageSY($sourceImage)); - } + $layerPositionX, + 'y' => $layerPositionY, + ); + } + + /** + * Convert Hex color to RGB color format + * + * @param string $hex + * + * @return array + */ + public static function convertHexToRGB($hex) + { + return array( + 'R' => (int) base_convert(substr($hex, 0, 2), 16, 10), + 'G' => (int) base_convert(substr($hex, 2, 2), 16, 10), + 'B' => (int) base_convert(substr($hex, 4, 2), 16, 10), + ); + } + + /** + * Generate a new image resource var + * + * @param integer $width + * @param integer $height + * @param string $color + * @param integer $opacity + * + * @return resource + */ + public static function generateImage($width = 100, $height = 100, $color = 'ffffff', $opacity = 127) + { + $RGBColors = ImageWorkshopLib::convertHexToRGB($color); + + $image = imagecreatetruecolor($width, $height); + imagesavealpha($image, true); + $color = imagecolorallocatealpha($image, $RGBColors['R'], $RGBColors['G'], $RGBColors['B'], $opacity); + imagefill($image, 0, 0, $color); + + return $image; + } + + /** + * Return dimension of a text + * + * @param $fontSize + * @param $fontAngle + * @param $fontFile + * @param $text + * + * @return array or boolean + */ + public static function getTextBoxDimension($fontSize, $fontAngle, $fontFile, $text) + { + if (!file_exists($fontFile)) { + throw new ImageWorkshopLibException('Can\'t find a font file at this path : "'.$fontFile.'".', static::ERROR_FONT_NOT_FOUND); + } + + $box = imagettfbbox($fontSize, $fontAngle, $fontFile, $text); + + if (!$box) { + + return false; + } + + $minX = min(array($box[0], $box[2], $box[4], $box[6])); + $maxX = max(array($box[0], $box[2], $box[4], $box[6])); + $minY = min(array($box[1], $box[3], $box[5], $box[7])); + $maxY = max(array($box[1], $box[3], $box[5], $box[7])); + $width = ($maxX - $minX); + $height = ($maxY - $minY); + $left = abs($minX) + $width; + $top = abs($minY) + $height; + + // to calculate the exact bounding box, we write the text in a large image + $img = @imagecreatetruecolor($width << 2, $height << 2); + $white = imagecolorallocate($img, 255, 255, 255); + $black = imagecolorallocate($img, 0, 0, 0); + imagefilledrectangle($img, 0, 0, imagesx($img), imagesy($img), $black); + + // for ensure that the text is completely in the image + imagettftext($img, $fontSize, $fontAngle, $left, $top, $white, $fontFile, $text); + + // start scanning (0=> black => empty) + $rleft = $w4 = $width<<2; + $rright = 0; + $rbottom = 0; + $rtop = $h4 = $height<<2; + + for ($x = 0; $x < $w4; $x++) { + + for ($y = 0; $y < $h4; $y++) { + + if (imagecolorat($img, $x, $y)) { + + $rleft = min($rleft, $x); + $rright = max($rright, $x); + $rtop = min($rtop, $y); + $rbottom = max($rbottom, $y); + } + } + } + + imagedestroy($img); + + return array( + 'left' => $left - $rleft, + 'top' => $top - $rtop, + 'width' => $rright - $rleft + 1, + 'height' => $rbottom - $rtop + 1, + ); + } + + /** + * Copy an image on another one and converse transparency + * + * @param resource $destImg + * @param resource $srcImg + * @param integer $destX + * @param integer $destY + * @param integer $srcX + * @param integer $srcY + * @param integer $srcW + * @param integer $srcH + * @param integer $pct + */ + public static function imageCopyMergeAlpha(&$destImg, &$srcImg, $destX, $destY, $srcX, $srcY, $srcW, $srcH, $pct = 0) + { + $destX = (int) $destX; + $destY = (int) $destY; + $srcX = (int) $srcX; + $srcY = (int) $srcY; + $srcW = (int) $srcW; + $srcH = (int) $srcH; + $pct = (int) $pct; + $destW = imageSX($destImg); + $destH = imageSY($destImg); + + for ($y = 0; $y < $srcH + $srcY; $y++) { + + for ($x = 0; $x < $srcW + $srcX; $x++) { + + if ($x + $destX >= 0 && $x + $destX < $destW && $x + $srcX >= 0 && $x + $srcX < $srcW && $y + $destY >= 0 && $y + $destY < $destH && $y + $srcY >= 0 && $y + $srcY < $srcH) { + + $destPixel = imageColorsForIndex($destImg, imageColorat($destImg, $x + $destX, $y + $destY)); + $srcImgColorat = imageColorat($srcImg, $x + $srcX, $y + $srcY); + + if ($srcImgColorat >= 0) { + + $srcPixel = imageColorsForIndex($srcImg, $srcImgColorat); + + $srcAlpha = 1 - ($srcPixel['alpha'] / 127); + $destAlpha = 1 - ($destPixel['alpha'] / 127); + $opacity = $srcAlpha * $pct / 100; + + if ($destAlpha >= $opacity) { + $alpha = $destAlpha; + } + + if ($destAlpha < $opacity) { + $alpha = $opacity; + } + + if ($alpha > 1) { + $alpha = 1; + } + + if ($opacity > 0) { + + $destRed = round((($destPixel['red'] * $destAlpha * (1 - $opacity)))); + $destGreen = round((($destPixel['green'] * $destAlpha * (1 - $opacity)))); + $destBlue = round((($destPixel['blue'] * $destAlpha * (1 - $opacity)))); + $srcRed = round((($srcPixel['red'] * $opacity))); + $srcGreen = round((($srcPixel['green'] * $opacity))); + $srcBlue = round((($srcPixel['blue'] * $opacity))); + $red = round(($destRed + $srcRed ) / ($destAlpha * (1 - $opacity) + $opacity)); + $green = round(($destGreen + $srcGreen) / ($destAlpha * (1 - $opacity) + $opacity)); + $blue = round(($destBlue + $srcBlue ) / ($destAlpha * (1 - $opacity) + $opacity)); + + if ($red > 255) { + $red = 255; + } + + if ($green > 255) { + $green = 255; + } + + if ($blue > 255) { + $blue = 255; + } + + $alpha = round((1 - $alpha) * 127); + $color = imageColorAllocateAlpha($destImg, $red, $green, $blue, $alpha); + imageSetPixel($destImg, $x + $destX, $y + $destY, $color); + } + } + } + } + } + } + + /** + * Merge two image var + * + * @param resource $destinationImage + * @param resource $sourceImage + * @param integer $destinationPosX + * @param integer $destinationPosY + * @param integer $sourcePosX + * @param integer $sourcePosY + */ + public static function mergeTwoImages(&$destinationImage, $sourceImage, $destinationPosX = 0, $destinationPosY = 0, $sourcePosX = 0, $sourcePosY = 0) + { + imageCopy($destinationImage, $sourceImage, $destinationPosX, $destinationPosY, $sourcePosX, $sourcePosY, imageSX($sourceImage), imageSY($sourceImage)); + } } \ No newline at end of file diff --git a/PHPImageWorkshop/Exception/ImageWorkshopBaseException.php b/PHPImageWorkshop/Exception/ImageWorkshopBaseException.php index 81ed653..e1925f5 100644 --- a/PHPImageWorkshop/Exception/ImageWorkshopBaseException.php +++ b/PHPImageWorkshop/Exception/ImageWorkshopBaseException.php @@ -1,38 +1,38 @@ -code}]: {$this->message}\n"; - } +code}]: {$this->message}\n"; + } } \ No newline at end of file diff --git a/PHPImageWorkshop/Exception/ImageWorkshopException.php b/PHPImageWorkshop/Exception/ImageWorkshopException.php index c2efa97..7663c93 100644 --- a/PHPImageWorkshop/Exception/ImageWorkshopException.php +++ b/PHPImageWorkshop/Exception/ImageWorkshopException.php @@ -1,22 +1,22 @@ -write($text, $fontPath, $fontSize, $fontColor, $textDimensions['left'], $textDimensions['top'], $textRotation); - - return $layer; - } - - /** - * Initialize a new virgin layer - * - * @param integer $width - * @param integer $height - * @param string $backgroundColor - * - * @return ImageWorkshopLayer - */ - public static function initVirginLayer($width = 100, $height = 100, $backgroundColor = null) - { - $opacity = 0; - - if (!$backgroundColor || $backgroundColor == 'transparent') { - $opacity = 127; - $backgroundColor = 'ffffff'; - } - - return new ImageWorkshopLayer(ImageWorkshopLib::generateImage($width, $height, $backgroundColor, $opacity)); - } - - /** - * Initialize a layer from a resource image var - * - * @param \resource $image - * - * @return ImageWorkshopLayer - */ - public static function initFromResourceVar($image) - { - return new ImageWorkshopLayer($image); - } - - /** - * Initialize a layer from a string (obtains with file_get_contents, cURL...) - * - * This not recommanded to initialize JPEG string with this method, GD displays bugs ! - * - * @param string $imageString - * - * @return ImageWorkshopLayer - */ - public static function initFromString($imageString) - { - if (!$image = @imageCreateFromString($imageString)) { - throw new ImageWorkshopException('Can\'t generate an image from the given string.', static::ERROR_CREATE_IMAGE_FROM_STRING); - } - - return new ImageWorkshopLayer($image); - } +write($text, $fontPath, $fontSize, $fontColor, $textDimensions['left'], $textDimensions['top'], $textRotation); + + return $layer; + } + + /** + * Initialize a new virgin layer + * + * @param integer $width + * @param integer $height + * @param string $backgroundColor + * + * @return ImageWorkshopLayer + */ + public static function initVirginLayer($width = 100, $height = 100, $backgroundColor = null) + { + $opacity = 0; + + if (!$backgroundColor || $backgroundColor == 'transparent') { + $opacity = 127; + $backgroundColor = 'ffffff'; + } + + return new ImageWorkshopLayer(ImageWorkshopLib::generateImage($width, $height, $backgroundColor, $opacity)); + } + + /** + * Initialize a layer from a resource image var + * + * @param \resource $image + * + * @return ImageWorkshopLayer + */ + public static function initFromResourceVar($image) + { + return new ImageWorkshopLayer($image); + } + + /** + * Initialize a layer from a string (obtains with file_get_contents, cURL...) + * + * This not recommanded to initialize JPEG string with this method, GD displays bugs ! + * + * @param string $imageString + * + * @return ImageWorkshopLayer + */ + public static function initFromString($imageString) + { + if (!$image = @imageCreateFromString($imageString)) { + throw new ImageWorkshopException('Can\'t generate an image from the given string.', static::ERROR_CREATE_IMAGE_FROM_STRING); + } + + return new ImageWorkshopLayer($image); + } } \ No newline at end of file diff --git a/config.inc.php b/config.inc.php index 0251c1a..b6284cc 100644 --- a/config.inc.php +++ b/config.inc.php @@ -1,8 +1,10 @@ -get('/photos/thumbnail/:imageID(/:createImgTag)', function ($imageID, $createImgTag = 0) use ($app) { - $mysqlconnetion = new MysqlClass; - - $retObj = $mysqlconnetion->queryToObject("select type_format, image_thumbnail from immagini where id=" . $imageID, false); - $mysqlconnetion->disconnetti(); - - if($createImgTag) - echo ''; - else - { - $app->contentType($retObj["type_format"]); - echo $retObj['image_thumbnail']; - } -}); - -$app->get('/photos/:imageID(/:createImgTag)', function ($imageID, $createImgTag = 0) use ($app) { - $mysqlconnetion = new MysqlClass; - - $retObj = $mysqlconnetion->queryToObject("select type_format, image from immagini where id=" . $imageID, false); - $mysqlconnetion->disconnetti(); - - if($createImgTag) - echo ''; -}); - -$app->put('/photos/publish/:imageID', function ($imageID) use ($app) { - $mysqlconnetion = new MysqlClass; - - $query = "update immagini set published = 1, published_date = NOW() where ProfiloID = " . $imageID; - $mysqlconnetion->disconnetti(); - $mysqlconnetion->insertRecord($query); - $mysqlconnetion->disconnetti(); -}); - -$app->post('/photos', function () use ($app) { - $idRicette = $app->request()->post('ricetta_id'); - $profileID = $app->request()->post('keyStore'); - $imageFileName = $_FILES['image']["tmp_name"]; - - $layer = ImageWorkshop::initFromPath($imageFileName); - $layer->resizeByLargestSideInPixel(640, true); - - $layer->save(dirname($imageFileName), basename($imageFileName)); - - $imgData = addslashes(file_get_contents($imageFileName)); - - $layer->resizeByLargestSideInPixel(300, true); - - $layer->save(dirname($imageFileName), basename($imageFileName)); - - $ThumbImageData = addslashes(file_get_contents($imageFileName)); - -// istanza della classe - $mysqlconnetion = new MysqlClass; -//$mysqlconneti on->connetti(); - $query = "insert into immagini(id_ricette, type_format, image_thumbnail, image, from_profile_id, uploaded_date) " . - "values(" . $idRicette . ", '" . image_type_to_mime_type($image->image_type) . - "', '" . $ThumbImageData . "', '" . $imgData . "', '" . $profileID . "', NOW())"; - $newID = $mysqlconnetion->insertRecord($query); - $mysqlconnetion->disconnetti(); - - echo $newID; -}); - -$app->put('/photos/:imageID', function ($imageID) use ($app) { - $imageFileName = $_FILES['image']["tmp_name"]; - - $layer = ImageWorkshop::initFromPath($imageFileName); - $layer->resizeByLargestSideInPixel(640, true); - - $layer->save(dirname($imageFileName), basename($imageFileName)); - - $imgData = addslashes(file_get_contents($imageFileName)); - - $layer->resizeByLargestSideInPixel(300, true); - - $layer->save(dirname($imageFileName), basename($imageFileName)); - - $ThumbImageData = addslashes(file_get_contents($imageFileName)); - -// istanza della classe - $mysqlconnetion = new MysqlClass; -//$mysqlconneti on->connetti(); - $query = "update immagini set (type_format = '" . image_type_to_mime_type($image->image_type) . "', " . - "image_thumbnail = '" . $ThumbImageData . "', " . - "image = '" . $imgData . "' where id=" . $imageID; - - $newID = $mysqlconnetion->insertRecord($query); - $mysqlconnetion->disconnetti(); - - return $newID; -}); +get('/photos/thumbnail/:imageID(/:createImgTag)', function ($imageID, $createImgTag = 0) use ($app, $dirRicetteDropBox) { + $mysqlconnetion = new MysqlClass; + + $retObj = $mysqlconnetion->queryToObject("select type_format, id_ricette from immagini where id=" . $imageID, false); + $mysqlconnetion->disconnetti(); + + $ext = ""; + if ($retObj["type_format"] == "image/jpeg") { + $ext = "jpg"; + } else if ($retObj["type_format"] == "image/png") { + $ext = "png"; + } + + $folder = $dirRicetteDropBox . "/" . $retObj["id_ricette"]; + + $imageFileName = $imageID . "_thumb_ricetta." . $ext; + + $dropBoxObj = new myDropBox(); + + if ($createImgTag) { + echo ''; + } +}); + +$app->get('/photos/:imageID(/:createImgTag)', function ($imageID, $createImgTag = 0) use ($app, $dirRicetteDropBox) { + $mysqlconnetion = new MysqlClass; + + $retObj = $mysqlconnetion->queryToObject("select type_format, id_ricette from immagini where id=" . $imageID, false); + $mysqlconnetion->disconnetti(); + $ext = ""; + if ($retObj["type_format"] == "image/jpeg") { + $ext = "jpg"; + } else if ($retObj["type_format"] == "image/png") { + $ext = "png"; + } + + $folder = $dirRicetteDropBox . "/" . $retObj["id_ricette"]; + + $imageFileName = $imageID . "_full_ricetta." . $ext; + + $dropBoxObj = new myDropBox(); + + if ($createImgTag) { + echo ''; + } +}); + +$app->put('/photos/publish/:imageID', function ($imageID) use ($app) { + $mysqlconnetion = new MysqlClass; + + $query = "update immagini set published = 1, published_date = NOW() where id = " . $imageID; + + $mysqlconnetion->insertRecord($query); + $mysqlconnetion->disconnetti(); +}); + +$app->post('/photos', function () use ($app, $dirRicetteDropBox) { + $idRicette = $app->request()->post('ricetta_id'); + $profileID = $app->request()->post('keyStore'); + $tmpFileName = $_FILES['image']["tmp_name"]; + $layer = ImageWorkshop::initFromPath($tmpFileName); + // istanza della classe + $mysqlconnetion = new MysqlClass; + //$mysqlconneti on->connetti(); + $query = "insert into immagini(id_ricette, type_format, from_profile_id, uploaded_date) " . + "values(" . $idRicette . ", '" . image_type_to_mime_type(exif_imagetype($tmpFileName)) . + "', '" . $profileID . "', NOW())"; + $newID = $mysqlconnetion->insertRecord($query); + $ext = image_type_to_extension(exif_imagetype($tmpFileName), FALSE); + + $imageFileName = $newID . "_full_ricetta." . $ext; + + $thumbFileName = $newID . "_thumb_ricetta." . $ext; + + $layer->resizeByLargestSideInPixel(640, true); + + $layer->save(dirname($tmpFileName), $imageFileName); + + $layer->resizeByLargestSideInPixel(300, true); + + $layer->save(dirname($tmpFileName), $thumbFileName); + + $dropBoxObj = new myDropBox(); + + $folder = $dirRicetteDropBox . "/" . $idRicette; + + try { + $dropBoxObj->CreateFolder($folder); + } catch (DropboxException $ex) { + + } + $fullPath = dirname($tmpFileName) . "/" . $imageFileName; + echo $fullPath . "\n"; + $thumbPath = dirname($tmpFileName) . "/" . $thumbFileName; + echo $thumbPath . "\n"; + $dropBoxObj->UploadFile($fullPath, $folder . "/" . $imageFileName); + + $dropBoxObj->UploadFile($thumbPath, $folder . "/" . $thumbFileName); + + $mysqlconnetion->disconnetti(); + + echo $newID; +}); + +$app->put('/photos/:imageID', function ($imageID) use ($app, $dirRicetteDropBox) { + $tmpFileName = $_FILES['image']["tmp_name"]; + $layer = ImageWorkshop::initFromPath($tmpFileName); +// istanza della classe + $mysqlconnetion = new MysqlClass; +//$mysqlconneti on->connetti(); + $query = "update immagini set (type_format = '" . image_type_to_mime_type(exif_imagetype($tmpFileName)) . "', " . + " where id=" . $imageID; + + $newID = $mysqlconnetion->insertRecord($query); + + $imageFileName = $imageID . "_full_ricetta"; + + $thumbFileName = $imageID . "_thumb_ricetta"; + + $layer->resizeByLargestSideInPixel(640, true); + + $layer->save(dirname($tmpFileName), $imageFileName); + + $layer->resizeByLargestSideInPixel(300, true); + + $layer->save(dirname($tmpFileName), $thumbFileName); + + $dropBoxObj = new myDropBox(); + + $folder = $dirRicetteDropBox . "/" . $idRicette; + + $dropBoxObj->UploadFile(dirname($tmpFileName) . DIRECTORY_SEPARATOR . $imageFileName, $folder . "\\" . $imageFileName); + + $dropBoxObj->UploadFile(dirname($tmpFileName) . DIRECTORY_SEPARATOR . $thumbFileName, $folder . "\\" . $thumbFileName); + + $mysqlconnetion->disconnetti(); + + return $newID; +}); diff --git a/include.php b/include.php index b400eb4..aae1e0e 100644 --- a/include.php +++ b/include.php @@ -14,7 +14,10 @@ $app = new \Slim\Slim(); $app->hook('slim.before.router', function () use ($app, $allowedHost) { $currentRefererRequest = $app->request()->getReferer(); - $currentRefererRequest = substr(substr($currentRefererRequest, 7), 0, strpos(substr($currentRefererRequest, 7), '/')); + $currentRefererRequest = substr($currentRefererRequest, 7); //Senza http:// + $indexDoublePoint = strpos($currentRefererRequest, ':'); + $indexFirstSlash = strpos($currentRefererRequest, '/'); + $currentRefererRequest = substr($currentRefererRequest, 0, $indexDoublePoint > 0 && $indexDoublePoint < $indexFirstSlash ? $indexDoublePoint : $indexFirstSlash ); if(!in_array($currentRefererRequest, $allowedHost)) { $app->halt(500, "Generic error occurred"); diff --git a/management.php b/management.php index e4165ae..81a0767 100644 --- a/management.php +++ b/management.php @@ -1,165 +1,165 @@ -get('/categories', function () use ($app) { - $callbackFn = $app->request()->get('callback'); - $mysqlconnetion = new MysqlClass; - //$mysqlconneti on->connetti(); - $retObj = $mysqlconnetion->queryToObject("select ID as category_id, NAME as name from categorie order by name"); - $mysqlconnetion->disconnetti(); - - returnJsonWithDecode($app, $callbackFn, $retObj); -}); - -$app->get('/typeingredients', function () use ($app) { - $callbackFn = $app->request()->get('callback'); - $mysqlconnetion = new MysqlClass; - //$mysqlconnetion->connetti(); - $retObj = $mysqlconnetion->queryToObject("select ID as tipo_ingredienti_id, name from tipo_ingredienti order by name"); - $mysqlconnetion->disconnetti(); - - returnJsonWithDecode($app, $callbackFn, $retObj); -}); - -$app->get('/typeqtys', function () use ($app) { - $callbackFn = $app->request()->get('callback'); - $mysqlconnetion = new MysqlClass; - //$mysqlconnetion->connetti(); - $retObj = $mysqlconnetion->queryToObject("select ID as tipo_quantita_id, name from tipo_quantita"); - $mysqlconnetion->disconnetti(); - - returnJsonWithDecode($app, $callbackFn, $retObj); -}); - -$app->get('/categoryitems/:catID', function ($categoryID) use ($app) { - $callbackFn = $app->request()->get('callback'); - $mysqlconnetion = new MysqlClass; - //$mysqlconnetion->connetti(); - $query = "select ID as ricetta_id, titolo, autore, valutazione, difficolta from ricette where ID_CATEGORIA = " . $categoryID . " order by titolo, autore"; - $retObj = $mysqlconnetion->queryToObject($query); - $mysqlconnetion->disconnetti(); - - returnJson($app, $callbackFn, $retObj); -}); - -$app->get('/ricetta/body/:itemID', function ($itemID) use ($app) { - $callbackFn = $app->request()->get('callback'); - // istanza della classe - $mysqlconnetion = new MysqlClass; - $query = "SELECT id_categoria, categorie.name AS categoria_name, ricette.ID AS ricetta_id, titolo, procedimento, autore, link_fonte, link_youtube, valutazione, difficolta FROM ricette INNER JOIN categorie ON categorie.ID = ricette.id_categoria WHERE ricette.ID = " . $itemID; - $retObj = $mysqlconnetion->queryToObject($query); - - $query2 = "select ingredienti.id_tipo_ingredienti, tipo_ingredienti.name as nome_ingrediente, quantita, ingredienti.id_tipo_quantita, tipo_quantita.Name as unita, note, posizione from ingredienti " . - "inner join tipo_ingredienti on ingredienti.ID_TIPO_INGREDIENTI = tipo_ingredienti.ID " . - "left outer join tipo_quantita on ingredienti.ID_TIPO_QUANTITA = tipo_quantita.ID " . - "where ingredienti.ID_RICETTE = " . $itemID . " order by ingredienti.posizione"; - - $retObj2 = $mysqlconnetion->queryToObject($query2); - - $retObj[0]["titolo"] = html_entity_decode($retObj[0]["titolo"],ENT_COMPAT | ENT_HTML401,'ISO-8859-1'); - $retObj[0]["procedimento"] = html_entity_decode($retObj[0]["procedimento"],ENT_COMPAT | ENT_HTML401,'ISO-8859-1'); - $retObj[0]["ingredienti"] = $retObj2; - - $mysqlconnetion->disconnetti(); - returnJson($app, $callbackFn, $retObj); -}); - -$app->post('/typeingredients', function () use ($app) { - $callbackFn = $app->request()->get('callback'); - $json_data_body = json_decode($app->request()->post('bodydata')); - $mysqlconnetion = new MysqlClass; - //$mysqlconnetion->connetti(); - $query = "insert into tipo_ingredienti(Name) values ('" . $json_data_body->name . "')"; - - $retNewID = $mysqlconnetion->insertRecord($query); - $mysqlconnetion->disconnetti(); - - returnJson($app, $callbackFn, $retNewID); -}); - -$app->post('/ricetta/body', function () use ($app) { - $callbackFn = $app->request()->get('callback'); - $json_data_body = json_decode($app->request()->post('bodydata')); - $retValue["result"] = true; - $retValue["message"] = ""; - $mysqlconnetion = new MysqlClass; - // istanza della classe - try { - $retNewID = 0; - if ($json_data_body->ricettaID != "") { - $query = "update ricette SET ID_CATEGORIA = " . $json_data_body->categoria_id . - ", titolo = '" . htmlentities($json_data_body->titolo, null, "UTF-8") . - "', procedimento = '" . str_replace("'", "''", htmlentities($json_data_body->preparazione, null, "UTF-8")) . - "', autore = '" . str_replace("'", "''", $json_data_body->autore) . - "', link_fonte = '" . $json_data_body->linkFonte . - "', Link_youtube = '" . $json_data_body->linkVideo . - "', Difficolta = '" . $json_data_body->difficolta . - "' where ID = " . $json_data_body->ricettaID; - - $mysqlconnetion->executeQuery($query); - $queryDelete = "DELETE FROM ingredienti where ID_RICETTE = " . $json_data_body->ricettaID; - $mysqlconnetion->executeQuery($queryDelete); - $retNewID = $json_data_body->ricettaID; - } else { - - $query = "insert into ricette(ID_CATEGORIA, titolo, procedimento, autore, link_fonte, Link_youtube,Difficolta) values (" . - $json_data_body->categoria_id . ",'" . htmlentities($json_data_body->titolo, null, "UTF-8") . "','" . str_replace("'", "''", htmlentities($json_data_body->preparazione, null, "UTF-8")) . - "','" . str_replace("'", "''", $json_data_body->autore) . "','" . - $json_data_body->linkFonte . "','" . $json_data_body->linkVideo . "', " . $json_data_body->difficolta . ")"; - - $retNewID = $mysqlconnetion->insertRecord($query); - } - - $pos = 0; - foreach ($json_data_body->ingredienti as $arr) { - $note = ""; - if ($arr->note != "") { - $note = str_replace("'", "''", htmlentities($arr->note)); - } - - $query = "insert into ingredienti(ID_TIPO_INGREDIENTI, ID_RICETTE, Quantita, ID_TIPO_QUANTITA, Note, Posizione) values (" . - $arr->ingrediente_id . "," . $retNewID . "," . ($arr->quantita == "" ? "0" : $arr->quantita) . "," . ($arr->tipo_quantita_id == "" ? "NULL" : $arr->tipo_quantita_id) . ",'" . $note . "'," . $pos . ")"; - - $mysqlconnetion->insertRecord($query); - $pos = $pos + 1; - } - - $retValue["message"] = "Ricetta inserita con successo"; - } catch (Exception $e) { - $retValue["message"] = $e->getMessage(); - } - - $mysqlconnetion->disconnetti(); - - returnJson($app, $callbackFn, $retValue); -}); - -$app->get('/photos/', function () use ($app) { - $callbackFn = $app->request()->get('callback'); - - $query = "SELECT * from ( SELECT id as ricetta_id, `titolo`,`autore`, ". - " (select COUNT(*) from immagini where immagini.id_ricette = `ricette`.id) as num_img,". - " (select COUNT(*) from immagini where immagini.id_ricette = `ricette`.id and immagini.published = 1) as num_img_pub". - " FROM `ricette`". - " ) as tmp". - " WHERE tmp.num_img> 0"; - - $mysqlconnetion = new MysqlClass; - //$mysqlconnetion->connetti(); - $retObj = $mysqlconnetion->queryToObject($query); - $mysqlconnetion->disconnetti(); - returnJson($app, $callbackFn, $retObj); -}); - -$app->get('/ricetta/:itemID/photos', function ($itemID) use ($app) { - $callbackFn = $app->request()->get('callback'); - - $query = "SELECT id as id_photo, type_format, from_profile_id, uploaded_date, profilo.Name as profile_name, published from immagini" . - " INNER JOIN profilo ON profilo.ProfiloID = immagini.from_profile_id". - " WHERE id_ricette = " . $itemID; - - $mysqlconnetion = new MysqlClass; - //$mysqlconnetion->connetti(); - $retObj = $mysqlconnetion->queryToObject($query); - $mysqlconnetion->disconnetti(); - returnJson($app, $callbackFn, $retObj); +get('/categories', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + //$mysqlconneti on->connetti(); + $retObj = $mysqlconnetion->queryToObject("select ID as category_id, NAME as name from categorie order by name"); + $mysqlconnetion->disconnetti(); + + returnJsonWithDecode($app, $callbackFn, $retObj); +}); + +$app->get('/typeingredients', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $retObj = $mysqlconnetion->queryToObject("select ID as tipo_ingredienti_id, name from tipo_ingredienti order by name"); + $mysqlconnetion->disconnetti(); + + returnJsonWithDecode($app, $callbackFn, $retObj); +}); + +$app->get('/typeqtys', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $retObj = $mysqlconnetion->queryToObject("select ID as tipo_quantita_id, name from tipo_quantita"); + $mysqlconnetion->disconnetti(); + + returnJsonWithDecode($app, $callbackFn, $retObj); +}); + +$app->get('/ricette/:catID', function ($categoryID) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $query = "select ID as ricetta_id, titolo, autore, valutazione, difficolta from ricette where ID_CATEGORIA = " . $categoryID . " order by titolo, autore"; + $retObj = $mysqlconnetion->queryToObject($query); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retObj); +}); + +$app->get('/ricetta/body/:itemID', function ($itemID) use ($app) { + $callbackFn = $app->request()->get('callback'); + // istanza della classe + $mysqlconnetion = new MysqlClass; + $query = "SELECT id_categoria, categorie.name AS categoria_name, ricette.ID AS ricetta_id, titolo, procedimento, autore, link_fonte, link_youtube, valutazione, difficolta FROM ricette INNER JOIN categorie ON categorie.ID = ricette.id_categoria WHERE ricette.ID = " . $itemID; + $retObj = $mysqlconnetion->queryToObject($query); + + $query2 = "select ingredienti.id_tipo_ingredienti, tipo_ingredienti.name as nome_ingrediente, quantita, ingredienti.id_tipo_quantita, tipo_quantita.Name as unita, note, posizione from ingredienti " . + "inner join tipo_ingredienti on ingredienti.ID_TIPO_INGREDIENTI = tipo_ingredienti.ID " . + "left outer join tipo_quantita on ingredienti.ID_TIPO_QUANTITA = tipo_quantita.ID " . + "where ingredienti.ID_RICETTE = " . $itemID . " order by ingredienti.posizione"; + + $retObj2 = $mysqlconnetion->queryToObject($query2); + + $retObj[0]["titolo"] = html_entity_decode($retObj[0]["titolo"],ENT_COMPAT | ENT_HTML401,'ISO-8859-1'); + $retObj[0]["procedimento"] = html_entity_decode($retObj[0]["procedimento"],ENT_COMPAT | ENT_HTML401,'ISO-8859-1'); + $retObj[0]["ingredienti"] = $retObj2; + + $mysqlconnetion->disconnetti(); + returnJson($app, $callbackFn, $retObj); +}); + +$app->post('/typeingredients', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $json_data_body = json_decode($app->request()->post('bodydata')); + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $query = "insert into tipo_ingredienti(Name) values ('" . $json_data_body->name . "')"; + + $retNewID = $mysqlconnetion->insertRecord($query); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retNewID); +}); + +$app->post('/ricetta/body', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $json_data_body = json_decode($app->request()->post('bodydata')); + $retValue["result"] = true; + $retValue["message"] = ""; + $mysqlconnetion = new MysqlClass; + // istanza della classe + try { + $retNewID = 0; + if ($json_data_body->ricettaID != "") { + $query = "update ricette SET ID_CATEGORIA = " . $json_data_body->categoria_id . + ", titolo = '" . htmlentities($json_data_body->titolo, null, "UTF-8") . + "', procedimento = '" . str_replace("'", "''", htmlentities($json_data_body->preparazione, null, "UTF-8")) . + "', autore = '" . str_replace("'", "''", $json_data_body->autore) . + "', link_fonte = '" . $json_data_body->linkFonte . + "', Link_youtube = '" . $json_data_body->linkVideo . + "', Difficolta = '" . $json_data_body->difficolta . + "' where ID = " . $json_data_body->ricettaID; + + $mysqlconnetion->executeQuery($query); + $queryDelete = "DELETE FROM ingredienti where ID_RICETTE = " . $json_data_body->ricettaID; + $mysqlconnetion->executeQuery($queryDelete); + $retNewID = $json_data_body->ricettaID; + } else { + + $query = "insert into ricette(ID_CATEGORIA, titolo, procedimento, autore, link_fonte, Link_youtube,Difficolta) values (" . + $json_data_body->categoria_id . ",'" . htmlentities($json_data_body->titolo, null, "UTF-8") . "','" . str_replace("'", "''", htmlentities($json_data_body->preparazione, null, "UTF-8")) . + "','" . str_replace("'", "''", $json_data_body->autore) . "','" . + $json_data_body->linkFonte . "','" . $json_data_body->linkVideo . "', " . $json_data_body->difficolta . ")"; + + $retNewID = $mysqlconnetion->insertRecord($query); + } + + $pos = 0; + foreach ($json_data_body->ingredienti as $arr) { + $note = ""; + if ($arr->note != "") { + $note = str_replace("'", "''", htmlentities($arr->note)); + } + + $query = "insert into ingredienti(ID_TIPO_INGREDIENTI, ID_RICETTE, Quantita, ID_TIPO_QUANTITA, Note, Posizione) values (" . + $arr->ingrediente_id . "," . $retNewID . "," . ($arr->quantita == "" ? "0" : $arr->quantita) . "," . ($arr->tipo_quantita_id == "" ? "NULL" : $arr->tipo_quantita_id) . ",'" . $note . "'," . $pos . ")"; + + $mysqlconnetion->insertRecord($query); + $pos = $pos + 1; + } + + $retValue["message"] = "Ricetta inserita con successo"; + } catch (Exception $e) { + $retValue["message"] = $e->getMessage(); + } + + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retValue); +}); + +$app->get('/photos/', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + + $query = "SELECT * from ( SELECT id as ricetta_id, `titolo`,`autore`, ". + " (select COUNT(*) from immagini where immagini.id_ricette = `ricette`.id) as num_img,". + " (select COUNT(*) from immagini where immagini.id_ricette = `ricette`.id and immagini.published = 1) as num_img_pub". + " FROM `ricette`". + " ) as tmp". + " WHERE tmp.num_img> 0"; + + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $retObj = $mysqlconnetion->queryToObject($query); + $mysqlconnetion->disconnetti(); + returnJson($app, $callbackFn, $retObj); +}); + +$app->get('/ricetta/:itemID/photos', function ($itemID) use ($app) { + $callbackFn = $app->request()->get('callback'); + + $query = "SELECT id as id_photo, type_format, from_profile_id, uploaded_date, profilo.Name as profile_name, published from immagini" . + " INNER JOIN profilo ON profilo.ProfiloID = immagini.from_profile_id". + " WHERE id_ricette = " . $itemID; + + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $retObj = $mysqlconnetion->queryToObject($query); + $mysqlconnetion->disconnetti(); + returnJson($app, $callbackFn, $retObj); }); \ No newline at end of file diff --git a/mdbTester.php b/mdbTester.php new file mode 100644 index 0000000..229296b --- /dev/null +++ b/mdbTester.php @@ -0,0 +1,53 @@ +GetLink($folder . "/" . $imageFileName); + +return; +*/ +$layer = ImageWorkshop::initFromPath($tmpFileName); + +echo $layer->getImage()->image_type; +return; + +$layer->resizeByLargestSideInPixel(640, true); + +$layer->save(dirname($tmpFileName), $imageFileName); + +$imgData = addslashes(file_get_contents($tmpFileName)); + +$layer->resizeByLargestSideInPixel(300, true); + +$layer->save(dirname($tmpFileName), $thumbFileName); + +try { + $dropBoxObj->CreateFolder($folder); +} catch (DropboxException $ex) { + +} + +$dropBoxObj->UploadFile(dirname($tmpFileName) . "/" . $imageFileName, $folder . "/" . $imageFileName); + +$dropBoxObj->UploadFile(dirname($tmpFileName) . "/" . $thumbFileName, $folder . "/" . $thumbFileName); \ No newline at end of file diff --git a/myDropBoxObj.php b/myDropBoxObj.php new file mode 100644 index 0000000..f120e43 --- /dev/null +++ b/myDropBoxObj.php @@ -0,0 +1,78 @@ +dropbox = new DropboxClient( + array( + 'app_key' => "ft0zodv89xx804e", + 'app_secret' => "ut43sn7m9wufy3s", + 'app_full_access' => true + ), 'it'); + $this->internalLoad(); + } + + protected function internalLoad() { + // first try to load existing access token + $access_token = $this->load_token("access"); + if (!empty($access_token)) { + $this->dropbox->SetAccessToken($access_token); + echo "loaded access token:"; + print_r($access_token); + } elseif (!empty($_GET['auth_callback'])) { // are we coming from dropbox's auth page? + // then load our previosly created request token + $request_token = $this->load_token($_GET['oauth_token']); + if (empty($request_token)) + die('Request token not found!'); + // get & store access token, the request token is not needed anymore + $access_token = $this->dropbox->GetAccessToken($request_token); + $this->store_token($access_token, "access"); + $this->delete_token($_GET['oauth_token']); + } + // checks if access token is required + if (!$this->dropbox->IsAuthorized()) { + // redirect user to dropbox auth page + $return_url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . "?auth_callback=1"; + $auth_url = $this->dropbox->BuildAuthorizeUrl($return_url); + $request_token = $this->dropbox->GetRequestToken(); + $this->store_token($request_token, $request_token['t']); + die("Authentication required. Click here."); + } + } + + public function UploadFile($fileToUpload, $dropBoxPath) { + $ret = $this->dropbox->UploadFile($fileToUpload, $dropBoxPath); + return true; + } + + public function GetLink($dropBoxPathFile) { + return $this->dropbox->GetLink($dropBoxPathFile, false, false); + } + + public function CreateFolder($dropBoxPath) { + $ret = $this->dropbox->CreateFolder($dropBoxPath); + return true; + } + + private function store_token($token, $name) { + if (!file_put_contents("tokens/$name.token", serialize($token))) + die('
Could not store token! Make sure that the directory `tokens` exists and is writable!'); + } + + private function load_token($name) { + if (!file_exists("tokens/$name.token")) + return null; + return @unserialize(@file_get_contents("tokens/$name.token")); + } + + private function delete_token($name) { + @unlink("tokens/$name.token"); + } + +} diff --git a/nbproject/private/config.properties b/nbproject/private/config.properties new file mode 100644 index 0000000..e69de29 diff --git a/nbproject/private/private.properties b/nbproject/private/private.properties new file mode 100644 index 0000000..49ccdf8 --- /dev/null +++ b/nbproject/private/private.properties @@ -0,0 +1,9 @@ +browser.id=Chrome.INTEGRATED +copy.src.files=false +copy.src.on.open=false +copy.src.target= +hostname=localhost +port=8888 +router=mdbTester.php +run.as=INTERNAL +url=http://localhost:8888/ diff --git a/nbproject/private/private.xml b/nbproject/private/private.xml new file mode 100644 index 0000000..284eeec --- /dev/null +++ b/nbproject/private/private.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/nbproject/project.properties b/nbproject/project.properties new file mode 100644 index 0000000..6df3cbb --- /dev/null +++ b/nbproject/project.properties @@ -0,0 +1,7 @@ +include.path=${php.global.include.path} +php.version=PHP_53 +source.encoding=UTF-8 +src.dir=. +tags.asp=false +tags.short=false +web.root=. diff --git a/nbproject/project.xml b/nbproject/project.xml new file mode 100644 index 0000000..aa3be94 --- /dev/null +++ b/nbproject/project.xml @@ -0,0 +1,9 @@ + + + org.netbeans.modules.php.project + + + Service + + + diff --git a/profile.php b/profile.php index 43b2044..b9e3369 100644 --- a/profile.php +++ b/profile.php @@ -1,111 +1,111 @@ -get('/profile/:keyStore/ricetta/:ricetta_id', function ($keyStore, $ricetta_id) use ($app) { - $callbackFn = $app->request()->get('callback'); - $mysqlconnetion = new MysqlClass; - $query = "select COUNT(*) as Exist FROM blocco_note where ricetta_id = " . $ricetta_id . " AND ProfiloID = '" . $keyStore . "'"; - $retObj = $mysqlconnetion->queryToObject($query); - $mysqlconnetion->disconnetti(); - - returnJson($app, $callbackFn, $retObj[0]["Exist"]); -}); - -$app->post('/profile/ricetta', function () use ($app) { - $callbackFn = $app->request()->get('callback'); - $json_data_body = json_decode($app->request()->post('dataPair')); - $mysqlconnetion = new MysqlClass; - $query = "insert into blocco_note(ricetta_id, ProfiloID) values (" . $json_data_body->ricetta_id . ", '" . $json_data_body->keyStore . "')"; - $retNewID = $mysqlconnetion->insertRecord($query); - $mysqlconnetion->disconnetti(); - - returnJson($app, $callbackFn, $retNewID); -}); - -$app->delete('/profile/:keyStore/ricetta/:ricetta_id', function ($keyStore, $ricetta_id) use ($app) { - //$callbackFn = $app->request()->params('callback'); - $mysqlconnetion = new MysqlClass; - $query = "delete from blocco_note where ricetta_id = " . $ricetta_id . " AND ProfiloID = '" . $keyStore . "'"; - - $retNewID = $mysqlconnetion->insertRecord($query); - $mysqlconnetion->disconnetti(); - - echo $retNewID; - //returnJson($app, $callbackFn, $retNewID); -}); - -$app->delete('/profile/:keyStore/ricette', function ($keyStore) use ($app) { - $callbackFn = $app->request()->get('callback'); - $mysqlconnetion = new MysqlClass; - $query = "delete from blocco_note where ProfiloID = '" . $keyStore . "'"; - - $retNewID = $mysqlconnetion->insertRecord($query); - $mysqlconnetion->disconnetti(); - - returnJson($app, $callbackFn, $retNewID); -}); - -$app->get('/profile/:keyStore/ricette', function ($keyStore) use ($app) { - $callbackFn = $app->request()->get('callback'); - $mysqlconnetion = new MysqlClass; - $query = "select ID as ricetta_id, titolo, autore, valutazione, difficolta from ricette" . - " INNER JOIN blocco_note ON blocco_note.ricetta_id = ricette.id" . - " where blocco_note.ProfiloID = '" . $keyStore . "' order by titolo, autore"; - $retObj = $mysqlconnetion->queryToObject($query); - $mysqlconnetion->disconnetti(); - - foreach ($retObj as $ele) { - $ele["titolo"] = html_entity_decode($ele["titolo"]); - } - - returnJson($app, $callbackFn, $retObj); -}); - -$app->get('/profile/:keyStore', function ($keyStore) use ($app) { - $callbackFn = $app->request()->get('callback'); - $mysqlconnetion = new MysqlClass; - $query = "select ProfiloID, TipoAccesso, RisultatiRicerca, TemaUI, Name, Gender, 0 as NumRicette from profilo" . - " where ProfiloID = '" . $keyStore . "'"; - $retObj = $mysqlconnetion->queryToObject($query); - - $query = "update profilo set PenultimoAccesso = UltimoAccesso, UltimoAccesso = NOW() where ProfiloID = '" . $keyStore . "'"; - $mysqlconnetion->insertRecord($query); - - $query = "SELECT COUNT( * ) as NumRicette FROM ricette WHERE data_creazione > ( SELECT PenultimoAccesso FROM profilo " . - "WHERE `ProfiloID` = '" . $keyStore . "' )"; - - $retObj2 = $mysqlconnetion->queryToObject($query); - - $retObj[0]["NumRicette"] = $retObj2[0]["NumRicette"]; - - returnJson($app, $callbackFn, $retObj); -}); - -$app->post('/profile', function () use ($app) { - $callbackFn = $app->request()->get('callback'); - $json_data_body = json_decode($app->request()->post('dataPair')); - $mysqlconnetion = new MysqlClass; - $query = "insert into profilo(ProfiloID, Name, Email, Gender, TipoAccesso, RisultatiRicerca, TemaUI, UltimoAccesso, CreatoIl) values ('" . $json_data_body->keyStore . "', '" . $json_data_body->name . "', '" . $json_data_body->email . "', '" . $json_data_body->gender . "', '" . $json_data_body->type . "', '" . $json_data_body->risRic . "', '" . $json_data_body->tema . "', NOW(), NOW())"; - - $retNewID = $mysqlconnetion->insertRecord($query); - $mysqlconnetion->disconnetti(); - - returnJson($app, $callbackFn, $retNewID); -}); - -$app->put('/profile', function () use ($app) { - $callbackFn = $app->request()->get('callback'); - $json_data_body = json_decode($app->request()->post('dataPair')); - $mysqlconnetion = new MysqlClass; - $query = "update profilo set RisultatiRicerca = '" . $json_data_body->risRic . "', TemaUI = '" . $json_data_body->tema . "' where ProfiloID = '" . $json_data_body->keyStore . "'"; - - $retNewID = $mysqlconnetion->insertRecord($query); - $mysqlconnetion->disconnetti(); - - returnJson($app, $callbackFn, $retNewID); -}); - -?> +get('/profile/:keyStore/ricetta/:ricetta_id', function ($keyStore, $ricetta_id) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + $query = "select COUNT(*) as Exist FROM blocco_note where ricetta_id = " . $ricetta_id . " AND ProfiloID = '" . $keyStore . "'"; + $retObj = $mysqlconnetion->queryToObject($query); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retObj[0]["Exist"]); +}); + +$app->post('/profile/ricetta', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $json_data_body = json_decode($app->request()->post('dataPair')); + $mysqlconnetion = new MysqlClass; + $query = "insert into blocco_note(ricetta_id, ProfiloID) values (" . $json_data_body->ricetta_id . ", '" . $json_data_body->keyStore . "')"; + $retNewID = $mysqlconnetion->insertRecord($query); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retNewID); +}); + +$app->delete('/profile/:keyStore/ricetta/:ricetta_id', function ($keyStore, $ricetta_id) use ($app) { + //$callbackFn = $app->request()->params('callback'); + $mysqlconnetion = new MysqlClass; + $query = "delete from blocco_note where ricetta_id = " . $ricetta_id . " AND ProfiloID = '" . $keyStore . "'"; + + $retNewID = $mysqlconnetion->insertRecord($query); + $mysqlconnetion->disconnetti(); + + echo $retNewID; + //returnJson($app, $callbackFn, $retNewID); +}); + +$app->delete('/profile/:keyStore/ricette', function ($keyStore) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + $query = "delete from blocco_note where ProfiloID = '" . $keyStore . "'"; + + $retNewID = $mysqlconnetion->insertRecord($query); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retNewID); +}); + +$app->get('/profile/:keyStore/ricette', function ($keyStore) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + $query = "select ID as ricetta_id, titolo, autore, valutazione, difficolta from ricette" . + " INNER JOIN blocco_note ON blocco_note.ricetta_id = ricette.id" . + " where blocco_note.ProfiloID = '" . $keyStore . "' order by titolo, autore"; + $retObj = $mysqlconnetion->queryToObject($query); + $mysqlconnetion->disconnetti(); + + foreach ($retObj as $ele) { + $ele["titolo"] = html_entity_decode($ele["titolo"]); + } + + returnJson($app, $callbackFn, $retObj); +}); + +$app->get('/profile/:keyStore', function ($keyStore) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + $query = "select ProfiloID, TipoAccesso, RisultatiRicerca, TemaUI, Name, Gender, 0 as NumRicette from profilo" . + " where ProfiloID = '" . $keyStore . "'"; + $retObj = $mysqlconnetion->queryToObject($query); + + $query = "update profilo set PenultimoAccesso = UltimoAccesso, UltimoAccesso = NOW() where ProfiloID = '" . $keyStore . "'"; + $mysqlconnetion->insertRecord($query); + + $query = "SELECT COUNT( * ) as NumRicette FROM ricette WHERE data_creazione > ( SELECT PenultimoAccesso FROM profilo " . + "WHERE `ProfiloID` = '" . $keyStore . "' )"; + + $retObj2 = $mysqlconnetion->queryToObject($query); + + $retObj[0]["NumRicette"] = $retObj2[0]["NumRicette"]; + + returnJson($app, $callbackFn, $retObj); +}); + +$app->post('/profile', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $json_data_body = json_decode($app->request()->post('dataPair')); + $mysqlconnetion = new MysqlClass; + $query = "insert into profilo(ProfiloID, Name, Email, Gender, TipoAccesso, RisultatiRicerca, TemaUI, UltimoAccesso, CreatoIl) values ('" . $json_data_body->keyStore . "', '" . $json_data_body->name . "', '" . $json_data_body->email . "', '" . $json_data_body->gender . "', '" . $json_data_body->type . "', '" . $json_data_body->risRic . "', '" . $json_data_body->tema . "', NOW(), NOW())"; + + $retNewID = $mysqlconnetion->insertRecord($query); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retNewID); +}); + +$app->put('/profile', function () use ($app) { + $callbackFn = $app->request()->get('callback'); + $json_data_body = json_decode($app->request()->post('dataPair')); + $mysqlconnetion = new MysqlClass; + $query = "update profilo set RisultatiRicerca = '" . $json_data_body->risRic . "', TemaUI = '" . $json_data_body->tema . "' where ProfiloID = '" . $json_data_body->keyStore . "'"; + + $retNewID = $mysqlconnetion->insertRecord($query); + $mysqlconnetion->disconnetti(); + + returnJson($app, $callbackFn, $retNewID); +}); + +?> diff --git a/ricette.php b/ricette.php index cd3d887..3d84941 100644 --- a/ricette.php +++ b/ricette.php @@ -33,7 +33,7 @@ $app->get('/typeqtys', function () use ($app) { returnJson($app, $callbackFn, $retObj); }); -$app->get('/categoryitems/:catID', function ($categoryID) use ($app) { +$app->get('/ricette/:catID', function ($categoryID) use ($app) { $callbackFn = $app->request()->get('callback'); $mysqlconnetion = new MysqlClass; //$mysqlconnetion->connetti(); @@ -48,7 +48,7 @@ $app->get('/categoryitems/:catID', function ($categoryID) use ($app) { returnJson($app, $callbackFn, $retObj); }); -$app->get('/categoryitems/:categoryID/mostvote(/:numItems)', function ($categoryID, $numItems = 10) use ($app) { +$app->get('/ricette/:categoryID/mostvote(/:numItems)', function ($categoryID, $numItems = 10) use ($app) { $callbackFn = $app->request()->get('callback'); $mysqlconnetion = new MysqlClass; //$mysqlconnetion->connetti(); @@ -63,7 +63,7 @@ $app->get('/categoryitems/:categoryID/mostvote(/:numItems)', function ($category returnJson($app, $callbackFn, $retObj); }); -$app->get('/categoryitems/:categoryID/lastinserted(/:numItems)', function ($categoryID, $numItems = 10) use ($app) { +$app->get('/ricette/:categoryID/lastinserted(/:numItems)', function ($categoryID, $numItems = 10) use ($app) { $callbackFn = $app->request()->get('callback'); $mysqlconnetion = new MysqlClass; //$mysqlconnetion->connetti(); @@ -78,7 +78,23 @@ $app->get('/categoryitems/:categoryID/lastinserted(/:numItems)', function ($cate returnJson($app, $callbackFn, $retObj); }); -$app->get('/categoryitems/search/:numItems(/:categoryId(/:difficolta(/:titolo)))', +$app->get('/ricette/lastinserted/:profileID', function ($profileID) use ($app) { + $callbackFn = $app->request()->get('callback'); + $mysqlconnetion = new MysqlClass; + //$mysqlconnetion->connetti(); + $query = "select ID as ricetta_id, titolo, autore FROM ricette WHERE data_creazione > ( SELECT PenultimoAccesso FROM profilo " . + "WHERE `ProfiloID` = '" . $profileID . "' ) order by Data_creazione desc, titolo, autore"; + $retObj = $mysqlconnetion->queryToObject($query); + $mysqlconnetion->disconnetti(); + + foreach ($retObj as $ele) { + $ele["titolo"] = html_entity_decode($ele["titolo"], ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'); + } + + returnJson($app, $callbackFn, $retObj); +}); + +$app->get('/ricette/search/:numItems(/:categoryId(/:difficolta(/:titolo)))', function ($numItems = 10, $categoryId = 0, $difficolta = 0, $titolo = "") use ($app) { $callbackFn = $app->request()->get('callback'); //$filterItem = json_decode($app->request()->post('post')); diff --git a/serviceapp.php b/serviceapp.php index 0857f4b..648eabb 100644 --- a/serviceapp.php +++ b/serviceapp.php @@ -1,16 +1,16 @@ -group('/api', function () use ($app) { - include "./ricette.php"; - include "./profile.php"; - include "./image.php"; -}); - -$app->group('/backend', function () use ($app) { - include "./management.php"; -}); -//include "./image.php"; - +group('/api', function () use ($app, $dirRicetteDropBox) { + include "./ricette.php"; + include "./profile.php"; + include "./image.php"; +}); + +$app->group('/backend', function () use ($app) { + include "./management.php"; +}); +//include "./image.php"; + $app->run(); \ No newline at end of file diff --git a/utility.php b/utility.php index 76caec5..dc959cd 100644 --- a/utility.php +++ b/utility.php @@ -1,78 +1,87 @@ -= '300000') { - return false; - } - - /* step through inArray */ - foreach ($inArray as $key => $val) { - if (is_array($val)) { - /* recurse on array elements */ - $newArray[$key] = utf8json($val); - } else { - /* encode string values */ - $newArray[$key] = utf8_encode($val); - } - } - /* return utf8 encoded array */ - return $newArray; - } - /* return utf8 encoded array */ - return $inArray; -} - -function returnJsonWithDecode($app, $callbackFn, $retObj) { - if ($callbackFn) { - $app->contentType('application/javascript; Charset=UTF-8'); - echo $callbackFn . "(" . html_entity_decode(json_encode(utf8json($retObj)), ENT_COMPAT | ENT_HTML401, 'ISO-8859-1') . ")"; - } else { - $app->contentType('application/x-json; Charset=UTF-8'); - echo html_entity_decode(json_encode(utf8json($retObj)), ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'); - } -} - -function returnJson($app, $callbackFn, $retObj) { - if ($callbackFn) { - $app->contentType('application/javascript; Charset=UTF-8'); - echo $callbackFn . "(" . (json_encode(utf8json($retObj))) . ")"; - } else { - $app->contentType('application/x-json; Charset=UTF-8'); - echo (json_encode(utf8json($retObj))); - } -} - -function makeThumbnail($im) { - $final_width_of_image = 300; - $ox = imagesx($im); - $oy = imagesy($im); - - $nx = $final_width_of_image; - $ny = floor($oy * ($final_width_of_image / $ox)); - - $nm = imagecreatetruecolor($nx, $ny); - - imagecopyresized($nm, $im, 0, 0, 0, 0, $nx, $ny, $ox, $oy); - - return $nm; -} - -function getContentFromResources($res) { - ob_start(); //Start output buffer. - imagejpeg($res); //This will normally output the image, but because of ob_start(), it won't. - $contents = ob_get_contents(); //Instead, output above is saved to $contents - ob_end_clean(); //End the output buffer. - - return $contents; -} - -?> += '300000') { + return false; + } + + /* step through inArray */ + foreach ($inArray as $key => $val) { + if (is_array($val)) { + /* recurse on array elements */ + $newArray[$key] = utf8json($val); + } else { + /* encode string values */ + $newArray[$key] = utf8_encode($val); + } + } + /* return utf8 encoded array */ + return $newArray; + } + /* return utf8 encoded array */ + return $inArray; +} + +function returnJsonWithDecode($app, $callbackFn, $retObj) { + if ($callbackFn) { + $app->contentType('application/javascript; Charset=UTF-8'); + echo $callbackFn . "(" . html_entity_decode(json_encode(utf8json($retObj)), ENT_COMPAT | ENT_HTML401, 'ISO-8859-1') . ")"; + } else { + $app->contentType('application/x-json; Charset=UTF-8'); + echo html_entity_decode(json_encode(utf8json($retObj)), ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'); + } +} + +function returnJson($app, $callbackFn, $retObj) { + if ($callbackFn) { + $app->contentType('application/javascript; Charset=UTF-8'); + echo $callbackFn . "(" . (json_encode(utf8json($retObj))) . ")"; + } else { + $app->contentType('application/x-json; Charset=UTF-8'); + echo (json_encode(utf8json($retObj))); + } +} + +function makeThumbnail($im) { + $final_width_of_image = 300; + $ox = imagesx($im); + $oy = imagesy($im); + + $nx = $final_width_of_image; + $ny = floor($oy * ($final_width_of_image / $ox)); + + $nm = imagecreatetruecolor($nx, $ny); + + imagecopyresized($nm, $im, 0, 0, 0, 0, $nx, $ny, $ox, $oy); + + return $nm; +} + +function getContentFromResources($res) { + ob_start(); //Start output buffer. + imagejpeg($res); //This will normally output the image, but because of ob_start(), it won't. + $contents = ob_get_contents(); //Instead, output above is saved to $contents + ob_end_clean(); //End the output buffer. + + return $contents; +} + +?>