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

Revision 15352, 45.0 KB checked in by grum, 8 years ago (diff)

feature:2634 - Compatibility with Piwigo 2.4
fix some RBuilder css

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    GPCCore::addHeaderCSS('gpc.rbuilder', 'plugins/'.$baseName.'rbuilder.css', 25);
539
540    //$template->append('head_elements', '<link href="plugins/'.$baseName.'rbuilder.css" type="text/css" rel="stylesheet"/>');
541    if(defined('IN_ADMIN')) GPCCore::addHeaderCSS('gpc.rbuilder', 'plugins/'.$baseName.'rbuilder_'.$template->get_themeconf('name').'.css', 26);
542    //$template->append('head_elements', '<link href="plugins/'.$baseName.'rbuilder_'.$template->get_themeconf('name').'.css" type="text/css" rel="stylesheet"/>');
543
544
545    $baseName=basename(dirname(dirname(__FILE__))).'/js/';
546    GPCCore::addHeaderJS('jquery', 'themes/default/js/jquery.js');
547    GPCCore::addHeaderJS('jquery.ui', 'themes/default/js/ui/jquery.ui.core.js', array('jquery'));
548    GPCCore::addHeaderJS('jquery.ui.widget', 'themes/default/js/ui/jquery.ui.widget.js', array('jquery.ui'));
549    GPCCore::addHeaderJS('jquery.ui.mouse', 'themes/default/js/ui/jquery.ui.mouse.js', array('jquery.ui.widget'));
550    GPCCore::addHeaderJS('jquery.ui.position', 'themes/default/js/ui/jquery.ui.position.js', array('jquery.ui.widget'));
551    GPCCore::addHeaderJS('jquery.ui.draggable', 'themes/default/js/ui/jquery.ui.draggable.js', array('jquery.ui.widget'));
552    GPCCore::addHeaderJS('jquery.ui.dialog', 'themes/default/js/ui/jquery.ui.dialog.js', array('jquery.ui.widget'));
553    GPCCore::addHeaderJS('jquery.ui.slider', 'themes/default/js/ui/jquery.ui.slider.js', array('jquery.ui.widget'));
554
555    GPCCore::addHeaderJS('gpc.external.inestedsortable', 'plugins/'.$baseName.'external/iNestedSortablePack.js', array('jquery', 'jquery.ui'));
556    GPCCore::addHeaderJS('gpc.rbCriteriaBuilder', 'plugins/'.$baseName.'rbCriteriaBuilder.js', array('gpc.external.inestedsortable'));
557
558    $template->append('head_elements',
559"<script type=\"text/javascript\">
560  requestBuilderOptions = {
561    textAND:\"".l10n('gpc_rb_textAND')."\",
562    textOR:\"".l10n('gpc_rb_textOR')."\",
563    textNoCriteria:\"".l10n('There is no criteria ! At least, one criteria is required to do search...')."\",
564    textSomethingWrong:\"".l10n('gpc_something_is_wrong_on_the_server_side')."\",
565    textCaddieUpdated:\"".l10n('gpc_the_caddie_is_updated')."\",
566    helpEdit:\"".l10n('gpc_help_edit_criteria')."\",
567    helpDelete:\"".l10n('gpc_help_delete_criteria')."\",
568    helpMove:\"".l10n('gpc_help_move_criteria')."\",
569    helpSwitchCondition:\"".l10n('gpc_help_switch_condition')."\",
570    ajaxUrl:'plugins/GrumPluginClasses/gpc_ajax.php',
571  }
572</script>");
573  }
574
575
576  /**
577   * execute request from the ajax call
578   *
579   * @return String : a ready to use HTML code
580   */
581  static public function executeRequest($ajaxfct)
582  {
583    $result='';
584    switch($ajaxfct)
585    {
586      case 'public.rbuilder.searchExecute':
587        $result=self::doCache();
588        break;
589      case 'public.rbuilder.searchGetPage':
590        $result=self::getPage($_REQUEST['requestNumber'], $_REQUEST['page'], $_REQUEST['numPerPage']);
591        break;
592    }
593    return($result);
594  }
595
596
597  /**
598   * clear the cache table
599   *
600   * @param Boolean $clearAll : if set to true, clear all records without
601   *                            checking timestamp
602   */
603  static public function clearCache($clearAll=false)
604  {
605    if($clearAll)
606    {
607      $sql="DELETE FROM ".self::$tables['result_cache'];
608    }
609    else
610    {
611      $sql="DELETE pgrc FROM ".self::$tables['result_cache']." pgrc
612              LEFT JOIN ".self::$tables['request']." pgr
613                ON pgrc.id = pgr.id
614              WHERE pgr.date < '".date('Y-m-d H:i:s', strtotime("-2 hour"))."'";
615    }
616    pwg_query($sql);
617  }
618
619  /**
620   * prepare the temporary table used for multirecord requests
621   *
622   * @param Integer $requestNumber : id of request
623   * @return String : name of the request key temporary table
624   */
625  static private function prepareTempTable($requestNumber)
626  {
627    //$tableName=call_user_func(Array('RBCallBack'.$plugin, 'getFrom'));
628    //$imageIdName=call_user_func(Array('RBCallBack'.$plugin, 'getImageId'));
629
630    $tempClauses=array();
631    foreach($_REQUEST['extraData'] as $key => $extraData)
632    {
633      $tempClauses[$key]=array(
634        'plugin' => $extraData['owner'],
635        'where' => call_user_func(Array('RBCallBack'.$extraData['owner'], 'getWhere'), $extraData['param']),
636        'having' => call_user_func(Array('RBCallBack'.$extraData['owner'], 'getHaving'), $extraData['param']),
637      );
638    }
639
640    $sql="INSERT INTO ".self::$tables['temp']." ".self::buildGroupRequest($_REQUEST[$_REQUEST['requestName']], $tempClauses, $_REQUEST['operator'], ' AND ', $requestNumber);
641//echo $sql;
642    $result=pwg_query($sql);
643
644    return($requestNumber);
645  }
646
647  /**
648   * clear the temporary table used for multirecord requests
649   *
650   * @param Array $requestNumber : the requestNumber to delete
651   */
652  static private function clearTempTable($requestNumber)
653  {
654    $sql="DELETE FROM ".self::$tables['temp']." WHERE requestId = '$requestNumber';";
655    pwg_query($sql);
656  }
657
658
659  /**
660   * execute a query, and place result in cache
661   *
662   *
663   * @return String : queryNumber;numberOfItems
664   */
665  static private function doCache()
666  {
667    global $user;
668
669    self::clearCache();
670
671    $registeredPlugin=self::getRegistered();
672    $requestNumber=self::getNewRequest($user['id']);
673
674    $build=Array(
675      'SELECT' => 'pit.id',
676      'FROM' => '',
677      'WHERE' => 'pit.level <= '.$user['level'],
678      'GROUPBY' => '',
679      'FILTER' => ''
680    );
681    $tmpBuild=Array(
682      'FROM' => Array(
683        '('.IMAGES_TABLE.' pit LEFT JOIN '.IMAGE_CATEGORY_TABLE.' pic ON pit.id = pic.image_id)' /*JOIN IMAGES & IMAGE_CATEGORY tables*/
684       .'   JOIN '.USER_CACHE_CATEGORIES_TABLE.' pucc ON pucc.cat_id=pic.category_id',  /* IMAGE_CATEGORY & USER_CACHE_CATEGORIES_TABLE tables*/
685
686      ),
687      'WHERE' => Array(),
688      'JOIN' => Array(999=>'pucc.user_id='.$user['id']),
689      'GROUPBY' => Array(
690        'pit.id'
691      ),
692      'FILTER' => Array(),
693    );
694
695    /* build data request for plugins
696     *
697     * Array('Plugin1' =>
698     *          Array(
699     *            criteriaNumber1 => pluginParam1,
700     *            criteriaNumber2 => pluginParam2,
701     *            criteriaNumberN => pluginParamN
702     *          ),
703     *       'Plugin2' =>
704     *          Array(
705     *            criteriaNumber1 => pluginParam1,
706     *            criteriaNumber2 => pluginParam2,
707     *            criteriaNumberN => pluginParamN
708     *          )
709     * )
710     *
711     */
712    $pluginNeeded=Array();
713    $pluginList=Array();
714    $tempName=Array();
715    foreach($_REQUEST['extraData'] as $key => $val)
716    {
717      $pluginNeeded[$val['owner']][$key]=$_REQUEST['extraData'][$key]['param'];
718      $pluginList[$val['owner']]=$val['owner'];
719    }
720
721    /* for each plugin, include the rb callback class file */
722    foreach($pluginList as $val)
723    {
724      if(file_exists($registeredPlugin[$val]['fileName']))
725      {
726        include_once($registeredPlugin[$val]['fileName']);
727      }
728    }
729
730    /* prepare the temp table for the request */
731    self::prepareTempTable($requestNumber);
732    $tmpBuild['FROM'][]=self::$tables['temp'];
733    $tmpBuild['JOIN'][]=self::$tables['temp'].".requestId = '".$requestNumber."'
734                        AND ".self::$tables['temp'].".imageId = pit.id";
735
736    /* for each needed plugin, prepare the filter */
737    foreach($pluginNeeded as $key => $val)
738    {
739      foreach($val as $itemNumber => $param)
740      {
741        $tmpFilter=call_user_func(Array('RBCallBack'.$key, 'getFilter'), $param);
742
743        if(trim($tmpFilter)!="") $tmpBuild['FILTER'][$key][]='('.$tmpFilter.')';
744      }
745    }
746
747
748    /* build FROM
749     *
750     */
751    $build['FROM']=implode(',', $tmpBuild['FROM']);
752    unset($tmpBuild['FROM']);
753
754    /* build WHERE
755     */
756    self::cleanArray($tmpBuild['WHERE']);
757    if(count($tmpBuild['WHERE'])>0)
758    {
759      $build['WHERE']=' ('.self::buildGroup($_REQUEST[$_REQUEST['requestName']], $tmpBuild['WHERE'], $_REQUEST['operator'], ' AND ').') ';
760    }
761    unset($tmpBuild['WHERE']);
762
763
764    /* build FILTER
765     */
766    self::cleanArray($tmpBuild['FILTER']);
767    if(count($tmpBuild['FILTER'])>0)
768    {
769      $tmp=array();
770      foreach($tmpBuild['FILTER'] as $key=>$val)
771      {
772        $tmp[$key]='('.implode(' OR ', $val).')';
773      }
774      $build['FILTER']=' ('.implode(' AND ', $tmp).') ';
775    }
776    unset($tmpBuild['FILTER']);
777
778
779    /* for each plugin, adds jointure with the IMAGE table
780     */
781    self::cleanArray($tmpBuild['JOIN']);
782    if(count($tmpBuild['JOIN'])>0)
783    {
784      if($build['WHERE']!='') $build['WHERE'].=' AND ';
785      $build['WHERE'].=' ('.implode(' AND ', $tmpBuild['JOIN']).') ';
786    }
787    unset($tmpBuild['JOIN']);
788
789    self::cleanArray($tmpBuild['GROUPBY']);
790    if(count($tmpBuild['GROUPBY'])>0)
791    {
792      $build['GROUPBY'].=' '.implode(', ', $tmpBuild['GROUPBY']).' ';
793    }
794    unset($tmpBuild['GROUPBY']);
795
796
797
798    $sql=' FROM '.$build['FROM'];
799    if($build['WHERE']!='')
800    {
801      $sql.=' WHERE '.$build['WHERE'];
802    }
803    if($build['GROUPBY']!='')
804    {
805      $sql.=' GROUP BY '.$build['GROUPBY'];
806    }
807
808    $sql.=" ORDER BY pit.id ";
809
810    $sql="INSERT INTO ".self::$tables['result_cache']." (SELECT DISTINCT $requestNumber, ".$build['SELECT']." $sql)";
811
812//echo $sql;
813    $returned="0;0";
814
815    $result=pwg_query($sql);
816    if($result)
817    {
818      $numberItems=pwg_db_changes($result);
819      self::updateRequest($requestNumber, $numberItems, 0, implode(',', $pluginList), $build['FILTER'], $_REQUEST['extraData']);
820
821      $returned="$requestNumber;".$numberItems;
822    }
823
824    self::clearTempTable($requestNumber);
825
826    return($returned);
827  }
828
829  /**
830   * return a page content. use the cache table to find request result
831   *
832   * @param Integer $requestNumber : the request number (from cache table)
833   * @param Integer $pageNumber : the page to be returned
834   * @param Integer $numPerPage : the number of items returned on a page
835   * @param String $mode : if mode = 'count', the function returns the number of
836   *                       rows ; otherwise, returns rows in a html string
837   * @return String : formatted HTML code
838   */
839  static private function getPage($requestNumber, $pageNumber, $numPerPage)
840  {
841    global $conf, $user;
842    $request=self::getRequest($requestNumber);
843
844    if($request===false)
845    {
846      return("KO");
847    }
848
849    $limitFrom=$numPerPage*($pageNumber-1);
850
851    $pluginNeeded=explode(',', $request['connected_plugin']);
852    $registeredPlugin=self::getRegistered();
853
854    $build=Array(
855      'SELECT' => '',
856      'FROM' => '',
857      'WHERE' => '',
858      'GROUPBY' => '',
859    );
860    $tmpBuild=Array(
861      'SELECT' => Array(
862        'RB_PIT' => "pit.id AS imageId, pit.name AS imageName, pit.path AS imagePath", // from the piwigo's image table
863        'RB_PIC' => "GROUP_CONCAT( pic.category_id SEPARATOR ',') AS imageCategoriesId",     // from the piwigo's image_category table
864        'RB_PCT' => "GROUP_CONCAT( CASE WHEN pct.name IS NULL THEN '' ELSE pct.name END SEPARATOR '#sep#') AS imageCategoriesNames,
865                     GROUP_CONCAT( CASE WHEN pct.permalink IS NULL THEN '' ELSE pct.permalink END SEPARATOR '#sep#') AS imageCategoriesPLink,
866                     GROUP_CONCAT( CASE WHEN pct.dir IS NULL THEN 'V' ELSE 'P' END) AS imageCategoriesDir",   //from the piwigo's categories table
867      ),
868      'FROM' => Array(
869        // join rb result_cache table with piwigo's images table, joined with the piwigo's image_category table, joined with the categories table
870        'RB' => "(((".self::$tables['result_cache']." pgrc
871                  RIGHT JOIN ".IMAGES_TABLE." pit
872                  ON pgrc.image_id = pit.id)
873                    RIGHT JOIN ".IMAGE_CATEGORY_TABLE." pic
874                    ON pit.id = pic.image_id)
875                       RIGHT JOIN ".CATEGORIES_TABLE." pct
876                       ON pct.id = pic.category_id)
877                          RIGHT JOIN ".USER_CACHE_CATEGORIES_TABLE." pucc
878                          ON pucc.cat_id = pic.category_id",
879      ),
880      'WHERE' => Array(
881        'RB' => "pgrc.id=".$requestNumber." AND pucc.user_id=".$user['id'],
882        ),
883      'JOIN' => Array(),
884      'GROUPBY' => Array(
885        'RB' => "pit.id"
886      )
887    );
888
889
890    $extraData=array();
891    foreach($request['parameters'] as $data)
892    {
893      $extraData[$data['owner']]=$data['param'];
894    }
895
896    /* for each needed plugin :
897     *  - include the file
898     *  - call the static public function getFrom, getJoin, getSelect
899     */
900    foreach($pluginNeeded as $key => $val)
901    {
902      if(array_key_exists($val, $registeredPlugin))
903      {
904        if(file_exists($registeredPlugin[$val]['fileName']))
905        {
906          include_once($registeredPlugin[$val]['fileName']);
907
908          $tmp=explode(',', call_user_func(Array('RBCallBack'.$val, 'getSelect'), $extraData[$val]));
909          foreach($tmp as $key2=>$val2)
910          {
911            $tmp[$key2]=self::groupConcatAlias($val2, '#sep#');
912          }
913          $tmpBuild['SELECT'][$val]=implode(',', $tmp);
914          $tmpBuild['FROM'][$val]=call_user_func(Array('RBCallBack'.$val, 'getFrom'), $extraData[$val]);
915          $tmpBuild['JOIN'][$val]=call_user_func(Array('RBCallBack'.$val, 'getJoin'), $extraData[$val]);
916        }
917      }
918    }
919
920    /* build SELECT
921     *
922     */
923    $build['SELECT']=implode(',', $tmpBuild['SELECT']);
924
925    /* build FROM
926     *
927     */
928    $build['FROM']=implode(',', $tmpBuild['FROM']);
929    unset($tmpBuild['FROM']);
930
931
932    /* build WHERE
933     */
934    if($request['filter']!='') $tmpBuild['WHERE'][]=$request['filter'];
935    $build['WHERE']=implode(' AND ', $tmpBuild['WHERE']);
936    unset($tmpBuild['WHERE']);
937
938    /* for each plugin, adds jointure with the IMAGE table
939     */
940    self::cleanArray($tmpBuild['JOIN']);
941    if(count($tmpBuild['JOIN'])>0)
942    {
943      $build['WHERE'].=' AND ('.implode(' AND ', $tmpBuild['JOIN']).') ';
944    }
945    unset($tmpBuild['JOIN']);
946
947    self::cleanArray($tmpBuild['GROUPBY']);
948    if(count($tmpBuild['GROUPBY'])>0)
949    {
950      $build['GROUPBY'].=' '.implode(', ', $tmpBuild['GROUPBY']).' ';
951    }
952    unset($tmpBuild['GROUPBY']);
953
954
955    $imagesList=Array();
956
957    $sql='SELECT DISTINCT '.$build['SELECT']
958        .' FROM '.$build['FROM']
959        .' WHERE '.$build['WHERE']
960        .' GROUP BY '.$build['GROUPBY'];
961
962    $sql.=' ORDER BY pit.id '
963         .' LIMIT '.$limitFrom.', '.$numPerPage;
964
965//echo $sql;
966    $result=pwg_query($sql);
967    if($result)
968    {
969      while($row=pwg_db_fetch_assoc($result))
970      {
971        // affect standard datas
972        $datas['imageThumbnail']=DerivativeImage::thumb_url(array('id'=>$row['imageId'], 'path'=>$row['imagePath']));
973        $datas['imageId']=$row['imageId'];
974        $datas['imagePath']=$row['imagePath'];
975        $datas['imageName']=$row['imageName'];
976
977        $datas['imageCategoriesId']=explode(',', $row['imageCategoriesId']);
978        $datas['imageCategoriesNames']=explode('#sep#', $row['imageCategoriesNames']);
979        $datas['imageCategoriesPLink']=explode('#sep#', $row['imageCategoriesPLink']);
980        $datas['imageCategoriesDir']=explode(',', $row['imageCategoriesDir']);
981
982        $datas['imageCategories']=Array();
983        for($i=0;$i<count($datas['imageCategoriesId']);$i++)
984        {
985          $datas['imageCategories'][]=array(
986            'id' => $datas['imageCategoriesId'][$i],
987            'name' => $datas['imageCategoriesNames'][$i],
988            'dirType' => $datas['imageCategoriesDir'][$i],
989            'pLinks' => $datas['imageCategoriesPLink'][$i],
990            'link'=> make_picture_url(
991                        array(
992                          'image_id' => $datas['imageId'],
993                          'category' => array
994                            (
995                              'id' => $datas['imageCategoriesId'][$i],
996                              'name' => $datas['imageCategoriesNames'][$i],
997                              'permalink' => $datas['imageCategoriesPLink'][$i]
998                            )
999                        )
1000                      )
1001          );
1002        }
1003
1004        /* affect datas for each plugin
1005         *
1006         * each plugin have to format the data in an HTML code
1007         *
1008         * so, for each plugin :
1009         *  - look the attributes given in the SELECT clause
1010         *  - for each attributes, associate the returned value of the record
1011         *  - affect in datas an index equals to the plugin pluginName, with returned HTML code ; HTML code is get from a formatData function
1012         *
1013         * Example :
1014         *  plugin ColorStart provide 2 attributes 'csColors' and 'csColorsPct'
1015         *
1016         *  we affect to the $attributes var :
1017         *  $attributes['csColors'] = $row['csColors'];
1018         *  $attributes['csColorsPct'] = $row['csColorsPct'];
1019         *
1020         *  call the ColorStat RB callback formatData with the $attributes => the function return a HTML code ready to use in the template
1021         *
1022         *  affect $datas['ColorStat'] = $the_returned_html_code;
1023         *
1024         *
1025         */
1026        foreach($tmpBuild['SELECT'] as $key => $val)
1027        {
1028          if($key!='RB_PIT' && $key!='RB_PIC' && $key!='RB_PCT')
1029          {
1030            $tmp=explode(',', $val);
1031
1032            $attributes=Array();
1033
1034            foreach($tmp as $key2 => $val2)
1035            {
1036              $name=self::getAttribute($val2);
1037              $attributes[$name]=$row[$name];
1038            }
1039
1040            $datas['plugin'][$key]=call_user_func(Array('RBCallBack'.$key, 'formatData'), $attributes);
1041
1042            unset($tmp);
1043            unset($attributes);
1044          }
1045        }
1046        $imagesList[]=$datas;
1047        unset($datas);
1048      }
1049    }
1050
1051    return(self::toHtml($imagesList));
1052    //return("get page : $requestNumber, $pageNumber, $numPerPage<br>$debug<br>$sql");
1053  }
1054
1055  /**
1056   * remove all empty value from an array
1057   * @param Array a$array : the array to clean
1058   */
1059  static private function cleanArray(&$array)
1060  {
1061    foreach($array as $key => $val)
1062    {
1063      if(is_array($val))
1064      {
1065        self::cleanArray($val);
1066        if(count($val)==0) unset($array[$key]);
1067      }
1068      elseif(trim($val)=='') unset($array[$key]);
1069    }
1070  }
1071
1072  /**
1073   * returns the alias for an attribute
1074   *
1075   *  item1                          => returns item1
1076   *  table1.item1                   => returns item1
1077   *  table1.item1 AS alias1         => returns alias1
1078   *  item1 AS alias1                => returns alias1
1079   *  GROUP_CONCAT( .... ) AS alias1 => returns alias1
1080   *
1081   * @param String $var : value to examine
1082   * @return String : the attribute name
1083   */
1084  static private function getAttribute($val)
1085  {
1086    preg_match('/(?:GROUP_CONCAT\(.*\)|(?:[A-Z0-9_]*)\.)?([A-Z0-9_]*)(?:\s+AS\s+([A-Z0-9_]*))?/i', trim($val), $result);
1087    if(array_key_exists(2, $result))
1088    {
1089      return($result[2]);
1090    }
1091    elseif(array_key_exists(1, $result))
1092    {
1093      return($result[1]);
1094    }
1095    else
1096    {
1097      return($val);
1098    }
1099  }
1100
1101
1102  /**
1103   * returns a a sql statement GROUP_CONCAT for an alias
1104   *
1105   *  item1                  => returns GROUP_CONCAT(item1 SEPARATOR $sep) AS item1
1106   *  table1.item1           => returns GROUP_CONCAT(table1.item1 SEPARATOR $sep) AS item1
1107   *  table1.item1 AS alias1 => returns GROUP_CONCAT(table1.item1 SEPARATOR $sep) AS alias1
1108   *  item1 AS alias1        => returns GROUP_CONCAT(item1 SEPARATOR $sep) AS alias1
1109   *
1110   * @param String $val : value to examine
1111   * @param String $sep : the separator
1112   * @return String : the attribute name
1113   */
1114  static private function groupConcatAlias($val, $sep=',')
1115  {
1116    /*
1117     * table1.item1 AS alias1
1118     *
1119     * $result[3] = alias1
1120     * $result[2] = item1
1121     * $result[1] = table1.item1
1122     */
1123    preg_match('/((?:(?:[A-Z0-9_]*)\.)?([A-Z0-9_]*))(?:\s+AS\s+([A-Z0-9_]*))?/i', trim($val), $result);
1124    if(array_key_exists(3, $result))
1125    {
1126      return("GROUP_CONCAT(DISTINCT ".$result[1]." SEPARATOR '$sep') AS ".$result[3]);
1127    }
1128    elseif(array_key_exists(2, $result))
1129    {
1130      return("GROUP_CONCAT(DISTINCT ".$result[1]." SEPARATOR '$sep') AS ".$result[2]);
1131    }
1132    else
1133    {
1134      return("GROUP_CONCAT(DISTINCT $val SEPARATOR '$sep') AS ".$val);
1135    }
1136  }
1137
1138
1139  /**
1140   * get a new request number and create it in the request table
1141   *
1142   * @param Integer $userId : id of the user
1143   * @return Integer : the new request number, -1 if something wrong appened
1144   */
1145  static private function getNewRequest($userId)
1146  {
1147    $sql="INSERT INTO ".self::$tables['request']." VALUES('', '$userId', '".date('Y-m-d H:i:s')."', 0, 0, '', '', '')";
1148    $result=pwg_query($sql);
1149    if($result)
1150    {
1151      return(pwg_db_insert_id());
1152    }
1153    return(-1);
1154  }
1155
1156  /**
1157   * update request properties
1158   *
1159   * @param Integer $request_id : the id of request to update
1160   * @param Integer $numItems : number of items found in the request
1161   * @param Float $executionTime : time in second to execute the request
1162   * @param String $pluginList : list of used plugins
1163   * @param String $parameters : parameters given for the request
1164   * @return Boolean : true if request was updated, otherwise false
1165   */
1166  static private function updateRequest($requestId, $numItems, $executionTime, $pluginList, $additionalFilter, $parameters)
1167  {
1168    $sql="UPDATE ".self::$tables['request']."
1169            SET num_items = $numItems,
1170                execution_time = $executionTime,
1171                connected_plugin = '$pluginList',
1172                filter = '".mysql_escape_string($additionalFilter)."',
1173                parameters = '".serialize($parameters)."'
1174            WHERE id = $requestId";
1175    $result=pwg_query($sql);
1176    if($result)
1177    {
1178      return(true);
1179    }
1180    return(false);
1181  }
1182
1183  /**
1184   * returns request properties
1185   *
1186   * @param Integer $request_id : the id of request to update
1187   * @return Array : properties for request, false if request doesn't exist
1188   */
1189  static private function getRequest($requestId)
1190  {
1191    $returned=false;
1192    $sql="SELECT user_id, date, num_items, execution_time, connected_plugin, filter, parameters
1193          FROM ".self::$tables['request']."
1194          WHERE id = $requestId";
1195    $result=pwg_query($sql);
1196    if($result)
1197    {
1198      while($row=pwg_db_fetch_assoc($result))
1199      {
1200        if($row['parameters']!='') $row['parameters']=unserialize($row['parameters']);
1201        $returned=$row;
1202      }
1203    }
1204    return($returned);
1205  }
1206
1207
1208  /**
1209   * internal function used by the executeRequest function for single record
1210   * requests
1211   *
1212   * this function is called recursively
1213   *
1214   * @param Array $groupContent :
1215   * @param Array $items :
1216   * @return String : a where clause
1217   */
1218  static private function buildGroup($groupContent, $items, $groups, $operator)
1219  {
1220    $returned=Array();
1221    foreach($groupContent as $key => $val)
1222    {
1223      if(strpos($val['id'], 'iCbGroup')!==false)
1224      {
1225        preg_match('/[0-9]*$/i', $val['id'], $groupNumber);
1226        $returned[]=self::buildGroup($val['children'], $items, $groups, $groups[$groupNumber[0]]);
1227      }
1228      else
1229      {
1230        preg_match('/[0-9]*$/i', $val['id'], $itemNumber);
1231        $returned[]=" (".$items[$itemNumber[0]].") ";
1232      }
1233    }
1234    return('('.implode($operator, $returned).')');
1235  }
1236
1237
1238  /**
1239   * internal function used by the executeRequest function for multi records
1240   * requests
1241   *
1242   * this function is called recursively
1243   *
1244   * @param Array $groupContent :
1245   * @param Array $clausesItems : array with 'where' and 'having' conditions (and 'plugin' for the plugin)
1246   * @param Array $groups : operators of each group
1247   * @param String $operator : 'OR' or 'AND', according with the current group operator
1248   * @param String $requestNumber : the request number
1249   * @return String : part of a SQL request
1250   */
1251  static private function buildGroupRequest($groupContent, $clausesItems, $groups, $operator, $requestNumber)
1252  {
1253    $returnedS='';
1254    $returned=Array();
1255    foreach($groupContent as $key => $val)
1256    {
1257      if(strpos($val['id'], 'iCbGroup')!==false)
1258      {
1259        preg_match('/[0-9]*$/i', $val['id'], $groupNumber);
1260
1261        $groupValue=self::buildGroupRequest($val['children'], $clausesItems, $groups, $groups[$groupNumber[0]], $requestNumber);
1262
1263        if($groupValue!='')
1264          $returned[]=array(
1265            'mode'  => 'group',
1266            'value' => $groupValue
1267          );
1268      }
1269      else
1270      {
1271        preg_match('/[0-9]*$/i', $val['id'], $itemNumber);
1272
1273        $returned[]=array(
1274          'mode'  => 'item',
1275          'plugin' => $clausesItems[$itemNumber[0]]['plugin'],
1276          'valueWhere' => ($clausesItems[$itemNumber[0]]['where']!='')?" (".$clausesItems[$itemNumber[0]]['where'].") ":'',
1277          'valueHaving' => ($clausesItems[$itemNumber[0]]['having'])?" (".$clausesItems[$itemNumber[0]]['having'].") ":'',
1278        );
1279      }
1280    }
1281
1282    if(count($returned)>0)
1283    {
1284      if(strtolower(trim($operator))=='and')
1285      {
1286        $tId=0;
1287        foreach($returned as $key=>$val)
1288        {
1289          if($tId>0) $returnedS.=" JOIN ";
1290
1291          if($val['mode']=='item')
1292          {
1293            $returnedS.="(SELECT DISTINCT ".call_user_func(Array('RBCallBack'.$val['plugin'], 'getImageId'))." AS imageId
1294                          FROM ".call_user_func(Array('RBCallBack'.$val['plugin'], 'getFrom'));
1295            if($val['valueWhere']!='') $returnedS.=" WHERE ".$val['valueWhere'];
1296            if($val['valueHaving']!='')
1297              $returnedS.=" GROUP BY imageId
1298                            HAVING ".$val['valueHaving'];
1299            $returnedS.=") t".self::$tGlobalId." ";
1300          }
1301          else
1302          {
1303            $returnedS.="(".$val['value'].") t".self::$tGlobalId." ";
1304          }
1305
1306          if($tId>0) $returnedS.=" ON t".(self::$tGlobalId-1).".imageId = t".self::$tGlobalId.".imageId ";
1307          $tId++;
1308          self::$tGlobalId++;
1309        }
1310        $returnedS="SELECT DISTINCT '$requestNumber', t".(self::$tGlobalId-$tId).".imageId FROM ".$returnedS;
1311      }
1312      else
1313      {
1314        foreach($returned as $key=>$val)
1315        {
1316          if($returnedS!='') $returnedS.=" UNION DISTINCT ";
1317
1318          if($val['mode']=='item')
1319          {
1320            $returnedS.="SELECT DISTINCT '$requestNumber', t".self::$tGlobalId.".imageId
1321                          FROM (SELECT ".call_user_func(Array('RBCallBack'.$val['plugin'], 'getImageId'))." AS imageId
1322                                FROM ".call_user_func(Array('RBCallBack'.$val['plugin'], 'getFrom'));
1323            if($val['valueWhere']!='') $returnedS.=" WHERE ".$val['valueWhere'];
1324            if($val['valueHaving']!='')
1325              $returnedS.=" GROUP BY imageId
1326                            HAVING ".$val['valueHaving'];
1327            $returnedS.=") t".self::$tGlobalId." ";
1328          }
1329          else
1330          {
1331            $returnedS.="SELECT DISTINCT '$requestNumber', t".self::$tGlobalId.".imageId FROM (".$val['value'].") t".self::$tGlobalId;
1332          }
1333
1334          self::$tGlobalId++;
1335        }
1336      }
1337    }
1338
1339    return($returnedS);
1340  }
1341
1342
1343  /**
1344   * convert a list of images to HTML
1345   *
1346   * @param Array $imagesList : list of images id & associated datas
1347   * @return String : list formatted into HTML code
1348   */
1349  static protected function toHtml($imagesList)
1350  {
1351    global $template;
1352
1353    $template->set_filename('result_items',
1354                dirname(dirname(__FILE__)).'/templates/GPCRequestBuilder_result.tpl');
1355
1356
1357
1358    $template->assign('datas', $imagesList);
1359
1360    return($template->parse('result_items', true));
1361  }
1362
1363
1364  /**
1365   * returns allowed (or not allowed) categories for a user
1366   *
1367   * used the USER_CACHE_TABLE if possible
1368   *
1369   * @param Integer $userId : a valid user Id
1370   * @return String : IN(...), NOT IN(...) or nothing if there is no restriction
1371   *                  for the user
1372   */
1373  public function getUserCategories($userId)
1374  {
1375/*
1376    $returned='';
1377    if($user['forbidden_categories']!='')
1378    {
1379      $returned=Array(
1380        'JOIN' => 'AND ('.IMAGE_CATEGORY.'.category_id NOT IN ('.$user['forbidden_categories'].') ) ',
1381        'FROM' => IMAGE_CATEGORY
1382      );
1383
1384
1385    }
1386    *
1387    *
1388    */
1389  }
1390
1391
1392  /**
1393   * display search page
1394   *
1395   * @param Array $filter : an array of string ; each item is the name of a
1396   *                        registered plugin
1397   *                        if no parameters are given, no filter is applied
1398   *                        otherwise only plugin wich name is given are
1399   *                        accessible
1400   */
1401  static public function displaySearchPage($filter=array())
1402  {
1403    global $template, $lang;
1404
1405    if(is_string($filter)) $filter=array($filter);
1406    $filter=array_flip($filter);
1407
1408    GPCCore::addHeaderJS('jquery.ui', 'themes/default/js/ui/jquery.ui.core.js', array('jquery'));
1409    GPCCore::addHeaderJS('jquery.ui.widget', 'themes/default/js/ui/jquery.ui.widget.js', array('jquery.ui'));
1410    GPCCore::addHeaderJS('jquery.ui.mouse', 'themes/default/js/ui/jquery.ui.mouse.js', array('jquery.ui.widget'));
1411    GPCCore::addHeaderJS('jquery.ui.position', 'themes/default/js/ui/jquery.ui.position.js', array('jquery.ui.widget'));
1412    GPCCore::addHeaderJS('jquery.ui.draggable', 'themes/default/js/ui/jquery.ui.draggable.js', array('jquery.ui.widget'));
1413    GPCCore::addHeaderJS('jquery.ui.dialog', 'themes/default/js/ui/jquery.ui.dialog.js', array('jquery.ui.widget'));
1414    GPCCore::addHeaderJS('jquery.ui.slider', 'themes/default/js/ui/jquery.ui.slider.js', array('jquery.ui.widget'));
1415    GPCCore::addHeaderJS('gpc.pagesNavigator', 'plugins/GrumPluginClasses/js/pagesNavigator.js');
1416    GPCCore::addHeaderJS('gpc.rbSearch', 'plugins/GrumPluginClasses/js/rbSearch.js');
1417
1418    $template->set_filename('gpc_search_page',
1419                dirname(dirname(__FILE__)).'/templates/GPCRequestBuilder_search.tpl');
1420
1421    $registeredPlugin=self::getRegistered();
1422    $dialogBox=Array();
1423    foreach($registeredPlugin as $key=>$val)
1424    {
1425      if(array_key_exists($key, $registeredPlugin) and
1426         (count($filter)==0 or array_key_exists($key, $filter)))
1427      {
1428        if(file_exists($registeredPlugin[$key]['fileName']))
1429        {
1430          include_once($registeredPlugin[$key]['fileName']);
1431
1432          $dialogBox[]=Array(
1433            'handle' => $val['name'].'DB',
1434            'dialogBoxClass' => call_user_func(Array('RBCallBack'.$key, 'getInterfaceDBClass')),
1435            'label' => call_user_func(Array('RBCallBack'.$key, 'getInterfaceLabel')),
1436            'content' => call_user_func(Array('RBCallBack'.$key, 'getInterfaceContent')),
1437          );
1438        }
1439      }
1440    }
1441
1442    $datas=Array(
1443      'dialogBox' => $dialogBox,
1444      'themeName' => defined('IN_ADMIN')?$template->get_themeconf('name'):'',
1445    );
1446
1447    $template->assign('datas', $datas);
1448
1449    return($template->parse('gpc_search_page', true));
1450  } //displaySearchPage
1451
1452}
1453
1454
1455?>
Note: See TracBrowser for help on using the repository browser.