source: extensions/GrumPluginClasses/gpc_ajax.php @ 15762

Last change on this file since 15762 was 12215, checked in by grum, 13 years ago

fix bugs
bug:2160 - CategorySelector : extended description are not managed
+add some functions to GPCCore

File size: 17.0 KB
Line 
1<?php
2/*
3 * -----------------------------------------------------------------------------
4 * Plugin Name: Grum Plugins Classes.3
5 * -----------------------------------------------------------------------------
6 * Author     : Grum
7 *   email    : grum@piwigo.org
8 *   website  : http://photos.grum.fr
9 *   PWG user : http://forum.piwigo.org/profile.php?id=3706
10 *
11 *   << May the Little SpaceFrog be with you ! >>
12 *
13 * -----------------------------------------------------------------------------
14 *
15 * See main.inc.php for release information
16 *
17 * manage all the ajax requests
18 *
19 * known functions :
20 *  - admin.rbuilder.fillCaddie
21 *  - admin.categorySelector.getList
22 *  - public.categorySelector.getList
23 *  - public.rbuilder.searchExecute
24 *  - public.rbuilder.searchGetPage
25 *  - public.tagSelector.get
26 *  - admin.tagSelector.get
27 *  - public.contact.sendMsg
28 *
29 *
30 * -----------------------------------------------------------------------------
31 */
32
33  define('PHPWG_ROOT_PATH',dirname(dirname(dirname(__FILE__))).'/');
34
35
36  /*
37   * set ajax module in admin mode if request is used for admin interface
38   */
39  if(!isset($_REQUEST['ajaxfct'])) $_REQUEST['ajaxfct']='';
40  if(preg_match('/^admin\./i', $_REQUEST['ajaxfct']))
41  {
42    define('IN_ADMIN', true);
43  }
44
45  // the common.inc.php file loads all the main.inc.php plugins files
46  include_once(PHPWG_ROOT_PATH.'include/common.inc.php' );
47  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php' );
48  include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/CommonPlugin.class.inc.php');
49  include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/GPCAjax.class.inc.php');
50
51  global $page;
52  $page['root_path']='./';
53
54  load_language('plugin.lang', GPC_PATH);
55
56  class GPC_Ajax extends CommonPlugin
57  {
58    /**
59     * return true if string equals 'true' ; otherwise return false
60     * @param String $value
61     * @return Bool
62     */
63    static function stringBool($value)
64    {
65      return($value=='true');
66    }
67
68    /**
69     * constructor
70     */
71    public function __construct($prefixeTable, $filelocation)
72    {
73      $this->setPluginName("Grum Plugin Classes");
74      $this->setPluginNameFiles("gpc");
75      parent::__construct($prefixeTable, $filelocation);
76
77      $tableList=array('result_cache');
78      $this->setTablesList($tableList);
79
80      $this->loadConfig();
81      $this->checkRequest();
82      $this->returnAjaxContent();
83    }
84
85    /**
86     * check the $_REQUEST values and set default values
87     *
88     */
89    protected function checkRequest()
90    {
91      global $user;
92
93      if(!isset($_REQUEST['ajaxfct'])) $_REQUEST['ajaxfct']='';
94
95      // check if asked function is valid
96      if(!(
97           $_REQUEST['ajaxfct']=='admin.rbuilder.fillCaddie' or
98           $_REQUEST['ajaxfct']=='public.rbuilder.searchExecute' or
99           $_REQUEST['ajaxfct']=='public.rbuilder.searchGetPage' or
100           $_REQUEST['ajaxfct']=='admin.categorySelector.getList' or
101           $_REQUEST['ajaxfct']=='public.categorySelector.getList' or
102           $_REQUEST['ajaxfct']=='public.tagSelector.get' or
103           $_REQUEST['ajaxfct']=='admin.tagSelector.get' or
104           $_REQUEST['ajaxfct']=='public.contact.sendMsg'
105          )
106        ) $_REQUEST['ajaxfct']='';
107
108      if(preg_match('/^admin\./i', $_REQUEST['ajaxfct']) and !is_admin()) $_REQUEST['ajaxfct']='';
109
110      if($_REQUEST['ajaxfct']!='')
111      {
112        /*
113         * check admin.rbuilder.fillCaddie values
114         */
115        if($_REQUEST['ajaxfct']=="admin.rbuilder.fillCaddie")
116        {
117          if(!isset($_REQUEST['fillMode'])) $_REQUEST['fillMode']="add";
118
119          if(!($_REQUEST['fillMode']=="add" or
120               $_REQUEST['fillMode']=="replace")) $_REQUEST['fillMode']="add";
121
122          if(!isset($_REQUEST['requestNumber'])) $_REQUEST['ajaxfct']="";
123        }
124
125        /*
126         * check public.rbuilder.searchExecute values
127         */
128        if($_REQUEST['ajaxfct']=="public.rbuilder.searchExecute")
129        {
130          if(!isset($_REQUEST['requestName'])) $_REQUEST['ajaxfct']="";
131        }
132
133        /*
134         * check public.rbuilder.searchGetPage values
135         */
136        if($_REQUEST['ajaxfct']=="public.rbuilder.searchGetPage")
137        {
138           if(!isset($_REQUEST['requestNumber'])) $_REQUEST['ajaxfct']="";
139
140          if(!isset($_REQUEST['page'])) $_REQUEST['page']=0;
141
142          if($_REQUEST['page']<0) $_REQUEST['page']=0;
143
144          if(!isset($_REQUEST['numPerPage'])) $_REQUEST['numPerPage']=25;
145
146          if($_REQUEST['numPerPage']>100) $_REQUEST['numPerPage']=100;
147        }
148
149
150        /*
151         * check admin.tagSelector.get values
152         */
153        if($_REQUEST['ajaxfct']=="admin.tagSelector.get" or
154           $_REQUEST['ajaxfct']=="public.tagSelector.get")
155        {
156          if(!isset($_REQUEST['letters'])) $_REQUEST['ajaxfct']="";
157          if(!isset($_REQUEST['filter'])) $_REQUEST['filter']="affected";
158
159          if(!($_REQUEST['filter']=="affected" or
160               $_REQUEST['filter']=="all")
161            ) $_REQUEST['filter']="affected";
162
163          if(!isset($_REQUEST['maxTags'])) $_REQUEST['maxTags']=1000;
164          if($_REQUEST['maxTags']<0) $_REQUEST['maxTags']=0;
165
166          if(!isset($_REQUEST['ignoreCase'])) $_REQUEST['ignoreCase']=true;
167
168          $_REQUEST['ignoreCase']=self::stringBool($_REQUEST['ignoreCase']);
169        }
170
171
172        /*
173         * check public.categorySelector.getList values
174         */
175        if($_REQUEST['ajaxfct']=="admin.categorySelector.getList" or
176           $_REQUEST['ajaxfct']=="public.categorySelector.getList")
177        {
178          if(!isset($_REQUEST['filter'])) $_REQUEST['filter']="accessible";
179
180          if(!($_REQUEST['filter']=="public" or
181               $_REQUEST['filter']=="accessible" or
182               $_REQUEST['filter']=="all")
183            ) $_REQUEST['filter']="accessible";
184
185          if(!isset($_REQUEST['galleryRoot'])) $_REQUEST['galleryRoot']="y";
186
187          if(!($_REQUEST['galleryRoot']=="y" or
188               $_REQUEST['galleryRoot']=="n")
189            ) $_REQUEST['galleryRoot']="y";
190
191          if(!isset($_REQUEST['tree'])) $_REQUEST['tree']="n";
192
193          if(!($_REQUEST['tree']=="y" or
194               $_REQUEST['tree']=="n")
195            ) $_REQUEST['tree']="n";
196        }
197
198        /*
199         * check public.contact.sendMsg
200         */
201        if($_REQUEST['ajaxfct']=="public.contact.sendMsg")
202        {
203          if(!isset($_REQUEST['email'])) $_REQUEST['email']='';
204          if(!isset($_REQUEST['subject'])) $_REQUEST['subject']='';
205          if(!isset($_REQUEST['msg'])) $_REQUEST['msg']='';
206          if(!isset($_REQUEST['token'])) $_REQUEST['token']='';
207
208          if($_REQUEST['token']!=get_pwg_token()) $_REQUEST['ajaxfct']='';
209        }
210
211      }
212    } //checkRequest()
213
214
215    /**
216     * return ajax content
217     */
218    protected function returnAjaxContent()
219    {
220      $result="<p class='errors'>An error has occured</p>";
221      switch($_REQUEST['ajaxfct'])
222      {
223        case 'admin.rbuilder.fillCaddie':
224          $result=$this->ajax_gpc_admin_rbuilderFillCaddie($_REQUEST['fillMode'], $_REQUEST['requestNumber']);
225          break;
226        case 'public.rbuilder.searchExecute':
227          $result=$this->ajax_gpc_public_rbuilderSearchExecute();
228          break;
229        case 'public.rbuilder.searchGetPage':
230          $result=$this->ajax_gpc_public_rbuilderSearchGetPage();
231          break;
232        case 'admin.categorySelector.getList':
233          $result=$this->ajax_gpc_admin_CategorySelectorGetList($_REQUEST['filter'], $_REQUEST['galleryRoot'], $_REQUEST['tree']);
234          break;
235        case 'public.categorySelector.getList':
236          $result=$this->ajax_gpc_public_CategorySelectorGetList($_REQUEST['filter'], $_REQUEST['galleryRoot'], $_REQUEST['tree']);
237          break;
238        case 'admin.tagSelector.get':
239          $result=$this->ajax_gpc_both_TagSelectorGet('admin', $_REQUEST['letters'], $_REQUEST['filter'], $_REQUEST['maxTags'], $_REQUEST['ignoreCase']);
240          break;
241        case 'public.tagSelector.get':
242          $result=$this->ajax_gpc_both_TagSelectorGet('public', $_REQUEST['letters'], $_REQUEST['filter'], $_REQUEST['maxTags'], $_REQUEST['ignoreCase']);
243          break;
244        case 'public.contact.sendMsg':
245          $result=$this->ajax_gpc_public_contactSendMsg($_REQUEST['email'], $_REQUEST['subject'], $_REQUEST['msg']);
246          break;
247      }
248      GPCAjax::returnResult($result);
249    }
250
251
252    /**
253     * check validity of an email address
254     *
255     * @param String $email : email to check
256     * @returned Boolean :
257     */
258    private function emailAdressValid($email)
259    {
260      return(preg_match('#^[_a-z0-9\.\-]*[_a-z0-9\-]+@[_a-z0-9\.\-]+\.[a-z0-9\-]{2,}$#im', $email)>0);
261    }
262
263
264    /*------------------------------------------------------------------------*
265     *
266     * ADMIN FUNCTIONS
267     *
268     *----------------------------------------------------------------------- */
269
270    /**
271     * fill the caddie with the result of the requestNumber
272     *
273     * @param String $fillMode : 'addCaddie' or 'replaceCaddie'
274     * @param Integer $requestNumber : number of the request in cache
275     * @return String :
276     */
277    private function ajax_gpc_admin_rbuilderFillCaddie($mode, $requestNumber)
278    {
279      global $user;
280
281      switch($mode)
282      {
283        case "replace":
284          $sql="DELETE FROM ".CADDIE_TABLE." WHERE user_id = '".$user['id']."';";
285          pwg_query($sql);
286        case "add":
287          $sql="INSERT IGNORE INTO ".CADDIE_TABLE."
288                  SELECT '".$user['id']."', image_id
289                  FROM ".$this->tables['result_cache']."
290                  WHERE id = '$requestNumber';";
291          pwg_query($sql);
292          break;
293      }
294    }
295
296
297
298    /**
299     * return the list of all categories
300     *
301     * @param String $filter : 'public' or 'accessible' or 'all'
302     * @param String $galleryRoot : 'y' if the gallery root is in the list
303     * @param String $tree : 'y' to obtain a recursive array, 'n' to obtain a flat array
304     * @return String : json string
305     */
306    private function ajax_gpc_admin_CategorySelectorGetList($filter, $galleryRoot, $tree)
307    {
308      global $user;
309
310      include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/GPCCategorySelector.class.inc.php');
311
312      $categorySelector=new GPCCategorySelector(
313        array(
314          'filter' => $filter,
315          'galleryRoot' => ($galleryRoot=='y')?true:false,
316          'tree' => ($tree=='y')?true:false,
317          'userMode' => 'admin'
318        )
319      );
320
321      $returned=array(
322        'userId' => $user['id'],
323        'nbCategories' => 0,
324        'categories' => $categorySelector->getCategoryList(),
325        'status' => array(
326          0=>l10n('Private'),
327          1=>l10n('Public')
328        )
329      );
330      $returned['nbCategories']=count($returned['categories']);
331
332      return(json_encode($returned));
333    } //ajax_gpc_admin_CategorySelectorGetList
334
335
336    /**
337     * return the list of all categories
338     *
339     * @param String $filter : 'public' or 'accessible' or 'all'
340     * @param String $galleryRoot : 'y' if the gallery root is in the list
341     * @param String $tree : 'y' to obtain a recursive array, 'n' to obtain a flat array
342     * @param String $userMode : 'public' or 'admin'
343     * @return String : json string
344     */
345    private function ajax_gpc_public_CategorySelectorGetList($filter, $galleryRoot, $tree)
346    {
347      global $user;
348
349      include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/GPCCategorySelector.class.inc.php');
350
351      $categorySelector=new GPCCategorySelector(
352        array(
353          'filter' => $filter,
354          'galleryRoot' => ($galleryRoot=='y')?true:false,
355          'tree' => ($tree=='y')?true:false,
356          'userMode' => 'public'
357        )
358      );
359
360      $returned=array(
361        'userId' => $user['id'],
362        'nbCategories' => 0,
363        'categories' => $categorySelector->getCategoryList(),
364        'status' => array(
365          0=>l10n('Private'),
366          1=>l10n('Public')
367        )
368      );
369      $returned['nbCategories']=count($returned['categories']);
370
371      return(json_encode($returned));
372    } //ajax_gpc_public_CategorySelectorGetList
373
374
375    /**
376     *
377     * @return String :
378     */
379    private function ajax_gpc_public_rbuilderSearchExecute()
380    {
381      global $prefixeTable;
382      include_once(GPC_PATH."classes/GPCRequestBuilder.class.inc.php");
383      GPCRequestBuilder::init($prefixeTable, 'gpc');
384      return(GPCRequestBuilder::executeRequest($_REQUEST['ajaxfct']));
385    }
386
387    /**
388     *
389     * @return String :
390     */
391    private function ajax_gpc_public_rbuilderSearchGetPage()
392    {
393      global $prefixeTable;
394      include_once(GPC_PATH."classes/GPCRequestBuilder.class.inc.php");
395      GPCRequestBuilder::init($prefixeTable, 'gpc');
396      return(GPCRequestBuilder::executeRequest($_REQUEST['ajaxfct']));
397    }
398
399
400
401    /**
402     * return the list of all known tags
403     *
404     * @param Striong $mode : 'admin' or 'public'
405     * @param String $letters : filtering on letters
406     * @param String $filter : 'accessible' or 'all'
407     * @param Integer $maxTags : maximum of items returned ; 0 = no limits
408     * @return String : json string
409     */
410    private function ajax_gpc_both_TagSelectorGet($mode, $letters, $filter, $maxTags, $ignoreCase)
411    {
412      global $user;
413
414      $returned=array(
415        'totalNbTags' => 0,
416        'tags' => array(),
417      );
418
419      $binary='';
420      $where=' LOWER(ptt.name) ';
421
422      if(!$ignoreCase)
423      {
424        $binary=" BINARY ";
425        $where=" ptt.name ";
426      }
427      else
428      {
429        $letters=strtolower($letters);
430      }
431
432
433      $sql="SELECT DISTINCT SQL_CALC_FOUND_ROWS ptt.id, ptt.name
434            FROM ((".TAGS_TABLE." ptt ";
435
436      if($filter=='affected')
437      {
438        $sql.=" JOIN ".IMAGE_TAG_TABLE." pitt
439                ON pitt.tag_id = ptt.id ) ";
440      }
441      else
442      {
443        $sql.=" ) ";
444      }
445
446
447      if($mode=='public' and $filter=='affected')
448      {
449        $sql.=" JOIN ".IMAGE_CATEGORY_TABLE." pict
450                ON pict.image_id = pitt.image_id )
451                JOIN ".USER_CACHE_CATEGORIES_TABLE." pucc
452                ON (pucc.cat_id = pict.category_id AND pucc.user_id='".$user['id']."' )";
453      }
454      else
455      {
456        $sql.=" ) ";
457      }
458
459      $sql.=" WHERE $where LIKE $binary '%$letters%'
460            ORDER BY ptt.name ";
461
462      if($maxTags>0) $sql.=" LIMIT 0, ".$maxTags;
463
464      $result=pwg_query($sql);
465      if($result)
466      {
467        while($row=pwg_db_fetch_assoc($result))
468        {
469          $returned['tags'][]=$row;
470        }
471
472        $sql="SELECT FOUND_ROWS();";
473        $result=pwg_query($sql);
474        if($result)
475        {
476          while($row=pwg_db_fetch_row($result))
477          {
478            $returned['totalNbTags']=$row[0];
479          }
480        }
481      }
482
483      return(json_encode($returned));
484    } //ajax_gpc_both_TagSelectorGet
485
486
487    /**
488     *
489     *
490     * @param String $email :
491     * @param String $subject :
492     * @param String $msg :
493     * @param Integer $token :
494     * @return String : json string
495     */
496    private function ajax_gpc_public_contactSendMsg($email, $subject, $msg)
497    {
498      global $user, $conf;
499
500      $returned=array('result' => false, 'msg' => '');
501
502      if($email==null or trim($email)=='')
503      {
504        $returned['msg']=l10n('Email is mandatory');
505        return(json_encode($returned));
506      }
507
508      if(!$this->emailAdressValid($email))
509      {
510        $returned['msg']=l10n('Email is not valid');
511        return(json_encode($returned));
512      }
513
514      if($subject==null or trim($subject)=='')
515      {
516        $returned['msg']=l10n('Subject is mandatory');
517        return(json_encode($returned));
518      }
519
520      if($msg==null or trim($msg)=='')
521      {
522        $returned['msg']=l10n('Message is mandatory');
523        return(json_encode($returned));
524      }
525
526
527
528      $admins=array();
529      $sql="SELECT put.".$conf['user_fields']['username']." AS username,
530                   put.".$conf['user_fields']['email']." AS mail_address
531            FROM ".USERS_TABLE." AS put
532              JOIN ".USER_INFOS_TABLE." AS puit
533                ON puit.user_id =  put.".$conf['user_fields']['id']."
534            WHERE puit.status IN ('webmaster',  'admin')
535              AND ".$conf['user_fields']['email']." IS NOT NULL
536              AND puit.user_id <> ".$user['id']."
537            ORDER BY username;";
538
539      $result = pwg_query($sql);
540      if($result)
541      {
542        while ($row = pwg_db_fetch_assoc($result))
543        {
544          if(!empty($row['mail_address']))
545          {
546            array_push($admins, format_email($row['username'], $row['mail_address']));
547          }
548        }
549      }
550
551      $args=array(
552        'subject' => sprintf(l10n('[%s][Message from %s] %s'), $conf['gallery_title'], $email, $subject),
553        'content' => sprintf("[%s]\n%s\n%s\n--------\n%s", $_SERVER['REMOTE_ADDR'], $email, $subject, stripslashes($msg))
554      );
555
556      $send=pwg_mail(implode(',', $admins), $args);
557
558      if(!$send)
559      {
560        $returned['msg']=l10n('Sorry, an error has occured while sending the message to the webmaster');
561      }
562      else
563      {
564        $returned['result']=true;
565        $returned['msg']=l10n('Your message was sent to the webmaster!');
566      }
567
568      return(json_encode($returned));
569
570    }
571
572
573  } //class
574
575
576  $returned=new GPC_Ajax($prefixeTable, __FILE__);
577
578
579
580
581
582?>
Note: See TracBrowser for help on using the repository browser.