GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

Issues (4873)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

mediawiki/include/mediawikiPlugin.class.php (7 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * MediaWikiPlugin Class
4
 *
5
 * Copyright 2000-2011, Fusionforge Team
6
 * Copyright 2012, Franck Villaume - TrivialDev
7
 * Copyright (c) Enalean SAS 2014. All Rights Reserved.
8
 *
9
 * This file is a part of Tuleap.
10
 *
11
 * Tuleap is free software; you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation; either version 2 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * Tuleap is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 * along with Tuleap; if not, write to the Free Software
23
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24
 */
25
26
require_once 'common/plugin/Plugin.class.php';
27
require_once 'constants.php';
28
29
class MediaWikiPlugin extends Plugin {
30
31
    const SERVICE_SHORTNAME = 'plugin_mediawiki';
32
33
    function __construct ($id=0) {
34
            $this->Plugin($id) ;
35
            $this->name = "mediawiki" ;
36
            $this->text = "Mediawiki" ; // To show in the tabs, use...
37
            $this->_addHook("groupmenu") ;	// To put into the project tabs
38
            $this->_addHook("groupisactivecheckbox") ; // The "use ..." checkbox in editgroupinfo
39
            $this->_addHook("groupisactivecheckboxpost") ; //
40
            $this->_addHook("project_public_area");
41
            $this->_addHook("role_get");
42
            $this->_addHook("role_normalize");
43
            $this->_addHook("role_translate_strings");
44
            $this->_addHook("role_has_permission");
45
            $this->_addHook("role_get_setting");
46
            $this->_addHook("list_roles_by_permission");
47
            $this->_addHook("clone_project_from_template") ;
48
            $this->_addHook('group_delete');
49
            $this->_addHook('cssfile');
50
            $this->addHook(Event::SERVICE_ICON);
51
            $this->addHook(Event::SERVICES_ALLOWED_FOR_PROJECT);
52
            $this->addHook(Event::PROCCESS_SYSTEM_CHECK);
53
54
            $this->addHook('permission_get_name');
55
            $this->_addHook('service_is_used');
56
            $this->_addHook('register_project_creation');
57
58
            $this->_addHook(Event::SERVICE_REPLACE_TEMPLATE_NAME_IN_LINK);
59
            $this->_addHook(Event::RENAME_PROJECT, 'rename_project');
60
            $this->_addHook(Event::GET_SYSTEM_EVENT_CLASS, 'getSystemEventClass');
61
            $this->_addHook(Event::SYSTEM_EVENT_GET_TYPES_FOR_DEFAULT_QUEUE);
62
63
            //User permissions
64
            $this->_addHook('project_admin_remove_user');
65
            $this->_addHook('project_admin_change_user_permissions');
66
            $this->_addHook('SystemEvent_USER_RENAME', 'systemevent_user_rename');
67
            $this->_addHook('project_admin_ugroup_remove_user');
68
            $this->_addHook('project_admin_remove_user_from_project_ugroups');
69
            $this->_addHook('project_admin_ugroup_deletion');
70
            $this->_addHook(Event::HAS_USER_BEEN_DELEGATED_ACCESS, 'has_user_been_delegated_access');
71
            $this->addHook(Event::IS_SCRIPT_HANDLED_FOR_RESTRICTED);
72
            $this->addHook(Event::GET_SERVICES_ALLOWED_FOR_RESTRICTED);
73
74
            // Search
75
            $this->addHook(Event::LAYOUT_SEARCH_ENTRY);
76
            $this->addHook(Event::SEARCH_TYPES_PRESENTERS);
77
            $this->addHook(Event::SEARCH_TYPE);
78
79
            $this->_addHook('plugin_statistics_service_usage');
80
81
            $this->addHook(Event::SERVICE_CLASSNAMES);
82
            $this->addHook(Event::GET_PROJECTID_FROM_URL);
83
84
            // Stats plugin
85
            $this->addHook('plugin_statistics_disk_usage_collect_project');
86
            $this->addHook('plugin_statistics_disk_usage_service_label');
87
            $this->addHook('plugin_statistics_color');
88
89
            // Site admin link
90
            $this->_addHook('site_admin_option_hook', 'site_admin_option_hook', false);
91
92
            $this->addHook(Event::PROJECT_ACCESS_CHANGE);
93
            $this->addHook(Event::SITE_ACCESS_CHANGE);
94
95
            /**
96
             * HACK
97
             */
98
            require_once MEDIAWIKI_BASE_DIR.'/../../fusionforge_compat/include/fusionforge_compatPlugin.class.php';
99
            $ff_plugin = new fusionforge_compatPlugin();
100
            $ff_plugin->loaded();
101
    }
102
103
    public function getServiceShortname() {
104
        return self::SERVICE_SHORTNAME;
105
    }
106
107
    public function service_icon($params) {
108
        $params['list_of_icon_unicodes'][$this->getServiceShortname()] = '\e812';
109
    }
110
111
    /**
112
     * @see Plugin::getDependencies()
113
     */
114
    public function getDependencies() {
115
        return array('fusionforge_compat');
116
    }
117
118
        public function loaded() {
119
            parent::loaded();
120
            require_once 'plugins_utils.php';
121
            if(is_dir("/usr/share/mediawiki")){
122
                forge_define_config_item('src_path','mediawiki', "/usr/share/mediawiki");
123
                forge_define_config_item('mwdata_path', 'mediawiki', '$core/data_path/plugins/mediawiki');
124
                forge_define_config_item('projects_path', 'mediawiki', '$mediawiki/mwdata_path/projects');
125
                forge_define_config_item('master_path', 'mediawiki', '$mediawiki/mwdata_path/master');
126
                forge_define_config_item('enable_uploads', 'mediawiki', false);
127
                forge_set_config_item_bool('enable_uploads', 'mediawiki');
128
            }
129
        }
130
131
        public function layout_search_entry($params) {
132
            $project = $this->getProjectFromRequest();
133
            if ($this->isSearchEntryAvailable($project)) {
134
                $params['search_entries'][] = array(
135
                    'value'    => $this->name,
136
                    'label'    => $this->text,
137
                    'selected' => $this->isSearchEntrySelected($params['type_of_search']),
138
                );
139
                $params['hidden_fields'][] = array(
140
                    'name'  => 'group_id',
141
                    'value' => $project->getID()
142
                );
143
            }
144
        }
145
146
        /**
147
         * @see Event::SEARCH_TYPE
148
         */
149
        public function search_type($params) {
150
            $query   = $params['query'];
151
            $project = $query->getProject();
152
153
            if ($query->getTypeOfSearch() == $this->name && $this->isSearchEntryAvailable($project)) {
154
                if (! $project->isError()) {
155
                   util_return_to($this->getMediawikiSearchURI($project, $query->getWords()));
156
                }
157
            }
158
        }
159
160
        /**
161
         * @see Event::SEARCH_TYPES_PRESENTERS
162
         */
163
        public function search_types_presenters($params) {
164
            if ($this->isSearchEntryAvailable($params['project'])) {
165
                $params['project_presenters'][] = new Search_SearchTypePresenter(
166
                    $this->name,
167
                    $this->text,
168
                    array(),
169
                    $this->getMediawikiSearchURI($params['project'], $params['words'])
170
                );
171
            }
172
        }
173
174
    /**
175
     * @see Event::PROCCESS_SYSTEM_CHECK
176
     */
177
    public function proccess_system_check($params) {
178
        $this->getMediawikiMLEBExtensionManager()->activateMLEBForCompatibleProjects($params['logger']);
179
    }
180
181
        private function getMediawikiSearchURI(Project $project, $words) {
182
            return $this->getPluginPath().'/wiki/'. $project->getUnixName() .'/index.php?title=Special%3ASearch&search=' . urlencode($words) . '&go=Go';
183
        }
184
185
        private function isSearchEntryAvailable(Project $project = null) {
186
            if ($project && ! $project->isError()) {
187
                return $project->usesService(self::SERVICE_SHORTNAME);
188
            }
189
            return false;
190
        }
191
192
        private function isSearchEntrySelected($type_of_search) {
193
            return ($type_of_search == $this->name) || $this->isMediawikiUrl();
194
        }
195
196
        private function isMediawikiUrl() {
197
            return preg_match('%'.$this->getPluginPath().'/wiki/.*%', $_SERVER['REQUEST_URI']);
198
        }
199
200
        /**
201
         *
202
         * @return Project | null
203
         */
204
        private function getProjectFromRequest() {
205
            $matches = array();
206
            preg_match('%'.$this->getPluginPath().'/wiki/([^/]+)/.*%', $_SERVER['REQUEST_URI'], $matches);
207
            if (isset($matches[1])) {
208
                $project = ProjectManager::instance()->getProjectByUnixName($matches[1]);
209
210
                if ($project->isError()) {
211
                    $project = ProjectManager::instance()->getProject($matches[1]);
212
                }
213
214
                if (! $project->isError()) {
215
                    return $project;
216
                }
217
            }
218
            return null;
219
        }
220
221
        public function cssFile($params) {
222
            // Only show the stylesheet if we're actually in the Mediawiki pages.
223
            if (strpos($_SERVER['REQUEST_URI'], $this->getPluginPath()) === 0 ||
224
                strpos($_SERVER['REQUEST_URI'], '/widgets/') === 0) {
225
                echo '<link rel="stylesheet" type="text/css" href="/plugins/mediawiki/themes/default/css/style.css" />';
226
            }
227
        }
228
229
        public function showImage(Codendi_Request $request) {
230
            $project = $this->getProjectFromRequest();
231
            $user    = $request->getCurrentUser();
232
233
            if (! $project) {
234
                exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method showImage() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
235
            }
236
237
            if ((! $project->isPublic() || $user->isRestricted())
238
                && ! $project->userIsMember()
239
                && ! $user->isSuperUser()
240
                && ! $this->doesUserHavePermission($user)
241
            ) {
242
                exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method showImage() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
243
            }
244
245
            preg_match('%'.$this->getPluginPath().'/wiki/[^/]+/images(.*)%', $_SERVER['REQUEST_URI'], $matches);
246
            $file_location = $matches[1];
247
248
            $folder_location = '';
249
            if (is_dir('/var/lib/codendi/mediawiki/projects/' . $project->getUnixName())) {
250
                $folder_location = '/var/lib/codendi/mediawiki/projects/' . $project->getUnixName().'/images';
251
            } elseif (is_dir('/var/lib/codendi/mediawiki/projects/' . $project->getId())) {
252
                $folder_location = '/var/lib/codendi/mediawiki/projects/' . $project->getId().'/images';
253
            } else {
254
                exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method showImage() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
255
            }
256
257
            $file = $folder_location.$file_location;
258
            if (! file_exists($file)) {
259
                exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method showImage() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
260
            }
261
262
            $size = getimagesize($file);
263
            $fp   = fopen($file, 'r');
264
265
            if ($size and $fp) {
266
                header('Content-Type: '.$size['mime']);
267
                header('Content-Length: '.filesize($file));
268
269
                readfile($file);
270
                exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method showImage() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
271
            }
272
        }
273
274
        function process() {
275
        echo '<h1>Mediawiki</h1>';
276
        echo $this->getPluginInfo()->getpropVal('answer');
0 ignored issues
show
The method getpropVal does only exist in ArchiveDeletedItemsPlugi...and MediaWikiPluginInfo, but not in AdminDelegationPluginInf...fo and hudsonPluginInfo.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
277
        }
278
279
        function &getPluginInfo() {
280
        if (!is_a($this->pluginInfo, 'MediaWikiPluginInfo')) {
281
            require_once 'MediaWikiPluginInfo.class.php';
282
            $this->pluginInfo = new MediaWikiPluginInfo($this);
0 ignored issues
show
The call to MediaWikiPluginInfo::__construct() misses a required argument $incname.

This check looks for function calls that miss required arguments.

Loading history...
283
        }
284
        return $this->pluginInfo;
285
    }
286
287
        public function service_replace_template_name_in_link($params) {
288
            $params['link'] = preg_replace(
289
                '#/plugins/mediawiki/wiki/'.preg_quote($params['template']['name']).'(/|$)#',
290
                '/plugins/mediawiki/wiki/'. $params['project']->getUnixName().'$1',
291
                $params['link']
292
            );
293
        }
294
295
    function CallHook ($hookname, &$params) {
296
        if (isset($params['group_id'])) {
297
            $group_id=$params['group_id'];
298
        } elseif (isset($params['group'])) {
299
            $group_id=$params['group'];
300
        } else {
301
            $group_id=null;
302
        }
303
        if ($hookname == "groupmenu") {
304
            $project = group_get_object($group_id);
305
            if (!$project || !is_object($project)) {
306
                return;
307
            }
308
            if ($project->isError()) {
309
                return;
310
            }
311
            if (!$project->isProject()) {
312
                return;
313
            }
314
            if ( $project->usesPlugin ( $this->name ) ) {
315
                $params['TITLES'][]=$this->text;
316
                $params['DIRS'][]=util_make_url('/plugins/mediawiki/wiki/'.$project->getUnixName().'/index.php');
317
                $params['ADMIN'][]='';
318
                $params['TOOLTIPS'][] = _('Mediawiki Space');
319
            }
320
            (($params['toptab'] == $this->name) ? $params['selected']=(count($params['TITLES'])-1) : '' );
321
        } elseif ($hookname == "groupisactivecheckbox") {
322
            //Check if the group is active
323
            // this code creates the checkbox in the project edit public info page to activate/deactivate the plugin
324
            $group = group_get_object($group_id);
325
            echo "<tr>";
326
            echo "<td>";
327
            echo ' <input type="checkbox" name="use_mediawikiplugin" value="1" ';
328
            // checked or unchecked?
329
            if ( $group->usesPlugin ( $this->name ) ) {
330
                echo "checked";
331
            }
332
            echo " /><br/>";
333
            echo "</td>";
334
            echo "<td>";
335
            echo "<strong>Use ".$this->text." Plugin</strong>";
336
            echo "</td>";
337
            echo "</tr>";
338
        } elseif ($hookname == "groupisactivecheckboxpost") {
339
            // this code actually activates/deactivates the plugin after the form was submitted in the project edit public info page
340
            $group = group_get_object($group_id);
341
            $use_mediawikiplugin = getStringFromRequest('use_mediawikiplugin');
342
            if ( $use_mediawikiplugin == 1 ) {
343
                $group->setPluginUse ( $this->name );
344
            } else {
345
                $group->setPluginUse ( $this->name, false );
346
            }
347
        } elseif ($hookname == "project_public_area") {
348
            $project = group_get_object($group_id);
349
            if (!$project || !is_object($project)) {
350
                return;
351
            }
352
            if ($project->isError()) {
353
                return;
354
            }
355
            if (!$project->isProject()) {
356
                return;
357
            }
358
            if ( $project->usesPlugin ( $this->name ) ) {
359
                echo '<div class="public-area-box">';
360
                print '<a href="'. util_make_url ('/plugins/mediawiki/wiki/'.$project->getUnixName().'/index.php').'">';
361
                print html_abs_image(util_make_url ('/plugins/mediawiki/wiki/'.$project->getUnixName().'/skins/fusionforge/wiki.png'),'20','20',array('alt'=>'Mediawiki'));
362
                print ' Mediawiki';
363
                print '</a>';
364
                echo '</div>';
365
            }
366
        } elseif ($hookname == "role_get") {
367
            $role =& $params['role'] ;
368
369
            // Read access
370
            $right = new PluginSpecificRoleSetting ($role,
371
                                'plugin_mediawiki_read') ;
372
            $right->SetAllowedValues (array ('0', '1')) ;
373
            $right->SetDefaultValues (array ('Admin' => '1',
374
                             'Senior Developer' => '1',
375
                             'Junior Developer' => '1',
376
                             'Doc Writer' => '1',
377
                             'Support Tech' => '1')) ;
378
379
            // Edit privileges
380
            $right = new PluginSpecificRoleSetting ($role,
381
                                'plugin_mediawiki_edit') ;
382
            $right->SetAllowedValues (array ('0', '1', '2', '3')) ;
383
            $right->SetDefaultValues (array ('Admin' => '3',
384
                             'Senior Developer' => '2',
385
                             'Junior Developer' => '1',
386
                             'Doc Writer' => '3',
387
                             'Support Tech' => '0')) ;
388
389
            // File upload privileges
390
            $right = new PluginSpecificRoleSetting ($role,
391
                                'plugin_mediawiki_upload') ;
392
            $right->SetAllowedValues (array ('0', '1', '2')) ;
393
            $right->SetDefaultValues (array ('Admin' => '2',
394
                             'Senior Developer' => '2',
395
                             'Junior Developer' => '1',
396
                             'Doc Writer' => '2',
397
                             'Support Tech' => '0')) ;
398
399
            // Administrative tasks
400
            $right = new PluginSpecificRoleSetting ($role,
401
                                'plugin_mediawiki_admin') ;
402
            $right->SetAllowedValues (array ('0', '1')) ;
403
            $right->SetDefaultValues (array ('Admin' => '1',
404
                             'Senior Developer' => '0',
405
                             'Junior Developer' => '0',
406
                             'Doc Writer' => '0',
407
                             'Support Tech' => '0')) ;
408
409
        } elseif ($hookname == "role_normalize") {
410
            $role =& $params['role'] ;
411
            $new_sa =& $params['new_sa'] ;
412
            $new_pa =& $params['new_pa'] ;
413
414
            $projects = $role->getLinkedProjects() ;
415
            foreach ($projects as $p) {
416
                $role->normalizePermsForSection ($new_pa, 'plugin_mediawiki_read', $p->getID()) ;
417
                $role->normalizePermsForSection ($new_pa, 'plugin_mediawiki_edit', $p->getID()) ;
418
                $role->normalizePermsForSection ($new_pa, 'plugin_mediawiki_upload', $p->getID()) ;
419
                $role->normalizePermsForSection ($new_pa, 'plugin_mediawiki_admin', $p->getID()) ;
420
            }
421
        } elseif ($hookname == "role_translate_strings") {
422
            $right = new PluginSpecificRoleSetting ($role,
423
                                   'plugin_mediawiki_read') ;
424
            $right->setDescription (_('Mediawiki read access')) ;
425
            $right->setValueDescriptions (array ('0' => _('No reading'),
426
                                 '1' => _('Read access'))) ;
427
428
            $right = new PluginSpecificRoleSetting ($role,
429
                                   'plugin_mediawiki_edit') ;
430
            $right->setDescription (_('Mediawiki write access')) ;
431
            $right->setValueDescriptions (array ('0' => _('No editing'),
432
                                 '1' => _('Edit existing pages only'),
433
                                 '2' => _('Edit and create pages'),
434
                                 '3' => _('Edit, create, move, delete pages'))) ;
435
436
            $right = new PluginSpecificRoleSetting ($role,
437
                                   'plugin_mediawiki_upload') ;
438
            $right->setDescription (_('Mediawiki file upload')) ;
439
            $right->setValueDescriptions (array ('0' => _('No uploading'),
440
                                 '1' => _('Upload permitted'),
441
                                 '2' => _('Upload and re-upload'))) ;
442
443
            $right = new PluginSpecificRoleSetting ($role,
444
                                   'plugin_mediawiki_admin') ;
445
            $right->setDescription (_('Mediawiki administrative tasks')) ;
446
            $right->setValueDescriptions (array ('0' => _('No administrative access'),
447
                                 '1' => _('Edit interface, import XML dumps'))) ;
448
        } elseif ($hookname == "role_get_setting") {
449
            $role = $params['role'] ;
450
            $reference = $params['reference'] ;
451
            $value = $params['value'] ;
452
453
            switch ($params['section']) {
454
            case 'plugin_mediawiki_read':
455
                if ($role->hasPermission('project_admin', $reference)) {
456
                    $params['result'] = 1 ;
457
                } else {
458
                    $params['result'] =  $value ;
459
                }
460
                break ;
461
            case 'plugin_mediawiki_edit':
462
                if ($role->hasPermission('project_admin', $reference)) {
463
                    $params['result'] = 3 ;
464
                } else {
465
                    $params['result'] =  $value ;
466
                }
467
                break ;
468
            case 'plugin_mediawiki_upload':
469
                if ($role->hasPermission('project_admin', $reference)) {
470
                    $params['result'] = 2 ;
471
                } else {
472
                    $params['result'] =  $value ;
473
                }
474
                break ;
475
            case 'plugin_mediawiki_admin':
476
                if ($role->hasPermission('project_admin', $reference)) {
477
                    $params['result'] = 1 ;
478
                } else {
479
                    $params['result'] =  $value ;
480
                }
481
                break ;
482
            }
483
        } elseif ($hookname == "role_has_permission") {
484
            $value = $params['value'];
485
            switch ($params['section']) {
486
            case 'plugin_mediawiki_read':
487
                switch ($params['action']) {
488
                case 'read':
489
                default:
490
                    $params['result'] |= ($value >= 1) ;
491
                    break ;
492
                }
493
                break ;
494
            case 'plugin_mediawiki_edit':
495
                switch ($params['action']) {
496
                case 'editexisting':
497
                    $params['result'] |= ($value >= 1) ;
498
                    break ;
499
                case 'editnew':
500
                    $params['result'] |= ($value >= 2) ;
501
                    break ;
502
                case 'editmove':
503
                    $params['result'] |= ($value >= 3) ;
504
                    break ;
505
                }
506
                break ;
507
            case 'plugin_mediawiki_upload':
508
                switch ($params['action']) {
509
                case 'upload':
510
                    $params['result'] |= ($value >= 1) ;
511
                    break ;
512
                case 'reupload':
513
                    $params['result'] |= ($value >= 2) ;
514
                    break ;
515
                }
516
                break ;
517
            case 'plugin_mediawiki_admin':
518
                switch ($params['action']) {
519
                case 'admin':
520
                default:
521
                    $params['result'] |= ($value >= 1) ;
522
                    break ;
523
                }
524
                break ;
525
            }
526
        } elseif ($hookname == "list_roles_by_permission") {
527
            switch ($params['section']) {
528
            case 'plugin_mediawiki_read':
529
                switch ($params['action']) {
530
                case 'read':
531
                default:
532
                    $params['qpa'] = db_construct_qpa ($params['qpa'], ' AND perm_val >= 1') ;
533
                    break ;
534
                }
535
                break ;
536
            case 'plugin_mediawiki_edit':
537
                switch ($params['action']) {
538
                case 'editexisting':
539
                    $params['qpa'] = db_construct_qpa ($params['qpa'], ' AND perm_val >= 1') ;
540
                    break ;
541
                case 'editnew':
542
                    $params['qpa'] = db_construct_qpa ($params['qpa'], ' AND perm_val >= 2') ;
543
                    break ;
544
                case 'editmove':
545
                    $params['qpa'] = db_construct_qpa ($params['qpa'], ' AND perm_val >= 3') ;
546
                    break ;
547
                }
548
                break ;
549
            case 'plugin_mediawiki_upload':
550
                switch ($params['action']) {
551
                case 'upload':
552
                    $params['qpa'] = db_construct_qpa ($params['qpa'], ' AND perm_val >= 1') ;
553
                    break ;
554
                case 'reupload':
555
                    $params['qpa'] = db_construct_qpa ($params['qpa'], ' AND perm_val >= 2') ;
556
                    break ;
557
                }
558
                break ;
559
            case 'plugin_mediawiki_admin':
560
                switch ($params['action']) {
561
                case 'admin':
562
                default:
563
                    $params['qpa'] = db_construct_qpa ($params['qpa'], ' AND perm_val >= 1') ;
564
                    break ;
565
                }
566
                break ;
567
            }
568
        } elseif ($hookname == "clone_project_from_template") {
569
            $template = $params['template'] ;
570
            $project = $params['project'] ;
571
            $id_mappings = $params['id_mappings'] ;
572
573
            $sections = array ('plugin_mediawiki_read', 'plugin_mediawiki_edit', 'plugin_mediawiki_upload', 'plugin_mediawiki_admin') ;
574
575
            foreach ($template->getRoles() as $oldrole) {
576
                $newrole = RBACEngine::getInstance()->getRoleById ($id_mappings['role'][$oldrole->getID()]) ;
577
                $oldsettings = $oldrole->getSettingsForProject ($template) ;
578
579
                foreach ($sections as $section) {
580
                    if (isset ($oldsettings[$section][$template->getID()])) {
581
                        $newrole->setSetting ($section, $project->getID(), $oldsettings[$section][$template->getID()]) ;
582
                    }
583
                }
584
            }
585
        } elseif ($hookname == 'group_delete') {
586
            $projectId = $params['group_id'];
587
            $projectObject = group_get_object($projectId);
588
            if ($projectObject->usesPlugin($this->name)) {
589
                //delete the files and db schema
590
                $schema = 'plugin_mediawiki_'.$projectObject->getUnixName();
591
                // Sanitize schema name
592
                $schema = strtr($schema, "-", "_");
593
                db_query_params('drop schema $1 cascade', array($schema));
594
                exec('/bin/rm -rf '.forge_get_config('projects_path', 'mediawiki').'/'.$projectObject->getUnixName());
595
            }
596
        }
597
    }
598
599
    public function register_project_creation($params) {
600
        if ($this->serviceIsUsedInTemplate($params['template_id'])) {
601
            $mediawiki_instantiater = $this->getInstantiater($params['group_id']);
602
            if ($mediawiki_instantiater) {
603
                $mediawiki_instantiater->instantiateFromTemplate($params['ugroupsMapping']);
604
            }
605
        }
606
    }
607
608
    public function has_user_been_delegated_access($params) {
609
        if (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], $this->getPluginPath()) === 0) {
610
611
            /**
612
             * Only change the access rights to the affirmative.
613
             * Otherwise, we could overwrite a "true" value set by another plugin.
614
             */
615
            if ($this->doesUserHavePermission($params['user'])) {
616
                $params['can_access'] = true;
617
            }
618
        }
619
    }
620
621
    private function doesUserHavePermission(PFUser $user) {
622
        $forge_user_manager = $this->getForgeUserGroupPermissionsManager();
623
624
        return $forge_user_manager->doesUserHavePermission(
625
            $user,
626
            new User_ForgeUserGroupPermission_MediawikiAdminAllProjects()
627
        );
628
    }
629
630
    /**
631
     * @return User_ForgeUserGroupPermissionsManager
632
     */
633
    private function getForgeUserGroupPermissionsManager() {
634
        return new User_ForgeUserGroupPermissionsManager(
635
            new User_ForgeUserGroupPermissionsDao()
636
        );
637
    }
638
639
    /**
640
     * @see Event::IS_SCRIPT_HANDLED_FOR_RESTRICTED
641
     */
642
    public function is_script_handled_for_restricted($params) {
643
        $uri = $params['uri'];
644
        if (strpos($uri, $this->getPluginPath()) === 0) {
645
            $params['allow_restricted'] = true;
646
        }
647
    }
648
649
    /**
650
     * @see Event::GET_SERVICES_ALLOWED_FOR_RESTRICTED
651
     */
652
    public function get_services_allowed_for_restricted($params) {
653
        $params['allowed_services'][] = $this->getServiceShortname();
654
    }
655
656
    private function serviceIsUsedInTemplate($project_id) {
657
        $project_manager = ProjectManager::instance();
658
        $project         = $project_manager->getProject($project_id);
659
660
        return $project->usesService(self::SERVICE_SHORTNAME);
661
    }
662
663
    public function service_is_used($params) {
664
        if ($params['shortname'] == 'plugin_mediawiki' && $params['is_used']) {
665
            $mediawiki_instantiater = $this->getInstantiater($params['group_id']);
666
            if ($mediawiki_instantiater) {
667
                $mediawiki_instantiater->instantiate();
668
            }
669
        }
670
    }
671
672
    private function getInstantiater($group_id) {
673
        $project_manager = ProjectManager::instance();
674
        $project = $project_manager->getProject($group_id);
675
676
        if (! $project instanceof Project || $project->isError()) {
677
            return;
678
        }
679
680
        include dirname(__FILE__) .'/MediawikiInstantiater.class.php';
681
682
        return new MediaWikiInstantiater(
683
            $project,
684
            $this->getMediawikiManager(),
685
            $this->getMediawikiLanguageManager(),
686
            $this->getMediawikiVersionManager(),
687
            $this->getMediawikiMLEBExtensionManager()
688
        );
689
    }
690
691
    private function getMediawikiLanguageManager() {
692
        require_once 'MediawikiLanguageManager.php';
693
        require_once 'MediawikiLanguageDao.php';
694
695
        return new MediawikiLanguageManager(new MediawikiLanguageDao());
696
    }
697
698
    public function plugin_statistics_service_usage($params) {
699
        require_once 'MediawikiDao.class.php';
700
701
        $dao             = new MediawikiDao();
702
        $project_manager = ProjectManager::instance();
703
        $start_date      = $params['start_date'];
704
        $end_date        = $params['end_date'];
705
706
        $number_of_page                   = array();
707
        $number_of_page_between_two_dates = array();
708
        $number_of_page_since_a_date      = array();
709
        foreach($project_manager->getProjectsByStatus(Project::STATUS_ACTIVE) as $project) {
710
            if ($project->usesService('plugin_mediawiki')) {
711
                $number_of_page[] = $dao->getMediawikiPagesNumberOfAProject($project);
712
                $number_of_page_between_two_dates[] = $dao->getModifiedMediawikiPagesNumberOfAProjectBetweenStartDateAndEndDate($project, $start_date, $end_date);
713
                $number_of_page_since_a_date[] = $dao->getCreatedPagesNumberSinceStartDate($project, $start_date);
714
            }
715
        }
716
717
        $params['csv_exporter']->buildDatas($number_of_page, "Mediawiki Pages");
718
        $params['csv_exporter']->buildDatas($number_of_page_between_two_dates, "Modified Mediawiki pages");
719
        $params['csv_exporter']->buildDatas($number_of_page_since_a_date, "Number of created Mediawiki pages since start date");
720
    }
721
722
    public function project_admin_ugroup_deletion($params) {
723
        $project = $this->getProjectFromParams($params);
724
        $dao     = $this->getDao();
725
726
        if ($project->usesService(MediaWikiPlugin::SERVICE_SHORTNAME)) {
727
            $dao->deleteUserGroup($project->getID(), $params['ugroup_id']);
728
            $dao->resetUserGroups($project);
729
        }
730
    }
731
732
    public function project_admin_remove_user($params) {
733
        $this->updateUserGroupMapping($params);
734
    }
735
736
    public function project_admin_ugroup_remove_user($params) {
737
        $this->updateUserGroupMapping($params);
738
    }
739
740
    public function project_admin_change_user_permissions($params) {
741
        $this->updateUserGroupMapping($params);
742
    }
743
744
    public function project_admin_remove_user_from_project_ugroups($params) {
745
        $this->updateUserGroupMapping($params);
746
    }
747
748
    private function updateUserGroupMapping($params) {
749
        $user    = $this->getUserFromParams($params);
750
        $project = $this->getProjectFromParams($params);
751
        $dao     = $this->getDao();
752
753
        if ($project->usesService(MediaWikiPlugin::SERVICE_SHORTNAME)) {
754
            $dao->resetUserGroupsForUser($user, $project);
755
        }
756
    }
757
758
    public function systemevent_user_rename($params) {
759
        $user            = $params['user'];
760
        $projects        = ProjectManager::instance()->getAllProjectsButDeleted();
761
        foreach ($projects as $project) {
762
            if ($project->usesService(MediaWikiPlugin::SERVICE_SHORTNAME)) {
763
                $this->getDao()->renameUser($project, $params['old_user_name'], $user->getUnixName());
764
            }
765
        }
766
    }
767
768
    private function getUserFromParams($params) {
769
        $user_id  = $params['user_id'];
770
771
        return UserManager::instance()->getUserById($user_id);
772
    }
773
774
    private function getProjectFromParams($params) {
775
        $group_id = $params['group_id'];
776
777
        return ProjectManager::instance()->getProject($group_id);
778
    }
779
780
    private function getDao() {
781
        return new MediawikiDao();
782
    }
783
784
    /**
785
     * @return MediawikiManager
786
     */
787
    private function getMediawikiManager() {
788
        include_once 'MediawikiManager.class.php';
789
790
        return new MediawikiManager($this->getDao());
791
    }
792
793
    public function service_classnames(array $params) {
794
        include_once 'ServiceMediawiki.class.php';
795
        $params['classnames']['plugin_mediawiki'] = 'ServiceMediawiki';
796
    }
797
798
    public function rename_project($params) {
799
        $project         = $params['project'];
800
        $project_manager = ProjectManager::instance();
801
        $new_link        = '/plugins/mediawiki/wiki/'. $params['new_name'];
802
803
        if (! $project_manager->renameProjectPluginServiceLink($project->getID(), self::SERVICE_SHORTNAME, $new_link)) {
804
            $params['success'] = false;
805
            return;
806
        }
807
808
        $this->updateMediawikiDirectory($project);
809
        $this->clearMediawikiCache($project);
810
    }
811
812
    private function updateMediawikiDirectory(Project $project) {
813
        $logger         = new BackendLogger();
814
        $project_id_dir = forge_get_config('projects_path', 'mediawiki') . "/". $project->getID() ;
815
816
        if (is_dir($project_id_dir)) {
817
            return true;
818
        }
819
820
        $project_name_dir = forge_get_config('projects_path', 'mediawiki') . "/" . $project->getUnixName();
821
        if (is_dir($project_name_dir)) {
822
            exec("mv $project_name_dir $project_id_dir");
823
            return true;
824
        }
825
826
        $logger->error('Project Rename: Can\'t find mediawiki directory for project: '.$project->getID());
827
        return false;
828
    }
829
830
    private function clearMediawikiCache(Project $project) {
831
        $schema = $this->getDao()->getMediawikiDatabaseName($project, false);
832
        $logger = new BackendLogger();
833
834
        if ($schema) {
835
            $delete = $this->getDao()->clearPageCacheForSchema($schema);
836
            if (! $delete) {
837
                $logger->error('Project Clear cache: Can\'t delete mediawiki cache for schema: '.$schema);
838
            }
839
        } else  {
840
            $logger->error('Project Clear cache: Can\'t find mediawiki db for project: '.$project->getID());
841
        }
842
    }
843
844
    public function get_projectid_from_url($params) {
845
        $url = $params['url'];
846
847
        if (strpos($url,'/plugins/mediawiki/wiki/') === 0) {
848
            $pieces       = explode("/", $url);
849
            $project_name = $pieces[4];
850
851
            $dao          = $params['project_dao'];
852
            $dao_results  = $dao->searchByUnixGroupName($project_name);
853
            if ($dao_results->rowCount() < 1) {
854
                // project does not exist
855
                return false;
856
            }
857
858
            $project_data         = $dao_results->getRow();
859
            $params['project_id'] = $project_data['group_id'];
860
        }
861
    }
862
863
    public function plugin_statistics_disk_usage_collect_project($params) {
864
        $row     = $params['project_row'];
865
        $project = ProjectManager::instance()->getProject($row['group_id']);
866
867
        $project_for_parth = $this->getMediawikiManager()->instanceUsesProjectID($project) ?
868
            $row['group_id'] : $row['unix_group_name'];
869
870
        $path = $GLOBALS['sys_data_dir']. '/mediawiki/projects/'. $project_for_parth;
871
        $size = $params['DiskUsageManager']->getDirSize($path);
872
873
        $params['DiskUsageManager']->_getDao()->addGroup(
874
            $row['group_id'],
875
            self::SERVICE_SHORTNAME,
876
            $size,
877
            $_SERVER['REQUEST_TIME']
878
        );
879
    }
880
881
    public function plugin_statistics_disk_usage_service_label($params) {
882
        $params['services'][self::SERVICE_SHORTNAME] = 'Mediawiki';
883
    }
884
885
    public function plugin_statistics_color($params) {
886
        if ($params['service'] == self::SERVICE_SHORTNAME) {
887
            $params['color'] = 'lightsalmon';
888
        }
889
    }
890
891
    public function site_admin_option_hook() {
892
        echo '<li><a href="'.$this->getPluginPath().'/forge_admin?action=site_index'.'">Mediawiki</a></li>';
893
    }
894
895
    public function system_event_get_types_for_default_queue(array &$params) {
896
        require_once 'events/SytemEvent_MEDIAWIKI_SWITCH_TO_123.class.php';
897
898
        $params['types'] = array_merge($params['types'], array(
899
            SystemEvent_MEDIAWIKI_SWITCH_TO_123::NAME
900
        ));
901
    }
902
903
    public function getSystemEventClass($params) {
904
        require_once 'events/SytemEvent_MEDIAWIKI_SWITCH_TO_123.class.php';
905
906
        switch($params['type']) {
907
            case SystemEvent_MEDIAWIKI_SWITCH_TO_123::NAME:
908
                $params['class'] = 'SystemEvent_MEDIAWIKI_SWITCH_TO_123';
909
                $params['dependencies'] = array(
910
                    $this->getMediawikiMigrator(),
911
                    $this->getProjectManager(),
912
                    $this->getMediawikiVersionManager(),
913
                    $this->getMediawikiMLEBExtensionManager()
914
                );
915
                break;
916
            default:
917
                break;
918
        }
919
    }
920
921
    private function getMediawikiMigrator() {
922
        require_once 'Migration/MediawikiMigrator.php';
923
924
        return new Mediawiki_Migration_MediawikiMigrator();
925
    }
926
927
    private function getProjectManager() {
928
        return ProjectManager::instance();
929
    }
930
931
    public function permission_get_name($params) {
932
        if (!$params['name']) {
933
            switch($params['permission_type']) {
934
                case MediawikiManager::READ_ACCESS:
935
                    $params['name'] = 'Read';
936
                    break;
937
                case MediawikiManager::WRITE_ACCESS:
938
                    $params['name'] = 'Write';
939
                    break;
940
                default:
941
                    break;
942
            }
943
        }
944
    }
945
946
    /**
947
     * @see Event::PROJECT_ACCESS_CHANGE
948
     */
949
    public function project_access_change($params) {
950
        $project = ProjectManager::instance()->getProject($params['project_id']);
951
952
        $this->getMediawikiManager()->updateAccessControlInProjectChangeContext(
953
            $project,
954
            $params['old_access'],
955
            $params['access']
956
        );
957
    }
958
959
    /**
960
     * @see Event::SITE_ACCESS_CHANGE
961
     */
962
    public function site_access_change($params) {
963
        $this->getMediawikiManager()->updateSiteAccess($params['old_value']);
964
    }
965
966
    private function getMediawikiVersionManager() {
967
        require_once 'MediawikiVersionManager.php';
968
        require_once 'MediawikiVersionDao.php';
969
970
        return new MediawikiVersionManager(new MediawikiVersionDao());
971
    }
972
973
    /**
974
     * @return MediawikiMLEBExtensionManager
975
     */
976
    private function getMediawikiMLEBExtensionManager() {
977
        require_once 'MediawikiMLEBExtensionManager.php';
978
979
        return new MediawikiMLEBExtensionManager(
980
            $this->getMediawikiMigrator(),
981
            $this->getMediawikiMLEBExtensionDao(),
982
            $this->getProjectManager(),
983
            $this->getMediawikiVersionManager(),
984
            $this->getMediawikiLanguageManager()
985
        );
986
    }
987
988
    private function getMediawikiMLEBExtensionDao() {
989
        require_once 'MediawikiMLEBExtensionDao.php';
990
991
        return new MediawikiMLEBExtensionDao();
992
    }
993
994
}
995