Dotclear

source: admin/services.php @ 3874:ab8368569446

Revision 3874:ab8368569446, 21.9 KB checked in by franck <carnet.franck.paul@…>, 7 years ago (diff)

short notation for array (array() → [])

Line 
1<?php
2/**
3 * @package Dotclear
4 * @subpackage Backend
5 *
6 * @copyright Olivier Meunier & Association Dotclear
7 * @copyright GPL-2.0-only
8 */
9
10require dirname(__FILE__) . '/../inc/admin/prepend.php';
11
12$core->rest->addFunction('getPostsCount', ['dcRestMethods', 'getPostsCount']);
13$core->rest->addFunction('getCommentsCount', ['dcRestMethods', 'getCommentsCount']);
14$core->rest->addFunction('checkNewsUpdate', ['dcRestMethods', 'checkNewsUpdate']);
15$core->rest->addFunction('checkCoreUpdate', ['dcRestMethods', 'checkCoreUpdate']);
16$core->rest->addFunction('getPostById', ['dcRestMethods', 'getPostById']);
17$core->rest->addFunction('getCommentById', ['dcRestMethods', 'getCommentById']);
18$core->rest->addFunction('quickPost', ['dcRestMethods', 'quickPost']);
19$core->rest->addFunction('validatePostMarkup', ['dcRestMethods', 'validatePostMarkup']);
20$core->rest->addFunction('getZipMediaContent', ['dcRestMethods', 'getZipMediaContent']);
21$core->rest->addFunction('getMeta', ['dcRestMethods', 'getMeta']);
22$core->rest->addFunction('delMeta', ['dcRestMethods', 'delMeta']);
23$core->rest->addFunction('setPostMeta', ['dcRestMethods', 'setPostMeta']);
24$core->rest->addFunction('searchMeta', ['dcRestMethods', 'searchMeta']);
25$core->rest->addFunction('setSectionFold', ['dcRestMethods', 'setSectionFold']);
26$core->rest->addFunction('getModuleById', ['dcRestMethods', 'getModuleById']);
27$core->rest->addFunction('setDashboardPositions', ['dcRestMethods', 'setDashboardPositions']);
28
29$core->rest->serve();
30
31/* Common REST methods */
32class dcRestMethods
33{
34    /**
35     * Serve method to get number of posts (whatever are their status) for current blog.
36     *
37     * @param     core     <b>dcCore</b>     dcCore instance
38     * @param     get     <b>array</b>     cleaned $_GET
39     */
40    public static function getPostsCount($core, $get)
41    {
42        $count = $core->blog->getPosts([], true)->f(0);
43        $str   = sprintf(__('%d post', '%d posts', $count), $count);
44
45        $rsp      = new xmlTag('count');
46        $rsp->ret = $str;
47
48        return $rsp;
49    }
50
51    /**
52     * Serve method to get number of comments (whatever are their status) for current blog.
53     *
54     * @param     core     <b>dcCore</b>     dcCore instance
55     * @param     get     <b>array</b>     cleaned $_GET
56     */
57    public static function getCommentsCount($core, $get)
58    {
59        $count = $core->blog->getComments([], true)->f(0);
60        $str   = sprintf(__('%d comment', '%d comments', $count), $count);
61
62        $rsp      = new xmlTag('count');
63        $rsp->ret = $str;
64
65        return $rsp;
66    }
67
68    public static function checkNewsUpdate($core, $get)
69    {
70        # Dotclear news
71
72        $rsp        = new xmlTag('news');
73        $rsp->check = false;
74        $ret        = __('Dotclear news not available');
75
76        if ($core->auth->user_prefs->dashboard->dcnews) {
77            try
78            {
79
80                if (empty($GLOBALS['__resources']['rss_news'])) {
81                    throw new Exception();
82                }
83                $feed_reader = new feedReader;
84                $feed_reader->setCacheDir(DC_TPL_CACHE);
85                $feed_reader->setTimeout(2);
86                $feed_reader->setUserAgent('Dotclear - http://www.dotclear.org/');
87                $feed = $feed_reader->parse($GLOBALS['__resources']['rss_news']);
88                if ($feed) {
89                    $ret = '<div class="box medium dc-box" id="ajax-news"><h3>' . __('Dotclear news') . '</h3><dl id="news">';
90                    $i   = 1;
91                    foreach ($feed->items as $item) {
92                        $dt = isset($item->link) ? '<a href="' . $item->link . '" class="outgoing" title="' . $item->title . '">' .
93                        $item->title . ' <img src="images/outgoing-link.svg" alt="" /></a>' : $item->title;
94
95                        if ($i < 3) {
96                            $ret .=
97                            '<dt>' . $dt . '</dt>' .
98                            '<dd><p><strong>' . dt::dt2str(__('%d %B %Y:'), $item->pubdate, 'Europe/Paris') . '</strong> ' .
99                            '<em>' . text::cutString(html::clean($item->content), 120) . '...</em></p></dd>';
100                        } else {
101                            $ret .=
102                            '<dt>' . $dt . '</dt>' .
103                            '<dd>' . dt::dt2str(__('%d %B %Y:'), $item->pubdate, 'Europe/Paris') . '</dd>';
104                        }
105                        $i++;
106                        if ($i > 2) {break;}
107                    }
108                    $ret .= '</dl></div>';
109                    $rsp->check = true;
110                }
111            } catch (Exception $e) {}
112        }
113        $rsp->ret = $ret;
114        return $rsp;
115    }
116
117    public static function checkCoreUpdate($core, $get)
118    {
119        # Dotclear updates notifications
120
121        $rsp        = new xmlTag('update');
122        $rsp->check = false;
123        $ret        = __('Dotclear update not available');
124
125        if ($core->auth->isSuperAdmin() && !DC_NOT_UPDATE && is_readable(DC_DIGESTS) &&
126            !$core->auth->user_prefs->dashboard->nodcupdate) {
127            $updater      = new dcUpdate(DC_UPDATE_URL, 'dotclear', DC_UPDATE_VERSION, DC_TPL_CACHE . '/versions');
128            $new_v        = $updater->check(DC_VERSION);
129            $version_info = $new_v ? $updater->getInfoURL() : '';
130
131            if ($updater->getNotify() && $new_v) {
132                // Check PHP version required
133                if (version_compare(phpversion(), $updater->getPHPVersion()) >= 0) {
134                    $ret =
135                    '<div class="dc-update" id="ajax-update"><h3>' . sprintf(__('Dotclear %s is available!'), $new_v) . '</h3> ' .
136                    '<p><a class="button submit" href="' . $core->adminurl->get("admin.update") . '">' . sprintf(__('Upgrade now'), $new_v) . '</a> ' .
137                    '<a class="button" href="' . $core->adminurl->get("admin.update", ['hide_msg' => 1]) . '">' . __('Remind me later') . '</a>' .
138                        ($version_info ? ' </p>' .
139                        '<p class="updt-info"><a href="' . $version_info . '">' . __('Information about this version') . '</a>' : '') . '</p>' .
140                        '</div>';
141                } else {
142                    $ret = '<p class="info">' .
143                    sprintf(__('A new version of Dotclear is available but needs PHP version ≥ %s, your\'s is currently %s'),
144                        $updater->getPHPVersion(), phpversion()) .
145                        '</p>';
146                }
147                $rsp->check = true;
148            } else {
149                if (version_compare(phpversion(), DC_NEXT_REQUIRED_PHP, '<')) {
150                    $ret = '<p class="info">' .
151                    sprintf(__('The next versions of Dotclear will not support PHP version < %s, your\'s is currently %s'),
152                        DC_NEXT_REQUIRED_PHP, phpversion()) .
153                        '</p>';
154                    $rsp->check = true;
155                }
156            }
157        }
158        $rsp->ret = $ret;
159        return $rsp;
160    }
161
162    public static function getPostById($core, $get)
163    {
164        if (empty($get['id'])) {
165            throw new Exception('No post ID');
166        }
167
168        $params = ['post_id' => (integer) $get['id']];
169
170        if (isset($get['post_type'])) {
171            $params['post_type'] = $get['post_type'];
172        }
173
174        $rs = $core->blog->getPosts($params);
175
176        if ($rs->isEmpty()) {
177            throw new Exception('No post for this ID');
178        }
179
180        $rsp     = new xmlTag('post');
181        $rsp->id = $rs->post_id;
182
183        $rsp->blog_id($rs->blog_id);
184        $rsp->user_id($rs->user_id);
185        $rsp->cat_id($rs->cat_id);
186        $rsp->post_dt($rs->post_dt);
187        $rsp->post_creadt($rs->post_creadt);
188        $rsp->post_upddt($rs->post_upddt);
189        $rsp->post_format($rs->post_format);
190        $rsp->post_url($rs->post_url);
191        $rsp->post_lang($rs->post_lang);
192        $rsp->post_title($rs->post_title);
193        $rsp->post_excerpt($rs->post_excerpt);
194        $rsp->post_excerpt_xhtml($rs->post_excerpt_xhtml);
195        $rsp->post_content($rs->post_content);
196        $rsp->post_content_xhtml($rs->post_content_xhtml);
197        $rsp->post_notes($rs->post_notes);
198        $rsp->post_status($rs->post_status);
199        $rsp->post_selected($rs->post_selected);
200        $rsp->post_open_comment($rs->post_open_comment);
201        $rsp->post_open_tb($rs->post_open_tb);
202        $rsp->nb_comment($rs->nb_comment);
203        $rsp->nb_trackback($rs->nb_trackback);
204        $rsp->user_name($rs->user_name);
205        $rsp->user_firstname($rs->user_firstname);
206        $rsp->user_displayname($rs->user_displayname);
207        $rsp->user_email($rs->user_email);
208        $rsp->user_url($rs->user_url);
209        $rsp->cat_title($rs->cat_title);
210        $rsp->cat_url($rs->cat_url);
211
212        $rsp->post_display_content($rs->getContent(true));
213        $rsp->post_display_excerpt($rs->getExcerpt(true));
214
215        $metaTag = new xmlTag('meta');
216        if (($meta = @unserialize($rs->post_meta)) !== false) {
217            foreach ($meta as $K => $V) {
218                foreach ($V as $v) {
219                    $metaTag->$K($v);
220                }
221            }
222        }
223        $rsp->post_meta($metaTag);
224
225        return $rsp;
226    }
227
228    public static function getCommentById($core, $get)
229    {
230        if (empty($get['id'])) {
231            throw new Exception('No comment ID');
232        }
233
234        $rs = $core->blog->getComments(['comment_id' => (integer) $get['id']]);
235
236        if ($rs->isEmpty()) {
237            throw new Exception('No comment for this ID');
238        }
239
240        $rsp     = new xmlTag('post');
241        $rsp->id = $rs->comment_id;
242
243        $rsp->comment_dt($rs->comment_dt);
244        $rsp->comment_upddt($rs->comment_upddt);
245        $rsp->comment_author($rs->comment_author);
246        $rsp->comment_site($rs->comment_site);
247        $rsp->comment_content($rs->comment_content);
248        $rsp->comment_trackback($rs->comment_trackback);
249        $rsp->comment_status($rs->comment_status);
250        $rsp->post_title($rs->post_title);
251        $rsp->post_url($rs->post_url);
252        $rsp->post_id($rs->post_id);
253        $rsp->post_dt($rs->post_dt);
254        $rsp->user_id($rs->user_id);
255
256        $rsp->comment_display_content($rs->getContent(true));
257
258        if ($core->auth->userID()) {
259            $rsp->comment_ip($rs->comment_ip);
260            $rsp->comment_email($rs->comment_email);
261            $rsp->comment_spam_disp(dcAntispam::statusMessage($rs));
262        }
263
264        return $rsp;
265    }
266
267    public static function quickPost($core, $get, $post)
268    {
269        # Create category
270        if (!empty($post['new_cat_title']) && $core->auth->check('categories', $core->blog->id)) {
271
272            $cur_cat            = $core->con->openCursor($core->prefix . 'category');
273            $cur_cat->cat_title = $post['new_cat_title'];
274            $cur_cat->cat_url   = '';
275
276            $parent_cat = !empty($post['new_cat_parent']) ? $post['new_cat_parent'] : '';
277
278            # --BEHAVIOR-- adminBeforeCategoryCreate
279            $core->callBehavior('adminBeforeCategoryCreate', $cur_cat);
280
281            $post['cat_id'] = $core->blog->addCategory($cur_cat, (integer) $parent_cat);
282
283            # --BEHAVIOR-- adminAfterCategoryCreate
284            $core->callBehavior('adminAfterCategoryCreate', $cur_cat, $post['cat_id']);
285        }
286
287        $cur = $core->con->openCursor($core->prefix . 'post');
288
289        $cur->post_title        = !empty($post['post_title']) ? $post['post_title'] : '';
290        $cur->user_id           = $core->auth->userID();
291        $cur->post_content      = !empty($post['post_content']) ? $post['post_content'] : '';
292        $cur->cat_id            = !empty($post['cat_id']) ? (integer) $post['cat_id'] : null;
293        $cur->post_format       = !empty($post['post_format']) ? $post['post_format'] : 'xhtml';
294        $cur->post_lang         = !empty($post['post_lang']) ? $post['post_lang'] : '';
295        $cur->post_status       = !empty($post['post_status']) ? (integer) $post['post_status'] : 0;
296        $cur->post_open_comment = (integer) $core->blog->settings->system->allow_comments;
297        $cur->post_open_tb      = (integer) $core->blog->settings->system->allow_trackbacks;
298
299        # --BEHAVIOR-- adminBeforePostCreate
300        $core->callBehavior('adminBeforePostCreate', $cur);
301
302        $return_id = $core->blog->addPost($cur);
303
304        # --BEHAVIOR-- adminAfterPostCreate
305        $core->callBehavior('adminAfterPostCreate', $cur, $return_id);
306
307        $rsp     = new xmlTag('post');
308        $rsp->id = $return_id;
309
310        $post = $core->blog->getPosts(['post_id' => $return_id]);
311
312        $rsp->post_status = $post->post_status;
313        $rsp->post_url    = $post->getURL();
314        return $rsp;
315    }
316
317    public static function validatePostMarkup($core, $get, $post)
318    {
319        if (!isset($post['excerpt'])) {
320            throw new Exception('No entry excerpt');
321        }
322
323        if (!isset($post['content'])) {
324            throw new Exception('No entry content');
325        }
326
327        if (empty($post['format'])) {
328            throw new Exception('No entry format');
329        }
330
331        if (!isset($post['lang'])) {
332            throw new Exception('No entry lang');
333        }
334
335        $excerpt       = $post['excerpt'];
336        $excerpt_xhtml = '';
337        $content       = $post['content'];
338        $content_xhtml = '';
339        $format        = $post['format'];
340        $lang          = $post['lang'];
341
342        $core->blog->setPostContent(0, $format, $lang, $excerpt, $excerpt_xhtml, $content, $content_xhtml);
343
344        $rsp = new xmlTag('result');
345
346        $v = htmlValidator::validate($excerpt_xhtml . $content_xhtml);
347
348        $rsp->valid($v['valid']);
349        $rsp->errors($v['errors']);
350
351        return $rsp;
352    }
353
354    public static function getZipMediaContent($core, $get, $post)
355    {
356        if (empty($get['id'])) {
357            throw new Exception('No media ID');
358        }
359
360        $id = (integer) $get['id'];
361
362        if (!$core->auth->check('media,media_admin', $core->blog)) {
363            throw new Exception('Permission denied');
364        }
365
366        try {
367            $core->media = new dcMedia($core);
368            $file        = $core->media->getFile($id);
369        } catch (Exception $e) {}
370
371        if ($file === null || $file->type != 'application/zip' || !$file->editable) {
372            throw new Exception('Not a valid file');
373        }
374
375        $rsp     = new xmlTag('result');
376        $content = $core->media->getZipContent($file);
377
378        foreach ($content as $k => $v) {
379            $rsp->file($k);
380        }
381
382        return $rsp;
383    }
384
385    public static function getMeta($core, $get)
386    {
387        $postid   = !empty($get['postId']) ? $get['postId'] : null;
388        $limit    = !empty($get['limit']) ? $get['limit'] : null;
389        $metaId   = !empty($get['metaId']) ? $get['metaId'] : null;
390        $metaType = !empty($get['metaType']) ? $get['metaType'] : null;
391
392        $sortby = !empty($get['sortby']) ? $get['sortby'] : 'meta_type,asc';
393
394        $rs = $core->meta->getMetadata([
395            'meta_type' => $metaType,
396            'limit'     => $limit,
397            'meta_id'   => $metaId,
398            'post_id'   => $postid]);
399        $rs = $core->meta->computeMetaStats($rs);
400
401        $sortby = explode(',', $sortby);
402        $sort   = $sortby[0];
403        $order  = isset($sortby[1]) ? $sortby[1] : 'asc';
404
405        switch ($sort) {
406            case 'metaId':
407                $sort = 'meta_id_lower';
408                break;
409            case 'count':
410                $sort = 'count';
411                break;
412            case 'metaType':
413                $sort = 'meta_type';
414                break;
415            default:
416                $sort = 'meta_type';
417        }
418
419        $rs->sort($sort, $order);
420
421        $rsp = new xmlTag();
422
423        while ($rs->fetch()) {
424            $metaTag               = new xmlTag('meta');
425            $metaTag->type         = $rs->meta_type;
426            $metaTag->uri          = rawurlencode($rs->meta_id);
427            $metaTag->count        = $rs->count;
428            $metaTag->percent      = $rs->percent;
429            $metaTag->roundpercent = $rs->roundpercent;
430            $metaTag->CDATA($rs->meta_id);
431
432            $rsp->insertNode($metaTag);
433        }
434
435        return $rsp;
436    }
437
438    public static function setPostMeta($core, $get, $post)
439    {
440        if (empty($post['postId'])) {
441            throw new Exception('No post ID');
442        }
443
444        if (empty($post['meta']) && $post['meta'] != '0') {
445            throw new Exception('No meta');
446        }
447
448        if (empty($post['metaType'])) {
449            throw new Exception('No meta type');
450        }
451
452        # Get previous meta for post
453        $post_meta = $core->meta->getMetadata([
454            'meta_type' => $post['metaType'],
455            'post_id'   => $post['postId']]);
456        $pm = [];
457        while ($post_meta->fetch()) {
458            $pm[] = $post_meta->meta_id;
459        }
460
461        foreach ($core->meta->splitMetaValues($post['meta']) as $m) {
462            if (!in_array($m, $pm)) {
463                $core->meta->setPostMeta($post['postId'], $post['metaType'], $m);
464            }
465        }
466
467        return true;
468    }
469
470    public static function delMeta($core, $get, $post)
471    {
472        if (empty($post['postId'])) {
473            throw new Exception('No post ID');
474        }
475
476        if (empty($post['metaId']) && $post['metaId'] != '0') {
477            throw new Exception('No meta ID');
478        }
479
480        if (empty($post['metaType'])) {
481            throw new Exception('No meta type');
482        }
483
484        $core->meta->delPostMeta($post['postId'], $post['metaType'], $post['metaId']);
485
486        return true;
487    }
488
489    public static function searchMeta($core, $get)
490    {
491        $q        = !empty($get['q']) ? $get['q'] : null;
492        $metaType = !empty($get['metaType']) ? $get['metaType'] : null;
493
494        $sortby = !empty($get['sortby']) ? $get['sortby'] : 'meta_type,asc';
495
496        $rs = $core->meta->getMetadata(['meta_type' => $metaType]);
497        $rs = $core->meta->computeMetaStats($rs);
498
499        $sortby = explode(',', $sortby);
500        $sort   = $sortby[0];
501        $order  = isset($sortby[1]) ? $sortby[1] : 'asc';
502
503        switch ($sort) {
504            case 'metaId':
505                $sort = 'meta_id_lower';
506                break;
507            case 'count':
508                $sort = 'count';
509                break;
510            case 'metaType':
511                $sort = 'meta_type';
512                break;
513            default:
514                $sort = 'meta_type';
515        }
516
517        $rs->sort($sort, $order);
518
519        $rsp = new xmlTag();
520
521        while ($rs->fetch()) {
522            if (stripos($rs->meta_id, $q) === 0) {
523                $metaTag               = new xmlTag('meta');
524                $metaTag->type         = $rs->meta_type;
525                $metaTag->uri          = rawurlencode($rs->meta_id);
526                $metaTag->count        = $rs->count;
527                $metaTag->percent      = $rs->percent;
528                $metaTag->roundpercent = $rs->roundpercent;
529                $metaTag->CDATA($rs->meta_id);
530
531                $rsp->insertNode($metaTag);
532            }
533        }
534
535        return $rsp;
536    }
537
538    public static function setSectionFold($core, $get, $post)
539    {
540        if (empty($post['section'])) {
541            throw new Exception('No section name');
542        }
543        if ($core->auth->user_prefs->toggles === null) {
544            $core->auth->user_prefs->addWorkspace('toggles');
545        }
546        $section = $post['section'];
547        $status  = isset($post['value']) && ($post['value'] != 0);
548        if ($core->auth->user_prefs->toggles->prefExists('unfolded_sections')) {
549            $toggles = explode(',', trim($core->auth->user_prefs->toggles->unfolded_sections));
550        } else {
551            $toggles = [];
552        }
553        $k = array_search($section, $toggles);
554        if ($status) {
555            // true == Fold section ==> remove it from unfolded list
556            if ($k !== false) {
557                unset($toggles[$k]);
558            }
559        } else {
560            // false == unfold section ==> add it to unfolded list
561            if ($k === false) {
562                $toggles[] = $section;
563            };
564        }
565        $core->auth->user_prefs->toggles->put('unfolded_sections', join(',', $toggles));
566        return true;
567    }
568
569    public static function setDashboardPositions($core, $get, $post)
570    {
571        if (empty($post['id'])) {
572            throw new Exception('No zone name');
573        }
574        if (empty($post['list'])) {
575            throw new Exception('No sorted list of id');
576        }
577
578        if ($core->auth->user_prefs->dashboard === null) {
579            $core->auth->user_prefs->addWorkspace('dashboard');
580        }
581
582        $zone  = $post['id'];
583        $order = $post['list'];
584
585        $core->auth->user_prefs->dashboard->put($zone, $order);
586        return true;
587    }
588
589    public static function getModuleById($core, $get, $post)
590    {
591        if (empty($get['id'])) {
592            throw new Exception('No module ID');
593        }
594        if (empty($get['list'])) {
595            throw new Exception('No list ID');
596        }
597
598        $id     = $get['id'];
599        $list   = $get['list'];
600        $module = [];
601
602        if ($list == 'plugin-activate') {
603            $modules = $core->plugins->getModules();
604            if (empty($modules) || !isset($modules[$id])) {
605                throw new Exception('Unknow module ID');
606            }
607            $module = $modules[$id];
608        } elseif ($list == 'plugin-new') {
609            $store = new dcStore(
610                $core->plugins,
611                $core->blog->settings->system->store_plugin_url
612            );
613            $store->check();
614
615            $modules = $store->get();
616            if (empty($modules) || !isset($modules[$id])) {
617                throw new Exception('Unknow module ID');
618            }
619            $module = $modules[$id];
620        } else {
621            // behavior not implemented yet
622        }
623
624        if (empty($module)) {
625            throw new Exception('Unknow module ID');
626        }
627
628        $module = adminModulesList::sanitizeModule($id, $module);
629
630        $rsp     = new xmlTag('module');
631        $rsp->id = $id;
632
633        foreach ($module as $k => $v) {
634            $rsp->{$k}((string) $v);
635        }
636
637        return $rsp;
638    }
639}
Note: See TracBrowser for help on using the repository browser.

Sites map