SavedSearch.php

Go to the documentation of this file.
00001 <?PHP
00002 #
00003 #   FILE:  SavedSearch.php
00004 #
00005 #   NOTES:
00006 #       - the "$SearchGroups" values used herein contain a multi-dimentional
00007 #           array in the form of:
00008 #               $Criteria["MAIN"]["SearchStrings"][<field names>] = <value>
00009 #           for fields with a single value, and:
00010 #               $Criteria[<field ID>]["SearchStrings"][<field name>][] = <value>
00011 #           for fields with multiple values
00012 #
00013 #   Part of the Collection Workflow Integration System (CWIS)
00014 #   Copyright 2005-2010 Edward Almasy and Internet Scout
00015 #   http://scout.wisc.edu/cwis
00016 #
00017 
00018 class SavedSearch {
00019 
00020     # ---- PUBLIC INTERFACE --------------------------------------------------
00021 
00022     # search frequency mnemonics
00023     const SEARCHFREQ_NEVER =      0;
00024     const SEARCHFREQ_HOURLY =     1;
00025     const SEARCHFREQ_DAILY =      2;
00026     const SEARCHFREQ_WEEKLY =     3;
00027     const SEARCHFREQ_BIWEEKLY =   4;
00028     const SEARCHFREQ_MONTHLY =    5;
00029     const SEARCHFREQ_QUARTERLY =  6;
00030     const SEARCHFREQ_YEARLY =     7;
00031 
00032     # object constructor
00033     function SavedSearch($SearchId, $SearchName = NULL, $UserId = NULL,
00034             $Frequency = NULL, $SearchGroups = NULL)
00035     {
00036         # get our own database handle
00037         $this->DB = new Database();
00038 
00039         # if search ID was provided
00040         if ($SearchId !== NULL)
00041         {
00042             # save search ID
00043             $this->SearchId = intval($SearchId);
00044 
00045             # initialize our local copies of data
00046             $this->DB->Query("SELECT * FROM SavedSearches"
00047                     ." WHERE SearchId = '".$this->SearchId."'");
00048             $this->Record = $this->DB->FetchRow();
00049 
00050             # update search details where provided
00051             if ($SearchName) {  $this->SearchName($SearchName);  }
00052             if ($UserId)     {  $this->UserId($UserId);  }
00053             if ($Frequency)  {  $this->Frequency($Frequency);  }
00054         }
00055         else
00056         {
00057             # add new saved search to database
00058             $this->DB->Query("INSERT INTO SavedSearches"
00059                     ." (SearchName, UserId, Frequency) VALUES ("
00060                     ."'".addslashes($SearchName)."', "
00061                     .intval($UserId).", "
00062                     .intval($Frequency).")");
00063 
00064             # retrieve and save ID of new search locally
00065             $this->SearchId = $this->DB->LastInsertId("SavedSearches");
00066 
00067             # save frequency and user ID locally
00068             $this->Record["SearchName"] = $SearchName;
00069             $this->Record["UserId"] = $UserId;
00070             $this->Record["Frequency"] = $Frequency;
00071         }
00072 
00073         # save search parameters if provided
00074         if ($SearchGroups) {  $this->SearchGroups($SearchGroups);  }
00075     }
00076 
00077     # get/set search parameters
00078     function SearchGroups($NewSearchGroups = NULL)
00079     {
00080         $Schema = new MetadataSchema();
00081 
00082         # if new search parameters were supplied
00083         if ($NewSearchGroups)
00084         {
00085             # remove existing entries for this search from the database
00086             $this->DB->Query("DELETE FROM SavedSearchTextParameters WHERE SearchId = ".$this->SearchId);
00087             $this->DB->Query("DELETE FROM SavedSearchIdParameters WHERE SearchId = ".$this->SearchId);
00088 
00089             # for each search group
00090             foreach ($NewSearchGroups as $GroupIndex => $Group)
00091             {
00092                 # if group holds single parameters
00093                 if ($GroupIndex == "MAIN")
00094                 {
00095                     # for each field within group
00096                     foreach ($Group["SearchStrings"] as $FieldName => $Value)
00097                     {
00098                         # convert value array to single value (if necessary)
00099                         if (is_array($Value))
00100                         {
00101                             $ConvertedValue = "";
00102                             foreach ($Value as $SingleValue)
00103                             {
00104                                 $ConvertedValue .= $SingleValue." ";
00105                             }
00106                             $Value = trim($ConvertedValue);
00107                         }
00108 
00109                         # add new text search parameter entry to database
00110                         if ($FieldName == "XXXKeywordXXX")
00111                         {
00112                             $FieldId = -101;
00113                         }
00114                         else
00115                         {
00116                             $Field = $Schema->GetFieldByName($FieldName);
00117                             $FieldId = $Field->Id();
00118                         }
00119                         $this->DB->Query("INSERT INTO SavedSearchTextParameters"
00120                                 ." (SearchId, FieldId, SearchText) VALUES"
00121                                 ." (".$this->SearchId.", ".$FieldId.", '".addslashes($Value)."')");
00122                     }
00123                 }
00124                 else
00125                 {
00126                     # convert value(s) as appropriate for field type
00127                     $FieldId = $GroupIndex;
00128                     $Field = $Schema->GetField($FieldId);
00129                     $FieldName = $Field->Name();
00130                     $Values = SavedSearch::TranslateValues($Field, $Group["SearchStrings"][$FieldName], "SearchGroup to Database");
00131 
00132                     # for each converted value
00133                     foreach ($Values as $Value)
00134                     {
00135                         # add new ID search parameter entry to database
00136                         $this->DB->Query("INSERT INTO SavedSearchIdParameters"
00137                                 ." (SearchId, FieldId, SearchValueId) VALUES"
00138                                 ." (".$this->SearchId.", ".$FieldId.", ".$Value.")");
00139                     }
00140                 }
00141             }
00142 
00143             # save search parameters locally
00144             $this->SearchGroups = $NewSearchGroups;
00145         }
00146         else
00147         {
00148             # if search groups not already read in
00149             if (!isset($this->SearchGroups))
00150             {
00151                 # for each text search parameter
00152                 $SearchGroups = array();
00153                 $this->DB->Query("SELECT * FROM SavedSearchTextParameters WHERE SearchId = ".$this->SearchId);
00154                 while ($Record = $this->DB->FetchRow())
00155                 {
00156                     # add parameter to search criteria
00157                     if ($Record["FieldId"] == -101)
00158                     {
00159                         $SearchGroups["MAIN"]["SearchStrings"]["XXXKeywordXXX"] =
00160                                 $Record["SearchText"];
00161                     }
00162                     else
00163                     {
00164                         $Field = $Schema->GetField($Record["FieldId"]);
00165                         $SearchGroups["MAIN"]["SearchStrings"][$Field->Name()] =
00166                                 $Record["SearchText"];
00167                     }
00168                 }
00169 
00170                 # for each value ID search parameter
00171                 $this->DB->Query("SELECT * FROM SavedSearchIdParameters WHERE SearchId = ".$this->SearchId);
00172                 while ($Record = $this->DB->FetchRow())
00173                 {
00174                     # translate value based on field type
00175                     $FieldId = $Record["FieldId"];
00176                     if (!isset($Fields[$FieldId])) {  $Fields[$FieldId] = new MetadataField($FieldId);  }
00177                     $Values = SavedSearch::TranslateValues($Fields[$FieldId],
00178                             $Record["SearchValueId"], "Database to SearchGroup");
00179 
00180                     # add parameter to search criteria
00181                     foreach ($Values as $Value)
00182                     {
00183                         $SearchGroups[$FieldId]["SearchStrings"][$Fields[$FieldId]->Name()][] = $Value;
00184                     }
00185                 }
00186 
00187                 # set appropriate logic in search parameters
00188                 foreach ($SearchGroups as $GroupIndex => $Group)
00189                 {
00190                     $SearchGroups[$GroupIndex]["Logic"] =
00191                             ($GroupIndex == "MAIN") ? SearchEngine::LOGIC_AND
00192                             : SearchEngine::LOGIC_OR;
00193                 }
00194 
00195                 # save search parameters locally
00196                 $this->SearchGroups = $SearchGroups;
00197             }
00198         }
00199 
00200         # return search parameters to caller
00201         return $this->SearchGroups;
00202     }
00203 
00209     function SearchName($NewValue = DB_NOVALUE)
00210             {  return $this->UpdateValue("SearchName", $NewValue);  }
00211 
00216     function Id() {  return $this->SearchId;  }
00217 
00223     function UserId($NewValue = DB_NOVALUE)
00224             {  return $this->UpdateValue("UserId", $NewValue);  }
00225 
00231     function Frequency($NewValue = DB_NOVALUE)
00232             {  return $this->UpdateValue("Frequency", $NewValue);  }
00233 
00234     # set date search was last run to current date/time
00235     function UpdateDateLastRun()
00236     {
00237         $this->DB->Query("UPDATE SavedSearches SET DateLastRun = NOW() WHERE SearchId = ".$this->SearchId);
00238     }
00239 
00240     # get/set date search was last run
00241     function DateLastRun($NewValue = DB_NOVALUE)
00242             {  return $this->UpdateValue("DateLastRun", $NewValue);  }
00243 
00249     function GetSearchGroupsAsUrlParameters()
00250     {
00251         return self::TranslateSearchGroupsToUrlParameters($this->SearchGroups());
00252     }
00253 
00260     static function TranslateSearchGroupsToUrlParameters($SearchGroups)
00261     {
00262         # assume that no parameters will be found
00263         $UrlPortion = "";
00264 
00265         # for each group in parameters
00266         $Schema = new MetadataSchema();
00267         foreach ($SearchGroups as $GroupIndex => $Group)
00268         {
00269             # if group holds single parameters
00270             if ($GroupIndex == "MAIN")
00271             {
00272                 # for each field within group
00273                 foreach ($Group["SearchStrings"] as $FieldName => $Value)
00274                 {
00275                     # add segment to URL for this field
00276                     if ($FieldName == "XXXKeywordXXX")
00277                     {
00278                         $FieldId = "K";
00279                     }
00280                     else
00281                     {
00282                         $Field = $Schema->GetFieldByName($FieldName);
00283                         $FieldId = $Field->Id();
00284                     }
00285                     if (is_array($Value))
00286                     {
00287                         $UrlPortion .= "&F".$FieldId."=";
00288                         $ValueString = "";
00289                         foreach ($Value as $SingleValue)
00290                         {
00291                             $ValueString .= $SingleValue." ";
00292                         }
00293                         $UrlPortion .= urlencode(trim($ValueString));
00294                     }
00295                     else
00296                     {
00297                         $UrlPortion .= "&F".$FieldId."=".urlencode($Value);
00298                     }
00299                 }
00300             }
00301             else
00302             {
00303                 # convert value based on field type
00304                 $FieldId = $GroupIndex;
00305                 $Field = $Schema->GetField($FieldId);
00306                 $FieldName = $Field->Name();
00307                 $Values = SavedSearch::TranslateValues($Field, $Group["SearchStrings"][$FieldName], "SearchGroup to Database");
00308 
00309                 # add values to URL
00310                 $FirstValue = TRUE;
00311                 foreach ($Values as $Value)
00312                 {
00313                     if ($FirstValue)
00314                     {
00315                         $FirstValue = FALSE;
00316                         $UrlPortion .= "&G".$FieldId."=".$Value;
00317                     }
00318                     else
00319                     {
00320                         $UrlPortion .= "-".$Value;
00321                     }
00322                 }
00323             }
00324         }
00325 
00326         # trim off any leading "&"
00327         if (strlen($UrlPortion)) {  $UrlPortion = substr($UrlPortion, 1);  }
00328 
00329         # return URL portion to caller
00330         return $UrlPortion;
00331     }
00332 
00338     function GetSearchGroupsAsUrlParameterArray()
00339     {
00340         return self::TranslateSearchGroupsToUrlParameters($this->SearchGroups());
00341     }
00342 
00349     static function TranslateSearchGroupsToUrlParameterArray($SearchGroups)
00350     {
00351         # assume that no parameters will be found
00352         $UrlPortion = array();
00353 
00354         # for each group in parameters
00355         $Schema = new MetadataSchema();
00356         foreach ($SearchGroups as $GroupIndex => $Group)
00357         {
00358             # if group holds single parameters
00359             if ($GroupIndex == "MAIN")
00360             {
00361                 # for each field within group
00362                 foreach ($Group["SearchStrings"] as $FieldName => $Value)
00363                 {
00364                     # add segment to URL for this field
00365                     if ($FieldName == "XXXKeywordXXX")
00366                     {
00367                         $FieldId = "K";
00368                     }
00369                     else
00370                     {
00371                         $Field = $Schema->GetFieldByName($FieldName);
00372                         $FieldId = $Field->Id();
00373                     }
00374                     if (is_array($Value))
00375                     {
00376                         $ValueString = "";
00377                         foreach ($Value as $SingleValue)
00378                         {
00379                             $ValueString .= $SingleValue." ";
00380                         }
00381 
00382                         $UrlPortion["F".$FieldId] = urlencode(trim($ValueString));
00383                     }
00384                     else
00385                     {
00386                         $UrlPortion["F".$FieldId] = urlencode($Value);
00387                     }
00388                 }
00389             }
00390             else
00391             {
00392                 # convert value based on field type
00393                 $FieldId = $GroupIndex;
00394                 $Field = $Schema->GetField($FieldId);
00395                 $FieldName = $Field->Name();
00396                 $Values = SavedSearch::TranslateValues($Field, $Group["SearchStrings"][$FieldName], "SearchGroup to Database");
00397 
00398                 # add values to URL
00399                 $FirstValue = TRUE;
00400                 foreach ($Values as $Value)
00401                 {
00402                     if ($FirstValue)
00403                     {
00404                         $FirstValue = FALSE;
00405                         $UrlPortion["G".$FieldId] = $Value;
00406                     }
00407                     else
00408                     {
00409                         $UrlPortion["G".$FieldId] .= "-".$Value;
00410                     }
00411                 }
00412             }
00413         }
00414 
00415         # return URL portion to caller
00416         return $UrlPortion;
00417     }
00418 
00419     # set search groups from URL (GET method) parameters
00420     # (returns search group array)
00421     static function TranslateUrlParametersToSearchGroups($GetVars)
00422     {
00423         # if URL segment was passed in instead of GET var array
00424         if (is_string($GetVars))
00425         {
00426             # split URL segment into GET var array
00427             $VarAssignments = explode("&", $GetVars);
00428             $GetVars = array();
00429             foreach ($VarAssignments as $VarAss)
00430             {
00431                 $VarAssBits = explode("=", $VarAss);
00432                 if (isset($VarAssBits[1]))
00433                 {
00434                     $GetVars[$VarAssBits[0]] = urldecode($VarAssBits[1]);
00435                 }
00436             }
00437         }
00438 
00439         # start with empty list of parameters
00440         $SearchGroups = array();
00441 
00442         # for each possible metadata field ID
00443         $Schema = new MetadataSchema();
00444         $HighestFieldId = $Schema->GetHighestFieldId();
00445         for ($FieldId = 0;  $FieldId <= $HighestFieldId;  $FieldId++)
00446         {
00447             # if field exists for this ID
00448             $Field = $Schema->GetField($FieldId);
00449             if ($Field)
00450             {
00451                 # if URL included literal value for this field
00452                 $FieldName = $Field->Name();
00453                 if (isset($GetVars["F".$FieldId]))
00454                 {
00455                     # retrieve value and add to search parameters
00456                     $SearchGroups["MAIN"]["SearchStrings"][$FieldName] = $GetVars["F".$FieldId];
00457                 }
00458 
00459                 # if URL included group value for this field
00460                 if (isset($GetVars["G".$FieldId]))
00461                 {
00462                     # retrieve and parse out values
00463                     $Values = explode("-", $GetVars["G".$FieldId]);
00464 
00465                     # translate values
00466                     $Values = SavedSearch::TranslateValues($Field, $Values, "Database to SearchGroup");
00467 
00468                     # add values to searchgroups
00469                     $SearchGroups[$FieldId]["SearchStrings"][$FieldName] = $Values;
00470                 }
00471             }
00472         }
00473 
00474         # if keyword psuedo-field was included in URL
00475         if (isset($GetVars["FK"]))
00476         {
00477             # retrieve value and add to search parameters
00478             $SearchGroups["MAIN"]["SearchStrings"]["XXXKeywordXXX"] = $GetVars["FK"];
00479         }
00480 
00481         # set search logic
00482         foreach ($SearchGroups as $GroupIndex => $Group)
00483         {
00484             $SearchGroups[$GroupIndex]["Logic"] = ($GroupIndex == "MAIN")
00485                     ? SearchEngine::LOGIC_AND : SearchEngine::LOGIC_OR;
00486         }
00487 
00488         # return parameters to caller
00489         return $SearchGroups;
00490     }
00491 
00502     function GetSearchGroupsAsTextDescription(
00503             $IncludeHtml = TRUE, $StartWithBreak = TRUE, $TruncateLongWordsTo = 0)
00504     {
00505         return self::TranslateSearchGroupsToTextDescription($this->SearchGroups(),
00506             $IncludeHtml, $StartWithBreak, $TruncateLongWordsTo);
00507     }
00508 
00520     static function TranslateSearchGroupsToTextDescription($SearchGroups,
00521             $IncludeHtml = TRUE, $StartWithBreak = TRUE, $TruncateLongWordsTo = 0)
00522     {
00523         # start with empty description
00524         $Descrip = "";
00525 
00526         # set characters used to indicate literal strings
00527         $LiteralStart = $IncludeHtml ? "<i>" : "\"";
00528         $LiteralEnd = $IncludeHtml ? "</i>" : "\"";
00529         $LiteralBreak = $IncludeHtml ? "<br>\n" : "\n";
00530 
00531         # if this is a simple keyword search
00532         if (isset($SearchGroups["MAIN"]["SearchStrings"]["XXXKeywordXXX"])
00533             && (count($SearchGroups) == 1)
00534             && (count($SearchGroups["MAIN"]["SearchStrings"]) == 1))
00535         {
00536             # just use the search string
00537             $Descrip .= $LiteralStart.htmlspecialchars(
00538                     $SearchGroups["MAIN"]["SearchStrings"]["XXXKeywordXXX"])
00539                     .$LiteralEnd.$LiteralBreak;
00540         }
00541         else
00542         {
00543             # start description on a new line (if requested)
00544             if ($StartWithBreak)
00545             {
00546                 $Descrip .= $LiteralBreak;
00547             }
00548 
00549             # define list of phrases used to represent logical operators
00550             $WordsForOperators = array(
00551                     "=" => "is",
00552                     ">" => "is greater than",
00553                     "<" => "is less than",
00554                     ">=" => "is at least",
00555                     "<=" => "is no more than",
00556                     "!" => "is not",
00557                     );
00558 
00559             # for each search group
00560             foreach ($SearchGroups as $GroupIndex => $Group)
00561             {
00562                 # if group is main
00563                 if ($GroupIndex == "MAIN")
00564                 {
00565                     # for each field in group
00566                     foreach ($Group["SearchStrings"] as $FieldName => $Value)
00567                     {
00568                         # convert keyword pseudo-field name if necessary
00569                         if ($FieldName == "XXXKeywordXXX") {  $FieldName = "Keyword";  }
00570 
00571                         # determine wording based on operator
00572                         preg_match("/^[=><!]+/", $Value, $Matches);
00573                         if (count($Matches) && isset($WordsForOperators[$Matches[0]]))
00574                         {
00575                             $Value = preg_replace("/^[=><!]+/", "", $Value);
00576                             $Wording = $WordsForOperators[$Matches[0]];
00577                         }
00578                         else
00579                         {
00580                             $Wording = "contains";
00581                         }
00582 
00583                         # add criteria for field
00584                         $Descrip .= $FieldName." ".$Wording." "
00585                                 .$LiteralStart.htmlspecialchars($Value)
00586                                         .$LiteralEnd.$LiteralBreak;
00587                     }
00588                 }
00589                 else
00590                 {
00591                     # for each field in group
00592                     foreach ($Group["SearchStrings"] as $FieldName => $Values)
00593                     {
00594                         # translate values
00595                         $Values = SavedSearch::TranslateValues($FieldName, $Values, "SearchGroup to Display");
00596 
00597                         # for each value
00598                         $FirstValue = TRUE;
00599                         foreach ($Values as $Value)
00600                         {
00601                             # determine wording based on operator
00602                             preg_match("/^[=><!]+/", $Value, $Matches);
00603                             $Operator = $Matches[0];
00604                             $Wording = $WordsForOperators[$Operator];
00605 
00606                             # strip off operator
00607                             $Value = preg_replace("/^[=><!]+/", "", $Value);
00608 
00609                             # add text to description
00610                             if ($FirstValue)
00611                             {
00612                                 $Descrip .= $FieldName." ".$Wording." ".$LiteralStart.htmlspecialchars($Value).$LiteralEnd.$LiteralBreak;
00613                                 $FirstValue = FALSE;
00614                             }
00615                             else
00616                             {
00617                                 $Descrip .= ($IncludeHtml ? "&nbsp;&nbsp;&nbsp;&nbsp;" : "    ")
00618                                         ."or ".$Wording." ".$LiteralStart
00619                                         .htmlspecialchars($Value).$LiteralEnd
00620                                         .$LiteralBreak;
00621                             }
00622                         }
00623                     }
00624                 }
00625             }
00626         }
00627 
00628         # if caller requested that long words be truncated
00629         if ($TruncateLongWordsTo > 4)
00630         {
00631             # break description into words
00632             $Words = explode(" ", $Descrip);
00633 
00634             # for each word
00635             $NewDescrip = "";
00636             foreach ($Words as $Word)
00637             {
00638                 # if word is longer than specified length
00639                 if (strlen(strip_tags($Word)) > $TruncateLongWordsTo)
00640                 {
00641                     # truncate word and add ellipsis
00642                     $Word = substr($Word, 0, ($TruncateLongWordsTo - 3))."...";
00643                 }
00644 
00645                 # add word to new description
00646                 $NewDescrip .= " ".$Word;
00647             }
00648 
00649             # set description to new description
00650             $Descrip = $NewDescrip;
00651         }
00652 
00653         # return description to caller
00654         return $Descrip;
00655     }
00656 
00661     function GetSearchFieldNames()
00662     {
00663         return self::TranslateSearchGroupsToSearchFieldNames($this->SearchGroups());
00664     }
00665 
00671     static function TranslateSearchGroupsToSearchFieldNames($SearchGroups)
00672     {
00673         # start out assuming no fields are being searched
00674         $FieldNames = array();
00675 
00676         # for each search group defined
00677         foreach ($SearchGroups as $GroupIndex => $Group)
00678         {
00679             # for each field in group
00680             foreach ($Group["SearchStrings"] as $FieldName => $Values)
00681             {
00682                 # add field name to list of fields being searched
00683                 $FieldNames[] = $FieldName;
00684             }
00685         }
00686 
00687         # return list of fields being searched to caller
00688         return $FieldNames;
00689     }
00690 
00696     static function GetSearchFrequencyList()
00697     {
00698         # define list with descriptions
00699         $FreqDescr = array(
00700                 self::SEARCHFREQ_NEVER     => "Never",
00701                 self::SEARCHFREQ_HOURLY    => "Hourly",
00702                 self::SEARCHFREQ_DAILY     => "Daily",
00703                 self::SEARCHFREQ_WEEKLY    => "Weekly",
00704                 self::SEARCHFREQ_BIWEEKLY  => "Bi-Weekly",
00705                 self::SEARCHFREQ_MONTHLY   => "Monthly",
00706                 self::SEARCHFREQ_QUARTERLY => "Quarterly",
00707                 self::SEARCHFREQ_YEARLY    => "Yearly",
00708                 );
00709 
00710         # for each argument passed in
00711         $Args = func_get_args();
00712         foreach ($Args as $Arg)
00713         {
00714             # remove value from list
00715             $FreqDescr = array_diff_key($FreqDescr, array($Arg => ""));
00716         }
00717 
00718         # return list to caller
00719         return $FreqDescr;
00720     }
00721 
00725     function Delete()
00726     {
00727         $this->DB->Query("DELETE FROM SavedSearches"
00728                 ." WHERE SearchId = ".intval($this->SearchId));
00729         $this->DB->Query("DELETE FROM SavedSearchTextParameters"
00730                 ." WHERE SearchId = ".intval($this->SearchId));
00731         $this->DB->Query("DELETE FROM SavedSearchIdParameters"
00732                 ." WHERE SearchId = ".intval($this->SearchId));
00733     }
00734 
00735 
00736     # ---- PRIVATE INTERFACE -------------------------------------------------
00737 
00738     private $SearchId;
00739     private $Record;
00740     private $SearchGroups;
00741 
00742     # utility function to convert between value representations
00743     # (method accepts a value or array and always return an array)
00744     # (this is needed because values are represented differently:
00745     #                                 FLAG    USER    OPTION
00746     #     in DB / in URL / in forms   0/1     123     456
00747     #     used in SearchGroups        0/1     jdoe    cname
00748     #     displayed to user           On/Off  jdoe    cname
00749     # where "123" and "456" are option or controlled name IDs)
00750     private static function TranslateValues($FieldOrFieldName, $Values, $TranslationType)
00751     {
00752         # start out assuming we won't find any values to translate
00753         $ReturnValues = array();
00754 
00755         # convert field name to field object if necessary
00756         if (is_object($FieldOrFieldName))
00757         {
00758             $Field = $FieldOrFieldName;
00759         }
00760         else
00761         {
00762             static $Schema;
00763             if (!isset($Schema)) {  $Schema = new MetadataSchema();  }
00764             $Field = $Schema->GetFieldByName($FieldOrFieldName);
00765         }
00766 
00767         # if incoming value is not an array
00768         if (!is_array($Values))
00769         {
00770             # convert incoming value to an array
00771             $Values = array($Values);
00772         }
00773 
00774         # for each incoming value
00775         foreach ($Values as $Value)
00776         {
00777             switch ($TranslationType)
00778             {
00779                 case "SearchGroup to Display":
00780                     # if field is Flag field
00781                     if ($Field->Type() == MetadataSchema::MDFTYPE_FLAG)
00782                     {
00783                         # translate value to true/false label and add leading operator
00784                         $ReturnValues[] = ($Value == "=1") ? "=".$Field->FlagOnLabel() : "=".$Field->FlagOffLabel();
00785                     }
00786                     elseif ($Field->Name() == "Cumulative Rating")
00787                     {
00788                         # translate numeric value to stars
00789                         $StarStrings = array(
00790                                 "20" => "*",
00791                                 "40" => "**",
00792                                 "60" => "***",
00793                                 "80" => "****",
00794                                 "100" => "*****",
00795                                 );
00796                         preg_match("/[0-9]+$/", $Value, $Matches);
00797                         $Number = $Matches[0];
00798                         preg_match("/^[=><!]+/", $Value, $Matches);
00799                         $Operator = $Matches[0];
00800                         $ReturnValues[] = $Operator.$StarStrings[$Number];
00801                     }
00802                     else
00803                     {
00804                         # use value as is
00805                         $ReturnValues[] = $Value;
00806                     }
00807                     break;
00808 
00809                 case "SearchGroup to Database":
00810                     # strip off leading operator on value
00811                     $Value = preg_replace("/^[=><!]+/", "", $Value);
00812 
00813                     # look up index for value
00814                     if ($Field->Type() & (MetadataSchema::MDFTYPE_FLAG|MetadataSchema::MDFTYPE_NUMBER))
00815                     {
00816                         # (for flag or number fields the value index is already what is used in SearchGroups)
00817                         if ($Value >= 0)
00818                         {
00819                             $ReturnValues[] = $Value;
00820                         }
00821                     }
00822                     elseif ($Field->Type() == MetadataSchema::MDFTYPE_USER)
00823                     {
00824                         # (for user fields the value index is the user ID)
00825                         $User = new SPTUser(strval($Value));
00826                         if ($User)
00827                         {
00828                             $ReturnValues[] = $User->Id();
00829                         }
00830                     }
00831                     elseif ($Field->Type() == MetadataSchema::MDFTYPE_OPTION)
00832                     {
00833                         if (!isset($PossibleFieldValues))
00834                         {
00835                             $PossibleFieldValues = $Field->GetPossibleValues();
00836                         }
00837                         $NewValue = array_search($Value, $PossibleFieldValues);
00838                         if ($NewValue !== FALSE)
00839                         {
00840                             $ReturnValues[] = $NewValue;
00841                         }
00842                     }
00843                     else
00844                     {
00845                         $NewValue = $Field->GetIdForValue($Value);
00846                         if ($NewValue !== NULL)
00847                         {
00848                             $ReturnValues[] = $NewValue;
00849                         }
00850                     }
00851                     break;
00852 
00853                 case "Database to SearchGroup":
00854                     # look up value for index
00855                     if ($Field->Type() == MetadataSchema::MDFTYPE_FLAG)
00856                     {
00857                         # (for flag fields the value index (0 or 1) is already what is used in Database)
00858                         if ($Value >= 0)
00859                         {
00860                             $ReturnValues[] = "=".$Value;
00861                         }
00862                     }
00863                     elseif ($Field->Type() == MetadataSchema::MDFTYPE_NUMBER)
00864                     {
00865                         # (for flag fields the value index (0 or 1) is already what is used in Database)
00866                         if ($Value >= 0)
00867                         {
00868                             $ReturnValues[] = ">=".$Value;
00869                         }
00870                     }
00871                     elseif ($Field->Type() == MetadataSchema::MDFTYPE_USER)
00872                     {
00873                         $User = new SPTUser(intval($Value));
00874                         if ($User)
00875                         {
00876                             $ReturnValues[] = "=".$User->Get("UserName");
00877                         }
00878                     }
00879                     elseif ($Field->Type() == MetadataSchema::MDFTYPE_OPTION)
00880                     {
00881                         if (!isset($PossibleFieldValues))
00882                         {
00883                             $PossibleFieldValues = $Field->GetPossibleValues();
00884                         }
00885 
00886                         if (isset($PossibleFieldValues[$Value]))
00887                         {
00888                             $ReturnValues[] = "=".$PossibleFieldValues[$Value];
00889                         }
00890                     }
00891                     else
00892                     {
00893                         $NewValue = $Field->GetValueForId($Value);
00894                         if ($NewValue !== NULL)
00895                         {
00896                             $ReturnValues[] = "=".$NewValue;
00897                         }
00898                     }
00899                     break;
00900             }
00901         }
00902 
00903         # return array of translated values to caller
00904         return $ReturnValues;
00905     }
00906 
00909     # utility function for updating values in database
00910     private function UpdateValue($FieldName, $NewValue)
00911     {
00912         return $this->DB->UpdateValue("SavedSearches", $FieldName, $NewValue,
00913                "SearchId = ".$this->SearchId, $this->Record);
00914     }
00915 
00916     # legacy methods for backward compatibility
00917     function GetSearchId() {  return $this->Id();  }
00918 
00920 }
00921 
00922 
00923 ?>