Uncaught SyntaxError: Unexpected token < - Wordpress - javascript

I am using the Penny auction theme and I am getting the following error message:
Uncaught SyntaxError: Unexpected token < penny_scripts.js:126
When I expand the error it shows:
(anonymous function) penny_scripts.js:126
$.ajax.success smart-updater.js:146
j jquery.js?ver=1.11.0:2
k.fireWith jquery.js?ver=1.11.0:2
x jquery.js?ver=1.11.0:4
b jquery.js?ver=1.11.0:4
Line 126 of penny_scripts.js is
var myObj = eval("(" + data + ")");
for (var i = 0; i < myObj.length; i++) <---This line
{
pid = myObj[i].pid;
rnd = myObj[i].rnd;
remaining_time = myObj[i].remaining_time;
current_bid = myObj[i].current_bid;
If I do alert(data); then I get the following message
Line 1092 of functions.php is:
$info = array(); global $wpdb;
$my_arr = $_POST['my_values'];
$OKOK = $_POST['OKOK'];
foreach($my_arr as $id_plus_rand)
{
$exp = explode("_",$id_plus_rand);
$pid = $exp[0];
$rnd = $exp[1];
//----------------------
$newpid = array();
$highest_bidder_id = PennyTheme_get_highest_bid_owner_obj($pid);
if($highest_bidder_id == false) $highest_bidder = "0";
else {
$s = "select user_login from ".$wpdb->users." where ID='{$highest_bidder_id->uid}'";
$r = $wpdb->get_results($s); $r = $r[0];
$highest_bidder = $r->user_login;
}
$newpid['highest_bidder'] = $highest_bidder;
$newpid['highest_bidder_id'] = $highest_bidder_id->id;
$newpid['pid'] = $pid;
$newpid['rnd'] = $rnd;
$newpid['remaining_time'] = get_post_meta($pid, 'ending', true) - current_time('timestamp',0);
$newpid['current_bid'] = PennyTheme_get_show_price(get_post_meta($pid, 'current_bid', true));
if($OKOK == "1"):
//$closed = get_post_meta($pid, 'closed', true);
//$post = get_post($pid);
$bids = "select * from ".$wpdb->prefix."penny_bids where pid='$pid' order by id DESC limit 13";
$res = $wpdb->get_results($bids);
$all_bids = '';
if(count($res) > 0)
{
$all_bids .= '<table width="100%">';
$all_bids .= '<thead><tr>';
$all_bids .= '<th>'.__('Username','PennyTheme').'</th>';
$all_bids .= '<th>'.__('Bid Amount','PennyTheme').'</th>';
// echo '<th>'.__('Date Made','PennyTheme').'</th>';
$all_bids .= '</tr></thead><tbody>';
//-------------
foreach($res as $row)
{
$user = get_userdata($row->uid);
$s = "select user_login from ".$wpdb->users." where ID='{$row->uid}'";
$r = $wpdb->get_results($s);
$all_bids .= '<tr>';
$all_bids .= '<th>'.$r[0]->user_login.'</th>';
$all_bids .= '<th>'.PennyTheme_get_show_price($row->bid).'</th>';
// echo '<th>'.date("d-M-Y H:i:s", $row->date_made).'</th>';
$all_bids .= '</tr>';
}
$all_bids .= '</tbody></table>';
}
else $all_bids .= __("No bids placed yet.", 'PennyTheme');
$newpid['bidders'] = $all_bids;
endif;
array_push($info,$newpid);
}
header('Content-type: application/json'); <---Line 1092
Line 146 of smart-update.js is:
if(es.rCallback && rCallback && es.rCallback.search(rCallback) != -1) {
window[rCallback](data);
} else {
es.callback(data); <---This line
}
Line 1395 of plugin.php:
function remove_menu_page( $menu_slug ) {
global $menu;
foreach ( $menu as $i => $item ) { <-- This line
if ( $menu_slug == $item[2] ) {
unset( $menu[$i] );
return $item;
}
}
return false;
}
I only get this error message when I am not logged into the site or logged in with an account that the user level is below Contributor.
I am unsure why that is happening or how to fix this. Any help is appreciated.

The above problem was caused by a plugin that I had enabled on my site. When I updated it, the error stopped. The error doesn't happen with version 2.19.5 or above. Changelog for 2.19.5
Remove Testimonials menu for authors removal code <--This was the change that fixed the error for me.
Require Aihrus Framework 1.1.4
Revise premium introduction
Update premium links

Related

I need to choose more values from some tasks that belong to same project

My question is: Is there any other method to select the values I need from all the tasks that belongs to same project and sum them? Other method that I tried in the down description?
Description:
I have an app where I can create a Project and, inside the Project, I can create Tasks. For every Task, I can add a percent and calculate a price (example picture 1).
Then I have a report page where I want to calculate all the prices from all of the Tasks of same project (example picture 2).
My problem is when I want to select all the prices from all the tasks that belongs to same projects and sum them in the table "price" of report page.
For the moment I tried a method with the code I put down, and it's not working as I need, because it take the correct value from the first task of the project but dont take corect value from the ohther tasks from the same project
picture 1
picture 2 (but here the problem is that just the first array is corrent the other are not)
code I use ( I commented in the code with "the code that doesnt work" the part that make the sum) :
<?php
defined('BASEPATH') or exit('No direct script access allowed');
$hasPermissionEdit = has_permission('tasks', '', 'edit');
$hasPermissionDelete = has_permission('tasks', '', 'delete');
$tasksPriorities = get_tasks_priorities();
$aColumns = [
db_prefix() . 'tasks.id as id',
db_prefix() . 'tasks.name as task_name',
'count(tbltasks.id) as totaltasks',
//'(SELECT GROUP_CONCAT(name SEPARATOR ",") FROM ' . db_prefix() . 'tasks) as itemlist',
];
$sIndexColumn = 'id';
$sTable = db_prefix() . 'tasks';
$where = [];
$join = [];
$sGroupBy = ' group by '.db_prefix() . 'tasks.rel_id';
// =============== Filter =================
if (isset($ts_filter_data['period-from']) && $ts_filter_data['period-from'] != '' && isset($ts_filter_data['period-to']) && $ts_filter_data['period-to'] != '') {
$ts_filter_from = to_sql_date($ts_filter_data['period-from']);
$ts_filter_from = date('Y-m-d', strtotime($ts_filter_from));
$ts_filter_to = to_sql_date($ts_filter_data['period-to']);
$ts_filter_to = date('Y-m-d', strtotime($ts_filter_to));
}
if (isset($ts_filter_data['this_month']) && $ts_filter_data['this_month'] != '') {
$ts_filter_from = date('Y-m-01');
$ts_filter_to = date('Y-m-t 23:59:59');
}
if (isset($ts_filter_data['last_month']) && $ts_filter_data['last_month'] != '') {
$ts_filter_from = date('Y-m-01', strtotime('-1 MONTH'));;
$ts_filter_to = date('Y-m-t 23:59:59', strtotime('-1 MONTH'));
}
if (isset($ts_filter_data['this_week']) && $ts_filter_data['this_week'] != '') {
$ts_filter_from = date('Y-m-d', strtotime('monday this week'));
$ts_filter_to = date('Y-m-d 23:59:59', strtotime('sunday this week'));
}
if (isset($ts_filter_data['last_week']) && $ts_filter_data['last_week'] != '') {
$ts_filter_from = date('Y-m-d', strtotime('monday last week'));
$ts_filter_to = date('Y-m-d 23:59:59', strtotime('sunday last week'));
}
if($ts_filter_from){
array_push($where, 'AND '.db_prefix().'tasks.startdate >="'.$ts_filter_from.'"');
}
if($ts_filter_to){
array_push($where, 'AND '.db_prefix().'tasks.startdate <="'.$ts_filter_to.'"');
}
// =============== Filter =================
array_push($where, 'AND '.db_prefix().'tasks.rel_type="project"');
// Script By Dev Websyms
$aColumns = hooks()->apply_filters('tasks_table_sql_columns', $aColumns);
// Fix for big queries. Some hosting have max_join_limit
if (count($custom_fields) > 4) {
#$this->ci->db->query('SET SQL_BIG_SELECTS=1');
}
$result = data_tables_init(
$aColumns,
$sIndexColumn,
$sTable,
$join,
$where,
[
'tbltasks.rel_type',
'tbltasks.rel_id',
'tbltasks.task_item_percentage',
'tbltasks.task_duration',
tasks_rel_name_select_query() . ' as rel_name',
get_sql_select_task_assignees_ids() . ' as assignees_ids',
'(SELECT staffid FROM ' . db_prefix() . 'task_assigned WHERE taskid=' . db_prefix() . 'tasks.id AND staffid=' . get_staff_user_id() . ') as is_assigned',
],
$sGroupBy
);
$output = $result['output'];
$rResult = $result['rResult'];
$loop = 1;
foreach ($rResult as $aRow) {
$row = [];
$projectTaskIds = get_assign_project_task($aRow['rel_id']);
$assignees_ids = $aRow['assignees_ids'];
$assignees_id = explode(',', $assignees_ids);
$calA = get_task_user_hourly_rate($assignees_id[0]); // hourly_rate
if($projectTaskIds && count($projectTaskIds)){
$realTime = 0;
$estimateCost = 0;
$itemName = '';
$realCost = 0;
$realCostArr = array();
$totalCalEArr = array();
foreach ($projectTaskIds as $key => $projectTaskId) {
// echo $projectTaskId['id'];
// echo "<br>";
$calB = 0;
$calC = 0;
$itemtotal = 0;
$items = get_items_by_type('task', $projectTaskId['id']);
if($items && count($items) > 0){
$itemNo = 1;
foreach ($items as $key => $item) {
$itemtotal += ($item["rate"]*$item["qty"]);
$itemName .= '<div>'.$itemNo.'.'.$item["description"].' <b>('.round($item["qty"]).')</b>'.'</div>';
$itemNo++;
}
}
// =============== the code that doesn't work ============
$calF = get_task_user_hourly_rate($assignees_id[0]); // hourly_rate
$calG = get_task_custom_billable_amount($aRow['id']);
$calE = ($itemtotal+$aRow['task_item_manual_total_price']-$itemtotal);
if(isset($aRow['task_item_percentage'])){
$calE = ((round($itemtotal + ((($calF * $aRow['task_duration'] / 60))))
*($aRow['task_item_percentage']/100)))
+(round($itemtotal + (($calF * $aRow['task_duration'] / 60)))); // additionalPriceTotal
}
$totalCalEArr[] = $calE;
if($totalCalEArr && count($totalCalEArr) > 0){
$totalsCalEaMount = 0;
foreach ($totalCalEArr as $key => $totalvalue) {
$totalsCalEaMount += $totalvalue;
}
}
// =============== the code that doesnt work ============
$realTime += get_calc_task_real_logged_time($projectTaskId['id']);
$calB = get_task_custom_billable_amount($projectTaskId['id']);
if($aRow['task_item_percentage']){
$calC = ((round($itemtotal + ((($calF * $aRow['task_duration'] / 60))))*($aRow['task_item_percentage']/100)))+(round($itemtotal + (($calF * $aRow['task_duration'] / 60)))); // additionalPriceTotal
} else {
$calC = ($itemtotal+$aRow['task_item_manual_total_price']-$itemtotal);
}
$estimateCost += round($itemtotal+($calA * $aRow['task_duration'] / 60));
$realCost = round($itemtotal+$calB);
// if($calC = 0){ $realCost = round($itemtotal+$calB);} else { $realCost = round($itemtotal+$calB+$calC);
// }
$realCostArr[] = $realCost;
}
if($realCostArr && count($realCostArr) > 0){
$realCostAmount = 0;
foreach ($realCostArr as $key => $reslcostvalue) {
$realCostAmount += $reslcostvalue;
}
}
}
$outputName = '';
$relName = '';
$row[] = $loop;
if ($aRow['rel_name']) {
$relName = task_rel_name($aRow['rel_name'], $aRow['rel_id'], $aRow['rel_type']);
$link = task_rel_link($aRow['rel_id'], $aRow['rel_type']);
$relName = '<span class="hide"> - </span><a class="text-muted task-table-related" data-toggle="tooltip" title="' . _l('task_related_to') . '" href="' . $link . '">' . $relName . '</a>';
}
$row[] = $relName;
$row[] = count($projectTaskIds);
$row[] = $itemName;
$row[] = $aRow['task_duration']*count($projectTaskIds);
$row[] = round($realTime/60);
$row[] = round($estimateCost);
$row[] = round($realCostAmount);
$row[] = '';
$row[] = $totalCalEArr; // display as array or
//$row[] = $totalsCalEaMount; //to display as a sum
$output['aaData'][] = $row;
$loop++;
}
And if you need more details you can find a guide how to use it: http://amco.ro/pdf/Error%20presentation.pdf

Treeview Directory reacts with Datatable

I have a treeview directory. The directory is an actual viewing of folders with files on it and beside the treeview of directory I have a datatable.
The interface looks like this:
When I click a treeview it will show its path through alert. Like this:( I clicked the runblack.png).
My question is how can I make the treeview react with the datatable beside.
Like if I click the year the datatable will search all files with the same year.
Then if i click the category below the year it will search the category with the year.
This is my code for the directory:
<?php
function php_file_tree($directory, $return_link, $extensions = array()) {
// Generates a valid XHTML list of all directories, sub-directories, and files in $directory
// Remove trailing slash
if( substr($directory, -1) == "/" ) $directory = substr($directory, 0, strlen($directory) - 1);
$code .= php_file_tree_dir($directory, $return_link, $extensions);
return $code;
}
function php_file_tree_dir($directory, $return_link, $extensions = array(), $first_call = true) {
// Recursive function called by php_file_tree() to list directories/files
// Get and sort directories/files
if( function_exists("scandir") ) $file = scandir($directory); else $file = php4_scandir($directory);
natcasesort($file);
// Make directories first
$files = $dirs = array();
foreach($file as $this_file) {
if( is_dir("$directory/$this_file" ) ) $dirs[] = $this_file; else $files[] = $this_file;
}
$file = array_merge($dirs, $files);
// Filter unwanted extensions
if( !empty($extensions) ) {
foreach( array_keys($file) as $key ) {
if( !is_dir("$directory/$file[$key]") ) {
$ext = substr($file[$key], strrpos($file[$key], ".") + 1);
if( !in_array($ext, $extensions) ) unset($file[$key]);
}
}
}
if( count($file) > 2 ) { // Use 2 instead of 0 to account for . and .. "directories"
$php_file_tree = "<ul";
if( $first_call ) { $php_file_tree .= " class=\"dirlist\""; $first_call = false; }
$php_file_tree .= ">";
foreach( $file as $this_file ) {
if( $this_file != "." && $this_file != ".." ) {
if( is_dir("$directory/$this_file") ) {
// Directory
$flink="./$directory/$this_file";
$dlink = str_replace("[link]", "$directory/". urlencode($this_file), $return_link);
$php_file_tree .= "<li class=\"hdir\" >" . htmlspecialchars($this_file)."" ;
$php_file_tree .= php_file_tree_dir("$directory/$this_file", $return_link ,$extensions, false);
$php_file_tree .= "</li>";
} else {
// File
// Get extension (prepend 'ext-' to prevent invalid classes from extensions that begin with numbers)
$ext = "ext-" . substr($this_file, strrpos($this_file, ".") + 1);
$link = str_replace("[link]", "$directory/" . urlencode($this_file), $return_link);
$flink="./$directory/" . urlencode($this_file);
$fsize = filesize ("$flink");
$ftime=date ("F d Y H:i:s.", filemtime($flink));
$php_file_tree .= "<li class=\"hfile " . strtolower($ext) . "\">" . htmlspecialchars($this_file) . "<br></li>";
}
}
}
$php_file_tree .= "</ul>";
}
return $php_file_tree;
}
// For PHP4 compatibility
function php4_scandir($dir) {
$dh = opendir($dir);
while( false !== ($filename = readdir($dh)) ) {
$files[] = $filename;
}
sort($files);
return($files);
}
I want it like when the treeview is clicked I will pass a query to the datatable to search for the needed data.
Query example: SELECT * FROM TABLE WHERE DATE = 'from treeview' AND CATEGORY = 'from treeview' ... and so on
My datatable viewing of data from the database is just the usual javascript to php connection for select.

trying to create a php foreach loop which generates a javascript file

So I have this script which im trying to create a filelist.js file from in php here's the code:
//CREATE fileslist.js
$thumbssize = "1";
$moviesize= "1";
$thumbarray = array_slice(scandir($tpath), 2);
echo print_r($thumbarray) . "<br/>";
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
$script="
fileList = {};
fileList[\"thumbs\"] = {};
fileList[\"movies\"] = {};
fileList[\"title\"]=\"{$foldername}\";";
foreach($thumbarray as $item) {
print "fileList[\"thumbs\"][1]=["$item['0']","$item['2']","$item['3']","$item['4']","$item['5']","$item['6']"];";
}
$script2 = "
fileList[\"thumbs\"][\"size\"]={$thumbssize};
fileList[\"thumbs\"][\"size\"]={$moviesize};";
//$script = preg_replace('/\s\s+/', ' ', $script);
$scriptName= $_SERVER['DOCUMENT_ROOT'] . "/{$foldername}/assets/js/filelist.js";
file_put_contents($scriptName, trim($script . $script2) . "\n", FILE_APPEND);
echo "Generating filelist.js</br>";
}
This here is the example output of the array:
Array ( [0] => 863_example_r003.mp4 [1] => 863_example_r004.mp4 [2] => 863_example_r005.mp4 [3] => 863_example_r006.mp4 [4] => 863_example_r007.mp4 ) 1
This is the filelist.js output as it stands right now:
fileList = {};
fileList["thumbs"] = {};
fileList["movies"] = {};
fileList["title"]="test7";
fileList["thumbs"]["size"]=1;
fileList["thumbs"]["size"]=1;
So up until this point its doing what i want except I cannot figure out how to make a foreach loop to generate this type of output :
fileList = {};
fileList["thumbs"] = {};
fileList["movies"] = {};
fileList["title"]="863-example";
fileList["thumbs"][1]=["863_example_r048.mp4","863_example_r049.mp4","863_example_r050.mp4","863_example_r051.mp4","863_example_r052.mp4","863_example_r053.mp4"];
fileList["thumbs"][2]=["863_example_r054.mp4","863_example_r055.mp4","863_example_r056.mp4","863_example_r057.mp4","863_example_r058.mp4","863_example_r059.mp4"];
fileList["thumbs"][3]=["863_example_r060.mp4","863_example_r061.mp4","863_example_r062.mp4","863_example_r003.mp4","863_example_r063.mp4","863_example_r064.mp4"];
fileList["thumbs"][4]=["863_example_r065.mp4","863_example_r004.mp4","863_example_r067.mp4","863_example_r068.mp4","863_example_r069.mp4","863_example_r070.mp4"];
fileList["thumbs"][5]=["863_example_r005.mp4","863_example_r071.mp4","863_example_r072.mp4","863_example_r073.mp4","863_example_r074.mp4","863_example_r006.mp4"];
fileList["thumbs"][6]=["863_example_r075.mp4","863_example_r076.mp4","863_example_r077.mp4","863_example_r078.mp4","863_example_r007.mp4","863_example_r079.mp4"];
fileList["thumbs"][7]=["863_example_r080.mp4","863_example_r081.mp4","863_example_r082.mp4","863_example_r008.mp4","863_example_r083.mp4","863_example_r084.mp4"];
fileList["thumbs"][8]=["863_example_r085.mp4","863_example_r086.mp4","863_example_r009.mp4","863_example_r087.mp4","863_example_r088.mp4","863_example_r089.mp4"];
The [1], [2], [3] refers to a page number and there needs to be 6 items per page as the example above
Thank you for your feedback. Just a minute ago I refined the code and tested it in my localhost. Here is the changed code that gives the result:
$script1 = "";
$i = 0;
$j = 0;
$inrow = 6; // files in row
foreach($thumbarray as $item => $itemv) {
// beginning of the row
if($j % $inrow == 0){
$script1 .= "\nfileList[\"thumbs\"][".($i+1)."]=[";
}
$script1 .= "\"" . $itemv . "\","; // add filename "863_example_r048.mp4",
// end of the row
if(($j + $inrow + 1) % $inrow == 0){
// Delete comma at end of row
if(substr($script1,-1) == ","){
$script1 = substr($script1, 0, strlen($script1) - 1);
}
$script1 .= "];";
}
if($j % $inrow == 0){
$i++;
}
$j++;
}
Here is the tested result:
fileList["thumbs"][1]=[".AndroidStudio1.3",".ICEauthority",".PlayOnLinux",".Skype",".Xauthority",".adobe"];
fileList["thumbs"][2]=[".android",".audacity-data",".bash_history",".bashrc",".bibletime",".cache"];
fileList["thumbs"][3]=[".claws-mail",".config",".dbus",".directory",".dmrc",".dosbox"];
fileList["thumbs"][4]=[".emacs",".esd_auth",".fltk",".fontconfig",".fonts",".fonts.conf"];
fileList["thumbs"][5]=[".frozen-bubble",".gimp-2.8",".gnome",".gnome2",".gnome2_private",".gnupg"];
fileList["thumbs"][6]=[".gstreamer-0.10",".gtkrc-2.0",".gvfs",".icewm",".inputrc",".ivy2"];
fileList["thumbs"][7]=[".java",".jsword",".kde",".kde4",".kismet",".local"];
fileList["thumbs"][8]=[".macromedia",".mozilla",".mplayer",".mtpaint",".opera",".pki"];
fileList["thumbs"][9]=[".profile",".putty",".pyhistory",".qt",".remmina",".sbt"];
fileList["thumbs"][10]=[".skel",".ssh",".streamtuner",".sword",".themes",".thumbnails"];
fileList["thumbs"][11]=[".thunderbird",".vnc",".wine",".xboardrc",".xdg_menu_cache",".xim.template"];
fileList["thumbs"][12]=[".xinitrc.template",".xiphos",".xscreensaver",".xsession-errors",".xsession-errors-192.168.1.101:1",".xsession-errors-192.168.1.103:1"];
fileList["thumbs"][13]=[".xsession-errors-:0",".xsession-errors-:1",".y2log",".y2usersettings","20150901_134031.jpg","281436_wpmu-dev-dashboard-3.5.3.zip"];
fileList["thumbs"][14]=["Android","AndroidStudioProjects","Bible Analyzer User Modules","Calibre Library","Desktop","Documents"];
fileList["thumbs"][15]=["Downloads","Java","Kismet-20141124-23-54-29-1.alert","Kismet-20141124-23-54-29-1.gpsxml","Kismet-20141124-23-54-29-1.nettxt","Kismet-20141124-23-54-29-1.netxml"];
fileList["thumbs"][16]=["Kismet-20141124-23-54-29-1.pcapdump","Movies","Music","Phpgtk","Pictures","PlayOnLinux's virtual drives"];
fileList["thumbs"][17]=["Public","Templates","Videos","VirtualBox VMs","WPMUDEV_PLUGINS.zip","battery"];
fileList["thumbs"][18]=["bibleanalyzer","bibledesktop-2.0-beta","bin","ca.key","deklaracia.jpg","deklaracia2.jpg"];
fileList["thumbs"][19]=["dfc","http:⁄⁄www.biblestudytools.com⁄niv⁄.desktop","konq","projects","public_html","scala"];
fileList["thumbs"][20]=["somefile","somefile.txt","viber","wget-log","wp-cron.php?import_key=d&import_id=20&action=processing","Запис0003.amr"];
you need to change below part
$index = 1;
foreach($thumbarray as $item) {
$script .= "fileList[\"thumbs\"][$index]= ".json_encode($item).";" ;
$index++;
}
You need two indexes. $i is incremented every time $i is deleted in $inrow times properly with the remainder of 0. If you want 6 rows of files then $i should be increased 6 times less then $j which is increased every time. This way $i would change when $j is 6,12,18,24 and etc. You will need to play a little bit with the code ...
$script1 = "";
$i = 0;
$j = 0
$inrow = 6; // files in row
foreach($thumbarray as $item => $itemv) {
// beginning of the row
if($j % $inrow == 0){
$script1 .= "fileList[\"thumbs\"][".($i+1)."]=[";
}
$script1 .= "\"" . $itemv . "\","; // add filename "863_example_r048.mp4",
// end of the row
if($j % $inrow == 0){
// Delete comma at end of row
if(substr($script1,-1) == ","){
$script1 = substr($script1, 0, strlen($script1) - 1);
}
$script1 .= "]";
$i++;
}
$j++;
}

Detect time from Wordpress

i hope this is the correct place to ask this. I'm working with a Wordpress theme which detects opening times of a business from a custom field, compares it to the current day and time and then displays a message to say if the business is currently open. This works perfectly in English, but when i change the site language to Spanish using qTranslate X Plugin, the business permanently appears as not open. I really have limited skills at this kinda thing, so i'm hoping someone can advise me.
From what i can see this is the js that does the comparison.
<?php
/* ============== Check TIme ============ */
if (!function_exists('listingpro_check_time')) {
function listingpro_check_time($postid,$status = false) {
$output='';
$buisness_hours = listing_get_metabox_by_ID('business_hours', $postid);
if(!empty($buisness_hours)){
if(!empty($postid)){
$lat = listing_get_metabox_by_ID('latitude',$postid);
$long = listing_get_metabox_by_ID('longitude',$postid);
}
//$timezone = getClosestTimezone($lat, $long);
$timezone = get_option('gmt_offset');
$time = gmdate("H:i", time() + 3600*($timezone+date("I")));
$day = gmdate("l");
$time = strtotime($time);
$lang = get_locale();
setlocale(LC_ALL, $lang.'.utf-8');
$day = strftime("%A");
$day = ucfirst($day);
foreach($buisness_hours as $key=>$value){
if($day == $key){
$dayName = esc_html__('Today','listingpro');
}else{
$dayName = $key;
}
$open = $value['open'];
$open = str_replace(' ', '', $open);
$close = $value['close'];
$close = str_replace(' ', '', $close);
$open = strtotime($open);
$close = strtotime($close);
$newTimeOpen = date('h:i A', $open);
$newTimeClose = date('h:i A', $close);
if($day == $key){
if($time > $open && $time < $close){
if($status == false){
$output = '<span class="grid-opened">'.esc_html__('Open Now~','listingpro').'</span>';
}else{
$output = 'open';
}
}else{
if($status == false){
$output = '<span class="grid-closed">'.esc_html__('Closed Now!','listingpro').'</span>';
}else{
$output = 'close';
}
}
}
}
}else{
if($status == true){
$output = 'open';
}
}
return $output;
}
}
Any direction would be greatly appreciated.

Select data from oracle and draw a chart using Google charts?

I want to select data from oracle and draw the chart but when I run the my code nothing else drawed.new3.php:
$tns2 = "(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)) (CONNECT_DATA = (SID = CLUSTDB1)))";
if ($conn = oci_connect("CAKTAS","******", $tns2)) {
echo "";
$stid = oci_parse($conn, "select wonum,STATUS, trunc( (sysdate-STATUSDATE) ) || 'd ' || trunc( mod((sysdate-STATUSDATE)*24,24) ) || ':' || trunc( mod( (sysdate-STATUSDATE)*24*60, 60 ) ) from maximo.WORKORDER_IT_VIEW where VFOPMGRGRP = 'IS_PRICHARHG' and STATUS <> 'COMPLETE' and STATUS <> 'CLOSE'");
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
echo json_encode($row);
} else {
die("could not connect to Maximo DB");
}
And it gives me correct array.
My html code:
<html>
<head>
<title>Kometschuh.de Tracker</title>
<!-- Load jQuery -->
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it
<script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
<!-- Load Google JSAPI -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "new3.php", //my getting data php file
dataType: "json",
async: false
}).responseText;
var obj = window.JSON.stringify(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'Kometschuh.de Trackerdaten'
};
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
var chart = new google.visualization.LineChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;">
</div>
</body>
</html>
but in browser, I couldnt any chart
Refer my blog: http://howdyharish.wordpress.com/2014/08/11/create-google-charts-using-php-and-oracle-database/#more-3
Here is the code.
Index.php
<?php
ini_set(‘max_execution_time’, 123456);
$conn=oci_connect(‘username‘,’password‘,’DBname‘);
If (!conn)
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$query= oci_parse($conn, “select col1, col2 from tablename“);
oci_execute($query);
$rows = array();
$table = array();
$table['cols'] = array(
array(‘label’ => ‘col1‘, ‘type’ => ‘string‘),
array(‘label’ => ‘col2‘, ‘type’ => ‘number‘),
);
$rows = array();
while($r = oci_fetch_array($query, OCI_ASSOC+OCI_RETURN_NULLS)) {
$temp = array();
//The below col names have to be in upper caps.
echo $r["COL1"];
$temp[] = array(‘v’ => (string) $r["COL1"]);
$temp[] = array(‘v’ => (int) $r["COL2"]);
$rows[] = array(‘c’ => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//Use the line below to see the data in jason format
//echo $jsonTable;
//Use the below lines of code to see data in a HTML table
/*echo “<table border=’1′ >\n”;
echo “<tr><th>col1</th><th>col2</th></tr>\n”;
while ($row = oci_fetch_array($query, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo “<tr>\n “;
foreach ($query as $block) {
echo ” <td>” . ($block !== null ? htmlentities($block, ENT_QUOTES) : “ ”) . “</td>\n”;
}
echo “</tr>\n”;
}
echo “</table>\n”; */
?>
//In head section
<!–Load the Ajax API–>
<script type=”text/javascript” src=”https://www.google.com/jsapi”></script>
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js”></script>
<script type=”text/javascript”>
google.load(‘visualization’, ‘1’, {‘packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: ‘name of the chart‘,
is3D: ‘true’,
width: 1000,
height: 600,
fontName: ‘Times-Roman‘,
fontSize: 23,
hAxis: {textStyle: {
fontName: ‘Times-Roman‘,
fontSize: ‘25‘ }}
};
//To create a line chart
var chart = new google.visualization.LineChart(document.getElementById(‘chart_div’));
chart.draw(data, options);
//To create a column chart
var chart2 = new google.visualization.ColumnChart(document.getElementById(‘chart_div2′));
chart2.draw(data, options);
}
</script>
// In body section
<!–this is the div that will hold the pie chart–>
<div id=”chart_div” ></div>
<div id=”chart_div2″ ></div>
You cannot just use json_encode, the PHP output needs to be in the format that the Google API will understand (Google Documentation Here). So basically, you need to have some kind of function in php that transforms the OCI results into a JSON string readable by Google.
I have published a solution that works pretty well in my setup, other users might benefit from it. You can see my code on GitHub:
https://github.com/ernestomonroy/PHP-for-Google-Visualization-API
The php code looks as folows:
<?php
/*
* #author Ernesto Monroy <ehmizmg#gmail.com>
* #version 1.0
* This function takes the Connection Details and the SQL String and creates an two arrays, one for the column info
* and one for the row data. This is then passed to the arrayToGoogleDataTable that builds and outputs the JSON string
*
* Input for this is:
* $un: User Name
* $pw: Password
* $db: Connection String for the DB
* (e.g. '(DESCRIPTION=(CID=MyDB)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521)))(CONNECT_DATA=(SID=MyDB)))' )
* (tip, if you are running your PHP and Oracle Instance on the same server 127.0.0.1 should be used)
*
* WARNINGS:
* -I have not included any Oracle Error Handling
* -I have not included any row limit, so if your query returns an unmanageable amount of rows, it may become an issue for you or your web users.
*FUTURE OPPORTUNITIES:
* -This functions only return type and label properties. If you want to use pattern, id or p (for styling) you can add a check when looping through the columns
* and try to detect a particular column name that you define as the property (EG. if oci_field_name($stid, $i)=="GOOGLE_P_DATA" then ....)
*/
function getSQLDataTable($un,$pw,$db,$SQLString){
$conn=oci_connect($un,$pw,$db);
$stid= oci_parse($conn, "ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
oci_execute($stid);
$stid= oci_parse($conn, $SQLString);
oci_execute($stid);
$ncols = oci_num_fields($stid);
$cols = array();
$rows = array();
$cell = array();
for ($i = 1; $i <= $ncols; $i++) {
$column_label = '"'.oci_field_name($stid, $i).'"';
$column_type = oci_field_type($stid, $i);
switch($column_type) {
case 'CHAR': case 'VARCHAR2':
$column_type='"string"';
break;
case 'DATE':
$column_type='"datetime"';
break;
case 'NUMBER':
$column_type='"number"';
break;
}
$cols[$i-1]=array('"type"'=>$column_type,'"label"'=>$column_label);
}
$j=0;
while (($row = oci_fetch_array($stid, OCI_NUM+OCI_RETURN_NULLS)) != false) {
for ($i = 0; $i <= $ncols-1; $i++) {
switch(oci_field_type($stid, $i+1)) {
case 'CHAR': case 'VARCHAR2':
$cellValue='"'.$row[$i].'"';
$cellFormat='"'.$row[$i].'"';
break;
case 'DATE':
if($row[$i]==null){
$cellValue='""';
$cellFormat='""';
} else {
$cellValue=convertGoogleDate(date_create($row[$i]));
$cellFormat='"'.date_format(date_create($row[$i]), 'd/m/Y H:i:s').'"';
}
break;
case 'NUMBER':
$cellValue=number_format($row[$i], 2, '.', '');
$cellFormat='"'.$row[$i].'"';
break;
} //end of switch
$cell[$i]=array('"v"'=>$cellValue,'"f"'=>$cellFormat);
}
$rows[$j]=$cell;
$j++;
}
arrayToGoogleDataTable($cols, $rows);
}
/*This function takes in the columns and rows created in the previous function and returns the JSON String*/
function arrayToGoogleDataTable($cols, $rows) {
//Convert column array into google string literal
echo "{\n";
echo "\t".'"cols"'.": [\n";
for($i = 0; $i < count($cols)-1; $i++) {
echo "\t\t{";
$n=count($cols[$i]);
foreach($cols[$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "},\n";
}
//Last column without ending comma (},)
echo "\t\t{";
$n=count($cols[$i]);
foreach($cols[$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "}\n\t]";
//Now do the rows
//Check if empty first
if (count($rows)>0){
echo ",\n\t".'"rows"'.": [\n";
//For each row
for($j = 0; $j < count($rows)-1; $j++) {
echo "\t\t{".'"c":[';
//For each cell
for($i = 0; $i < count($rows[$j])-1; $i++) {
echo "{";
$n=count($rows[$j][$i]);
foreach($rows[$j][$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "},";
}
//Last column without ending comma (},)
$n=count($rows[$j][$i]);
echo "{";
foreach($rows[$j][$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "}]},\n";
}
//Last row
echo "\t\t{".'"c":[';
//For each cell
for($i = 0; $i < count($rows[$j])-1; $i++) {
echo "{";
$n=count($rows[$j][$i]);
foreach($rows[$j][$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "},";
}
$n=count($rows[$j][$i]);
echo "{";
foreach($rows[$j][$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "}]}\n";
echo "\t]";
}
echo"\n}";
}
/*This simply takes in a Date and converts it to a string that the google API recognizes as a Date*/
function convertGoogleDate(DateTime $inDate) {
$googleString='"Date(';
$googleString=$googleString.date_format($inDate, 'Y').',';
$googleString=$googleString.(date_format($inDate, 'm')-1).',';
$googleString=$googleString.(date_format($inDate, 'd')*1).',';
$googleString=$googleString.(date_format($inDate, 'H')*1).',';
$googleString=$googleString.(date_format($inDate, 'i')*1).',';
$googleString=$googleString.(date_format($inDate, 's')*1).')"';
return $googleString;
}
?>
For the rest of the implementation on Java and HTML check the git repo posted above
I know its a late reply, but still a top hit on Google and I have been asked the question a couple of times

Categories