YouTube videos don’t play - object

Thank you!!!! But this did no help… Listen I am new to this ant I don’t know any think about PHP I have Buy a this script and I ask for help from the developers but they don’t answer to me. I have a file with is named (Youtube.class.php) I believe this is where is my problem. My website is (madolino.com) and I send you the (Youtube.class.php) below it maybe help you for help me if you want and if you get the time…..
<?php
# YouTube PHP class
# used for embedding videos as well as video screenies on web page without single line of HTML code
#
# Dedicated to my beloved brother FILIP. Rest in peace!
#
# by Avram, www.avramovic.info
class Youtube
{
private $id = NULL;
/**
* Set YouTube ID explicitly
*
* This method sets YouTube ID explicitly. It checks if the ID is in good format. If yes it will set it
* and return true, and if not - it will return false
*
* #access public
* #param string $id YouTube ID
* #return boolean Whether the ID has been set successfully
*/
public function setID($id)
{
if (preg_match('/([A-Za-z0-9_-]+)/', $url, $matches)) {
$this->id = $id;
return true;
} else
return false;
}
/**
* Get string representation of YouTube ID
*
* This method returns YouTube video ID if any. Otherwise returns null.
*
* #access public
* #return string YouTube video ID if any, otherwise null
*/
public function getID()
{
return $this->id;
}
public function url2id($url)
{
$aux = explode("?", $url);
$aux2 = explode("&", $aux[1]);
foreach ($aux2 as $campo => $valor) {
$aux3 = explode("=", $valor);
if ($aux3[0] == 'v')
$video = $aux3[1];
}
return $this->id = $video;
}
/**
* Parse YouTube URL and return video ID.
*
* This method sreturnns YouTube video ID if any. Otherwise returns null.
*
* #access public
* #static
* #param string $url URL of YouTube video in any of most commonly used forms
* #return string YouTube video ID if any, otherwise null
*/
public static function parseURL($url)
{
if (preg_match('/watch\?v\=([A-Za-z0-9_-]+)/', $url, $matches))
return $matches[1];
else
return false;
}
/**
* Get YouTube video HTML embed code
*
* This method returns HTML code which is used to embed YouTube video in page
*
* #access public
* #param string $url YouTube video URL. If this cannot be parsed it will be used as video ID. It can be omitted
* #param integer $width Width of embedded video, in pixels. Defaults to 425
* #param integer $height Height of embedded video, in pixels. Defaults to 344
* #return string HTML code which is used to embed YouTube video in page
*/
public function embedVideo($url = null, $width = 425, $height = 344)
{
if ($url == null)
$videoid = $this->id;
else {
$videoid = YouTube::parseURL($url);
if (!$videoid)
$videoid = $url;
}
return '<object width="' . $width . '" height="' . $height . '"><param name="movie" value="http://www.youtube.com/v/' . $videoid . '?rel=0&fs=1&loop=0&autoplay=1"></param><param name="wmode" value="transparent"></param><param name="allowFullScreen" value="true"><embed src="http://www.youtube.com/v/' . $videoid . '?rel=0&fs=1&loop=0&autoplay=1" allowfullscreen="true" type="application/x-shockwave-flash" wmode="transparent" width="' . $width . '" height="' . $height . '"></embed></object>';
}
/**
* Get URL of YouTube video screenshot
*
* This method returns URL of YouTube video screenshot. It can get one of three screenshots defined by YouTube
*
* #access public
* #param string $url YouTube video URL. If this cannot be parsed it will be used as video ID. It can be omitted
* #param integer $imgid Number of screenshot to be returned. It can be 1, 2 or 3
* #return string URL of YouTube video screenshot
*/
public function getImgURL($url = null, $imgid = 1)
{
if ($url == null)
$videoid = $this->id;
else {
$videoid = YouTube::parseURL($url);
if (!$videoid)
$videoid = $url;
}
return "http://img.youtube.com/vi/$videoid/$imgid.jpg";
}
/**
* Get URL of YouTube video screenshot
*
* This method returns URL of YouTube video screenshot. It can get one of three screenshots defined by YouTube
* DEPRECATED! Use getImgURL instead.
*
* #deprecated
* #see getImgURL
* #access public
* #param string $url YouTube video URL. If this cannot be parsed it will be used as video ID. It can be omitted
* #param integer $imgid Number of screenshot to be returned. It can be 1, 2 or 3
* #return string URL of YouTube video screenshot
*/
public function getImg($url = null, $imgid = 1)
{
return getImgURL($url, $imgid);
}
/**
* Get YouTube screenshot HTML embed code
*
* This method returns HTML code which is used to embed YouTube video screenshot in page
*
* #access public
* #param string $url YouTube video URL. If this cannot be parsed it will be used as video ID
* #param integer $imgid Number of screenshot to be returned. It can be 1, 2 or 3
* #param string $alt Alternate text of the screenshot
* #return string HTML code which embeds YouTube video screenshot
*/
public function showImg($url = null, $imgid = 1, $alt = 'Video screenshot')
{
return "<img src='" . $this->getImgURL($url, $imgid) . "' width='130' height='97' border='0' alt='" . $alt . "' title='" . $alt . "' />";
}
public function search($query, $max = 5)
{
if ($_SERVER['HTTP_X_FORWARD_FOR']) {
$ip = $_SERVER['HTTP_X_FORWARD_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
$feedURL = 'http://gdata.youtube.com/feeds/base/videos?q=' . $query . '&client=ytapi-youtube-search&format=5&restriction=' . $ip . '&max-results=' . $max . '&v=2';
$sxml = simplexml_load_file($feedURL);
$i = 0;
foreach ($sxml->entry as $entry) {
$details = $entry->content;
$info[$i]["title"] = $entry->title;
$aux = explode($info[$i]["title"], $details);
$aux2 = explode("<a", $aux[0]);
$aux3 = explode('href="', $aux2[1]);
$aux4 = explode('&', $aux3[1]);
$info[$i]["link"] = $aux4[0];
$details_notags = strip_tags($details);
$texto = explode("From", $details_notags);
$info[$i]["description"] = $texto[0];
$aux = explode("Views:", $texto[1]);
$aux2 = explode(" ", $aux[1]);
$info[$i]["views"] = $aux2[0];
$aux = explode("Time:", $texto[1]);
$aux2 = explode("More", $aux[1]);
$info[$i]["time"] = $aux2[0];
$imgs = strip_tags($details, '<img>');
$aux = explode("<img", $imgs);
array_shift($aux);
array_shift($aux);
$aux2 = explode("gif\">", $aux[4]);
array_pop($aux);
$aux3 = $aux2[0] . 'gif">';
$aux[] = $aux3;
$images = '';
foreach ($aux as $campo => $valor) {
$images .= '<img' . $valor;
}
$info[$i]["images"] = $images;
$i++;
}
return $info;
}
public function linkSearch($query, $max = 5)
{
if ($_SERVER['HTTP_X_FORWARD_FOR']) {
$ip = $_SERVER['HTTP_X_FORWARD_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
$feedURL = 'http://gdata.youtube.com/feeds/base/videos?q=' . rawurlencode($query) . '&client=ytapi-youtube-search&format=5&restriction=' . $ip . '&max-results=' . $max . '&v=2';
$sxml = simplexml_load_file($feedURL);
$i = 0;
foreach ($sxml->entry as $entry) {
$details = $entry->content;
$aux = explode($entry->title, $details);
$aux2 = explode("<a", $aux[0]);
$aux3 = explode('href="', $aux2[1]);
$aux4 = explode('&', $aux3[1]);
$info[$i] = $aux4[0];
$i++;
}
return $info;
}
}

Go to the video you want to embed then find this...
Copy and paste that code where you want the video to show up.
Code...
echo '<iframe width="'.$width.'" height="'.$height.'" src="https://www.youtube.com/embed/'.$videoid.'?rel=0&fs=1&loop=0&autoplay=1" frameborder="0" allowfullscreen></iframe>';

Ok, looking at your code again this might help.
To display the video in the page using the YouTube.class try this.
<?php
echo '<object width="' . $width . '" height="' . $height . '"><param name="movie" value="youtube.com/v/' . $videoid . '?rel=0&fs=1&loop=0&autoplay=1"></param><param name="wmode" value="transparent"></param><param name="allowFullScreen" value="true"><embed src="youtube.com/v/' . $videoid . '?rel=0&fs=1&loop=0&autoplay=1" allowfullscreen="true" type="application/x-shockwave-flash" wmode="transparent" width="' . $width . '" height="' . $height . '"></embed></object>';
?>
as long as you are setting the correct variables ($width, $height, $videoid) correctly this should work.

Related

Magento2 Attribute Group Name from Attribute Collection

I need Attribute Group Name from Attribute Collection associated with attribute Id. I have Aattribute Set ID.
Thanks!
/**
* #var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory
*/
protected $_groupCollection;
public function __construct(
\Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory $groupCollectionFactory
)
{
$this->_groupCollection = $groupCollectionFactory;
}
/**
* #param $attributSetID
* #return array
*/
public function getAttributeGroupName($attributeSetID){
$groups = $this->_groupCollection->create();
$groups->setAttributeSetFilter($attributeSetID);
$groupData = [];
/* #var $group \Magento\Eav\Model\Entity\Attribute\Group */
foreach ($groups as $group) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$attributeCollection = $objectManager->create('Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection');
$attributeCollection
->setAttributeGroupFilter($group->getId())
->setAttributeSetFilter($attributeSetID);
foreach ($attributeCollection->getAllIds() as $attributeId) {
$groupData[$attributeId] = $group->getAttributeGroupName();
}
}
return $groupData;
}

How to get more result using node-youtube getbyId() method

I am using node-youtube(data api) to get the result of youtube-saerch by id. When I write
res.render('index',{data:(JSON.stringify(result, null, 2))}); then I get two results. But when i write res.render('index',{data:result}); then i get only when result. How can i get more results by simply writing res.render('index',{data:result});
rather than writing
res.render('index',{data:(JSON.stringify(result, null, 2))});
Here is the code of getbyId() metod.
var YouTube = require('youtube-node');
var youTube = new YouTube();
youTube.setKey('*************************');
youTube.getById('HcwTxRuq-uk', function(error, result) {
if (error) {
console.log(error);
}
else {
res.render('index',{data:(JSON.stringify(result, null, 2))});
}
});
I have also tried JSON.parse() method.
like this
var str=(JSON.stringify(result, null, 3));
var data=JSON.parse(str);
In str there are 3 results but in data there is only 1 result. why it return
one result. Also can i get 3 results using JSON.parse().
I hope this is what you want
Also notice there's no need for JSON.stringify at all
var YouTube = require('youtube-node');
var youTube = new YouTube();
youTube.setKey('************************************');
youTube.search('World War z Trailer', 2, function(error, result) {
if (error) {
console.log(error);
} else {
// result should contain 2 videos with some info
// to get more info use getById
var videos = [];
var video1 = result.items[0].id.videoId;
var video2 = result.items[1].id.videoId;
//get 1st video
youTube.getById(video1, function(error, result) {
if (!error) videos.push(result.items[0]);
// get 2nd video
youTube.getById(video2, function(error, result) {
if (!error) videos.push(result.items[0]);
//console.log(videos[0]);
//console.log(videos[1]);
res.render('index',{data:videos)});
});
});
}
});
I know this is not exactly your question, but I think it could help you to see how I'm doing in one of my projects.
If your videos are in a playlist, you can fetch up to 50 videos at the same time and use the pageToken to fetch more if you want more videos from the playlist.
You can fetch the playlist like this :
/**
* Return an array about the videos contained in the GEM-MECHANIC playlist (based on the selected language).
*
* #param $errorMessage String to return the error message.
* #param $language Int language code for which we must fetch the video (default 1 = english)
* #param $maxVideo Int maximum of video we must fetch with the request (<= 0 mean infinite, 5 if invalid)
* #param $playList Int Playlist which want to fetch (Use PlayList class constants).
*
* #return Bidimensionnal Array
*/
static public function getVideoList(&$errorMessage, $language = 1, $maxVideo = 0, $playList = PlayList::GEM_CAR){
$errorMessage = "";
$list = array();
$gemPlayList = self::getPlayList($playList);
if (array_key_exists($language, $gemPlayList)){
if (!is_numeric($maxVideo) or $maxVideo < 0){
$maxVideo = 5;
}
$list = self::fetchVideoList($errorMessage, $gemPlayList[$language], $maxVideo);
}
elseif(empty($gemPlayList)){
$errorMessage = GeneralDbManager::getInstance()->getErrorMessage("GEM_MECHANIC_INVALID_PLAYLIST_ERR", "The selected playlist doesn't exists.");
}
else{
$errorMessage = GeneralDbManager::getInstance()->getErrorMessage("GEM_MECHANIC_INVALID_LANGUAGE_ERR", 'The selected playlist do not contains videos for the language selected.');
}
return $list;
}
/**
* Return an array about the videos contained in the GEM-MECHANIC playlist (based on the selected language).
*
* #param $errorMessage String to return the error message.
* #param $playListId String id of the youtube playlist for which we want to fetch the video list.
* #param $maxVideo Int maximum of video we must fetch with the request
* #param $maxVideo Int number of videos with fetched so far.
* #param $nextToken String to use to fetch more videos.
*
* #return Bidimensionnal Array
*/
private static function fetchVideoList(&$errorMessage, $playListId, $maxVideo, $currentCount = 0, $nextToken = "", $currentList = array()){
if ($currentCount < $maxVideo or $maxVideo === 0) {
$result = abs($maxVideo - $currentCount);
$param = array('playlistId' => $playListId);
if ($result > 50 or $result === 0){
$param['maxResults'] = 50;
$result = 50;
}
else{
$param['maxResults'] = $result;
}
if (!empty($nextToken)){
$param['pageToken'] = $nextToken;
}
try{
$client = new Google_Client();
$client->setDeveloperKey(self::$apiKey);
$youtube = new Google_Service_YouTube($client);
$playList = $youtube->playlistItems->listPlaylistItems('contentDetails, snippet', $param);
unset($youtube);
unset($client);
foreach($playList as $video){
$currentList[] = array('id' => $video['contentDetails']['videoId'], "title" => $video['snippet']['title'], "check" => 0);
}
$currentCount += $result;
if (empty($errorMessage) and !is_null($playList['nextPageToken']) and $currentCount < $maxVideo){
self::fetchVideoList($errorMessage, $language, $maxVideo, $currentCount, $playList['nextPageToken'], $currentList);
}
unset($playList);
}
catch (Google_Exception $exception) {
ExceptionLogger::logException($exception);
$errorMessage = GeneralDbManager::getInstance()->getErrorMessage("GEM_MECHANIC_CANT_FETCH_VIDEO_ERR", 'We are currently not able to fetch the video list from Youtube.');
}
}
return $currentList;
}

Symfony2 - Using controller security for user and category

I am trying to restrict user access from accessing the CRUD access in the controller.
I have a bi-directional OneToOne relationship with User and Category. It's setup to only allow 1 user to be able to access 1 blog.
I am testing this by logging in as another user that is not related to this category. And upon clicking on new, the form loads by-passing any security I have setup.
Speculating that the problem is with the $title parameter being passed in, (trying to pass this in as the route variable) as I don't think I'm setting this up correctly.
Can someone guide me on what I'm doing wrong?
Controller code
/**
* Post controller.
*
* #Route("/category")
*/
/**
* Creates a new Post entity.
*
* #Route("/", name="category_create")
* #Method("POST")
* #Template("AcmeDemoBundle:Page:new.html.twig")
*/
public function createAction(Request $request, $title)
{
// User security
$em = $this->getDoctrine()->getManager();
$categoryRepository = $em->getRepository('AcmeDemoBundle:Category');
$category = $categoryRepository->findOneBy(array(
'title' => '$title',
));
$owner = $category->getUser();
$currentUser = $this->get('security.context')->getToken()->getUser();
if ($owner != $currentUser) {
throw new AccessDeniedException('You do not have access for this');
}
// Form creation
$post = new Post();
$form = $this->createCreateForm($post);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
return $this->redirect($this->generateUrl('category_show', array('id' => $post->getId())));
}
return array(
'post' => $post,
'form' => $form->createView(),
);
}
Category entity
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string
*
* #Gedmo\Slug(fields={"title"}, unique=false)
* #ORM\Column(length=255)
*/
private $catslug;
/**
* #ORM\OneToMany(targetEntity="Post", mappedBy="category")
*/
protected $posts;
/**
* #ORM\OneToOne(targetEntity="Acme\DemoBundle\Entity\User", inversedBy="cat")
* #ORM\JoinColumn(name="cat_id", referencedColumnName="id")
*/
protected $user;
User entity
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=255)
* #Assert\NotBlank(message="Field cannot be blank")
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank()
*/
private $email;
/**
* #ORM\Column(type="json_array")
*/
private $roles = array();
/**
* #var bool
*
* #ORM\Column(type="boolean")
*/
private $isActive = true;
/**
* #Assert\NotBlank
* #Assert\Regex(
* pattern="/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$/",
* message="Use 1 upper case letter, 1 lower case letter, and 1 number")
*/
private $plainPassword;
/**
* #ORM\OneToOne(targetEntity="Acme\DemoBundle\Entity\Category", mappedBy="user")
*/
private $cat;
You can try to create own Security Voter to check if user has a permission to this action. Sample code:
class CategoryVoter implements VoterInterface
{
const CREATE = 'create';
/**
* #param string $attribute
* #return bool
*/
public function supportsAttribute($attribute)
{
return in_array($attribute, [
self::CREATE
]);
}
/**
* #param string $class
* #return bool
*/
public function supportsClass($class)
{
$supportedClass = 'Acme\DemoBundle\Entity\Category';
return $supportedClass === $class || is_subclass_of($class, $supportedClass);
}
/**
* #param TokenInterface $token
* #param object $blog
* #param array $attributes
* #return int
*/
public function vote(TokenInterface $token, Category $category, array $attributes)
{
....
$attribute = $attributes[0];
$user = $token->getUser();
switch($attribute) {
case 'create':
if ($user->getId() === $category->getUser()->getId()) {
return VoterInterface::ACCESS_GRANTED;
}
break;
....
}
...
}
}
create action:
public function createAction(Request $request, $title)
{
$em = $this->getDoctrine()->getManager();
$categoryRepository = $em->getRepository('AcmeDemoBundle:Category');
$category = $categoryRepository->findOneBy([
'title' => '$title',
]);
...
if (false === $this->get('security.context')->isGranted('create', $category)) {
throw new AccessDeniedException('Unauthorised access!');
}
...
}

Command a2ps and Cups - Chineses Characters

Good day.
I have a problem to print files with Chinese characters directly of linux.
We use CUPS to manage your printers on linux and send the print command by a2ps.
Our files are in the encode/unicode (UTF-8 and ISO-8859), but the physical printing is not seeing the Chinese characters
example:
¸£ÌØÆû³µ½ðÈÚ£¨Öйú£©ÓÐÏÞ¹«Ë¾/
Has anyone been through this and know how I can change the unicode of the a2ps command or cups to be able to convert the files?
As a solution, I adopted perform a conversion to pdf with the correct encode and send the converted PDF to CUPS via PrintJob.java file.
public class PDFPrintService {
/**
* Printer Job.
*/
private PrinterJob printerJob = null;
/**
* File to printer.
*/
private InputStream file;
/**
* Class that represents the file to be printed.
*/
private PDFFilePrint pdfFilePrint;
/**
* File converted to PDF for printed.
*/
private PDFFile pdfFile;
/**
* Temporary directory used in the conversion to postscript used in prints.
*/
private String temporaryDirectoryPostscriptFiles;
/**
* Default Temporary Directory of Files.
*/
private String defaultTemporaryDirectoryFiles;
/**
* java.io.tmpdir
*/
private static final String JAVA_IO_TEMPDIR = "java.io.tmpdir";
/**
* Constructs the print job based on the PDFFilePrint class.
*
* #param inputStream
* #param jobName
* #throws IOException
* #throws PrinterException
*/
public PDFPrintService(PDFFilePrint pdfFilePrint) throws IOException, PrinterException {
this.pdfFilePrint = pdfFilePrint;
loadFile(pdfFilePrint.getFileName());
byte[] pdfContent = new byte[this.file.available()];
this.file.read(pdfContent, 0, this.file.available());
initialize(pdfContent, this.pdfFilePrint.getJobName());
}
/**
* Method responsible to load the file for print.
*
* #param fileName
* #throws FileNotFoundException
*/
private void loadFile(final String fileName) throws FileNotFoundException{
try {
this.file = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new FileNotFoundException("The File : " + fileName);
}
}
/**
* Initializes the job
*
* #param pdfContent
* #param jobName
* #throws IOException
* #throws PrinterException
*/
private void initialize(byte[] pdfContent, String jobName)
throws IOException, PrinterException {
ByteBuffer bb = ByteBuffer.wrap(pdfContent);
this.pdfFile = new PDFFile(bb);
PDFPrintPage pages = new PDFPrintPage(pdfFile);
this.printerJob = PrinterJob.getPrinterJob();
loadPrinterDestination();
PageFormat pageFormat = PrinterJob.getPrinterJob().defaultPage();
Book book = new Book();
book.append(pages, pageFormat, pdfFile.getNumPages());
printerJob.setPageable(book);
printerJob.setJobName(jobName);
Paper paper = new Paper();
paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
pageFormat.setPaper(paper);
}
/**
* Method responsible to get the printer.
*
* #throws PrinterException
*/
private void loadPrinterDestination() throws PrinterException {
String printerName = new String();
try {
PrintService[] services = PrinterJob.lookupPrintServices();
for (PrintService printService : services) {
printerName = printService.getName();
if (printerName.equalsIgnoreCase(this.pdfFilePrint.getPrinterName())) {
printerJob.setPrintService(printService);
break;
}
}
} catch (PrinterException e) {
e.printStackTrace();
throw new PrinterException("Printer not found : printerName " + printerName);
}
}
/**
* Method responsible to printer.
*
* #throws PrinterException
*/
public void print() throws PrinterException {
try {
loadNewTemporaryDirectoryPostscriptFiles();
this.printerJob.print(getPrinterPageSettings());
} finally {
loadDefaultTemporaryDirectoryPostscriptFiles();
closeFile();
}
}
/**
* Method responsible to load a new area for a temporary converted files in
* server.
*/
private void loadNewTemporaryDirectoryPostscriptFiles() {
this.defaultTemporaryDirectoryFiles = System.getProperty(JAVA_IO_TEMPDIR, null);
if(!temporaryDirectoryPostscriptFiles.trim().isEmpty()){
System.setProperty(JAVA_IO_TEMPDIR, temporaryDirectoryPostscriptFiles);
}
}
/**
* /**
* Method responsible to load a default temporary area of files.
*/
private void loadDefaultTemporaryDirectoryPostscriptFiles() {
String currentDirectoryUsed = System.getProperty(JAVA_IO_TEMPDIR, null);
if(!currentDirectoryUsed.equalsIgnoreCase(defaultTemporaryDirectoryFiles)){
System.setProperty(JAVA_IO_TEMPDIR, defaultTemporaryDirectoryFiles);
}
}
/**
* Method responsible to load settings of printer.
*
* #return PrintRequestAttributeSet
*/
private PrintRequestAttributeSet getPrinterPageSettings() {
PrintRequestAttributeSet printRequestAttribute = new HashPrintRequestAttributeSet();
loadPageRange(printRequestAttribute);
loadSide(printRequestAttribute);
loadOrientationPortrait(printRequestAttribute);
printRequestAttribute.add(NORMAL);
return printRequestAttribute;
}
/**
* Method responsible to close the file after the printer.
*/
private void closeFile() {
try {
this.file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Method responsible to load the orientation Portrait.
*
* #param printRequestAttribute
*/
private void loadOrientationPortrait(PrintRequestAttributeSet printRequestAttribute) {
printRequestAttribute.add(PORTRAIT);
}
/**
* Method responsible to load the Side of printer(ONE_SIDED or DUPLEX).
*
* #param printRequestAttribute
*/
private void loadSide(PrintRequestAttributeSet printRequestAttribute) {
if (!this.pdfFilePrint.isDuplexSidet()) {
printRequestAttribute.add(ONE_SIDED);
} else {
printRequestAttribute.add(DUPLEX);
}
}
/**
* Method responsible to load the page range of print.
*
* #param printRequestAttribute
*/
private void loadPageRange(PrintRequestAttributeSet printRequestAttribute) {
int lowerBound = pdfFilePrint.getLowerBound();
int upperBound = pdfFilePrint.getUpperBound();
if ((lowerBound < 1) && (upperBound < 1)) {
lowerBound = 1;
upperBound = pdfFile.getNumPages();
} else {
if ((lowerBound < 1) && (upperBound > 0)) {
lowerBound = 1;
} else {
if ((lowerBound > 0) && (upperBound < 1)) {
upperBound = pdfFile.getNumPages();
}
}
}
if (upperBound < lowerBound) {
upperBound = lowerBound;
}
if (lowerBound > pdfFile.getNumPages()) {
lowerBound = pdfFile.getNumPages();
}
if (upperBound > pdfFile.getNumPages()) {
upperBound = pdfFile.getNumPages();
}
PageRanges pageRanges = new PageRanges(lowerBound, upperBound);
printRequestAttribute.add(pageRanges);
}
/**
* Set temporaryDirectoryPostscriptFiles.
*
* #param temporaryDirectoryPostscriptFiles
*/
public void setTemporaryDirectoryPostscriptFiles(
String temporaryDirectoryPostscriptFiles) {
this.temporaryDirectoryPostscriptFiles = temporaryDirectoryPostscriptFiles;
}
}

Password strenght of closest keyboard button

How can I find the password entropy of a string composed pressing the closest buttons on the keyboard?
I would like to define with an algoritm in witch strings like:
querty
or
asdfghjk
are checked like bad passwords.
There is a way to calculate that without dictionaries?
I found a solution by myself.
Actually I'm checking only "qwerty" keyboards.
The getMaxPathLength function gives the maximum path of adjacent keys searching in all the directions.
<?php
/*
* Find the max path in a qwerty keyboard giving an input string
Copyright (C) 2013 Danilo Rossini <rossinidan#gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
USAGE:
// Examples
$array = array("qwertyui"); //get 8 as result
$array = array("quedc"); //get 5 as result
$array = array("qaz"); //get 3 as result
$array = array("zxcdfvppp"); //get 6 as result
$fp = new Path_length("qwertyu");
echo $fp->getMaxPathLength();
*/
class Path_length{
private $maxPathLength = 1;
/*
* Keyboard layout: QUERTY
*/
private $matrix = array(
array("1","2","3","4","5","6","7","8","9","0"),
array("q","w","e","r","t","y","u","i","o","p"),
array("a","s","d","f","g","h","j","k","l"),
array("z","x","c","v","b","n","m"),
);
private $colSize = 10;
private $rowSize = 4;
private $arrayInput = array();
private $arraySize = null;
public function __construct($inputString) {
if(!isset($inputString)) die("NULL input array!");
$this->splitStringInArray($inputString);
$this->cycleMatrix();
}
public function getMaxPathLength(){
return $this->maxPathLength;
}
/**
* Split each element of the string into an array and store it, with his length
* in global variables
* #param type $string
*/
private function splitStringInArray($string){
$length = strlen($string);
$tmpArray = array();
for ($i=0; $i<$length; $i++) {
$tmpArray[$i] = $string[$i];
}
$this->arraySize = $length;
$this->arrayInput = $tmpArray;
}
/**
* Iterate each element of the matrix, calling the function $this->findPath
*/
private function cycleMatrix(){
for($i=0;$i<$this->colSize;$i++){
for($j=0;$j<$this->rowSize;$j++){
if(isset($this->matrix[$j][$i]) && $this->arrayInput[0]==$this->matrix[$j][$i]){
$this->findPath($j, $i, $this->maxPathLength, 1);
}
}
}
}
/**
* Recursive function that search if the closest element in the matrix (up, down, left, right)
* is contained in the input array at the cursor pointer.
* It save into $this->maxPathLength the maximum length path found.
*
* #param int $a -> x position on the matrix
* #param int $b -> y position on the matrix
* #param int $max -> max path lenght found until now by the recursive call
* #param int $c -> array cursor on the input array
* #return int
*/
private function findPath($a, $b, $max, $c){
$this->maxPathLength = max(array($this->maxPathLength, $max));
if($a>=($this->rowSize-1) && $b>=($this->colSize-1)) {
return 1;
}
if($c===$this->arraySize) {
return 1;
}
/* Search next right key */
if(isset($this->matrix[$a+1][$b]) &&
$this->matrix[$a+1][$b]===$this->arrayInput[$c] &&
$this->findPath($a+1, $b, $max+1, $c+1)){
return 1;
}
/* Search next bottom key */
if(isset($this->matrix[$a][$b+1]) &&
$this->matrix[$a][$b+1]===$this->arrayInput[$c] &&
$this->findPath($a, $b+1, $max+1, $c+1)){
return 1;
}
/* Search next left key */
if(isset($this->matrix[$a-1][$b]) &&
$this->matrix[$a-1][$b]===$this->arrayInput[$c] &&
$this->findPath($a-1, $b, $max+1, $c+1)){
return 1;
}
/* Search next up key */
if(isset($this->matrix[$a][$b-1]) &&
$this->matrix[$a][$b-1]===$this->arrayInput[$c] &&
$this->findPath($a, $b-1, $max+1, $c+1)){
return 1;
}
return 0;
}
}
Edit
New version of the previous code with detection of shifted keys.
<?php
/*
* Find the max path in a qwerty keyboard giving an input string
Copyright (C) 2013 Danilo Rossini <rossinidan#gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
USAGE:
// Examples
$string = "qwertyui"; //get 8 as result
$string = "qwedc"; //get 5 as result
$fp = new Path_length("qwertyu");
echo $fp->getMaxPathLength();
*/
class Path_length{
private $maxPathLength = 1;
/*
* Keyboard layout: QUERTY
*/
private $keyLower = array(
array("1","2","3","4","5","6","7","8","9","0"),
array("q","w","e","r","t","y","u","i","o","p"),
array("a","s","d","f","g","h","j","k","l"),
array("z","x","c","v","b","n","m"),
);
private $keyUpper = array(
array("1","2","3","4","5","6","7","8","9","0"),
array("Q","W","E","R","T","Y","U","I","O","P"),
array("A","S","D","F","G","H","J","K","L"),
array("Z","X","C","V","B","N","M"),
);
private $matrix = array();
private $colSize = 10;
private $rowSize = 4;
private $arrayInput = array();
private $arraySize = null;
public function __construct($inputString) {
if(!isset($inputString) || !is_string($inputString)) die("Invalid input string!");
$this->initKeyboard();
$this->splitStringInArray($inputString);
$this->cycleMatrix();
}
private function initKeyboard(){
$this->matrix[0] = $this->keyLower;
$this->matrix[1] = $this->keyUpper;
}
public function getMaxPathLength(){
return $this->maxPathLength;
}
/**
* Split each element of the string into an array and store it, with his length
* in global variables
* #param type $string
*/
private function splitStringInArray($string){
$length = strlen($string);
$tmpArray = array();
for ($i=0; $i<$length; $i++) {
$tmpArray[$i] = $string[$i];
}
$this->arraySize = $length;
$this->arrayInput = $tmpArray;
}
private function isUpper($chr){
return ctype_upper($chr) ? 1 : 0;
}
/**
* Iterate each element of the matrix, calling the function $this->findPath
*/
private function cycleMatrix(){
for($i=0;$i<$this->colSize;$i++){
for($j=0;$j<$this->rowSize;$j++){
for($c=0; $c<$this->arraySize; $c++) {
$isUp = $this->isUpper($this->arrayInput[$c]);
if( isset($this->matrix[$isUp][$j][$i]) &&
$this->arrayInput[$c]===$this->matrix[$isUp][$j][$i]){
$this->findPath($j, $i, 1, $c+1, $isUp);
}
}
}
}
}
/**
* Recursive function that search if the closest element in the matrix (up, down, left, right)
* is contained in the input array at the cursor pointer.
* It save into $this->maxPathLength the maximum length path found.
*
* #param int $a -> x position on the matrix
* #param int $b -> y position on the matrix
* #param int $max -> max path lenght found until now by the recursive call
* #param int $c -> array cursor on the input array
* #return int
*/
private function findPath($a, $b, $max, $c, $isUp){
$this->maxPathLength = max(array($this->maxPathLength, $max));
if($a>=($this->rowSize-1) && $b>=($this->colSize-1)) {
return 1;
}
if($c===$this->arraySize) {
return 1;
}
/* Search next right key */
if(isset($this->matrix[$isUp][$a+1][$b]) &&
$this->matrix[$isUp][$a+1][$b]===$this->arrayInput[$c] &&
$this->findPath($a+1, $b, $max+1, $c+1, $isUp)){
return 1;
}
/* Search next bottom key */
if(isset($this->matrix[$isUp][$a][$b+1]) &&
$this->matrix[$isUp][$a][$b+1]===$this->arrayInput[$c] &&
$this->findPath($a, $b+1, $max+1, $c+1, $isUp)){
return 1;
}
/* Search next left key */
if(isset($this->matrix[$isUp][$a-1][$b]) &&
$this->matrix[$isUp][$a-1][$b]===$this->arrayInput[$c] &&
$this->findPath($a-1, $b, $max+1, $c+1, $isUp)){
return 1;
}
/* Search next up key */
if(isset($this->matrix[$isUp][$a][$b-1]) &&
$this->matrix[$isUp][$a][$b-1]===$this->arrayInput[$c] &&
$this->findPath($a, $b-1, $max+1, $c+1, $isUp)){
return 1;
}
return 0;
}
}

Resources