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.
Completed
Push — develop ( fdaf56...d74b32 )
by
unknown
9s
created

LocaliseModelLanguage::copy()   C

Complexity

Conditions 8
Paths 9

Size

Total Lines 74
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 74
rs 6.2894
cc 8
eloc 38
nc 9
nop 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
 * @package     Com_Localise
4
 * @subpackage  model
5
 *
6
 * @copyright   Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
7
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
8
 */
9
10
defined('_JEXEC') or die;
11
12
jimport('joomla.filesystem.file');
13
jimport('joomla.client.helper');
14
jimport('joomla.access.rules');
15
16
/**
17
 * Language model.
18
 *
19
 * @since  1.0
20
 */
21
class LocaliseModelLanguage extends JModelAdmin
22
{
23
	protected $context = 'com_localise.language';
24
25
	/**
26
	 * Method to auto-populate the model state.
27
	 *
28
	 * @return  void
29
	 */
30
	protected function populateState()
31
	{
32
		$jinput = JFactory::getApplication()->input;
33
34
		$client = $jinput->get('client', 'site', 'cmd');
35
		$tag    = $jinput->get('tag', '', 'cmd');
36
		$id     = $jinput->get('id', '0', 'int');
37
38
		$this->setState('language.client', $client);
39
		$this->setState('language.tag', $tag);
40
		$this->setState('language.id', $id);
41
42
		parent::populateState();
43
	}
44
45
	/**
46
	 * Returns a Table object, always creating it.
47
	 *
48
	 * @param   string  $type    The table type to instantiate
49
	 * @param   string  $prefix  A prefix for the table class name. Optional.
50
	 * @param   array   $config  Configuration array for model. Optional.
51
	 *
52
	 * @return  JTable              A database object
53
	 */
54
	public function getTable($type = 'Localise', $prefix = 'LocaliseTable', $config = array())
55
	{
56
		return JTable::getInstance($type, $prefix, $config);
57
	}
58
59
	/**
60
	 * Method to get the record form.
61
	 *
62
	 * @param   array    $data      Data for the form.
63
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
64
	 *
65
	 * @return  mixed               A JForm object on success, false on failure
66
	 */
67
	public function getForm($data = array(), $loadData = true)
68
	{
69
		// Get the form.
70
		$form = $this->loadForm('com_localise.language', 'language', array('control'   => 'jform', 'load_data' => $loadData));
71
72
		// Make Client field readonly when the file exists
73
		if ($this->getState('language.id'))
74
		{
75
			$form->setFieldAttribute('client', 'readonly', 'true');
76
77
			$client = $form->getValue('client');
78
79
			if ($client == "installation")
80
			{
81
				$form->setFieldAttribute('locale', 'required', 'false');
82
				$form->setFieldAttribute('locale', 'disabled', 'true');
83
84
				$form->setFieldAttribute('weekEnd', 'disabled', 'true');
85
86
				$form->setFieldAttribute('firstDay', 'required', 'false');
87
				$form->setFieldAttribute('firstDay', 'disabled', 'true');
88
89
				$form->setFieldAttribute('authorEmail', 'disabled', 'true');
90
				$form->setFieldAttribute('authorUrl', 'disabled', 'true');
91
				$form->setFieldAttribute('copyright', 'disabled', 'true');
92
			}
93
		}
94
95
		return $form;
96
	}
97
98
	/**
99
	 * Method to get the data that should be injected in the form.
100
	 *
101
	 * @return   JObject  The data for the form.
102
	 */
103
	protected function loadFormData()
104
	{
105
		// Check the session for previously entered form data.
106
		$data = JFactory::getApplication()->getUserState('com_localise.edit.language.data', array());
107
108
		// Get the language data.
109
		$data = empty($data) ? $this->getItem() : new JObject($data);
110
111
		$data->joomlacopyright = sprintf("Copyright (C) 2005 - %s Open Source Matters. All rights reserved.", JFactory::getDate()->format('Y'));
112
113
		return $data;
114
	}
115
116
	/**
117
	 * Method to get the ftp form.
118
	 *
119
	 * @return  mixed  A JForm object on success, false on failure or not ftp
120
	 */
121 View Code Duplication
	public function getFormFtp()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
122
	{
123
		// Get the form.
124
		$form = $this->loadForm('com_localise.ftp', 'ftp');
125
126
		if (empty($form))
127
		{
128
			return false;
129
		}
130
131
		// Check for an error.
132
		if (JError::isError($form))
133
		{
134
			$this->setError($form->getMessage());
135
136
			return false;
137
		}
138
139
		return $form;
140
	}
141
142
	/**
143
	 * Method to get the language.
144
	 *
145
	 * @param   integer  $pk  The ID of the primary key.
146
	 *
147
	 * @return JObject
148
	 */
149
	public function getItem($pk = null)
150
	{
151
		$id     = $this->getState('language.id');
152
		$client = $this->getState('language.client');
153
		$tag    = $this->getState('language.tag');
154
155
		$language = new JObject;
156
157
		$language->id          = $id;
158
		$language->client      = $client;
159
		$language->tag         = $tag;
160
		$language->checked_out = 0;
161
162
		$params = JComponentHelper::getParams('com_localise');
163
		$language->author      = isset($language->author)
164
			? $language->author
165
			: $params->get('author');
166
		$language->authorEmail = isset($language->authorEmail)
167
			? $language->authorEmail
168
			: $params->get('authorEmail');
169
		$language->authorUrl   = isset($language->authorUrl)
170
			? $language->authorUrl
171
			: $params->get('authorUrl');
172
		$language->copyright   = isset($language->copyright)
173
			? $language->copyright
174
			: $params->get('copyright');
175
		$language->license     = isset($language->license)
176
			? $language->license
177
			: $params->get('license');
178
179
		if (!empty($id))
180
		{
181
			$table = $this->getTable();
182
			$table->load($id);
183
184
			$user = JFactory::getUser($table->checked_out);
185
186
			$language->setProperties($table->getProperties());
187
188
			if ($language->checked_out == JFactory::getUser()->id)
189
			{
190
				$language->checked_out = 0;
191
			}
192
193
			$language->editor   = JText::sprintf('COM_LOCALISE_TEXT_LANGUAGE_EDITOR', $user->name, $user->username);
194
			$language->writable = LocaliseHelper::isWritable($language->path);
195
196
			if (JFile::exists($language->path))
197
			{
198
				$xml = simplexml_load_file($language->path);
199
200
				if ($xml)
201
				{
202
					foreach ($xml->children() as $node)
203
					{
204
						if ($node->getName() == 'metadata')
205
						{
206
							// Metadata nodes
207
							foreach ($node->children() as $subnode)
208
							{
209
								$property            = $subnode->getName();
210
								$language->$property = (string) $subnode;
211
							}
212
						}
213
						else
214
						{
215
							// Main nodes
216
							$property = $node->getName();
217
218
							if ($property == 'copyright')
219
							{
220
								if (isset($language->joomlacopyright))
221
								{
222
									$language->copyright[] = (string) $node;
223
								}
224
								else
225
								{
226
									$language->copyright       = array();
227
									$language->joomlacopyright = (string) $node;
228
								}
229
							}
230
							else
231
							{
232
								$language->$property = (string) $node;
233
							}
234
						}
235
					}
236
237
					$language->copyright = implode('<br/>', $language->copyright);
238
				}
239
				else
240
				{
241
					$this->setError(JText::sprintf('COM_LOCALISE_ERROR_LANGUAGE_FILEEDIT', $language->path));
242
				}
243
			}
244
		}
245
246
		return $language;
247
	}
248
249
	/**
250
	 * Method to validate the form data.
251
	 *
252
	 * @param   JForm   $form   The form to validate against.
253
	 * @param   array   $data   The data to validate.
254
	 * @param   string  $group  The name of the field group to validate.
255
	 *
256
	 * @return  mixed  Array of filtered data if valid, false otherwise.
257
	 *
258
	 * @see     JFormRule
259
	 * @see     JFilterInput
260
	 * @since   12.2
261
	 */
262
	public function validate($form, $data, $group = null)
263
	{
264
		if ($data['client'] == "installation")
265
		{
266
			$form->setFieldAttribute('locale', 'required', 'false');
267
268
			$form->setFieldAttribute('firstDay', 'required', 'false');
269
		}
270
271
		return parent::validate($form, $data, $group);
272
	}
273
274
	/**
275
	 * Saves a language
276
	 *
277
	 * @param   array  $data  Language data
278
	 *
279
	 * @return bool
280
	 */
281
	public function save($data = array())
282
	{
283
		$id = $this->getState('language.id');
284
		$tag    = $data['tag'];
285
286
		// Trim whitespace in $tag
287
		$tag = JFilterInput::getInstance()->clean($tag, 'TRIM');
288
289
		// Check tag is correct
290
		if (strpos($tag, '-') == false)
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing strpos($tag, '-') of type integer to the boolean false. If you are specifically checking for 0, consider using something more explicit like === 0 instead.
Loading history...
291
		{
292
			$this->setError(JText::_('COM_LOCALISE_ERROR_LANGUAGE_TAG'));
293
294
			return false;
295
		}
296
297
		$partstag = explode('-', $tag);
298
299
		if (strlen($partstag[1]) > 2 || strtoupper($partstag[1]) != $partstag[1]
300
			|| strlen($partstag[0]) > 3 || strtolower($partstag[0]) != $partstag[0])
301
		{
302
			$this->setError(JText::_('COM_LOCALISE_ERROR_LANGUAGE_TAG'));
303
304
			return false;
305
		}
306
307
		// Checks that a custom language name has been entered
308
		if ($data['name'] == "[Name of language] ([Country name])")
309
		{
310
			$this->setError(JText::_('COM_LOCALISE_ERROR_LANGUAGE_NAME'));
311
312
			return false;
313
		}
314
315
		$client = $data['client'];
316
		$path   = constant('LOCALISEPATH_' . strtoupper($client)) . "/language/$tag/$tag.xml";
317
		$exists = JFile::exists($path);
318
		$parts = explode('.', $data['version']);
319
		$small_version = implode('.', array($parts[0],$parts[1]));
320
321
		if ($exists && !empty($id) || !$exists && empty($id))
322
		{
323
			$text = '';
324
			$text .= '<?xml version="1.0" encoding="utf-8"?>' . "\n";
325
			$text .= '<metafile version="' . $small_version . '" client="' . htmlspecialchars($client, ENT_COMPAT, 'UTF-8') . '">' . "\n";
326
			$text .= "\t" . '<tag>' . htmlspecialchars($tag, ENT_COMPAT, 'UTF-8') . '</tag>' . "\n";
327
			$text .= "\t" . '<name>' . htmlspecialchars($data['name'], ENT_COMPAT, 'UTF-8') . '</name>' . "\n";
328
			$text .= "\t" . '<version>' . htmlspecialchars($data['version'], ENT_COMPAT, 'UTF-8') . '</version>' . "\n";
329
			$text .= "\t" . '<creationDate>' . htmlspecialchars($data['creationDate'], ENT_COMPAT, 'UTF-8') . '</creationDate>' . "\n";
330
			$text .= "\t" . '<author>' . htmlspecialchars($data['author'], ENT_COMPAT, 'UTF-8') . '</author>' . "\n";
331
332
			// AuthorEmail, authorURL are not used in the installation
333
			if ($client != "installation")
334
			{
335
				$text .= "\t" . '<authorEmail>' . htmlspecialchars($data['authorEmail'], ENT_COMPAT, 'UTF-8') . '</authorEmail>' . "\n";
336
				$text .= "\t" . '<authorUrl>' . htmlspecialchars($data['authorUrl'], ENT_COMPAT, 'UTF-8') . '</authorUrl>' . "\n";
337
			}
338
339
			$text .= "\t" . '<copyright>' . htmlspecialchars($data['joomlacopyright'], ENT_COMPAT, 'UTF-8') . '</copyright>' . "\n";
340
341
			// Author copyright is not used in installation. It is present in CREDITS file
342
			if ($client != "installation")
343
			{
344
				$data['copyright'] = explode("\n", $data['copyright']);
345
346
				foreach ($data['copyright'] as $copyright)
347
				{
348
					if ($copyright)
349
					{
350
						$text .= "\t" . '<copyright>' . htmlspecialchars($copyright, ENT_COMPAT, 'UTF-8') . '</copyright>' . "\n";
351
					}
352
				}
353
			}
354
355
			$text .= "\t" . '<license>' . htmlspecialchars($data['license'], ENT_COMPAT, 'UTF-8') . '</license>' . "\n";
356
			$text .= "\t" . '<description>' . htmlspecialchars($data['description'], ENT_COMPAT, 'UTF-8') . '</description>' . "\n";
357
			$text .= "\t" . '<metadata>' . "\n";
358
			$text .= "\t\t" . '<name>' . htmlspecialchars($data['name'], ENT_COMPAT, 'UTF-8') . '</name>' . "\n";
359
			$text .= "\t\t" . '<tag>' . htmlspecialchars($data['tag'], ENT_COMPAT, 'UTF-8') . '</tag>' . "\n";
360
			$text .= "\t\t" . '<rtl>' . htmlspecialchars($data['rtl'], ENT_COMPAT, 'UTF-8') . '</rtl>' . "\n";
361
362
			// Locale, firstDay and weekEnd are not used in the installation
363
			if ($client != "installation")
364
			{
365
				$text .= "\t\t" . '<locale>' . htmlspecialchars($data['locale'], ENT_COMPAT, 'UTF-8') . '</locale>' . "\n";
366
				$text .= "\t\t" . '<firstDay>' . htmlspecialchars($data['firstDay'], ENT_COMPAT, 'UTF-8') . '</firstDay>' . "\n";
367
				$text .= "\t\t" . '<weekEnd>' . htmlspecialchars($data['weekEnd'], ENT_COMPAT, 'UTF-8') . '</weekEnd>' . "\n";
368
			}
369
370
			$text .= "\t" . '</metadata>' . "\n";
371
			$text .= "\t" . '<params />' . "\n";
372
			$text .= '</metafile>' . "\n";
373
374
			// Set FTP credentials, if given.
375
			JClientHelper::setCredentialsFromRequest('ftp');
376
			$ftp = JClientHelper::getCredentials('ftp');
377
378
			// Try to make the file writeable.
379 View Code Duplication
			if ($exists && !$ftp['enabled'] && JPath::isOwner($path) && !JPath::setPermissions($path, '0644'))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
380
			{
381
				$this->setError(JText::sprintf('COM_LOCALISE_ERROR_LANGUAGE_WRITABLE', $path));
382
383
				return false;
384
			}
385
386
			$return = JFile::write($path, $text);
387
388
			// Get the Localise parameters
389
			$params = JComponentHelper::getParams('com_localise');
390
391
			// Get the file save permission
392
			$fileSavePermission = $params->get('filesavepermission', '0444');
393
394
			// Try to make the template file unwriteable.
395 View Code Duplication
			if (!$ftp['enabled'] && JPath::isOwner($path) && !JPath::setPermissions($path, $fileSavePermission))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
396
			{
397
				$this->setError(JText::sprintf('COM_LOCALISE_ERROR_LANGUAGE_UNWRITABLE', $path));
398
399
				return false;
400
			}
401
			else
402
			{
403
				if (!$return)
404
				{
405
					$this->setError(JText::sprintf('COM_LOCALISE_ERROR_LANGUAGE_FILESAVE', $path));
406
407
					return false;
408
				}
409
			}
410
411
			$id = LocaliseHelper::getFileId($path);
412
413
			// Dummy call to populate state
414
			$this->getState('language.id');
415
416
			$this->setState('language.id', $id);
417
418
			// Bind the rules.
419
			$table = $this->getTable();
420
			$table->load($id);
421
422
			if (isset($data['rules']))
423
			{
424
				$rules = new JAccessRules($data['rules']);
425
				$table->setRules($rules);
426
			}
427
428
			// Check the data.
429
			if (!$table->check())
430
			{
431
				$this->setError($table->getError());
432
433
				return false;
434
			}
435
436
			// Store the data.
437
			if (!$table->store())
438
			{
439
				$this->setError($table->getError());
440
441
				return false;
442
			}
443
444
			return true;
445
		}
446
		else
447
		{
448
			$this->setError(JText::sprintf('COM_LOCALISE_ERROR_LANGUAGE_FILERESET', $path));
449
450
			return false;
451
		}
452
	}
453
454
	/**
455
	 * Remove languages
456
	 *
457
	 * @param   array  &$pks  An array of item ids.
458
	 *
459
	 * @return  boolean  true for success, false for failure
460
	 */
461
	public function delete(&$pks = null)
462
	{
463
		$params  = JComponentHelper::getParams('com_languages');
464
		$id      = $this->getState('language.id');
465
		$tag     = $this->getState('language.tag');
466
		$client  = $this->getState('language.client');
467
		$default = $params->get($client, 'en-GB');
468
		$path    = constant('LOCALISEPATH_' . strtoupper($client)) . "/language/$tag";
469
470
		if ($tag == $default)
471
		{
472
			$this->setError(JText::sprintf('COM_LOCALISE_CANNOT_REMOVE_DEFAULT_LANGUAGE', $path));
473
474
			return false;
475
		}
476
477
		// Check we're not trying to remove an installed langauge pack
478
		$db = JFactory::getDbo();
479
		$query = $db->getQuery(true)
480
			->select($db->quoteName('name'))
481
			->from($db->quoteName('#__extensions'))
482
			->where($db->quoteName('type') . ' = ' . $db->quote('package'))
483
			->where($db->quoteName('state') . ' = 0')
484
			->where($db->quoteName('element') . ' = "pkg_' . $tag . '"');
485
		$db->setQuery($query);
486
		$installedPack = $db->loadResult('name');
487
488
		if ($installedPack != null)
489
		{
490
			$this->setError(JText::sprintf('COM_LOCALISE_CANNOT_REMOVE_INSTALLED_LANGUAGE', $tag));
491
492
			return false;
493
		}
494
495
		if ($tag == 'en-GB')
496
		{
497
			$this->setError(JText::_('COM_LOCALISE_CANNOT_REMOVE_ENGLISH_LANGUAGE'));
498
499
			return false;
500
		}
501
502
		if (!JFactory::getUser()->authorise('localise.delete', $this->option . '.' . $id))
503
		{
504
			$this->setError(JText::_('COM_LOCALISE_CANNOT_REMOVE_LANGUAGE'));
505
506
			return false;
507
		}
508
509
		if (!JFolder::delete($path))
510
		{
511
			$this->setError(JText::sprintf('COM_LOCALISE_ERROR_LANGUAGES_REMOVE', "$path"));
512
513
			return false;
514
		}
515
516
		// Clear UserState for select.tag if the language deleted is selected in the filter.
517
		$app = JFactory::getApplication();
518
		$data = $app->getUserState('com_localise.select');
519
520
		if ($data['tag'] == $tag)
521
		{
522
			$data['tag'] = '';
523
			$app->setUserState('com_localise.select', $data);
524
		}
525
526
		$pks = array($id);
527
528
		return parent::delete($pks);
529
	}
530
531
	/**
532
	 * Method to copy the files from the reference lang to the translation language
533
	 *
534
	 * @return  boolean   true if copy is fine, false otherwise
535
	 *
536
	 * @since	4.0.17
537
	 */
538
	public function copy()
539
	{
540
		$app     = JFactory::getApplication();
541
		$params  = JComponentHelper::getParams('com_localise');
542
		$data    = $app->input->get('jform', array(), 'array');
543
544
		$id      = $app->getUserState('com_localise.edit.language.id');
0 ignored issues
show
Unused Code introduced by
$id is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
545
		$ref_tag = $params->get('reference', 'en-GB');
546
		$tag     = $data['tag'];
547
		$client  = $data['client'];
548
549
		$fromPath = constant('LOCALISEPATH_' . strtoupper($client)) . "/language/$ref_tag/";
550
		$toPath   = constant('LOCALISEPATH_' . strtoupper($client)) . "/language/$tag/";
551
552
		// Make sure new language and reference language are different
553
		// en-GB should be left alone
554
		if ($tag == $ref_tag || $tag == 'en-GB')
555
		{
556
			$app->enqueueMessage(JText::_('COM_LOCALISE_ERROR_LANGUAGE_COPY_FILES_NOT_PERMITTED'), 'error');
557
558
			return false;
559
		}
560
561
		// Are there already ini files in the destination folder?
562
		$inifiles = JFolder::files($toPath, ".ini$");
563
564
		if (!empty($inifiles))
565
		{
566
			$app->enqueueMessage(JText::sprintf('COM_LOCALISE_ERROR_LANGUAGE_NOT_ONLY_XML', $client, $tag), 'error');
567
568
			return false;
569
		}
570
571
		$refFiles = JFolder::files($fromPath);
572
573
		foreach ($refFiles as $file)
574
		{
575
			$ext = JFile::getExt($file);
576
577
			// We do not want to copy existing xmls
578
			if ($ext !== 'xml')
579
			{
580
				// Changing prefix for the copied files
581
				$destFile = str_replace($ref_tag, $tag, $file);
582
583
				if (!JFile::copy($fromPath . $file, $toPath . $destFile))
584
				{
585
					$app->enqueueMessage(JText::Sprintf('COM_LOCALISE_ERROR_LANGUAGE_COULD_NOT_COPY_FILES', $client, $ref_tag, $tag), 'error');
586
587
					return false;
588
				}
589
			}
590
		}
591
592
		// Modify localise.php to fit new tag
593
		$refclassname	= str_replace('-', '_', $ref_tag);
594
		$refclassname	= ucfirst($refclassname);
595
		$langclassname	= str_replace('-', '_', $tag);
596
		$langclassname	= ucfirst($langclassname);
597
		$refComment     = "* " . $ref_tag . " localise class";
598
		$langComment    = "* " . $tag . " localise class";
599
600
		$localisephpPath = constant('LOCALISEPATH_' . strtoupper($client)) . "/language/$tag/$tag.localise.php";
601
602
		if (JFile::exists($localisephpPath))
603
		{
604
			$language_data = file_get_contents($localisephpPath);
605
			$language_data = str_replace($refclassname, $langclassname, $language_data);
606
			$language_data = str_replace($refComment, $langComment, $language_data);
607
			JFile::write($localisephpPath, $language_data);
608
		}
609
610
		return true;
611
	}
612
}
613