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

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

Fix some bugs on the request builder and improve results display

File size: 27.3 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, $dialogBoxObject)
167  {
168    $config=Array();
169    if(GPCCore::loadConfig(self::$pluginName, $config))
170    {
171      $config['registered'][$pluginName]=Array(
172        'name' => $pluginName,
173        'fileName' => $fileName,
174        'dialogBox' => $dialogBoxObject,
175        'date' => date("Y-m-d H:i:s"),
176        'version' => self::$version,
177      );
178      return(GPCCore::saveConfig(self::$pluginName, $config));
179    }
180    return(false);
181  }
182
183  /**
184   * unregister a plugin using GPCRequestBuilder
185   *
186   * assume that if the plugin was not registerd before, unregistering returns
187   * a true value
188   *
189   * @param String $pluginName : the plugin name
190   * @return Boolean : true if registering is Ok, otherwise false
191   */
192  static public function unregister($plugin)
193  {
194    $config=Array();
195    if(GPCCore::loadConfig(self::$pluginName, $config))
196    {
197      if(array_key_exists('registered', $config))
198      {
199        if(array_key_exists($plugin, $config['registered']))
200        {
201          unset($config['registered'][$plugin]);
202          return(GPCCore::saveConfig(self::$pluginName, $config));
203        }
204      }
205    }
206    // assume if the plugin was not registered before, unregistering it is OK
207    return(true);
208  }
209
210  /**
211   * @return Array : list of registered plugins
212   */
213  static public function getRegistered()
214  {
215    $config=Array();
216    if(GPCCore::loadConfig(self::$pluginName, $config))
217    {
218      if(array_key_exists('registered', $config))
219      {
220        return($config['registered']);
221      }
222    }
223    return(Array());
224  }
225
226
227  /**
228   * initialise the class
229   *
230   * @param String $prefixeTable : the piwigo prefixe used on tables name
231   * @param String $pluginNameFile : the plugin name used for tables name
232   */
233  static public function init($prefixeTable, $pluginNameFile)
234  {
235    $list=Array('request', 'result_cache');
236
237    for($i=0;$i<count($list);$i++)
238    {
239      self::$tables[$list[$i]]=$prefixeTable.$pluginNameFile.'_'.$list[$i];
240    }
241  }
242
243  /**
244   * create the tables needed by RequestBuilder (used during the gpc process install)
245   */
246  static public function createTables()
247  {
248    $tablesDef=array(
249"CREATE TABLE `".self::$tables['request']."` (
250  `id` int(10) unsigned NOT NULL auto_increment,
251  `user_id` int(10) unsigned NOT NULL,
252  `date` datetime NOT NULL,
253  `num_items` int(10) unsigned NOT NULL default '0',
254  `execution_time` float unsigned NOT NULL default '0',
255  `connected_plugin` char(255) NOT NULL,
256  PRIMARY KEY  (`id`)
257)
258CHARACTER SET utf8 COLLATE utf8_general_ci",
259
260"CREATE TABLE `".self::$tables['result_cache']."` (
261  `id` int(10) unsigned NOT NULL,
262  `image_id` int(10) unsigned NOT NULL,
263  PRIMARY KEY  (`id`,`image_id`)
264)
265CHARACTER SET utf8 COLLATE utf8_general_ci",
266  );
267
268    $tablef= new GPCTables(self::$tables);
269    $tablef->create($tablesDef);
270
271    return(true);
272  }
273
274  /**
275   * delete the tables needed by RequestBuilder
276   */
277  static public function deleteTables()
278  {
279    $tablef= new GPCTables(self::$tables);
280    $tablef->drop($tables_def);
281    return(true);
282  }
283
284
285  /**
286   * this function add and handler on the 'loc_end_page_header' to add request
287   * builder JS script & specific CSS on the page
288   *
289   * use it when the displayed page need an access to the criteriaBuilder GUI
290   *
291   */
292  static public function loadJSandCSS()
293  {
294    add_event_handler('loc_end_page_header', array('GPCRequestBuilder', 'insertJSandCSSFiles'));
295  }
296
297
298  /**
299   * insert JS a CSS file in header
300   *
301   * the function is declared public because it used by the 'loc_end_page_header'
302   * event callback
303   *
304   * DO NOT USE IT DIRECTLY
305   *
306   */
307  static public function insertJSandCSSFiles()
308  {
309    global $template;
310
311    $baseName=basename(dirname(dirname(__FILE__))).'/css/';
312    $template->append('head_elements', '<link href="plugins/'.$baseName.'rbuilder.css" type="text/css" rel="stylesheet"/>');
313
314    $baseName=basename(dirname(dirname(__FILE__))).'/js/';
315    $template->append('head_elements', '<script type="text/javascript" src="plugins/'.$baseName.'external/interface/interface.js"></script>');
316    $template->append('head_elements', '<script type="text/javascript" src="plugins/'.$baseName.'external/inestedsortable.pack.js"></script>');
317    $template->append('head_elements', '<script type="text/javascript" src="plugins/'.$baseName.'criteriaBuilder.js"></script>');
318    $template->append('head_elements',
319"<script type=\"text/javascript\">
320  requestBuilderOptions = {
321      textAND:'".l10n('gpc_rb_textAND')."',
322      textOR:'".l10n('gpc_rb_textOR')."',
323      imgEditUrl:'',
324      imgDeleteUrl:'',
325      ajaxUrl:'admin.php?page=plugin&section=".basename(GPC_DIR)."/admin/plugin_admin.php&searchRequest=',
326  }
327</script>");
328  }
329
330
331  /**
332   * execute request from the ajax call
333   *
334   * @return String : a ready to use HTML code
335   */
336  static public function executeRequest()
337  {
338    if(self::checkAjaxRequest())
339    {
340      switch($_REQUEST['searchRequest'])
341      {
342        case 'execute':
343          $result=self::doCache();
344          break;
345        case 'getPage':
346          $result=self::getPage($_REQUEST['requestNumber'], $_REQUEST['page'], $_REQUEST['numPerPage']);
347          break;
348      }
349      GPCAjax::returnResult($result);
350    }
351    else
352    {
353      GPCAjax::returnResult(l10n('gpc_rb_invalid_request'));
354    }
355  }
356
357
358  /**
359   * clear the cache table
360   *
361   * @param Boolean $clearAll : if set to true, clear all records without
362   *                            checking timestamp
363   */
364  static public function clearCache($clearAll=false)
365  {
366    if($clearAll)
367    {
368      $sql="DELETE FROM ".self::$tables['result_cache'];
369    }
370    else
371    {
372      $sql="DELETE pgrc FROM ".self::$tables['result_cache']." pgrc
373              LEFT JOIN ".self::$tables['request']." pgr
374                ON pgrc.id = pgr.id
375              WHERE pgr.date < '".date('Y-m-d H:i:s', strtotime("-2 hour"))."'";
376    }
377    pwg_query($sql);
378  }
379
380  /**
381   * execute a query, and place result in cache
382   *
383   *
384   * @return String : queryNumber;numberOfItems
385   */
386  static private function doCache()
387  {
388    global $user;
389
390    self::clearCache();
391
392    $registeredPlugin=self::getRegistered();
393
394    $build=Array(
395      'SELECT' => 'pit.id',
396      'FROM' => '',
397      'WHERE' => '',
398      'GROUPBY' => '',
399    );
400    $tmpBuild=Array(
401      'FROM' => Array(
402        '('.IMAGES_TABLE.' pit LEFT JOIN '.IMAGE_CATEGORY_TABLE.' pic ON pit.id = pic.image_id)', //JOIN IMAGES & IMAGE_CATEGORY tables
403      ),
404      'WHERE' => Array(),
405      'JOIN' => Array(),
406      'GROUPBY' => Array(
407        'pit.id'
408      )
409    );
410
411    /* build data request for plugins
412     *
413     * Array('Plugin1' =>
414     *          Array(
415     *            criteriaNumber1 => pluginParam1,
416     *            criteriaNumber2 => pluginParam2,
417     *            criteriaNumberN => pluginParamN
418     *          ),
419     *       'Plugin2' =>
420     *          Array(
421     *            criteriaNumber1 => pluginParam1,
422     *            criteriaNumber2 => pluginParam2,
423     *            criteriaNumberN => pluginParamN
424     *          )
425     * )
426     *
427     */
428    $pluginNeeded=Array();
429    $pluginList=Array();
430    foreach($_REQUEST['extraData'] as $key => $val)
431    {
432      $pluginNeeded[$val['owner']][$key]=$_REQUEST['extraData'][$key]['param'];
433      $pluginList[$val['owner']]=$val['owner'];
434    }
435
436    /* for each needed plugin :
437     *  - include the file
438     *  - call the static public function getWhere
439     */
440    foreach($pluginNeeded as $key => $val)
441    {
442      if(array_key_exists($key, $registeredPlugin))
443      {
444        if(file_exists($registeredPlugin[$key]['fileName']))
445        {
446          include_once($registeredPlugin[$key]['fileName']);
447
448          $tmpBuild['FROM'][]=call_user_func(Array('RBCallBack'.$key, 'getFrom'));
449          $tmpBuild['JOIN'][]=call_user_func(Array('RBCallBack'.$key, 'getJoin'));
450
451          foreach($val as $itemNumber => $param)
452          {
453            $tmpBuild['WHERE'][$itemNumber]=call_user_func(Array('RBCallBack'.$key, 'getWhere'), $param);
454          }
455        }
456      }
457    }
458
459
460    /* build FROM
461     *
462     */
463    $build['FROM']=implode(',', $tmpBuild['FROM']);
464    unset($tmpBuild['FROM']);
465
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;
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 piwigo_categories pct
569                       ON pct.id = pic.category_id ",
570      ),
571      'WHERE' => Array(
572        'RB' => "pgrc.id=".$requestNumber,
573        ),
574      'JOIN' => Array(),
575      'GROUPBY' => Array(
576        'RB' => "pit.id"
577      )
578    );
579
580    /* for each needed plugin :
581     *  - include the file
582     *  - call the static public function getFrom, getJoin, getSelect
583     */
584    foreach($pluginNeeded as $key => $val)
585    {
586      if(array_key_exists($val, $registeredPlugin))
587      {
588        if(file_exists($registeredPlugin[$val]['fileName']))
589        {
590          include_once($registeredPlugin[$val]['fileName']);
591          $tmpBuild['SELECT'][$val]=call_user_func(Array('RBCallBack'.$val, 'getSelect'));
592          $tmpBuild['FROM'][$val]=call_user_func(Array('RBCallBack'.$val, 'getFrom'));
593          $tmpBuild['JOIN'][$val]=call_user_func(Array('RBCallBack'.$val, 'getJoin'));
594        }
595      }
596    }
597
598    /* build SELECT
599     *
600     */
601    $build['SELECT']=implode(',', $tmpBuild['SELECT']);
602
603    /* build FROM
604     *
605     */
606    $build['FROM']=implode(',', $tmpBuild['FROM']);
607    unset($tmpBuild['FROM']);
608
609
610    /* build WHERE
611     */
612    $build['WHERE']=implode(' AND ', $tmpBuild['WHERE']);
613    unset($tmpBuild['WHERE']);
614
615
616    /* for each plugin, adds jointure with the IMAGE table
617     */
618    self::cleanArray($tmpBuild['JOIN']);
619    if(count($tmpBuild['JOIN'])>0)
620    {
621      $build['WHERE'].=' AND ('.implode(' AND ', $tmpBuild['JOIN']).') ';
622    }
623    unset($tmpBuild['JOIN']);
624
625    self::cleanArray($tmpBuild['GROUPBY']);
626    if(count($tmpBuild['GROUPBY'])>0)
627    {
628      $build['GROUPBY'].=' '.implode(', ', $tmpBuild['GROUPBY']).' ';
629    }
630    unset($tmpBuild['GROUPBY']);
631
632
633    $imagesList=Array();
634
635    $sql='SELECT '.$build['SELECT']
636        .' FROM '.$build['FROM']
637        .' WHERE '.$build['WHERE']
638        .' GROUP BY '.$build['GROUPBY']
639        .' ORDER BY pit.id '
640        .' LIMIT '.$limitFrom.', '.$numPerPage;
641
642    $result=pwg_query($sql);
643    if($result)
644    {
645      while($row=pwg_db_fetch_assoc($result))
646      {
647        // affect standard datas
648        $datas['imageThumbnail']=dirname($row['imagePath'])."/".$conf['dir_thumbnail']."/".$conf['prefix_thumbnail'].basename($row['imagePath']);
649        $datas['imageId']=$row['imageId'];
650        $datas['imagePath']=$row['imagePath'];
651        $datas['imageName']=$row['imageName'];
652
653        $datas['imageCategoriesId']=explode(',', $row['imageCategoriesId']);
654        $datas['imageCategoriesNames']=explode('#sep#', $row['imageCategoriesNames']);
655        $datas['imageCategoriesPLink']=explode('#sep#', $row['imageCategoriesPLink']);
656        $datas['imageCategoriesDir']=explode(',', $row['imageCategoriesDir']);
657
658
659        $datas['imageCategories']=Array();
660        for($i=0;$i<count($datas['imageCategoriesId']);$i++)
661        {
662          $datas['imageCategories'][]=array(
663            'id' => $datas['imageCategoriesId'][$i],
664            'name' => $datas['imageCategoriesNames'][$i],
665            'dirType' => $datas['imageCategoriesDir'][$i],
666            'pLinks' => $datas['imageCategoriesPLink'][$i],
667            'link'=> make_index_url(
668                              array(
669                                'category' => array(
670                                  'id' => $datas['imageCategoriesId'][$i],
671                                  'name' => $datas['imageCategoriesNames'][$i],
672                                  'permalink' => $datas['imageCategoriesPLink'][$i])
673                              )
674                            )
675          );
676        }
677
678        /* affect datas for each plugin
679         *
680         * each plugin have to format the data in an HTML code
681         *
682         * so, for each plugin :
683         *  - look the attributes given in the SELECT clause
684         *  - for each attributes, associate the returned value of the record
685         *  - affect in datas an index equals to the plugin pluginName, with returned HTML code ; HTML code is get from a formatData function
686         *
687         * Example :
688         *  plugin ColorStart provide 2 attributes 'csColors' and 'csColorsPct'
689         *
690         *  we affect to the $attributes var :
691         *  $attributes['csColors'] = $row['csColors'];
692         *  $attributes['csColorsPct'] = $row['csColorsPct'];
693         *
694         *  call the ColorStat RB callback formatData with the $attributes => the function return a HTML code ready to use in the template
695         *
696         *  affect $datas['ColorStat'] = $the_returned_html_code;
697         *
698         *
699         */
700        foreach($tmpBuild['SELECT'] as $key => $val)
701        {
702          if($key!='RB_PIT' && $key!='RB_PIC' && $key!='RB_PCT')
703          {
704            $tmp=explode(',', $val);
705
706            $attributes=Array();
707
708            foreach($tmp as $key2 => $val2)
709            {
710              $name=self::getAttribute($val2);
711              $attributes[$name]=$row[$name];
712            }
713
714            $datas['plugin'][$key]=call_user_func(Array('RBCallBack'.$key, 'formatData'), $attributes);
715
716            unset($tmp);
717            unset($attributes);
718          }
719        }
720        $imagesList[]=$datas;
721        unset($datas);
722      }
723    }
724
725    return(self::toHtml($imagesList));
726    //return("get page : $requestNumber, $pageNumber, $numPerPage<br>$debug<br>$sql");
727  }
728
729  /**
730   * remove all empty value from an array
731   * @param Array a$array : the array to clean
732   */
733  static private function cleanArray(&$array)
734  {
735    foreach($array as $key => $val)
736    {
737      if(trim($val)=='') unset($array[$key]);
738    }
739  }
740
741  /**
742   * returns the alias for an attribute
743   *
744   *  item1                  => returns item1
745   *  table1.item1           => returns item1
746   *  table1.item1 AS alias1 => returns alias1
747   *  item1 AS alias1        => returns alias1
748   *
749   * @param String $var : value ti examine
750   * @return String : the attribute name
751   */
752  static private function getAttribute($val)
753  {
754    preg_match('/(?:(?:[A-Z0-9_]*)\.)?([A-Z0-9_]*)(?:\s+AS\s+([A-Z0-9_]*))?/i', trim($val), $result);
755    if(array_key_exists(2, $result))
756    {
757      return($result[2]);
758    }
759    elseif(array_key_exists(1, $result))
760    {
761      return($result[1]);
762    }
763    else
764    {
765      return($val);
766    }
767  }
768
769
770  /**
771   * get a new request number and create it in the request table
772   *
773   * @param Integer $userId : id of the user
774   * @return Integer : the new request number, -1 if something wrong appened
775   */
776  static private function getNewRequest($userId)
777  {
778    $sql="INSERT INTO ".self::$tables['request']." VALUES('', '$userId', '".date('Y-m-d H:i:s')."', 0, 0, '')";
779    $result=pwg_query($sql);
780    if($result)
781    {
782      return(pwg_db_insert_id());
783    }
784    return(-1);
785  }
786
787  /**
788   * update request properties
789   *
790   * @param Integer $request_id : the id of request to update
791   * @param Integer $numItems : number of items found in the request
792   * @param Float $executionTime : time in second to execute the request
793   * @param String $pluginList : list of used plugins
794   * @return Boolean : true if request was updated, otherwise false
795   */
796  static private function updateRequest($requestId, $numItems, $executionTime, $pluginList)
797  {
798    $sql="UPDATE ".self::$tables['request']."
799            SET num_items = $numItems,
800                execution_time = $executionTime,
801                connected_plugin = '$pluginList'
802            WHERE id = $requestId";
803    $result=pwg_query($sql);
804    if($result)
805    {
806      return(true);
807    }
808    return(false);
809  }
810
811  /**
812   * returns request properties
813   *
814   * @param Integer $request_id : the id of request to update
815   * @return Array : properties for request, false if request doesn't exist
816   */
817  static private function getRequest($requestId)
818  {
819    $returned=false;
820    $sql="SELECT user_id, date, num_items, execution_time, connected_plugin
821          FROM ".self::$tables['request']."
822          WHERE id = $requestId";
823    $result=pwg_query($sql);
824    if($result)
825    {
826      while($row=pwg_db_fetch_assoc($result))
827      {
828        $returned=$row;
829      }
830    }
831    return($returned);
832  }
833
834
835  /**
836   * internal function used by the executeRequest function
837   *
838   * this function is called recursively
839   *
840   * @param Array $groupContent :
841   * @param Array $items :
842   * @return String : a where clause
843   */
844  static private function buildGroup($groupContent, $items, $groups, $operator)
845  {
846    $returned=Array();
847    foreach($groupContent as $key => $val)
848    {
849      if(strpos($val['id'], 'iCbGroup')!==false)
850      {
851        preg_match('/[0-9]*$/i', $val['id'], $groupNumber);
852        $returned[]=self::buildGroup($val['children'], $items, $groups, $groups[$groupNumber[0]]);
853      }
854      else
855      {
856        preg_match('/[0-9]*$/i', $val['id'], $itemNumber);
857        $returned[]=" (".$items[$itemNumber[0]].") ";
858      }
859    }
860    return('('.implode($operator, $returned).')');
861  }
862
863
864  /**
865   * convert a list of images to HTML
866   *
867   * @param Array $imagesList : list of images id & associated datas
868   * @return String : list formatted into HTML code
869   */
870  static protected function toHtml($imagesList)
871  {
872    global $template;
873
874    $template->set_filename('result_items',
875                dirname(dirname(__FILE__)).'/templates/GPCRequestBuilder_result.tpl');
876
877
878
879    $template->assign('datas', $imagesList);
880
881    return($template->parse('result_items', true));
882  }
883
884
885  /**
886   * returns allowed (or not allowed) categories for a user
887   *
888   * used the USER_CACHE_TABLE if possible
889   *
890   * @param Integer $userId : a valid user Id
891   * @return String : IN(...), NOT IN(...) or nothing if there is no restriction
892   *                  for the user
893   */
894  public function getUserCategories($userId)
895  {
896/*
897    $returned='';
898    if($user['forbidden_categories']!='')
899    {
900      $returned=Array(
901        'JOIN' => 'AND ('.IMAGE_CATEGORY.'.category_id NOT IN ('.$user['forbidden_categories'].') ) ',
902        'FROM' => IMAGE_CATEGORY
903      );
904
905
906    }
907    *
908    *
909    */
910  }
911
912
913  /**
914   * check if this is a valid ajax request
915   *
916   * @return Boolean : true if this is a valide ajax request
917   */
918  static protected function checkAjaxRequest()
919  {
920    if(isset($_REQUEST['searchRequest']))
921    {
922      if($_REQUEST['searchRequest']=='execute')
923      {
924        if(!isset($_REQUEST['requestName'])) return(false);
925
926        return(true);
927      }
928
929      if($_REQUEST['searchRequest']=='getPage')
930      {
931        if(!isset($_REQUEST['requestNumber'])) return(false);
932
933        if(!isset($_REQUEST['page']))
934        {
935          $_REQUEST['page']=0;
936        }
937        if($_REQUEST['page']<0) $_REQUEST['page']=0;
938
939        if(!isset($_REQUEST['numPerPage']))
940        {
941          $_REQUEST['numPerPage']=25;
942        }
943
944        if($_REQUEST['numPerPage']>100) $_REQUEST['numPerPage']=100;
945
946        return(true);
947      }
948
949    }
950    return(false);
951  }
952
953
954
955  /**
956   * display search page
957   */
958  static public function displaySearchPage()
959  {
960    global $template, $lang;
961
962    load_language('rbuilder.lang', GPC_PATH);
963
964    $template->set_filename('gpc_search_page',
965                dirname(dirname(__FILE__)).'/templates/GPCRequestBuilder_search.tpl');
966
967    $registeredPlugin=self::getRegistered();
968    $dialogBox=Array();
969    foreach($registeredPlugin as $key=>$val)
970    {
971      if(array_key_exists($key, $registeredPlugin))
972      {
973        if(file_exists($registeredPlugin[$key]['fileName']))
974        {
975          include_once($registeredPlugin[$key]['fileName']);
976
977          $dialogBox[]=Array(
978            'handle' => $val['name'].'DB',
979            'dialogBoxClass' => call_user_func(Array('RBCallBack'.$key, 'getInterfaceDBClass')),
980            'label' => call_user_func(Array('RBCallBack'.$key, 'getInterfaceLabel')),
981            'content' => call_user_func(Array('RBCallBack'.$key, 'getInterfaceContent')),
982          );
983        }
984      }
985    }
986
987    $datas=Array(
988      'dialogBox' => $dialogBox,
989      'themeName' => $template->get_themeconf('name'),
990    );
991
992    $template->assign('datas', $datas);
993
994    return($template->parse('gpc_search_page', true));
995  } //displaySearchPage
996
997}
998
999
1000?>
Note: See TracBrowser for help on using the repository browser.