source: extensions/GrumPluginClasses/classes/GPCRequestBuilder.class.inc.php @ 6213

Last change on this file since 6213 was 6213, checked in by grum, 14 years ago

results for request builder if filtered with user rights access

File size: 27.6 KB
Line 
1<?php
2/* -----------------------------------------------------------------------------
3  class name: GCPRequestBuilder
4  class version  : 1.0.0
5  plugin version : 3.1.0
6  date           : 2010-04-29
7
8  ------------------------------------------------------------------------------
9  Author     : Grum
10    email    : grum@piwigo.org
11    website  : http://photos.grum.com
12    PWG user : http://forum.phpwebgallery.net/profile.php?id=3706
13
14    << May the Little SpaceFrog be with you ! >>
15  ------------------------------------------------------------------------------
16
17  * theses classes provides base functions to manage search pictures in the
18  * database
19  *
20
21
22  ------------------------------------------------------------------------------
23  :: HISTORY
24
25| release | date       |
26| 1.0.0   | 2010/04/30 | * start coding
27|         |            |
28|         |            |
29|         |            |
30|         |            |
31|         |            |
32|         |            |
33|         |            |
34|         |            |
35|         |            |
36|         |            |
37|         |            |
38
39  --------------------------------------------------------------------------- */
40
41include_once('GPCAjax.class.inc.php');
42include_once('GPCTables.class.inc.php');
43
44
45class GPCSearchCallback {
46
47  /**
48   * the getSelect function must return an attribute list separated with a comma
49   *
50   * "att1, att2, att3, att4"
51   */
52  static public function getSelect($param="")
53  {
54    return("");
55  }
56
57  /**
58   * the getFrom function must return a tables list separated with a comma
59   *
60   * "table1, (table2 left join table3 on table2.key = table3.key), table4"
61   */
62  static public function getFrom($param="")
63  {
64    return("");
65  }
66
67  /**
68   * the getWhere function must return a ready to use where clause
69   *
70   * "(att1 = value0 OR att2 = value1) AND att4 LIKE value2 "
71   */
72  static public function getWhere($param="")
73  {
74    return("");
75  }
76
77  /**
78   * the getJoin function must return a ready to use where allowing to join the
79   * IMAGES table (key : pit.id) with given conditions
80   *
81   * "att3 = pit.id "
82   */
83  static public function getJoin($param="")
84  {
85    return("");
86  }
87
88
89  /**
90   * this function is called by the request builder, allowing to display plugin
91   * data with a specific format
92   *
93   * @param Array $attributes : array of ('attribute_name' => 'attribute_value')
94   * @return String : HTML formatted value
95   */
96  static public function formatData($attributes)
97  {
98    return(print_r($attributes, true));
99  }
100
101
102  /**
103   * this function is called by the request builder to make the search page, and
104   * must return the HTML & JS code of the dialogbox used to select criterion
105   *
106   * Notes :
107   *  - the dialogbox is a JS object with a public method 'show'
108   *  - when the method show is called, one parameter is given by the request
109   *    builder ; the parameter is an object defined as this :
110   *      {
111   *        cBuilder: an instance of the criteriaBuilder object used in the page,
112   *      }
113   *
114   *
115   *
116   *
117   * @param String $mode : can take 'admin' or 'public' values, allowing to
118   *                       return different interface if needed
119   * @return String : HTML formatted value
120   */
121  static public function getInterfaceContent($mode='admin')
122  {
123    return("");
124  }
125
126  /**
127   * this function returns the label displayed in the criterion menu
128   *
129   * @return String : label displayed in the criterions menu
130   */
131  static public function getInterfaceLabel()
132  {
133    return(l10n('gpc_rb_unknown_interface'));
134  }
135
136  /**
137   * this function returns the name of the dialog box class
138   *
139   * @return String : name of the dialogbox class
140   */
141  static public function getInterfaceDBClass()
142  {
143    return('');
144  }
145
146
147}
148
149
150
151class GPCRequestBuilder {
152
153  static public $pluginName = 'GPCRequestBuilder';
154  static public $version = '1.0.0';
155
156  static private $tables = Array();
157
158  /**
159   * register a plugin using GPCRequestBuilder
160   *
161   * @param String $pluginName : the plugin name
162   * @param String $fileName : the php filename where the callback function can
163   *                           be found
164   * @return Boolean : true if registering is Ok, otherwise false
165   */
166  static public function register($pluginName, $fileName)
167  {
168    $config=Array();
169    if(GPCCore::loadConfig(self::$pluginName, $config))
170    {
171      $config['registered'][$pluginName]=Array(
172        'name' => $pluginName,
173        'fileName' => $fileName,
174        'date' => date("Y-m-d H:i:s"),
175        'version' => self::$version,
176      );
177      return(GPCCore::saveConfig(self::$pluginName, $config));
178    }
179    return(false);
180  }
181
182  /**
183   * unregister a plugin using GPCRequestBuilder
184   *
185   * assume that if the plugin was not registerd before, unregistering returns
186   * a true value
187   *
188   * @param String $pluginName : the plugin name
189   * @return Boolean : true if registering is Ok, otherwise false
190   */
191  static public function unregister($plugin)
192  {
193    $config=Array();
194    if(GPCCore::loadConfig(self::$pluginName, $config))
195    {
196      if(array_key_exists('registered', $config))
197      {
198        if(array_key_exists($plugin, $config['registered']))
199        {
200          unset($config['registered'][$plugin]);
201          return(GPCCore::saveConfig(self::$pluginName, $config));
202        }
203      }
204    }
205    // assume if the plugin was not registered before, unregistering it is OK
206    return(true);
207  }
208
209  /**
210   * @return Array : list of registered plugins
211   */
212  static public function getRegistered()
213  {
214    $config=Array();
215    if(GPCCore::loadConfig(self::$pluginName, $config))
216    {
217      if(array_key_exists('registered', $config))
218      {
219        return($config['registered']);
220      }
221    }
222    return(Array());
223  }
224
225
226  /**
227   * initialise the class
228   *
229   * @param String $prefixeTable : the piwigo prefixe used on tables name
230   * @param String $pluginNameFile : the plugin name used for tables name
231   */
232  static public function init($prefixeTable, $pluginNameFile)
233  {
234    $list=Array('request', 'result_cache');
235
236    for($i=0;$i<count($list);$i++)
237    {
238      self::$tables[$list[$i]]=$prefixeTable.$pluginNameFile.'_'.$list[$i];
239    }
240  }
241
242  /**
243   * create the tables needed by RequestBuilder (used during the gpc process install)
244   */
245  static public function createTables()
246  {
247    $tablesDef=array(
248"CREATE TABLE `".self::$tables['request']."` (
249  `id` int(10) unsigned NOT NULL auto_increment,
250  `user_id` int(10) unsigned NOT NULL,
251  `date` datetime NOT NULL,
252  `num_items` int(10) unsigned NOT NULL default '0',
253  `execution_time` float unsigned NOT NULL default '0',
254  `connected_plugin` char(255) NOT NULL,
255  PRIMARY KEY  (`id`)
256)
257CHARACTER SET utf8 COLLATE utf8_general_ci",
258
259"CREATE TABLE `".self::$tables['result_cache']."` (
260  `id` int(10) unsigned NOT NULL,
261  `image_id` int(10) unsigned NOT NULL,
262  PRIMARY KEY  (`id`,`image_id`)
263)
264CHARACTER SET utf8 COLLATE utf8_general_ci",
265  );
266
267    $tablef= new GPCTables(self::$tables);
268    $tablef->create($tablesDef);
269
270    return(true);
271  }
272
273  /**
274   * delete the tables needed by RequestBuilder
275   */
276  static public function deleteTables()
277  {
278    $tablef= new GPCTables(self::$tables);
279    $tablef->drop($tables_def);
280    return(true);
281  }
282
283
284  /**
285   * this function add and handler on the 'loc_end_page_header' to add request
286   * builder JS script & specific CSS on the page
287   *
288   * use it when the displayed page need an access to the criteriaBuilder GUI
289   *
290   */
291  static public function loadJSandCSS()
292  {
293    add_event_handler('loc_end_page_header', array('GPCRequestBuilder', 'insertJSandCSSFiles'));
294  }
295
296
297  /**
298   * insert JS a CSS file in header
299   *
300   * the function is declared public because it used by the 'loc_end_page_header'
301   * event callback
302   *
303   * DO NOT USE IT DIRECTLY
304   *
305   */
306  static public function insertJSandCSSFiles()
307  {
308    global $template;
309
310    $baseName=basename(dirname(dirname(__FILE__))).'/css/';
311    $template->append('head_elements', '<link href="plugins/'.$baseName.'rbuilder.css" type="text/css" rel="stylesheet"/>');
312
313    $baseName=basename(dirname(dirname(__FILE__))).'/js/';
314    $template->append('head_elements', '<script type="text/javascript" src="plugins/'.$baseName.'external/interface/interface.js"></script>');
315    $template->append('head_elements', '<script type="text/javascript" src="plugins/'.$baseName.'external/inestedsortable.pack.js"></script>');
316    $template->append('head_elements', '<script type="text/javascript" src="plugins/'.$baseName.'criteriaBuilder.js"></script>');
317    $template->append('head_elements',
318"<script type=\"text/javascript\">
319  requestBuilderOptions = {
320      textAND:'".l10n('gpc_rb_textAND')."',
321      textOR:'".l10n('gpc_rb_textOR')."',
322      imgEditUrl:'',
323      imgDeleteUrl:'',
324      ajaxUrl:'admin.php?page=plugin&section=".basename(GPC_DIR)."/admin/plugin_admin.php&searchRequest=',
325  }
326</script>");
327  }
328
329
330  /**
331   * execute request from the ajax call
332   *
333   * @return String : a ready to use HTML code
334   */
335  static public function executeRequest()
336  {
337    if(self::checkAjaxRequest())
338    {
339      switch($_REQUEST['searchRequest'])
340      {
341        case 'execute':
342          $result=self::doCache();
343          break;
344        case 'getPage':
345          $result=self::getPage($_REQUEST['requestNumber'], $_REQUEST['page'], $_REQUEST['numPerPage']);
346          break;
347      }
348      GPCAjax::returnResult($result);
349    }
350    else
351    {
352      GPCAjax::returnResult(l10n('gpc_rb_invalid_request'));
353    }
354  }
355
356
357  /**
358   * clear the cache table
359   *
360   * @param Boolean $clearAll : if set to true, clear all records without
361   *                            checking timestamp
362   */
363  static public function clearCache($clearAll=false)
364  {
365    if($clearAll)
366    {
367      $sql="DELETE FROM ".self::$tables['result_cache'];
368    }
369    else
370    {
371      $sql="DELETE pgrc FROM ".self::$tables['result_cache']." pgrc
372              LEFT JOIN ".self::$tables['request']." pgr
373                ON pgrc.id = pgr.id
374              WHERE pgr.date < '".date('Y-m-d H:i:s', strtotime("-2 hour"))."'";
375    }
376    pwg_query($sql);
377  }
378
379  /**
380   * execute a query, and place result in cache
381   *
382   *
383   * @return String : queryNumber;numberOfItems
384   */
385  static private function doCache()
386  {
387    global $user;
388
389    self::clearCache();
390
391    $registeredPlugin=self::getRegistered();
392
393    $build=Array(
394      'SELECT' => 'pit.id',
395      'FROM' => '',
396      'WHERE' => '',
397      'GROUPBY' => '',
398    );
399    $tmpBuild=Array(
400      'FROM' => Array(
401        '('.IMAGES_TABLE.' pit LEFT JOIN '.IMAGE_CATEGORY_TABLE.' pic ON pit.id = pic.image_id)' /*JOIN IMAGES & IMAGE_CATEGORY tables*/
402       .'   JOIN '.USER_CACHE_CATEGORIES_TABLE.' pucc ON pucc.cat_id=pic.category_id',  /* IMAGE_CATEGORY & USER_CACHE_CATEGORIES_TABLE tables*/
403
404      ),
405      'WHERE' => Array(),
406      'JOIN' => Array(999=>'pucc.user_id='.$user['id']),
407      'GROUPBY' => Array(
408        'pit.id'
409      )
410    );
411
412    /* build data request for plugins
413     *
414     * Array('Plugin1' =>
415     *          Array(
416     *            criteriaNumber1 => pluginParam1,
417     *            criteriaNumber2 => pluginParam2,
418     *            criteriaNumberN => pluginParamN
419     *          ),
420     *       'Plugin2' =>
421     *          Array(
422     *            criteriaNumber1 => pluginParam1,
423     *            criteriaNumber2 => pluginParam2,
424     *            criteriaNumberN => pluginParamN
425     *          )
426     * )
427     *
428     */
429    $pluginNeeded=Array();
430    $pluginList=Array();
431    foreach($_REQUEST['extraData'] as $key => $val)
432    {
433      $pluginNeeded[$val['owner']][$key]=$_REQUEST['extraData'][$key]['param'];
434      $pluginList[$val['owner']]=$val['owner'];
435    }
436
437    /* for each needed plugin :
438     *  - include the file
439     *  - call the static public function getWhere
440     */
441    foreach($pluginNeeded as $key => $val)
442    {
443      if(array_key_exists($key, $registeredPlugin))
444      {
445        if(file_exists($registeredPlugin[$key]['fileName']))
446        {
447          include_once($registeredPlugin[$key]['fileName']);
448
449          $tmpBuild['FROM'][]=call_user_func(Array('RBCallBack'.$key, 'getFrom'));
450          $tmpBuild['JOIN'][]=call_user_func(Array('RBCallBack'.$key, 'getJoin'));
451
452          foreach($val as $itemNumber => $param)
453          {
454            $tmpBuild['WHERE'][$itemNumber]=call_user_func(Array('RBCallBack'.$key, 'getWhere'), $param);
455          }
456        }
457      }
458    }
459
460
461    /* build FROM
462     *
463     */
464    $build['FROM']=implode(',', $tmpBuild['FROM']);
465    unset($tmpBuild['FROM']);
466
467    /* build WHERE
468     */
469    self::cleanArray($tmpBuild['WHERE']);
470    if(count($tmpBuild['WHERE'])>0)
471    {
472      $build['WHERE']=' ('.self::buildGroup($_REQUEST[$_REQUEST['requestName']], $tmpBuild['WHERE'], $_REQUEST['operator'], ' AND ').') ';
473    }
474    unset($tmpBuild['WHERE']);
475
476
477    /* for each plugin, adds jointure with the IMAGE table
478     */
479    self::cleanArray($tmpBuild['JOIN']);
480    if(count($tmpBuild['JOIN'])>0)
481    {
482      $build['WHERE'].=' AND ('.implode(' AND ', $tmpBuild['JOIN']).') ';
483    }
484    unset($tmpBuild['JOIN']);
485
486    self::cleanArray($tmpBuild['GROUPBY']);
487    if(count($tmpBuild['GROUPBY'])>0)
488    {
489      $build['GROUPBY'].=' '.implode(', ', $tmpBuild['GROUPBY']).' ';
490    }
491    unset($tmpBuild['GROUPBY']);
492
493
494
495    $sql=' FROM '.$build['FROM'];
496    if($build['WHERE']!='')
497    {
498      $sql.=' WHERE '.$build['WHERE'];
499    }
500    if($build['GROUPBY']!='')
501    {
502      $sql.=' GROUP BY '.$build['GROUPBY'];
503    }
504
505    $sql.=" ORDER BY pit.id ";
506
507    $requestNumber=self::getNewRequest($user['id']);
508
509    $sql="INSERT INTO ".self::$tables['result_cache']." (SELECT DISTINCT $requestNumber, ".$build['SELECT']." $sql)";
510
511    $result=pwg_query($sql);
512    if($result)
513    {
514      $numberItems=pwg_db_changes($result);
515      self::updateRequest($requestNumber, $numberItems, 0, implode(',', $pluginList));
516
517
518      return("$requestNumber;".$numberItems);
519    }
520
521    return("0;0");
522  }
523
524  /**
525   * return a page content. use the cache table to find request result
526   *
527   * @param Integer $requestNumber : the request number (from cache table)
528   * @param Integer $pageNumber : the page to be returned
529   * @param Integer $numPerPage : the number of items returned on a page
530   * @return String : formatted HTML code
531   */
532  static private function getPage($requestNumber, $pageNumber, $numPerPage)
533  {
534    global $conf, $user;
535    $request=self::getRequest($requestNumber);
536
537    if($request===false)
538    {
539      return("KO");
540    }
541
542    $limitFrom=$numPerPage*($pageNumber-1);
543
544    $pluginNeeded=explode(',', $request['connected_plugin']);
545    $registeredPlugin=self::getRegistered();
546
547    $build=Array(
548      'SELECT' => '',
549      'FROM' => '',
550      'WHERE' => '',
551      'GROUPBY' => '',
552    );
553    $tmpBuild=Array(
554      'SELECT' => Array(
555        'RB_PIT' => "pit.id AS imageId, pit.name AS imageName, pit.path AS imagePath", // from the piwigo's image table
556        'RB_PIC' => "GROUP_CONCAT(pic.category_id SEPARATOR ',') AS imageCategoriesId",     // from the piwigo's image_category table
557        'RB_PCT' => "GROUP_CONCAT(CASE WHEN pct.name IS NULL THEN '' ELSE pct.name END SEPARATOR '#sep#') AS imageCategoriesNames,
558                     GROUP_CONCAT(CASE WHEN pct.permalink IS NULL THEN '' ELSE pct.permalink END SEPARATOR '#sep#') AS imageCategoriesPLink,
559                     GROUP_CONCAT(CASE WHEN pct.dir IS NULL THEN 'V' ELSE 'P' END) AS imageCategoriesDir",   //from the piwigo's categories table
560      ),
561      'FROM' => Array(
562        // join rb result_cache table with piwigo's images table, joined with the piwigo's image_category table, joined with the categories table
563        'RB' => "(((".self::$tables['result_cache']." pgrc
564                  RIGHT JOIN ".IMAGES_TABLE." pit
565                  ON pgrc.image_id = pit.id)
566                    RIGHT JOIN ".IMAGE_CATEGORY_TABLE." pic
567                    ON pit.id = pic.image_id)
568                       RIGHT JOIN ".CATEGORIES_TABLE." pct
569                       ON pct.id = pic.category_id)
570                          RIGHT JOIN ".USER_CACHE_CATEGORIES_TABLE." pucc
571                          ON pucc.cat_id = pic.category_id",
572      ),
573      'WHERE' => Array(
574        'RB' => "pgrc.id=".$requestNumber." AND pucc.user_id=".$user['id'],
575        ),
576      'JOIN' => Array(),
577      'GROUPBY' => Array(
578        'RB' => "pit.id"
579      )
580    );
581
582    /* for each needed plugin :
583     *  - include the file
584     *  - call the static public function getFrom, getJoin, getSelect
585     */
586    foreach($pluginNeeded as $key => $val)
587    {
588      if(array_key_exists($val, $registeredPlugin))
589      {
590        if(file_exists($registeredPlugin[$val]['fileName']))
591        {
592          include_once($registeredPlugin[$val]['fileName']);
593          $tmpBuild['SELECT'][$val]=call_user_func(Array('RBCallBack'.$val, 'getSelect'));
594          $tmpBuild['FROM'][$val]=call_user_func(Array('RBCallBack'.$val, 'getFrom'));
595          $tmpBuild['JOIN'][$val]=call_user_func(Array('RBCallBack'.$val, 'getJoin'));
596        }
597      }
598    }
599
600    /* build SELECT
601     *
602     */
603    $build['SELECT']=implode(',', $tmpBuild['SELECT']);
604
605    /* build FROM
606     *
607     */
608    $build['FROM']=implode(',', $tmpBuild['FROM']);
609    unset($tmpBuild['FROM']);
610
611
612    /* build WHERE
613     */
614    $build['WHERE']=implode(' AND ', $tmpBuild['WHERE']);
615    unset($tmpBuild['WHERE']);
616
617
618    /* for each plugin, adds jointure with the IMAGE table
619     */
620    self::cleanArray($tmpBuild['JOIN']);
621    if(count($tmpBuild['JOIN'])>0)
622    {
623      $build['WHERE'].=' AND ('.implode(' AND ', $tmpBuild['JOIN']).') ';
624    }
625    unset($tmpBuild['JOIN']);
626
627    self::cleanArray($tmpBuild['GROUPBY']);
628    if(count($tmpBuild['GROUPBY'])>0)
629    {
630      $build['GROUPBY'].=' '.implode(', ', $tmpBuild['GROUPBY']).' ';
631    }
632    unset($tmpBuild['GROUPBY']);
633
634
635    $imagesList=Array();
636
637    $sql='SELECT '.$build['SELECT']
638        .' FROM '.$build['FROM']
639        .' WHERE '.$build['WHERE']
640        .' GROUP BY '.$build['GROUPBY']
641        .' ORDER BY pit.id '
642        .' LIMIT '.$limitFrom.', '.$numPerPage;
643
644    $result=pwg_query($sql);
645    if($result)
646    {
647      while($row=pwg_db_fetch_assoc($result))
648      {
649        // affect standard datas
650        $datas['imageThumbnail']=dirname($row['imagePath'])."/".$conf['dir_thumbnail']."/".$conf['prefix_thumbnail'].basename($row['imagePath']);
651        $datas['imageId']=$row['imageId'];
652        $datas['imagePath']=$row['imagePath'];
653        $datas['imageName']=$row['imageName'];
654
655        $datas['imageCategoriesId']=explode(',', $row['imageCategoriesId']);
656        $datas['imageCategoriesNames']=explode('#sep#', $row['imageCategoriesNames']);
657        $datas['imageCategoriesPLink']=explode('#sep#', $row['imageCategoriesPLink']);
658        $datas['imageCategoriesDir']=explode(',', $row['imageCategoriesDir']);
659
660
661        $datas['imageCategories']=Array();
662        for($i=0;$i<count($datas['imageCategoriesId']);$i++)
663        {
664          $datas['imageCategories'][]=array(
665            'id' => $datas['imageCategoriesId'][$i],
666            'name' => $datas['imageCategoriesNames'][$i],
667            'dirType' => $datas['imageCategoriesDir'][$i],
668            'pLinks' => $datas['imageCategoriesPLink'][$i],
669            'link'=> make_index_url(
670                              array(
671                                'category' => array(
672                                  'id' => $datas['imageCategoriesId'][$i],
673                                  'name' => $datas['imageCategoriesNames'][$i],
674                                  'permalink' => $datas['imageCategoriesPLink'][$i])
675                              )
676                            )
677          );
678        }
679
680        /* affect datas for each plugin
681         *
682         * each plugin have to format the data in an HTML code
683         *
684         * so, for each plugin :
685         *  - look the attributes given in the SELECT clause
686         *  - for each attributes, associate the returned value of the record
687         *  - affect in datas an index equals to the plugin pluginName, with returned HTML code ; HTML code is get from a formatData function
688         *
689         * Example :
690         *  plugin ColorStart provide 2 attributes 'csColors' and 'csColorsPct'
691         *
692         *  we affect to the $attributes var :
693         *  $attributes['csColors'] = $row['csColors'];
694         *  $attributes['csColorsPct'] = $row['csColorsPct'];
695         *
696         *  call the ColorStat RB callback formatData with the $attributes => the function return a HTML code ready to use in the template
697         *
698         *  affect $datas['ColorStat'] = $the_returned_html_code;
699         *
700         *
701         */
702        foreach($tmpBuild['SELECT'] as $key => $val)
703        {
704          if($key!='RB_PIT' && $key!='RB_PIC' && $key!='RB_PCT')
705          {
706            $tmp=explode(',', $val);
707
708            $attributes=Array();
709
710            foreach($tmp as $key2 => $val2)
711            {
712              $name=self::getAttribute($val2);
713              $attributes[$name]=$row[$name];
714            }
715
716            $datas['plugin'][$key]=call_user_func(Array('RBCallBack'.$key, 'formatData'), $attributes);
717
718            unset($tmp);
719            unset($attributes);
720          }
721        }
722        $imagesList[]=$datas;
723        unset($datas);
724      }
725    }
726
727    return(self::toHtml($imagesList));
728    //return("get page : $requestNumber, $pageNumber, $numPerPage<br>$debug<br>$sql");
729  }
730
731  /**
732   * remove all empty value from an array
733   * @param Array a$array : the array to clean
734   */
735  static private function cleanArray(&$array)
736  {
737    foreach($array as $key => $val)
738    {
739      if(trim($val)=='') unset($array[$key]);
740    }
741  }
742
743  /**
744   * returns the alias for an attribute
745   *
746   *  item1                  => returns item1
747   *  table1.item1           => returns item1
748   *  table1.item1 AS alias1 => returns alias1
749   *  item1 AS alias1        => returns alias1
750   *
751   * @param String $var : value ti examine
752   * @return String : the attribute name
753   */
754  static private function getAttribute($val)
755  {
756    preg_match('/(?:(?:[A-Z0-9_]*)\.)?([A-Z0-9_]*)(?:\s+AS\s+([A-Z0-9_]*))?/i', trim($val), $result);
757    if(array_key_exists(2, $result))
758    {
759      return($result[2]);
760    }
761    elseif(array_key_exists(1, $result))
762    {
763      return($result[1]);
764    }
765    else
766    {
767      return($val);
768    }
769  }
770
771
772  /**
773   * get a new request number and create it in the request table
774   *
775   * @param Integer $userId : id of the user
776   * @return Integer : the new request number, -1 if something wrong appened
777   */
778  static private function getNewRequest($userId)
779  {
780    $sql="INSERT INTO ".self::$tables['request']." VALUES('', '$userId', '".date('Y-m-d H:i:s')."', 0, 0, '')";
781    $result=pwg_query($sql);
782    if($result)
783    {
784      return(pwg_db_insert_id());
785    }
786    return(-1);
787  }
788
789  /**
790   * update request properties
791   *
792   * @param Integer $request_id : the id of request to update
793   * @param Integer $numItems : number of items found in the request
794   * @param Float $executionTime : time in second to execute the request
795   * @param String $pluginList : list of used plugins
796   * @return Boolean : true if request was updated, otherwise false
797   */
798  static private function updateRequest($requestId, $numItems, $executionTime, $pluginList)
799  {
800    $sql="UPDATE ".self::$tables['request']."
801            SET num_items = $numItems,
802                execution_time = $executionTime,
803                connected_plugin = '$pluginList'
804            WHERE id = $requestId";
805    $result=pwg_query($sql);
806    if($result)
807    {
808      return(true);
809    }
810    return(false);
811  }
812
813  /**
814   * returns request properties
815   *
816   * @param Integer $request_id : the id of request to update
817   * @return Array : properties for request, false if request doesn't exist
818   */
819  static private function getRequest($requestId)
820  {
821    $returned=false;
822    $sql="SELECT user_id, date, num_items, execution_time, connected_plugin
823          FROM ".self::$tables['request']."
824          WHERE id = $requestId";
825    $result=pwg_query($sql);
826    if($result)
827    {
828      while($row=pwg_db_fetch_assoc($result))
829      {
830        $returned=$row;
831      }
832    }
833    return($returned);
834  }
835
836
837  /**
838   * internal function used by the executeRequest function
839   *
840   * this function is called recursively
841   *
842   * @param Array $groupContent :
843   * @param Array $items :
844   * @return String : a where clause
845   */
846  static private function buildGroup($groupContent, $items, $groups, $operator)
847  {
848    $returned=Array();
849    foreach($groupContent as $key => $val)
850    {
851      if(strpos($val['id'], 'iCbGroup')!==false)
852      {
853        preg_match('/[0-9]*$/i', $val['id'], $groupNumber);
854        $returned[]=self::buildGroup($val['children'], $items, $groups, $groups[$groupNumber[0]]);
855      }
856      else
857      {
858        preg_match('/[0-9]*$/i', $val['id'], $itemNumber);
859        $returned[]=" (".$items[$itemNumber[0]].") ";
860      }
861    }
862    return('('.implode($operator, $returned).')');
863  }
864
865
866  /**
867   * convert a list of images to HTML
868   *
869   * @param Array $imagesList : list of images id & associated datas
870   * @return String : list formatted into HTML code
871   */
872  static protected function toHtml($imagesList)
873  {
874    global $template;
875
876    $template->set_filename('result_items',
877                dirname(dirname(__FILE__)).'/templates/GPCRequestBuilder_result.tpl');
878
879
880
881    $template->assign('datas', $imagesList);
882
883    return($template->parse('result_items', true));
884  }
885
886
887  /**
888   * returns allowed (or not allowed) categories for a user
889   *
890   * used the USER_CACHE_TABLE if possible
891   *
892   * @param Integer $userId : a valid user Id
893   * @return String : IN(...), NOT IN(...) or nothing if there is no restriction
894   *                  for the user
895   */
896  public function getUserCategories($userId)
897  {
898/*
899    $returned='';
900    if($user['forbidden_categories']!='')
901    {
902      $returned=Array(
903        'JOIN' => 'AND ('.IMAGE_CATEGORY.'.category_id NOT IN ('.$user['forbidden_categories'].') ) ',
904        'FROM' => IMAGE_CATEGORY
905      );
906
907
908    }
909    *
910    *
911    */
912  }
913
914
915  /**
916   * check if this is a valid ajax request
917   *
918   * @return Boolean : true if this is a valide ajax request
919   */
920  static protected function checkAjaxRequest()
921  {
922    if(isset($_REQUEST['searchRequest']))
923    {
924      if($_REQUEST['searchRequest']=='execute')
925      {
926        if(!isset($_REQUEST['requestName'])) return(false);
927
928        return(true);
929      }
930
931      if($_REQUEST['searchRequest']=='getPage')
932      {
933        if(!isset($_REQUEST['requestNumber'])) return(false);
934
935        if(!isset($_REQUEST['page']))
936        {
937          $_REQUEST['page']=0;
938        }
939        if($_REQUEST['page']<0) $_REQUEST['page']=0;
940
941        if(!isset($_REQUEST['numPerPage']))
942        {
943          $_REQUEST['numPerPage']=25;
944        }
945
946        if($_REQUEST['numPerPage']>100) $_REQUEST['numPerPage']=100;
947
948        return(true);
949      }
950
951    }
952    return(false);
953  }
954
955
956
957  /**
958   * display search page
959   */
960  static public function displaySearchPage()
961  {
962    global $template, $lang;
963
964    load_language('rbuilder.lang', GPC_PATH);
965
966    $template->set_filename('gpc_search_page',
967                dirname(dirname(__FILE__)).'/templates/GPCRequestBuilder_search.tpl');
968
969    $registeredPlugin=self::getRegistered();
970    $dialogBox=Array();
971    foreach($registeredPlugin as $key=>$val)
972    {
973      if(array_key_exists($key, $registeredPlugin))
974      {
975        if(file_exists($registeredPlugin[$key]['fileName']))
976        {
977          include_once($registeredPlugin[$key]['fileName']);
978
979          $dialogBox[]=Array(
980            'handle' => $val['name'].'DB',
981            'dialogBoxClass' => call_user_func(Array('RBCallBack'.$key, 'getInterfaceDBClass')),
982            'label' => call_user_func(Array('RBCallBack'.$key, 'getInterfaceLabel')),
983            'content' => call_user_func(Array('RBCallBack'.$key, 'getInterfaceContent')),
984          );
985        }
986      }
987    }
988
989    $datas=Array(
990      'dialogBox' => $dialogBox,
991      'themeName' => $template->get_themeconf('name'),
992    );
993
994    $template->assign('datas', $datas);
995
996    return($template->parse('gpc_search_page', true));
997  } //displaySearchPage
998
999}
1000
1001
1002?>
Note: See TracBrowser for help on using the repository browser.