init.php ➔ LibCaldav_upgrade()   B
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 72

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 4
nop 2
dl 0
loc 72
rs 7.9886
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
//-------------------------------------------------------------------------
3
// OVIDENTIA http://www.ovidentia.org
4
// Ovidentia is free software; you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation; either version 2, or (at your option)
7
// any later version.
8
//
9
// This program is distributed in the hope that it will be useful, but
10
// WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
// See the GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with this program; if not, write to the Free Software
16
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
17
// USA.
18
//-------------------------------------------------------------------------
19
/**
20
 * @license http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL)
21
 * @copyright Copyright (c) 2010 by CANTICO ({@link http://www.cantico.fr})
22
 */
23
require_once dirname(__FILE__).'/functions.php';
24
25
function LibCaldav_upgrade($version_base, $version_ini)
26
{
27
	require_once $GLOBALS['babInstallPath'].'utilit/devtools.php';
28
	require_once $GLOBALS['babInstallPath'].'utilit/functionalityincl.php';
29
	include_once $GLOBALS['babInstallPath']."utilit/eventincl.php";
30
	
31
	if (!@bab_functionality::includefile('CalendarBackend')) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class bab_functionality as the method includefile() does only exist in the following sub-classes of bab_functionality: Func_Archive, Func_Archive_Zip, Func_Archive_Zip_ZipArchive, Func_Archive_Zip_Zlib, Func_CalendarBackend, Func_CalendarBackend_Caldav, Func_CalendarBackend_Ovi, Func_Icons, Func_Icons_Default, Func_Ovml, Func_Ovml_Container, Func_Ovml_Container_Addon, Func_Ovml_Container_Article, Func_Ovml_Container_ArticleCategories, Func_Ovml_Container_ArticleCategory, Func_Ovml_Container_ArticleCategoryNext, Func_Ovml_Container_ArticleCategoryPrevious, Func_Ovml_Container_ArticleFiles, Func_Ovml_Container_ArticleNext, Func_Ovml_Container_ArticlePrevious, Func_Ovml_Container_ArticleTopic, Func_Ovml_Container_ArticleTopicNext, Func_Ovml_Container_ArticleTopicPrevious, Func_Ovml_Container_ArticleTopics, Func_Ovml_Container_Articles, Func_Ovml_Container_ArticlesHomePages, Func_Ovml_Container_CalendarCategories, Func_Ovml_Container_CalendarEventDomains, Func_Ovml_Container_CalendarEvents, Func_Ovml_Container_CalendarGroupEvents, Func_Ovml_Container_CalendarResourceEvents, Func_Ovml_Container_CalendarUserEvents, Func_Ovml_Container_Calendars, Func_Ovml_Container_DbDirectories, Func_Ovml_Container_DbDirectory, Func_Ovml_Container_DbDirectoryAcl, Func_Ovml_Container_DbDirectoryEntry, Func_Ovml_Container_DbDirectoryEntryFields, Func_Ovml_Container_DbDirectoryFields, Func_Ovml_Container_DbDirectoryMemberFields, Func_Ovml_Container_DbDirectoryMembers, Func_Ovml_Container_Delegation, Func_Ovml_Container_DelegationAdministrators, Func_Ovml_Container_DelegationItems, Func_Ovml_Container_DelegationManaged, Func_Ovml_Container_Delegations, Func_Ovml_Container_DelegationsCategories, Func_Ovml_Container_DelegationsCategory, Func_Ovml_Container_DelegationsManaged, Func_Ovml_Container_Faq, Func_Ovml_Container_FaqNext, Func_Ovml_Container_FaqPrevious, Func_Ovml_Container_FaqQuestion, Func_Ovml_Container_FaqQuestionNext, Func_Ovml_Container_FaqQuestionPrevious, Func_Ovml_Container_FaqQuestions, Func_Ovml_Container_FaqSubCategories, Func_Ovml_Container_FaqSubCategory, Func_Ovml_Container_Faqs, Func_Ovml_Container_File, Func_Ovml_Container_FileFields, Func_Ovml_Container_FileNext, Func_Ovml_Container_FilePrevious, Func_Ovml_Container_Files, Func_Ovml_Container_Folder, Func_Ovml_Container_FolderNext, Func_Ovml_Container_FolderPrevious, Func_Ovml_Container_Folders, Func_Ovml_Container_Forum, Func_Ovml_Container_ForumNext, Func_Ovml_Container_ForumPrevious, Func_Ovml_Container_Forums, Func_Ovml_Container_IfEqual, Func_Ovml_Container_IfGreaterThan, Func_Ovml_Container_IfGreaterThanOrEqual, Func_Ovml_Container_IfIsSet, Func_Ovml_Container_IfLessThan, Func_Ovml_Container_IfLessThanOrEqual, Func_Ovml_Container_IfNotEqual, Func_Ovml_Container_IfNotIsSet, Func_Ovml_Container_IfUserMemberOfGroups, Func_Ovml_Container_Multipages, Func_Ovml_Container_ObjectsInfo, Func_Ovml_Container_OrgPathToEntity, Func_Ovml_Container_OrgUserEntities, Func_Ovml_Container_OvmlArray, Func_Ovml_Container_OvmlArrayFields, Func_Ovml_Container_OvmlSoap, Func_Ovml_Container_ParentsArticleCategory, Func_Ovml_Container_Post, Func_Ovml_Container_PostFiles, Func_Ovml_Container_RecentArticles, Func_Ovml_Container_RecentComments, Func_Ovml_Container_RecentFaqQuestions, Func_Ovml_Container_RecentFiles, Func_Ovml_Container_RecentPosts, Func_Ovml_Container_RecentThreads, Func_Ovml_Container_SitemapEntries, Func_Ovml_Container_SitemapEntry, Func_Ovml_Container_SitemapPath, Func_Ovml_Container_Soap, Func_Ovml_Container_SubFolders, Func_Ovml_Container_Tags, Func_Ovml_Container_Thread, Func_Ovml_Container_TmProjects, Func_Ovml_Container_TmSpaces, Func_Ovml_Container_TmTaskFields, Func_Ovml_Container_TmTasks, Func_Ovml_Container_WaitingArticles, Func_Ovml_Container_WaitingComments, Func_Ovml_Container_WaitingFiles, Func_Ovml_Container_WaitingPosts, Func_Ovml_Function, Func_Ovml_Function_AOAddition, Func_Ovml_Function_AODivision, Func_Ovml_Function_AOModulus, Func_Ovml_Function_AOMultiplication, Func_Ovml_Function_AOSubtraction, Func_Ovml_Function_AddStyleSheet, Func_Ovml_Function_Addon, Func_Ovml_Function_Ajax, Func_Ovml_Function_ArticleTree, Func_Ovml_Function_FileTree, Func_Ovml_Function_Get, Func_Ovml_Function_GetCookie, Func_Ovml_Function_GetPageTitle, Func_Ovml_Function_GetPath, Func_Ovml_Function_GetSessionVar, Func_Ovml_Function_GetVar, Func_Ovml_Function_Header, Func_Ovml_Function_IfNotIsSet, Func_Ovml_Function_Include, Func_Ovml_Function_NextArticle, Func_Ovml_Function_Post, Func_Ovml_Function_PreviousArticle, Func_Ovml_Function_PreviousOrNextArticle, Func_Ovml_Function_PutArray, Func_Ovml_Function_PutSoapArray, Func_Ovml_Function_PutVar, Func_Ovml_Function_Recurse, Func_Ovml_Function_Request, Func_Ovml_Function_SetCookie, Func_Ovml_Function_SetSessionVar, Func_Ovml_Function_SitemapCustomNodeId, Func_Ovml_Function_SitemapMenu, Func_Ovml_Function_SitemapPosition, Func_Ovml_Function_SitemapUrl, Func_Ovml_Function_Translate, Func_Ovml_Function_UrlContent, Func_Ovml_Function_WebStat, Func_PortalAuthentication, Func_PortalAuthentication_AuthOvidentia, Func_SearchUi, Func_SitemapDynamicNode, Func_SitemapDynamicNode_Topic, Func_UserEditor, Func_WorkingHours, Func_WorkingHours_Ovidentia, Ovml_Container_Sitemap, bab_ArithmeticOperator, bab_Ovml_Container_Operator, bab_rgp. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
32
		return false;
33
	}
34
35
	$addonName = 'LibCaldav';
36
	$addonInfo = bab_getAddonInfosInstance($addonName);
37
	
38
	$addonPhpPath = $addonInfo->getPhpPath();
39
	
40
	$functionalities = new bab_functionalities();
41
	$functionalities->registerClass('Func_CalendarBackend_Caldav', $addonPhpPath . 'caldav.class.php');
42
43
	$addonInfo->removeAllEventListeners();
44
	$addonInfo->addEventListener('bab_eventBeforePeriodsCreated', 'caldav_onBeforePeriodsCreated', 'eventperiod.php');
45
	$addonInfo->addEventListener('bab_eventBeforePeriodsCreated', 'caldav_onBeforePeriodsCreated', 'eventperiod.php');
46
	$addonInfo->addEventListener('bab_eventCollectCalendarsBeforeDisplay', 'caldav_onCollectCalendarsBeforeDisplay', 'eventperiod.php');
47
	$addonInfo->addEventListener('bab_eventPageRefreshed', 'LibCaldav_onPageRefreshed', 'init.php');
48
	$addonInfo->addEventListener('bab_eventUserCreated', 'LibCaldav_onUserCreated', 'init.php');
49
	
50
	$tables = new bab_synchronizeSql();
51
	$tables->fromSqlFile(dirname(__FILE__).'/tables.sql');
52
	
53
	$registry = bab_getRegistryInstance();
54
	$registry->changeDirectory('/LibCaldav/');
55
	
56
	if ($serverUrl = $registry->getValue('defaultServerUrl'))
57
	{
58
		// move default server from registry to server table
59
		
60
		$userCalendarPath = $registry->getValue('defaultUserCalendarPath');
61
		
62
		$url = parse_url($serverUrl);
63
		if (isset($url['host']))
64
		{
65
			$host = $url['host'];
66
		} else {
67
			$host = 'Serveur';
68
		}
69
		$useuniqueid = 'false';
70
		global $babDB;
71
		$babDB->db_query('INSERT INTO libcaldav_servers (name, server_url, user_calendar_path, use_unique_id) 
72
				VALUES ('.$babDB->quote($host).', '.$babDB->quote($serverUrl).', '.$babDB->quote($userCalendarPath).', '.$babDB->quote($useuniqueid).')');
73
		
74
		$id_server = (int) $babDB->db_insert_id();
75
		
76
		$registry->removeKey('defaultUserCalendarPath');
77
		$registry->removeKey('defaultServerUrl');
78
		
79
		// browse users
80
		
81
		$registry->changeDirectory('/LibCaldav/Users/');
82
		$keys = array();
83
		while ($id_user = $registry->fetchChildDir())
84
		{
85
			$keys[] = $id_user;
86
		}
87
		
88
		foreach($keys as $dirkey)
89
		{
90
			$registry->changeDirectory("/LibCaldav/Users/$dirkey");
91
			$registry->setKeyValue('server', $id_server);
92
		}
93
	}
94
	
95
	return true;
96
}
97
98
$GLOBALS['LibCaldav_AdminSectionMenus'] = array(
99
	'CalDAV configuration' => $GLOBALS['babAddonUrl'].'configuration'
100
);
101
102
function LibCaldav_getAdminSectionMenus(&$url, &$text)
0 ignored issues
show
Unused Code introduced by
The parameter $url is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $text is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
103
{
104
	global $LibCaldav_AdminSectionMenus;
105
	if (list($text, $url) = each($LibCaldav_AdminSectionMenus))
106
	{
107
		$text =  caldav_translate($text);
108
		return true;
109
	}
110
	reset($LibCaldav_AdminSectionMenus);
111
	return false;
112
}
113
114
115
116
117
function LibCaldav_onDeleteAddon()
118
{
119
	require_once $GLOBALS['babInstallPath'].'utilit/functionalityincl.php';
120
	include_once $GLOBALS['babInstallPath']."utilit/eventincl.php";
121
	
122
	
123
	bab_removeEventListener('bab_eventBeforePeriodsCreated'			,'caldav_onBeforePeriodsCreated'			,'addons/LibCaldav/eventperiod.php');
124
	bab_removeEventListener('bab_eventCollectCalendarsBeforeDisplay','caldav_onCollectCalendarsBeforeDisplay'	,'addons/LibCaldav/eventperiod.php');
125
	bab_removeEventListener('bab_eventPageRefreshed', 'LibCaldav_onPageRefreshed', 'addons/LibCaldav/init.php');
126
	bab_removeEventListener('bab_eventUserCreated', 'LibCaldav_onUserCreated', 'addons/LibCaldav/init.php');
127
	
128
	$functionalities = new bab_functionalities();
129
	$functionalities->unregister('CalendarBackend/Caldav');
130
}
131
132
133
134
135
function LibCaldav_onPageRefreshed(bab_eventPageRefreshed $event)
0 ignored issues
show
Unused Code introduced by
The parameter $event is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
136
{
137
	// afficher les stats de connexion a caldav
138
	
139
	/*
140
	if (!isset($_SESSION['LibCaldav']['stats']))
141
	{
142
		return;
143
	}
144
	
145
	if (isset($_SESSION['LibCaldav']['stats']['pending'])) {
146
		$_SESSION['LibCaldav']['stats'][date('H:i:s')] = array_values($_SESSION['LibCaldav']['stats']['pending']);
147
		unset($_SESSION['LibCaldav']['stats']['pending']);
148
	}
149
	
150
	// get only the last 10 queries
151
	if (count($_SESSION['LibCaldav']['stats']) > 10)
152
	{
153
		$_SESSION['LibCaldav']['stats'] = array_slice($_SESSION['LibCaldav']['stats'], -10, 10, true);
154
	}
155
	
156
	
157
	bab_debug($_SESSION['LibCaldav']['stats'], DBG_TRACE, 'Caldav statistics');
158
	*/
159
}
160
161
162
163
function LibCaldav_onUserCreated(bab_eventUserCreated $event)
164
{
165
	$registry = bab_getRegistryInstance();
166
	$registry->changeDirectory('/LibCaldav/');
167
	
168
	if ($registry->getValue('default_backend'))
169
	{
170
		require_once $GLOBALS['babInstallPath'].'utilit/calapi.php';
171
		
172
		/* @var $caldav Func_CalendarBackend_Caldav */
173
		$caldav = bab_functionality::get('CalendarBackend/Caldav');
174
		
175
		bab_setPersonnalCalendarBackend($event->id_user, $caldav);
176
	}
177
	
178
	
179
}
180