Merged changes from main trunk up to 2.2.5
[fa-stable.git] / includes / ui / ui_view.inc
1 <?php
2 /**********************************************************************
3     Copyright (C) FrontAccounting, LLC.
4         Released under the terms of the GNU General Public License, GPL, 
5         as published by the Free Software Foundation, either version 3 
6         of the License, or (at your option) any later version.
7     This program is distributed in the hope that it will be useful,
8     but WITHOUT ANY WARRANTY; without even the implied warranty of
9     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
10     See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
12 include_once($path_to_root . "/admin/db/voiding_db.inc");
13 include_once($path_to_root . "/includes/types.inc");
14
15 //--------------------------------------------------------------------------------------
16
17 function get_supplier_trans_view_str($type, $trans_no, $label="", $icon=false, 
18         $class='', $id='')
19 {
20         $viewer = "purchasing/view/";
21         if ($type == ST_PURCHORDER)
22                 $viewer .= "view_po.php";
23         elseif ($type == ST_SUPPINVOICE)
24                 $viewer .= "view_supp_invoice.php";
25         elseif ($type == ST_SUPPCREDIT)
26                 $viewer .= "view_supp_credit.php";
27         elseif ($type == ST_SUPPAYMENT)
28                 $viewer .= "view_supp_payment.php";
29         elseif ($type == ST_SUPPRECEIVE)
30                 $viewer .= "view_grn.php";
31         else
32                 return null;
33         $viewer .= "?trans_no=$trans_no";
34
35         if ($label == "")
36                 $label = $trans_no;
37
38         return viewer_link($label, $viewer, $class, $id,  $icon);
39 }
40
41 //--------------------------------------------------------------------------------------
42
43 function get_gl_view_str($type, $trans_no, $label="", $force=false, $class='', $id='')
44 {
45         if (!$force && !user_show_gl_info())
46                 return "";
47
48         $icon = false;
49         if ($label == "")
50         {
51                 $label = _("GL");
52                 $icon = ICON_GL;
53         }       
54
55         return viewer_link($label, 
56                 "gl/view/gl_trans_view.php?type_id=$type&trans_no=$trans_no", 
57                 $class, $id, $icon);
58 }
59
60 //--------------------------------------------------------------------------------------
61
62 function get_gl_view_str_cell($type, $trans_no, $label="")
63 {
64         $str = get_gl_view_str($type, $trans_no, $label);
65         if ($str != "")
66                 return "<td>$str</td>";
67 }
68
69 //--------------------------------------------------------------------------------------
70
71 function get_customer_trans_view_str($type, $trans_no, $label="", $icon=false, 
72         $class='', $id='')
73 {
74         $viewer = "sales/view/";
75
76         if ($type == ST_SALESINVOICE)
77                 $viewer .= "view_invoice.php";
78         elseif ($type == ST_CUSTCREDIT)
79                 $viewer .= "view_credit.php";
80         elseif ($type == ST_CUSTPAYMENT)
81                 $viewer .= "view_receipt.php";
82         elseif ($type == ST_CUSTDELIVERY)
83                 $viewer .= "view_dispatch.php";
84         elseif ($type == ST_SALESORDER || $type == ST_SALESQUOTE)
85                 $viewer .= "view_sales_order.php";
86         else
87                 return null;
88
89   if(!is_array($trans_no)) $trans_no = array($trans_no);
90
91   $lbl = $label;
92   $preview_str = '';
93
94   foreach($trans_no as $trans) {
95         if ($label == "")
96                 $lbl = $trans;
97         if($preview_str!='') $preview_str .= ',';
98
99         $preview_str .= viewer_link($lbl, $viewer."?trans_no=$trans&trans_type=$type", 
100                 $class, $id, $icon);
101
102   }
103   return $preview_str;
104 }
105
106 //--------------------------------------------------------------------------------------
107
108 function get_banking_trans_view_str($type, $trans_no, $label="", 
109         $icon=false, $class='', $id='')
110 {
111         if ($label == "")
112                 $label = $trans_no;
113
114         if ($type == ST_BANKTRANSFER)
115                 $viewer = "bank_transfer_view.php";
116         elseif ($type == ST_BANKPAYMENT)
117                 $viewer = "gl_payment_view.php";
118         elseif ($type == ST_BANKDEPOSIT)
119                 $viewer = "gl_deposit_view.php";
120         else
121                 return null;
122
123         return viewer_link($label, "gl/view/$viewer?trans_no=$trans_no", 
124                 $class, $id,  $icon);
125 }
126
127 //--------------------------------------------------------------------------------------
128
129 function get_inventory_trans_view_str($type, $trans_no, $label="", 
130         $icon=false, $class='', $id='')
131 {
132         $viewer = "inventory/view/";
133
134         if ($type == ST_INVADJUST)
135                 $viewer .= "view_adjustment.php";
136         elseif ($type == ST_LOCTRANSFER)
137                 $viewer .= "view_transfer.php";
138         else
139                 return null;
140         $viewer .= "?trans_no=$trans_no";
141
142         if ($label == "")
143                 $label = $trans_no;
144
145         return viewer_link($label, $viewer, $class, $id,  $icon);
146 }
147
148 //--------------------------------------------------------------------------------------
149
150 function get_manufacturing_trans_view_str($type, $trans_no, $label="", 
151         $icon=false, $class='', $id='')
152 {
153         $viewer = "manufacturing/view/";
154
155         if ($type == ST_MANUISSUE)
156                 $viewer .= "wo_issue_view.php";
157         elseif ($type == ST_MANURECEIVE)
158                 $viewer .= "wo_production_view.php";
159         elseif ($type == ST_WORKORDER)
160                 $viewer .= "work_order_view.php";
161         else
162                 return null;
163
164         $viewer .= "?trans_no=$trans_no";
165
166         if ($label == "")
167                 $label = $trans_no;
168
169         return viewer_link($label, $viewer, $class, $id,  $icon);
170 }
171
172 //--------------------------------------------------------------------------------------
173
174 function get_dimensions_trans_view_str($type, $trans_no, $label="", $icon=false, 
175         $class='', $id='')
176 {
177         if ($type == ST_DIMENSION)
178                 $viewer = "dimensions/view/view_dimension.php?trans_no=$trans_no";
179         else
180                 return null;
181
182         if ($label == "")
183                 $label = $trans_no;
184
185         return viewer_link($label, $viewer, $class, $id,  $icon);
186 }
187 /*
188         Journal entry or cost update postings link
189 */
190 function get_journal_trans_view_str($type, $trans_no, $label="", $icon=false, 
191         $class='', $id='')
192 {
193         if ($type == ST_JOURNAL || $type == ST_COSTUPDATE)
194                 $viewer = "gl/view/gl_trans_view.php?type_id=$type&trans_no=$trans_no";
195         else
196                 return null;
197
198         if ($label == "")
199                 $label = $trans_no;
200
201         return viewer_link($label, $viewer, $class, $id,  $icon);
202 }
203
204 //--------------------------------------------------------------------------------------
205
206 function get_trans_view_str($type, $trans_no, $label="", $icon=false, 
207         $class='', $id='')
208 {
209         $view_str = get_customer_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
210         if ($view_str != null)
211                 return $view_str;
212
213         $view_str = get_supplier_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
214         if ($view_str != null)
215                 return $view_str;
216
217         $view_str = get_banking_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
218         if ($view_str != null)
219                 return $view_str;
220
221         $view_str = get_inventory_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
222         if ($view_str != null)
223                 return $view_str;
224
225         $view_str = get_manufacturing_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
226         if ($view_str != null)
227                 return $view_str;
228
229         $view_str = get_dimensions_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
230         if ($view_str != null)
231                 return $view_str;
232
233         $view_str = get_journal_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
234         if ($view_str != null)
235                 return $view_str;
236
237         return null;
238 }
239
240 //--------------------------------------------------------------------------------------
241 // Displays currency exchange rate for given date.
242 // When there is no exrate for today, 
243 // gets it form ECB and stores in local database.
244 //
245 function exchange_rate_display($from_currency, $to_currency, $date_, $edit_rate=false)
246 {
247     global $Ajax;
248
249         if ($from_currency != $to_currency)
250         {
251                 $comp_currency = get_company_currency();
252                 if ($from_currency == $comp_currency)
253                         $currency = $to_currency;
254                 else
255                         $currency = $from_currency;
256                 $rate = 0;
257                 if ($date_ == Today()) {
258                         $rate = get_date_exchange_rate($currency, $date_);
259                         if (!$rate) {
260                                 $row = get_currency($currency);
261                                 if ($row['auto_update']) {
262                                         $rate = retrieve_exrate($currency, $date_);
263                                         if ($rate) 
264                                                 add_exchange_rate($currency, $date_, $rate, $rate);
265                                 }
266                         }
267                 }
268                 if (!$rate)
269                         $rate = get_exchange_rate_from_home_currency($currency, $date_);
270                 if ($from_currency != $comp_currency)
271                         $rate = 1 / ($rate / get_exchange_rate_from_home_currency($to_currency, $date_));
272
273                 $rate = number_format2($rate, user_exrate_dec());
274                 if ($edit_rate)
275                         text_row(_("Exchange Rate:"), '_ex_rate', $rate, 8, 8, null, "", " $from_currency = 1 $to_currency"); 
276                 else
277                 label_row(_("Exchange Rate:"),"<span style='vertical-align:top;' id='_ex_rate'>$rate</span> $from_currency = 1 $to_currency" );
278                 $Ajax->addUpdate('_ex_rate','_ex_rate', $rate);
279         }
280 }
281
282 //--------------------------------------------------------------------------------------
283
284 function is_voided_display($type, $id, $label)
285 {
286         global $table_style;
287         $void_entry = get_voided_entry($type, $id);
288
289         if ($void_entry == null)
290                 return false;
291
292         start_table("width=50% $table_style");
293         echo "<tr><td align=center><font color=red>$label</font><br>";
294         echo "<font color=red>" . _("Date Voided:") . " " . sql2date($void_entry["date_"]) . "</font><br>";
295         if (strlen($void_entry["memo_"]) > 0)
296                 echo "<center><font color=red>" . _("Memo:") . " " . $void_entry["memo_"] . "</font></center><br>";
297         echo "</td></tr>";
298         end_table(1);
299
300         return true;
301 }
302
303 //--------------------------------------------------------------------------------------
304
305 function comments_display_row($type, $id)
306 {
307         $comments = get_comments($type, $id);
308         if ($comments and db_num_rows($comments))
309         {
310                 echo "<tr><td colspan=15>";
311         while ($comment = db_fetch($comments))
312         {
313                 echo $comment["memo_"] . "<br>";
314         }
315                 echo "</td></tr>";
316         }
317 }
318
319 //--------------------------------------------------------------------------------------
320
321 function get_comments_string($type, $type_no)
322 {
323         $str_return = "";
324         $result = get_comments($type, $type_no);
325         while ($comment = db_fetch($result))
326         {
327                 if (strlen($str_return))
328                         $str_return = $str_return . " \n";
329                 $str_return = $str_return . $comment["memo_"];
330         }
331         return $str_return;
332 }
333
334 //--------------------------------------------------------------------------------------
335
336 function view_stock_status($stock_id, $description=null, $echo=true)
337 {
338         global $path_to_root;
339         if ($description)
340                 //hyperlink_params_separate($path_to_root . "/inventory/inquiry/stock_status.php", (user_show_codes()?$stock_id . " - ":"") . $description, "stock_id=$stock_id");
341                 $preview_str = "<a target='_blank' href='$path_to_root/inventory/inquiry/stock_status.php?stock_id=$stock_id' onclick=\"javascript:openWindow(this.href,this.target); return false;\" >". (user_show_codes()?$stock_id . " - ":"") . $description."</a>";
342         else
343                 //hyperlink_params_separate($path_to_root . "/inventory/inquiry/stock_status.php", $stock_id, "stock_id=$stock_id");
344                 $preview_str = "<a target='_blank' href='$path_to_root/inventory/inquiry/stock_status.php?stock_id=$stock_id' onclick=\"javascript:openWindow(this.href,this.target); return false;\" >$stock_id</a>";
345         if($echo)
346                 echo $preview_str;
347         return $preview_str;
348 }
349
350 function view_stock_status_cell($stock_id, $description=null)
351 {
352         echo "<td>";
353         view_stock_status($stock_id, $description);
354         echo "</td>";
355 }
356
357 //--------------------------------------------------------------------------------------
358
359 function display_debit_or_credit_cells($value)
360 {
361         $value = round2($value, user_price_dec());
362         if ($value >= 0)
363         {
364                 amount_cell($value);
365                 label_cell("");
366         }
367         elseif ($value < 0)
368         {
369                 label_cell("");
370                 amount_cell(abs($value));
371         }
372 }
373
374 //--------------------------------------------------------------------------------------
375
376 function display_customer_trans_tax_details($tax_items, $columns)
377 {
378     while ($tax_item = db_fetch($tax_items))
379     {
380         $tax = number_format2($tax_item['amount'],user_price_dec());
381         if ($tax_item['included_in_price'])
382                 label_row(_("Included") . " " . $tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%) " .
383                         _("Amount") . ": $tax", "", "colspan=$columns align=right", "align=right");
384         else
385                 label_row($tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%)",
386                         $tax, "colspan=$columns align=right", "align=right");
387     }
388 }
389
390 //--------------------------------------------------------------------------------------
391
392 function display_supp_trans_tax_details($tax_items, $columns)
393 {
394     while ($tax_item = db_fetch($tax_items))
395     {
396         $tax = number_format2(abs($tax_item['amount']),user_price_dec());
397         if ($tax_item['included_in_price'])
398                 label_row(_("Included") . " " . $tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%) " .
399                         _("Amount") . ": $tax", "colspan=$columns align=right", "align=right");
400         else
401                 label_row($tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%)",
402                         $tax, "colspan=$columns align=right", "align=right");
403     }
404 }
405
406 //--------------------------------------------------------------------------------------
407
408 function display_edit_tax_items($taxes, $columns, $tax_included, $leftspan=0)
409 {
410         $total = 0;
411
412     foreach ($taxes as $taxitem)
413     {
414         if ($tax_included)
415         {
416                 label_row(_("Included") . " " . $taxitem['tax_type_name'] . " (" . $taxitem['rate'] . "%) " .
417                         _("Amount:") . " " . number_format2($taxitem['Value'],user_price_dec()), "", "colspan=$columns align=right", "align=right",$leftspan);
418         }
419         else
420         {
421                 label_row($taxitem['tax_type_name'] . " (" . $taxitem['rate'] . "%)",
422                         number_format2($taxitem['Value'],user_price_dec()), "colspan=$columns align=right", "align=right",$leftspan);
423                 $total +=  round2($taxitem['Value'], user_price_dec());
424         }
425     }
426
427     return $total;
428 }
429
430 //--------------------------------------------------------------------------------------
431
432 function display_footer_exit()
433 {
434         br(2);
435         end_page(false, false, true);
436         exit;
437 }
438
439 //--------------------------------------------------------------------------------------
440
441 function display_allocations($alloc_result, $total)
442 {
443         global $table_style, $systypes_array;
444
445         if (!$alloc_result || db_num_rows($alloc_result) == 0)
446                 return;
447
448     display_heading2(_("Allocations"));
449
450     start_table("$table_style width=80%");
451
452     $th = array( _("Type"), _("Number"), _("Date"), _("Total Amount"),
453         _("Left to Allocate"), _("This Allocation"));
454         table_header($th);
455     $k = $total_allocated = 0;
456
457     while ($alloc_row = db_fetch($alloc_result))
458     {
459
460         alt_table_row_color($k);
461
462         label_cell($systypes_array[$alloc_row['type']]);
463         label_cell(get_trans_view_str($alloc_row['type'],$alloc_row['trans_no']));
464         label_cell(sql2date($alloc_row['tran_date']));
465         $alloc_row['Total'] = round2($alloc_row['Total'], user_price_dec());
466         $alloc_row['amt'] = round2($alloc_row['amt'], user_price_dec());
467         amount_cell($alloc_row['Total']);
468         //amount_cell($alloc_row['Total'] - $alloc_row['PrevAllocs'] - $alloc_row['amt']);
469         amount_cell($alloc_row['Total'] - $alloc_row['amt']);
470         amount_cell($alloc_row['amt']);
471         end_row();
472
473         $total_allocated += $alloc_row['amt'];
474     }
475     start_row();
476         label_cell(_("Total Allocated:"), "align=right colspan=5");
477         amount_cell($total_allocated);
478         end_row();
479         start_row();
480     label_cell(_("Left to Allocate:"), "align=right colspan=5");
481     $total = round2($total, user_price_dec());
482     amount_cell($total - $total_allocated);
483     end_row();
484
485     end_table(1);
486 }
487
488 //--------------------------------------------------------------------------------------
489
490 function display_allocations_from($person_type, $person_id, $type, $type_no, $total)
491 {
492         switch ($person_type)
493         {
494                 case PT_CUSTOMER :
495                         $alloc_result = get_allocatable_to_cust_transactions($person_id, $type_no, $type);
496                         display_allocations($alloc_result, $total);
497                         return;
498                 case PT_SUPPLIER :
499                         $alloc_result = get_allocatable_to_supp_transactions($person_id, $type_no, $type);
500                         display_allocations($alloc_result, $total);
501                         return;
502         }
503 }
504
505 //--------------------------------------------------------------------------------------
506 //
507 //      Expands selected quick entry $id into GL posings and adds to cart.
508 //              returns calculated amount posted to bank GL account.
509 //
510 function display_quick_entries(&$cart, $id, $base, $type, $descr='')
511 {
512         $bank_amount = 0;
513         
514         if (!isset($id) || $id == null || $id == "")
515         {
516                 display_error( _("No Quick Entries are defined."));
517                 set_focus('totamount');
518         }
519         else
520         {
521                 if ($type == QE_DEPOSIT)
522                         $base = -$base;
523                 if ($type != QE_SUPPINV)        // only one quick entry on journal/bank transaction
524                         $cart->clear_items();
525                 $qe = get_quick_entry($id);
526                 if ($qe['bal_type'] == 1)
527                 {
528                         if ($qe['base_amount'] == 1.0) // monthly
529                                 $begin = begin_month($cart->tran_date);
530                         else
531                         {
532                                 if (is_account_balancesheet($qe['base_desc'])) // total
533                                         $begin = "";
534                                 else
535                                         $begin = begin_fiscalyear(); // from fiscalyear begin
536                         }               
537                         $base = get_gl_trans_from_to($begin, $cart->tran_date, $qe['base_desc']);
538                                 
539                 }
540                 if ($descr != '') $qe['description'] .= ': '.$descr;
541                 $result = get_quick_entry_lines($id);
542                 if (db_num_rows($result) == 0)
543                 {
544                         display_error( _("No Quick Entry lines are defined."));
545                         set_focus('totamount');
546                 }       
547                 $totrate = 0;
548                 while ($row = db_fetch($result))
549                 {
550                         $qe_lines[] = $row;
551
552                         switch (strtolower($row['action'])) {
553                                 case "t": // post taxes calculated on base amount
554                                 case "t+": // ditto & increase base amount
555                                 case "t-": // ditto & reduce base amount
556                                         if (substr($row['action'],0,1) != 'T') 
557                                                 $totrate += get_tax_type_default_rate($row['dest_id']);
558                         }
559                 }
560                 $first = true;
561                 $taxbase = 0;
562                 foreach($qe_lines as $qe_line)
563                 {
564                         switch (strtolower($qe_line['action'])) {
565                                 case "=": // post current base amount to GL account
566                                         $part = $base;
567                                         break;
568                                 case "a": // post amount to GL account and reduce base
569                                         $part = $qe_line['amount'];
570                                         break;
571                                 case "a+": // post amount to GL account and increase base
572                                         $part = $qe_line['amount']; $base += $part;
573                                         break;
574                                 case "a-": // post amount to GL account and reduce base
575                                         $part = $qe_line['amount']; $base -= $part;
576                                         break;
577                                 case "%":       // store acc*amount% to GL account
578                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
579                                         break;
580                                 case "%+":      // ditto & increase base amount
581                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
582                                         $base += $part;
583                                         break;
584                                 case "%-":      // ditto & reduce base amount
585                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
586                                         $base -= $part;
587                                         break;
588                                 case "t": // post taxes calculated on base amount
589                                 case "t+": // ditto & increase base amount
590                                 case "t-": // ditto & reduce base amount
591                                         if ($first)
592                                         {
593                                                 $taxbase = $base/($totrate+100);
594                                                 $first = false;
595                                         }
596
597                                         if (substr($qe_line['action'],0,1) != 'T') 
598                                                 $part = $taxbase;
599                                         else
600                                                 $part = $base/100;
601                                         $item_tax = get_tax_type($qe_line['dest_id']);
602                                         //if ($type == QE_SUPPINV && substr($qe_line['action'],0,1) != 'T')
603                                         if ($type == QE_SUPPINV)
604                                         {
605                                                 $taxgroup = $cart->tax_group_id;
606                                                 $rates = 0;
607                                                 $res = get_tax_group_items($cart->tax_group_id);
608                                                 while ($row = db_fetch($res))
609                                                         $rates += $row['rate'];
610                                                 if ($rates == 0)
611                                                         continue 2;
612                                         }
613                                         $tax = round2($part * $item_tax['rate'],  user_price_dec());
614                                         if ($tax==0) continue 2;
615                                         $gl_code = ($type == QE_DEPOSIT || ($type == QE_JOURNAL && $base < 0)) 
616                                                 ? $item_tax['sales_gl_code'] : $item_tax['purchasing_gl_code'];
617                                         if (!is_tax_gl_unique($gl_code)) {
618                                                 display_error(_("Cannot post to GL account used by more than one tax type."));
619                                                 break 2;
620                                         }
621                                         if ($type != QE_SUPPINV)
622                                                 $cart->add_gl_item($gl_code, 
623                                                         $qe_line['dimension_id'], $qe_line['dimension2_id'], 
624                                                         $tax, $qe['description']);
625                                         else 
626                                         {
627                                                 $acc_name = get_gl_account_name($gl_code);
628                                                 $cart->add_gl_codes_to_trans($gl_code, 
629                                                         $acc_name, $qe_line['dimension_id'], 
630                                                         $qe_line['dimension2_id'], $tax, $qe['description']);
631                                         }
632                                         if (strpos($qe_line['action'], '+'))
633                                                 $base += $tax;
634                                         elseif (strpos($qe_line['action'], '-'))
635                                                 $base -= $tax;
636                                         continue 2;
637                         }
638                         if ($type != QE_SUPPINV)
639                                 $cart->add_gl_item($qe_line['dest_id'], $qe_line['dimension_id'],
640                                         $qe_line['dimension2_id'], $part, $qe['description']);
641                         else 
642                         {
643                                 $acc_name = get_gl_account_name($qe_line['dest_id']);
644                                 $cart->add_gl_codes_to_trans($qe_line['dest_id'], 
645                                         $acc_name, $qe_line['dimension_id'], 
646                                         $qe_line['dimension2_id'], $part, $qe['description']);
647                         }
648                 }
649         }       
650         return $bank_amount;
651 }
652
653 //--------------------------------------------------------------------------------------
654 //
655 //      Simple English version of number to words conversion.
656 //
657 function _number_to_words($number) 
658
659     $Bn = floor($number / 1000000000); /* Billions (giga) */ 
660     $number -= $Bn * 1000000000; 
661     $Gn = floor($number / 1000000);  /* Millions (mega) */ 
662     $number -= $Gn * 1000000; 
663     $kn = floor($number / 1000);     /* Thousands (kilo) */ 
664     $number -= $kn * 1000; 
665     $Hn = floor($number / 100);      /* Hundreds (hecto) */ 
666     $number -= $Hn * 100; 
667     $Dn = floor($number / 10);       /* Tens (deca) */ 
668     $n = $number % 10;               /* Ones */
669
670     $res = ""; 
671
672     if ($Bn) 
673         $res .= _number_to_words($Bn) . " Billion"; 
674     if ($Gn) 
675         $res .= (empty($res) ? "" : " ") . _number_to_words($Gn) . " Million"; 
676     if ($kn) 
677         $res .= (empty($res) ? "" : " ") . _number_to_words($kn) . " Thousand"; 
678     if ($Hn) 
679         $res .= (empty($res) ? "" : " ") . _number_to_words($Hn) . " Hundred"; 
680
681     $ones = array("", "One", "Two", "Three", "Four", "Five", "Six", 
682         "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", 
683         "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen", 
684         "Nineteen"); 
685     $tens = array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", 
686         "Seventy", "Eigthy", "Ninety"); 
687
688     if ($Dn || $n) 
689     { 
690         if (!empty($res)) 
691             $res .= " and "; 
692         if ($Dn < 2) 
693             $res .= $ones[$Dn * 10 + $n]; 
694         else 
695         { 
696             $res .= $tens[$Dn]; 
697             if ($n) 
698                 $res .= "-" . $ones[$n]; 
699         } 
700     } 
701
702     if (empty($res)) 
703         $res = "zero"; 
704     return $res; 
705
706
707 function price_in_words($amount, $document=0)
708 {
709         global $Hooks;
710         // use local price_in_words() if the hook is defined
711         if (method_exists($Hooks, 'price_in_words'))
712         {
713                 return $Hooks->price_in_words($amount, $document);
714         }
715         // Only usefor Remittance and Receipts as default
716         if (!($document == ST_SUPPAYMENT || $document == ST_CUSTPAYMENT || $document == ST_CHEQUE))
717                 return "";
718         if ($amount < 0 || $amount > 999999999999)
719                 return "";
720         $dec = user_price_dec();
721         if ($dec > 0)
722         {
723                 $divisor = pow(10, $dec);       
724                 $frac = round2($amount - floor($amount), $dec) * $divisor;
725                 $frac = sprintf("%0{$dec}d", $frac);
726                 $and = _("and");
727         $frac = " $and $frac/$divisor";
728     }
729     else
730         $frac = "";
731     return _number_to_words(intval($amount)) . $frac;
732 }    
733
734 function get_js_open_window($width, $height)
735 {
736         $js ="function openWindow(url, title)\n"
737                 . "{\n"
738                 . " var left = (screen.width - $width) / 2;\n"
739                 . " var top = (screen.height - $height) / 2;\n"
740                 . " return window.open(url, title, 'width=$width,height=$height,left='+left+',top='+top+',screenX='+left+',screenY='+top+',status=no,scrollbars=yes');\n"
741                 . "}\n";
742         return $js;
743 }
744
745 /*
746   Setting focus on element $name in $form.
747   If $form<0 $name is element id.
748 */
749 function set_focus($name, $form_no=0) {
750   global $Ajax;
751         $Ajax->addFocus(true, $name);
752     $_POST['_focus'] = $name;
753 }
754 //
755 //      Set default focus on first field $name if not set yet
756 //      Returns unique name if $name=null
757 //      
758 function default_focus($name=null, $form_no=0) {
759         static $next; 
760         if ($name==null) 
761                 $name = uniqid('_el',true);
762     if (!isset($_POST['_focus'])) {
763           set_focus($name);
764     }
765         return $name;
766 }
767 /*
768         Reset focus to next control element (e.g. link).
769 */
770 function reset_focus()
771 {
772         unset($_POST['_focus']);
773 }
774
775 function get_js_png_fix()
776 {
777         $js = "function fixPNG(myImage)\n"
778                 . "{\n"
779                 . " var arVersion = navigator.appVersion.split(\"MSIE\")\n"
780                 . " var version = parseFloat(arVersion[1])\n"
781         . " if ((version >= 5.5) && (version < 7) && (document.body.filters))\n"
782         . " {\n"
783         . "  var imgID = (myImage.id) ? \"id='\" + myImage.id + \"' \" : \"\"\n"
784                 . "  var imgClass = (myImage.className) ? \"class='\" + myImage.className + \"' \" : \"\"\n"
785                 . "  var imgTitle = (myImage.title) ?\n"
786                 . "    \"title='\" + myImage.title  + \"' \" : \"title='\" + myImage.alt + \"' \"\n"
787                 . "  var imgStyle = \"display:inline-block;\" + myImage.style.cssText\n"
788                 . "  var strNewHTML = \"<span \" + imgID + imgClass + imgTitle\n"
789         . "    + \" style=\\\"\" + \"width:\" + myImage.width\n"
790         . "    + \"px; height:\" + myImage.height\n"
791         . "    + \"px;\" + imgStyle + \";\"\n"
792         . "    + \"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader\"\n"
793         . "    + \"(src=\'\" + myImage.src + \"\', sizingMethod='scale');\\\"></span>\"\n"
794                 . "  myImage.outerHTML = strNewHTML\n"
795         . " }\n"
796                 . "}\n";
797         return $js;
798 }
799
800 function get_js_date_picker()
801 {
802     global $comp_path, $go_debug;
803     $fpath = $comp_path.'/'.user_company().'/js_cache/'.'date_picker.js';
804
805     if (!file_exists($fpath) || $go_debug) {
806
807         global $dateseps, $date_system;
808
809         $how = user_date_format();                              // 0 = us/ca, 1 = eu, au, nz, 2 = jp, sw
810         $sep = $dateseps[user_date_sep()];              // date separator
811         $wstart = (($date_system == 1 || $date_system == 2 || $date_system == 3) ? 6 : ($how == 0 ? 0 : 1));    // weekstart (sun = 0, mon = 1)
812         $months = array(_("January"),_("February"),_("March"),_("April"),_("May"),_("June"),_("July"),_("August"),_("September"),_("October"),_("November"),_("December"));
813         $wdays = array(_("Su"),_("Mo"),_("Tu"),_("We"),_("Th"),_("Fr"),_("Sa"));
814         $wno = _("W"); // week no
815         $back = _("Back");
816         if ($date_system == 1)
817                 list($cyear, $cmon, $cday) = gregorian_to_jalali(date("Y"), date("n"), date("j"));
818         else if ($date_system == 2)
819                 list($cyear, $cmon, $cday) = gregorian_to_islamic(date("Y"), date("n"), date("j"));
820
821
822         $js = "
823 function positionInfo(object) {
824   var p_elm = object;
825   this.getElementLeft = getElementLeft;
826   function getElementLeft() {
827     var x = 0;
828     var elm;
829     if(typeof(p_elm) == 'object'){
830       elm = p_elm;
831     } else {
832       elm = document.getElementById(p_elm);
833     }
834     while (elm != null) {
835       x+= elm.offsetLeft;
836       elm = elm.offsetParent;
837     }
838     return parseInt(x);
839   }
840   this.getElementWidth = getElementWidth;
841   function getElementWidth(){
842     var elm;
843     if(typeof(p_elm) == 'object'){
844       elm = p_elm;
845     } else {
846       elm = document.getElementById(p_elm);
847     }
848     return parseInt(elm.offsetWidth);
849   }
850   this.getElementRight = getElementRight;
851   function getElementRight(){
852     return getElementLeft(p_elm) + getElementWidth(p_elm);
853   }
854   this.getElementTop = getElementTop;
855   function getElementTop() {
856     var y = 0;
857     var elm;
858     if(typeof(p_elm) == 'object'){
859       elm = p_elm;
860     } else {
861       elm = document.getElementById(p_elm);
862     }
863     while (elm != null) {
864       y+= elm.offsetTop;
865       elm = elm.offsetParent;
866     }
867     return parseInt(y);
868   }
869   this.getElementHeight = getElementHeight;
870   function getElementHeight(){
871     var elm;
872     if(typeof(p_elm) == 'object'){
873       elm = p_elm;
874     } else {
875       elm = document.getElementById(p_elm);
876     }
877     return parseInt(elm.offsetHeight);
878   }
879   this.getElementBottom = getElementBottom;
880   function getElementBottom(){
881     return getElementTop(p_elm) + getElementHeight(p_elm);
882   }
883 }
884 function CC() {
885   var calendarId = 'CC';
886   var currentYear = 0;
887   var currentMonth = 0;
888   var currentDay = 0;
889   var selectedYear = 0;
890   var selectedMonth = 0;
891   var selectedDay = 0;
892   var months = ['$months[0]','$months[1]','$months[2]','$months[3]','$months[4]','$months[5]','$months[6]','$months[7]','$months[8]','$months[9]','$months[10]','$months[11]'];
893   var wdays = ['$wdays[0]', '$wdays[1]', '$wdays[2]', '$wdays[3]', '$wdays[4]', '$wdays[5]', '$wdays[6]'];
894   var dateField = null;
895   function getProperty(p_property){
896     var p_elm = calendarId;
897     var elm = null;
898     if(typeof(p_elm) == 'object'){
899       elm = p_elm;
900     } else {
901       elm = document.getElementById(p_elm);
902     }
903     if (elm != null){
904       if(elm.style){
905         elm = elm.style;
906         if(elm[p_property]){
907           return elm[p_property];
908         } else {
909           return null;
910         }
911       } else {
912         return null;
913       }
914     }
915   }
916   function setElementProperty(p_property, p_value, p_elmId){
917     var p_elm = p_elmId;
918     var elm = null;
919     if(typeof(p_elm) == 'object'){
920       elm = p_elm;
921     } else {
922       elm = document.getElementById(p_elm);
923     }
924     if((elm != null) && (elm.style != null)){
925       elm = elm.style;
926       elm[ p_property ] = p_value;
927     }
928   }
929   function setProperty(p_property, p_value) {
930     setElementProperty(p_property, p_value, calendarId);
931   }
932   function getDaysInMonth(year, month) {
933 ";
934         if ($date_system == 1)
935                 $js .= "
936     return [31,31,31,31,31,31,30,30,30,30,30,(((((((year - ((year > 0) ? 474 : 473)) % 2820) + 474) + 38) * 682) % 2816) < 682 ? 30 : 29)][month-1];
937 ";
938         else if ($date_system == 2)
939                 $js .= "
940     return [30,29,30,29,30,29,30,29,30,29,30,(((((11 * year) + 14) % 30) < 11) ? 30 : 29)][month-1];
941 ";
942         else
943                 $js .= "
944     return [31,((!(year % 4 ) && ( (year % 100 ) || !( year % 400 ) ))?29:28),31,30,31,30,31,31,30,31,30,31][month-1];
945 ";
946         $js .= "
947   }
948   function getDayOfWeek(year, month, day) {
949 ";
950         if ($date_system == 1 || $date_system == 2)
951         {
952                 $js .= "
953         function mod(a, b)
954         {
955             return a - (b * Math.floor(a / b));
956         }
957         function jwday(j)
958         {
959             return mod(Math.floor((j + 1.5)), 7);
960         }
961 ";
962         if ($date_system == 1)
963                 $js .= "
964     var epbase, epyear, t;
965     epbase = year - ((year >= 0) ? 474 : 473);
966     epyear = 474 + mod(epbase, 2820);
967     t = day + ((month <= 7) ? ((month - 1) * 31) : (((month - 1) * 30) + 6)) +
968       Math.floor(((epyear * 682) - 110) / 2816) + (epyear - 1) * 365 +
969       Math.floor(epbase / 2820) * 1029983 + (1948320.5 - 1);
970 ";
971         else if ($date_system == 2)
972                 $js .= "
973         var t;
974         t = Math.floor((11 * year + 3) / 30) + 354 * year + 30 * month -
975           Math.floor((month - 1) / 2) + day + 1948440 - 385;
976 ";
977         $js .= "
978     return jwday(t);
979 ";
980         }
981         else
982                 $js .= "
983     var date = new Date(year,month-1,day)
984     return date.getDay();
985 ";
986         $js .= "
987   }
988   this.clearDate = clearDate;
989   function clearDate() {
990     dateField.value = '';
991     hide();
992   }
993   this.getWeek = getWeek;
994   function getWeek(year, month, day) {
995 ";
996         if ($how == 0)
997                 $js .= "  day++;";
998         $js .= "
999     var date = new Date(year,month-1,day);
1000     var D = date.getDay();
1001     if(D == 0) D = 7;
1002     date.setDate(date.getDate() + (4 - D));
1003     var YN = date.getFullYear();
1004     var ZBDoCY = Math.floor((date.getTime() - new Date(YN, 0, 1, -6)) / 86400000);
1005     var WN = 1 + Math.floor(ZBDoCY / 7);
1006     return WN;
1007   }
1008   this.setDate = setDate;
1009   function setDate(year, month, day) {
1010     if (dateField) {
1011       if (month < 10) {month = '0' + month;}
1012       if (day < 10) {day = '0' + day;}
1013 ";
1014         if ($how == 0)
1015                 $js .= "
1016       var dateString = month+'$sep'+day+'$sep'+year;
1017 ";
1018         else if ($how == 1)
1019                 $js .= "
1020       var dateString = day+'$sep'+month+'$sep'+year;
1021 ";
1022         else
1023                 $js .= "
1024       var dateString = year+'$sep'+month+'$sep'+day;
1025 ";
1026         $js .= "
1027       dateField.value = dateString;
1028           setFocus(dateField.name);
1029         if(dateField.getAttribute('aspect')=='cdate')
1030       setElementProperty('color', (dateField.value==user.date ? 'black':'red'), dateField);
1031           if (dateField.className=='searchbox')
1032                 dateField.onblur();
1033       hide();
1034     }
1035     return;
1036   }
1037   this.changeMonth = changeMonth;
1038   function changeMonth(change) {
1039     currentMonth += change;
1040     currentDay = 0;
1041     if(currentMonth > 12) {
1042       currentMonth = 1;
1043       currentYear++;
1044     } else if(currentMonth < 1) {
1045       currentMonth = 12;
1046       currentYear--;
1047     }
1048     calendar = document.getElementById(calendarId);
1049     calendar.innerHTML = calendarDrawTable();
1050   }
1051   this.changeYear = changeYear;
1052   function changeYear(change) {
1053     currentYear += change;
1054     currentDay = 0;
1055     calendar = document.getElementById(calendarId);
1056     calendar.innerHTML = calendarDrawTable();
1057   }
1058   function getCurrentYear() {
1059     var year = new Date().getYear();
1060     if(year < 1900) year += 1900;
1061     return year;
1062   }
1063   function getCurrentMonth() {
1064     return new Date().getMonth() + 1;
1065   }
1066   function getCurrentDay() {
1067     return new Date().getDate();
1068   }
1069   function calendarDrawTable() {
1070     var dayOfMonth = 1;
1071     var wstart = $wstart;
1072     var wno = '&nbsp;$wno&nbsp;';
1073     var validDay = 0;
1074     var startDayOfWeek = getDayOfWeek(currentYear, currentMonth, dayOfMonth);
1075     var daysInMonth = getDaysInMonth(currentYear, currentMonth);
1076     var css_class = null; //CSS class for each day
1077     var table = \"<table cellspacing='0' cellpadding='0' border='0'>\";
1078     table += \"<tr class='header'>\";
1079     table += \"  <td colspan='2' class='previous'><a href='javascript:changeCCMonth(-1);'>&lt;</a><br><a href='javascript:changeCCYear(-1);'>&laquo;</a></td>\";
1080     table += \"  <td colspan='4' class='title'>\" + months[currentMonth-1] + \"<br>\" + currentYear + \"</td>\";
1081     table += \"  <td colspan='2' class='next'><a href='javascript:changeCCMonth(1);'>&gt;</a><br><a href='javascript:changeCCYear(1);'>&raquo;</a></td>\";
1082     table += \"</tr>\";
1083     table += \"<tr>\";
1084     table += \"<th class='weekno'>\"+wno+\"</th>\";
1085     for (var n=0; n<7; n++)
1086         table += \"<th>\" + wdays[(wstart+n)%7]+\"</th>\";
1087     table += \"</tr>\";
1088     for(var week=0; week < 6; week++) {
1089       table += \"<tr>\";
1090       for(var n=0; n < 7; n++) {
1091         dayOfWeek = (wstart+n)%7;
1092         if(week == 0 && startDayOfWeek == dayOfWeek) {
1093           validDay = 1;
1094         } else if (validDay == 1 && dayOfMonth > daysInMonth) {
1095           validDay = 0;
1096         }
1097         if (n==0)
1098         {
1099                 if (dayOfMonth > daysInMonth)
1100                         table += \"<td class='empty'>&nbsp;</td>\";
1101                 else
1102                         table += \"<td class='weekno'>\"+getWeek(currentYear, currentMonth, dayOfMonth)+\"</td>\";
1103         }
1104         if(validDay) {
1105           if (dayOfMonth == selectedDay && currentYear == selectedYear && currentMonth == selectedMonth) {
1106             css_class = 'current';
1107 ";
1108         if ($date_system == 1 || $date_system == 2 || $date_system == 3)
1109                 $js .= "
1110           } else if (dayOfWeek == 5) {
1111 ";
1112         else
1113                 $js .= "
1114           } else if (dayOfWeek == 0 || dayOfWeek == 6) {
1115 ";
1116                 $js .= "
1117             css_class = 'weekend';
1118           } else {
1119             css_class = 'weekday';
1120           }
1121           table += \"<td><a class='\"+css_class+\"' href=\\\"javascript:setCCDate(\"+currentYear+\",\"+currentMonth+\",\"+dayOfMonth+\")\\\">\"+dayOfMonth+\"</a></td>\";
1122           dayOfMonth++;
1123         } else {
1124           table += \"<td class='empty'>&nbsp;</td>\";
1125         }
1126       }
1127       table += \"</tr>\";
1128     }
1129     table += \"<tr class='header'><th colspan='8' style='padding: 3px;text-align:center;'><a href='javascript:hideCC();'>$back</a></td></tr>\";
1130     table += \"</table>\";
1131     return table;
1132   }
1133   this.show = show;
1134   function show(field) {
1135     can_hide = 0;
1136     if (dateField == field) {
1137       return;
1138     } else {
1139       dateField = field;
1140     }
1141     if(dateField) {
1142       try {
1143         var dateString = new String(dateField.value);
1144         var dateParts = dateString.split('$sep');
1145 ";
1146         if ($how == 0)
1147                 $js .= "
1148         selectedMonth = parseInt(dateParts[0],10);
1149         selectedDay = parseInt(dateParts[1],10);
1150         selectedYear = parseInt(dateParts[2],10);
1151 ";
1152         else if ($how == 1)
1153                 $js .= "
1154         selectedDay = parseInt(dateParts[0],10);
1155         selectedMonth = parseInt(dateParts[1],10);
1156         selectedYear = parseInt(dateParts[2],10);
1157 ";
1158         else
1159                 $js .= "
1160         selectedYear = parseInt(dateParts[0],10);
1161         selectedMonth = parseInt(dateParts[1],10);
1162         selectedDay = parseInt(dateParts[2],10);
1163 ";
1164         $js .= "
1165       } catch(e) {}
1166     }
1167     if (!(selectedYear && selectedMonth && selectedDay)) {
1168 ";
1169         if ($date_system == 1 || $date_system == 2)
1170         {
1171                 $js .= "
1172       selectedMonth = $cmon;
1173       selectedDay = $cday;
1174       selectedYear = $cyear;
1175 ";
1176         }
1177         else
1178         {
1179                 $js .= "
1180       selectedMonth = getCurrentMonth();
1181       selectedDay = getCurrentDay();
1182       selectedYear = getCurrentYear();
1183 ";
1184         }
1185         $js .= "
1186     }
1187     currentMonth = selectedMonth;
1188     currentDay = selectedDay;
1189     currentYear = selectedYear;
1190     if(document.getElementById){
1191       calendar = document.getElementById(calendarId);
1192       calendar.innerHTML = calendarDrawTable(currentYear, currentMonth);
1193       var fieldPos = new positionInfo(dateField);
1194       var calendarPos = new positionInfo(calendarId);
1195       var x = fieldPos.getElementLeft();
1196       var y = fieldPos.getElementBottom();
1197       setProperty('left', x + 'px');
1198       setProperty('top', y + 'px');
1199       setProperty('display', 'block');
1200       if (document.all) {
1201         setElementProperty('left', x + 'px', 'CCIframe');
1202         setElementProperty('top', y + 'px', 'CCIframe');
1203         setElementProperty('width', calendarPos.getElementWidth() + 'px', 'CCIframe');
1204         setElementProperty('height', calendarPos.getElementHeight() + 'px', 'CCIframe');
1205         setElementProperty('display', 'block', 'CCIframe');
1206       }
1207     }
1208   }
1209   this.hide = hide;
1210   function hide() {
1211     if(dateField) {
1212       setProperty('display', 'none');
1213       setElementProperty('display', 'none', 'CCIframe');
1214       dateField = null;
1215     }
1216   }
1217   this.visible = visible;
1218   function visible() {
1219     return dateField
1220   }
1221   this.can_hide = can_hide;
1222   var can_hide = 0;
1223 }
1224 var cC = new CC();
1225 function date_picker(textField) {
1226   cC.show(textField);
1227 }
1228 function hideCC() {
1229   if (cC.visible()) {
1230     cC.hide();
1231   }
1232 }
1233 function setCCDate(year, month, day) {
1234   cC.setDate(year, month, day);
1235 }
1236 function changeCCYear(change) {
1237   cC.changeYear(change);
1238 }
1239 function changeCCMonth(change) {
1240   cC.changeMonth(change);
1241 }
1242 document.write(\"<iframe id='CCIframe' src='javascript:false;' frameBorder='0' scrolling='no'></iframe>\");
1243 document.write(\"<div id='CC'></div>\");";
1244
1245      cache_js_file($fpath, $js);
1246     }
1247     add_js_ufile($fpath);
1248
1249  return '';
1250 }
1251
1252 function alert($msg)
1253 {
1254         echo "\n<script type=\"text/javascript\">\n"
1255                 . "<!--\n"
1256                 . "alert('$msg');\n"
1257                 . "-->\n"
1258                 . "</script>\n";
1259 }
1260
1261 if (!function_exists('_vd'))
1262 {
1263         function _vd($mixed, $title = '', $exit = false)
1264         {
1265         // Only the site admin is able to proceed here.
1266         $str = (!empty($title) ? ($title .':') : '') .'<pre>';
1267         $str .= print_r($mixed, true); //var_dump($mixed);
1268         $str .= "</pre>\n";
1269                 display_error('<table><tr><td>'.$str.'</td></tr></table>');
1270         if ($exit)
1271                 exit;
1272         }
1273 }
1274
1275 function display_backtrace($cond=true, $msg='') {
1276
1277         if ($cond) {
1278                 if ($msg) 
1279                         $str = "<center><span class='headingtext'>$msg</span></center>\n";
1280                 else
1281                         $str = '';
1282                 $str .= '<table border=0>';
1283         $trace = debug_backtrace();
1284                 foreach($trace as $trn => $tr) {
1285                         if (!$trn) continue;
1286                         $str .= '<tr><td>';
1287                         $str .= $tr['file'].':'.$tr['line'].': ';
1288                         $str .= '</td><td>';
1289                         if (isset($tr['type'])) {
1290                                 if($tr['type'] == '::') {
1291                                         $str .= $tr['class'].'::';
1292                                 } else if($tr['type'] == '->') {
1293                                         $str .= '('.$tr['class'].' Object)'.'->';
1294                                 }
1295                         }
1296                         foreach($tr['args'] as $n=>$a) {
1297                                 if (is_object($tr['args'][$n]))
1298                                         $tr['args'][$n] = "(".get_class($tr['args'][$n])." Object)";
1299                                 if (is_array($tr['args'][$n]))
1300                                         $tr['args'][$n] = "(Array[".count($tr['args'][$n])."])";
1301                                 else
1302                                         $tr['args'][$n] = "'".$tr['args'][$n]."'";
1303                         }
1304                         $str .= $tr['function'].'('. implode(',',$tr['args']).')</td>';
1305
1306                         $str .= '</tr>';
1307                 }
1308                 
1309                 $str .= '</table>';
1310         display_error($str);
1311         }
1312 }
1313
1314 ?>