Exemplo n.º 1
0
 /**
  * Crop user photo.
  *
  * @return null
  */
 public function actionCropLogo()
 {
     $this->requireAjaxRequest();
     $this->requireAdmin();
     try {
         $x1 = craft()->request->getRequiredPost('x1');
         $x2 = craft()->request->getRequiredPost('x2');
         $y1 = craft()->request->getRequiredPost('y1');
         $y2 = craft()->request->getRequiredPost('y2');
         $source = craft()->request->getRequiredPost('source');
         // Strip off any querystring info, if any.
         $source = UrlHelper::stripQueryString($source);
         $imagePath = craft()->path->getTempUploadsPath() . $source;
         if (IOHelper::fileExists($imagePath) && craft()->images->checkMemoryForImage($imagePath)) {
             $targetPath = craft()->path->getStoragePath() . 'logo/';
             IOHelper::ensureFolderExists($targetPath);
             IOHelper::clearFolder($targetPath);
             craft()->images->loadImage($imagePath, 300, 300)->crop($x1, $x2, $y1, $y2)->scaleToFit(300, 300, false)->saveAs($targetPath . $source);
             IOHelper::deleteFile($imagePath);
             $html = craft()->templates->render('settings/general/_logo');
             $this->returnJson(array('html' => $html));
         }
         IOHelper::deleteFile($imagePath);
     } catch (Exception $exception) {
         $this->returnErrorJson($exception->getMessage());
     }
     $this->returnErrorJson(Craft::t('Something went wrong when processing the logo.'));
 }
 /**
  * Adds remote image file as asset
  *
  * @param mixed $settings Array of settings
  * @param string $remoteImagePath url of remote image
  * @param string $baseUrl domain and uri path to Wordpress site
  * @param bool $returnArray Return array or int of Asset Id's
  *
  * @return bool / array File Ids
  */
 private function _addAsset($settings, $remoteImagePath, $baseUrl, $returnArray = true)
 {
     $assetIds = array();
     $tempFolder = craft()->path->getStoragePath() . 'instablog/';
     $remoteImagePath = $this->_getAbsoluteUrl($remoteImagePath, $baseUrl);
     $remoteImageParsed = parse_url($remoteImagePath);
     $imageFileName = IOHelper::getFileName($remoteImageParsed['path']);
     // Ensure folder exists
     IOHelper::ensureFolderExists($tempFolder);
     // Ensure target folder is writable
     try {
         $this->_checkUploadPermissions($settings->assetDestination);
     } catch (Exception $e) {
         Craft::log(var_export($e->getMessage(), true), LogLevel::Error, true, '_addAsset', 'InstaBlog');
         return false;
     }
     // Check to see if this is a WP resized image
     if (preg_match('|-([\\d]+)x([\\d]+)|i', $imageFileName, $resizeDimentions)) {
         // WP dimentions detected in filename. Attempt to get original size image.
         $assetIds['original'] = $this->_addAsset($settings, str_replace($resizeDimentions[0], '', $remoteImagePath), $baseUrl, false);
         $assetIds['originalSrc'] = str_replace($resizeDimentions[0], '', $remoteImagePath);
         // Check to see if this is a Wordpress.com resized image (example: filename.ext?w=XXX)
     } else {
         if (array_key_exists('query', $remoteImageParsed)) {
             parse_str($remoteImageParsed['query'], $params);
             if (array_key_exists('w', $params)) {
                 // WP dimentions detected in parameters. Attempt to import original size image.
                 $assetIds['original'] = $this->_addAsset($settings, UrlHelper::stripQueryString($remoteImagePath), $baseUrl, false);
                 $assetIds['originalSrc'] = UrlHelper::stripQueryString($remoteImagePath);
                 // Add width dimension to asset filename to differentiate from original size image.
                 $imageFileNameParts = explode('.', $imageFileName);
                 $imageFileNameParts[0] .= '-' . $params['w'];
                 $imageFileName = implode('.', $imageFileNameParts);
             }
         }
     }
     // Temp Local Image
     $tempLocalImage = $tempFolder . $imageFileName;
     $curlResponse = $this->_getRemoteFile($remoteImagePath, $tempLocalImage);
     if ($curlResponse && $this->_validateImage($remoteImagePath, $tempLocalImage)) {
         $response = craft()->assets->insertFileByLocalPath($tempLocalImage, $imageFileName, $settings->assetDestination, AssetConflictResolution::KeepBoth);
         $fileId = $response->getDataItem('fileId');
         $assetIds['asset'] = $fileId;
     } else {
         Craft::log('Unable to import ' . $remoteImagePath, LogLevel::Error, true, '_addAsset', 'InstaBlog');
         return false;
     }
     IOHelper::deleteFile($tempLocalImage, true);
     return $returnArray ? $assetIds : $assetIds['asset'];
 }
Exemplo n.º 3
0
 /**
  * Crop user photo.
  *
  * @return null
  */
 public function actionCropUserPhoto()
 {
     $this->requireAjaxRequest();
     craft()->userSession->requireLogin();
     $userId = craft()->request->getRequiredPost('userId');
     if ($userId != craft()->userSession->getUser()->id) {
         craft()->userSession->requirePermission('editUsers');
     }
     try {
         $x1 = craft()->request->getRequiredPost('x1');
         $x2 = craft()->request->getRequiredPost('x2');
         $y1 = craft()->request->getRequiredPost('y1');
         $y2 = craft()->request->getRequiredPost('y2');
         $source = craft()->request->getRequiredPost('source');
         // Strip off any querystring info, if any.
         $source = UrlHelper::stripQueryString($source);
         $user = craft()->users->getUserById($userId);
         $userName = AssetsHelper::cleanAssetName($user->username, false);
         // make sure that this is this user's file
         $imagePath = craft()->path->getTempUploadsPath() . 'userphotos/' . $userName . '/' . $source;
         if (IOHelper::fileExists($imagePath) && craft()->images->checkMemoryForImage($imagePath)) {
             craft()->users->deleteUserPhoto($user);
             $image = craft()->images->loadImage($imagePath);
             $image->crop($x1, $x2, $y1, $y2);
             if (craft()->users->saveUserPhoto(IOHelper::getFileName($imagePath), $image, $user)) {
                 IOHelper::clearFolder(craft()->path->getTempUploadsPath() . 'userphotos/' . $userName);
                 $html = craft()->templates->render('users/_userphoto', array('account' => $user));
                 $this->returnJson(array('html' => $html));
             }
         }
         IOHelper::clearFolder(craft()->path->getTempUploadsPath() . 'userphotos/' . $userName);
     } catch (Exception $exception) {
         $this->returnErrorJson($exception->getMessage());
     }
     $this->returnErrorJson(Craft::t('Something went wrong when processing the photo.'));
 }
Exemplo n.º 4
0
 /**
  * @return mixed
  */
 public function init()
 {
     /* -- Listen for exceptions */
     craft()->onException = function (\CExceptionEvent $event) {
         if ($event->exception instanceof \CHttpException && $event->exception->statusCode == 404) {
             if (craft()->request->isSiteRequest() && !craft()->request->isLivePreview()) {
                 /* -- See if we should redirect */
                 $url = urldecode(craft()->request->getRequestUri());
                 $noQueryUrl = UrlHelper::stripQueryString($url);
                 /* -- Redirect if we find a match, otherwise let Craft handle it */
                 $redirect = craft()->retour->findRedirectMatch($url);
                 if (isset($redirect)) {
                     craft()->retour->incrementStatistics($url, true);
                     $event->handled = true;
                     RetourPlugin::log("Redirecting " . $url . " to " . $redirect['redirectDestUrl'], LogLevel::Info, false);
                     craft()->request->redirect($redirect['redirectDestUrl'], true, $redirect['redirectHttpCode']);
                 } else {
                     /* -- Now try it without the query string, too, otherwise let Craft handle it */
                     $redirect = craft()->retour->findRedirectMatch($noQueryUrl);
                     if (isset($redirect)) {
                         craft()->retour->incrementStatistics($url, true);
                         $event->handled = true;
                         RetourPlugin::log("Redirecting " . $url . " to " . $redirect['redirectDestUrl'], LogLevel::Info, false);
                         craft()->request->redirect($redirect['redirectDestUrl'], true, $redirect['redirectHttpCode']);
                     } else {
                         craft()->retour->incrementStatistics($url, false);
                     }
                 }
             }
         }
     };
     /* -- Listen for structure changes so we can regenerated our FieldType's URLs */
     craft()->on('structures.onMoveElement', function (Event $e) {
         $element = $e->params['element'];
         $elemType = $element->getElementType();
         if ($element) {
             if ($elemType == ElementType::Entry) {
                 /* -- Check the field layout, so that we only do this for FieldLayouts that have our Retour fieldtype in them */
                 $fieldLayouts = $element->fieldLayout->getFields();
                 foreach ($fieldLayouts as $fieldLayout) {
                     $field = craft()->fields->getFieldById($fieldLayout->fieldId);
                     if ($field->type == "Retour") {
                         craft()->elements->saveElement($element);
                         RetourPlugin::log("Resaved moved structure element", LogLevel::Info, false);
                         break;
                     }
                 }
             }
         }
     });
     /* -- Listen for entries whose slug changes */
     craft()->on('entries.onBeforeSaveEntry', function (Event $e) {
         $this->originalUris = array();
         if (!$e->params['isNewEntry']) {
             $entry = $e->params['entry'];
             $thisSection = $entry->getSection();
             if ($thisSection->hasUrls) {
                 $this->originalUris = craft()->retour->getLocalizedUris($entry);
             }
         }
     });
     craft()->on('entries.onSaveEntry', function (Event $e) {
         if (!$e->params['isNewEntry']) {
             $entry = $e->params['entry'];
             $newUris = craft()->retour->getLocalizedUris($entry);
             foreach ($newUris as $newUri) {
                 $oldUri = current($this->originalUris);
                 next($this->originalUris);
                 if (strcmp($oldUri, $newUri) != 0 && $oldUri != "") {
                     $record = new Retour_StaticRedirectsRecord();
                     /* -- Set the record attributes for our new auto-redirect */
                     $record->locale = $entry->locale;
                     $record->redirectMatchType = 'exactmatch';
                     $record->redirectSrcUrl = $oldUri;
                     if ($record->redirectMatchType == "exactmatch" && $record->redirectSrcUrl != "") {
                         $record->redirectSrcUrl = '/' . ltrim($record->redirectSrcUrl, '/');
                     }
                     $record->redirectSrcUrlParsed = $record->redirectSrcUrl;
                     $record->redirectDestUrl = $newUri;
                     if ($record->redirectMatchType == "exactmatch" && $record->redirectDestUrl != "") {
                         $record->redirectDestUrl = '/' . ltrim($record->redirectDestUrl, '/');
                     }
                     $record->redirectHttpCode = '301';
                     $record->hitLastTime = DateTimeHelper::currentUTCDateTime();
                     $record->associatedElementId = 0;
                     $result = craft()->retour->saveStaticRedirect($record);
                 }
             }
         }
     });
 }