PhpLabWare version 0.3 
/includes/ -> db_inc.php

1  <?php
2    
3  // db_inc.php - functions interfacing with the database
4  // db_inc.php - author: Nico Stuurman <nicost@soureforge.net>
5    /***************************************************************************
6    * This script contain functions interfacing with the database *
7    * Although they are geared towards phplabware, they might be more generally*
8    * useful. *
9    * *
10    * *
11    * Copyright (c) 2001 by Nico Stuurman *
12    * ------------------------------------------------------------------------ *
13    * This program is free software; you can redistribute it and/or modify it *
14    * under the terms of the GNU General Public License as published by the *
15    * Free Software Foundation; either version 2 of the License, or (at your *
16    * option) any later version. *
17    \**************************************************************************/
18 
19  class tableinfo {
20     var $short;
21     var $realname;
22     var $label;
23     var $desname;
24     var $queryname;
25     var $pagename;
26     var $id;
27 
28     // hackers way of overloading
29     function tableinfo ($db,$realname=false,$id=false) {
30        global $HTTP_GET_VARS;
31 
32        if ($id)
33           $r=$db->Execute("SELECT id,shortname,tablename,real_tablename,table_desc_name,label FROM tableoftables WHERE id='$id'");
34        elseif ($realname)
35           $r=$db->Execute("SELECT id,shortname,tablename,real_tablename,table_desc_name,label FROM tableoftables WHERE real_tablename='$realname'");
36        else
37           $r=$db->Execute("SELECT id,shortname,tablename,real_tablename,table_desc_name,label FROM tableoftables WHERE tablename='$HTTP_GET_VARS[tablename]'");
38        $this->id=$r->fields['id'];
39        $this->short=$r->fields['shortname'];
40        $this->realname=$r->fields['real_tablename'];
41        $this->name=$r->fields['tablename'];
42        $this->label=$r->fields['label'];
43        $this->desname=$r->fields['table_desc_name'];
44        $this->fields=comma_array_SQL($db,$this->desname,columnname);
45     }
46  }
47 
48 
49  if (!function_exists("array_key_exists")) {
50     function array_key_exists($find,$array){
51        while ((list($key,$value)=each($array)) && !$test) {
52           if ($key==$find)
53              $test=true;
54        }
55        return $test;
56     }
57  }
58 
59  //////////////////////////////////////////////////////
60  ////
61  // !Analogue of adodb GetMenu2, but display referenced values (using getvalues)
62  function GetValuesMenu ($db,$selectname,$selected,$tablename,$columnname,$whereclause=false,$jscript=false) {
63     global $max_menu_length;
64 
65     $tableinfo=new tableinfo($db,$tablename);
66     $r=$db->Execute("SELECT id FROM $tablename $whereclause");
67     while ($r && !$r->EOF) {
68        $values[]=getvalues($db,$tableinfo,$columnname,'id',$r->fields[0]);
69        $r->MoveNext();
70     }
71     $text="<select name='$selectname' $jscript>\n";
72     $text.="<option value=''></option>\n";
73     foreach ($values as $value) {
74        $v["{$value[0]['recordid']}"]=$value[0]['text'];
75     }
76     asort($v);
77     while (list ($key,$val)=each($v)) {
78        if ($key==$selected)
79           $selecttext='selected';
80        else
81           $selecttext=false;
82        $text.="<option $selecttext value='$key'>$val</option>\n";
83     }
84     $text.="</select>\n";
85     return $text;
86  }
87 
88 
89  //////////////////////////////////////////////////////
90  ////
91  // !SQL where search that returns a comma delimited string
92  function comma_array_SQL_where($db,$tablein,$column,$searchfield,$searchval)
93  {
94     $rs = $db->Execute("select $column from $tablein where $searchfield='$searchval' order by sortkey");
95 
96     if ($rs) {
97        while (!$rs->EOF) {
98           $tempa[]=$rs->fields[0];
99           $rs->MoveNext();
100        }
101     }
102     $out=join(",",$tempa);
103     return $out;
104  }
105 
106  //////////////////////////////////////////////////////
107  ////
108  // !SQL search (entrire column) that returns a comma delimited string
109  function comma_array_SQL($db,$tablein,$column,$where=false)
110  {
111     $rs = $db->Execute("select $column from $tablein $where order by sortkey");
112     if ($rs) {
113        while (!$rs->EOF) {
114           $tempa[]=$rs->fields[0];
115           $rs->MoveNext();
116        }
117     }
118     if ($tempa)
119        return join(",",$tempa);
120  }
121 
122  ////
123  // !Update sortdirarray and returns formatted sortdirstring
124  function sortstring(&$sortdirarray,$sortup,$sortdown) {
125     if ($sortup && $sortup<>" ") {
126        if (is_array($sortdirarray) && array_key_exists($sortup,$sortdirarray)) {
127           if ($sortdirarray[$sortup]=="asc")
128              unset($sortdirarray[$sortup]);
129           else
130              $sortdirarray[$sortup]="asc";
131        }
132        elseif (!is_array($sortdirarray) || !array_key_exists($sortup,$sortdirarray))
133           $sortdirarray[$sortup]="asc";
134     }
135     if ($sortdown && $sortdown <>" ") {
136        if (is_array($sortdirarray) && array_key_exists($sortdown,$sortdirarray)) {
137           if ($sortdirarray[$sortdown]=="desc")
138              unset($sortdirarray[$sortdown]);
139           else
140              $sortdirarray[$sortdown]="desc";
141        }
142        elseif (!is_array($sortdirarray) || !array_key_exists($sortdown,$sortdirarray))
143           $sortdirarray[$sortdown]="desc";
144     }
145 
146     if ($sortdirarray) {
147        foreach($sortdirarray as $key => $value) {
148           if ($sortstring)
149              $sortstring .= ", ";
150           $sortstring .= "$key $value";
151        }
152     }
153     return $sortstring;
154  }
155 
156  ////
157  // !Displays header of 'general' table
158  function tableheader ($sortdirarray,$columnname, $columnlabel) {
159     echo "<th><table align='center' width='100%'><td align='left'>";
160     if ($sortdirarray[$columnname]=="asc")
161        $sortupicon="icons/sortup_active.png";
162     else
163        $sortupicon="icons/sortup.png";
164     echo "<input type='image' name='sortup_$columnname' value='$columnlabel' src='$sortupicon' alt='Sort Up'>";
165     echo "</td><th align='center'>$columnlabel</th><td align='right'>";
166     if ($sortdirarray[$columnname]=="desc")
167        $sortdownicon="icons/sortdown_active.png";
168     else
169        $sortdownicon="icons/sortdown.png";
170     echo "<input type='image' name='sortdown_$columnname' value='$columnlabel' src='$sortdownicon' alt='Sort Down'>";
171     echo "</td></tr></table></th>\n";
172  }
173 
174  ////
175  // !Inserts $fields with $fieldvalues into $table
176  // Returns the id of inserted record on succes, false otherwise.
177  // $fields is a comma separated list with all column names
178  // Fieldvalues must be an associative array containing all the $fields to be added.
179  // Fields named 'date' are automatically filled with a Unix timestamp
180  function add ($db,$table,$fields,$fieldvalues,$USER,$tableid) {
181     if (!may_write($db,$tableid,false,$USER)) {
182        echo "<h3>You are not allowed to do this.<br>";
183        return false;
184     }
185     // test if upload already took place through variable magic
186     if ($fieldvalues["magic"])
187        if ($test=get_cell($db,$table,"id","magic",$fieldvalues["magic"])) {
188           echo "<h3 align='center'>That record was already uploaded.</h3>\n";
189           return -1;
190        }
191     include('includes/defines_inc.php');
192     if (!($USER["permissions"] & $WRITE) )
193        return false;
194     // generate the new ID
195     $id=$db->GenID($table."_id_seq");
196     if ($id) {
197        $columns="id";
198        $values="$id";
199        $column=strtok($fields,",");
200        while ($column) {
201           if (!($column=='id')) {
202              $columns.=",$column";
203              // set userid
204              if ($column=='ownerid')
205                 $fieldvalues['ownerid']=$USER['id'];
206              // set default access rights,
207              elseif (in_array($column, array('gr','gw','er','ew')))
208                 $fieldvalues[$column]=get_access($fieldvalues,$column);
209 
210              // set timestamp
211              if ($column=='date') {
212                 $date=(time());
213                 $values.=",$date";
214              }
215              else {
216                 if (isset($fieldvalues[$column]) &&
217                          !(is_array($fieldvalues[$column])) &&
218                          strlen($fieldvalues[$column])>0)
219           $values.=",'$fieldvalues[$column]'";
220                 else
221                    $values.=",NULL";
222              }
223           }
224           $column=strtok(",");
225        }
226        // add trusted users entered on the form
227        if (is_array($fieldvalues["trust_read"]))
228           foreach ($fieldvalues["trust_read"] as $userid)
229              $db->Execute("INSERT INTO trust VALUES ('$tableid','$id','$userid','r')");
230        if (is_array($fieldvalues["trust_write"]))
231           foreach ($fieldvalues["trust_write"] as $userid)
232              $db->Execute("INSERT INTO trust VALUES ('$tableid','$id','$userid','w')");
233        $query="INSERT INTO $table ($columns) VALUES ($values)";
234        if ($db->Execute($query))
235           return $id;
236        else {
237           echo "<h3>Database error. Contact your system administrator.</h3>\n";
238        }
239     }
240  }
241 
242  ////
243  // !For multiple choice pulldowns.
244  // Deletes entries in key_table for a give record,and then re-inserts the ones present in the array
245  function update_mpulldown ($db,$key_table,$recordid,$valueArray) {
246     $db->Execute ("DELETE FROM $key_table WHERE recordid=$recordid");
247     if (is_array($valueArray)) {
248        while (list($key,$value)=each($valueArray)) {
249           $db->Execute ("INSERT INTO $key_table VALUES ($recordid,$value)");
250        }
251     }
252  }
253 
254 
255  ////
256  // !Modifies $fields in $table with values $fieldvalues where id=$id
257  // Returns true on succes, false on failure
258  // Fieldvalues must be an associative array containing all the $fields to be added.
259  // If a field is not present in $fieldvalues, it will not be changed.
260  // The entry 'id' in $fields will be ignored.
261  // Fields lastmodby and lastmoddate will be automatically set
262  function modify ($db,$table,$fields,$fieldvalues,$id,$USER,$tableid) {
263     if (!may_write($db,$tableid,$id,$USER))
264        return false;
265     // delete all entries in trust related to this record first
266     $db->Execute("DELETE FROM trust WHERE tableid='$tableid' and recordid='$id'");
267     // then add back trusted users entered on the form
268     if (is_array($fieldvalues["trust_read"]))
269        foreach ($fieldvalues["trust_read"] as $userid)
270           $db->Execute("INSERT INTO trust VALUES ('$tableid','$id','$userid','r')");
271     if (is_array($fieldvalues["trust_write"]))
272        foreach ($fieldvalues["trust_write"] as $userid)
273           $db->Execute("INSERT INTO trust VALUES ('$tableid','$id','$userid','w')");
274 
275     $query="UPDATE $table SET ";
276     $column=strtok($fields,",");
277     while ($column) {
278        if (! ($column=='id' || $column=='date' || $column=='ownerid' || is_array($fieldvalues[$column]) ) ) {
279           $test=true;
280           //if ($column=="access")
281           // $fieldvalues["access"]=get_access($fieldvalues);
282           if (in_array($column, array('gr','gw','er','ew')))
283              $fieldvalues[$column]=get_access($fieldvalues,$column);
284           if ($column=="lastmodby")
285              $fieldvalues["lastmodby"]=$USER["id"];
286           if ($column=="lastmoddate")
287              $fieldvalues["lastmoddate"]=time();
288           if (isset($fieldvalues[$column]) && (strlen($fieldvalues[$column])>0))
289              $query.="$column='$fieldvalues[$column]',";
290           else
291              $query.="$column=NULL,";
292        }
293        $column=strtok(",");
294     }
295     $query[strrpos($query,",")]=" ";
296 
297     if ($test) {
298        $query.=" WHERE id='$id'";
299        $result=$db->Execute($query);
300        if ($result)
301           return true;
302     }
303  }
304 
305 
306  ////
307  // !Deletes the entry with id=$id
308  // Returns true on succes, false on failure
309  // Checks whether the delete is allowed
310  // This is very generic, it is likely that you will need to do more cleanup
311  function delete ($db, $tableid, $id, $USER, $filesonly=false) {
312 
313     $table=get_cell($db,"tableoftables","real_tablename","id",$tableid);
314     if (!may_write($db,$tableid,$id,$USER))
315        return false;
316 
317     // check for associated files
318     $r=$db->Execute("SELECT id FROM files
319                      WHERE tablesfk=$tableid AND ftableid=$id");
320     while ($r && !$r->EOF) {
321        delete_file ($db,$r->fields("id"),$USER);
322        $r->MoveNext();
323     }
324     // and now delete for real
325     if (!$filesonly) {
326        if ($db->Execute("DELETE FROM $table WHERE id=$id"))
327           return true;
328        else
329           return false;
330     }
331     else
332        return true;
333  }
334 
335  ////
336  // !Generates thumbnails and extracts information from 2-D image files
337  function process_image($db,$fileid,$bigsize)
338  {
339     global $USER, $system_settings;
340     
341     if (!$fileid)
342        return false;
343     $imagefile=file_path ($db,$fileid);
344     $bigthumb=$system_settings['thumbnaildir']."/big/$fileid.jpg";
345     $smallthumb=$system_settings['thumbnaildir']."/small/$fileid.jpg";
346     $smallsize=$system_settings['smallthumbsize'];
347     $convert=$system_settings['convert'];
348 
349     // make big thumbnail and get image info
350     $command = "$convert -verbose -sample ".$bigsize."x".$bigsize." $action \"$imagefile\" jpg:$bigthumb";
351     exec($command, $result_str_arr, $status);
352 
353     // make small thumbnail
354     $command = "$convert -sample ".$smallsize."x".$smallsize." $action \"$imagefile\" jpg:$smallthumb";
355     `$command`;
356 
357     // get size, mime, and type from image file.
358     // Try exif function, if that fails use convert
359     $sizearray=getimagesize($imagefile);
360     $width=$sizearray[0];
361     if ($width) {
362        $height=$sizearray[1];
363        $mime=$sizearray['mime'];
364        switch ($sizearray[2]) {
365           case 1: $filename_extension='GIF'; break;
366           case 2: $filename_extension='JPG'; break;
367           case 3: $filename_extension='PNG'; break;
368           case 4: $filename_extension='SWF'; break;
369           case 5: $filename_extension='PSD'; break;
370           case 6: $filename_extension='BMP'; break;
371           case 7: $filename_extension='TIFF'; break;
372           case 8: $filename_extension='TIFF'; break;
373           case 9: $filename_extension='JPC'; break;
374           case 10: $filename_extension='JP2'; break;
375           case 11: $filename_extension='JPX'; break;
376           case 12: $filename_extension='JB2'; break;
377           case 13: $filename_extension='SWC'; break;
378           case 14: $filename_extension='IFF'; break;
379        }
380     }
381     else {
382        // get filetype and size in pixels from convert. Take first token after filesize. Don't know if it always works.
383        // appparently convert yields:
384        // original filename, dimensions, Class, (optional) colordepht, size (in kb), filetype, ???, ???
385        $convertresult[0] = strtok ($result_str_arr[0]," ");
386        $test = false;
387        for ($i=1; $i<7; $i++) {
388           $convertresult[$i] = strtok (" ");
389           if ($i == 1)
390              $pixels = $convertresult[$i];
391           if ($test) {
392              $filename_extension = $convertresult[$i];
393              $test = false;
394           }
395           if (substr ($convertresult[$i], -2) == 'kb')
396              $test = true;
397        }
398        // extract pixel dimensions, this fails when there are spaces in the filename
399        $width = (int) strtok ($pixels, 'x+= >');
400        $height = (int) strtok ('x+= >');
401     }
402 
403     if($mime)
404        $db->Execute("UPDATE files SET mime='$mime' WHERE id=$fileid");
405     $r=$db->Execute("SELECT id FROM images WHERE id=$fileid");
406 
407     if (!$r->fields["id"])
408        $query="INSERT INTO images (id,x_size,y_size,xbt_size,ybt_size,xst_size,yst_size,type) VALUES ('$fileid', '$width', '$height', '$bigsize', '$bigsize', '$smallsize', '$smallsize', '$filename_extension')";
409     else
410        $query="UPDATE images SET x_size='$width',y_size='$height',xbt_size='$bigsize',ybt_size='$bigsize',xst_size='$smallsize',yst_size='$smallsize',type='$filename_extension' WHERE id=$fileid";
411     $db->Execute($query);
412     
413  }
414 
415  ////
416  // !Upload files and enters then into table files
417  // files should be called file[] in HTTP_POST_FILES
418  // filetitle in HTTP_POST_VARS will be inserted in the title field of table files
419  // returns id of last uploaded file upon succes, false otherwise
420  function upload_files ($db,$tableid,$id,$columnid,$columnname,$USER,$system_settings)
421  {
422     global $HTTP_POST_FILES,$HTTP_POST_VARS,$system_settings;
423 
424     $table=get_cell($db,'tableoftables','tablename','id',$tableid);
425     $real_tablename=get_cell($db,'tableoftables','real_tablename','id',$tableid);
426 
427     if (!($db && $table && $id)) {
428        echo "Error in code: $db, $table, or $id is not defined.<br>";
429        return false;
430     }
431     if (!may_write($db,$tableid,$id,$USER)) {
432        echo "You do not have permission to write to table $table.<br>";
433        return false;
434     }
435     if (isset($HTTP_POST_FILES["$columnname"]['name'][0]) && !$filedir=$system_settings['filedir']) {
436        echo "<h3><i>Filedir</i> was not set. The file was not uploaded. Please contact your system administrator</h3>";
437        return false;
438     }
439     for ($i=0;$i<sizeof($HTTP_POST_FILES["$columnname"]['name']);$i++) {
440        if (!$fileid=$db->GenID("files_id_seq"))
441           return false;
442        $originalname=$HTTP_POST_FILES["$columnname"]['name'][$i];
443        $mime=$HTTP_POST_FILES["$columnname"]['type'][$i];
444        // sometimes mime types are not set properly, let's try to fix those
445        if (substr($originalname,-4,4)=='.pdf')
446           $mime='application/pdf';
447        // work around php bug??
448        $mime=strtok ($mime,";");
449        $filestype=substr(strrchr($mime,'/'),1);
450        $size=$HTTP_POST_FILES["$columnname"]['size'][$i];
451        $title=$HTTP_POST_VARS['filetitle'][$i];
452        if (!$title)
453           $title='NULL';
454        else
455           $title="'$title'";
456        $type=$HTTP_POST_VARS['filetype'][$i];
457        // this works asof php 4.02
458        if (move_uploaded_file($HTTP_POST_FILES["$columnname"]['tmp_name'][$i],"$filedir/$fileid"."_"."$originalname")) {
459           $query="INSERT INTO files (id,filename,mime,size,title,tablesfk,ftableid,ftablecolumnid,type) VALUES ($fileid,'$originalname','$mime','$size',$title,'$tableid',$id,'$columnid','$filestype')";
460           $db->Execute($query);
461        }
462        else
463           $fileid=false;
464     }
465     return $fileid;
466  }
467 
468 
469  ////
470  // !returns an array with id,name,title,size, and hyperlink to all
471  // files associated with the given record
472  function get_files ($db,$table,$id,$columnid,$format=1,$thumbtype='small') {
473     $tableid=get_cell($db,'tableoftables','id','tablename',$table);
474     $r=$db->Execute("SELECT id,filename,title,mime,type,size FROM files WHERE tablesfk=$tableid AND ftableid=$id AND ftablecolumnid='$columnid'");
475     if ($r && !$r->EOF) {
476        $i=0;
477        $sid=SID;
478        while (!$r->EOF) {
479           $filesid=$files[$i]['id']=$r->fields('id');
480           $filesname=$files[$i]['name']=$r->fields('filename');
481           $filestitle=$files[$i]['title']=$r->fields('title');
482           $mime=$files[$i]['mime']=$r->fields('mime');
483           $filestype=$files[$i]['type']=$r->fields('type');
484           $filesize=$files[$i]['size']=nice_bytes($r->fields('size'));
485           // if this is an image, we'll send the thumbnail
486           $rb=$db->Execute("SELECT id FROM images WHERE id='$filesid'");
487           if ($rb->fields(0)) {
488              $text="<img src=showfile.php?id=$filesid&type=$thumbtype&$sid>";
489           }
490           elseif ($format==1) {
491              if (strlen($filestitle) > 0)
492                 $text=$filestitle;
493              else
494                  $text=$filesname;
495           }
496           elseif ($format==2)
497           $text="file_$i";
498           else
499           $text=$filesname;
500           //$text.="<br>\n";
501           $icon="icons/$filestype.jpg";
502           if (@is_readable($icon))
503              $text="<img src='$icon'>";
504           $files[$i]['link']="<a href='showfile.php?id=$filesid&$sid'>$text</a>\n";
505           $r->MoveNext();
506           $i++;
507        }
508     return $files;
509     }
510  }
511 
512 
513  ////
514  // !Returns path to the file
515  function file_path ($db,$fileid) {
516     global $system_settings;
517     $filename=get_cell($db,'files','filename','id',$fileid);
518     return $system_settings['filedir']."/$fileid"."_$filename";
519  }
520 
521 
522  ////
523  // !Deletes all file associated with this record,column and table
524  function delete_column_file($db,$tableid,$columnid,$recordid,$USER) {
525 
526     $r=$db->Execute("SELECT id FROM files
527                      WHERE tablesfk=$tableid AND ftableid=$recordid AND ftablecolumnid=$columnid");
528     while ($r && !$r->EOF) {
529        delete_file ($db,$r->fields('id'),$USER);
530        $r->MoveNext();
531     }
532  }
533 
534 
535  ////
536  // !Deletes file identified with id.
537  // Checks 'mother table' whether this is allowed
538  // Also deletes entries in index table for this file
539  // Returns name of deleted file on succes
540  function delete_file ($db,$fileid,$USER) {
541     global $system_settings;
542 
543     $tableid=get_cell($db,'files','tablesfk','id',$fileid);
544     $tabledesc=get_cell($db,'tableoftables','table_desc_name','id',$tableid);
545     $ftableid=get_cell($db,'files','ftableid','id',$fileid);
546     $columnid=get_cell($db,'files','ftablecolumnid','id',$fileid);
547     $associated_table=get_cell($db,$tabledesc,'associated_table','id',$columnid);
548     $filename=get_cell($db,'files','filename','id',$fileid);
549     if (!may_write($db,$tableid,$ftableid,$USER))
550        return false;
551     @unlink($system_settings['filedir']."/$fileid"."_$filename");
552     // even if unlink fails we should really remove the entry from the database:
553     $db->Execute("DELETE FROM files WHERE id=$fileid");
554     // if this was an image:
555     $db->Execute("DELETE FROM images WHERE id=$fileid");
556     // remove indexing of file content
557     $db->Execute ("DELETE FROM $associated_table WHERE fileid=$fileid");
558     return $filename;
559  }
560 
561  ////
562  // !Returns a 2D array with id and full name of all users
563  // called by show_access
564  function user_array ($db) {
565     $r=$db->Execute("SELECT id,firstname,lastname FROM users ORDER BY lastname");
566     while (!$r->EOF){
567        $ua[$i]["id"]=$r->fields['id'];
568        if ($r->fields['firstname'])
569           $ua[$i]['name']=$r->fields['firstname']." ".$r->fields['lastname'];
570        else
571           $ua[$i]['name']=$r->fields['lastname'];
572        $i++;
573        $r->MoveNext();
574     }
575     return $ua;
576  }
577   
578  ////
579  // !Prints a table with access rights
580  // input is string as 'rw-rw-rw-'
581  // names are same as used in get_access
582  function show_access ($db,$tableid,$id,$USER,$global_settings) {
583     global $client;
584     $table=get_cell($db,'tableoftables','real_tablename','id',$tableid);
585     if ($id) {
586        $ra=$db->Execute("SELECT gr,gw,er,ew,ownerid FROM $table WHERE id='$id'");
587        if ($ra) {
588           $gr=$ra->fields[0];
589           $gw=$ra->fields[1];
590           $er=$ra->fields[2];
591           $ew=$ra->fields[3];
592           $ownerid=$ra->fields[4];
593        }
594        // $access=get_cell($db,$table,"access","id",$id);
595        // $ownerid=get_cell($db,$table,"ownerid","id",$id);
596        $groupid=get_cell($db,'users','groupid','id',$ownerid);
597        $group=get_cell($db,'groups','name','id',$groupid);
598        $rur=$db->Execute("SELECT trusteduserid FROM trust WHERE tableid='$tableid' AND recordid='$id' AND rw='r'");
599        while (!$rur->EOF) {
600           $ur[]=$rur->fields('trusteduserid');
601           $rur->MoveNext();
602        }
603        $ruw=$db->Execute("SELECT trusteduserid FROM trust WHERE tableid='$tableid' AND recordid='$id' AND rw='w'");
604        while (!$ruw->EOF) {
605           $uw[]=$ruw->fields('trusteduserid');
606           $ruw->MoveNext();
607        }
608     }
609     else {
610        $access=$global_settings['access'];
611        // translate the $access string into our new format
612        if ($access{3}=='r')
613           $gr=1;
614        if ($access{4}=='w')
615           $gw=1;
616        if ($access{6}=='r')
617           $er=1;
618        if ($access{7}=='w')
619           $ew=1;
620        $group=get_cell($db,'groups','name','id',$USER['groupid']);
621     }
622     $user_array=user_array($db);
623     echo "<table border=0>\n";
624     echo "<tr><th>Access:</th><th>$group</th><th>Everyone</th><th>and also</th></tr>\n";
625     echo "<tr><th>Read</th>\n";
626     if ($gr) $sel="checked"; else $sel=false;
627     echo "<td><input type='checkbox' $sel name='grr' value='&nbsp;'></td>\n";
628     if ($er) $sel="checked"; else $sel=false;
629     echo "<td><input type='checkbox' $sel name='evr' value='&nbsp;'></td>\n";
630     // multiple select box for trusted users. Opera does not like 1 as size
631     if ($client->browser=="Opera" || $client->browser=="Internet Explorer")
632        $size=2;
633     else
634         $size=2;
635     echo "<td>\n<select multiple size='$size' name='trust_read[]'>\n";
636     echo "<option>nobody else</option>\n";
637     foreach ($user_array as $user) {
638       if (@in_array($user["id"],$ur))
639           $selected="selected";
640        else
641           $selected=false;
642       echo "<option $selected value=".$user["id"].">".$user["name"]."</option>\n";
643     }
644     echo "</select></td>\n";
645     echo "</tr>\n";
646     echo "<tr><th>Write</th>\n";
647     if ($gw) $sel="checked"; else $sel=false;
648     echo "<td><input type='checkbox' $sel name='grw' value='&nbsp;'></td>\n";
649     if ($ew) $sel="checked"; else $sel=false;
650     echo "<td><input type='checkbox' $sel name='evw' value='&nbsp;'></td>\n";
651     echo "<td>\n<select multiple size='$size' name='trust_write[]'>\n";
652     echo "<option>nobody else</option>\n";
653     foreach ($user_array as $user) {
654       if (@in_array($user["id"],$uw))
655           $selected="selected";
656        else
657           $selected=false;
658        echo "<option $selected value=".$user["id"].">".$user["name"]."</option>\n";
659     }
660     echo "</select></td>\n";
661     echo "</tr>\n";
662     echo "</table>\n";
663  }
664 
665 
666  ////
667  // !Returns a formatted access strings given an associative array
668  // with 'grr','evr','grw','evw' as keys
669  function get_access ($fieldvalues,$column) {
670     global $system_settings;
671     $gr=0; $gw=0; $er=0; $ew=0;
672 
673     if (!$fieldvalues) {
674        $system_settings["access"];
675        // translate the $access string into our new format
676        if ($access{3}=='r')
677           $gr=1;
678        if ($access{4}=='w')
679           $gw=1;
680        if ($access{6}=='r')
681           $er=1;
682        if ($access{7}=='w')
683           $ew=1;
684        return ${$column};
685     }
686     if ($fieldvalues["grr"])
687        $gr=1;
688     if ($fieldvalues["evr"])
689        $er=1;
690     if ($fieldvalues["grw"])
691        $gw=1;
692     if ($fieldvalues["evw"])
693        $ew=1;
694 
695     return ${$column};
696  }
697 
698 
699  ////
700  // !Returns an SQL SELECT statement with ids of records the user may see
701  // Since it uses subqueries it does not work with MySQL
702  function may_read_SQL_subselect ($db,$table,$tableid,$USER,$clause=false) {
703     include_once ('includes/defines_inc.php');
704     $query="SELECT id FROM $table ";
705     // don't know why, but variables defined in defines_in.php are not know here
706     // bug in my php version?
707     $SUPER=64;
708 
709     if ($USER['permissions'] & $SUPER) {
710        if ($clause)
711           $query .= "WHERE $clause";
712     }
713     else {
714        $grouplist=$USER['group_list'];
715        $userid=$USER['id'];
716        $query .= ' WHERE ';
717        if ($clause)
718           $query .= " $clause AND ";
719        // owner
720        $query .= "( (ownerid=$userid) ";
721        // group (quote gr='1', otherwise index willnot be used)
722        $query .= "OR (CAST( (SELECT groupid FROM users WHERE users.id=$table.ownerid) AS int) IN ($grouplist) AND gr='1') ";
723        // world
724        $query .= "OR (er='1')";
725        // and also
726        $query .= "OR id IN (SELECT recordid FROM trust WHERE tableid='$tableid' AND trusteduserid='$userid' AND rw='r')";
727        $query .=")";
728     }
729     return $query;
730  }
731 
732  ////
733  // !returns a comma-separated list of quoted values from a SQL search
734  // helper function for may_read_SQL
735  function make_SQL_ids ($r,$ids,$field="id") {
736     if (!$r || $r->EOF)
737        return substr ($ids,0,-1);
738     $id=$r->fields[$field];
739     $ids .="$id";
740     $r->MoveNext();
741     $column_count=1;
742     while (!$r->EOF) {
743        $id=$r->fields[$field];
744        if ($id)
745           $ids .=",$id";
746        $r->MoveNext();
747        $column_count+=1;
748     }
749     return ($ids);
750  }
751 
752 
753  ////
754  // !Returns an array with ids of records the user may see in SQL format
755  // Works with MySQL but not with early postgres 7 versions (current ones should
756  // work)
757  function may_read_SQL_JOIN ($db,$table,$USER) {
758     include ('includes/defines_inc.php');
759     if (!($USER["permissions"] & $SUPER)) {
760        $query="SELECT id FROM $table ";
761        $usergroup=$USER['groupid'];
762        $group_list=$USER['group_list'];
763        $userid=$USER['id'];
764        $query .= " WHERE ";
765        // owner and everyone
766        $query .= "( (ownerid=$userid) ";
767        $query .= "OR (er='1')";
768        $query .=")";
769        $r=$db->CacheExecute(2,$query);
770        if ($r) {
771           $ids=make_SQL_ids($r,$ids);
772        }
773        // group
774        $query="SELECT $table.id FROM $table LEFT JOIN users ON $table.ownerid=users.id WHERE users.groupid IN ($group_list) AND ($table.gr='1')";
775        $r=$db->CacheExecute(2,$query);
776     }
777     else { // superuser
778        $query="SELECT id FROM $table ";
779        $r=$db->CacheExecute(2,$query);
780     }
781     if ($ids)
782        $ids.=",";
783     if ($r)
784        return make_SQL_ids($r,$ids);
785  }
786 
787 
788  ////
789  // !Generates an SQL query asking for the records that mey be seen by this users
790  // Generates a left join for mysql, subselect for postgres
791  function may_read_SQL ($db,$tableinfo,$USER,$temptable="tempa") {
792     global $db_type;
793     if ($db_type=='mysql') {
794        $list=may_read_SQL_JOIN ($db,$tableinfo->realname,$USER);
795        if (!$list)
796           $list='-1';
797        $result['sql']= " id IN ($list) ";
798        $result['numrows']=substr_count($list,',');
799     }
800     else {
801        //return may_read_SQL_subselect ($db,$table,$tableid,$USER);
802        $r=$db->Execute(may_read_SQL_subselect ($db,$tableinfo->realname,$tableinfo->id,$USER,false));
803        $result['numrows']=$r->NumRows();
804        make_temp_table($db,$temptable,$r);
805        $result['sql'] = " ($tableinfo->realname.id = $temptable.uniqueid) ";
806     }
807     return $result;
808  }
809 
810  ////
811  // Generates a temporary table from given recordset
812  function make_temp_table ($db,$temptable,$r) {
813     global $system_settings;
814     $rc=$db->Execute("CREATE TEMPORARY TABLE $temptable (
815                       uniqueid int UNIQUE NOT NULL)");
816     if ($rc) {
817        $r->MoveFirst();
818        while (!$r->EOF) {
819           $string .= $r->fields["id"]."\n";
820           $r->MoveNext();
821        }
822     }
823     // INSERT is too slow. COPY instead from a file. postgres only!
824     $tmpfile=tempnam($system_settings["tmppsql"],"tmptable");
825     $fp=fopen($tmpfile,"w");
826     fwrite($fp,$string);
827     fflush($fp);
828     chmod ($tmpfile,0644);
829     $rd=$db->Execute ("COPY $temptable FROM '$tmpfile'");
830     $rc=$db->Execute("ALTER TABLE $temptable ADD PRIMARY KEY (uniqueid)");
831     fclose ($fp);
832     unlink($tmpfile);
833  }
834 
835  ////
836  // !determines whether or not the user may read this record
837  function may_read ($db,$tableinfo,$id,$USER) {
838     $list=may_read_SQL($db,$tableinfo,$USER);
839     $query="SELECT id FROM $tableinfo->realname WHERE ".$list["sql"];
840     $r=$db->Execute($query);
841     if (!$r)
842        return false;
843     if ($r->EOF)
844        return false;
845     else
846        return true;
847  }
848 
849  ////
850  // !checks if this user may write/modify/delete these data
851  function may_write ($db,$tableid,$id,$USER) {
852     include ('includes/defines_inc.php');
853     
854     $table=get_cell($db,'tableoftables','real_tablename','id',$tableid);
855     if ($USER['permissions'] & $SUPER)
856        return true;
857     if ( ($USER['permissions'] & $WRITE) && (!$id))
858        return true;
859     $ownerid=get_cell($db,$table,'ownerid','id',$id);
860     $ownergroup=get_cell($db,'users','groupid','id',$ownerid);
861     if ($USER['permissions'] & $ADMIN) {
862        if ($USER['groupid']==$ownergroup)
863           return true;
864     }
865     if ( ($USER['permissions'] & $WRITE) && $id) {
866        $userid=$USER['id'];
867        // 'user' write access
868        if ($r=$db->Execute("SELECT * FROM $table WHERE id=$id AND
869              ownerid=$userid"))
870           if (!$r->EOF)
871              return true;
872        // 'group' write access
873        if ($r=$db->Execute("SELECT * FROM $table WHERE id=$id AND gw='1'"))
874           if (!$r->EOF && in_array($ownergroup, $USER['group_array']))
875              return true;
876        // 'world' write access
877        if ($r=$db->Execute("SELECT * FROM $table WHERE id=$id AND ew='1'") )
878           if (!$r->EOF)
879              return true;
880        // 'and also' write access
881        if ($r=$db->Execute("SELECT * FROM trust WHERE trusteduserid='$userid'
882                AND tableid='$tableid' AND recordid='$id' AND rw='w'"))
883           if (!$r->EOF)
884              return true;
885     }
886  }
887 
888  ////
889  // !returns an comma-separated list of quoted values from a SQL search
890  // derived from make_SQL_ids but can be called from anywhere
891  function make_SQL_csf ($r,$ids,$field="id",&$column_count) {
892     if (!$r || $r->EOF)
893        return false;
894     $r->MoveFirst();
895     while (!$id && !$r->EOF) {
896        $id=$r->fields[$field];
897        $ids .="$id";
898        $r->MoveNext();
899     }
900     $column_count=1;
901     unset ($id);
902     while (!$r->EOF) {
903        $id=$r->fields[$field];
904        if ($id) {
905           $ids .=",$id";
906           $column_count+=1;
907        }
908        $r->MoveNext();
909     }
910     return ($ids);
911  }
912  ////
913  // !helperfunction for numerictoSQL
914  function typevalue ($value,$type) {
915     if ($type=="int") {
916        return (int)$value;
917     }
918     elseif ($type=="float") {
919        return (float)$value;
920     }
921     return false;
922  }
923 
924  ////
925  // !interprets numerical search terms into an SQL statement
926  // implements ranges (i.e. 1-6), and lists (1,2,3) and combinations thereof
927  // < and > can also be used
928  function numerictoSQL ($searchterm,$column,$type,$and) {
929     $commalist=explode(",",$searchterm);
930     for ($i=0;$i<sizeof($commalist);$i++) {
931        $rangelist=explode("-",$commalist[$i]);
932        if (sizeof($rangelist)==2) {
933           sort($rangelist);
934           $value1=typevalue($rangelist[0],$type);
935           $value2=typevalue($rangelist[1],$type);
936           if ($i>0) {
937              $sql.="OR ";
938           }
939           $sql.="($column>=$value1 AND $column<=$value2) ";
940        }
941        elseif (sizeof($rangelist)==1) {
942           if ($commalist[$i]{0}=='<' || $commalist[$i]{0}=='>') {
943              $token=$commalist[$i]{0};
944              $commalist[$i]=substr($commalist[$i],1);
945           }
946           $value=typevalue ($commalist[$i],$type);
947           if ($i>0) {
948              $sql.="OR ";
949           }
950           if (!$token)
951              $token='=';
952           $sql.="($column$token$value) ";
953        }
954     }
955     return "$and ($sql) ";
956  }
957 
958  ////
959  // !Helper function for search
960  // Interprets fields the right way
961  function searchhelp ($db,$tableinfo,$column,&$columnvalues,$query,$wcappend,$and) {
962     if ($column=="ownerid") {
963        $query[1]=true;
964        $r=$db->Execute("SELECT id FROM ".$tableinfo->realname." WHERE ownerid=$columnvalues[$column]");
965        $list=make_SQL_ids($r,false);
966        if ($list)
967           $query[0].= "$and id IN ($list) ";
968     }
969     else {
970        $query[1]=true;
971        // since all tables now have desc. tables,we can check for int/floats
972        // should probably do this more upstream for performance gain
973        $rc=$db->Execute("SELECT type,datatype,associated_table,key_table,associated_column,associated_local_key FROM ".$tableinfo->desname." WHERE columnname='$column'");
974        if ($rc->fields[1]=='file' && $rc->fields[2]) {
975           $rw=$db->Execute("SELECT id FROM words WHERE word LIKE '".strtolower($columnvalues[$column])."%'");
976           if ($rw && $rw->fields[0]) {
977              $rh=$db->Execute("SELECT recordid FROM ".$rc->fields[2]." WHERE wordid='".$rw->fields[0]."'");
978              if ($rh && $rh->fields[0]) {
979                  while (!$rh->EOF) {
980                     $rhtemp[]=$rh->fields[0];
981                     $rh->MoveNext();
982                  }
983                  $ids=join (",",$rhtemp);
984                  $query[0].="$and id IN ($ids) ";
985               }
986           // if we come up empty handed, the SQL search should too:
987           else $query[0].="$and id=0 ";
988           }
989           else $query[0].="$and id=0 ";
990        }
991        elseif ($rc->fields[1]=='table') {
992           $rtableoftables=$db->Execute("SELECT real_tablename,table_desc_name,id FROM tableoftables WHERE id={$rc->fields['associated_table']}");
993           $rtdesc=$db->Execute("SELECT columnname,datatype,type FROM {$rtableoftables->fields[1]} WHERE id='{$rc->fields['associated_column']}'");
994           $tablecolumnvalues[$rtdesc->fields[0]]=$columnvalues[$column];
995           $asstableinfo=new tableinfo($db,false,$rtableoftables->fields[2]);
996           $table_where=searchhelp($db,$asstableinfo,$rtdesc->fields[0],&$tablecolumnvalues,false,$wcappend,false);
997           $rtable=$db->Execute("SELECT id FROM {$rtableoftables->fields[0]} WHERE {$table_where[0]}");
998           if ($rtable && $rtable->fields[0]) {
999               while (!$rtable->EOF) {
1000                  $rhtemp[]=$rtable->fields[0];
1001                  $rtable->MoveNext();
1002               }
1003               $ids=join (",",$rhtemp);
1004               if ($rc->fields['associated_local_key']) {
1005                  $rasslk=$db->Execute("SELECT columnname FROM {$tableinfo->desname} WHERE id={$rc->fields['associated_local_key']}");
1006                  $query[0].="$and {$rasslk->fields[0]} IN ($ids) ";
1007               }
1008               else
1009                  $query[0].="$and $column IN ($ids) ";
1010           }
1011           // no search results so give an impossible clause
1012           else
1013              $query[0].="$and $column='0' ";
1014        }
1015        // there are some (old) cases where pulldowns are of type text...
1016        elseif ($rc->fields[1]=='pulldown') {
1017           $columnvalues[$column]=(int)$columnvalues[$column];
1018           if ($columnvalues["$column"]==-1)
1019              $query[0].="$and ($column='' OR $column IS NULL) ";
1020           else
1021              $query[0].="$and $column='$columnvalues[$column]' ";
1022        }
1023        elseif ($rc->fields[1]=='mpulldown') {
1024           // emulate a logical AND between values selected in a mpulldown
1025           unset ($id_list);
1026           // keep the code to deal with single selects and multiple selects
1027           if (is_array($columnvalues)) {
1028              unset($id_list);
1029              $j=0;
1030              // read in values from types tables and arrange in groups
1031              foreach($columnvalues[$column] as $typeid) {
1032                 $rl=$db->Execute("SELECT recordid FROM {$rc->fields[3]} WHERE typeid=$typeid");
1033                 while ($rl && !$rl->EOF) {
1034                    $id_list[$j].=$rl->fields[0].',';
1035                    $rl->MoveNext();
1036                 }
1037                 $id_list[$j]=substr($id_list[$j],0,-1);
1038                 // if nothing is found we'll pass an impossible id value
1039                 if (strlen($id_list[$j]) <1)
1040                    $id_list[$j]='-1';
1041                 $j++;
1042              }
1043           }
1044           else { // for 'single' selects
1045              $rmp=$db->Execute("SELECT recordid FROM {$rc->fields[3]} WHERE typeid='{$columnvalues[$column]}'");
1046              if ($rmp) {
1047                 $id_list=$rmp->fields[0];
1048                 $rmp->MoveNext();
1049                 while (!$rmp->EOF) {
1050                    $id_list.=",{$rmp->fields[0]}";
1051                    $rmp->MoveNext();
1052                 }
1053              }
1054           }
1055           // pass the multiple lists to the main query
1056           if (is_array($id_list)) {
1057              foreach ($id_list as $list) {
1058                 if (!$listfound) {
1059                    $query[0].="$and id IN ($list) ";
1060                    $listfound=true;
1061                 }
1062                 else
1063                    $query[0].="AND id IN ($list) ";
1064              }
1065              // we should not be able to get here:
1066              if (!$listfound)
1067                 $query[0].="$and id IN (-1) ";
1068           }
1069           elseif ($id_list) // for 'single' selects
1070              $query[0].="$and id IN ($id_list) ";
1071           else // nothing found, make sure we do not crash the search statement
1072              $query[0].="$and id IN (-1) ";
1073              
1074        }
1075        elseif (substr($rc->fields[0],0,3)=='int') {
1076           $query[0].=numerictoSQL ($columnvalues[$column],$column,"int",$and);
1077        }
1078        elseif (substr($rc->fields[0],0,5)=='float') {
1079           $query[0].=numerictoSQL ($columnvalues[$column],$column,"float",$and);
1080        }
1081        else {
1082           $columnvalues[$column]=trim($columnvalues[$column]);
1083           $columnvalue=$columnvalues[$column];
1084           $columnvalue=str_replace('*','%',$columnvalue);
1085           if ($wcappend)
1086              $columnvalue="%$columnvalue%";
1087           //else
1088           // $columnvalue="% $columnvalue %";
1089           $query[0].="$and UPPER($column) LIKE UPPER('$columnvalue') ";
1090        }
1091     }
1092     return $query;
1093  }
1094 
1095  ////
1096  // !Returns an SQL search statement
1097  // The whereclause should NOT start with WHERE
1098  // The whereclause should contain the output of may_read_SQL and
1099  // can also be used for sorting
1100  function search ($db,$tableinfo,$fields,&$fieldvalues,$whereclause=false,$wcappend=true) {
1101     $columnvalues=$fieldvalues;
1102     $query[0]="SELECT $fields FROM ".$tableinfo->realname." WHERE ";
1103     $query[1]=$query[2]=false;
1104     $column=strtok($fields,",");
1105     while ($column && !$columnvalues[$column])
1106        $column=strtok (",");
1107     if ($column && $columnvalues[$column]) {
1108        $query[1]=true;
1109        $query=searchhelp ($db,$tableinfo,$column,$columnvalues,$query,$wcappend,false);
1110     }
1111     $column=strtok (",");
1112     while ($column) {
1113        if ($column && $columnvalues[$column]) {
1114           $query=searchhelp ($db,$tableinfo,$column,$columnvalues,$query,$wcappend,"AND");
1115        }
1116        $column=strtok (",");
1117     }
1118     if ($whereclause)
1119        if ($query[1])
1120           $query[0] .= "AND $whereclause";
1121        else
1122           $query[0] .= $whereclause;
1123     if (function_exists("plugin_search"))
1124        $query[0]=plugin_search($query[0],$columnvalues,$query[1]);
1125     return $query[0];
1126  }
1127 
1128 
1129  ////
1130  // ! sets AtFirstPage and AtLastPage
1131  function first_last_page (&$r,&$current_page,$r_p_p,$numrows) {
1132     // protect against pushing the reload button while at the last page
1133     if ( (($current_page-1) * $r_p_p) >= $numrows)
1134        $current_page -=1;
1135     // if we are still outof range, this must be a new search statement and we can go to page 1
1136     if ( (($current_page-1) * $r_p_p) >= $numrows)
1137        $current_page =1;
1138 
1139     if ($current_page < 2)
1140        $r->AtFirstPage=true;
1141     else
1142        $r->AtFirstPage=false;
1143     if ( ($current_page * $r_p_p) >= $numrows)
1144        $r->AtLastPage=true;
1145     else
1146        $r->AtLastPage=false;
1147  }
1148 
1149  ////
1150  // !Displays the next and previous buttons
1151  // $r is the result of a $db->Execute query used to display the table with records
1152  // When $paging is true, the records per page field will also be displayed
1153  // $num_p_r holds the (global) records per page variable
1154  function next_previous_buttons($r,$paging=false,$num_p_r=false,$numrows=false,$pagenr=false,$db=false,$tableinfo=false) {
1155     echo "<table border=0 width=100%>\n<tr width=100%>\n<td align='left'>";
1156     if (function_exists($r->AtFirstPage))
1157        $r->AtFirstPage=$r->AtFirstPage();
1158     if ($r && !$r->AtFirstPage)
1159        echo "<input type=\"submit\" name=\"previous\" value=\"Previous\"></td>\n";
1160     else
1161        if ($paging)
1162           echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>\n";
1163        else
1164           echo "&nbsp;</td>\n";
1165     if ($db && $tableinfo)
1166        show_reports($db,$tableinfo);
1167     if ($paging) {
1168        if ($numrows>0) {
1169           echo "<td align='center'>$numrows Records found. ";
1170           if ($pagenr) {
1171              $start=($pagenr-1)*$num_p_r+1;
1172              $end=$pagenr*$num_p_r;
1173              if ($end > $numrows)
1174                 $end=$numrows;
1175              echo "Showing $start through $end. ";
1176           }
1177           echo "</td>\n";
1178        }
1179        else
1180           echo "<td align='center'>No records found. </td>\n";
1181        echo "<td align='center'>\n";
1182        echo "<input type='text' name='num_p_r'value='$num_p_r' size=3>&nbsp;";
1183        echo "Records per page</td>\n";
1184     }
1185     echo "<td align='right'>";
1186 
1187     // add direct links to pages
1188     if ($pagenr) {
1189        $startp=$pagenr-5;
1190        if ($startp<1)
1191           $startp=1;
1192        $endp=$startp+9;
1193        if ($numrows) {
1194           if ($numrows < ($endp*$num_p_r)) {
1195              $endp= ceil($numrows/$num_p_r);
1196           }
1197        }
1198 
1199        if ($endp > 1) {
1200           echo "Goto page: ";
1201           echo "<input type='hidden' name='{$tableinfo->pagename}' value='0'>\n";
1202           for ($i=$startp; $i<=$endp; $i++) {
1203              if ($pagenr==$i)
1204                 echo "<b>$i </b>";
1205              else
1206              // try using links with javascript converting it into post variables
1207                 echo "<a href='javascript:document.g_form.{$tableinfo->pagename}.value=\"$i\"; document.g_form.searchj.value=\"Search\"; document.g_form.submit()'>$i </a>";
1208           }
1209        }
1210     }
1211       
1212     if (function_exists($r->AtLastPage))
1213        $r->AtLastPage=$r->AtLastPage();
1214     if ($r && !$r->AtLastPage)
1215        echo "<input type=\"submit\" name=\"next\" value=\"Next\"></td>\n";
1216     else
1217        if ($paging)
1218           echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
1219        else
1220           echo "&nbsp;";
1221     echo "</td>\n</tr>\n";
1222     echo "</table>\n";
1223  }
1224 
1225  ////
1226  // !Returns the variable $num_p_r holding the # of records per page
1227  // check user settings and POST_VARS
1228  // Write the value back to the user defaults
1229  // When no value is found, default to 10
1230  function paging ($num_p_r,&$USER) {
1231     global $HTTP_POST_VARS;
1232     if (!$num_p_r)
1233        $num_p_r=$USER['settings']['num_p_r'];
1234     if (isset($HTTP_POST_VARS['num_p_r']))
1235        $num_p_r=$HTTP_POST_VARS['num_p_r'];
1236     if (!isset($num_p_r))
1237       $num_p_r=10;
1238     $USER['settings']['num_p_r']=$num_p_r;
1239     return $num_p_r;
1240  }
1241 
1242  ////
1243  // !Returns current page
1244  // current page is table specific, therefore
1245  // The variable name is formed using the short name for the table
1246  function current_page($curr_page, $sname, $num_p_r, $numrows) {
1247     global $HTTP_POST_VARS, $HTTP_SESSION_VARS;
1248     $varname=$sname.'_curr_page';
1249     ${$varname}=$curr_page;
1250 
1251     if (!isset($$varname))
1252        ${$varname}=$HTTP_SESSION_VARS[$varname];
1253     // if the current page is out of bound, we'll reset it to 1
1254     if (${$varname} > ($numrows/$num_p_r))
1255        ${$varname}=1;
1256     // the page number can be set directly or by clicking the next/previous buttons (see function next_previous_buttons)
1257     if ($HTTP_POST_VARS[$varname]) {
1258        ${$varname}=$HTTP_POST_VARS[$varname];
1259     }
1260     elseif (isset($HTTP_POST_VARS['next'])) {
1261        ${$varname}+=1;
1262     }
1263     elseif (isset($HTTP_POST_VARS['previous'])) {
1264        $$varname-=1;
1265     }
1266     if ($$varname<1)
1267        $$varname=1;
1268     $HTTP_SESSION_VARS[$varname]=${$varname};
1269     session_register($varname);
1270     return ${$varname};
1271  }
1272 
1273  ////
1274  // !Assembles the search SQL statement and remembers it in HTTP_SESSION_VARS
1275  function make_search_SQL($db,$tableinfo,$fields,$USER,$search,$searchsort="title",$whereclause=false) {
1276     global $HTTP_POST_VARS, $HTTP_SESSION_VARS;
1277 
1278     if (!$searchsort)
1279        $searchsort='title';
1280     $fieldvarsname=$tableinfo->short.'_fieldvars';
1281     global ${$fieldvarsname};
1282     $queryname=$tableinfo->short.'_query';
1283     if (!$whereclause)
1284        $whereclause=may_read_SQL ($db,$tableinfo,$USER);
1285     if (!$whereclause)
1286        $whereclause=-1;
1287     if ($search=='Search') {
1288        ${$queryname}=search($db,$tableinfo,$fields,$HTTP_POST_VARS," $whereclause ORDER BY $searchsort");
1289        ${$fieldvarsname}=$HTTP_POST_VARS;
1290     }
1291     elseif (session_is_registered ($queryname) && isset($HTTP_SESSION_VARS[$queryname])) {
1292        ${$queryname}=$HTTP_SESSION_VARS[$queryname];
1293        ${$fieldvarsname}=$HTTP_SESSION_VARS[$fieldvarsname];
1294     }
1295     else {
1296        ${$queryname} = "SELECT $fields FROM $tableinfo->realname WHERE $whereclause ORDER BY date DESC";
1297        ${$fieldvarsname}=$HTTP_POST_VARS;
1298     }
1299     $HTTP_SESSION_VARS[$queryname]=${$queryname};
1300     session_register($queryname);
1301     if (!${$fieldvarsname})
1302        ${$fieldvarsname}=$HTTP_POST_VARS;
1303     $HTTP_SESSION_VARS[$fieldvarsname]=${$fieldvarsname};
1304     session_register($fieldvarsname);
1305 
1306     if ($search !='Show All') {
1307        // globalize HTTP_POST_VARS
1308        $column=strtok($fields,',');
1309        while ($column) {
1310           global ${$column};
1311           ${$column}=$HTTP_POST_VARS[$column];
1312           $column=strtok(',');
1313        }
1314        // extract variables from session
1315        globalize_vars ($fields, ${$fieldvarsname});
1316     }
1317  //echo "${$queryname}.<br>";
1318     return ${$queryname};
1319  }
1320 
1321 
1322  ////
1323  // !Checks whether a user has access to a given table
1324  //
1325  function may_see_table($db,$USER,$tableid) {
1326     include ('includes/defines_inc.php');
1327     // Sysadmin may see it all
1328     if ($USER['permissions'] & $SUPER)
1329        return true;
1330     $group_list=$USER['group_list'];
1331     $r=$db->Execute ("SELECT tableid FROM groupxtable_display WHERE groupid IN ($group_list) AND tableid='$tableid'");
1332     if ($r && !$r->EOF)
1333        return true;
1334     else
1335        return false;
1336  }
1337 
1338  ?>


Generated: Sun Oct 5 21:17:35 2003 SourceForge Logo Generated by PHPXref 0.2