PageRenderTime 47ms CodeModel.GetById 35ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 0ms

/gulliver/methods/genericAjax.php

https://bitbucket.org/ferOnti/processmaker
PHP | 367 lines | 291 code | 45 blank | 31 comment | 57 complexity | 9cea15390f5e0d3e91656fe66af5ad49 MD5 | raw file
  1<?php
  2
  3$request = isset($_POST['request'])? $_POST['request']: null;
  4if( !isset($request) ){
  5  $request = isset($_GET['request'])? $_GET['request']: null;
  6}
  7if( isset($request) ){
  8  switch($request){
  9    case 'deleteGridRowOnDynaform':
 10      //This code is to update the SESSION variable for dependent fields in grids
 11
 12      if (!defined("XMLFORM_AJAX_PATH")) {
 13          define("XMLFORM_AJAX_PATH", PATH_XMLFORM);
 14      }
 15
 16      if (is_array($_SESSION[$_POST["formID"]][$_POST["gridname"]])) {
 17          if (!is_array($_SESSION[$_POST["formID"]][$_POST["gridname"]])) {
 18              $_SESSION[$_POST["formID"]][$_POST["gridname"]] = (array)$_SESSION[$_POST["formID"]][$_POST["gridname"]];
 19          }
 20          ksort($_SESSION[$_POST["formID"]][$_POST["gridname"]]);
 21          $oFields = array();
 22          $initialKey = 1;
 23
 24          foreach ($_SESSION[$_POST["formID"]][$_POST["gridname"]] as $key => $value) {
 25              if ($key != $_POST["rowpos"]) {
 26                  $oFields[$initialKey] = $value;
 27                  $initialKey++;
 28              }
 29          }
 30
 31          unset($_SESSION[$_POST["formID"]][$_POST["gridname"]]);
 32
 33          $_SESSION[$_POST["formID"]][$_POST["gridname"]] = $oFields;
 34      }
 35
 36    /*  if( isset($_SESSION['APPLICATION']) ){
 37        G::LoadClass('case');
 38        $oApp= new Cases();
 39        $aFields = $oApp->loadCase($_SESSION['APPLICATION']);
 40        unset($aFields['APP_DATA'][$_POST['gridname']][$_POST['rowpos']]);
 41        $initialKey = 1;
 42        foreach ($aFields['APP_DATA'][$_POST['gridname']] as $key => $value) {
 43          $oFields[$initialKey] = $value;
 44          $initialKey++;
 45          $aFields['APP_DATA'][$_POST['gridname']] = $oFields;
 46        }
 47        $oApp->updateCase($_SESSION['APPLICATION'], $aFields);
 48      }
 49*/
 50    break;
 51    /** widgets **/
 52    case 'suggest':
 53
 54      try {
 55        if(isset($_GET["inputEnconde64"])) {
 56          $_GET['input'] = base64_decode($_GET['input']);
 57        }
 58        $sData = base64_decode(str_rot13($_GET['hash']));
 59        list($SQL, $DB_UID) = explode('@|', $sData);
 60        // Remplace values for dependent fields
 61        $aDependentFieldsKeys  = explode("|", base64_decode(str_rot13($_GET['dependentFieldsKeys'])));
 62        $aDependentFieldsValue = explode("|", $_GET['dependentFieldsValue']);
 63        if($aDependentFieldsKeys){
 64          $SQL = str_replace($aDependentFieldsKeys, $aDependentFieldsValue, $SQL);
 65        }
 66
 67        // Parsed SQL Structure
 68        G::LoadClass('phpSqlParser');
 69
 70        $parser = new PHPSQLParser($SQL);
 71        // Verif parsed array
 72        // print_r($parser->parsed);
 73        $SQL = queryModified($parser->parsed, $_GET['input']);
 74
 75        $aRows = Array();
 76        try {
 77          $con = Propel::getConnection($DB_UID);
 78          $con->begin();
 79          $rs = $con->executeQuery($SQL);
 80          $con->commit();
 81
 82          while ( $rs->next() ) {
 83            array_push($aRows, $rs->getRow());
 84          }
 85        } catch (SQLException $sqle) {
 86            $con->rollback();
 87        }
 88
 89        $input    = strtolower( $_GET['input'] );
 90        $len      = strlen($input);
 91        $limit    = isset($_GET['limit']) ? (int) $_GET['limit'] : 0;
 92        $aResults = array();
 93        $count    = 0;
 94        $aRows    = sortByChar($aRows, $input);
 95
 96        if ($len){
 97          for ($i=0;$i<count($aRows);$i++){
 98            $aRow  = $aRows[$i];
 99            $nCols = sizeof($aRow);
100
101            $aRow  = array_values($aRow);
102            switch( $nCols ){
103              case 1:
104                  $id    = $aRow[0];
105                  $value = $aRow[0];
106                  $info  = '';
107                  break;
108
109              case 2:
110                  $id    = $aRow[0];
111                  $value = $aRow[1];
112                  $info  = '';
113                  break;
114
115              case $nCols >= 3:
116                  $id    = $aRow[0];
117                  $value = $aRow[1];
118                  $info  = $aRow[2];
119                  break;
120            }
121
122
123            // had to use utf_decode, here
124            // not necessary if the results are coming from mysql
125            //
126            $count++;
127            $aResults[] = array( "id"=>$id ,"value"=>htmlspecialchars($value), "info"=>htmlspecialchars($info) );
128
129            if ($limit && $count==$limit)
130              break;
131          }
132        }
133
134        header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
135        header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
136        header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
137        header ("Pragma: no-cache"); // HTTP/1.0
138
139        if (isset($_REQUEST['json'])) {
140          header("Content-Type: application/json");
141          echo "{\"status\":0,  \"results\": [";
142          $arr = array();
143          $aReplace = array("(\r\n)", "(\n\r)", "(\n)", "(\r)");
144          for ($i=0;$i<count($aResults);$i++) {
145            $arr[] = "{\"id\": \"".$aResults[$i]['id']."\", \"value\": \"". html_entity_decode(preg_replace($aReplace, "", $aResults[$i]['value']))."\", \"info\": \"".$aResults[$i]['info']."\"}";
146          }
147          echo implode(", ", $arr);
148          echo "]}";
149        } else {
150          header("Content-Type: text/xml");
151
152          echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?><results>";
153          for ($i=0;$i<count($aResults);$i++)
154          {
155            echo "<rs id=\"".$aResults[$i]['id']."\" info=\"".$aResults[$i]['info']."\">".$aResults[$i]['value']."</rs>";
156          }
157          echo "</results>";
158        }
159
160      } catch(Exception $e){
161        $err = $e->getMessage();
162        //$err = eregi_replace("[\n|\r|\n\r]", ' ', $err);
163        $err = preg_replace("[\n|\r|\n\r]", ' ', $err);//Made compatible to PHP 5.3
164        echo '{"status":1, "message":"'.$err.'"}';
165      }
166    break;
167
168
169    case 'storeInTmp':
170      try {
171        $con = Propel::getConnection($_GET['cnn']);
172        if($_GET['pkt'] == 'int'){
173          $rs = $con->executeQuery("SELECT MAX({$_GET['pk']}) as lastId FROM {$_GET['table']};");
174          $rs->next();
175          $row = $rs->getRow();
176          $gKey = (int)$row['lastId'] + 1;
177
178        } else {
179          $gKey = md5(date('Y-m-d H:i:s').'@'.rand());
180        }
181
182        $rs = $con->executeQuery("INSERT INTO {$_GET['table']} ({$_GET['pk']}, {$_GET['fld']}) VALUES ('$gKey', '{$_GET['value']}');");
183
184        echo "{status: 1, message: \"success\"}";
185      } catch (Exception $e) {
186        $err = $e->getMessage();
187        //$err = eregi_replace("[\n|\r|\n\r]", ' ', $err);
188        $err = preg_replace("[\n|\r|\n\r]", " ", $err); //Made compatible to PHP 5.3
189
190        echo "{status: 0, message: \"" . $err . "\"}";
191      }
192      break;
193  }
194}
195
196function sortByChar($aRows, $charSel)
197{
198  $aIniChar = array();
199  $aRest    = array();
200  for($i=0; $i<count($aRows) ;$i++){
201    $aRow      = $aRows[$i];
202    $nCols     = sizeof($aRow);
203    $aRowOrder = array_values($aRow);
204    switch( $nCols ){
205        case 1:
206            $value = $aRowOrder[0];
207            break;
208        case 2:
209            $value = $aRowOrder[1];
210            break;
211        case $nCols >= 3:
212            $value = $aRowOrder[1];
213            break;
214    }
215
216    if(substr(strtolower($value), 0, 1) == substr( strtolower($charSel), 0, 1)){
217      array_push($aIniChar, $aRow);
218    } else {
219      array_push($aRest, $aRow);
220    }
221  }
222  return array_merge($aIniChar, $aRest);
223}
224
225
226/*
227 * Converts a SQL array parsing to a SQL string.
228 * @param string $sqlParsed
229 * @param string $inputSel default value empty string
230 * @return string
231 */
232function queryModified($sqlParsed, $inputSel = "")
233{
234
235  if(!empty($sqlParsed['SELECT'])) {
236
237    $sqlSelect = "SELECT ";
238    $aSelect   = $sqlParsed['SELECT'];
239
240    $sFieldSel = (count($aSelect)>1 ) ? $aSelect[1]['base_expr'] : $aSelect[0]['base_expr'];
241    foreach($aSelect as $key => $value ) {
242      if($key != 0)
243        $sqlSelect .= ", ";
244      $sAlias    = str_replace("`","", $aSelect[$key]['alias']);
245      $sBaseExpr = $aSelect[$key]['base_expr'];
246      switch($aSelect[$key]['expr_type']){
247        case 'colref' : if($sAlias === $sBaseExpr)
248                           $sqlSelect .= $sAlias;
249                         else
250                           $sqlSelect .= $sBaseExpr . ' AS ' . $sAlias;
251                         break;
252        case 'expression' : if($sAlias === $sBaseExpr)
253                           $sqlSelect .= $sBaseExpr;
254                         else
255                           $sqlSelect .= $sBaseExpr . ' AS ' . $sAlias;
256                         break;
257        case 'subquery' : if(strpos($sAlias, $sBaseExpr,0) != 0)
258                           $sqlSelect .= $sAlias;
259                         else
260                           $sqlSelect .= $sBaseExpr . " AS " . $sAlias;
261                         break;
262        case 'operator' : $sqlSelect .= $sBaseExpr;
263                         break;
264        default        : $sqlSelect .= $sBaseExpr;
265                         break;
266      }
267    }
268
269    $sqlFrom = " FROM ";
270    if(!empty($sqlParsed['FROM'])){
271      $aFrom = $sqlParsed['FROM'];
272      if(count($aFrom) > 0){
273        foreach($aFrom as $key => $value ){
274          if($key == 0) {
275            $sqlFrom .= $aFrom[$key]['table'] . (($aFrom[$key]['table'] == $aFrom[$key]['alias'])?"" : " " . $aFrom[$key]['alias']);
276          } else {
277            $sqlFrom .= " " . (($aFrom[$key]['join_type']=='JOIN')?"INNER": $aFrom[$key]['join_type']) . " JOIN " . $aFrom[$key]['table']
278                     . (($aFrom[$key]['table'] == $aFrom[$key]['alias'])?"" : " " . $aFrom[$key]['alias']) . " " . $aFrom[$key]['ref_type'] . " " . $aFrom[$key]['ref_clause'] ;
279          }
280
281        }
282      }
283    }
284
285    if(!empty($sqlParsed['WHERE'])){
286      $sqlWhere = " WHERE ";
287      $aWhere   = $sqlParsed['WHERE'];
288      foreach($aWhere as $key => $value ){
289        $sqlWhere .= $value['base_expr'] . " ";
290      }
291      $sqlWhere .= " AND " . $sFieldSel . " LIKE '%". $inputSel . "%'";
292    }
293    else {
294      $sqlWhere = " WHERE " . $sFieldSel . " LIKE '%". $inputSel ."%' ";
295    }
296
297    $sqlGroupBy = "";
298    if(!empty($sqlParsed['GROUP'])){
299      $sqlGroupBy = "GROUP BY ";
300      $aGroup     = $sqlParsed['GROUP'];
301      foreach($aGroup as $key => $value ){
302        if($key != 0)
303          $sqlGroupBy .= ", ";
304        if($value['direction'] == 'ASC' )
305          $sqlGroupBy .= $value['base_expr'];
306        else
307          $sqlGroupBy .= $value['base_expr'] . " " . $value['direction'];
308      }
309    }
310
311    $sqlHaving = "";
312    if(!empty($sqlParsed['HAVING'])){
313      $sqlHaving = "HAVING ";
314      $aHaving   = $sqlParsed['HAVING'];
315      foreach($aHaving as $key => $value ){
316        $sqlHaving .= $value['base_expr'] . " ";
317      }
318    }
319
320    $sqlOrderBy = "";
321    if(!empty($sqlParsed['ORDER'])){
322      $sqlOrderBy = "ORDER BY ";
323      $aOrder     = $sqlParsed['ORDER'];
324      foreach($aOrder as $key => $value ){
325        if($key != 0)
326          $sqlOrderBy .= ", ";
327        if($value['direction'] == 'ASC' )
328          $sqlOrderBy .= $value['base_expr'];
329        else
330          $sqlOrderBy .= $value['base_expr'] . " " . $value['direction'];
331      }
332    } else {
333      $sqlOrderBy = " ORDER BY " . $sFieldSel;
334    }
335
336    $sqlLimit  = "";
337    if(!empty($sqlParsed['LIMIT'])){
338      $sqlLimit  = "LIMIT ". $sqlParsed['LIMIT']['start'] . ", " . $sqlParsed['LIMIT']['end'];
339    }
340
341    return $sqlSelect . $sqlFrom . $sqlWhere . $sqlGroupBy . $sqlHaving . $sqlOrderBy . $sqlLimit;
342  }
343  if(!empty($sqlParsed['CALL'])){
344    $sCall = "CALL ";
345    $aCall = $sqlParsed['CALL'];
346    foreach($aCall as $key => $value ){
347      $sCall .= $value . " ";
348    }
349    return $sCall;
350  }
351  if(!empty($sqlParsed['EXECUTE'])){
352    $sCall = "EXECUTE ";
353    $aCall = $sqlParsed['EXECUTE'];
354    foreach($aCall as $key => $value ){
355      $sCall .= $value . " ";
356    }
357    return $sCall;
358  }
359  if(!empty($sqlParsed[''])){
360    $sCall = "";
361    $aCall = $sqlParsed[''];
362    foreach($aCall as $key => $value ){
363      $sCall .= $value . " ";
364    }
365    return $sCall;
366  }
367}