Get page number of pdf form field using php - php

I am currently using SetaPDF to get the form fields located in a document and saving those form field names in a DB. However, I'm trying to get the page number of those form fields. I can't find anything in the Seta documentation that will help with this. Is there another PDF library I can use to accomplish this?
$document = SetaPDF_Core_Document::loadByFilename($file);
$formFiller = new SetaPDF_FormFiller($document);
$fields = $formFiller->getFields();
foreach ($fields->getNames() as $fieldName) {
$field = $fields->get($fieldName);
$is_read_only = 0;
if ($field->isReadOnly()) {
$is_read_only = 1;
}
$is_text = 1;
$field_name = DB::Scrub($fieldName);
$base_field_name = $field->getOriginalQualifiedName();
if (strpos($base_field_name,"#") !== false) {
$arr_field = explode("#", $base_field_name);
$base_field_name = $arr_field[0];
}
if (strpos($base_field_name,"*") !== false) {
$is_text = 0;
$base_field_name = str_replace("*","",$base_field_name);
}
$sql = "INSERT INTO [cust].[PDF_Fields] (file_name,field_name,base_field_name,is_read_only,is_text)
VALUES ('$new_file','$field_name','$base_field_name',$is_read_only,$is_text)";
DB::Query($sql);
}

As Ryan already wrote form fields are not directly related to a page but their representations as Widget Annotations are. This is done by adding the reference to the individual Widget Annotations in the /Annots array of the page. Sadly it is optional to have this the other way round (from the annotation to the page).
You can get the page and its number through some low level methods of the SetaPDF-Core component: First you need an instance of the Widget Annotation of a form field. This can be done with the getAnnotation() method of a form field instance.
Then you can use this instance to search the page via the getPageByAnnotation() method of the main pages instance. To get only the page number you can pass this result to the getPageNumberByPageObject() then.
The written above in code could look like:
$pages = $document->getCatalog()->getPages();
$annotation = $field->getAnnotation();
// Method name is a bit vague and accepts an annotation instance starting with revision > 1371 only
$page = $pages->getPageByAnnotation($annotation->getIndirectObject($document));
// $page = $pages->getPageByAnnotation($annotation); // works with revision > 1371
$pageNumber = $pages->getPageNumberByPageObject($page);

Related

Drupal ajax_command_after function

Regarding the ajax_command_after() function in Drupal 7
Currently I have it working and outputting some content.
however it wraps the content in an unlabelled DIV (no class, no id ect).
Is there a way to make it add an ID to this DIV so that I can target the DIV later?
The functions documentation says that its final argument is an array of settings but the only thing it says about the settings is...
"$settings: An optional array of settings that will be used for this command only".
It does not say what settings are available or how to use them.
Can the required ID for the wrapper DIV be inserted here
if yes
What would the syntax be?
This is the relevant documentation
https://api.drupal.org/api/drupal/includes%21ajax.inc/function/ajax_command_after/7
I also could not find an example of this in Drupals examples module.
my code is
function view_file_page(){
$args = func_get_args();
$connection = connect();
$ID = $args[0];
$row = $args[2];
$stream = $connection->getContentStream($ID);
// Create a new AJAX command that replaces the #page text with our own text.
$ajax_commands[] = ajax_command_after('#' . $row, $stream);
$ajax_commands[] = ajax_command_remove('#name-and-slogan');
// $ajax_commands[0]['method'] = 'replaceWith';
// $sam = $ajax_commands[0]['method'];
// Return our commands in JSON.
ajax_deliver(array('#type' => 'ajax', '#commands' => $ajax_commands));
}

Order an XML scoreboard and return it with PHP

I'm creating a game where when a timer ends the user can enter their name. I pass the name and score to a PHP file with AJAX. That PHP file adds it to an XML file. I loop through it to create a table holding the scores and it's then returned to AJAX and I then output it on the screen with jQuery. I have all of this working fine right now.
What I want to accomplish is this:
1. After the score is added to the XML file I want to order the nodes according to score, in descending order
2. I then want to populate the table with the values in order. I'd also like to limit it to only the top 10 scores.
Basically where I'm running into problems coming up with a solution is the ordering. Once the XML is ordered populating the table and limiting it to 10 should be pretty straight forward. Any suggestions on how I should do this?
XML : http://people.rit.edu/lxl1500/Prog4/Project%202/scoreboard.xml
jQuery Ajax call:
function addScore(score,name){
var url = 'scoreboard.php';
$.post(url,{Score:score, Name:name},function(data){
$('#score').html(data).show();
});
}
scoreboard.php:
<?php
$score = $_POST['Score'];
$name = $_POST['Name'];
if($name == ''){
$name = 'Player'.rand(0,5000);
}
$scoreboard = new domDocument;
$scoreboard->load('scoreboard.xml');
$root=$scoreboard->documentElement;
$entry = $scoreboard->createElement('entry');
$userScore = $scoreboard->createElement('score',$score);
$userName = $scoreboard->createElement('name',$name);
$entry->appendChild($userName);
$entry->appendChild($userScore);
$root->appendChild($entry);
$scoreboard->save('scoreboard.xml');
$scores = $scoreboard->getElementsByTagName('entry');
$string = '<table id="score-table" cellspacing="10"><tbody><tr><th align="left">User</th><th align="left">Score</th></tr>';
foreach($scores as $score){
$getScore = $score->getElementsByTagName('score')->item(0)->nodeValue;
$getPlayer = $score->getElementsByTagName('name')->item(0)->nodeValue;
$string.="<tr><td>$getPlayer</td><td>$getScore</td></tr>";
}
$string.='</tbody></table>';
echo $string;
?>
Any help would be greatly appreciated! Thanks.
You can build a sorted XML file, that is add the nodes to the xml file in sorted order, something like
$entries = $root->getElementsByTagName('entry');
$added = false;
foreach ($entries as $item) {
if ($score <= $item->getElementsByTagName('score')->item(0)->nodeValue) continue;
$root->insertBefore($entry, $item);
$added = true;
break;
}
// if not yet added, add it
if (!$added) {
$root->appendChild($entry);
}
For this to work the file has to be sorted (or empty).

Kohana Model Saved Twice

I just installed a fresh copy of Kohana 3.2, built my database, wrote my first model, and tried testing it. Everything works fine except the model's "save" method is being executed twice--I end up with two new entries in the database instead of one. The problem only occurs when I use the "find" code shown below.
Why would the model's save get executed twice, once as expected and once because of the find?
Here's the code:
class Controller_Welcome extends Controller {
public function action_index()
{
$rating = ORM::factory('rating');
$rating->user_id = 1;
$rating->userlevel_id = 3;
$rating->category_id = 1;
$rating->page_id = 1;
$rating->rating = 4;
$rating->comments = 'This one is a real killer';
$rating->ratingstatus_id = 1;
$rating->save();
$found = ORM::factory('rating')
->where('id', '=', 1)
->find();
$this->response->body($found->comments); // Test to check for found data
}
} // End Welcome
Thanks in advance!
There are two issues that were causing my problem:
I didn't have a favicon.ico on my server. Many browsers request one, and all URLs that aren't actual files or directories get redirected to the index page. Every time I loaded the page, the browser would request a missing favicon and get redirected to my index page--two requests. After looking at my logs, this page was what tipped me off: http://forum.kohanaframework.org/discussion/7447/error-kohana_request_exception/p1
After I added a favicon, I still saw the double request behavior occasionally. It turns out it was a behavior of Google Chrome--Chrome prefetches pages, so each time I changed the content, Chrome would prefetch and cache the page (adding a request).
After adding a favicon and when using a browser besides Chrome, everything behaves as expected.
$rating = ORM::factory('rating');
This line represents nothing.
If you want to create new record you should use create() instead save().
$rating = new Model_Rating;
$rating->user_id = 1;
$rating->userlevel_id = 3;
$rating->category_id = 1;
$rating->page_id = 1;
$rating->rating = 4;
$rating->comments = 'This one is a real killer';
$rating->ratingstatus_id = 1;
$rating->create();
If you want to load single rating object with given id:
$found = ORM::factory('rating', 1);

Inserting added logic on the fly within a PHP for loop that generates an array

Situation:
I have a front-page slider where users can select from a menu of options which pages they want to include in a front-page slider. The options are stored in a static array and only print the selections of the user up to whatever limit I determine, please see code below.
<?
// Counts the Number of Boxes available for the front page slider
$numberOfBoxes = 6;
$group = array (); // Create an empty array to store all of your final data
//Counts all the checkboxes and their corresponding sliderboxes
for ( $a = 1; $a <= $numberOfBoxes; $a++ )
{
if (${'checkBox_'.$a} == TRUE){
$tempDefaultArray = ${'sliderBox_'.$a};
array_push($group , $tempDefaultArray); // Push the data to the $group array
}
}
$arraySize = sizeof($group); // Find the size of the final array
// Take the outcome from the above calculations and create slider
for ( $i = 0; $i <= ($arraySize - 1); $i++ )
{
$image = $group[$i]['image'];
$title = $group[$i]['title'];
$tagline = $group[$i]['tagline'];
$url = $group[$i]['url'];
$vanityUrl = $group[$i]['vanityUrl'];
print'
<li '.$sliderDivider.'>
<img src="'.$image.'" border="0"/>
<h1>'.$title.'</h1>
<p>'.$tagline.'</p>
<a href="'.$url.'" '.$sliderLink.'/>'.$vanityUrl.'</a>
';}?>
Problem:
This works perfectly, but I want to state that if a particular external variable isset and/or true that the third box in my slider will populate data from a specific object in my array. I would like to maintain the functionality of this existing logic, and just incorporate some extra to override the third box if that variable is set.
Example:
I choose for my slider options to be: Article 1, Article 2, Blog 1, Image 1, and then in a separate area of the customization the user selects YouTube videos. By default when that variable isset, lets call it $youTube then the third selection (in this ex Blog 1) would default to the YouTube. Additional note, this default box lives in the same array as the static options.
This is kind of a tricky thing to explain, and if their are any ninja PHPrs out there that could recommend an efficient way to handle this I would appreciate it.
Hmm, if I understand your question right, you want to have an override within your loop if a certain condition is set outside the array variables?
You can put an if statement in your loop checking the external variable:
if($external_var=="something") {
$image = $static_array['image'];
$title = $static_array['title'];
$tagline = $static_array['tagline'];
$url = $static_array['url'];
$vanityUrl = $static_array['vanityUrl'];
} else {
$image = $group[$i]['image'];
$title = $group[$i]['title'];
$tagline = $group[$i]['tagline'];
$url = $group[$i]['url'];
$vanityUrl = $group[$i]['vanityUrl'];
}

Process for pulling data from a sql database

I want to make a program that pulls objects from a sql database and processes the objects against a set of functions before returning the data to the user.
It will work like this:
User specifies a date range in a javascript form.
The date range is sent to a php file on the server that converts it to
a sql query.
The sql query pulls all data in the database that matches the date
range, and stores each matching item and its associated information as a php
class in a temporary php file (see example below).
The main php program then processes each class in the temporary php file against a set of functions and returns the information to the user.
Example temporary php file:
class ice_cream
{
$temperature = 0;
$texture = 'soft';
}
class hard_candy
{
$temperature = 20;
texture = 'hard';
}
Example of Functions to process the classes against:
function will_it_break_dentures($class_name)
{
//$class_name is passed to the function based on the classes available in temp file
$food_type_class = new $class_name();
$damage_potential_temperature = $food_type_class->temperature;
$damage_potential_temperature = $food_type_class->texture;
if($damage_potential_temperature >= 15) && ($damage_potential_texture === 'hard')
{
print("Don't eat it");
}
}
Is there a more efficient/secure way to pull data from a database and process it against a set of functions? Is this the standard way to pull data from a database for processing? Item #3 seems suspect, but it's the best I could come up with. Any relevant informational resources on best practice are appreciated.
Your class definition should define the properties of the object, not the values. It should be defined statically, not dynamically at runtime. At runtime you create instances of this class and populate the data for each instance.
Try something like this:
class Food {
var $name;
var $temp;
var $texture;
// Constructor
public function food($name, $temp, $texture) {
$this->name = $name;
$this->temp = $temp;
$this->texture = $texture;
}
public function breaksDentures() {
if($this->temp >= 15) && ($this->texture === 'hard')
return true;
else
return false;
}
}
And use it like this:
function processFoods($daterange) {
$query = build_query_from_daterange($daterange);
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
$food = new Food($row['name'], $row['temp'], $row['texture']);
// Now $food is an instance of the Food class populate with the values
// from the db, e.g., 'ice cream', 0, 'hard'.
if $food->breaksDentures() {
print("Don't eat it");
}
}
}
P.S. You may want to brush up on your object-oriented concepts. Your question is a good one but indicates some confusion about OO basics.

Categories