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

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

Fix bugs

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