Completed
Push — master ( a833c2...4c7587 )
by Adam
18:52
created

EmailTemplateFormBase::processImages()   C

Complexity

Conditions 13
Paths 8

Size

Total Lines 60
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 13
eloc 40
nc 8
nop 4
dl 0
loc 60
rs 6.3453
c 1
b 0
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
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3
/*********************************************************************************
4
 * SugarCRM Community Edition is a customer relationship management program developed by
5
 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
6
7
 * SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
8
 * Copyright (C) 2011 - 2014 Salesagility Ltd.
9
 *
10
 * This program is free software; you can redistribute it and/or modify it under
11
 * the terms of the GNU Affero General Public License version 3 as published by the
12
 * Free Software Foundation with the addition of the following permission added
13
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
14
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
15
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
16
 *
17
 * This program is distributed in the hope that it will be useful, but WITHOUT
18
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
20
 * details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License along with
23
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
24
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
25
 * 02110-1301 USA.
26
 *
27
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
28
 * SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
29
 *
30
 * The interactive user interfaces in modified source and object code versions
31
 * of this program must display Appropriate Legal Notices, as required under
32
 * Section 5 of the GNU Affero General Public License version 3.
33
 *
34
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
35
 * these Appropriate Legal Notices must retain the display of the "Powered by
36
 * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
37
 * reasonably feasible for  technical reasons, the Appropriate Legal Notices must
38
 * display the words  "Powered by SugarCRM" and "Supercharged by SuiteCRM".
39
 ********************************************************************************/
40
41
/*********************************************************************************
42
43
 * Description:  Base Form For Notes
44
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
45
 * All Rights Reserved.
46
 * Contributor(s): ______________________________________..
47
 ********************************************************************************/
48
49
50
class EmailTemplateFormBase {
51
52
    function __construct()
53
    {
54
55
    }
56
57
	function getFormBody($prefix, $mod='',$formname='', $size='30') {
58
59
60
		global $mod_strings;
61
62
		$temp_strings = $mod_strings;
63
64
		if(!empty($mod)) {
65
			global $current_language;
66
			$mod_strings = return_module_language($current_language, $mod);
67
		}
68
					global $app_strings;
69
					global $app_list_strings;
70
71
				$lbl_required_symbol = $app_strings['LBL_REQUIRED_SYMBOL'];
72
				$lbl_subject = $mod_strings['LBL_NOTE_SUBJECT'];
73
				$lbl_description = $mod_strings['LBL_NOTE'];
74
				$default_parent_type= $app_list_strings['record_type_default_key'];
75
76
$form = <<<EOF
77
				<input type="hidden" name="${prefix}record" value="">
78
				<input type="hidden" name="${prefix}parent_type" value="${default_parent_type}">
79
				<p>
80
				<table cellspacing="0" cellpadding="0" border="0">
81
				<tr>
82
				    <td scope="row">$lbl_subject <span class="required">$lbl_required_symbol</span></td>
83
				</tr>
84
				<tr>
85
				    <td ><input name='${prefix}name' size='${size}' maxlength='255' type="text" value=""></td>
86
				</tr>
87
				<tr>
88
				    <td scope="row">$lbl_description</td>
89
				</tr>
90
				<tr>
91
				    <td ><textarea name='${prefix}description' cols='${size}' rows='4' ></textarea></td>
92
				</tr>
93
				</table></p>
94
EOF;
95
96
	$javascript = new javascript();
97
	$javascript->setFormName($formname);
98
	$javascript->setSugarBean(new EmailTemplate());
99
	$javascript->addRequiredFields($prefix);
100
	$form .=$javascript->getScript();
101
	$mod_strings = $temp_strings;
102
	return $form;
103
	}
104
105
	function getForm($prefix, $mod='') {
106
		if(!empty($mod)) {
107
		global $current_language;
108
		$mod_strings = return_module_language($current_language, $mod);
109
	}else global $mod_strings;
110
		global $app_strings;
111
		global $app_list_strings;
112
113
		$lbl_save_button_title = $app_strings['LBL_SAVE_BUTTON_TITLE'];
114
		$lbl_save_button_key = $app_strings['LBL_SAVE_BUTTON_KEY'];
115
		$lbl_save_button_label = $app_strings['LBL_SAVE_BUTTON_LABEL'];
116
117
118
		$the_form = get_left_form_header($mod_strings['LBL_NEW_FORM_TITLE']);
119
$the_form .= <<<EOQ
120
121
				<form name="${prefix}EmailTemplateSave" onSubmit="return check_form('${prefix}EmailTemplateSave')" method="POST" action="index.php">
122
					<input type="hidden" name="${prefix}module" value="EmailTemplates">
123
					<input type="hidden" name="${prefix}action" value="Save">
124
EOQ;
125
		$the_form .= $this->getFormBody($prefix, $mod, "${prefix}EmailTemplateSave", "20");
126
$the_form .= <<<EOQ
127
				<p><input title="$lbl_save_button_title" accessKey="$lbl_save_button_key" class="button" type="submit" name="button" value="  $lbl_save_button_label  " ></p>
128
				</form>
129
130
EOQ;
131
132
		$the_form .= get_left_form_footer();
133
		$the_form .= get_validate_record_js();
134
135
136
		return $the_form;
137
	}
138
139
140
	function handleSave($prefix,$redirect=true, $useRequired=false, $useSiteURL = false, $entryPoint = 'download', $useUploadFolder = false)
141
	{
142
		require_once('include/formbase.php');
143
		require_once('include/upload_file.php');
144
		global $upload_maxsize;
145
		global $mod_strings;
146
		global $sugar_config;
147
148
		$focus = new EmailTemplate();
149
		if ($useRequired && !checkRequired($prefix, array_keys($focus->required_fields))) {
150
			return null;
151
		}
152
		$focus = populateFromPost($prefix, $focus);
153
		//process the text only flag
154
		if (isset($_POST['text_only']) && ($_POST['text_only'] == '1')) {
155
			$focus->text_only = 1;
156
		} else {
157
			$focus->text_only = 0;
158
		}
159
		if (!$focus->ACLAccess('Save')) {
160
			ACLController::displayNoAccess(true);
161
			sugar_cleanup(true);
162
		}
163
		if (!isset($_REQUEST['published'])) $focus->published = 'off';
164
165
		$this->handleAttachmentsProcessImages($focus, $redirect, $useSiteURL, $entryPoint, $useUploadFolder);
166
		return $focus;
167
	}
168
169
	public function handleAttachmentsProcessImages($focus, $redirect, $useSiteURL = false, $entryPoint = 'download', $useUploadFolder = false) {
170
		$return_id = $this->processImages($focus, $useSiteURL, $entryPoint, $useUploadFolder);
171
		return $this->handleAttachments($focus, $redirect, $return_id);
172
	}
173
174
	public function processImages(&$focus, $useSiteURL, $entryPoint, $useUploadFolder) {
175
		global $sugar_config;
176
		$preProcessedImages = array();
177
		$emailTemplateBodyHtml = from_html($focus->body_html);
178
		if (strpos($emailTemplateBodyHtml, '"cache/images/')) {
179
			$matches = array();
180
			preg_match_all('#<img[^>]*[\s]+src[^=]*=[\s]*["\']cache/images/(.+?)["\']#si', $emailTemplateBodyHtml, $matches);
181
			foreach ($matches[1] as $match) {
182
				$filename = urldecode($match);
183
				if ($filename != pathinfo($filename, PATHINFO_BASENAME)) {
184
					// don't allow paths there
185
					$emailTemplateBodyHtml = str_replace("cache/images/$match", "", $emailTemplateBodyHtml);
186
					continue;
187
				}
188
				$file_location = sugar_cached("images/{$filename}");
189
				$mime_type = pathinfo($filename, PATHINFO_EXTENSION);
190
191
				if (file_exists($file_location)) {
192
					//$id = create_guid();
193
194
					$note = new Note();
195
					$note->save();
196
					$id = $note->id;
197
198
					$newFileLocation = "upload://$id";
199
					if (!copy($file_location, $newFileLocation)) {
200
						$GLOBALS['log']->debug("EMAIL Template could not copy attachment to $newFileLocation");
201
					} else {
202
						if($useUploadFolder) {
203
							$secureLink = ($useSiteURL ? $sugar_config['site_url'] . '/' : '') . "public/{$id}";
204
							// create a copy with correct extension by mime type
205
							if(!file_exists('public')) {
206
								sugar_mkdir('public', 777);
207
							}
208
							if(copy($file_location, "public/{$id}.{$mime_type}")) {
209
								$secureLink .= ".{$mime_type}";
210
							}
211
						}
212
						else {
213
							$secureLink = ($useSiteURL ? $sugar_config['site_url'] . '/' : '') . "index.php?entryPoint=" . $entryPoint . "&type=Notes&id={$id}&filename=" . $match;
214
						}
215
216
						$emailTemplateBodyHtml = str_replace("cache/images/$match", $secureLink, $emailTemplateBodyHtml);
217
						//unlink($file_location);
218
						$preProcessedImages[$filename] = $id;
219
					}
220
				} // if
221
			} // foreach
222
		} // if
223
		if (isset($GLOBALS['check_notify'])) {
224
			$check_notify = $GLOBALS['check_notify'];
225
		} else {
226
			$check_notify = FALSE;
227
		}
228
		if($preProcessedImages) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $preProcessedImages of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
229
			$focus->body_html = $emailTemplateBodyHtml;
230
		}
231
		$return_id = $focus->save($check_notify);
232
		return $return_id;
233
	}
234
235
	public function handleAttachments($focus, $redirect, $return_id) {
236
		///////////////////////////////////////////////////////////////////////////////
237
		////	ATTACHMENT HANDLING
238
239
		///////////////////////////////////////////////////////////////////////////
240
		////	ADDING NEW ATTACHMENTS
241
242
		global $mod_strings;
243
244
		$max_files_upload = count($_FILES);
245
246
		if(!empty($focus->id)) {
247
			$note = new Note();
248
			$where = "notes.parent_id='{$focus->id}'";
249
			if(!empty($_REQUEST['old_id'])) { // to support duplication of email templates
250
				$where .= " OR notes.parent_id='".htmlspecialchars($_REQUEST['old_id'], ENT_QUOTES)."'";
251
			}
252
			$notes_list = $note->get_full_list("", $where, true);
253
		}
254
255
		if(!isset($notes_list)) {
256
			$notes_list = array();
257
		}
258
259
		if(!is_array($focus->attachments)) { // PHP5 does not auto-create arrays(). Need to initialize it here.
260
			$focus->attachments = array();
261
		}
262
		$focus->attachments = array_merge($focus->attachments, $notes_list);
263
264
265
266
		//for($i = 0; $i < $max_files_upload; $i++) {
267
268
		foreach ($_FILES as $key => $file)
269
		{
270
			$note = new Note();
271
272
			//Images are presaved above so we need to prevent duplicate files from being created.
273
			if( isset($preProcessedImages[$file['name']]) )
274
			{
275
			    $oldId = $preProcessedImages[$file['name']];
276
			    $note->id = $oldId;
277
			    $note->new_with_id = TRUE;
278
			    $GLOBALS['log']->debug("Image {$file['name']} has already been processed.");
279
            }
280
281
			$i=preg_replace("/email_attachment(.+)/",'$1',$key);
282
			$upload_file = new UploadFile($key);
283
284
			if(isset($_FILES[$key]) && $upload_file->confirm_upload() && preg_match("/^email_attachment/",$key)) {
285
				$note->filename = $upload_file->get_stored_file_name();
286
				$note->file = $upload_file;
287
				$note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'].': '.$note->file->original_file_name;
288
				if(isset($_REQUEST['embedded'.$i]) && !empty($_REQUEST['embedded'.$i])){
289
                  if($_REQUEST['embedded'.$i]=='true'){
290
				  	$note->embed_flag =true;
291
                  }
292
                  else{
293
                  	$note->embed_flag =false;
294
                  }
295
				}
296
				array_push($focus->attachments, $note);
297
			}
298
299
		}
300
301
		$focus->saved_attachments = array();
302
		foreach($focus->attachments as $note)
303
		{
304
			if( !empty($note->id) && $note->new_with_id === FALSE)
305
			{
306
				if(empty($_REQUEST['old_id']))
307
					array_push($focus->saved_attachments, $note); // to support duplication of email templates
308
				else
309
				{
310
					// we're duplicating a template with attachments
311
					// dupe the file, create a new note, assign the note to the new template
312
					$newNote = new Note();
313
					$newNote->retrieve($note->id);
314
					$newNote->id = create_guid();
315
					$newNote->parent_id = $focus->id;
316
					$newNote->new_with_id = true;
317
					$newNote->date_modified = '';
318
					$newNote->date_entered = '';
319
					/* BEGIN - SECURITY GROUPS */
320
					//Need to do this so that attachments show under an EmailTemplate correctly for a normal user
321
					global $current_user;
322
					$newNote->assigned_user_id = $current_user->id;
323
					/* END - SECURITY GROUPS */
324
					$newNoteId = $newNote->save();
325
326
					UploadFile::duplicate_file($note->id, $newNoteId, $note->filename);
327
				}
328
				continue;
329
			}
330
			$note->parent_id = $focus->id;
331
			$note->parent_type = 'Emails';
332
			$note->file_mime_type = $note->file->mime_type;
333
			/* BEGIN - SECURITY GROUPS */
334
			//Need to do this so that attachments show under an EmailTemplate correctly for a normal user
335
			global $current_user;
336
			$note->assigned_user_id = $current_user->id;
337
			/* END - SECURITY GROUPS */
338
			$note_id = $note->save();
339
			array_push($focus->saved_attachments, $note);
340
			$note->id = $note_id;
341
342
			if($note->new_with_id === FALSE)
343
    			$note->file->final_move($note->id);
344
    	    else
345
    	       $GLOBALS['log']->debug("Not performing final move for note id {$note->id} as it has already been processed");
346
		}
347
348
		////	END NEW ATTACHMENTS
349
		///////////////////////////////////////////////////////////////////////////
350
351
	///////////////////////////////////////////////////////////////////////////
352
	////	ATTACHMENTS FROM DOCUMENTS
353
	$count='';
354
	//_pp($_REQUEST);
355
	//_ppd(count($_REQUEST['document']));
356
	if(!empty($_REQUEST['document'])){
357
      $count = count($_REQUEST['document']);
358
    }
359
    else{
360
    	$count=10;
361
    }
362
363
	for($i=0; $i<$count; $i++) {
364
		if(isset($_REQUEST['documentId'.$i]) && !empty($_REQUEST['documentId'.$i])) {
365
			$doc = new Document();
366
			$docRev = new DocumentRevision();
367
			$docNote = new Note();
368
369
			$doc->retrieve($_REQUEST['documentId'.$i]);
370
			$docRev->retrieve($doc->document_revision_id);
371
372
			array_push($focus->saved_attachments, $docRev);
373
374
			$docNote->name = $doc->document_name;
375
			$docNote->filename = $docRev->filename;
376
			$docNote->description = $doc->description;
377
			$docNote->parent_id = $focus->id;
378
			$docNote->parent_type = 'Emails';
379
			$docNote->file_mime_type = $docRev->file_mime_type;
380
			$docId = $docNote = $docNote->save();
381
382
			UploadFile::duplicate_file($docRev->id, $docId, $docRev->filename);
383
		}
384
385
	}
386
387
	////	END ATTACHMENTS FROM DOCUMENTS
388
	///////////////////////////////////////////////////////////////////////////
389
390
		///////////////////////////////////////////////////////////////////////////
391
		////	REMOVE ATTACHMENTS
392
393
		if(isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
394
			foreach($_REQUEST['remove_attachment'] as $noteId) {
395
				$q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
396
				$focus->db->query($q);
397
			}
398
399
		}
400
401
		////	END REMOVE ATTACHMENTS
402
		///////////////////////////////////////////////////////////////////////////
403
	////	END ATTACHMENT HANDLING
404
	///////////////////////////////////////////////////////////////////////////////
405
406
        clear_register_value('select_array', $focus->object_name);
407
408
		if($redirect) {
409
		$GLOBALS['log']->debug("Saved record with id of ".$return_id);
410
			handleRedirect($return_id, "EmailTemplates");
411
		}else{
412
			return $focus;
413
		}
414
	}
415
416
}
417
?>