Yii2Assets/yii2-pdfjs doesn't work with enablePrettyUrl enabled - yii2

I have installed Yii2Assets/yii2-pdfjs, it was working fine until I have enabled enablePrettyUrl in the urlManager.
I have found the problem:
In the file
yii2-pdfjs/views/viewer.php
If I replace the default url
$url = Url::to(['/pdfjs/','file'=>Url::to($urlFile)]);
by
$url = Url::to('/pdfjs/?file='.$urlFile);
It works
$urlFile="/link_to_my_pdf.pdf"
the $url generated is: mydomain.com/pdfjs/?file=/link_to_my_pdf.pdf
So my question is: is there a solution to add a trailing / in Url::to or is there another solution?

Related

How to use MySQL Data within Tag?

I am facing a problem with a WordPress website. I have a table named wp0o_terms I am fetching data via
global $wpdb;
$result = $wpdb->get_results ( "SELECT * FROM wp0o_terms" );
foreach ( $result as $print );
Printing as- echo $print->name;, where name is a field containing URL ( https://example.com ).
Actually, I want the URL within a a tag like href="$print->name;"
Everything is okay, but the link https://example.com is loading with currentpageurl/https://example.com.
I want only https://example.com which is in my table field.
Thank you
I believe I just got help on a similar question and the answer to yours would be to use something like
echo '<h3><a href ='. $print['URL'].'>'.$print['Name'].'</a></h3>';
Though I will say, you need to be sure you are storing the URL on a different column in MySQL or whatever database you are using. I have a column called CourseName but in order to get to that columns URL I am using CourseURL

Error when rendering .tpl file from SQL query

I'm trying to get a result from a MySQL database and display selected values into a .tpl template file.
This is what I tried so far:
{php}
$clienthosting = $this->get_template_vars(service);//Here is where the exception is thrown
$dbid = $clienthosting['id'];
$query = mysql_query("SELECT dedicatedip FROM tblhosting WHERE id = $dbid");
$result = mysql_fetch_array($query);
$dedicatedip = $result["dedicatedip"];
$this->assign("dedicatedip", $dedicatedip);
{/php}
But it generated the following error:
Something went wrong and we couldn't process your request.
What am I doing wrong?
Thanks.
WHMCS recommends not use {php} inside tpl files, you can use hooks instead to add variables and use them in the TPL file.
But you can enable it in the settings: Setup > General Settings > Security > Allow Smarty PHP Tags.
Also, if you're running PHP 7 the mysql extension is removed, you can't use functions like mysql_query and mysql_fetch_array.
You should use Capsule and Eloquent as recommended at Interacting with the Database page

Connecting to a MySQL database using DBI

I am trying to connect to a MySQL database.
I found this script and I am trying to use it on my PC and web host, but it doesn't show any output.
Please have a look at this code. I am running perl at xampp.
#!C:\xampp\perl\bin\perl.exe
print "Content-type: text/html\n\n";
use DBI;
use strict;
my $driver = "localhost";
my $database = "data";
my $dsn = "DBI:$driver:database = $database";
my $userid = "root";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr;
I am using the same database with PHP.
but it doesn't show any output.
Judging by the CGI header you're displaying, I assume that you're running this as a CGI program. In which case, it's no surprised that you're not seeing any output - you're not sending any output.
If you ran it as a command line program (and it's often a good idea to get stuff working on the command line before leaping into CGI programming), then you would see the "Content-Type" header. Alternatively, you could add some output to your program and see if that appears in your browser. Something simple like:
print 'It works!';
I'd also like to add, that CGI looks rather outdated these days and there are far better (by which I mean easier and more powerful) ways to write web applications with Perl. You might like to read CGI::Alternatives to get an idea of what is available.
Update:
I've just seen this question asked on Facebook (please don't cross-post without telling people) and I've noticed that your $driver variable is wrong. If you're connecting to MySQL, then $driver should be "mysql" (so that DBI loads "DBD::mysql").
A DSN for the MySQL driver looks like this
DBI:mysql:database=$database;host=$hostname;port=$port
where the host and port fields are optional. (The database is also optional, but you don't want to leave that out.) There are several more esoteric options too, but they're irrelevant here
But you're supplying
DBI:localhost:database = data
Which doesn't even specify a MySQL connection, so I'm not surprised if it doesn't work! I don't know whether the spaces are legal, but I would leave them out to keep in line with the documentation.
You should change that statement to
my $dsn = "DBI:mysql:database=$database;host=$driver"
You may remove ;host=$driver if you wish (why have you called the host name "driver"?) as localhost is the default. A DSN that specifies just a database name and uses the default for all the other fields may be contracted to just
my $dsn = "DBI:mysql:$database"
It may be easier to just write print statements at first to generate some output. You will want to print a MIME content type header of text/plain instead of text/html. Try print "$DBI::errstr\n" for now instead of die, as the latter writes to stderr which won't appear in your browser
you could add:
if ($dbh) {
print 'connect ok';
} else {
print 'connect failed';
}

Override WP_SITEURL and WP_HOME for WordPress Multisite

For doing local development on a WordPress site (http://www.example.com), I was previously overriding the WP_SITEURL and WP_HOME values in wp-config.php like so:
define('WP_SITEURL', 'http://local-example/');
define('WP_HOME', 'http://local-example/');
This would allow me to copy the database and site files to a local server, and make modifications as necessary, testing on the local install.
It was then necessary to convert the install to a WordPress Multisite so that users, authentication, plugins, etc. could be shared between the main site and a secondary site, hosted on a subdomain (http://second.example.com).
The method above to override the values in the wp_options table no longer works, but I am unsure the proper way to set a value for the entries in wp_blogs as well as the wp_2_options table for the primary and subdomain.
Updating my HOSTS file is somewhat of a workaround, but it not ideal (I am not able to compare to the live site, etc). Running a script to change the database values is another option I have tried, but is slightly more cumbersome, so my questions is whether or not there is an option in MultiSite to override these values in a settings file, such as wp-config.php, and if so what it would look like.
Update: full updated plugin code with additional description can be found here: http://justinsilver.com/technology/wordpress/wordpress-plugins/wordpress-plugin-wp-server-migration/
I was able to come up with a solution with the help of #user916011. I needed to be able to copy the wp_options table(s) to my development environment as they contain configurations that are needed. To overcome the issue of not being able to set the WP_SITEURL and WP_HOME values in MultiSite, I wrote a custom filter to replace the _config_wp_siteurl() and _config_wp_home() functions that are available for non-multisite installs that is included in a plugin that is available network-wide and is configured in wp-config.php. I am then able to copy all of the database tables except wp_site and wp_blogs to a local database.
I highly recommend the URL Token Replacement Techniques for WordPress 3.0 article by Chris Murphy to help handle URLs in your content.
This example assumes a subdomain multisite install, with a domain of example.com and two subdomains, www.example.com and second.example.com. The local development URLs will be www.example.local and second.example.local respectively.
Database Changes:
Update the domain value in wp_site:
UPDATE wp_site SET domain = 'example.local' WHERE domain = 'example.com';
Update the domain value(s) in wp_blogs:
UPDATE wp_blogs SET domain = 'www.example.local' WHERE domain = 'www.example.com';
UPDATE wp_blogs SET domain = 'second.example.local' WHERE domain = 'second.example.com';
Plugin Code:
The following plugin should be installed network-wide.
<?php
/*
Plugin Name: MultiSite WP_HOME and WP_SITEURL
Plugin URI: http://doublesharp.com/
Description: Allows wp_options values to be overwritten in wp-config.php for MultiSite
Author: Justin Silver
Version: 1.0
Author URI: http://doublesharp.com
License: GPL2
*/
function _ms_config_wp_siteurl( $url = '' ) {
if (is_multisite()):
global $blog_id, $current_site;
$cur_blog_id = defined('BLOG_ID_CURRENT_SITE')? BLOG_ID_CURRENT_SITE : 1;
$key = ($blog_id!=$cur_blog_id)? $blog_id.'_' : '';
$constant = 'WP_'.$key.'SITEURL';
if ( defined( $constant ) )
return untrailingslashit( constant($constant) );
endif;
return $url;
}
add_filter( 'option_siteurl', '_ms_config_wp_siteurl' );
function _ms_config_wp_home( $url = '' ) {
if (is_multisite()):
global $blog_id;
$cur_blog_id = defined('BLOG_ID_CURRENT_SITE')? BLOG_ID_CURRENT_SITE : 1;
$key = ($blog_id!=$cur_blog_id)? $blog_id.'_' : '';
$constant = 'WP_'.$key.'HOME';
if ( defined( $constant ) )
return untrailingslashit( constant($constant) );
endif;
return $url;
}
add_filter( 'option_home', '_ms_config_wp_home' );
?>
Configure wp-config.php:
Add new constants to wp-config.php. The primary site should use the standard WP_HOME and WP_SITEURL and the tertiary URLs should use WP_{$blog_id}_HOME and WP_{$blog_id}_SITEURL
define('WP_HOME', 'http://www.example.local');
define('WP_SITEURL', 'http://www.example.local');
define('WP_2_HOME', 'http://secondary.example.local');
define('WP_2_SITEURL', 'http://secondary.example.local');
You could use the update_option in functions.php
update_option("siteurl","http://example.com");
update_option("home","http://example.com");
There's a similar question being asked here: Team Development of a Wordpress Site which I provided a possible solution for. In your case, you may not want to go to that extent (though it would be very flexible); however, you could always look at the portion of the answer that mentions a domain-replacement technique.
I've outlined that solution here: URL Token Replacement Techniques...
I had the same issue and wanted a solution as similar to defining WP_HOME & WP_SITEURL in wp-config.php as possible.
I can't use a plugin, because I am syncing with GIT and don't want to have that plugin in my repo and I would have to add the plugin everytime... I suppose it could be activated network wide through the wp_sitemeta table... but it wasn't ideal for me.
I came up with this solution.
Be sure to not sync wp_blogs, wp_site, wp_sitemeta. And then add this code to your local wp-config.php somewhere below $table_prefix:
/* Update local database */
mysql_connect( DB_HOST, DB_USER, DB_PASSWORD ) or die( mysql_error() );
mysql_select_db( DB_NAME );
$result = mysql_query("SELECT * FROM `". $table_prefix ."blogs`") or die( mysql_error() );
while( $row = mysql_fetch_array( $result ) )
{
$id = (1 == $row['blog_id']) ? '' : $row['blog_id'] .'_';
mysql_query( "UPDATE `". $table_prefix . $id ."options` SET `option_value`='http://". $row['domain'] ."/' WHERE (`option_name`='siteurl' OR `option_name`='home')" ) or die( mysql_error() );
}
This will make sure your sites are synced up to your local wp_blogs table.
The only drawback is that when you add a new site, you do manually need to copy it into your wp_blogs table and update its local url.
This question is too old to answer, but recently I faced a similar situation where I have to migrate my wp site from staging to production and it was painful as it is having 5 subsite.
After scratching my head for all day, I found a simple and useful solution.
Of course one have to make changes in wp-config.php.
Other then that you have to follow below steps.
Generate database dump using following command.
mysqldump -u [user name] –p [password] [options] [database_name] [tablename] > [FileName]
After that open that file in any editor.
Find and replace your old domain with new domain.
Now restore the database with dump you created.
mysql -u [user name] -p [password] [database name] < [file anme]

Pairing content on an external website with entries in an mySQL database

tl;dr: I'm looking for a way to find entries in our database which are missing information, getting that information from a website and adding it to the database entry.
We have a media management program which uses a mySQL table to store the information. When employees download media (video files, images, audio files) and import it into the media manager they are suppose to also copy the description of the media (from the source website) and add it to the description in the Media Manager. However this has not been done for thousands of files.
The file name (eg. file123.mov) is unique and the details page for that file can be accessed by going to a URL on the source website:
website.com/content/file123
The information we want to scrape from that page has an element ID which is always the same.
In my mind the process would be:
Connect to database and Load table
Filter: "format" is "Still Image (JPEG)"
Filter: "description" is "NULL"
Get first result
Get "FILENAME" without extension)
Load the URL: website.com/content/FILENAME
Copy contents of the element "description" (on website)
Paste contents into the "description" (SQL entry)
Get 2nd result
Rinse and repeat until last result is reached
My question(s) are:
Is there software that could perform such a task or is this something that would need to be scripted?
If scripted, what would be the best type of script (eg could I achieve this using AppleScript or would it need to be made in java or php etc.)
Is there software that could perform such a task or is this something that would need to be scripted?
I'm not aware of anything that will do what you want out of the box (and even if there was, the configuration required won't be much less work than the scripting involved in rolling your own solution).
If scripted, what would be the best type of script (eg could I achieve this using AppleScript or would it need to be made in java or php etc.)
AppleScript can't connect to databases, so you will definitely need to throw something else into the mix. If the choice is between Java and PHP (and you're equally familiar with both), I'd definitely recommend PHP for this purpose, as there will be considerably less code involved.
Your PHP script would look something like this:
$BASEURL = 'http://website.com/content/';
// connect to the database
$dbh = new PDO($DSN, $USERNAME, $PASSWORD);
// query for files without descriptions
$qry = $dbh->query("
SELECT FILENAME FROM mytable
WHERE format = 'Still Image (JPEG)' AND description IS NULL
");
// prepare an update statement
$update = $dbh->prepare('
UPDATE mytable SET description = :d WHERE FILENAME = :f
');
$update->bindParam(':d', $DESCRIPTION);
$update->bindParam(':f', $FILENAME);
// loop over the files
while ($FILENAME = $qry->fetchColumn()) {
// construct URL
$i = strrpos($FILENAME, '.');
$url = $BASEURL . (($i === false) ? $FILENAME : substr($FILENAME, 0, $i));
// fetch the document
$doc = new DOMDocument();
$doc->loadHTMLFile($url);
// get the description
$DESCRIPTION = $doc->getElementsById('description')->nodeValue;
// update the database
$update->execute();
}
I too am not aware of any existing software packages that will do everything you're looking for. However, Python can connect to your database, make web requests easily, and handle dirty html. Assuming you already have Python installed, you'll need three packages:
MySQLdb for connecting to the database.
Requests for easily making http web requests.
BeautifulSoup for robust parsing of html.
You can install these packages with pip commands or Windows installers. Appropriate instructions are on each site. The whole process won't take more than 10 minutes.
import MySQLdb as db
import os.path
import requests
from bs4 import BeautifulSoup
# Connect to the database. Fill in these fields as necessary.
con = db.connect(host='hostname', user='username', passwd='password',
db='dbname')
# Create and execute our SELECT sql statement.
select = con.cursor()
select.execute('SELECT filename FROM table_name \
WHERE format = ? AND description = NULL',
('Still Image (JPEG)',))
while True:
# Fetch a row from the result of the SELECT statement.
row = select.fetchone()
if row is None: break
# Use Python's built-in os.path.splitext to split the extension
# and get the url_name.
filename = row[0]
url_name = os.path.splitext(filename)[0]
url = 'http://www.website.com/content/' + url_name
# Make the web request. You may want to rate-limit your requests
# so that the website doesn't get angry. You can slow down the
# rate by inserting a pause with:
#
# import time # You can put this at the top with other imports
# time.sleep(1) # This will wait 1 second.
response = requests.get(url)
if response.status_code != 200:
# Don't worry about skipped urls. Just re-run this script
# on spurious or network-related errors.
print 'Error accessing:', url, 'SKIPPING'
continue
# Parse the result. BeautifulSoup does a great job handling
# mal-formed input.
soup = BeautifulSoup(response.content)
description = soup.find('div', {'id': 'description'}).contents
# And finally, update the database with another query.
update = db.cursor()
update.execute('UPDATE table_name SET description = ? \
WHERE filename = ?',
(description, filename))
I'll warn that I've made a good effort to make that code "look right" but I haven't actually tested it. You'll need to fill in the private details.
PHP is a good scraper . I have made a class that wraps the cURL port of PHP here:
http://semlabs.co.uk/journal/object-oriented-curl-class-with-multi-threading
You'll probably need to use some of the options:
http://www.php.net/manual/en/function.curl-setopt.php
To scrape HTML, I usually use regular expressions, but here is a class I made that should be able to query HTML without issues:
http://pastebin.com/Jm9jKjAU
Useage is:
$h = new HTMLQuery();
$h->load( $string_containing_html );
$h->getElements( 'p', 'id' ); // Returns all p tags with an id attribute
The best option to scrape would be XPath, but it can't handle dirty HTML. You can use that to do things like:
//div[#class = 'itm']/p[last() and text() = 'Hello World'] <- selects the last p in div elements that have the innerHTML 'Hello World'
You can use that in PHP with the DOM class (built-in).