Convert url() call to string - stylus

I am trying to write transparent background-image mixin for retina images, however, I got stuck because Stylus treats url() as call and does not allow any string manipulation.
Base of the mixin:
background-image($file, $retina = false)
if $retina == "2x"
$path = pathjoin(dirname($file), basename($file, extname($file)) + '#2x' + extname($file))
background-image: unquote($path)
else
background-image: $file
Which means this works
.foo {
background-image: "url(img/man-with-tablet.jpg)" 2x;
}
but I would like to have clean CSS syntax:
.foo {
background-image: url(img/man-with-tablet.jpg) 2x;
}
which results into error TypeError: expected string, ident or literal, but got call:url(img / man-with-tablet . jpg)
Is there any way how to convert $file from url() call to string? Thanks!

You can coerce this call to string (by concatenating it with ''). But in this case, you need to wrap the arguments of url() call into quotes.
background-image($file, $retina = false)
if $retina == "2x"
$file = '' + $file
$path = pathjoin(dirname($file), basename($file, extname($file)) + '#2x' + extname($file))
background-image: unquote($path)
else
background-image: $file
.foo {
background-image: url('img/man-with-tablet.jpg') 2x;
}

Related

How to extract all URL's from webpage in an array an see if certain value is there

I am trying to extract all the links from a webpage and put them into an array that I can then compare values with to see if there is a match. The problem that I'm having is I cannot seem to get the values into an array. I am able to see all the links and I see that there is a match with the one I'm trying to compare with but it's not recognizing that it's there. My code is as follows. Any help would be greatly appreciated.
$content = file_get_contents("sample_url");
$content = strip_tags($content, "<a>");
$subString = preg_split("/<\/a>/", $content);
$items = array();
foreach ( $subString as $val ){
if( strpos($val, "<a href=") !== FALSE ) {
$val = preg_replace("/.*<a\s+href=\"/sm", "", $val);
$val = preg_replace("/\".*/", "", $val);
$items[] = $val;
var_dump($val . "<br />");
}
}
if (in_array($testing_link, $items, true)) {
echo 'It is here!';
}
else {
echo 'it is NOT here :( ';
}
Better to use the DOMDocument to get the links into an array. Like this:
$doc = new DOMDocument();
// the string containing all the URLs and stuff
$doc->loadHTML($content);
//Extract the links from the HTML. From https://thisinterestsme.com/php-find-links-in-html/
$links = $doc->getElementsByTagName('a');
//Array that will contain our extracted links.
$extracted_links = array();
//Loop through the DOMNodeList.
//We can do this because the DOMNodeList object is traversable.
foreach ($links as $link) {
//Get the link text.
//$linkText = $link->nodeValue;
//Get the link in the href attribute.
$linkHref = $link->getAttribute('href');
}
Now all the HREFS are in the $linkHref array.
Better to use DOMDocument rather than RegEx. Much easier, and more accurate and consistent in results.

Upload multiple pictures renaming files in Codeigniter 3

I'm not able to figure out what's wrong in my code.
In my project the user is allowed to upload multiple pictures for each aircraft registration number; I want to rename each uploaded files with the following rules: registration id, minus sign, progressive number; so if the user upload a new image file for the registration id xxx, the uploaded filename becomes xxx-1.jpg
The code to upload the multiple files is the following; it works fine so far...
// Count uploaded files
$countfiles = count($_FILES['files']['name']);
// Define new image name
$image = $id . '-1.jpg';
for($i=0;$i<$countfiles;$i++)
{
if(!empty($_FILES['files']['name'][$i]))
{
// Define new $_FILES array - $_FILES['file']
$_FILES['file']['name'] = $_FILES['files']['name'][$i];
$_FILES['file']['type'] = $_FILES['files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['files']['error'][$i];
$_FILES['file']['size'] = $_FILES['files']['size'][$i];
// Check if the image file exist and modify name in case
$filename = $this->_file_newname($uploaddir,$image);
// Set preference
$config['upload_path'] = $upload_path;
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = '5000';
$config['file_name'] = $filename;
//Load upload library
$this->load->library('upload',$config);
$arr = array('msg' => 'something went wrong', 'success' => false);
// File upload
if($this->upload->do_upload('file'))
{
$data = $this->upload->data();
}
}
}
The _file_newname() function does the file renaming jog, here you are the code:
private function _file_newname($path, $filename)
{
if ($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
} else {
$name = $filename;
}
$newpath = $path.$filename;
$newname = $filename;
if(file_exists($newpath)){
$counter = 1;
if($pos = strrpos($name, '-')) {
$oldcounter = substr($name, $pos + 1);
if(is_numeric($oldcounter)){
$counter = $oldcounter++;
$name = substr($name, 0, $pos);
}
}
$newname = $name . '-' . $counter . $ext;
$newpath = $path . $newname;
while (file_exists($newpath)) {
$newname = $name .'-'. $counter . $ext;
$newpath = $path.$newname;
$counter++;
}
}
return $newname;
}
Now...the issue....the renaming function works fine if the user upload one file each time...so the first upload set the file name xxx-1.jpg, the second upload set the filename to xxx-2.jpg and so on....but....if the user upload more then one file at time...the second file become xxx-1x.jpg.
If already exists one file on server ( for example xxx-1.jpg ) and the user upload two more files..they are renamed as xxx-2.jpg ( correct) and xxx-21.jpg (wrong...should be xxx-3.jpg).
Any hint or suggestion to fix the issue?
Thanks a lot
Your new file name is out of the loop for the uploaded photos.
So it becomes static.
Put that line inside the loop:
// Define new image name
$image = $id . '-' . $i . '.jpg';
This way you are gonna keep the $id and rename the files according to the iteration of the loop - $i.

Collapsable print_r() tree with PHP 7 (w/o preg_replace() and /e)

In order to print_r a collapsable tree, I'm currently using his code which uses preg_replace() and the /e modifier, which is depreciated in PHP7:
<?php
function print_r_tree($data)
{
// capture the output of print_r
$out = print_r($data, true);
// replace something like '[element] => <newline> (' with ...<div id="..." style="display: none;">
$out = preg_replace('/([ \t]*)(\[[^\]]+\][ \t]*\=\>[ \t]*[a-z0-9 \t_]+)\n[ \t]*\(/iUe',"'\\1\\2<div id=\"'.\$id.'\" style=\"display: none;\">'", $out);
// replace ')' on its own on a new line (surrounded by whitespace is ok) with '</div>
$out = preg_replace('/^\s*\)\s*$/m', '</div>', $out);
// print the javascript function toggleDisplay() and then the transformed output
echo '<script language="Javascript">function toggleDisplay(id) { document.getElementById(id).style.display = (document.getElementById(id).style.display == "block") ? "none" : "block"; }</script>'."\n$out";
}
?>
In order to fix it, I tried this solution Preg replace deprecated, attempting to fix
but it's not working. (Yes, I recognized the ';' is missing in the function there).
Since - due to lack of 'reputation' points - I can't comment there, I'm trying to get an answer here...
This is the unchanged proposed solution for 2nd $out in the link:
$out = preg_replace_callback('/([ \t]*)(\[[^\]]+\][ \t]*\=\>[ \t]*[a-z0-9 \t_]+)\n[ \t]*\(/iU', "callbackFunction", $out);
function callbackFunction($matches) {
return "'".$matches[1]."".$matches[2]."<div id=\"'.\$id.'\" style=\"display: none;\">'"
}
You need to concat the variable $id value, try this:
function callbackFunction($matches) {
$id = substr(md5(rand().$matches[0]), 0, 7);
return "$matches[1]$matches[2]<div id='$id' style=\"display: none;\">'";
}

Drupal 7 tokens and img tags

I am using Drupal 7, webform and webform2pdf modules to create an application form, that once filled out, will generate a PDF with all of the information from the applicant.
Problem that I am having is that the fields I set up for uploading a .jpg head shot and a .pdf of a short explanation are showing as links instead of just listing the content.
I am using tokens generated from the webform components to dynamically fill the content into the PDF.
for example [submission:value:recent_photo]
is there a special syntax I need to display the image instead of just the link?
Here's the solution i've found to solve the same problem (Drupal 7, Webform 4).
Type this function in MYADMINTHEME/template.php
function MYADMINTHEME_webform_display_file($variables) {
$element = $variables['element'];
$current_path = current_path();
$file = $element['#value'];
$filemime = !empty($file) ? $element['#value']->filemime : '';
if (substr_count($current_path, 'downloadpdf') && in_array($filemime, array('image/jpeg','image/gif','image/png'))){
if ($element['#format'] == 'text')
return !empty($file) ? webform_file_url($file->uri) : t('no upload');
$url = drupal_realpath($file->uri);
return '<img src="' . $url . '"/>';
} else {
$url = !empty($file) ? webform_file_url($file->uri) : t('no upload');
return !empty($file) ? ($element['#format'] == 'text' ? $url : l($file->filename, $url)) : ' ';
}
}

how to set the full base url to a cdn while using HtmlHelper in cakephp?

My cakephp app is running on 2.4.0
It is already running live on yourapp.com
I am attempting to use Amazon CloudFront to serve static assets like css, js, and images.
The CDN domain I chose was cdn.yourapp.com
Sadly, when I tried to use it this way:
echo $this->Html->css('alpha_landing/styles', array('fullBase' => $cdnBaseUrl));
where $cdnBaseUrl is http://cdn.yourapp.com/
I did not get back the correct url I was expecting.
I was expecting
http://cdn.yourapp.com/css/some.css
But I got back
http://yourapp.com/css/some.css
How can I overcome this problem?
Two solutions:
Simply write a HtmlHelper that can override the default image, css, etc functions
See https://stackoverflow.com/a/9601207/80353 for details
or
you can rewrite the assetUrl function in your AppHelper so that you need not rewrite all the related functions.
public function assetUrl($path, $options = array()) {
$cdnBaseUrl = Configure::read('App.assetsUrl');
$legitCDN = (strpos($cdnBaseUrl, '://') !== false);
if (is_array($path)) {
$path = $this->url($path, !empty($options['fullBase']));
if ($legitCDN) {
return rtrim($cdnBaseUrl, '/') . '/' . ltrim($path, '/');
}
return $path;
}
if (strpos($path, '://') !== false) {
return $path;
}
if (!array_key_exists('plugin', $options) || $options['plugin'] !== false) {
list($plugin, $path) = $this->_View->pluginSplit($path, false);
}
if (!empty($options['pathPrefix']) && $path[0] !== '/') {
$path = $options['pathPrefix'] . $path;
}
if (
!empty($options['ext']) &&
strpos($path, '?') === false &&
substr($path, -strlen($options['ext'])) !== $options['ext']
) {
$path .= $options['ext'];
}
if (isset($plugin)) {
$path = Inflector::underscore($plugin) . '/' . $path;
}
$path = $this->_encodeUrl($this->assetTimestamp($this->webroot($path)));
if ($legitCDN) {
$path = rtrim($cdnBaseUrl, '/') . '/' . ltrim($path, '/');
}
return $path;
}
This is the sample code for the assetUrl
props to #lorenzo at https://github.com/cakephp/cakephp/issues/2149 for this solution
P.S.: I have rewritten the above as a Plugin.
So you can simply have the AppHelper extend this CDNAppHelper instead.
https://github.com/simkimsia/UtilityHelpers
If you are looking for simplest stuff just update few parameters in end of your core.php file
Configure::write('App.imageBaseUrl', 'http://cdn.yourdomain.com/img/');
Configure::write('App.cssBaseUrl', 'http://cdn.yourdomain.com/css/');
Configure::write('App.jsBaseUrl', 'http://cdn.yourdomain.com/js/');
echo $this->Html->css('alpha_landing/styles', array(
'fullBase' => true,
'pathPrefix'=>$cdnBaseUrl.'css/'));
Try this one

Resources