How do I test an image's .RawFormat against a List<string> of extensions from Web.Config? - list

I want to put the allowed extensions for an image upload in the web.config for easy modification later. what I have here currently works but is hard-coded.
if (!img.RawFormat.Equals(ImageFormat.Png)
&& !img.RawFormat.Equals(ImageFormat.Gif)
&& !img.RawFormat.Equals(ImageFormat.Jpeg)
&& !img.RawFormat.Equals(ImageFormat.Bmp))
{
ViewBag.Message = "Wrong Image Type. Please use an image one with the following extenstions:<br /><b>.jpeg, .gif, .png, or .bmp</b>";
return View(location);
}
This is what I was trying, but I need to pass in an ImageFormat not a string... How do I accomplish this?
bool isAcceptedType = false;
List<string> AcceptedImageTypes = System.Configuration.ConfigurationManager.AppSettings["AcceptedImageTypes"].Split('|').ToList();
foreach (string s in AcceptedImageTypes)
{
if (img.RawFormat.Equals(s))
{
isAcceptedType = true;
}
}
if (!isAcceptedType)
{
ViewBag.Message = "Wrong Image Type. Please use an image one with the following extenstions:<br /><b>.jpeg, .gif, .png, or .bmp</b>";
return View(location);
}

I have found the answer here on this page..

Related

How can I compress the images before saving them in the directory? PHP

i'm recovering images from an xml file.
I save them correctly in the directory but I would like to compress them in order to reduce their weight.
How can I do?
I enclose the code
$uno = 1; //
if (!file_exists(__DIR__ .'/../web/media/imm/imm'.$idImmobile.'')) {
mkdir(__DIR__ .'/../web/media/imm/imm'.$idImmobile.'', 0777, true);
}
foreach ($empl->images->image as $images){
$urlimg{$num} = $images->url;enter code here
#$rawImage = file_get_contents($urlimg{$num});
if($rawImage){
file_put_contents(__DIR__ ."/../web/media/imm/imm".$idImmobile."/photo_".$uno++.".jpg",$rawImage);
echo 'Image Saved';
}
else
{
echo 'Error Occured';
}
}

Drupal 8 Webform add prefix to uploaded file names

I have a webform with a file upload field. I need do one of two things. Either upload files into a subfolder inside the private area, OR, add a prefix to the filename that the user is uploading. The user can upload several files. The webform editor allows you to 'Rename' the file and use tokens for this, but I don't see any way of preserving the original file name. I can hack getFileDestinationUri() in WebformManagedFileBase.php to do what I want, but obviously I would rather not do that. Am I missing something?
It turns out that you can use the drupal form alter hook to alter the destination. I had thought of this but felt if was unlikely to work. It does.
Below is MY code solution: (I may be missing container types)
function _mymodule_fix_elements(&$elements) {
foreach ($elements as $key => &$element) {
if (strpos($key, '#') !== 0) {
if (is_array($element)) {
if (isset($element['#type'])) {
if (($element['#type'] == 'fieldset') ||
($element['#type'] == 'webform_flexbox') ||
($element['#type'] == 'container')) {
_mymodule_fix_elements($element);
} else if ($element['#type'] == 'managed_file') {
$pattern = $element['#upload_location'];
if (strpos($pattern, 'private:') === 0) {
$element['#upload_location'] = $pattern . '/' . $key;
}
}
}
}
}
}
}
function mymodule_form_alter(&$form, &$form_state, $id) {
if (strpos($id, 'webform_') === 0) {
_mymodule_fix_elements($form['elements']);
}
}

Magento 2.3.3 dashboard keeps loading

I have installed latest version of magento in my localhost.
After login to admin panel dashboard keeps loading.
Here is the image-
Please help to solve this error.
First Go to magento root directory then :
vendor/magento/framework/view/element/tempalate/file/validator.php (dont exactly copy this url just follow this path)
open this file using any editor and change this line
$realPath = $this->fileDriver->getRealPath($path); //you can comment this out
with this one
$realPath = str_replace('\\','/',$this->fileDriver->getRealPath($path));
then goto to
app/etc/di.xml
and search for view_preprocessed
you will find a whole line like this :
Magento\Framework\App\View\Asset\MaterializationStrategy\Symlink
and change the Symlink with Copy
Magento 2.3
go to \lib\internal\Magento\Framework\View\Element\Template\File
go to the function isPathInDirectories and replace the function with following
protected function isPathInDirectories($path, $directories)
{
if (!is_array($directories)) {
$directories = (array)$directories;
}
//$realPath = $this->fileDriver->getRealPath($path);
$realPath = str_replace('\\','/',$this->fileDriver->getRealPath($path));
foreach ($directories as $directory) {
//$realDirectory = $this->fileDriver->getRealPath($directory);
$realDirectory = str_replace('\\','/',$this->fileDriver->getRealPath($directory));
if ($realDirectory && 0 === strpos($realPath, $realDirectory)) {
return true;
}
}
return false;
}
go to app/etc/di.xml then search for view_preprocessed
you will find a whole line like this :
Magento\Framework\App\View\Asset\MaterializationStrategy\Symlink and change to Magento\Framework\App\View\Asset\MaterializationStrategy\Copy
#1. go to vendor/magento/framework/View/Element/Template/File/Validator.php#
#2. go to the function isPathInDirectories and replace the function with following:#
protected function isPathInDirectories($path, $directories)
{
if (!is_array($directories)) {
$directories = (array)$directories;
}
//$realPath = $this->fileDriver->getRealPath($path);
$realPath = str_replace('\\','/',$this->fileDriver->getRealPath($path));
foreach ($directories as $directory) {
//$realDirectory = $this->fileDriver->getRealPath($directory);
$realDirectory = str_replace('\\','/',$this->fileDriver->getRealPath($directory));
if ($realDirectory && 0 === strpos($realPath, $realDirectory)) {
return true;
}
}
return false;
}
#3. go to app/etc/di.xml then search for view_preprocessed
you will find a whole line like this :
Magento\Framework\App\View\Asset\MaterializationStrategy\Symlink and change to
Magento\Framework\App\View\Asset\MaterializationStrategy\Copy #

Hide product description

How can I hide product description when the description is long in Opencart (product page) to reduce the load product page, but after clicking on the detail link then came out a full description.
In image you can see Example, Sorry for my bad english, Thanks!
Here is a link to example image example
Why not just truncate it? It will force it to be the right length for you every time!
Go to catalog/controller/product/category.php and when you see
foreach ($results as $result) {
if ($result['image']) {
$image = $this->model_tool_image->resize($result['image'], $this->config->get('config_image_product_width'), $this->config->get('config_image_product_height'));
} else {
$image = false;
}
Add this next:
function truncate($description, $tLimit="20", $break=" ", $pad="...")
{
if(strlen($string) <= $tlimit) return $string;
if(false !== ($breakpoint = strpos($string, $break, $tlimit))) {
if($breakpoint < strlen($string) - 1) {
$string = substr($string, 0, $breakpoint) . $pad;
}
}
return $description;
}
Feel free to change the variables:
$tLimit is how many letters you want to allow it.
$break is where you want it to cut off, right now it is set to cut off at the next space. You can have it interrupt words if you like by putting $break=""
$pad is what you want it to show after it cuts off the text.
If you really want no description to show at all Then I recommend still doing something similar to the original script.
function getDescriptionLength($description, $tLimit="20")
{
if(strlen($string) <= $tlimit) return $string;
else {
$description = NULL;
}
return $description;
}

How to get the large picture from feed with graph api?

When loading the Facebook feeds from one page, if a picture exist in the feed, I want to display the large picture.
How can I get with the graph API ? The picture link in the feed is not the large one.
Thanks.
The Graph API photo object has a picture connection (similar to that the user object has):
“The album-sized view of the photo. […] Returns: HTTP 302 redirect to the URL of the picture.”
So requesting https://graph.facebook.com/{object-id-from-feed}/picture will redirect you to the album-sized version of the photo immediately. (Usefull not only for displaying it in a browser, but also if f.e. you want to download the image to your server, using cURL with follow_redirect option set.)
Edit:
Beginning with API v2.3, the /picture edge for feed posts is deprecated.
However, as a field the picture can still be requested – but it will be a small one.
But full_picture is available as well.
So /{object-id-from-feed}?fields=picture,full_picture can be used to request those, or they can be requested directly with the rest of feed data, like this /page-id/feed?fields=picture,full_picture,… (additional fields, such as message etc., must be specified the same way.)
What worked for me :
getting the picture link from the feed and replacing "_s.jpg" with "_n.jpg"
OK, I found a better way. When you retrieve a feed with the graph API, any feed item with a type of photo will have a field called object_id, which is not there for plain status type items. Query the Graph API with that ID, e.g. https://graph.facebook.com/1234567890. Note that the object ID isn't an underscore-separated value like the main ID of that feed item is.
The result of the object_id query will be a new JSON dictionary, where you will have a source attribute containing a URL for an image that has so far been big enough for my needs.
There is additionally an images array that contains more image URLs for different sizes of the image, but the sizes there don't seem to be predictable, and don't all actually correspond to the physical dimensions of the image behind that URL.
I still wish there was a way to do this with a single Graph API call, but it doesn't look like there is one.
For high res image links from:
Link posts
Video posts
Photo posts
I use the following:
Note: The reason I give the _s -> _o hack precedence over the object_id/picture approach is because the object_id approach was not returning results for all images.
var picture = result.picture;
if (picture) {
if (result.type === 'photo') {
if (picture.indexOf('_s') !== -1) {
console.log('CONVERTING');
picture = picture.replace(/_s/, '_o');
} else if (result.object_id) {
picture = 'https://graph.facebook.com/' + result.object_id + '/picture?width=9999&height=9999';
}
} else {
var qps = result.picture.split('&');
for (var i = 0; i < qps.length; i++) {
var qp = qps[i];
var matches = qp.match(/(url=|src=)/gi);
if (matches && matches.length > 0) picture = decodeURIComponent(qp.split(matches[0])[1]);
}
}
}
This is a new method to get a big image. it was born after the previews method doesn't works
/**
* return a big url of facebook
* works onky for type PHOTO
* #param picture
* #param is a post type link
* #return url of image
*/
#Transactional
public String getBigImageByFacebookPicture(String pictrue,Boolean link){
if(link && pictrue.contains("url=http")){
String url = pictrue.substring(pictrue.indexOf("url=") + 4);
try {
url = java.net.URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
StringBuffer sb = new StringBuffer("Big image for Facebook link not found: ");
sb.append(link);
loggerTakePost.error(sb.toString());
return null;
}
return url;
}else{
try {
Document doc = Jsoup.connect(pictrue).get();
return doc.select("#fbPhotoImage").get(0).attr("src");
} catch (Exception e) {
StringBuffer sb = new StringBuffer("Big image for Facebook link not found: ");
sb.append(link);
loggerTakePost.error(sb.toString());
return null;
}
}
}
Enjoy your large image :)
Actually, you need two different solutions to fully fix this.
1] https://graph.facebook.com/{object_id}/picture
This solution works fine for images and videos posted to Facebook, but sadly, it returns small images in case the original image file was not uploaded to Facebook directly. (When posting a link to another site on your page for example).
2] The Facebook Graph API provides a way to get the full images in the feed itself for those external links. If you add 'full_picture' to the fields like in this example below when calling the API, you will be provided a link to the higher resolution version.
https://graph.facebook.com/your_facebook_id/posts?fields=id,link,full_picture,description,name&access_token=123456
Combining these two solutions I ended up filtering the input in PHP as follows:
if ( isset( $post['object_id'] ) ){
$image_url = 'https://graph.facebook.com/'.$post['object_id'].'/picture';
}else if ( isset( $post['full_picture'] ) ) {
$image_url = $post['full_picture'];
}else{
$image_url = '';
}
See: http://api-portal.anypoint.mulesoft.com/facebook/api/facebook-graph-api/docs/reference/pictures
Just put "?type=large" after the URL to get the big picture.
Thanks to #mattdlockyer for the JS solution. Here is a similar thing in PHP:
$posts = $facebook->api('/[page]/posts/', 'get');
foreach($posts['data'] as $post)
{
if(stristr(#$post['picture'], '_s.'))
{
$post['picture'] = str_replace('_s.', '_n.', #$post['picture']);
}
if(stristr(#$post['picture'], 'url='))
{
parse_str($post['picture'], $picturearr);
if($picturearr['url'])
$post['picture'] = $picturearr['url'];
}
//do more stuff with $post and $post['picture'] ...
}
After positive comment from #Lachezar Todorov I decided to post my current approach (including paging and using Json.NET ;):
try
{
FacebookClient fbClient = new FacebookClient(HttpContext.Current.Session[SessionFacebookAccessToken].ToString());
JObject posts = JObject.Parse(fbClient.Get(String.Format("/{0}/posts?fields=message,picture,link,attachments", FacebookPageId)).ToString());
JArray newsItems = (JArray)posts["data"];
List<NewsItem> result = new List<NewsItem>();
while (newsItems.Count > 0)
{
result.AddRange(GetItemsFromJsonData(newsItems));
if (result.Count > MaxNewsItems)
{
result.RemoveRange(MaxNewsItems, result.Count - MaxNewsItems);
break;
}
JToken paging = posts["paging"];
if (paging != null)
{
if (paging["next"] != null)
{
posts = JObject.Parse(fbClient.Get(paging.Value<String>("next")).ToString());
newsItems = (JArray)posts["data"];
}
}
}
return result;
}
And the helper method to retieve individual items:
private static IEnumerable<NewsItem> GetItemsFromJsonData(IEnumerable<JToken> items)
{
List<NewsItem> newsItems = new List<NewsItem>();
foreach (JToken item in items.Where(item => item["message"] != null))
{
NewsItem ni = new NewsItem
{
Message = item.Value<String>("message"),
DateTimeCreation = item.Value<DateTime?>("created_time"),
Link = item.Value<String>("link"),
Thumbnail = item.Value<String>("picture"),
// http://stackoverflow.com/questions/28319242/simplify-looking-up-nested-json-values-with-json-net/28359155#28359155
Image = (String)item.SelectToken("attachments.data[0].media.image.src") ?? (String)item.SelectToken("attachments.data[0].subattachments.data[0].media.image.src")
};
newsItems.Add(ni);
}
return newsItems;
}
NewsItem class I use:
public class NewsItem
{
public String Message { get; set; }
public DateTime? DateTimeCreation { get; set; }
public String Link { get; set; }
public String Thumbnail { get; set; }
public String Image { get; set; }
}