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

Revision 15340, 44.8 KB checked in by grum, 8 years ago (diff)

feature:2436 - Compatibility with Piwigo 2.4

Line 
1<?php
2/* -----------------------------------------------------------------------------
3  class name: GCPRequestBuilder
4  class version  : 1.1.6
5  plugin version : 3.5.1
6  date           : 2011-05-15
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  * HOW TO USE IT ?
22  * ===============
23  *
24  * when installing the plugin, you have to register the usage of the request
25  * builder
26  *
27  * 1/ Create a RBCallback class
28  *  - extends the GPCSearchCallback class ; the name of the extended class must
29  *    be "RBCallBack%" => replace the "%" by the plugin name
30  *     for example : 'ThePlugin' => 'RBCallBackThePlugin'
31  *
32  * 2/ In the plugin 'maintain.inc.php' file :
33  *  - function plugin_install, add :
34  *       GPCRequestBuilder::register('plugin name', 'path to the RBCallback classe');
35  *          for example : GPCRequestBuilder::register('ThePlugin', $piwigo_path.'plugins/ThePlugin/rbcallback_file_name.php');
36  *
37  *
38  *  - function plugin_uninstall, add :
39  *       GPCRequestBuilder::unregister('plugin name');
40  *          for example : GPCRequestBuilder::unregister('ThePlugin');
41  *
42  * 3/ In the plugin code, put somewhere
43  *     GPCRequestBuilder::loadJSandCSS();
44  *     => this will load specific JS and CSS in the page, by adding url in the
45  *        the header, so try to put this where you're used to prepare the header
46  *
47  * 4/ to display the request builder, just add the returned string in the html
48  *    page
49  *       $stringForTheTemplate=GPCRequestBuilder::displaySearchPage();
50  *
51  *
52  *
53  * HOW DOES THE REQUEST BUILDER WORKS ?
54  * ====================================
55  *
56  * the request builder works in 2 steps :
57  *  - first step  : build a cache, to associate all image id corresponding to
58  *                  the search criterion
59  *                  the cache is an association of request ID/image id
60  *  - second step : use the cache to retrieve images informations
61  *
62  ------------------------------------------------------------------------------
63  :: HISTORY
64
65| release | date       |
66| 1.0.0   | 2010/04/30 | * start coding
67|         |            |
68| 1.1.0   | 2010/09/08 | * add functionnalities to manage complex requests
69|         |            |
70| 1.1.1   | 2010/10/14 | * fix bug on the buildGroupRequest function
71|         |            |   . adding 'DISTINCT' keyword to the SQL requests
72|         |            |
73|         |            | * ajax management moved into the gpc_ajax.php file
74|         |            |
75|         |            | * fix bug on user level access to picture
76|         |            |
77| 1.1.2   | 2010/11/01 | * mantis bug:1984
78|         |            |   . RBuilder returns an error message when one picture
79|         |            |     have multiple categories
80|         |            |
81| 1.1.3   | 2011/01/31 | * mantis bug:2156
82|         |            |   . undefined variable on RBuilder screens
83|         |            |
84| 1.1.4   | 2011/01/31 | * mantis bug:2167
85|         |            |
86| 1.1.5   | 2011/04/10 | * Compatibility with piwigo 2.2
87|         |            |
88| 1.1.6   | 2011/05/15 | * mantis bug:2302
89|         |            |   . Request builder user interface don't work
90|         |            |
91|         |            |
92|         |            |
93|         |            |
94
95  --------------------------------------------------------------------------- */
96
97if(!defined('GPC_DIR')) define('GPC_DIR' , baseName(dirname(dirname(__FILE__))));
98if(!defined('GPC_PATH')) define('GPC_PATH' , PHPWG_PLUGINS_PATH . GPC_DIR . '/');
99
100include_once('GPCTables.class.inc.php');
101
102/**
103 *
104 * Preparing the temporary table => doCache()
105 * ------------------------------------------
106 * To prepare the cache, the request builder use the following functions :
107 *  - getImageId
108 *  - getFrom
109 *  - getWhere
110 *  - getHaving
111 *
112 * Preparing the cache table => doCache()
113 * --------------------------------------
114 * To prepare the cache, the request builder use the following functions :
115 *  => the getFilter function is used to prepare the filter for the getPage()
116 *     function ; not used to build the cache
117 *
118 * Retrieving the results => getPage()
119 * -----------------------------------
120 * To retrieve the image informations, the request builder uses the following
121 * functions :
122 *  - getSelect
123 *  - getFrom
124 *  - getJoin
125 *  - getFilter (in fact, the result of this function is stored by the doCache()
126 *               function while the cache is builded, but it is used only when
127 *               retrieving the results for multirecord tables)
128 *  - formatData
129 *
130 *
131 * Example
132 * -------
133 * Consider the table "tableA" like this
134 *
135 *  - (*) imageId
136 *  - (*) localId
137 *  -     att1
138 *  -     att2
139 *  The primary key is the 'imageId'+'localId' attributes
140 *    => for one imageId, you can have ZERO or more than ONE record
141 *       when you register the class, you have to set the $multiRecord parameter
142 *       to 'y'
143 *
144 *  gatImageId returns      : "tableA.imageId"
145 *  getSelect returns       : "tableA.att1, tableA.att2"
146 *  getFrom returns         : "tableA"
147 *  getWhere returns        : "tableA.localId= xxxx AND tableA.att1 = zzzz"
148 *  getJoin returns         : "tableA.imageId = pit.id"
149 *  getFilter returns       : "tableA.localId= xxxx"
150 *
151 *  Examples :
152 *   - plugin AdvancedMetadata use getFilter
153 *   - plugin AdvancedSearchEngine, module ASETag use getHaving and getWhere
154 */
155class GPCSearchCallback {
156
157  /**
158   * the getImageId returns the name of the image id attribute
159   * return String
160   */
161  static public function getImageId()
162  {
163    return("");
164  }
165
166  /**
167   * the getSelect function must return an attribute list separated with a comma
168   *
169   * "att1, att2, att3, att4"
170   *
171   * you can specifie tables names and aliases
172   *
173   * "table1.att1 AS alias1, table1.att2 AS alias2, table2.att3 AS alias3"
174   */
175  static public function getSelect($param="")
176  {
177    return("");
178  }
179
180  /**
181   * the getFrom function must return a tables list separated with a comma
182   *
183   * "table1, (table2 left join table3 on table2.key = table3.key), table4"
184   */
185  static public function getFrom($param="")
186  {
187    return("");
188  }
189
190  /**
191   * the getWhere function must return a ready to use where clause
192   *
193   * "(att1 = value0 OR att2 = value1) AND att4 LIKE value2 "
194   */
195  static public function getWhere($param="")
196  {
197    return("");
198  }
199
200
201  /**
202   * the getHaving function return a ready to user HAVING clause
203   *
204   * " FIND_IN_SET(value0, GROUP_CONCAT(DISTINCT att1 SEPARATOR ',')) AND
205   *   FIND_IN_SET(value0, GROUP_CONCAT(DISTINCT att1 SEPARATOR ',')) "
206   *
207   */
208  static public function getHaving($param="")
209  {
210    return("");
211  }
212
213
214  /**
215   * the getJoin function must return a ready to use sql statement allowing to
216   * join the IMAGES table (key : pit.id) with given conditions
217   *
218   * "att3 = pit.id "
219   */
220  static public function getJoin($param="")
221  {
222    return("");
223  }
224
225
226  /**
227   * the getFilter function must return a ready to use where clause
228   * this where clause is used to filter the cache when the used tables can
229   * return more than one result
230   *
231   * the filter can be empty, can be equal to the where clause, or can be equal
232   * to a sub part of the where clause
233   *
234   * in most case, return "" is the best solution
235   *
236   */
237  static public function getFilter($param="")
238  {
239    //return(self::getWhere($param));
240    return("");
241  }
242
243
244  /**
245   * this function is called by the request builder, allowing to display plugin
246   * data with a specific format
247   *
248   * @param Array $attributes : array of ('attribute_name' => 'attribute_value')
249   * @return String : HTML formatted value
250   */
251  static public function formatData($attributes)
252  {
253    return(print_r($attributes, true));
254  }
255
256
257  /**
258   * this function is called by the request builder to make the search page, and
259   * must return the HTML & JS code of the dialogbox used to select criterion
260   *
261   * Notes :
262   *  - the dialogbox is a JS object with a public method 'show'
263   *  - when the method show is called, one parameter is given by the request
264   *    builder ; the parameter is an object defined as this :
265   *      {
266   *        cBuilder: an instance of the criteriaBuilder object used in the page,
267   *      }
268   *
269   *
270   *
271   *
272   * @param String $mode : can take 'admin' or 'public' values, allowing to
273   *                       return different interface if needed
274   * @return String : HTML formatted value
275   */
276  static public function getInterfaceContent($mode='admin')
277  {
278    return("");
279  }
280
281  /**
282   * this function returns the label displayed in the criterion menu
283   *
284   * @return String : label displayed in the criterions menu
285   */
286  static public function getInterfaceLabel()
287  {
288    return(l10n('gpc_rb_unknown_interface'));
289  }
290
291  /**
292   * this function returns the name of the dialog box class
293   *
294   * @return String : name of the dialogbox class
295   */
296  static public function getInterfaceDBClass()
297  {
298    return('');
299  }
300
301
302}
303
304
305//load_language('rbuilder.lang', GPC_PATH);
306
307
308class GPCRequestBuilder {
309
310  static public $pluginName = 'GPCRequestBuilder';
311  static public $version = '1.1.4';
312
313  static private $tables = Array();
314  static protected $tGlobalId=0;
315
316  /**
317   * register a plugin using GPCRequestBuilder
318   *
319   * @param String $pluginName : the plugin name
320   * @param String $fileName : the php filename where the callback function can
321   *                           be found
322   * @return Boolean : true if registering is Ok, otherwise false
323   */
324  static public function register($plugin, $fileName)
325  {
326    $config=Array();
327    if(!GPCCore::loadConfig(self::$pluginName, $config))
328    {
329      $config['registered']=array();
330    }
331
332    $config['registered'][$plugin]=Array(
333      'name' => $plugin,
334      'fileName' => $fileName,
335      'date' => date("Y-m-d H:i:s"),
336      'version' => self::$version
337    );
338    return(GPCCore::saveConfig(self::$pluginName, $config));
339  }
340
341  /**
342   * unregister a plugin using GPCRequestBuilder
343   *
344   * assume that if the plugin was not registerd before, unregistering returns
345   * a true value
346   *
347   * @param String $pluginName : the plugin name
348   * @return Boolean : true if registering is Ok, otherwise false
349   */
350  static public function unregister($plugin)
351  {
352    $config=Array();
353    if(GPCCore::loadConfig(self::$pluginName, $config))
354    {
355      if(array_key_exists('registered', $config))
356      {
357        if(array_key_exists($plugin, $config['registered']))
358        {
359          unset($config['registered'][$plugin]);
360          return(GPCCore::saveConfig(self::$pluginName, $config));
361        }
362      }
363    }
364    // assume if the plugin was not registered before, unregistering it is OK
365    return(true);
366  }
367
368  /**
369   * @return Array : list of registered plugins
370   */
371  static public function getRegistered()
372  {
373    $config=Array();
374    if(GPCCore::loadConfig(self::$pluginName, $config))
375    {
376      if(array_key_exists('registered', $config))
377      {
378        return($config['registered']);
379      }
380    }
381    return(Array());
382  }
383
384
385  /**
386   * initialise the class
387   *
388   * @param String $prefixeTable : the piwigo prefixe used on tables name
389   * @param String $pluginNameFile : the plugin name used for tables name
390   */
391  static public function init($prefixeTable, $pluginNameFile)
392  {
393    $list=Array('request', 'result_cache', 'temp');
394
395    for($i=0;$i<count($list);$i++)
396    {
397      self::$tables[$list[$i]]=$prefixeTable.$pluginNameFile.'_'.$list[$i];
398    }
399  }
400
401  /**
402   * create the tables needed by RequestBuilder (used during the gpc process install)
403   */
404  static public function createTables()
405  {
406    $tablesDef=array(
407"CREATE TABLE `".self::$tables['request']."` (
408  `id` int(10) unsigned NOT NULL auto_increment,
409  `user_id` int(10) unsigned NOT NULL,
410  `date` datetime NOT NULL,
411  `num_items` int(10) unsigned NOT NULL default '0',
412  `execution_time` float unsigned NOT NULL default '0',
413  `connected_plugin` char(255) NOT NULL,
414  `filter` text NOT NULL,
415  `parameters` text NOT NULL,
416  PRIMARY KEY  (`id`)
417)
418CHARACTER SET utf8 COLLATE utf8_general_ci",
419
420"CREATE TABLE `".self::$tables['result_cache']."` (
421  `id` int(10) unsigned NOT NULL,
422  `image_id` int(10) unsigned NOT NULL,
423  PRIMARY KEY  (`id`,`image_id`)
424)
425CHARACTER SET utf8 COLLATE utf8_general_ci",
426
427"CREATE TABLE `".self::$tables['temp']."` (
428  `requestId` char(30) NOT NULL,
429  `imageId` mediumint(8) unsigned NOT NULL,
430  PRIMARY KEY  (`requestId`,`imageId`)
431)
432CHARACTER SET utf8 COLLATE utf8_general_ci",
433  );
434
435    $tablef= new GPCTables(self::$tables);
436    $tablef->create($tablesDef);
437
438    return(true);
439  }
440
441  /**
442   * update the tables needed by RequestBuilder (used during the gpc process
443   * activation)
444   */
445  static public function updateTables($pluginPreviousRelease)
446  {
447    $tablef=new GPCTables(array(self::$tables['temp']));
448
449    switch($pluginPreviousRelease)
450    {
451      case '03.01.00':
452        $tablesCreate=array();
453        $tablesUpdate=array();
454
455        $tablesCreate[]=
456"CREATE TABLE `".self::$tables['temp']."` (
457  `requestId` char(30) NOT NULL,
458  `imageId` mediumint(8) unsigned NOT NULL,
459  PRIMARY KEY  (`requestId`,`imageId`)
460)
461CHARACTER SET utf8 COLLATE utf8_general_ci";
462
463        $tablesUpdate[self::$tables['request']]['filter']=
464"ADD COLUMN  `filter` text NOT NULL default '' ";
465
466
467
468        $tablef->create($tablesCreate);
469        $tablef->updateTablesFields($tablesUpdate);
470        // no break ! need to be updated like the next release
471        // break;
472      case '03.01.01':
473      case '03.02.00':
474      case '03.02.01':
475      case '03.03.00':
476      case '03.03.01':
477        $tablesUpdate=array();
478
479        $tablesUpdate[self::$tables['request']]['parameters']=
480"ADD COLUMN `parameters` TEXT NOT NULL AFTER `filter`";
481
482        $tablef->updateTablesFields($tablesUpdate);
483        // no break ! need to be updated like the next release
484        // break;
485    }
486
487    return(true);
488  }
489
490  /**
491   * delete the tables needed by RequestBuilder
492   */
493  static public function deleteTables()
494  {
495    $tablef= new GPCTables(self::$tables);
496    $tablef->drop();
497    return(true);
498  }
499
500
501  /**
502   * delete the config
503   */
504  static public function deleteConfig()
505  {
506    GPCCore::deleteConfig(self::$pluginName);
507  }
508
509  /**
510   * this function add and handler on the 'loc_end_page_header' to add request
511   * builder JS script & specific CSS on the page
512   *
513   * use it when the displayed page need an access to the criteriaBuilder GUI
514   *
515   */
516  static public function loadJSandCSS()
517  {
518    load_language('rbuilder.lang', GPC_PATH);
519    add_event_handler('loc_begin_page_header', array('GPCRequestBuilder', 'insertJSandCSSFiles'), 9);
520  }
521
522
523  /**
524   * insert JS a CSS file in header
525   *
526   * the function is declared public because it used by the 'loc_begin_page_header'
527   * event callback
528   *
529   * DO NOT USE IT DIRECTLY
530   *
531   */
532  static public function insertJSandCSSFiles()
533  {
534    global $template;
535
536
537    $baseName=basename(dirname(dirname(__FILE__))).'/css/';
538    $template->append('head_elements', '<link href="plugins/'.$baseName.'rbuilder.css" type="text/css" rel="stylesheet"/>');
539    if(defined('IN_ADMIN')) $template->append('head_elements', '<link href="plugins/'.$baseName.'rbuilder_'.$template->get_themeconf('name').'.css" type="text/css" rel="stylesheet"/>');
540
541
542    $baseName=basename(dirname(dirname(__FILE__))).'/js/';
543    GPCCore::addHeaderJS('jquery', 'themes/default/js/jquery.js');
544    GPCCore::addHeaderJS('jquery.ui', 'themes/default/js/ui/jquery.ui.core.js', array('jquery'));
545    GPCCore::addHeaderJS('jquery.ui.widget', 'themes/default/js/ui/jquery.ui.widget.js', array('jquery.ui'));
546    GPCCore::addHeaderJS('jquery.ui.mouse', 'themes/default/js/ui/jquery.ui.mouse.js', array('jquery.ui.widget'));
547    GPCCore::addHeaderJS('jquery.ui.position', 'themes/default/js/ui/jquery.ui.position.js', array('jquery.ui.widget'));
548    GPCCore::addHeaderJS('jquery.ui.draggable', 'themes/default/js/ui/jquery.ui.draggable.js', array('jquery.ui.widget'));
549    GPCCore::addHeaderJS('jquery.ui.dialog', 'themes/default/js/ui/jquery.ui.dialog.js', array('jquery.ui.widget'));
550    GPCCore::addHeaderJS('jquery.ui.slider', 'themes/default/js/ui/jquery.ui.slider.js', array('jquery.ui.widget'));
551
552    GPCCore::addHeaderJS('gpc.external.inestedsortable', 'plugins/'.$baseName.'external/iNestedSortablePack.js', array('jquery', 'jquery.ui'));
553    GPCCore::addHeaderJS('gpc.rbCriteriaBuilder', 'plugins/'.$baseName.'rbCriteriaBuilder.js', array('gpc.external.inestedsortable'));
554
555    $template->append('head_elements',
556"<script type=\"text/javascript\">
557  requestBuilderOptions = {
558    textAND:\"".l10n('gpc_rb_textAND')."\",
559    textOR:\"".l10n('gpc_rb_textOR')."\",
560    textNoCriteria:\"".l10n('There is no criteria ! At least, one criteria is required to do search...')."\",
561    textSomethingWrong:\"".l10n('gpc_something_is_wrong_on_the_server_side')."\",
562    textCaddieUpdated:\"".l10n('gpc_the_caddie_is_updated')."\",
563    helpEdit:\"".l10n('gpc_help_edit_criteria')."\",
564    helpDelete:\"".l10n('gpc_help_delete_criteria')."\",
565    helpMove:\"".l10n('gpc_help_move_criteria')."\",
566    helpSwitchCondition:\"".l10n('gpc_help_switch_condition')."\",
567    ajaxUrl:'plugins/GrumPluginClasses/gpc_ajax.php',
568  }
569</script>");
570  }
571
572
573  /**
574   * execute request from the ajax call
575   *
576   * @return String : a ready to use HTML code
577   */
578  static public function executeRequest($ajaxfct)
579  {
580    $result='';
581    switch($ajaxfct)
582    {
583      case 'public.rbuilder.searchExecute':
584        $result=self::doCache();
585        break;
586      case 'public.rbuilder.searchGetPage':
587        $result=self::getPage($_REQUEST['requestNumber'], $_REQUEST['page'], $_REQUEST['numPerPage']);
588        break;
589    }
590    return($result);
591  }
592
593
594  /**
595   * clear the cache table
596   *
597   * @param Boolean $clearAll : if set to true, clear all records without
598   *                            checking timestamp
599   */
600  static public function clearCache($clearAll=false)
601  {
602    if($clearAll)
603    {
604      $sql="DELETE FROM ".self::$tables['result_cache'];
605    }
606    else
607    {
608      $sql="DELETE pgrc FROM ".self::$tables['result_cache']." pgrc
609              LEFT JOIN ".self::$tables['request']." pgr
610                ON pgrc.id = pgr.id
611              WHERE pgr.date < '".date('Y-m-d H:i:s', strtotime("-2 hour"))."'";
612    }
613    pwg_query($sql);
614  }
615
616  /**
617   * prepare the temporary table used for multirecord requests
618   *
619   * @param Integer $requestNumber : id of request
620   * @return String : name of the request key temporary table
621   */
622  static private function prepareTempTable($requestNumber)
623  {
624    //$tableName=call_user_func(Array('RBCallBack'.$plugin, 'getFrom'));
625    //$imageIdName=call_user_func(Array('RBCallBack'.$plugin, 'getImageId'));
626
627    $tempClauses=array();
628    foreach($_REQUEST['extraData'] as $key => $extraData)
629    {
630      $tempClauses[$key]=array(
631        'plugin' => $extraData['owner'],
632        'where' => call_user_func(Array('RBCallBack'.$extraData['owner'], 'getWhere'), $extraData['param']),
633        'having' => call_user_func(Array('RBCallBack'.$extraData['owner'], 'getHaving'), $extraData['param']),
634      );
635    }
636
637    $sql="INSERT INTO ".self::$tables['temp']." ".self::buildGroupRequest($_REQUEST[$_REQUEST['requestName']], $tempClauses, $_REQUEST['operator'], ' AND ', $requestNumber);
638//echo $sql;
639    $result=pwg_query($sql);
640
641    return($requestNumber);
642  }
643
644  /**
645   * clear the temporary table used for multirecord requests
646   *
647   * @param Array $requestNumber : the requestNumber to delete
648   */
649  static private function clearTempTable($requestNumber)
650  {
651    $sql="DELETE FROM ".self::$tables['temp']." WHERE requestId = '$requestNumber';";
652    pwg_query($sql);
653  }
654
655
656  /**
657   * execute a query, and place result in cache
658   *
659   *
660   * @return String : queryNumber;numberOfItems
661   */
662  static private function doCache()
663  {
664    global $user;
665
666    self::clearCache();
667
668    $registeredPlugin=self::getRegistered();
669    $requestNumber=self::getNewRequest($user['id']);
670
671    $build=Array(
672      'SELECT' => 'pit.id',
673      'FROM' => '',
674      'WHERE' => 'pit.level <= '.$user['level'],
675      'GROUPBY' => '',
676      'FILTER' => ''
677    );
678    $tmpBuild=Array(
679      'FROM' => Array(
680        '('.IMAGES_TABLE.' pit LEFT JOIN '.IMAGE_CATEGORY_TABLE.' pic ON pit.id = pic.image_id)' /*JOIN IMAGES & IMAGE_CATEGORY tables*/
681       .'   JOIN '.USER_CACHE_CATEGORIES_TABLE.' pucc ON pucc.cat_id=pic.category_id',  /* IMAGE_CATEGORY & USER_CACHE_CATEGORIES_TABLE tables*/
682
683      ),
684      'WHERE' => Array(),
685      'JOIN' => Array(999=>'pucc.user_id='.$user['id']),
686      'GROUPBY' => Array(
687        'pit.id'
688      ),
689      'FILTER' => Array(),
690    );
691
692    /* build data request for plugins
693     *
694     * Array('Plugin1' =>
695     *          Array(
696     *            criteriaNumber1 => pluginParam1,
697     *            criteriaNumber2 => pluginParam2,
698     *            criteriaNumberN => pluginParamN
699     *          ),
700     *       'Plugin2' =>
701     *          Array(
702     *            criteriaNumber1 => pluginParam1,
703     *            criteriaNumber2 => pluginParam2,
704     *            criteriaNumberN => pluginParamN
705     *          )
706     * )
707     *
708     */
709    $pluginNeeded=Array();
710    $pluginList=Array();
711    $tempName=Array();
712    foreach($_REQUEST['extraData'] as $key => $val)
713    {
714      $pluginNeeded[$val['owner']][$key]=$_REQUEST['extraData'][$key]['param'];
715      $pluginList[$val['owner']]=$val['owner'];
716    }
717
718    /* for each plugin, include the rb callback class file */
719    foreach($pluginList as $val)
720    {
721      if(file_exists($registeredPlugin[$val]['fileName']))
722      {
723        include_once($registeredPlugin[$val]['fileName']);
724      }
725    }
726
727    /* prepare the temp table for the request */
728    self::prepareTempTable($requestNumber);
729    $tmpBuild['FROM'][]=self::$tables['temp'];
730    $tmpBuild['JOIN'][]=self::$tables['temp'].".requestId = '".$requestNumber."'
731                        AND ".self::$tables['temp'].".imageId = pit.id";
732
733    /* for each needed plugin, prepare the filter */
734    foreach($pluginNeeded as $key => $val)
735    {
736      foreach($val as $itemNumber => $param)
737      {
738        $tmpFilter=call_user_func(Array('RBCallBack'.$key, 'getFilter'), $param);
739
740        if(trim($tmpFilter)!="") $tmpBuild['FILTER'][$key][]='('.$tmpFilter.')';
741      }
742    }
743
744
745    /* build FROM
746     *
747     */
748    $build['FROM']=implode(',', $tmpBuild['FROM']);
749    unset($tmpBuild['FROM']);
750
751    /* build WHERE
752     */
753    self::cleanArray($tmpBuild['WHERE']);
754    if(count($tmpBuild['WHERE'])>0)
755    {
756      $build['WHERE']=' ('.self::buildGroup($_REQUEST[$_REQUEST['requestName']], $tmpBuild['WHERE'], $_REQUEST['operator'], ' AND ').') ';
757    }
758    unset($tmpBuild['WHERE']);
759
760
761    /* build FILTER
762     */
763    self::cleanArray($tmpBuild['FILTER']);
764    if(count($tmpBuild['FILTER'])>0)
765    {
766      $tmp=array();
767      foreach($tmpBuild['FILTER'] as $key=>$val)
768      {
769        $tmp[$key]='('.implode(' OR ', $val).')';
770      }
771      $build['FILTER']=' ('.implode(' AND ', $tmp).') ';
772    }
773    unset($tmpBuild['FILTER']);
774
775
776    /* for each plugin, adds jointure with the IMAGE table
777     */
778    self::cleanArray($tmpBuild['JOIN']);
779    if(count($tmpBuild['JOIN'])>0)
780    {
781      if($build['WHERE']!='') $build['WHERE'].=' AND ';
782      $build['WHERE'].=' ('.implode(' AND ', $tmpBuild['JOIN']).') ';
783    }
784    unset($tmpBuild['JOIN']);
785
786    self::cleanArray($tmpBuild['GROUPBY']);
787    if(count($tmpBuild['GROUPBY'])>0)
788    {
789      $build['GROUPBY'].=' '.implode(', ', $tmpBuild['GROUPBY']).' ';
790    }
791    unset($tmpBuild['GROUPBY']);
792
793
794
795    $sql=' FROM '.$build['FROM'];
796    if($build['WHERE']!='')
797    {
798      $sql.=' WHERE '.$build['WHERE'];
799    }
800    if($build['GROUPBY']!='')
801    {
802      $sql.=' GROUP BY '.$build['GROUPBY'];
803    }
804
805    $sql.=" ORDER BY pit.id ";
806
807    $sql="INSERT INTO ".self::$tables['result_cache']." (SELECT DISTINCT $requestNumber, ".$build['SELECT']." $sql)";
808
809//echo $sql;
810    $returned="0;0";
811
812    $result=pwg_query($sql);
813    if($result)
814    {
815      $numberItems=pwg_db_changes($result);
816      self::updateRequest($requestNumber, $numberItems, 0, implode(',', $pluginList), $build['FILTER'], $_REQUEST['extraData']);
817
818      $returned="$requestNumber;".$numberItems;
819    }
820
821    self::clearTempTable($requestNumber);
822
823    return($returned);
824  }
825
826  /**
827   * return a page content. use the cache table to find request result
828   *
829   * @param Integer $requestNumber : the request number (from cache table)
830   * @param Integer $pageNumber : the page to be returned
831   * @param Integer $numPerPage : the number of items returned on a page
832   * @param String $mode : if mode = 'count', the function returns the number of
833   *                       rows ; otherwise, returns rows in a html string
834   * @return String : formatted HTML code
835   */
836  static private function getPage($requestNumber, $pageNumber, $numPerPage)
837  {
838    global $conf, $user;
839    $request=self::getRequest($requestNumber);
840
841    if($request===false)
842    {
843      return("KO");
844    }
845
846    $limitFrom=$numPerPage*($pageNumber-1);
847
848    $pluginNeeded=explode(',', $request['connected_plugin']);
849    $registeredPlugin=self::getRegistered();
850
851    $build=Array(
852      'SELECT' => '',
853      'FROM' => '',
854      'WHERE' => '',
855      'GROUPBY' => '',
856    );
857    $tmpBuild=Array(
858      'SELECT' => Array(
859        'RB_PIT' => "pit.id AS imageId, pit.name AS imageName, pit.path AS imagePath", // from the piwigo's image table
860        'RB_PIC' => "GROUP_CONCAT( pic.category_id SEPARATOR ',') AS imageCategoriesId",     // from the piwigo's image_category table
861        'RB_PCT' => "GROUP_CONCAT( CASE WHEN pct.name IS NULL THEN '' ELSE pct.name END SEPARATOR '#sep#') AS imageCategoriesNames,
862                     GROUP_CONCAT( CASE WHEN pct.permalink IS NULL THEN '' ELSE pct.permalink END SEPARATOR '#sep#') AS imageCategoriesPLink,
863                     GROUP_CONCAT( CASE WHEN pct.dir IS NULL THEN 'V' ELSE 'P' END) AS imageCategoriesDir",   //from the piwigo's categories table
864      ),
865      'FROM' => Array(
866        // join rb result_cache table with piwigo's images table, joined with the piwigo's image_category table, joined with the categories table
867        'RB' => "(((".self::$tables['result_cache']." pgrc
868                  RIGHT JOIN ".IMAGES_TABLE." pit
869                  ON pgrc.image_id = pit.id)
870                    RIGHT JOIN ".IMAGE_CATEGORY_TABLE." pic
871                    ON pit.id = pic.image_id)
872                       RIGHT JOIN ".CATEGORIES_TABLE." pct
873                       ON pct.id = pic.category_id)
874                          RIGHT JOIN ".USER_CACHE_CATEGORIES_TABLE." pucc
875                          ON pucc.cat_id = pic.category_id",
876      ),
877      'WHERE' => Array(
878        'RB' => "pgrc.id=".$requestNumber." AND pucc.user_id=".$user['id'],
879        ),
880      'JOIN' => Array(),
881      'GROUPBY' => Array(
882        'RB' => "pit.id"
883      )
884    );
885
886
887    $extraData=array();
888    foreach($request['parameters'] as $data)
889    {
890      $extraData[$data['owner']]=$data['param'];
891    }
892
893    /* for each needed plugin :
894     *  - include the file
895     *  - call the static public function getFrom, getJoin, getSelect
896     */
897    foreach($pluginNeeded as $key => $val)
898    {
899      if(array_key_exists($val, $registeredPlugin))
900      {
901        if(file_exists($registeredPlugin[$val]['fileName']))
902        {
903          include_once($registeredPlugin[$val]['fileName']);
904
905          $tmp=explode(',', call_user_func(Array('RBCallBack'.$val, 'getSelect'), $extraData[$val]));
906          foreach($tmp as $key2=>$val2)
907          {
908            $tmp[$key2]=self::groupConcatAlias($val2, '#sep#');
909          }
910          $tmpBuild['SELECT'][$val]=implode(',', $tmp);
911          $tmpBuild['FROM'][$val]=call_user_func(Array('RBCallBack'.$val, 'getFrom'), $extraData[$val]);
912          $tmpBuild['JOIN'][$val]=call_user_func(Array('RBCallBack'.$val, 'getJoin'), $extraData[$val]);
913        }
914      }
915    }
916
917    /* build SELECT
918     *
919     */
920    $build['SELECT']=implode(',', $tmpBuild['SELECT']);
921
922    /* build FROM
923     *
924     */
925    $build['FROM']=implode(',', $tmpBuild['FROM']);
926    unset($tmpBuild['FROM']);
927
928
929    /* build WHERE
930     */
931    if($request['filter']!='') $tmpBuild['WHERE'][]=$request['filter'];
932    $build['WHERE']=implode(' AND ', $tmpBuild['WHERE']);
933    unset($tmpBuild['WHERE']);
934
935    /* for each plugin, adds jointure with the IMAGE table
936     */
937    self::cleanArray($tmpBuild['JOIN']);
938    if(count($tmpBuild['JOIN'])>0)
939    {
940      $build['WHERE'].=' AND ('.implode(' AND ', $tmpBuild['JOIN']).') ';
941    }
942    unset($tmpBuild['JOIN']);
943
944    self::cleanArray($tmpBuild['GROUPBY']);
945    if(count($tmpBuild['GROUPBY'])>0)
946    {
947      $build['GROUPBY'].=' '.implode(', ', $tmpBuild['GROUPBY']).' ';
948    }
949    unset($tmpBuild['GROUPBY']);
950
951
952    $imagesList=Array();
953
954    $sql='SELECT DISTINCT '.$build['SELECT']
955        .' FROM '.$build['FROM']
956        .' WHERE '.$build['WHERE']
957        .' GROUP BY '.$build['GROUPBY'];
958
959    $sql.=' ORDER BY pit.id '
960         .' LIMIT '.$limitFrom.', '.$numPerPage;
961
962//echo $sql;
963    $result=pwg_query($sql);
964    if($result)
965    {
966      while($row=pwg_db_fetch_assoc($result))
967      {
968        // affect standard datas
969        $datas['imageThumbnail']=DerivativeImage::thumb_url(array('id'=>$row['imageId'], 'path'=>$row['imagePath']));
970        $datas['imageId']=$row['imageId'];
971        $datas['imagePath']=$row['imagePath'];
972        $datas['imageName']=$row['imageName'];
973
974        $datas['imageCategoriesId']=explode(',', $row['imageCategoriesId']);
975        $datas['imageCategoriesNames']=explode('#sep#', $row['imageCategoriesNames']);
976        $datas['imageCategoriesPLink']=explode('#sep#', $row['imageCategoriesPLink']);
977        $datas['imageCategoriesDir']=explode(',', $row['imageCategoriesDir']);
978
979        $datas['imageCategories']=Array();
980        for($i=0;$i<count($datas['imageCategoriesId']);$i++)
981        {
982          $datas['imageCategories'][]=array(
983            'id' => $datas['imageCategoriesId'][$i],
984            'name' => $datas['imageCategoriesNames'][$i],
985            'dirType' => $datas['imageCategoriesDir'][$i],
986            'pLinks' => $datas['imageCategoriesPLink'][$i],
987            'link'=> make_picture_url(
988                        array(
989                          'image_id' => $datas['imageId'],
990                          'category' => array
991                            (
992                              'id' => $datas['imageCategoriesId'][$i],
993                              'name' => $datas['imageCategoriesNames'][$i],
994                              'permalink' => $datas['imageCategoriesPLink'][$i]
995                            )
996                        )
997                      )
998          );
999        }
1000
1001        /* affect datas for each plugin
1002         *
1003         * each plugin have to format the data in an HTML code
1004         *
1005         * so, for each plugin :
1006         *  - look the attributes given in the SELECT clause
1007         *  - for each attributes, associate the returned value of the record
1008         *  - affect in datas an index equals to the plugin pluginName, with returned HTML code ; HTML code is get from a formatData function
1009         *
1010         * Example :
1011         *  plugin ColorStart provide 2 attributes 'csColors' and 'csColorsPct'
1012         *
1013         *  we affect to the $attributes var :
1014         *  $attributes['csColors'] = $row['csColors'];
1015         *  $attributes['csColorsPct'] = $row['csColorsPct'];
1016         *
1017         *  call the ColorStat RB callback formatData with the $attributes => the function return a HTML code ready to use in the template
1018         *
1019         *  affect $datas['ColorStat'] = $the_returned_html_code;
1020         *
1021         *
1022         */
1023        foreach($tmpBuild['SELECT'] as $key => $val)
1024        {
1025          if($key!='RB_PIT' && $key!='RB_PIC' && $key!='RB_PCT')
1026          {
1027            $tmp=explode(',', $val);
1028
1029            $attributes=Array();
1030
1031            foreach($tmp as $key2 => $val2)
1032            {
1033              $name=self::getAttribute($val2);
1034              $attributes[$name]=$row[$name];
1035            }
1036
1037            $datas['plugin'][$key]=call_user_func(Array('RBCallBack'.$key, 'formatData'), $attributes);
1038
1039            unset($tmp);
1040            unset($attributes);
1041          }
1042        }
1043        $imagesList[]=$datas;
1044        unset($datas);
1045      }
1046    }
1047
1048    return(self::toHtml($imagesList));
1049    //return("get page : $requestNumber, $pageNumber, $numPerPage<br>$debug<br>$sql");
1050  }
1051
1052  /**
1053   * remove all empty value from an array
1054   * @param Array a$array : the array to clean
1055   */
1056  static private function cleanArray(&$array)
1057  {
1058    foreach($array as $key => $val)
1059    {
1060      if(is_array($val))
1061      {
1062        self::cleanArray($val);
1063        if(count($val)==0) unset($array[$key]);
1064      }
1065      elseif(trim($val)=='') unset($array[$key]);
1066    }
1067  }
1068
1069  /**
1070   * returns the alias for an attribute
1071   *
1072   *  item1                          => returns item1
1073   *  table1.item1                   => returns item1
1074   *  table1.item1 AS alias1         => returns alias1
1075   *  item1 AS alias1                => returns alias1
1076   *  GROUP_CONCAT( .... ) AS alias1 => returns alias1
1077   *
1078   * @param String $var : value to examine
1079   * @return String : the attribute name
1080   */
1081  static private function getAttribute($val)
1082  {
1083    preg_match('/(?:GROUP_CONCAT\(.*\)|(?:[A-Z0-9_]*)\.)?([A-Z0-9_]*)(?:\s+AS\s+([A-Z0-9_]*))?/i', trim($val), $result);
1084    if(array_key_exists(2, $result))
1085    {
1086      return($result[2]);
1087    }
1088    elseif(array_key_exists(1, $result))
1089    {
1090      return($result[1]);
1091    }
1092    else
1093    {
1094      return($val);
1095    }
1096  }
1097
1098
1099  /**
1100   * returns a a sql statement GROUP_CONCAT for an alias
1101   *
1102   *  item1                  => returns GROUP_CONCAT(item1 SEPARATOR $sep) AS item1
1103   *  table1.item1           => returns GROUP_CONCAT(table1.item1 SEPARATOR $sep) AS item1
1104   *  table1.item1 AS alias1 => returns GROUP_CONCAT(table1.item1 SEPARATOR $sep) AS alias1
1105   *  item1 AS alias1        => returns GROUP_CONCAT(item1 SEPARATOR $sep) AS alias1
1106   *
1107   * @param String $val : value to examine
1108   * @param String $sep : the separator
1109   * @return String : the attribute name
1110   */
1111  static private function groupConcatAlias($val, $sep=',')
1112  {
1113    /*
1114     * table1.item1 AS alias1
1115     *
1116     * $result[3] = alias1
1117     * $result[2] = item1
1118     * $result[1] = table1.item1
1119     */
1120    preg_match('/((?:(?:[A-Z0-9_]*)\.)?([A-Z0-9_]*))(?:\s+AS\s+([A-Z0-9_]*))?/i', trim($val), $result);
1121    if(array_key_exists(3, $result))
1122    {
1123      return("GROUP_CONCAT(DISTINCT ".$result[1]." SEPARATOR '$sep') AS ".$result[3]);
1124    }
1125    elseif(array_key_exists(2, $result))
1126    {
1127      return("GROUP_CONCAT(DISTINCT ".$result[1]." SEPARATOR '$sep') AS ".$result[2]);
1128    }
1129    else
1130    {
1131      return("GROUP_CONCAT(DISTINCT $val SEPARATOR '$sep') AS ".$val);
1132    }
1133  }
1134
1135
1136  /**
1137   * get a new request number and create it in the request table
1138   *
1139   * @param Integer $userId : id of the user
1140   * @return Integer : the new request number, -1 if something wrong appened
1141   */
1142  static private function getNewRequest($userId)
1143  {
1144    $sql="INSERT INTO ".self::$tables['request']." VALUES('', '$userId', '".date('Y-m-d H:i:s')."', 0, 0, '', '', '')";
1145    $result=pwg_query($sql);
1146    if($result)
1147    {
1148      return(pwg_db_insert_id());
1149    }
1150    return(-1);
1151  }
1152
1153  /**
1154   * update request properties
1155   *
1156   * @param Integer $request_id : the id of request to update
1157   * @param Integer $numItems : number of items found in the request
1158   * @param Float $executionTime : time in second to execute the request
1159   * @param String $pluginList : list of used plugins
1160   * @param String $parameters : parameters given for the request
1161   * @return Boolean : true if request was updated, otherwise false
1162   */
1163  static private function updateRequest($requestId, $numItems, $executionTime, $pluginList, $additionalFilter, $parameters)
1164  {
1165    $sql="UPDATE ".self::$tables['request']."
1166            SET num_items = $numItems,
1167                execution_time = $executionTime,
1168                connected_plugin = '$pluginList',
1169                filter = '".mysql_escape_string($additionalFilter)."',
1170                parameters = '".serialize($parameters)."'
1171            WHERE id = $requestId";
1172    $result=pwg_query($sql);
1173    if($result)
1174    {
1175      return(true);
1176    }
1177    return(false);
1178  }
1179
1180  /**
1181   * returns request properties
1182   *
1183   * @param Integer $request_id : the id of request to update
1184   * @return Array : properties for request, false if request doesn't exist
1185   */
1186  static private function getRequest($requestId)
1187  {
1188    $returned=false;
1189    $sql="SELECT user_id, date, num_items, execution_time, connected_plugin, filter, parameters
1190          FROM ".self::$tables['request']."
1191          WHERE id = $requestId";
1192    $result=pwg_query($sql);
1193    if($result)
1194    {
1195      while($row=pwg_db_fetch_assoc($result))
1196      {
1197        if($row['parameters']!='') $row['parameters']=unserialize($row['parameters']);
1198        $returned=$row;
1199      }
1200    }
1201    return($returned);
1202  }
1203
1204
1205  /**
1206   * internal function used by the executeRequest function for single record
1207   * requests
1208   *
1209   * this function is called recursively
1210   *
1211   * @param Array $groupContent :
1212   * @param Array $items :
1213   * @return String : a where clause
1214   */
1215  static private function buildGroup($groupContent, $items, $groups, $operator)
1216  {
1217    $returned=Array();
1218    foreach($groupContent as $key => $val)
1219    {
1220      if(strpos($val['id'], 'iCbGroup')!==false)
1221      {
1222        preg_match('/[0-9]*$/i', $val['id'], $groupNumber);
1223        $returned[]=self::buildGroup($val['children'], $items, $groups, $groups[$groupNumber[0]]);
1224      }
1225      else
1226      {
1227        preg_match('/[0-9]*$/i', $val['id'], $itemNumber);
1228        $returned[]=" (".$items[$itemNumber[0]].") ";
1229      }
1230    }
1231    return('('.implode($operator, $returned).')');
1232  }
1233
1234
1235  /**
1236   * internal function used by the executeRequest function for multi records
1237   * requests
1238   *
1239   * this function is called recursively
1240   *
1241   * @param Array $groupContent :
1242   * @param Array $clausesItems : array with 'where' and 'having' conditions (and 'plugin' for the plugin)
1243   * @param Array $groups : operators of each group
1244   * @param String $operator : 'OR' or 'AND', according with the current group operator
1245   * @param String $requestNumber : the request number
1246   * @return String : part of a SQL request
1247   */
1248  static private function buildGroupRequest($groupContent, $clausesItems, $groups, $operator, $requestNumber)
1249  {
1250    $returnedS='';
1251    $returned=Array();
1252    foreach($groupContent as $key => $val)
1253    {
1254      if(strpos($val['id'], 'iCbGroup')!==false)
1255      {
1256        preg_match('/[0-9]*$/i', $val['id'], $groupNumber);
1257
1258        $groupValue=self::buildGroupRequest($val['children'], $clausesItems, $groups, $groups[$groupNumber[0]], $requestNumber);
1259
1260        if($groupValue!='')
1261          $returned[]=array(
1262            'mode'  => 'group',
1263            'value' => $groupValue
1264          );
1265      }
1266      else
1267      {
1268        preg_match('/[0-9]*$/i', $val['id'], $itemNumber);
1269
1270        $returned[]=array(
1271          'mode'  => 'item',
1272          'plugin' => $clausesItems[$itemNumber[0]]['plugin'],
1273          'valueWhere' => ($clausesItems[$itemNumber[0]]['where']!='')?" (".$clausesItems[$itemNumber[0]]['where'].") ":'',
1274          'valueHaving' => ($clausesItems[$itemNumber[0]]['having'])?" (".$clausesItems[$itemNumber[0]]['having'].") ":'',
1275        );
1276      }
1277    }
1278
1279    if(count($returned)>0)
1280    {
1281      if(strtolower(trim($operator))=='and')
1282      {
1283        $tId=0;
1284        foreach($returned as $key=>$val)
1285        {
1286          if($tId>0) $returnedS.=" JOIN ";
1287
1288          if($val['mode']=='item')
1289          {
1290            $returnedS.="(SELECT DISTINCT ".call_user_func(Array('RBCallBack'.$val['plugin'], 'getImageId'))." AS imageId
1291                          FROM ".call_user_func(Array('RBCallBack'.$val['plugin'], 'getFrom'));
1292            if($val['valueWhere']!='') $returnedS.=" WHERE ".$val['valueWhere'];
1293            if($val['valueHaving']!='')
1294              $returnedS.=" GROUP BY imageId
1295                            HAVING ".$val['valueHaving'];
1296            $returnedS.=") t".self::$tGlobalId." ";
1297          }
1298          else
1299          {
1300            $returnedS.="(".$val['value'].") t".self::$tGlobalId." ";
1301          }
1302
1303          if($tId>0) $returnedS.=" ON t".(self::$tGlobalId-1).".imageId = t".self::$tGlobalId.".imageId ";
1304          $tId++;
1305          self::$tGlobalId++;
1306        }
1307        $returnedS="SELECT DISTINCT '$requestNumber', t".(self::$tGlobalId-$tId).".imageId FROM ".$returnedS;
1308      }
1309      else
1310      {
1311        foreach($returned as $key=>$val)
1312        {
1313          if($returnedS!='') $returnedS.=" UNION DISTINCT ";
1314
1315          if($val['mode']=='item')
1316          {
1317            $returnedS.="SELECT DISTINCT '$requestNumber', t".self::$tGlobalId.".imageId
1318                          FROM (SELECT ".call_user_func(Array('RBCallBack'.$val['plugin'], 'getImageId'))." AS imageId
1319                                FROM ".call_user_func(Array('RBCallBack'.$val['plugin'], 'getFrom'));
1320            if($val['valueWhere']!='') $returnedS.=" WHERE ".$val['valueWhere'];
1321            if($val['valueHaving']!='')
1322              $returnedS.=" GROUP BY imageId
1323                            HAVING ".$val['valueHaving'];
1324            $returnedS.=") t".self::$tGlobalId." ";
1325          }
1326          else
1327          {
1328            $returnedS.="SELECT DISTINCT '$requestNumber', t".self::$tGlobalId.".imageId FROM (".$val['value'].") t".self::$tGlobalId;
1329          }
1330
1331          self::$tGlobalId++;
1332        }
1333      }
1334    }
1335
1336    return($returnedS);
1337  }
1338
1339
1340  /**
1341   * convert a list of images to HTML
1342   *
1343   * @param Array $imagesList : list of images id & associated datas
1344   * @return String : list formatted into HTML code
1345   */
1346  static protected function toHtml($imagesList)
1347  {
1348    global $template;
1349
1350    $template->set_filename('result_items',
1351                dirname(dirname(__FILE__)).'/templates/GPCRequestBuilder_result.tpl');
1352
1353
1354
1355    $template->assign('datas', $imagesList);
1356
1357    return($template->parse('result_items', true));
1358  }
1359
1360
1361  /**
1362   * returns allowed (or not allowed) categories for a user
1363   *
1364   * used the USER_CACHE_TABLE if possible
1365   *
1366   * @param Integer $userId : a valid user Id
1367   * @return String : IN(...), NOT IN(...) or nothing if there is no restriction
1368   *                  for the user
1369   */
1370  public function getUserCategories($userId)
1371  {
1372/*
1373    $returned='';
1374    if($user['forbidden_categories']!='')
1375    {
1376      $returned=Array(
1377        'JOIN' => 'AND ('.IMAGE_CATEGORY.'.category_id NOT IN ('.$user['forbidden_categories'].') ) ',
1378        'FROM' => IMAGE_CATEGORY
1379      );
1380
1381
1382    }
1383    *
1384    *
1385    */
1386  }
1387
1388
1389  /**
1390   * display search page
1391   *
1392   * @param Array $filter : an array of string ; each item is the name of a
1393   *                        registered plugin
1394   *                        if no parameters are given, no filter is applied
1395   *                        otherwise only plugin wich name is given are
1396   *                        accessible
1397   */
1398  static public function displaySearchPage($filter=array())
1399  {
1400    global $template, $lang;
1401
1402    if(is_string($filter)) $filter=array($filter);
1403    $filter=array_flip($filter);
1404
1405    GPCCore::addHeaderJS('jquery.ui', 'themes/default/js/ui/jquery.ui.core.js', array('jquery'));
1406    GPCCore::addHeaderJS('jquery.ui.widget', 'themes/default/js/ui/jquery.ui.widget.js', array('jquery.ui'));
1407    GPCCore::addHeaderJS('jquery.ui.mouse', 'themes/default/js/ui/jquery.ui.mouse.js', array('jquery.ui.widget'));
1408    GPCCore::addHeaderJS('jquery.ui.position', 'themes/default/js/ui/jquery.ui.position.js', array('jquery.ui.widget'));
1409    GPCCore::addHeaderJS('jquery.ui.draggable', 'themes/default/js/ui/jquery.ui.draggable.js', array('jquery.ui.widget'));
1410    GPCCore::addHeaderJS('jquery.ui.dialog', 'themes/default/js/ui/jquery.ui.dialog.js', array('jquery.ui.widget'));
1411    GPCCore::addHeaderJS('jquery.ui.slider', 'themes/default/js/ui/jquery.ui.slider.js', array('jquery.ui.widget'));
1412    GPCCore::addHeaderJS('gpc.pagesNavigator', 'plugins/GrumPluginClasses/js/pagesNavigator.js');
1413    GPCCore::addHeaderJS('gpc.rbSearch', 'plugins/GrumPluginClasses/js/rbSearch.js');
1414
1415    $template->set_filename('gpc_search_page',
1416                dirname(dirname(__FILE__)).'/templates/GPCRequestBuilder_search.tpl');
1417
1418    $registeredPlugin=self::getRegistered();
1419    $dialogBox=Array();
1420    foreach($registeredPlugin as $key=>$val)
1421    {
1422      if(array_key_exists($key, $registeredPlugin) and
1423         (count($filter)==0 or array_key_exists($key, $filter)))
1424      {
1425        if(file_exists($registeredPlugin[$key]['fileName']))
1426        {
1427          include_once($registeredPlugin[$key]['fileName']);
1428
1429          $dialogBox[]=Array(
1430            'handle' => $val['name'].'DB',
1431            'dialogBoxClass' => call_user_func(Array('RBCallBack'.$key, 'getInterfaceDBClass')),
1432            'label' => call_user_func(Array('RBCallBack'.$key, 'getInterfaceLabel')),
1433            'content' => call_user_func(Array('RBCallBack'.$key, 'getInterfaceContent')),
1434          );
1435        }
1436      }
1437    }
1438
1439    $datas=Array(
1440      'dialogBox' => $dialogBox,
1441      'themeName' => defined('IN_ADMIN')?$template->get_themeconf('name'):'',
1442    );
1443
1444    $template->assign('datas', $datas);
1445
1446    return($template->parse('gpc_search_page', true));
1447  } //displaySearchPage
1448
1449}
1450
1451
1452?>
Note: See TracBrowser for help on using the repository browser.