Completed
Push — console-installer ( e2b50d...6ce748 )
by Adam
22:30
created

ParserLabel::addLabels()   F

Complexity

Conditions 34
Paths > 20000

Size

Total Lines 172
Code Lines 98

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 34
eloc 98
nc 92890
nop 5
dl 0
loc 172
rs 2
c 1
b 1
f 0

How to fix   Long Method    Complexity   

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
if (!defined('sugarEntry') || !sugarEntry) {
4
    die('Not A Valid Entry Point');
5
}
6
/**
7
 * SugarCRM Community Edition is a customer relationship management program developed by
8
 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
9
 *
10
 * SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd.
11
 * Copyright (C) 2011 - 2016 SalesAgility Ltd.
12
 *
13
 * This program is free software; you can redistribute it and/or modify it under
14
 * the terms of the GNU Affero General Public License version 3 as published by the
15
 * Free Software Foundation with the addition of the following permission added
16
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
17
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
18
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
19
 *
20
 * This program is distributed in the hope that it will be useful, but WITHOUT
21
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
22
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
23
 * details.
24
 *
25
 * You should have received a copy of the GNU Affero General Public License along with
26
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
27
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
28
 * 02110-1301 USA.
29
 *
30
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
31
 * SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
32
 *
33
 * The interactive user interfaces in modified source and object code versions
34
 * of this program must display Appropriate Legal Notices, as required under
35
 * Section 5 of the GNU Affero General Public License version 3.
36
 *
37
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
38
 * these Appropriate Legal Notices must retain the display of the "Powered by
39
 * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
40
 * reasonably feasible for  technical reasons, the Appropriate Legal Notices must
41
 * display the words  "Powered by SugarCRM" and "Supercharged by SuiteCRM".
42
 */
43
require_once 'modules/ModuleBuilder/parsers/ModuleBuilderParser.php';
44
45
class ParserLabel
46
{
47
    public function __construct($moduleName, $packageName = '')
48
    {
49
        $this->moduleName = $moduleName;
50
        if (!empty($packageName)) {
51
            $this->packageName = $packageName;
52
        }
53
    }
54
55
    /**
56
     * @deprecated deprecated since version 7.6, PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code, use __construct instead
57
     */
58
    public function ParserLabel($moduleName, $packageName = '')
59
    {
60
        $deprecatedMessage = 'PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code';
61
        if (isset($GLOBALS['log'])) {
62
            $GLOBALS['log']->deprecated($deprecatedMessage);
63
        } else {
64
            trigger_error($deprecatedMessage, E_USER_DEPRECATED);
65
        }
66
        self::__construct($moduleName, $packageName);
67
    }
68
69
    /**
70
     * Takes in the request params from a save request and processes
71
     * them for the save.
72
     *
73
     * @param array  $params   Labels as "label_".System label => Display label pairs
74
     * @param string $language Language key, for example 'en_us'
75
     *
76
     * @return bool
77
     */
78
    public function handleSave($params, $language)
79
    {
80
        $labels = array();
81
        foreach ($params as $key => $value) {
82
            if (preg_match('/^label_/', $key) && strcmp($value, 'no_change') != 0) {
83
                $labels [ strtoupper(substr($key, 6)) ] = SugarCleaner::cleanHtml(from_html($value), false);
84
            }
85
        }
86
        if (!empty($this->packageName)) {
87
            //we are in Module builder
88
89
            return self::addLabels($language, $labels, $this->moduleName, "custom/modulebuilder/packages/{$this->packageName}/modules/{$this->moduleName}/language");
90
        } else {
91
            return self::addLabels($language, $labels, $this->moduleName);
92
        }
93
    }
94
95
    /*
96
     * Remove a label from the language pack for a module
97
     * @param string $language      Language key, for example 'en_us'
98
     * @param string $label         The label to remove
99
     * @param string $labelvalue    The value of the label to remove
100
     * @param string $moduleName    Name of the module to which to add these labels
101
     * @param string $basepath      base path of the language file
102
     * @param string $forRelationshipLabel      whether this is a relationship label
103
     */
104
    public static function removeLabel($language, $label, $labelvalue, $moduleName, $basepath = null, $forRelationshipLabel = false)
105
    {
106
        $GLOBALS [ 'log' ]->debug("ParserLabel->removeLabels($language, \$label, \$labelvalue, $moduleName, $basepath );");
107
        if (is_null($basepath)) {
108
            $deployedModule = true;
109
            $basepath = "custom/modules/$moduleName/language";
110
            if ($forRelationshipLabel) {
111
                $basepath = "custom/modules/$moduleName/Ext/Language";
112
            }
113
            if (!is_dir($basepath)) {
114
                $GLOBALS ['log']->debug("$basepath is not a directory.");
115
116
                return false;
117
            }
118
        }
119
120
        $filename = "$basepath/$language.lang.php";
121
        if ($forRelationshipLabel) {
122
            $filename = "$basepath/$language.lang.ext.php";
123
        }
124
125
        $dir_exists = is_dir($basepath);
126
127
        $mod_strings = array();
128
129
        if ($dir_exists) {
130
            if (file_exists($filename)) {
131
                // obtain $mod_strings
132
                include $filename;
133
            } else {
134
                $GLOBALS ['log']->debug("file $filename does not exist.");
135
136
                return false;
137
            }
138
        } else {
139
            $GLOBALS ['log']->debug("directory $basepath does not exist.");
140
141
            return false;
142
        }
143
144
        $changed = false;
145
146
        if (isset($mod_strings[$label]) && $mod_strings[$label] == $labelvalue) {
147
            unset($mod_strings[$label]);
148
            $changed = true;
149
        }
150
151
        if ($changed) {
152
            if (!write_array_to_file('mod_strings', $mod_strings, $filename)) {
153
                $GLOBALS [ 'log' ]->fatal("Could not write $filename");
154
            } else {
155
                // if we have a cache to worry about, then clear it now
156
                if ($deployedModule) {
157
                    $GLOBALS ['log']->debug('PaserLabel->addLabels: clearing language cache');
158
                    $cache_key = 'module_language.'.$language.$moduleName;
159
                    sugar_cache_clear($cache_key);
160
                    LanguageManager::clearLanguageCache($moduleName, $language);
161
                }
162
            }
163
        }
164
165
        return true;
166
    }
167
168
    /*
169
     * Add a set of labels to the language pack for a module, deployed or undeployed
170
     * @param string $language      Language key, for example 'en_us'
171
     * @param array $labels         The labels to add in the form of an array of System label => Display label pairs
172
     * @param string $moduleName    Name of the module to which to add these labels
173
     * @param string $packageName   If module is undeployed, name of the package to which it belongs
0 ignored issues
show
Bug introduced by
There is no parameter named $packageName. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
174
     */
175
    public static function addLabels($language, $labels, $moduleName, $basepath = null, $forRelationshipLabel = false)
176
    {
177
        $GLOBALS [ 'log' ]->debug("ParserLabel->addLabels($language, \$labels, $moduleName, $basepath );");
178
        $GLOBALS [ 'log' ]->debug('$labels:'.print_r($labels, true));
179
180
        $deployedModule = false;
181
        if (is_null($basepath)) {
182
            $deployedModule = true;
183
            $basepath = "custom/modules/$moduleName/language";
184
            if ($forRelationshipLabel) {
185
                $basepath = "custom/modules/$moduleName/Ext/Language";
186
            }
187
            if (!is_dir($basepath)) {
188
                mkdir_recursive($basepath);
189
            }
190
        }
191
192
        $filename = "$basepath/$language.lang.php";
193
        if ($forRelationshipLabel) {
194
            $filename = "$basepath/$language.lang.ext.php";
195
        }
196
        $dir_exists = is_dir($basepath);
197
198
        $mod_strings = array();
199
200
        if ($dir_exists) {
201
            if (file_exists($filename)) {
202
                // obtain $mod_strings
203
                include $filename;
204
            } elseif ($forRelationshipLabel) {
205
                $fh = fopen($filename, 'a');
206
                fclose($fh);
207
            }
208
        } else {
209
            return false;
210
        }
211
212
        $changed = false;
213
214
        //$charset = (isset($app_strings['LBL_CHARSET'])) ? $app_strings['LBL_CHARSET'] : $GLOBALS['sugar_config']['default_charset'] ;
215
216
            foreach ($labels as $key => $value) {
217
                if (!isset($mod_strings [ $key ]) || strcmp($value, $mod_strings [ $key ]) != 0) {
218
                    $mod_strings [$key] = to_html(strip_tags(from_html($value))); // must match encoding used in view.labels.php
219
                    $changed = true;
220
                }
221
            }
222
223
        if ($changed) {
224
            $GLOBALS [ 'log' ]->debug("ParserLabel->addLabels: writing new mod_strings to $filename");
225
            $GLOBALS [ 'log' ]->debug('ParserLabel->addLabels: mod_strings='.print_r($mod_strings, true));
226
            if (!write_array_to_file('mod_strings', $mod_strings, $filename)) {
227
                $GLOBALS [ 'log' ]->fatal("Could not write $filename");
228
            } else {
229
                // if we have a cache to worry about, then clear it now
230
                if ($deployedModule) {
231
                    SugarCache::cleanOpcodes();
232
                    $GLOBALS [ 'log' ]->debug('PaserLabel->addLabels: clearing language cache');
233
                    $cache_key = 'module_language.'.$language.$moduleName;
234
                    sugar_cache_clear($cache_key);
235
                    LanguageManager::clearLanguageCache($moduleName, $language);
236
                }
237
            }
238
        }
239
240
        // Fix for bug #51
241
        // when the label is recreated it defaults back to the original value (In this case its "User").
242
243
        // Solution:
244
        // 1. Changes to the label names should go to custom/Extension/modules/{ModuleName}/Ext/Language
245
        // This is done in case different users edit the same Relationship concurrently.
246
        // The changes from custom/Extension/modules/{ModuleName}/Ext/Language
247
        // will overwrite stuff in custom/modules/{ModuleName}/Ext/Language/en_us.lang.ext.php after
248
        //  Quick Repair and Rebuild is applied.
249
        if ($forRelationshipLabel) {
250
            if (!empty($_POST[view_module]) && !empty($_POST[relationship_name]) && !empty($_POST[rhs_label]) && !empty($_POST[lhs_module])) {
251
                // 1. Overwrite custom/Extension/modules/{ModuleName}/Ext/Language
252
                $extension_basepath = 'custom/Extension/modules/'.$_POST[view_module].'/Ext/Language';
253
                mkdir_recursive($extension_basepath);
254
255
                $headerString = "<?php\n//THIS FILE IS AUTO GENERATED, DO NOT MODIFY\n";
256
                $out = $headerString;
257
258
                $extension_filename = "$extension_basepath/$language.custom".$_POST[relationship_name].'.php';
259
260
                $mod_strings = array();
261
                if (file_exists($extension_filename)) {
262
                    // obtain $mod_strings
263
                    include $extension_filename;
264
                }
265
266
                foreach ($labels as $key => $value) {
267
                    foreach ($mod_strings as $key_mod_string => $value_mod_string) {
268
                        if (strpos($key_mod_string, strtoupper($_POST[relationship_name])) !== false) {
269
                            $mod_strings[$key_mod_string] = to_html(strip_tags(from_html($_POST[rhs_label]))); // must match encoding used in view.labels.php
270
                        }
271
                    }
272
                }
273
274
                foreach ($mod_strings as $key => $val) {
275
                    $out .= override_value_to_string_recursive2('mod_strings', $key, $val);
276
                }
277
278
                try {
279
                    $file_contents = fopen($extension_filename, 'w');
280
                    fputs($file_contents, $out, strlen($out));
281
                    fclose($file_contents);
282
                } catch (Exception $e) {
283
                    $GLOBALS ['log']->fatal("Could not write $filename");
284
                    $GLOBALS ['log']->fatal('Exception '.$e->getMessage());
285
                }
286
287
                //2. Overwrite custom/Extension/modules/relationships/language/{ModuleName}.php
288
                // Also need to overwrite custom/Extension/modules/relationships/language/{ModuleName}.php
289
                // because whenever new relationship is created this place is checked by the system to get
290
                // all the label names
291
                $relationships_basepath = 'custom/Extension/modules/relationships/language';
292
                mkdir_recursive($relationships_basepath);
293
294
                $headerString = "<?php\n//THIS FILE IS AUTO GENERATED, DO NOT MODIFY\n";
295
                $out = $headerString;
296
297
                $relationships_filename = "$relationships_basepath/".$_POST[lhs_module].'.php';
298
299
                $mod_strings = array();
300
                if (file_exists($relationships_filename)) {
301
                    // obtain $mod_strings
302
                    include $relationships_filename;
303
                }
304
305
                $changed_mod_strings = false;
306
                foreach ($labels as $key => $value) {
307
                    foreach ($mod_strings as $key_mod_string => $value_mod_string) {
308
                        if (strpos($key_mod_string, strtoupper($_POST[relationship_name])) !== false) {
309
                            $mod_strings[$key_mod_string] = to_html(strip_tags(from_html($_POST[rhs_label]))); // must match encoding used in view.labels.php
310
                            $changed_mod_strings = true;
311
                        }
312
                    }
313
                }
314
315
                foreach ($mod_strings as $key => $val) {
316
                    $out .= override_value_to_string_recursive2('mod_strings', $key, $val);
317
                }
318
319
                $failed_to_write = false;
320
                try {
321
                    $file_contents = fopen($relationships_filename, 'w');
322
                    fputs($file_contents, $out, strlen($out));
323
                    fclose($file_contents);
324
                } catch (Exception $e) {
325
                    $GLOBALS ['log']->fatal("Could not write $filename");
326
                    $GLOBALS ['log']->fatal('Exception '.$e->getMessage());
327
                    $failed_to_write = true;
328
                }
329
330
                if ($changed_mod_strings) {
331
                    if (!$failed_to_write) {
332
                        // if we have a cache to worry about, then clear it now
333
                        if ($deployedModule) {
334
                            SugarCache::cleanOpcodes();
335
                            $GLOBALS ['log']->debug('PaserLabel->addLabels: clearing language cache');
336
                            $cache_key = 'module_language.'.$language.$moduleName;
337
                            sugar_cache_clear($cache_key);
338
                            LanguageManager::clearLanguageCache($moduleName, $language);
339
                        }
340
                    }
341
                }
342
            }
343
        }
344
345
        return true;
346
    }
347
348
    /**
349
     * Takes in the request params from a save request and processes
350
     * them for the save.
351
     *
352
     * @param $metadata
353
     * @param string $language Language key, for example 'en_us'
354
     */
355
    public function handleSaveRelationshipLabels($metadata, $language)
356
    {
357
        foreach ($metadata as $definition) {
358
            $labels = array();
359
            $labels[$definition [ 'system_label' ]] = $definition [ 'display_label' ];
360
            self::addLabels($language, $labels, $definition [ 'module' ], null, true);
361
        }
362
    }
363
364
    public function addLabelsToAllLanguages($labels)
365
    {
366
        $langs = get_languages();
367
        foreach ($langs as $lang_key => $lang_display) {
368
            $this->addLabels($lang_key, $labels, $this->moduleName);
369
        }
370
    }
371
}
372