source: extensions/GrumPluginClasses/gpc_ajax.php @ 19961

Last change on this file since 19961 was 16012, checked in by grum, 12 years ago

feature:2634- compatibility with Piwigo 2.4
+add some objects on js framework

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