phpBMS

root/trunk/phpbms/include/common_functions.php

Revision 725, 32.9 KB (checked in by brieb, 2 years ago)
  • Fixed more path disclosure and possible SQL injection bugs in the load search class
  • Property svn:keywords set to LastChangedBy LastChangedDate LastChangedRevision
Line 
1<?php
2/*
3 $Rev$ | $LastChangedBy$
4 $LastChangedDate$
5 +-------------------------------------------------------------------------+
6 | Copyright (c) 2004 - 2010, Kreotek LLC                                  |
7 | All rights reserved.                                                    |
8 +-------------------------------------------------------------------------+
9 |                                                                         |
10 | Redistribution and use in source and binary forms, with or without      |
11 | modification, are permitted provided that the following conditions are  |
12 | met:                                                                    |
13 |                                                                         |
14 | - Redistributions of source code must retain the above copyright        |
15 |   notice, this list of conditions and the following disclaimer.         |
16 |                                                                         |
17 | - Redistributions in binary form must reproduce the above copyright     |
18 |   notice, this list of conditions and the following disclaimer in the   |
19 |   documentation and/or other materials provided with the distribution.  |
20 |                                                                         |
21 | - Neither the name of Kreotek LLC nor the names of its contributore may |
22 |   be used to endorse or promote products derived from this software     |
23 |   without specific prior written permission.                            |
24 |                                                                         |
25 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS     |
26 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT       |
27 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A |
28 | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT      |
29 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,   |
30 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT        |
31 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,   |
32 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY   |
33 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT     |
34 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE   |
35 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.    |
36 |                                                                         |
37 +-------------------------------------------------------------------------+
38*/
39// uber phpbms class for common functions that reference the DB
40// it should be instanced in session.php
41class phpbms{
42
43        var $db;
44        var $modules = array();//array of installed modules
45        var $cssIncludes = array();
46        var $jsIncludes = array();
47        var $topJS = array();
48        var $bottomJS = array();
49        var $onload = array();
50
51        var $showFooter = true;
52        var $showMenu = true;
53
54        function phpbms($db){
55                $this->db = $db;
56
57                $this->modules = $this->getModules();
58        }
59
60
61        function showCssIncludes(){
62                foreach($this->cssIncludes as $theinclude){
63                        ?><link href="<?php echo APP_PATH ?>common/stylesheet/<?php echo STYLESHEET ."/".$theinclude ?>" rel="stylesheet" type="text/css" />
64                        <?php
65                }
66        }
67
68        function showJsIncludes(){
69                foreach($this->jsIncludes as $theinclude){
70                        ?><script language="JavaScript" src="<?php echo APP_PATH.$theinclude ?>" type="text/javascript" ></script>
71                        <?php
72                }
73        }
74
75        function showExtraJs($array){
76                if(count($array)){
77                ?><script language="JavaScript" type="text/javascript">
78                <?php
79                foreach($array as $theextra)
80                        echo $theextra."\n";
81                ?>
82                </script><?php
83                }//endid
84        }//end method
85
86
87        function getModules(){
88                $modules = array();
89
90                $querystatement = "SELECT * FROM `modules`";
91                $queryresult = $this->db->query($querystatement);
92                while($therecord = $this->db->fetchArray($queryresult))
93                        $modules[$therecord["name"]] = $therecord;
94
95                return $modules;
96        }
97
98
99        /**
100         * displays the user name for a role
101         *
102         * @param string $roleid uuid of role
103         * @param string $rolename rolename to overwrite
104         */
105        function displayRights($roleid, $rolename = ""){
106
107                        switch($roleid){
108
109                                case "":
110                                        echo "EVERYONE";
111                                        break;
112
113                                case "Admin":
114                                        echo "Administrators";
115                                        break;
116
117                                default:
118                                        if(!$rolename){
119
120                                                $querystatement = "
121                                                        SELECT
122                                                                        name
123                                                        FROM
124                                                                        roles
125                                                        WHERE
126                                                                        uuid = '".mysql_real_escape_string($roleid)."'";
127
128                                                $queryresult = $this->db->query($querystatement);
129
130                                                $therecord = $this->db->fetchArray($queryresult);
131
132                                                $rolename = $therecord["name"];
133
134                                        }//end if
135
136                                        echo $rolename;
137
138                        }//end case
139
140        }//end method
141
142
143        /**
144          * Generates and displays tabs based on a tab group name
145          *
146          * @param string $groupname The name of the tab grup to display
147          * @param string $currenttabid The UUID of the currentl selected tab
148          * @param string $recordid id of the current record
149          */
150        function showTabs($tabgroup, $currenttabid, $recordid = 0){
151
152                $querystatement = "
153                        SELECT
154                                `uuid`,
155                                `name`,
156                                `location`,
157                                `enableonnew`,
158                                `notificationsql`,
159                                `tooltip`,
160                                `roleid`
161                        FROM
162                                `tabs`
163                        WHERE
164                                `tabgroup` ='".$tabgroup."'
165                        ORDER BY
166                                `displayorder`";
167
168                $queryresult = $this->db->query($querystatement);
169
170                ?><ul class="tabs"><?php
171
172                        while($therecord=$this->db->fetchArray($queryresult)){
173
174                                if(hasRights($therecord["roleid"])){
175
176                                        ?><li <?php if($therecord["uuid"]==$currenttabid) echo "class=\"tabsSel\"" ?>><?php
177
178                                                if($therecord["uuid"]==$currenttabid || ($recordid==0 && $therecord["enableonnew"]==0)){
179
180                                                        $opener="<div>";
181                                                        $closer="</div>";
182
183                                                } else {
184
185                                                        $opener="<a href=\"".APP_PATH.$therecord["location"]."?id=".urlencode($recordid)."\">";
186                                                        $closer="</a>";
187
188                                                }//endif
189
190                                                if($therecord["notificationsql"]!=""){
191
192                                                        $therecord["notificationsql"]=str_replace("{{id}}",((int) $recordid),$therecord["notificationsql"]);
193
194                                                        $notificationresult=$this->db->query($therecord["notificationsql"]);
195
196                                                        if($this->db->numRows($notificationresult)!=0){
197
198                                                                $notificationrecord=$this->db->fetchArray($notificationresult);
199
200                                                                if(isset($notificationrecord["theresult"]))
201                                                                        if($notificationrecord["theresult"]>0){
202
203                                                                                $opener.="<span>";
204                                                                                $closer="</span>".$closer;
205
206                                                                        }//endif
207
208                                                        }//endif
209
210                                                }//endif
211
212                                                echo $opener.$therecord["name"].$closer;
213
214                                        ?></li><?php
215                                }//endif hasRights
216                        }//end whilt
217                ?>
218                </ul><?php
219        }//end method
220
221
222        function getUserName($id = null, $uuid = false){
223
224                if($uuid){
225
226                        $getfield = "uuid";
227                        $id = "'".mysql_real_escape_string($id)."'";
228
229                } else {
230
231                        $getfield = "id";
232                        $id = (int) $id;
233                }//endif
234
235                $querystatement="
236                        SELECT
237                                `firstname`,
238                                `lastname`
239                        FROM
240                                `users`
241                        WHERE
242                                `".$getfield."` = ".$id;
243
244                $queryresult = $this->db->query($querystatement);
245
246                $tempinfo = $this->db->fetchArray($queryresult);
247
248                return trim($tempinfo["firstname"]." ".$tempinfo["lastname"]);
249
250        }// end method
251
252}// end class
253
254
255//=================================================
256//Most Common Functions of the Application go here.
257//=================================================
258
259/**
260  * generates a Universal Unique ID (UUID) with an optional prefix
261  *
262  * @param string $prefix prefix to prepend to the UUID
263  */
264function uuid($prefix = ''){
265
266        $chars = md5(uniqid(mt_rand(), true));
267
268        $uuid = substr($chars, 0, 8) . '-';
269        $uuid .= substr($chars, 8, 4) . '-';
270        $uuid .= substr($chars, 12, 4) . '-';
271        $uuid .= substr($chars, 16, 4) . '-';
272        $uuid .= substr($chars, 20, 12);
273
274        return $prefix.$uuid;
275
276}//end function uuid
277
278
279/**
280  * retrieves a uuid given an id and a table definition's uuid
281  *
282  * @param object $db the database object
283  * @param string $tabledefuuid the table definition's uuid
284  * @param int $id the records id
285  */
286function getUuid($db, $tabledefuuid, $id){
287
288        $querystatement = "
289                SELECT
290                        `maintable`
291                FROM
292                        `tabledefs`
293                WHERE
294                        `uuid` = '".$tabledefuuid."'";
295
296        $queryresult = $db->query($querystatement);
297
298        $tablerecord = $db->fetchArray($queryresult);
299
300        $querystatement = "
301                SELECT
302                        `uuid`
303                FROM
304                        `".$tablerecord["maintable"]."`
305                WHERE
306                        `id` = ".((int) $id);
307
308        $queryresult = $db->query($querystatement);
309
310        if($db->numRows($queryresult))
311                $therecord = $db->fetchArray($queryresult);
312        else
313                $therecord["uuid"] = "";
314
315        return $therecord["uuid"];
316
317}//end function getUuid
318
319
320/**
321 * function getUuidArray
322 * Gets an array of uuids for a given tabledefuuid and list of ids.  Will not
323 * give a uuid more than once and may not return an array of the same count
324 * as the count of the $ids array.
325 *
326 * @param object $db
327 * @param string $tabledefuuid
328 * @param array $ids
329 *
330 * @return array Array of Uuids for the $ids in no particular order.  Count
331 * (length) of this array is less than or equal to the $ids array.  Returns false
332 * if $ids is of length 0.
333 */
334
335function getUuidArray($db, $tabledefuuid, $ids){
336
337        if(!count($ids))
338                return false;
339
340        $querystatement = "
341                        SELECT
342                                        `maintable`
343                        FROM
344                                        `tabledefs`
345                        WHERE
346                                        `uuid` = '".$tabledefuuid."'";
347
348        $queryresult = $db->query($querystatement);
349
350        $tablerecord = $db->fetchArray($queryresult);
351
352        $whereclause = "";
353        foreach($ids as $id)
354                $whereclause .= " OR `id` = '".(int)$id."'";
355
356        $whereclause = substr($whereclause, 4);
357
358        $querystatement = "
359                        SELECT
360                                        `uuid`
361                        FROM
362                                        `".$tablerecord["maintable"]."`
363                        WHERE
364                                        ".$whereclause;
365
366        $queryresult = $db->query($querystatement);
367
368        $thereturn = array();
369        if($db->numRows($queryresult))
370                while($therecord = $db->fetchArray($queryresult))
371                        $thereturn[] = $therecord["uuid"];
372
373        return $thereturn;
374
375}//end function --getUuidArray--
376
377
378/**
379  * retrieves an id given a uuid and a table definition's uuid
380  *
381  * @param object $db the database object
382  * @param string $tabledefuuid the table definition's uuid
383  * @param string $uuid the records id
384  *
385  * @return int id
386  */
387function getId($db, $tabledefuuid, $uuid){
388
389        $querystatement = "
390                SELECT
391                        `maintable`
392                FROM
393                        `tabledefs`
394                WHERE
395                        `uuid` = '".$tabledefuuid."'";
396
397        $queryresult = $db->query($querystatement);
398
399        $tablerecord = $db->fetchArray($queryresult);
400
401        $querystatement = "
402                SELECT
403                        `id`
404                FROM
405                        `".$tablerecord["maintable"]."`
406                WHERE
407                        `uuid` = '".$uuid."'";
408
409        $queryresult = $db->query($querystatement);
410
411        if($db->numRows($queryresult))
412                $therecord = $db->fetchArray($queryresult);
413        else
414                $therecord["id"] = null;
415
416        return $therecord["id"];
417
418}//end function getId
419
420
421/**
422 * retreive uuid prefix of a tabledef
423 *
424 * @param object $db database object
425 * @param sring $tabledefuuid uuid of tabledef to retrieve
426 */
427function getUuidPrefix($db, $tabledefuuid){
428
429        $querystatement = "
430                SELECT
431                        `prefix`
432                FROM
433                        `tabledefs`
434                WHERE
435                        `uuid` = '".$tabledefuuid."'";
436
437        $queryresult = $db->query($querystatement);
438
439        $therecord = $db->fetchArray($queryresult);
440
441        return $therecord["prefix"];
442
443}//end function getUuidPrefix
444
445
446/**
447 * function moduleExists
448 * @param string $moduleUuid A potential module uuid
449 * @param array $moduleArray array of module information from $phpbms->modules
450 * @return bool Whether or not the module corrisponding to the $moduleUuid exists
451 * in the $moduleArray
452 */
453
454function moduleExists($moduleUuid, $moduleArray) {
455
456        if(count($moduleArray)){
457
458                foreach($moduleArray as $moduleRecord){
459
460                        if(isset($moduleRecord["uuid"]))
461                                if($moduleRecord["uuid"] == $moduleUuid)
462                                        return true;
463
464                }//end foreach
465
466        }//end if
467
468        return false;
469
470}//end function
471
472
473function xmlEncode($str){
474        $str=str_replace("&","&amp;",$str);
475        $str=str_replace("<","&lt;",$str);
476        $str=str_replace(">","&gt;",$str);
477        return $str;
478}
479
480
481function goURL($url){
482        if(headers_sent())
483                $error = new appError("450","Could not redirect to: ".$url);
484                header("Location: ".$url);
485        exit;
486}
487
488
489/**
490 * Determines if currently logged in user has rights
491 *
492 * @param string $roleid uuid of the role to check for
493 * @param bool $fullAccessAdmin should we check for admin status?
494 */
495function hasRights($roleid, $fullAccessAdmin = true){
496
497        $hasRights = false;
498
499        if($_SESSION["userinfo"]["admin"] == 1 && ($fullAccessAdmin || $roleid == "Admin"))
500                $hasRights = true;
501        elseif($roleid == "")
502                $hasRights = true;
503        else
504                foreach($_SESSION["userinfo"]["roles"] as $role){
505
506                        if($role == $roleid){
507
508                                $hasRights = true;
509                                break;
510
511                        }//endif
512
513                }//endif
514
515        return $hasRights;
516
517}//end function hasRights
518
519/**
520 * function getPathToAppRoot
521 * @return string path (up) to application root
522 */
523
524function getPathToAppRoot() {
525
526                $currdirectory = getcwd();
527                $count = 0;
528                $path = "";
529
530                //We need to find the applications root
531                while(!file_exists("phpbmsversion.php") && $count < 9){
532
533                        $path.="../";
534                        @ chdir("../");
535                        $count++;
536
537                }//end while
538
539                chdir($currdirectory);
540
541                if($count < 9)
542                        return $path;
543                else
544                        return NULL;
545
546}//end function --getPathToAppRoot()--
547
548
549/**
550  *  function makeDelimeterString
551  *
552  *  Creates a string with the same length as $string, with a delimeter where
553  *  the corresponding part of the string is on or within that delimeter, and
554  *  zeroes everywhere else.
555  *
556  *  @param string $string
557  *  @param array $delimeters Array of delimeters.  The delimeters are assumed
558  *  to be symmetric [i.e. "`" works because it is used symmetrically, but
559  *  parenthesis ( "(" and ")" ) do not].
560  *  @param char $escapeCharacter An escape character escaping delimeters.
561  *  @return string The delimeter string the same length as $string,
562  *  with a delimeter where the corresponding part of the string is
563  *  on or within that delimeter, and zeroes everywhere else. Returns false if
564  *  an error has occurred
565  */
566function makeDelimeterString($string, $delimeters, $escapeCharacter = "\\"){
567
568        if(!$escapeCharacter)
569                $escapeCharacter = NULL;
570
571        if(strlen($escapeCharacter) > 1)
572                return false;
573
574        $returnString = "";
575        $stringArray = str_split($string);
576        $inside = false;
577        $prevChar = "";
578        foreach($stringArray as $char){
579
580                if(!$inside){
581                        if(in_array($char, $delimeters) && $prevChar != $escapeCharacter){
582                                $inside = true;
583                                $delimeter = $char;
584                                $returnString .= $delimeter;
585                        }else
586                                $returnString .= "0";
587                }else{
588
589                        if($char == $delimeter && $prevChar != $escapeCharacter){
590                                $inside = false;
591                                $returnString .= "0";
592                        }else
593                                $returnString .= $delimeter;
594
595                }//end if
596
597                $prevChar = $char;
598
599        }//end foreach
600
601        return $returnString;
602
603}//end function
604
605
606/*
607 * function getSearchFrom
608 * Returns the part of $querystatement from the general FROM to its ORDER BY or
609 * the end of the querystatement if no ORDER BY exists.
610 *
611 * @param $querystatement
612 * @return string The part of $querystatement from the general FROM to its
613 * ORDER BY.
614 */
615function getSearchFrom($querystatement) {
616
617        $modstatement = $querystatement;
618        $insideString = makeDelimeterString($querystatement, array("'", "\"", "`"));
619        $insideArray = str_split($insideString);
620
621
622        /**
623          *  Check for SELECTs that are not inside quotes or tics.
624          *  Put the positions of them in the string inside an ordered array,
625          *  with the first ones in the string with the lowest array indices.
626          */
627        $selectArray = array();
628        $offset = 0;
629        do{
630
631                $pos = stripos($querystatement, "select", $offset);
632
633                if($pos !== false)
634                        if(!$insideArray[$pos])
635                                $selectArray[] = $pos;
636                $offset = $pos+1;
637
638        }while($pos !== false);
639
640        /**
641          *  Check for FROMSs that are not inside quotes or tics.
642          *  Put the positions of them in the string inside an ordered array,
643          *  with the first ones in the string with the lowest array indices.
644          */
645        $fromArray = array();
646        $offset = 0;
647        do{
648
649                $pos = stripos($querystatement, "from", $offset);
650
651                if($pos !== false)
652                        if(!$insideArray[$pos])
653                                $fromArray[] = $pos;
654                $offset = $pos+1;
655
656        }while($pos !== false);
657
658        /**
659          *  Check for ORDER BYs that are not inside quotes or tics.
660          *  Put the positions of them in the string inside an ordered array,
661          *  with the first ones in the string with the lowest array indices.
662          */
663        $orderArray = array();
664        $offset = 0;
665        do{
666
667                $pos = stripos($querystatement, "order by", $offset);
668
669                if($pos !== false)
670                        if(!$insideArray[$pos])
671                                $orderArray[] = $pos;
672                $offset = $pos+1;
673
674        }while($pos !== false);
675
676
677        /**
678          *  Pair the SELECTs with their appropriate FROMs
679          */
680        $godArray = array();
681        $tempSelectArray = $selectArray;
682        $j = 0;
683        foreach($fromArray as $fromPos){
684
685                $closest = 0;
686                $index = 0;
687                for($i=0; $i < count($tempSelectArray); $i++)
688                        if($fromPos > $tempSelectArray[$i]){
689                                $closest = $tempSelectArray[$i];
690                                $index = $i;
691                        }//end if
692
693                unset($tempSelectArray[$index]);
694                $godArray[$j]["select"] = $closest;
695                $godArray[$j]["from"] = $fromPos;
696                $j++;
697
698        }//end foreach
699
700
701        /**
702          *  Pair the ORDER BYs with their approriate FROMs (and thus their
703          *  appropriate SELECTs).
704          */
705        $tempFromArray = $fromArray;
706        $j = 0;
707        foreach($orderArray as $orderPos){
708
709                $closest = 0;
710                $index = 0;
711                for($i=0; $i < count($tempFromArray); $i++)
712                        if($orderPos > $tempFromArray[$i]){
713                                $closest = $tempFromArray[$i];
714                                $index = $i;
715                        }//end if
716
717                unset($tempFromArray[$index]);
718                for($k=0; $k < count($godArray); $k++)
719                        if($godArray[$k]["from"] == $closest)
720                                $godArray[$k]["order"] = $orderPos;
721
722                $j++;
723
724        }//end foreach
725
726
727        /**
728          *  The last entry in the $godArray should be the outermost / first
729          *  SQL statement.
730          */
731        $l = count($godArray) - 1;
732        if(!isset($godArray[$l]["order"]))
733                $godArray[$l]["order"] = strlen($querystatement);
734
735        if(!($godArray[$l]["order"]))
736                $godArray[$l]["order"] = strlen($querystatement);
737
738        return substr($querystatement, $godArray[$l]["from"], $godArray[$l]["order"] - $godArray[$l]["from"]);
739
740}//end function
741
742// date/time functions
743//=====================================================================
744function stringToDate($datestring,$format=DATE_FORMAT){
745        $thedate=NULL;
746        if($datestring){
747                switch($format){
748
749                        case "SQL":
750                                $temparray=explode("-",$datestring);
751                                if(count($temparray)==3)
752                                        $thedate=mktime(0,0,0,(int) $temparray[1],(int) $temparray[2],(int) $temparray[0]);
753                                else
754                                        return false;
755                        break;
756
757                        case "English, US":
758                                $datestring="/".preg_replace("/,./","/",$datestring);
759                                $temparray=explode("/",$datestring);
760                                if(count($temparray)==4)
761                                        $thedate=mktime(0,0,0,(int) $temparray[1],(int) $temparray[2],(int) $temparray[3]);
762                                else
763                                        return false;
764                        break;
765
766                        case "English, UK":
767                                $datestring="/".preg_replace("/,./","/",$datestring);
768                                $temparray=explode("/",$datestring);
769                                if(count($temparray)==4)
770                                        $thedate=mktime(0,0,0,(int) $temparray[2],(int) $temparray[1],(int) $temparray[3]);
771                                else
772                                        return false;
773                        break;
774
775                        case "Dutch, NL":
776                                $datestring="-".preg_replace("/,./","-",$datestring);
777                                $temparray=explode("-",$datestring);
778                                if(count($temparray)==4)
779                                        $thedate=mktime(0,0,0,(int) $temparray[2],(int) $temparray[1],(int) $temparray[3]);
780                                else
781                                        return false;
782                        break;
783
784                }
785        }
786        return $thedate;
787}
788
789function stringToTime($timestring, $format=TIME_FORMAT){
790
791        $thetime = NULL;
792
793        if($timestring){
794                switch($format){
795
796                        case "24 Hour":
797                                $temparray=explode(":",$timestring);
798                                if(count($temparray)==3)
799                                        $thetime=mktime($temparray[0],$temparray[1],$temparray[2]);
800                                else
801                                        return false;
802                        break;
803
804                        case "12 Hour":
805                                if(strpos($timestring,"AM")!==false){
806                                        $timestring=str_replace(" AM","",$timestring);
807                                        $addtime=0;
808                                }
809                                else {
810                                        $timestring=str_replace(" PM","",$timestring);
811                                        $addtime=12;
812                                }
813                                $timearray=explode(":",$timestring);
814                                if(count($timearray) == 2){
815                                        if ($timearray[0]==12)
816                                                $timearray[0]=0;
817                                        $timearray[0]= ((integer) $timearray[0]) + $addtime;
818                                        $thetime=mktime($timearray[0],$timearray[1],0);
819                                }else
820                                        return false;
821                        break;
822                }
823        }
824        return $thetime;
825}
826
827function dateToString($thedate,$format=DATE_FORMAT){
828        $datestring="";
829        if($thedate){
830                switch($format){
831
832                        case "SQL":
833                                $datestring=@strftime("%Y-%m-%d",$thedate);
834                        break;
835
836                        case "English, US":
837                                $datestring=@strftime("%m/%d/%Y",$thedate);
838                        break;
839
840                        case "English, UK":
841                                $datestring=@strftime("%d/%m/%Y",$thedate);
842                        break;
843
844                        case "Dutch, NL":
845                                $datestring=@strftime("%d-%m-%Y",$thedate);
846                        break;
847                }
848        }
849        return $datestring;
850}
851
852function timeToString($thetime,$format=TIME_FORMAT){
853        $timestring="";
854        if($thetime){
855                switch($format){
856                        case "24 Hour":
857                                $timestring=@strftime("%H:%M:%S",$thetime);
858                        break;
859                        case "12 Hour":
860                                $timestring=trim(@strftime(HOUR_FORMAT.":%M %p",$thetime));
861                        break;
862                }
863        }
864        return $timestring;
865}
866
867function formatFromSQLDate($sqldate,$format=DATE_FORMAT){
868        $datestring="";
869        if($sqldate!="")
870                if($format=="SQL")
871                        $datestring=$sqldate;
872                else
873                        $datestring=dateToString(stringToDate($sqldate,"SQL"),$format);
874        return $datestring;
875}
876
877function formatFromSQLTime($sqltime,$format=TIME_FORMAT){
878        $timestring="";
879        if($sqltime!="")
880                if($format=="24 Hour")
881                        $timestring=$sqltime;
882                else
883                        $timestring=timeToString(stringToTime($sqltime,"24 Hour"),$format);
884        return $timestring;
885}
886
887function dateFromSQLDatetime($sqldatetime){
888                $thedatetime=false;
889                $datetimearray=explode(" ",$sqldatetime);
890                if(count($datetimearray)==2){
891                        $tempdatearray=explode("-",$datetimearray[0]);
892                        $temptimearray=explode(":",$datetimearray[1]);
893                        if(count($tempdatearray)>1 && count($temptimearray)>1)
894                                $thedatetime=mktime((int) $temptimearray[0],(int) $temptimearray[1],(int) $temptimearray[2],(int) $tempdatearray[1],(int) $tempdatearray[2],(int) $tempdatearray[0]);
895                }
896                return $thedatetime;
897}
898
899function formatFromSQLDatetime($sqldatetime,$dateformat=DATE_FORMAT,$timeformat=TIME_FORMAT){
900        $datetimestring="";
901        $timestring="";
902        if($sqldatetime!=""){
903                $datetimearray=explode(" ",$sqldatetime);
904
905                $datestring=trim($datetimearray[0]);
906                if($dateformat=="SQL")
907                        $datestring=$datestring;
908                else
909                        $datestring=dateToString(stringToDate($datestring,"SQL"),$dateformat);
910                if(isset($datetimearray[1])){
911                        $timestring=$datetimearray[1];
912                        if($timeformat=="24 Hour")
913                                $timestring=$timestring;
914                        else
915                                $timestring=timeToString(stringToTime($timestring,"24 Hour"),$timeformat);
916                }
917                $datetimestring=trim($datestring." ".$timestring);
918        }
919        return $datetimestring;
920}
921
922function formatFromSQLTimestamp ($datetime,$dateformat=DATE_FORMAT,$timeformat=TIME_FORMAT) {
923        if($datetime=="")
924                return mktime();
925        $hour=0;
926        $minute=0;
927        $second=0;
928        $month=1;
929        $day=1;
930        $year=1974;
931        settype($datetime, 'string');
932        preg_match('/(....)(..)(..)(..)(..)(..)/i',$datetime,$matches);
933        array_shift ($matches);
934        foreach (array('year','month','day','hour','minute','second') as $var) {
935                $$var = (int) array_shift($matches);
936        }
937
938
939        $thedatetime=mktime($hour,$minute,$second,$month,$day,$year);
940
941        return trim(dateToString($thedatetime,$dateformat)." ".timeToString($thedatetime,$timeformat));
942}
943
944function sqlDateFromString($datestring,$format=DATE_FORMAT){
945        $sqldate="0000-00-00";
946        if($datestring){
947                if($format=="SQL")
948                        $sqldate=$datestring;
949                else
950                        $sqldate=dateToString(stringToDate($datestring,$format),"SQL");
951        }
952        return $sqldate;
953}
954
955function sqlTimeFromString($timestring,$format=TIME_FORMAT){
956        $sqltime="0000-00-00";
957        if($timestring){
958                if($format=="24 Hour")
959                        $sqltime=$timestring;
960                else
961                        $sqltime=timeToString(stringToTime($timestring,$format),"24 Hour");
962        }
963        return $sqltime;
964}
965
966// Currency functions
967//=====================================================================
968function numberToCurrency($number){
969        $currency="";
970        if($number<0)
971                $currency.="-";
972        $currency.=CURRENCY_SYM.number_format(abs($number),CURRENCY_ACCURACY,DECIMAL_SYMBOL,THOUSANDS_SEPARATOR);
973        return $currency;
974}
975
976function currencyToNumber($currency){
977        $number=str_replace(CURRENCY_SYM,"",$currency);
978        $number=str_replace(THOUSANDS_SEPARATOR,"",$number);
979        $number=str_replace(DECIMAL_SYMBOL,".",$number);
980        $number=((real) $number);
981
982        return $number;
983}
984
985// Phone/Email functions
986//=====================================================================
987function validateEmail($value){
988
989        $thereturn = false;
990        $atPos = strpos($value, "@");
991
992        //@ symobol must be after first char
993        if($atPos > 0){
994
995                $dotPos = strpos($value, ".", $atPos);
996                $length = strlen($value);
997
998                //the dot must be at least 2 chars away from at
999                //it also must not be the last char in the string
1000                if( ($dotPos > ($atPos + 1)) && ($length > ($dotPos + 1)) )
1001                        $thereturn = true;
1002
1003        }//end if
1004
1005        return $thereturn;
1006
1007}//end function --validateEmail--
1008
1009
1010function validatePhone($number){
1011
1012        //need to decide on the phone reg ex based upon settings information
1013        switch(PHONE_FORMAT){
1014
1015                case "US - Loose":
1016                        $phoneRegEx = "/^(?:[\+]?(?:[\d]{1,3})?(?:\s*[\(\.-]?(\d{3})[\)\.-])?\s*(\d{3})[\.-](\d{4}))(?:(?:[ ]+(?:[xX]|(?:[eE][xX][tT][\.]?)))[ ]?[\d]{1,5})?$/";
1017                break;
1018
1019                case "US - Strict":
1020                        $phoneRegEx = "/^[2-9]\d{2}-\d{3}-\d{4}$/";
1021                break;
1022
1023                case "UK - Loose":
1024                        $phoneRegEx = "/^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/";
1025                break;
1026
1027                case "International":
1028                        $phoneRegEx = "/^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$/";
1029                break;
1030                case "No Verification":
1031                        $phoneRegEx = "/.*/";
1032                break;
1033        }//end switch
1034
1035        return preg_match($phoneRegEx,$number);
1036
1037}//end function --validatePhone--
1038
1039//============================================================================
1040function ordinal($number) {
1041
1042    // when fed a number, adds the English ordinal suffix. Works for any
1043    // number, even negatives
1044
1045    if ($number % 100 > 10 && $number %100 < 14):
1046        $suffix = "th";
1047    else:
1048        switch($number % 10) {
1049
1050            case 0:
1051                $suffix = "th";
1052                break;
1053
1054            case 1:
1055                $suffix = "st";
1056                break;
1057
1058            case 2:
1059                $suffix = "nd";
1060                break;
1061
1062            case 3:
1063                $suffix = "rd";
1064                break;
1065
1066            default:
1067                $suffix = "th";
1068                break;
1069        }
1070
1071    endif;
1072
1073    return "${number}$suffix";
1074
1075}
1076
1077
1078function addSlashesToArray($thearray){
1079
1080        //This function prepares an array for SQL manipulation.
1081
1082        if(get_magic_quotes_runtime() || get_magic_quotes_gpc()){
1083
1084                foreach ($thearray as $key=>$value)
1085                        if(is_array($value))
1086                                $thearray[$key]= addSlashesToArray($value);
1087                        else
1088                                $thearray[$key] = mysql_real_escape_string(stripslashes($value));
1089
1090        } else
1091                foreach ($thearray as $key=>$value)
1092                        if(is_array($value))
1093                                $thearray[$key]= addSlashesToArray($value);
1094                        else
1095                                $thearray[$key] = mysql_real_escape_string($value);
1096
1097        return $thearray;
1098
1099}//end function
1100
1101
1102function htmlQuotes($string){
1103
1104        global $sqlEncoding;
1105        if(!isset($sqlEncoding))
1106                $sqlEncoding = "";
1107
1108        switch ($sqlEncoding){
1109
1110                case "latin1":
1111                        $encoding = "ISO-8859-15";
1112                        break;
1113
1114                case "utf8":
1115                default:
1116                        $encoding = "UTF-8";
1117                        break;
1118
1119        }//endswitch
1120
1121        return htmlspecialchars($string, ENT_COMPAT, $encoding);
1122
1123}
1124
1125
1126/*
1127 * function cleanFilename
1128 * @param $string
1129 * @return string $string with only alpha-numeric characters, periods (.),
1130 * dashes (-), and underscores (_)
1131 */
1132
1133function cleanFilename($string) {
1134
1135        $pattern = "/[^\w\d\.\-\_]/";
1136        $string = preg_replace($pattern, "", $string);
1137
1138        return $string;
1139
1140}//end function --cleanFilename--
1141
1142
1143
1144function htmlFormat($string,$quotes=false){
1145        $trans = get_html_translation_table(HTML_ENTITIES);
1146        $encoded = strtr($string, $trans);
1147        return $encoded;
1148}
1149
1150
1151function showSaveCancel($ids=1){
1152        ?><div class="saveCancels"><input <?php if($ids==1) {?>accesskey="s"<?php }?> title="Save (alt+s)" id="saveButton<?php echo $ids?>" name="command" type="submit" value="save" class="Buttons" /><input id="cancelButton<?php echo $ids?>" name="command" type="submit" value="cancel" class="Buttons" onclick="this.form.cancelclick.value=true;" <?php if($ids==1) {?>accesskey="x" <?php }?> title="(access key+x)" /></div><?php
1153}
1154
1155
1156/**
1157 * get's the add or edit file for a tabledefinition
1158 *
1159 * @param object $db database object
1160 * @param string $tabledefid tabledef's uuid
1161 * @param string $addedit add/edit - which file to get
1162 *
1163 * @return string file name and path of add or edit file
1164 */
1165function getAddEditFile($db, $tabledefid, $addedit="edit"){
1166
1167        $querystatement = "
1168                SELECT
1169                        ".$addedit."file AS thefile
1170                FROM
1171                        tabledefs
1172                WHERE uuid = '".mysql_real_escape_string($tabledefid)."'";
1173
1174        $queryresult = $db->query($querystatement);
1175
1176        $therecord = $db->fetchArray($queryresult);
1177
1178        return APP_PATH.$therecord["thefile"];
1179
1180}//end function getAddEditFile
1181
1182
1183function booleanFormat($bool){
1184        if($bool==1)
1185                return "X";
1186        else
1187                return"&middot;";
1188}
1189
1190
1191function formatVariable($value, $format=NULL){
1192        switch($format){
1193                case "real":
1194                        $value = number_format($value,2);
1195                        break;
1196
1197                case "currency":
1198                        $value=htmlQuotes(numberToCurrency($value));
1199                        break;
1200
1201                case "boolean":
1202                        $value=booleanFormat($value);
1203                        break;
1204
1205                case "date":
1206                        $value=formatFromSQLDate($value);
1207                        break;
1208
1209                case "time":
1210                        $value=formatFromSQLTime($value);
1211                        break;
1212
1213                case "datetime":
1214                        $value=formatFromSQLDatetime($value);
1215                        break;
1216
1217                case "filelink":
1218                        $value="<button class=\"graphicButtons buttonDownload\" type=\"button\" onclick=\"document.location='".APP_PATH."servefile.php?i=".$value."'\"><span>download</span></button>";
1219                        //$value="<a href=\"".APP_PATH."servefile.php?i=".$value."\" style=\"display:block;\"><img src=\"".APP_PATH."common/stylesheet/".STYLESHEET."/image/button-download.png\" align=\"middle\" alt=\"view\" width=\"16\" height=\"16\" border=\"0\" /></a>";
1220                        break;
1221
1222                case "noencoding":
1223                        $value=$value;
1224                        break;
1225
1226
1227                case "bbcode":
1228                        $value=htmlQuotes($value);
1229
1230                        // This list needs to be expanded
1231                        $bbcodelist["[b]"] = "<strong>";
1232                        $bbcodelist["[/b]"] = "</strong>";
1233                        $bbcodelist["[br]"] = "<br />";
1234                        $bbcodelist["[space]"] = "&nbsp;";
1235
1236                        foreach($bbcodelist as $bbcode => $translation)
1237                                $value = str_replace($bbcode, $translation, $value);
1238
1239                        break;
1240
1241                default:
1242                        $value=htmlQuotes($value);
1243        }
1244        return $value;
1245}
1246
1247
1248/**
1249 * function debug
1250 *
1251 * essentially provides a formatted var_dump with extra info for development purposes
1252 */
1253function debug($variable, $exit = false){
1254
1255        echo "<pre>";
1256        var_dump($variable);
1257        echo "</pre>";
1258
1259        $backtrace = debug_backtrace();
1260
1261        if(count($backtrace) > 1)
1262            array_shift($backtrace);
1263
1264        foreach($backtrace as $trace){
1265
1266                echo "* ";
1267
1268                if(isset($trace["class"]))
1269                    echo $trace["class"]."-&gt; ";
1270
1271                if(isset($trace["function"]))
1272                    echo $trace["function"]." ";
1273
1274                echo "in ".$trace["file"]." ";
1275                echo "on line ".$trace["line"]."<br />";
1276
1277        }//endforeach
1278
1279        if($exit)
1280                exit();
1281
1282}//endif
1283
1284//for windows servers, we have no define time constants and nl_langinfo function
1285//in a limited fashion; some windows servers still show that the function
1286//exists even though it's not implemented, thus the second check;
1287
1288$nl_exists = function_exists("nl_langinfo");
1289if($nl_exists)
1290        $nl_exists = @ nl_langinfo(CODESET);
1291
1292if(!$nl_exists){
1293
1294        function nl_langinfo($constant){
1295
1296                return $constant;
1297
1298        }//end function
1299
1300        function nl_setup(){
1301
1302                $date = mktime(0,0,0,10,7,2007);
1303
1304                for($i = 1; $i<=7; $i++){
1305
1306                        define("ABDAY_".$i, date("D", $date));
1307                        define("DAY_".$i, date("l"), $date);
1308
1309                        $date = strtotime("tomorrow", $date);
1310                }//end for
1311
1312
1313                for($i = 1; $i<=12; $i++){
1314
1315                        $date = mktime(0, 0, 0, $i, 1, 2007);
1316
1317                        define("ABMON_".$i, date("M", $date));
1318                        define("MON_".$i, date("F"), $date);
1319
1320                }//end for
1321
1322        }//end function
1323
1324        nl_setup();
1325
1326}//end if
1327?>
Note: See TracBrowser for help on using the browser.
Scanned by Orvant Copyright © 2010 Kreotek, LLC. All Rights reserved.