1<?php
2/*
3 * e107 website system
4 *
5 * Copyright (C) 2008-2017 e107 Inc (e107.org)
6 * Released under the terms and conditions of the
7 * GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
8 *
9 * Download Plugin Administration UI
10 *
11*/
12
13if (!defined('e107_INIT')){ exit; }
14
15class plugin_download_admin extends e_admin_dispatcher
16{
17	/**
18	 * Format: 'MODE' => array('controller' =>'CONTROLLER_CLASS'[, 'index' => 'list', 'path' => 'CONTROLLER SCRIPT PATH', 'ui' => 'UI CLASS NAME child of e_admin_ui', 'uipath' => 'UI SCRIPT PATH']);
19	 * Note - default mode/action is autodetected in this order:
20	 * - $defaultMode/$defaultAction (owned by dispatcher - see below)
21	 * - $adminMenu (first key if admin menu array is not empty)
22	 * - $modes (first key == mode, corresponding 'index' key == action)
23	 * @var array
24	 */
25	protected $modes = array (
26		'main'		=> array (
27			'controller' 	=> 'download_main_admin_ui',
28			'path' 			=> null,
29			'ui' 			=> 'download_main_admin_form_ui',
30			'uipath' 		=> null
31		),
32		'cat'		=> array (
33			'controller' 	=> 'download_cat_ui',
34			'path' 			=> null,
35			'ui' 			=> 'download_cat_form_ui',
36			'uipath' 		=> null
37		),
38		'mirror'	=> array(
39			'controller' 	=> 'download_mirror_ui',
40			'path' 			=> null,
41			'ui' 			=> 'download_mirror_form_ui',
42			'uipath' 		=> null
43		),
44		'broken'	=> array(
45			'controller' 	=> 'download_broken_ui',
46			'path' 			=> null,
47			'ui' 			=> 'download_broken_form_ui',
48			'uipath' 		=> null
49		),
50	);
51
52	/* Both are optional
53	protected $defaultMode = null;
54	protected $defaultAction = null;
55	*/
56
57	/**
58	 * Format: 'MODE/ACTION' => array('caption' => 'Menu link title'[, 'url' => '{e_PLUGIN}release/admin_config.php', 'perm' => '0']);
59	 * Additionally, any valid e107::getNav()->admin() key-value pair could be added to the above array
60	 * @var array
61	 */
62	protected $adminMenu = array(
63		'main/list'			=> array('caption'=> LAN_MANAGE, 'perm' => 'P'),
64		'main/create' 		=> array('caption'=> LAN_CREATE, 'perm' => 'P'),
65
66		'other0' 		=> array('divider'=> true),
67
68		'cat/list'			=> array('caption'=> LAN_CATEGORIES, 'perm'=>'P'),
69		'cat/create' 		=> array('caption'=> LAN_CREATE_CATEGORY, 'perm' => 'Q'),
70
71		'other1' 		=> array('divider'=> true),
72
73		'mirror/list'		=> array('caption'=> DOWLAN_128, 'perm' => 'P'),
74		'mirror/create'		=> array('caption'=> DOWLAN_143, 'perm' => 'P'),
75
76		'other2' 		=> array('divider'=> true),
77
78		'broken/list' 		=> array('caption'=> LAN_DL_BROKENDOWNLOADSREPORTS, 'perm' => 'P'),
79
80		'other3' 		=> array('divider'=> true),
81
82		'main/settings' 	=> array('caption'=> LAN_PREFS, 'perm' => 'P'),
83	//	'main/maint' 		=> array('caption'=> DOWLAN_165, 'perm' => 'P'),
84		'main/limits'		=> array('caption'=> DOWLAN_112, 'perm' => 'P'),
85
86	//	'main/mirror'		=> array('caption'=> DOWLAN_128, 'perm' => 'P')
87	);
88/*
89	$var['main']['text'] = DOWLAN_29;
90	$var['main']['link'] = e_SELF;
91	$var['create']['text'] = DOWLAN_30;
92	$var['create']['link'] = e_SELF."?create";
93	$var['cat']['text'] = DOWLAN_31;
94	$var['cat']['link'] = e_SELF."?cat";
95	$var['cat']['perm'] = "Q";
96	$var['opt']['text'] = LAN_OPTIONS;
97	$var['opt']['link'] = e_SELF."?opt";
98	$var['maint']['text'] = DOWLAN_165;
99	$var['maint']['link'] = e_SELF."?maint";
100	$var['limits']['text'] = DOWLAN_112;
101	$var['limits']['link'] = e_SELF."?limits";
102	$var['mirror']['text'] = DOWLAN_128;
103	$var['mirror']['link'] = e_SELF."?mirror";
104	e107::getNav()->admin(DOWLAN_32, $action, $var);
105
106   unset($var);
107	$var['ulist']['text'] = DOWLAN_22;
108	$var['ulist']['link'] = e_SELF."?ulist";;
109	$var['filetypes']['text'] = DOWLAN_23;
110	$var['filetypes']['link'] = e_SELF."?filetypes";
111	$var['uopt']['text'] = LAN_OPTIONS;
112	$var['uopt']['link'] = e_SELF."?uopt";
113
114*/
115
116	/**
117	 * Optional, mode/action aliases, related with 'selected' menu CSS class
118	 * Format: 'MODE/ACTION' => 'MODE ALIAS/ACTION ALIAS';
119	 * This will mark active main/list menu item, when current page is main/edit
120	 * @var array
121	 */
122	protected $adminMenuAliases = array(
123		'main/edit'	=> 'main/list',
124		'cat/edit'	=> 'cat/list'
125	);
126
127	/**
128	 * Navigation menu title
129	 * @var string
130	 */
131	protected $menuTitle = LAN_PLUGIN_DOWNLOAD_NAME;
132}
133
134
135class download_cat_ui extends e_admin_ui
136{
137		protected $pluginTitle	    = LAN_PLUGIN_DOWNLOAD_NAME;
138		protected $pluginName	    = 'download';
139		protected $eventName        = 'download-category';
140		protected $table 		    = "download_category";
141		protected $pid			    = "download_category_id";
142		protected $perPage 		    = 0; //no limit
143
144		protected $batchCopy		= true;
145
146		// initiate as a parent/child tree.
147		protected $sortField		= 'download_category_order';
148		protected $sortParent       = 'download_category_parent';
149		protected $treePrefix       = 'download_category_name';
150	//	protected $orderStep		= // automatic
151	//	protected $listOrder		= // automatic
152
153		//legacy URL scheme
154		protected $url         		= array('route'=>'download/list/category', 'vars' => array('id' => 'download_category_id', 'name' => 'download_category_sef'), 'name' => 'download_category_name', 'description' => ''); // 'link' only needed if profile not provided.
155
156
157		protected $fields = array(
158			'checkboxes'						=> array('title'=> '',				'type' => null, 			'width' =>'5%', 'forced'=> TRUE, 'thclass'=>'center', 'class'=>'center'),
159			'download_category_icon' 			=> array('title'=> LAN_ICON,		'type' => 'method',			'width' => '5%', 'thclass' => 'center','class'=>'center','writeParms'=>'glyphs=1' ),
160			'download_category_id'				=> array('title'=> LAN_ID,			'type' => 'number',			'width' =>'5%', 'forced'=> TRUE, 'readParms'=>'link=sef&target=blank'),
161         	'download_category_name' 			=> array('title'=> LAN_TITLE,		'type' => 'text',		'data'=>'str',	'inline' => true, 'width' => 'auto', 'thclass' => 'left', 'writeParms'=>'size=xxlarge'),
162       		'download_category_sef' 			=> array('title'=> LAN_SEFURL,		'type' => 'text',		'data'=>'str',	'batch'=>true, 'inline' => true,	'width' => 'auto', 'thclass' => 'left', 'writeParms'=>'sef=download_category_name&size=xxlarge'),
163
164	     	'download_category_description' 	=> array('title'=> LAN_DESCRIPTION,	'type' => 'bbarea',		'data'=>'str',	'width' => '30%', 'readParms' => 'expand=...&truncate=50&bb=1'), // Display name
165		 	'download_category_parent' 			=> array('title'=> LAN_PARENT,		'type' => 'method',			'width' => '5%', 'batch' => TRUE, 'filter'=>TRUE),
166			'download_category_class' 			=> array('title'=> LAN_VISIBILITY,	'type' => 'userclass',		'inline' => true, 'width' => 'auto', 'data' => 'int', 'batch' => TRUE, 'filter'=>TRUE),
167			'download_category_order' 			=> array('title'=> LAN_ORDER,		'type' => 'number',	'nolist'=>true, 'data'=>'int',		'width' => '5%', 'thclass' => 'right', 'class'=> 'right' ),
168			'options' 							=> array('title'=> LAN_OPTIONS,		'type' => null,				'width' => '10%', 'forced'=>TRUE, 'thclass' => 'center last', 'class' => 'center', 'sort'=>1)
169		);
170
171		protected $fieldpref = array('download_category_icon', 'download_category_id', 'download_category_name', 'download_category_sef', 'download_category_class', 'download_category_order');
172
173	protected $downloadCats = array();
174
175	function init()
176	{
177		if(deftrue('e_DEBUG'))
178		{
179			$this->fields['download_category_order']['nolist'] = false;
180		}
181
182		$this->setDownloadCategoryTree();
183
184	}
185
186
187	private function setDownloadCategoryTree()
188	{
189
190
191		$sql = e107::getDb();
192		$qry = $this->getParentChildQry(true);
193		$sql->gen($qry);
194
195		$this->downloadCats[0] = LAN_NONE;
196
197		while($row = $sql->fetch())
198		{
199			$num = $row['_depth'] - 1;
200			$id = $row['download_category_id'];
201			$this->downloadCats[$id] = str_repeat("&nbsp;&nbsp;",$num).$row['download_category_name'];
202		}
203
204		if($this->getAction() === 'edit') // make sure parent is not the same as ID.
205		{
206			$r = $this->getId();
207			unset($this->downloadCats[$r]);
208		}
209
210	}
211
212
213
214	function getDownloadCategoryTree($id = false)
215	{
216
217		if($id)
218		{
219			return $this->downloadCats[$id];
220		}
221
222		return $this->downloadCats;
223	}
224
225}
226
227class download_cat_form_ui extends e_admin_form_ui
228{
229	public function download_category_parent($curVal,$mode)
230	{
231		// TODO - catlist combo without current cat ID in write mode, parents only for batch/filter
232		// Get UI instance
233		$controller = $this->getController();
234		switch($mode)
235		{
236			case 'read':
237				return e107::getParser()->toHTML($controller->getDownloadCategoryTree($curVal), false, 'TITLE');
238			break;
239
240			case 'write':
241				return $this->select('download_category_parent', $controller->getDownloadCategoryTree(), $curVal);
242			break;
243
244			case 'filter':
245			case 'batch':
246				return $controller->getDownloadCategoryTree();
247			break;
248		}
249	}
250
251
252
253
254	public function download_category_icon($curVal,$mode)
255	{
256
257		if(!empty($curVal) && strpos($curVal, chr(1)))
258		{
259			list($curVal,$tmp) = explode(chr(1),$curVal);
260		}
261
262		switch($mode)
263		{
264			case 'read':
265				return e107::getParser()->toIcon($curVal, array('legacy'=>'{e_IMAGE}icons/'));
266			break;
267
268			case 'write':
269				return $this->iconpicker('download_category_icon', $curVal,null,array('glyphs'=>true, 'legacyPath'=>'{e_IMAGE}icons/'));
270			break;
271
272			case 'filter':
273			case 'batch':
274				return null;
275			break;
276		}
277	}
278}
279
280
281
282
283
284
285
286class download_main_admin_ui extends e_admin_ui
287{
288		// required
289		protected $pluginTitle = LAN_PLUGIN_DOWNLOAD_NAME;
290		protected $pluginName = 'download';
291		protected $eventName = 'download';
292		protected $table = "download"; // DB Table, table alias is supported. Example: 'r.release'
293		protected $listQry = "SELECT m.*, c.download_category_sef, u.user_id,u.user_name FROM #download AS m
294			lEFT JOIN #download_category AS c on m.download_category = c.download_category_id LEFT JOIN #user AS u ON m.download_author = u.user_id "; // without any Order or Limit.
295
296		//required - default column user prefs
297		protected $fieldpref = array('checkboxes', 'download_image', 'download_id', 'download_datestamp', 'download_category', 'download_name', 'download_active', 'download_class', 'fb_order', 'options');
298
299		// Security modes
300		protected $security_options = array(
301			'none' => LAN_DL_SECURITY_MODE_NONE,
302			'nginx-secure_link_md5' => LAN_DL_SECURITY_MODE_NGINX_SECURELINKMD5
303		);
304
305		// optional - required only in case of e.g. tables JOIN. This also could be done with custom model (set it in init())
306		//protected $editQry = "SELECT * FROM #release WHERE release_id = {ID}";
307
308		// required - if no custom model is set in init() (primary id)
309		protected $pid = "download_id";
310
311		// optional
312		protected $perPage = 10;
313
314		// default - true - TODO - move to displaySettings
315		protected $batchDelete = true;
316
317		/** @deprecated see writeParms() on download_id below. */
318	//	protected $url         		= array('route'=>'download/view/item', 'vars' => array('id' => 'download_id', 'name' => 'download_sef'), 'name' => 'download_name', 'description' => ''); // 'link' only needed if profile not provided.
319
320
321
322    	protected  $fields = array(
323			'checkboxes'				=> array('title'=> '', 					'type' => null,			'data' => null,			'width'=>'5%', 		'thclass' =>'center', 'forced'=> TRUE,  'class'=>'center', 'toggle' => 'e-multiselect'),
324			'download_id'				=> array('title'=> LAN_ID, 				'type' => 'text',		'data' => 'int',		'width'=>'5%',		'thclass' => '',	'forced'=> TRUE, 'readParms'=>'url=item&target=blank', 'primary'=>TRUE/*, 'noedit'=>TRUE*/), //Primary ID is not editable
325            'download_name' 			=> array('title'=> LAN_TITLE, 			'type' => 'text', 		'data' => 'str',		'inline'=>true, 'width' => 'auto',	'thclass' => ''),
326            'download_url'	   			=> array('title'=> DOWLAN_13, 			'type' => 'url', 	'data' => 'str',		'width'=>'auto',	'thclass' => '', 'batch' => TRUE, 'filter'=>TRUE),
327		    'download_sef'	   			=> array('title'=> LAN_SEFURL, 			'type' => 'text', 	'inline'=>true, 'data' => 'str',		'width'=>'auto',	'thclass' => '', 'batch' => TRUE, 'filter'=>TRUE, 'writeParms'=>'sef=download_name'),
328		  	'download_keywords'	    	=> array('title'=> LAN_KEYWORDS, 		'type' => 'tags', 	'inline'=>true, 'data' => 'str',		'width'=>'auto',	'thclass' => ''),
329
330			'download_author' 			=> array('title'=> LAN_AUTHOR,			'type' => 'user', 		'data' => 'str',		'width' => 'auto',	'thclass' => 'left'),
331         	'download_author_email' 	=> array('title'=> DOWLAN_16, 			'type' => 'email', 		'data' => 'str',		'width' => 'auto',	'thclass' => 'left'),
332         	'download_author_website' 	=> array('title'=> DOWLAN_17, 			'type' => 'url', 		'data' => 'str',		'width' => 'auto',	'thclass' => 'left'),
333            'download_description' 		=> array('title'=> LAN_DESCRIPTION,		'type' => 'bbarea',			'width' => '30%', 'readParms' => 'expand=...&truncate=50&bb=1'), // Display name
334
335		 	'download_filesize' 		=> array('title'=> DOWLAN_66,			'type' => 'text', 		'data' => 'str',		'width' => 'auto',	'thclass' => 'right', 'class' => 'right'),
336		 	'download_requested' 		=> array('title'=> DOWLAN_29, 			'type' => 'text', 		'data' => 'str',		'width' => 'auto',	'thclass' => 'right', 'class' => 'right'),
337			'download_category' 		=> array('title'=> LAN_CATEGORY,		'type' => 'dropdown',	'width' => 'auto',	'inline'=>true, 'batch' => TRUE, 'filter'=>TRUE),
338			'download_active'			=> array('title'=> DOWLAN_21,			'type' => 'method', 		'data' => 'int',		'width' => '5%',	'thclass' => 'center', 'class' => 'center',	'batch' => TRUE, 'filter'=>TRUE, 'noedit' => true),
339			'download_datestamp' 		=> array('title'=> LAN_DATE, 			'type' => 'datestamp', 	'data' => 'int',		'width' => 'auto',	'thclass' => '', 'readParms' => 'long', 'writeParms' => ''),
340
341			'download_thumb' 			=> array('title'=> DOWLAN_20,			'type' => 'image', 		'data' => 'str',		'width' => '100px',	'thclass' => 'center', 'class'=>'center', 'readParms'=>'thumb=60&thumb_urlraw=0&thumb_aw=60&legacyPath={e_FILE}downloadthumbs', 'writeParms' => 'media=download_image', 'readonly'=>TRUE ),
342			'download_image' 			=> array('title'=> DOWLAN_19,			'type' => 'image', 		'data' => 'str',		'width' => '100px',	'thclass' => 'center', 'class'=>'center', 'readParms'=>'thumb=60&thumb_urlraw=0&thumb_aw=60&legacyPath={e_FILE}downloadimages', 'writeParms' => 'media=download_image', 'readonly'=>TRUE,	'batch' => FALSE, 'filter'=>FALSE),
343			'download_comment'			=> array('title'=> DOWLAN_102,			'type' => 'boolean', 		'data' => 'int',		'width' => '5%',	'thclass' => 'center',	'batch' => TRUE, 'filter'=>TRUE, 'noedit' => true),
344
345			'download_class' 			=> array('title'=> DOWLAN_113,			'type' => 'userclass',		'width' => 'auto', 'inline'=>true, 'data' => 'int','batch' => TRUE, 'filter'=>TRUE),
346			'download_visible' 			=> array('title'=> LAN_VISIBILITY,		'type' => 'userclass',	'inline'=>true,	'width' => 'auto', 'data' => 'int', 'batch' => TRUE, 'filter'=>TRUE),
347
348			'download_mirror' 			=> array('title'=> DOWLAN_128,			'type' => 'text', 		'data' => 'str',		'width' => '10%',	'thclass' => 'center' ),
349			'download_mirror_type' 		=> array('title'=> DOWLAN_195,			'type' => 'method', 		'data' => 'str',		'width' => '10%',	'thclass' => 'center' ),
350
351
352		//	'download_order' 	=> array('title'=> LAN_ORDER,	'type' => 'text',			'width' => '5%', 'thclass' => 'left' ),
353			'issue' 					=> array('title'=> 'Issue', 		'type' => 'method', 		'data' => null,	'nolist'=>TRUE, 'noedit'=>TRUE, 'filter'=>TRUE),
354			'options' 					=> array('title'=> LAN_OPTIONS, 		'type' => null, 		'data' => null,			'width' => '10%',	'thclass' => 'center last', 'class' => 'center last', 'forced'=>TRUE)
355		);
356
357
358		protected $action 		= array();
359		protected $subAction 	= array();
360		protected $id			= "";
361
362
363
364/*
365$columnInfo = array(
366		 "checkboxes"	   			=> array("title" => "", "forced"=> TRUE, "width" => "3%", "thclass" => "center first", "toggle" => "dl_selected"),
367         "download_id"              => array("title"=>LAN_ID,  "type"=>"", "width"=>"auto", "thclass"=>"", "forced"=>true),
368         "download_name"            => array("title"=>DOWLAN_12,  "type"=>"", "width"=>"auto", "thclass"=>""),
369         "download_url"             => array("title"=>DOWLAN_13,  "type"=>"", "width"=>"auto", "thclass"=>""),
370         "download_author"          => array("title"=>DOWLAN_15,  "type"=>"", "width"=>"auto", "thclass"=>""),
371         "download_author_email"    => array("title"=>DOWLAN_16,  "type"=>"", "width"=>"auto", "thclass"=>""),
372         "download_author_website"  => array("title"=>DOWLAN_17,  "type"=>"", "width"=>"auto", "thclass"=>""),
373         "download_description"     => array("title"=>DOWLAN_18,  "type"=>"", "width"=>"auto", "thclass"=>""),
374
375 * 		 "download_filesize"        => array("title"=>DOWLAN_66,  "type"=>"", "width"=>"auto", "thclass"=>"right"),
376         "download_requested"       => array("title"=>DOWLAN_29,  "type"=>"", "width"=>"auto", "thclass"=>"center"),
377         "download_category"        => array("title"=>DOWLAN_11,  "type"=>"", "width"=>"auto", "thclass"=>""),
378         "download_active"          => array("title"=>DOWLAN_21,  "type"=>"", "width"=>"auto", "thclass"=>"center"),
379         "download_datestamp"       => array("title"=>DOWLAN_182, "type"=>"", "width"=>"auto", "thclass"=>""),
380
381 * 		 "download_thumb"           => array("title"=>DOWLAN_20,  "type"=>"", "width"=>"auto", "thclass"=>"center"),
382         "download_image"           => array("title"=>DOWLAN_19,  "type"=>"", "width"=>"auto", "thclass"=>""),
383         "download_comment"         => array("title"=>DOWLAN_102, "type"=>"", "width"=>"auto", "thclass"=>"center"),
384         "download_class"           => array("title"=>DOWLAN_113, "type"=>"", "width"=>"auto", "thclass"=>""),
385         "download_mirror"          => array("title"=>DOWLAN_128, "type"=>"", "width"=>"auto", "thclass"=>""),
386         "download_mirror_type"     => array("title"=>DOWLAN_195, "type"=>"", "width"=>"auto", "thclass"=>""),
387         "download_visible"         => array("title"=>DOWLAN_43,  "type"=>"", "width"=>"auto", "thclass"=>""),
388		 "options"			        => array("title"=>LAN_OPTIONS, "width"=>"10%", "thclass"=>"center last", "forced"=>true)
389		);
390*/
391
392
393
394
395
396		// FORMAT field_name=>type - optional if fields 'data' attribute is set or if custom model is set in init()
397		/*protected $dataFields = array();*/
398
399		// optional, could be also set directly from $fields array with attributes 'validate' => true|'rule_name', 'rule' => 'condition_name', 'error' => 'Validation Error message'
400		/*protected  $validationRules = array(
401			'release_url' => array('required', '', 'Release URL', 'Help text', 'not valid error message')
402		);*/
403
404		// optional, if $pluginName == 'core', core prefs will be used, else e107::getPluginConfig($pluginName);
405		protected $prefs = array(
406			'pref_type'	   				=> array('title'=> 'type', 'type'=>'text', 'data' => 'string', 'validate' => true),
407			'pref_folder' 				=> array('title'=> 'folder', 'type' => 'boolean', 'data' => 'integer'),
408			'pref_name' 				=> array('title'=> 'name', 'type' => 'text', 'data' => 'string', 'validate' => 'regex', 'rule' => '#^[\w]+$#i', 'help' => 'allowed characters are a-zA-Z and underscore')
409		);
410
411
412		public function observe()
413		{
414			if (isset($_POST['submit_download'])) // Create or Update a Download.
415			{
416				$this->submit_download();
417			}
418
419			if (isset($_POST['updatedownlaodoptions'])) // Save Download Options.
420			{
421				$this->saveSettings();
422			}
423
424			if (isset($_POST['submit_mirror']))
425			{
426				$this->submit_mirror();
427			}
428
429			if (isset($_POST))
430			{
431				e107::getCache()->clear("download_cat");
432			}
433		}
434
435
436
437
438
439		// optional
440		public function init()
441		{
442
443
444			$this->action 		= $this->getMode(); // vartrue($_GET['mode']);
445			$this->subAction 	= $this->getAction(); // vartrue($_GET['action']);
446			$this->id			= $this->getId(); // vartrue($_GET['id']);
447
448			$this->observe();
449
450
451			$categories = array();
452			if(e107::getDb()->select('download_category'))
453			{
454				//$categories[0] = LAN_SELECT;
455				while ($row = e107::getDb()->fetch())
456				{
457					$id = $row['download_category_id'];
458					$categories[$id] = $row['download_category_name'];
459				}
460			}
461
462			$this->fields['download_category']['writeParms'] 		= $categories;
463			// DEPRECATED
464			//$this->fields['fb_rendertype']['writeParms'] 	= array(FBLAN_23,FBLAN_24);
465			//$this->fields['fb_mode']['writeParms'] 			= array(FBLAN_13,FBLAN_14);
466
467			$this->fields['download_category']['readParms'] 		= $categories;
468
469			// Custom filter queries
470			if(vartrue($_GET['filter_options']))
471			{
472				list($filter,$mode) = explode("__",$_GET['filter_options']);
473
474				if($mode == 'missing')
475				{
476					$this->filterQry = $this->missingFiles();
477				}
478
479				if($mode == 'nocategory')
480				{
481					$this->filterQry = "SELECT * FROM `#download` WHERE download_category=0";
482				}
483
484	  			if($mode == 'duplicates')
485				{
486					$this->filterQry = "SELECT GROUP_CONCAT(d.download_id SEPARATOR ',') as gc, d.download_id, d.download_name, d.download_url, dc.download_category_name
487                      FROM #download as d
488                      LEFT JOIN #download_category AS dc ON dc.download_category_id=d.download_category
489                      GROUP BY d.download_url
490                      HAVING COUNT(d.download_id) > 1";
491				}
492
493				if($mode == "filesize")
494				{
495					$this->filterQry = $this->missingFiles('filesize');
496				}
497
498			}
499
500		}
501
502
503		/*
504		 * Return a query for Missing Files and Filesize mismatch
505		 */
506		public function missingFiles($mode='missing')
507		{
508
509			$sql = e107::getDb();
510			$count = array();
511
512            if ($sql->gen("SELECT * FROM `#download` ORDER BY download_id"))
513            {
514               while($row = $sql->fetch())
515			   {
516               		if (!is_readable(e_DOWNLOAD.$row['download_url']))
517					{
518					 	$count[] = $row['download_id'];
519					}
520					elseif($mode == 'filesize')
521					{
522					 	$filesize = filesize(e_DOWNLOAD.$row['download_url']);
523                     	if ($filesize <> $row['download_filesize'])
524						{
525							$count[] = $row['download_id'];
526						}
527					}
528
529               }
530            }
531
532			if($count > 0)
533			{
534				return "SELECT * FROM `#download` WHERE download_id IN (".implode(",",$count).")";
535			}
536
537		}
538
539
540
541		function orphanFiles() //TODO
542		{
543
544			$files = e107::getFile()->get_files(e_DOWNLOAD);
545            $foundSome = false;
546            foreach($files as $file)
547			{
548               if (0 == $sql->db_Count('download', '(*)', " WHERE download_url='".$file['fname']."'")) {
549                  if (!$foundSome) {
550   		           // $text .= $rs->form_open("post", e_SELF."?".e_QUERY, "myform");
551                     $text .= '<form method="post" action="'.e_SELF.'?'.e_QUERY.'" id="myform">
552                     <table class="adminlist">';
553                     $text .= '<tr>';
554                     $text .= '<th>'.DOWLAN_13.'</th>';
555                     $text .= '<th>'.DOWLAN_182.'</th>';
556                     $text .= '<th>'.DOWLAN_66.'</th>';
557                     $text .= '<th>'.LAN_OPTIONS.'</th>';
558                     $text .= '</tr>';
559                     $foundSome = true;
560                  }
561                  $filesize = (is_readable(e_DOWNLOAD.$row['download_url']) ? eHelper::parseMemorySize(filesize(e_DOWNLOAD.$file['fname'])) : DOWLAN_181);
562                  $filets   = (is_readable(e_DOWNLOAD.$row['download_url']) ? e107::getDate()->convert_date(filectime(e_DOWNLOAD.$file['fname']), "long") : DOWLAN_181);
563                  $text .= '<tr>';
564                  $text .= '<td>'.$tp->toHTML($file['fname']).'</td>';
565                  $text .= '<td>'.$filets.'</td>';
566                  $text .= '<td>'.$filesize.'</td>';
567
568               }
569            }
570		}
571
572        /**
573         * @inheritdoc
574         */
575        public function afterDelete($deleted_data, $id, $deleted_check)
576        {
577            if($deleted_check)
578            {
579                $sql = e107::getDb('mmcleanup');
580                if(strpos($deleted_data['download_url'], '{e_MEDIA_') === 0 && $sql->delete('core_media', "media_url='{$deleted_data['download_url']}'"))
581                {
582                    $mediaFile = e107::getParser()->replaceConstants($deleted_data['download_url']);
583                    @unlink($mediaFile);
584                    e107::getMessage()->addSuccess('Associated media record successfully erased');
585                }
586                if(strpos($deleted_data['download_image'], '{e_MEDIA_') === 0 && $sql->delete('core_media', "media_url='{$deleted_data['download_image']}'"))
587                {
588                    $mediaImage = e107::getParser()->replaceConstants($deleted_data['download_image']);
589                    e107::getMessage()->addSuccess('Associated media image successfully erased');
590                    @unlink($mediaImage);
591                }
592            }
593        }
594
595		function createPage()
596		{
597			global $adminDownload;
598			$this->create_download();
599		}
600
601		function importPage()
602		{
603			$this->batchImportForm();
604		}
605
606		function settingsPage()
607		{
608			// global $adminDownload;
609			$this->show_download_options();
610		}
611
612		function limitsPage()
613		{
614			$this->showLimits();
615		}
616
617		function maintPage()
618		{
619			showMaint();
620		}
621
622		function mirrorPage()
623		{
624			global $adminDownload;
625			$this->show_existing_mirrors();
626		}
627
628
629
630		function showLimits()
631		{
632			$sql = e107::getDb();
633			$ns = e107::getRender();
634			$tp = e107::getParser();
635			$pref = e107::getPref();
636
637			//global $pref;
638
639			if ($sql->select('userclass_classes','userclass_id, userclass_name'))
640			{
641				$classList = $sql->db_getList();
642			}
643			if ($sql->select("generic", "gen_id as limit_id, gen_datestamp as limit_classnum, gen_user_id as limit_bw_num, gen_ip as limit_bw_days, gen_intdata as limit_count_num, gen_chardata as limit_count_days", "gen_type = 'download_limit'"))
644			{
645				while($row = $sql->fetch())
646				{
647					$limitList[$row['limit_classnum']] = $row;
648				}
649			}
650			$txt = "
651				<form method='post' action='".e_SELF."?".e_QUERY."'>
652				<table class='table adminform'>
653				<tr>
654					<td colspan='4' style='text-align:left'>
655				";
656				if(vartrue($pref['download_limits']) == 1)
657				{
658					$chk = " checked = 'checked'";
659				}
660				else
661				{
662					$chk = "";
663				}
664
665				$txt .= "
666					<input type='checkbox' name='download_limits' value='on'{$chk}/> ".DOWLAN_125."
667					</td>
668				</tr>
669				<tr>
670					<th class='fcaption'>".LAN_ID."</th>
671					<th class='fcaption'>".DOWLAN_113."</th>
672					<th class='fcaption'>".DOWLAN_107."</th>
673					<th class='fcaption'>".DOWLAN_108."</th>
674				</tr>
675			";
676
677			if(is_array(vartrue($limitList)))
678			{
679				foreach($limitList as $row)
680				{
681					$txt .= "
682					<tr>
683					<td>".$row['limit_id']."</td>
684					<td>".r_userclass_name($row['limit_classnum'])."</td>
685					<td class='form-inline'>
686						<input type='text' class='form-control' size='5' name='count_num[{$row['limit_id']}]' value='".($row['limit_count_num'] ? $row['limit_count_num'] : "")."'/> ".DOWLAN_109."
687						<input type='text' class='form-control' size='5' name='count_days[{$row['limit_id']}]' value='".($row['limit_count_days'] ? $row['limit_count_days'] : "")."'/> ".DOWLAN_110."
688					</td>
689					<td class='form-inline'>
690						<input type='text' class='form-control' size='5' name='bw_num[{$row['limit_id']}]' value='".($row['limit_bw_num'] ? $row['limit_bw_num'] : "")."'/> ".DOWLAN_111." ".DOWLAN_109."
691						<input type='text' class='form-control' size='5' name='bw_days[{$row['limit_id']}]' value='".($row['limit_bw_days'] ? $row['limit_bw_days'] : "")."'/> ".DOWLAN_110."
692					</td>
693					</tr>
694					";
695				}
696			}
697			$txt .= "
698			</table>
699			<div class='buttons-bar center'>
700			<input type='submit' class='btn btn-default btn-secondary button' name='updatelimits' value='".DOWLAN_115."'/>
701			</div>
702
703			<table class='table adminlist'>
704			<tr>
705			<td colspan='4'><br/><br/></td>
706			</tr>
707			<tr>
708			<td colspan='2'>".r_userclass("newlimit_class", 0, "off", "guest, member, admin, classes, language")."</td>
709			<td class='form-inline'>
710				<input type='text' class='form-control' size='5' name='new_count_num' value=''/> ".DOWLAN_109."
711				<input type='text' class='form-control' size='5' name='new_count_days' value=''/> ".DOWLAN_110."
712			</td>
713			<td class='form-inline'>
714				<input type='text' class='form-control' size='5' name='new_bw_num' value=''/> ".DOWLAN_111." ".DOWLAN_109."
715				<input type='text' class='form-control' size='5' name='new_bw_days' value=''/> ".DOWLAN_110."
716			</td>
717			</tr>
718			<tr>
719
720			";
721
722			$txt .= "</table>
723			<div class='buttons-bar center'>
724			<input type='submit' class='btn btn-default btn-secondary button' name='addlimit' value='".DOWLAN_114."'/>
725			</div></form>";
726			echo $txt;
727
728		//	$ns->tablerender(DOWLAN_112, $txt);
729			// require_once(e_ADMIN.'footer.php');
730			// exit;
731		}
732
733
734
735		function showMaint() //XXX Deprecated.
736		{
737			$mes = e107::getMessage();
738			$mes->addInfo("Deprecated Area - please use filter instead under 'Manage' ");
739
740			global $pref;
741			$ns = e107::getRender();
742			$sql = e107::getDb();
743			$frm = e107::getForm();
744			$tp = e107::getParser();
745
746		   if (isset($_POST['dl_maint'])) {
747		      switch ($_POST['dl_maint'])
748		      {
749		         case 'duplicates':
750		         {
751		            $title = DOWLAN_166;
752		            $query = 'SELECT GROUP_CONCAT(d.download_id SEPARATOR ",") as gc, d.download_id, d.download_name, d.download_url, dc.download_category_name
753		                      FROM #download as d
754		                      LEFT JOIN #download_category AS dc ON dc.download_category_id=d.download_category
755		                      GROUP BY d.download_url
756		                      HAVING COUNT(d.download_id) > 1
757		               ';
758		            $text = "";
759		            $count = $sql->gen($query);
760		            $foundSome = false;
761		            if ($count) {
762		               $currentURL = "";
763		               while($row = $sql->fetch()) {
764		                  if (!$foundSome) {
765		   		          //  $text .= $rs->form_open("post", e_SELF."?".e_QUERY, "myform");
766		                     $text .= '<form method="post" action="'.e_SELF.'?'.e_QUERY.'" id="myform">
767		                     			<table class="table adminform">';
768		                     $text .= '<tr>';
769		                     $text .= '<th>'.DOWLAN_13.'</th>';
770		                     $text .= '<th>'.LAN_ID.'</th>';
771		                     $text .= '<th>'.DOWLAN_27.'</th>';
772		                     $text .= '<th>'.DOWLAN_11.'</th>';
773		                     $text .= '<th>'.LAN_OPTIONS.'</th>';
774		                     $text .= '</tr>';
775		                     $foundSome = true;
776		                  }
777		                  $query = "SELECT d.*, dc.* FROM `#download` AS d
778		                     LEFT JOIN `#download_category` AS dc ON dc.download_category_id=d.download_category
779		                     WHERE download_id IN (".$row['gc'].")
780		                     ORDER BY download_id ASC";
781		                  $count = $sql2->gen($query);
782		                  while($row = $sql2->fetch()) {
783		                     $text .= '<tr>';
784		                     if ($currentURL != $row['download_url']) {
785		                        $text .= '<td>'.$tp->toHTML($row['download_url']).'</td>';
786		                        $currentURL = $row['download_url'];
787		                     } else {
788		                        $text .= '<td>*</td>';
789		                     }
790		                     $text .= '<td>'.$row['download_id'].'</td>';
791		                     $text .= "<td><a href='".e_PLUGIN."download/download.php?view.".$row['download_id']."'>".$e107->tp->toHTML($row['download_name']).'</a></td>';
792		                     $text .= '<td>'.$tp->toHTML($row['download_category_name']).'</td>';
793		                     $text .= '<td>
794		                                 <a href="'.e_SELF.'?create.edit.'.$row["download_id"].'.maint.duplicates">'.ADMIN_EDIT_ICON.'</a>
795		   				                  <input type="image" title="'.LAN_DELETE.'" name="delete[main_'.$row["download_id"].']" src="'.ADMIN_DELETE_ICON_PATH.'" onclick=\'return jsconfirm("'.$tp->toJS(DOWLAN_33.' [ID: '.$row["download_id"].' ]').'") \'/>
796		   				               </td>';
797		                     $text .= '</tr>';
798		                  }
799		               }
800		            }
801		            if ($foundSome) {
802		               $text .= '</table></form>';
803		            }
804		            else
805		            {
806						e107::getMessage()->addInfo(DOWLAN_172);
807		            }
808		            break;
809		         }
810		         case 'orphans':
811		         {
812		            $title = DOWLAN_167;
813		            $text = "";
814		            require_once(e_HANDLER."file_class.php");
815		            $efile = new e_file();
816		            $files = $efile->get_files(e_DOWNLOAD);
817		            $foundSome = false;
818		            foreach($files as $file) {
819		               if (0 == $sql->db_Count('download', '(*)', " WHERE download_url='".$file['fname']."'")) {
820		                  if (!$foundSome) {
821		   		           // $text .= $rs->form_open("post", e_SELF."?".e_QUERY, "myform");
822		                     $text .= '<form method="post" action="'.e_SELF.'?'.e_QUERY.'" id="myform">
823		                     <table class="table adminform">';
824		                     $text .= '<tr>';
825		                     $text .= '<th>'.DOWLAN_13.'</th>';
826		                     $text .= '<th>'.DOWLAN_182.'</th>';
827		                     $text .= '<th>'.DOWLAN_66.'</th>';
828		                     $text .= '<th>'.LAN_OPTIONS.'</th>';
829		                     $text .= '</tr>';
830		                     $foundSome = true;
831		                  }
832		                  $filesize = (is_readable(e_DOWNLOAD.$row['download_url']) ? $e107->parseMemorySize(filesize(e_DOWNLOAD.$file['fname'])) : DOWLAN_181);
833		                  $filets   = (is_readable(e_DOWNLOAD.$row['download_url']) ? $gen->convert_date(filectime(e_DOWNLOAD.$file['fname']), "long") : DOWLAN_181);
834		                  $text .= '<tr>';
835		                  $text .= '<td>'.$tp->toHTML($file['fname']).'</td>';
836		                  $text .= '<td>'.$filets.'</td>';
837		                  $text .= '<td>'.$filesize.'</td>';
838		   //TODO               $text .= '<td>
839		   //TODO                           <a href="'.e_SELF.'?create.add.'. urlencode($file["fname"]).'">'.E_16_CREATE.'</a>
840		   //TODO					            <input type="image" title="'.LAN_DELETE.'" name="delete[main_'.$file["fname"].']" src="'.ADMIN_DELETE_ICON_PATH.'" onclick=\'return jsconfirm("'.$tp->toJS(DOWLAN_173.' [ '.$file["fname"].' ]').'") \'/>
841		   //TODO					         </td>';
842		                  $text .= '</tr>';
843		               }
844		            }
845		            if ($foundSome) {
846		               $text .= '</table></form>';
847		            }
848		            else
849		            {
850		            	e107::getMessage()->addInfo(DOWLAN_174);
851
852		            }
853		            break;
854		         }
855		         case 'missing':
856		         {
857		            $title = DOWLAN_168;
858		            $text = "";
859		            $query = "SELECT d.*, dc.* FROM `#download` AS d LEFT JOIN `#download_category` AS dc ON dc.download_category_id=d.download_category";
860		            $count = $sql->gen($query);
861		            $foundSome = false;
862		            if ($count) {
863		               while($row = $sql->fetch()) {
864		                  if (!is_readable(e_DOWNLOAD.$row['download_url'])) {
865		                     if (!$foundSome)
866							 {
867		   		              // $text .= $rs->form_open("post", e_SELF."?".e_QUERY, "myform");
868
869		                        $text .= '<form method="post" action="'.e_SELF.'?'.e_QUERY.'" id="myform">
870		                        		<table class="adminlist">';
871		                        $text .= '<tr>';
872		                        $text .= '<th>'.LAN_ID.'</th>';
873		                        $text .= '<th>'.DOWLAN_27.'</th>';
874		                        $text .= '<th>'.DOWLAN_11.'</th>';
875		                        $text .= '<th>'.DOWLAN_13.'</th>';
876		                        $text .= '<th>'.LAN_OPTIONS.'</th>';
877		                        $text .= '</tr>';
878		                        $foundSome = true;
879		                     }
880		                     $text .= '<tr>';
881		                     $text .= '<td>'.$row['download_id'].'</td>';
882		                     $text .= "<td><a href='".e_PLUGIN."download/download.php?view.".$row['download_id']."'>".$tp->toHTML($row['download_name']).'</a></td>';
883		                     $text .= '<td>'.$tp->toHTML($row['download_category_name']).'</td>';
884		                     $text .= '<td>'.$tp->toHTML($row['download_url']).'</td>';
885		                     $text .= '<td>
886		                                 <a href="'.e_SELF.'?create.edit.'.$row["download_id"].'.maint.missing">'.ADMIN_EDIT_ICON.'</a>
887		   					               <input type="image" title="'.LAN_DELETE.'" name="delete[main_'.$row["download_id"].']" src="'.ADMIN_DELETE_ICON_PATH.'" onclick=\'return jsconfirm("'.$tp->toJS(DOWLAN_33.' [ID: '.$row["download_id"].' ]').'") \'/>
888		   					            </td>';
889		                     $text .= '</tr>';
890		                  }
891		               }
892		            }
893		            if ($foundSome) {
894		               $text .= '</table></form>';
895		            }
896		            else
897		            {
898		            	e107::getMessage()->addInfo(DOWLAN_172);
899		              //  $text = DOWLAN_172;
900		            }
901		            break;
902		         }
903		         case 'inactive':
904		         {
905		            $title = DOWLAN_169;
906		            $text = "";
907		            $query = "SELECT d.*, dc.* FROM `#download` AS d LEFT JOIN `#download_category` AS dc ON dc.download_category_id=d.download_category WHERE download_active=0";
908		            $count = $sql->gen($query);
909		            $foundSome = false;
910		            if ($count) {
911		               while($row = $sql->fetch()) {
912		                  if (!$foundSome)
913		                  {
914		   		           // $text .= $rs->form_open("post", e_SELF."?".e_QUERY, "myform");
915		                     $text .= '<form method="post" action="'.e_SELF.'?'.e_QUERY.'" id="myform">
916		                     		<table class="table adminform">';
917		                     $text .= '<tr>';
918		                     $text .= '<th>'.LAN_ID.'</th>';
919		                     $text .= '<th>'.DOWLAN_27.'</th>';
920		                     $text .= '<th>'.DOWLAN_11.'</th>';
921		                     $text .= '<th>'.DOWLAN_13.'</th>';
922		                     $text .= '<th>'.LAN_OPTIONS.'</th>';
923		                     $text .= '</tr>';
924		                     $foundSome = true;
925		                  }
926
927		                  $text .= '<tr>';
928		                  $text .= '<td>'.$row['download_id'].'</td>';
929		                  $text .= "<td><a href='".e_PLUGIN."download/download.php?view.".$row['download_id']."'>".$e107->tp->toHTML($row['download_name']).'</a></td>';
930		                  $text .= '<td>'.$e107->tp->toHTML($row['download_category_name']).'</td>';
931		                  if (strlen($row['download_url']) > 0) {
932		                     $text .= '<td>'.$row['download_url'].'</td>';
933		                  } else {
934		   					   $mirrorArray = download::makeMirrorArray($row['download_mirror'], TRUE);
935		                     $text .= '<td>';
936		                     foreach($mirrorArray as $mirror) {
937		                        $text .= $mirror['url'].'<br/>';
938		                     }
939		                     $text .= '</td>';
940		                  }
941		                  $text .= '<td>
942		                              <a href="'.e_SELF.'?create.edit.'.$row["download_id"].'.maint.inactive">'.ADMIN_EDIT_ICON.'</a>
943		   				               <input type="image" title="'.LAN_DELETE.'" name="delete[main_'.$row["download_id"].']" src="'.ADMIN_DELETE_ICON_PATH.'" onclick=\'return jsconfirm("'.$tp->toJS(DOWLAN_33.' [ID: '.$row["download_id"].' ]').'") \'/>
944		   				            </td>';
945		                  $text .= '</tr>';
946		               }
947		            }
948		            if ($foundSome) {
949		               $text .= '</table></form>';
950		            }
951		            else
952		            {
953		            	e107::getMessage()->addInfo(DOWLAN_172);
954		               // $text = DOWLAN_172;
955		            }
956		            break;
957		         }
958		         case 'nocategory':
959		         {
960		            $title = DOWLAN_178;
961		            $text = "";
962		            $query = "SELECT * FROM `#download` WHERE download_category=0";
963		            $count = $sql->gen($query);
964		            $foundSome = false;
965		            if ($count) {
966		               while($row = $sql->fetch()) {
967		                  if (!$foundSome) {
968		   		          //  $text .= $rs->form_open("post", e_SELF."?".e_QUERY, "myform");
969		                     $text .= '
970		                     <form method="post" action="'.e_SELF.'?'.e_QUERY.'" id="myform">
971		                     <table class="table adminlist">';
972		                     $text .= '<tr>';
973		                     $text .= '<th>'.LAN_ID.'</th>';
974		                     $text .= '<th>'.DOWLAN_27.'</th>';
975		                     $text .= '<th>'.DOWLAN_13.'</th>';
976		                     $text .= '<th>'.LAN_OPTIONS.'</th>';
977		                     $text .= '</tr>';
978		                     $foundSome = true;
979		                  }
980		                  $text .= '<tr>';
981		                  $text .= '<td>'.$row['download_id'].'</td>';
982		                  $text .= "<td><a href='".e_PLUGIN."download/download.php?view.".$row['download_id']."'>".$e107->tp->toHTML($row['download_name']).'</a></td>';
983		                  if (strlen($row['download_url']) > 0) {
984		                     $text .= '<td>'.$e107->tp->toHTML($row['download_url']).'</td>';
985		                  } else {
986		   					   $mirrorArray = download::makeMirrorArray($row['download_mirror'], TRUE);
987		                     $text .= '<td>';
988		                     foreach($mirrorArray as $mirror) {
989		                        $text .= $mirror['url'].'<br/>';
990		                     }
991		                     $text .= '</td>';
992		                  }
993		                  $text .= '<td>
994		                              <a href="'.e_SELF.'?create.edit.'.$row["download_id"].'.maint.nocategory">'.ADMIN_EDIT_ICON.'</a>
995		   				               <input type="image" title="'.LAN_DELETE.'" name="delete[main_'.$row["download_id"].']" src="'.ADMIN_DELETE_ICON_PATH.'" onclick=\'return jsconfirm("'.$tp->toJS(DOWLAN_33.' [ID: '.$row["download_id"].' ]').'") \'/>
996		   				            </td>';
997		                  $text .= '</tr>';
998		               }
999		            }
1000		            if ($foundSome) {
1001		               $text .= '</table></form>';
1002		            }
1003		            else
1004		            {
1005		            	e107::getMessage()->addInfo(DOWLAN_172);
1006		              // $text = DOWLAN_172;
1007		            }
1008		            break;
1009		         }
1010		         case 'filesize':
1011		         {
1012		            $title = DOWLAN_66;
1013		            $text = "";
1014		            $query = "SELECT d.*, dc.* FROM `#download` AS d LEFT JOIN `#download_category` AS dc ON dc.download_category_id=d.download_category WHERE d.download_url<>''";
1015		            $count = $sql->gen($query);
1016		            $foundSome = false;
1017		            if ($count) {
1018		               while($row = $sql->fetch()) {
1019		                  if (is_readable(e_DOWNLOAD.$row['download_url'])) {
1020		                     $filesize = filesize(e_DOWNLOAD.$row['download_url']);
1021		                     if ($filesize <> $row['download_filesize']) {
1022		                        if (!$foundSome) {
1023		   		                 // $text .= $rs->form_open("post", e_SELF."?".e_QUERY, "myform");
1024		                           $text .= '<form method="post" action="'.e_SELF.'?'.e_QUERY.'" id="myform">
1025		                           		<table class="table adminlist">';
1026		                           $text .= '<tr>';
1027		                           $text .= '<th>'.LAN_ID.'</th>';
1028		                           $text .= '<th>'.DOWLAN_27.'</th>';
1029		                           $text .= '<th>'.DOWLAN_11.'</th>';
1030		                           $text .= '<th>'.DOWLAN_13.'</th>';
1031		                           $text .= '<th>'.DOWLAN_180.'</th>';
1032		                           $text .= '<th>'.LAN_OPTIONS.'</th>';
1033		                           $text .= '</tr>';
1034		                           $foundSome = true;
1035		                        }
1036		                        $text .= '<tr>';
1037		                        $text .= '<td>'.$row['download_id'].'</td>';
1038		                        $text .= "<td><a href='".e_PLUGIN."download/download.php?view.".$row['download_id']."'>".$e107->tp->toHTML($row['download_name']).'</a></td>';
1039		                        $text .= '<td>'.$e107->tp->toHTML($row['download_category_name']).'</td>';
1040		                        $text .= '<td>'.$e107->tp->toHTML($row['download_url']).'</td>';
1041		                        $text .= '<td>'.$row['download_filesize'].' / ';
1042		                        $text .= $filesize;
1043		                        $text .= '</td>';
1044		                        $text .= '<td>
1045		                                    <a href="'.e_SELF.'?create.edit.'.$row["download_id"].'.maint.filesize">'.ADMIN_EDIT_ICON.'</a>
1046		   					                  <input type="image" title="'.LAN_DELETE.'" name="delete[main_'.$row["download_id"].']" src="'.ADMIN_DELETE_ICON_PATH.'" onclick=\'return jsconfirm("'.$tp->toJS(DOWLAN_33.' [ID: '.$row["download_id"].' ]').'") \'/>
1047		   					               </td>';
1048		                        $text .= '</tr>';
1049		                     }
1050		                  }
1051		               }
1052		            }
1053		            if ($foundSome) {
1054		               $text .= '</table></form>';
1055		            }
1056		            else
1057		            {
1058		            	e107::getMessage()->addInfo(DOWLAN_172);
1059		              // $text = DOWLAN_172;
1060		            }
1061		            break;
1062		         }
1063		         case 'log':
1064		         {
1065		            $text = "log - view manage download history log";
1066		            header('location: '.e_ADMIN.'admin_log.php?downlog');
1067		            exit();
1068		            break;
1069		         }
1070		      }
1071		   }
1072		   else {
1073		      $title = DOWLAN_193;
1074		      $text = DOWLAN_179;
1075		      $eform = new e_form();
1076		      $text = "
1077		      	<form method='post' action='".e_SELF."?".e_QUERY."' id='core-db-main-form'>
1078		      		<fieldset id='core-db-plugin-scan'>
1079		      		<legend class='e-hideme'>".DOWLAN_10."</legend>
1080		      			<table class='table adminform'>
1081		      			<colgroup span='2'>
1082		      				<col style='width: 40%'></col>
1083		      				<col style='width: 60%'></col>
1084		      			</colgroup>
1085		      			<tbody>
1086		      				<tr>
1087		      					<td>".DOWLAN_166."</td>
1088		      					<td>
1089		      						".$eform->radio('dl_maint', 'duplicates').$eform->label(DOWLAN_185, 'dl_maint', 'duplicates')."
1090		      					</td>
1091		      				</tr>
1092		      				<tr>
1093		      					<td>".DOWLAN_167."</td>
1094		      					<td>
1095		      						".$eform->radio('dl_maint', 'orphans').$eform->label(DOWLAN_186, 'dl_maint', 'orphans')."
1096		      					</td>
1097		      				</tr>
1098		      				<tr>
1099		      					<td>".DOWLAN_168."</td>
1100		      					<td>
1101		      						".$eform->radio('dl_maint', 'missing').$eform->label(DOWLAN_187, 'dl_maint', 'missing')."
1102		      					</td>
1103		      				</tr>
1104		      				<tr>
1105		      					<td>".DOWLAN_169."</td>
1106		      					<td>
1107		      						".$eform->radio('dl_maint', 'inactive').$eform->label(DOWLAN_188, 'dl_maint', 'inactive')."
1108		      					</td>
1109		      				</tr>
1110		      				<tr>
1111		      					<td>".DOWLAN_178."</td>
1112		      					<td>
1113		      						".$eform->radio('dl_maint', 'nocategory').$eform->label(DOWLAN_189, 'dl_maint', 'nocategory')."
1114		      					</td>
1115		      				</tr>
1116		      				<tr>
1117		      					<td>".DOWLAN_66."</td>
1118		      					<td>
1119		      						".$eform->radio('dl_maint', 'filesize').$eform->label(DOWLAN_190, 'dl_maint', 'filesize')."
1120		      					</td>
1121		      				</tr>
1122		      				<tr>
1123		      					<td>".DOWLAN_171."</td>
1124		      					<td>
1125		      						".$eform->radio('dl_maint', 'log').$eform->label(DOWLAN_191, 'dl_maint', 'log')."
1126		      					</td>
1127		      				</tr>
1128
1129		      				</tbody>
1130		      			</table>
1131		      			<div class='buttons-bar center'>
1132		      				".$eform->admin_button('trigger_db_execute', DOWLAN_192, 'execute')."
1133		      			</div>
1134		      		</fieldset>
1135		      	</form>
1136		      	";
1137		   }
1138
1139		   echo $text;
1140		   // 	$ns->tablerender(DOWLAN_165.$title, $text);
1141		}
1142
1143
1144
1145
1146		function saveSettings()
1147		{
1148			global $admin_log,$pref;
1149
1150			$tp = e107::getParser();
1151
1152			$expected_params = array(
1153				'download_php', 'download_view', 'download_sort', 'download_order',
1154				'mirror_order', 'recent_download_days', 'agree_flag',
1155				'agree_text', 'download_denied', 'download_reportbroken',
1156				'download_security_mode', 'download_security_expression', 'download_security_link_expiry'
1157			);
1158
1159			$temp = array();
1160			foreach($expected_params as $expected_param)
1161			{
1162				$temp[$expected_param] = $_POST[$expected_param];
1163			}
1164
1165			$temp['download_subsub'] = $_POST['download_subsub'] ? '1' : '0';
1166			$temp['download_incinfo'] = $_POST['download_incinfo'] ? '1' : '0';
1167
1168			if ($_POST['download_security_mode'] !== 'nginx-secure_link_md5')
1169			{
1170				unset($temp['download_security_mode']);
1171				unset($temp['download_security_expression']);
1172				unset($temp['download_security_link_expiry']);
1173				e107::getConfig('core')->removePref('download_security_mode');
1174				e107::getConfig('core')->removePref('download_security_expression');
1175				e107::getConfig('core')->removePref('download_security_link_expiry');
1176			}
1177
1178			e107::getConfig('core')->setPref($temp)->save(false);
1179
1180		}
1181
1182
1183		// Create Download FORM.
1184	   function create_download()
1185	   {
1186	   		$action		= $this->action;
1187			$subAction	= $this->subAction;
1188			$id			= $this->id;
1189
1190			$sql = e107::getDb();
1191			$tp = e107::getParser();
1192			$fl = e107::getFile();
1193			$mes = e107::getMessage();
1194
1195		//	print_a($this);
1196
1197	      	global $e107, $cal, $rs, $ns, $file_array, $image_array, $thumb_array;
1198	      	require_once(e_PLUGIN.'download/download_shortcodes.php');
1199			require_once(e_PLUGIN.'download/handlers/download_class.php');
1200	      	require_once(e_HANDLER."form_handler.php");
1201
1202			$download = new download;
1203
1204		    if ($file_array = $fl->get_files(e_DOWNLOAD, "","standard",5))
1205		    {
1206		    	sort($file_array);
1207		    }
1208		    if ($public_array = $fl->get_files(e_UPLOAD))
1209		    {
1210		    	foreach($public_array as $key=>$val)
1211		    	{
1212					$file_array[] = str_replace(e_UPLOAD,"",$val);
1213				}
1214			}
1215	/*      if ($sql->select("rbinary")) //TODO Remove me.
1216	      {
1217	         while ($row = $sql->fetch())
1218	         {
1219	            extract($row);
1220	            $file_array[] = "Binary ".$binary_id."/".$binary_name;
1221	         }
1222	      }
1223	*/
1224	      if ($image_array = $fl->get_files(e_FILE.'downloadimages/', '\.gif$|\.jpg$|\.png$|\.GIF$|\.JPG$|\.PNG$','standard',2))
1225	      {
1226	         sort($image_array);
1227	      }
1228	      if ($thumb_array = $fl->get_files(e_FILE.'downloadthumbs/', '\.gif$|\.jpg$|\.png$|\.GIF$|\.JPG$|\.PNG$','standard',2))
1229	      {
1230	         sort($thumb_array);
1231	      }
1232
1233	      $frm = new e_form();
1234	      $mirrorArray = array();
1235
1236	      $download_status[0] = DOWLAN_122;
1237	      $download_status[1] = DOWLAN_123;
1238	      $download_status[2] = DOWLAN_124;
1239
1240	      if (!$sql->select("download_category"))
1241	      {
1242	         //$ns->tablerender(ADLAN_24, "<div style='text-align:center'>".DOWLAN_5."</div>");
1243	         $mes->addInfo(DOWLAN_5);
1244	         return;
1245	      }
1246	      $download_active = 1;
1247	      if ($_GET['action'] == "edit" && !$_POST['submit'])
1248	      {
1249	         if ($sql->select("download", "*", "download_id=".intval($_GET['id'])))
1250	         {
1251	            $row = $sql->fetch();
1252	            extract($row);
1253
1254	            $mirrorArray = $this->makeMirrorArray($row['download_mirror']);
1255	         }
1256	      }
1257
1258	      if ($subAction == "dlm" && !$_POST['submit'])
1259	      {
1260	         require_once(e_PLUGIN.'download/download_shortcodes.php');
1261	         if ($sql->select("upload", "*", "upload_id=".$id))
1262	         {
1263	            $row = $sql->fetch();
1264
1265	            $download_category = $row['upload_category'];
1266	            $download_name = $row['upload_name'].($row['upload_version'] ? " v" . $row['upload_version'] : "");
1267	            $download_url = $row['upload_file'];
1268	            $download_author_email = $row['upload_email'];
1269	            $download_author_website = $row['upload_website'];
1270	            $download_description = $row['upload_description'];
1271	            $download_image = $row['upload_ss'];
1272	            $download_filesize = $row['upload_filesize'];
1273	            $image_array[] = array("path" => "", "fname" => $row['upload_ss']);
1274	            $download_author = substr($row['upload_poster'], (strpos($row['upload_poster'], ".")+1));
1275	         }
1276	      }
1277
1278
1279	      $text = "
1280
1281	         <ul class='nav nav-tabs'>
1282	            <li class='active'><a data-toggle='tab' href='#download-create'>".DOWLAN_175."</a></li>
1283	            <li><a data-toggle='tab' href='#download-edit-external'>".DOWLAN_176."</a></li>
1284	            <li><a data-toggle='tab' href='#download-edit-mirror'>".DOWLAN_128."</a></li>
1285	         </ul>
1286	         <form method='post' action='".e_SELF."?".e_QUERY."' id='myform'>
1287	          <div class='tab-content'>
1288	          <div class='tab-pane active' id='download-create'>
1289
1290
1291	                  <table class='table adminform' style='margin:0'>
1292	                     <tr>
1293	                        <td>".DOWLAN_13."</td>
1294	                        <td style='width:80%'>
1295	                           <div>".DOWLAN_131."&nbsp;&nbsp;";
1296
1297	                   //       $text .= "<select name='download_url' class='form-control'>
1298	                  //               <option value=''>&nbsp;</option>\n";
1299
1300
1301	      $counter = 0;
1302	      while (isset($file_array[$counter]))
1303	      {
1304	         $fpath = str_replace(e_DOWNLOAD,"",$file_array[$counter]['path']).$file_array[$counter]['fname'];
1305	         $selected = '';
1306	         if (stristr($fpath, $download_url) !== FALSE)
1307	         {
1308	            $selected = " selected='selected'";
1309	            $found = 1;
1310	         }
1311
1312	     //    $text .= "<option value='".$fpath."' $selected>".$fpath."</option>\n";
1313	         $counter++;
1314	      }
1315
1316	      if (preg_match("/http:|https:|ftp:/", $download_url))
1317	      {
1318	         $download_url_external = $download_url;
1319	         $download_url = '';
1320	      }
1321
1322	      $etext = " - (".DOWLAN_68.")";
1323	      if (file_exists(e_UPLOAD.$download_url))
1324	      {
1325	         $etext = "";
1326	      }
1327
1328	      if (!$found && $download_url)
1329	      {
1330	    //     $text .= "<option value='".$download_url."' selected='selected'>".$download_url.$etext."</option>\n";
1331	      }
1332
1333	  //    $text .= "             </select>";
1334
1335	  	$text .= e107::getForm()->filepicker("download_url",$download_url,DOWLAN_131,"media=download_file&title=Choose a file");
1336
1337	      $text .= "
1338	                        </div>
1339	                     </td>
1340	                  </tr>
1341	               </table>
1342	            </div>
1343	            <div class='tab-pane' id='download-edit-external'>
1344	               <table class='table adminform' style='margin:0'>
1345	                  <tr>
1346	                       <td>".DOWLAN_149."</td>
1347	                       <td style='width:80%;'>
1348	                          <input class='form-control input-xxlarge' type='text' name='download_url_external' size='90' value='{$download_url_external}' maxlength='255'/>
1349	                       </td>
1350	                    </tr>
1351	                    <tr>
1352	                       <td>".DOWLAN_66."</td>
1353	                       <td class='form-inline'>
1354	                          <input class='form-control' type='text' name='download_filesize_external' size='8' value='{$download_filesize}' maxlength='10'/>
1355	                       	 <select class='form-control' name='download_filesize_unit'>
1356						      <option value='B'{$b_sel}>".CORE_LAN_B."</option>
1357						      <option value='KB'{$kb_sel}>".CORE_LAN_KB."</option>
1358						      <option value='MB'>".CORE_LAN_MB."</option>
1359						      <option value='GB'>".CORE_LAN_GB."</option>
1360						      <option value='TB'>".CORE_LAN_TB."</option>
1361							  </select>
1362	                       </td>
1363	                  </tr>
1364	               </table>
1365	            </div>
1366	            <div  class='tab-pane' id='download-edit-mirror'>
1367	               <table class='table adminlist'>
1368	                  <tr>
1369	                     <td style='width:20%'><span title='".DOWLAN_129."' style='cursor:help'>".DOWLAN_128."</span></td>
1370	                     <td style='width:80%'>";
1371
1372	      // See if any mirrors to display
1373	      if (!$sql -> select("download_mirror"))
1374	      {   // No mirrors defined here
1375	         $text .= DOWLAN_144."</td></tr>";
1376	      }
1377	      else
1378	      {
1379	         $text .= DOWLAN_132."<div id='mirrorsection'>";
1380	         $mirrorList = $sql -> db_getList();         // Get the list of possible mirrors
1381	         $m_count = (count($mirrorArray) ? count($mirrorArray) : 1);      // Count of mirrors actually in use (or count of 1 if none defined yet)
1382	         for($count = 1; $count <= $m_count; $count++)
1383	         {
1384	            $opt = ($count==1) ? "id='mirror'" : "";
1385	            $text .="
1386	                        <div {$opt}>
1387	                           <select name='download_mirror_name[]' class='form-control'>
1388	                              <option value=''>&nbsp;</option>";
1389
1390	            foreach ($mirrorList as $mirror)
1391	            {
1392	               extract($mirror);
1393	               $text .= "<option value='{$mirror_id}'".($mirror_id == $mirrorArray[($count-1)]['id'] ? " selected='selected'" : "").">{$mirror_name}</option>\n";
1394	            }
1395
1396	            $text .= "</select>
1397	                           <input  class='form-control' type='text' name='download_mirror[]' style='width: 60%;' value=\"".$mirrorArray[($count-1)]['url']."\" maxlength='200'/>
1398	                           <input  class='form-control' type='text' name='download_mirror_size[]' style='width: 15%;' value=\"".$mirrorArray[($count-1)]['filesize']."\" maxlength='10'/>";
1399	            if (DOWNLOAD_DEBUG)
1400	            {
1401	               if ($id)
1402	               {
1403	                  $text .= '('.$mirrorArray[($count-1)]['requests'].')';
1404	               }
1405	               else
1406	               {
1407	               $text .= "<input  class='form-control' type='text' name='download_mirror_requests[]' style='width: 10%;' value=\"".$mirrorArray[($count-1)]['requests']."\" maxlength='10'/>";
1408	               }
1409	            }
1410	            $text .= "  </div>";
1411	         }
1412	         $text .="      </div>
1413	                        <input class='btn btn-default btn-secondary button' type='button' name='addoption' value='".DOWLAN_130."' onclick=\"duplicateHTML('mirror','mirrorsection')\"/>
1414	                     </td>
1415	                  </tr>
1416	                  <tr>
1417	                     <td style='width:20%' ><span style='cursor:help' title='".DOWLAN_154."'>".DOWLAN_155."</span></td>
1418	                     <td style='width:80%'>
1419	                        <input type='radio' name='download_mirror_type' value='1'".($download_mirror_type ? " checked='checked'" : "")."/> ".DOWLAN_156."<br/>
1420	                        <input type='radio' name='download_mirror_type' value='0'".(!$download_mirror_type ? " checked='checked'" : "")."/> ".DOWLAN_157."
1421	                     </td>
1422	                  </tr>";
1423	      }      // End of mirror-related stuff
1424
1425	      $download_author = $subAction != "edit" && $download_author == "" ? USERNAME : $download_author;//TODO what if editing an no author specified
1426	      $download_author_email = $subAction != "edit" && $download_author_email == "" ? USEREMAIL : $download_author_email;
1427	      $text .= "
1428	               </table>
1429	            </div>
1430	           </div>
1431	            <fieldset id='download-edit-therest'>
1432	               <table class='table adminform' >
1433	                  <tr>
1434	                     <td style='width:20%'>".DOWLAN_11."</td>
1435	                     <td style='width:80%'>";
1436
1437
1438	      $text .= $download->getCategorySelectList($download_category);
1439	   // $text .= download::getCategorySelectList($download_category);
1440
1441	      $text .= "     </td>
1442	                  </tr>
1443	                  <tr>
1444	                     <td >".DOWLAN_12."</td>
1445	                     <td style='width:80%'>
1446	                        <input class='form-control input-xxlarge' type='text' id='download-name' name='download_name' size='60' value=\"".$tp->toForm($download_name)."\" maxlength='200'/>
1447	                     </td>
1448	                  </tr>
1449	                  <tr>
1450	                     <td style='width:20%'>".DOWLAN_15."</td>
1451	                     <td style='width:80%'>
1452	                        <input class='form-control' type='text' name='download_author' size='60' value='$download_author' maxlength='100'/>
1453	                     </td>
1454	                  </tr>
1455	                  <tr>
1456	                     <td style='width:20%'>".DOWLAN_16."</td>
1457	                     <td style='width:80%'>
1458	                        <input class='form-control' type='text' name='download_author_email' size='60' value='$download_author_email' maxlength='100'/>
1459	                     </td>
1460	                  </tr>
1461	                  <tr>
1462	                     <td style='width:20%'>".DOWLAN_17."</td>
1463	                     <td style='width:80%'>
1464	                        <input class='form-control' type='text' name='download_author_website' size='60' value='$download_author_website' maxlength='100'/>
1465	                     </td>
1466	                  </tr>
1467	                  <tr>
1468	                     <td style='width:20%'>".DOWLAN_18."</td>
1469	                     <td style='width:80%'>
1470	      ";
1471	      $text .= $frm->bbarea('download_description',$download_description);
1472
1473	      $text .= "     </td>
1474	                  </tr>
1475
1476	                  <tr>
1477	                     <td style='width:20%'>".DOWLAN_19."</td>
1478	                     <td style='width:80%'>";
1479	       /*
1480															$text = "<select name='download_image' class='form-control'>
1481										  <option value=''>&nbsp;</option>";
1482																foreach($image_array as $img)
1483					 {
1484						$fpath = str_replace(e_FILE."downloadimages/","",$img['path'].$img['fname']);
1485						  $sel = ($download_image == $fpath) ? " selected='selected'" : "";
1486						  $text .= "<option value='".$fpath."' $sel>".$fpath."</option>\n";
1487					 }
1488									 $text .= "     </select>";
1489										   */
1490
1491		$text .= $frm->imagepicker('download_image', $download_image,'',array('media'=>'download_image', 'legacyPath'=>'{e_FILE}downloadimages'));
1492
1493	      if ($subAction == "dlm" && $download_image)
1494	      {
1495	         $text .= "
1496	         <input type='hidden' name='move_image' value='1'/>\n";
1497	      }
1498	      $text .= "     </td>
1499	                  </tr>";
1500
1501
1502
1503	      if(is_dir(e_FILE."downloadthumbs")) // Legacy
1504	      {
1505
1506	           $text .= "
1507	                 <tr>
1508			            <td style='width:20%'>".DOWLAN_20."</td>
1509			           <td style='width:80%'>";
1510			     /*
1511												   $text .= "
1512											 <select name='download_thumb' class='form-control'>
1513												<option value=''>&nbsp;</option>";
1514						   foreach($thumb_array as $thm){
1515							  $tpath = str_replace(e_FILE."downloadthumbs/","",$thm['path'].$thm['fname']);
1516							  $sel = ($download_thumb == $tpath) ? " selected='selected'" : "";
1517							  $text .= "<option value='".$tpath."' $sel>".$tpath."</option>\n";
1518						   }
1519										 $text .= "        </select>";
1520						   */
1521
1522				 $text .= $frm->imagepicker('download_thumb', $download_thumb,'',array('media'=>'download_thumb', 'legacyPath'=>'{e_FILE}downloadthumbs'));
1523
1524
1525			    $text .= "
1526			                </td>
1527			              </tr>";
1528	      }
1529
1530
1531
1532			$text .= "
1533	                  <tr>
1534	                     <td style='width:20%'>".LAN_DATESTAMP."</td>
1535	                     <td style='width:80%'>";
1536	      if (!$download_datestamp){
1537	           $download_datestamp = time();
1538	      }
1539
1540			$text .= $frm->datepicker('download_datestamp', $download_datestamp, 'type=datetime');
1541
1542	  //    $update_checked = ($_POST['update_datestamp']) ? "checked='checked'" : "";
1543	  //    $text .= "        &nbsp;&nbsp;<span><input type='checkbox' value='1' name='update_datestamp' $update_checked/>".DOWLAN_148."</span>";
1544
1545		  $text .= "
1546	                     </td>
1547	                  </tr>
1548
1549	     			 <tr>
1550	                     <td >".LAN_SEFURL."</td>
1551	                     <td class='input-group' style='width:80%'>
1552	                        ".$frm->renderElement('download_sef',$download_sef, array('type'=>'text', 'writeParms'=>array('sef'=>'download_name','size'=>'xxlarge')))."
1553	                     </td>
1554	                  </tr>
1555
1556
1557	                 <tr>
1558	                     <td >".LAN_KEYWORDS."</td>
1559	                     <td style='width:80%'>".$frm->tags('download_keywords',$download_keywords)."
1560
1561	                     </td>
1562	                  </tr>
1563
1564
1565
1566	                  <tr>
1567	                     <td style='width:20%'>".DOWLAN_21."</td>
1568	                     <td style='width:80%'>
1569	                        <select name='download_active' class='form-control input-xxlarge'>";
1570	      foreach($download_status as $key => $val){
1571	         $sel = ($download_active == $key) ? " selected = 'selected' " : "";
1572	           $text .= "<option value='{$key}' {$sel}>{$val}</option>\n";
1573	      }
1574	      $text .= "        </select>
1575	                     </td>
1576	                  </tr>
1577	                  <tr>
1578	                     <td style='width:20%'>".DOWLAN_102."</td>
1579	                     <td style='width:80%'>";
1580	      if ($download_comment == "0") {
1581	         $text .= LAN_YES.": <input type='radio' name='download_comment' value='1'/>
1582	            ".LAN_NO.": <input type='radio' name='download_comment' value='0' checked='checked'/>";
1583	      } else {
1584	         $text .= LAN_YES.": <input type='radio' name='download_comment' value='1' checked='checked'/>
1585	            ".LAN_NO.": <input type='radio' name='download_comment' value='0'/>";
1586	      }
1587	      $text .= "     </td>
1588	                  </tr>
1589	                  <tr>
1590	                     <td style='width:20%'>".DOWLAN_145."</td>
1591	                     <td style='width:80%'>".r_userclass('download_visible', $download_visible, 'off', 'public, nobody, member, admin, classes, language')."</td>
1592	                  </tr>
1593	                  <tr>
1594	                     <td style='width:20%'>".DOWLAN_106."</td>
1595	                     <td style='width:80%'>".r_userclass('download_class', $download_class, 'off', 'public, nobody, member, admin, classes, language')."</td>
1596	                  </tr>";
1597	      if ($subAction == "dlm") {
1598	         $text .= "
1599	                  <tr>
1600	                     <td style='width:30%'>".DOWLAN_153."</td>
1601	                     <td style='width:70%'>
1602	                        <select name='move_file' class='form-control'>
1603	                           <option value=''>".LAN_NO."</option>";
1604	           $dl_dirlist = $fl->get_dirs(e_DOWNLOAD);
1605	           if ($dl_dirlist){
1606	            sort($dl_dirlist);
1607	            $text .= "<option value='".e_DOWNLOAD."'>/</option>\n";
1608	            foreach($dl_dirlist as $dirs)
1609	            {
1610	                 $text .= "<option value='". e_DOWNLOAD.$dirs."/'>".$dirs."/</option>\n";
1611	            }
1612	         }
1613	         else
1614	         {
1615	              $text .= "<option value='".e_DOWNLOAD."'>".LAN_YES."</option>\n";
1616	         }
1617	         $text .= "     </select>
1618	                     </td>
1619	                  </tr>
1620	                  <tr>
1621	                     <td style='width:30%'>".DOWLAN_103."</td>
1622	                     <td style='width:70%'>
1623	                        <input type='checkbox' name='remove_upload' value='1'/>
1624	                        <input type='hidden' name='remove_id' value='$id'/>
1625	                     </td>
1626	                  </tr>";
1627	      }
1628
1629	      //triggerHook
1630	      $data = array('method'=>'form', 'table'=>'download', 'id'=>$id, 'plugin'=>'download', 'function'=>'create_download');
1631	      $text .= $frm->renderHooks($data);
1632
1633
1634
1635	      $text .= "
1636
1637	               </table>
1638	        <div class='buttonsbar center'>";
1639
1640
1641
1642	      if ($id && $subAction == "edit")
1643		  {
1644	         $text .= "<input class='btn btn-success' type='submit' name='submit_download' value='".DOWLAN_24."'/> ";
1645	      } else
1646	      {
1647	         $text .= "<input class='btn btn-success' type='submit' name='submit_download' value='".DOWLAN_25."'/>";
1648	      }
1649
1650	      $text .= "
1651	                     </div>
1652
1653	            </fieldset>
1654	         </form>
1655
1656
1657	        ";
1658	     // $ns->tablerender(ADLAN_24, $text);
1659	     echo $text;
1660	   }
1661
1662	function calc_filesize($size, $unit)
1663	{
1664		switch($unit)
1665		{
1666			case 'B' :
1667				return $size;
1668				break;
1669			case 'KB' :
1670				return $size * 1024;
1671				break;
1672			case 'MB' :
1673				return $size * 1024 * 1024;
1674				break;
1675			case 'GB' :
1676				return $size * 1024 * 1024 * 1024;
1677				break;
1678			case 'TB' :
1679				return $size * 1024 * 1024 * 1024 * 1024;
1680				break;
1681		}
1682	}
1683
1684	// Actually save a new or edited download to the DB
1685	   function submit_download()
1686	   {
1687			global $e107, $tp, $sql, $DOWNLOADS_DIRECTORY, $e_event;
1688
1689			$action		= $this->action;
1690			$subAction	= $this->subAction;
1691			$id			= $this->id;
1692
1693	   		$sql = e107::getDb();
1694			$tp = e107::getParser();
1695			$fl = e107::getFile();
1696			$mes = e107::getMessage();
1697
1698			$dlInfo = array();
1699			$dlMirrors = array();
1700
1701		    if ($subAction == 'edit')
1702		    {
1703		    	if ($_POST['download_url_external'] == '')
1704		        {
1705		        	$_POST['download_filesize_external'] = FALSE;
1706		       	}
1707			}
1708
1709			if (!empty($_POST['download_url_external']) && empty($_POST['download_url']) && !empty($_POST['download_filesize_unit']))
1710			{
1711				$dlInfo['download_url'] = $tp->toDB($_POST['download_url_external']);
1712			//	$filesize = intval($_POST['download_filesize_external']);
1713				$filesize = $this->calc_filesize($_POST['download_filesize_external'], $_POST['download_filesize_unit']);
1714			}
1715			else
1716			{
1717				$dlInfo['download_url'] = $tp->toDB($_POST['download_url']);
1718				if ($_POST['download_filesize_external'])
1719				{
1720	            	$filesize = intval($_POST['download_filesize_external']);
1721
1722	         	}
1723	         	else
1724	         	{
1725		            if (strpos($DOWNLOADS_DIRECTORY, "/") === 0 || strpos($DOWNLOADS_DIRECTORY, ":") >= 1)
1726		            {
1727		               $filesize = filesize($DOWNLOADS_DIRECTORY.$dlInfo['download_url']);
1728		            }
1729					elseif($dlInfo['download_url'][0] == '{')
1730					{
1731						$filesize = filesize($tp->replaceConstants($dlInfo['download_url']));
1732					}
1733		            else
1734		            {
1735		               $filesize = filesize(e_BASE.$DOWNLOADS_DIRECTORY.$dlInfo['download_url']);
1736		            }
1737				}
1738			}
1739
1740	      if (!$filesize)
1741	      {
1742	         if ($sql->select("upload", "upload_filesize", "upload_file='{$dlInfo['download_url']}'"))
1743	         {
1744	            $row = $sql->fetch();
1745	            $filesize = $row['upload_filesize'];
1746	         }
1747	      }
1748	      $dlInfo['download_filesize'] = $filesize;
1749
1750
1751	      //  ----   Move Images and Files ------------
1752	      if ($_POST['move_image'])
1753	      {
1754	         if ($_POST['download_thumb'])
1755	         {
1756	            $oldname = e_UPLOAD.$_POST['download_thumb'];
1757	            $newname = e_FILE."downloadthumbs/".$_POST['download_thumb'];
1758	            if (!$this -> move_file($oldname,$newname))
1759	            {
1760	                  return;
1761	            }
1762	         }
1763	         if ($_POST['download_image'])
1764	         {
1765	            $oldname = e_UPLOAD.$_POST['download_image'];
1766	            $newname = e_FILE."downloadimages/".$_POST['download_image'];
1767	            if (!$this -> move_file($oldname,$newname))
1768	            {
1769	                  return;
1770	            }
1771	         }
1772	      }
1773
1774	        if ($_POST['move_file'] && $_POST['download_url'])
1775	      {
1776	           $oldname = e_UPLOAD.$_POST['download_url'];
1777	         $newname = $_POST['move_file'].$_POST['download_url'];
1778	         if (!$this -> move_file($oldname,$newname))
1779	         {
1780	               return;
1781	         }
1782	            $dlInfo['download_url'] = str_replace(e_DOWNLOAD,"",$newname);
1783	      }
1784
1785
1786	       // ------------------------------------------
1787
1788
1789			$dlInfo['download_description'] 		= $tp->toDB($_POST['download_description']);
1790			$dlInfo['download_name'] 				= $tp->toDB($_POST['download_name']);
1791			$dlInfo['download_sef'] 				= vartrue($_POST['download_sef']) ? eHelper::secureSef($_POST['download_sef']) : eHelper::title2sef($_POST['download_name']);
1792			$dlInfo['download_keywords']				= $tp->toDB($_POST['download_keywords']);
1793			$dlInfo['download_author'] 				= $tp->toDB($_POST['download_author']);
1794			$dlInfo['download_author_email'] 		= $tp->toDB($_POST['download_author_email']);
1795			$dlInfo['download_author_website'] 		= $tp->toDB($_POST['download_author_website']);
1796			$dlInfo['download_category'] 			= intval($_POST['download_category']);
1797			$dlInfo['download_active']  			= intval($_POST['download_active']);
1798			$dlInfo['download_thumb']				= $tp->toDB($_POST['download_thumb']);
1799	      	$dlInfo['download_image']				= $tp->toDB($_POST['download_image']);
1800	      	$dlInfo['download_comment']				= $tp->toDB($_POST['download_comment']);
1801	      	$dlInfo['download_class']				= $tp->toDB($_POST['download_class']);
1802	      	$dlInfo['download_visible']				= $tp->toDB($_POST['download_visible']);
1803			$dlInfo['download_datestamp']			= intval($_POST['download_datestamp']);
1804
1805
1806	      if($_POST['update_datestamp'])
1807	      {
1808				$dlInfo['download_datestamp'] = time();
1809	      }
1810
1811	      $mirrorStr = "";
1812	      $mirrorFlag = FALSE;
1813
1814	      // See if any mirrors defined
1815	      // Need to check all the possible mirror names - might have deleted the first one if we're in edit mode
1816
1817	      if(count($_POST['download_mirror_name']))
1818		  {
1819				foreach ($_POST['download_mirror_name'] as $mn)
1820				{
1821					if ($mn)
1822		        	{
1823		        	   $mirrorFlag = TRUE;
1824		        	   break;
1825		        	}
1826		     	}
1827		  }
1828
1829	      if ($mirrorFlag)
1830	      {
1831	         $mirrors = count($_POST['download_mirror_name']);
1832	         $mirrorArray = array();
1833	         $newMirrorArray = array();
1834	         if ($id && $sql->select('download','download_mirror', 'download_id = '.$id))      // Get existing download stats
1835	         {
1836	            if ($row = $sql->fetch())
1837	            {
1838	               $mirrorArray = $this->makeMirrorArray($row['download_mirror'], TRUE);
1839	            }
1840	         }
1841	         for($a=0; $a<$mirrors; $a++)
1842	         {
1843	            $mid = trim($_POST['download_mirror_name'][$a]);
1844	            $murl = trim($_POST['download_mirror'][$a]);
1845	            $msize = trim($_POST['download_mirror_size'][$a]);
1846	            if ($mid && $murl)
1847	            {
1848	               $newMirrorArray[$mid] = array('id' => $mid, 'url' => $murl, 'requests' => 0, 'filesize' => $msize);
1849	               if (DOWNLOAD_DEBUG && !$id)
1850	               {
1851	                  $newMirrorArray[$mid]['requests'] = intval($_POST['download_mirror_requests'][$a]);
1852	               }
1853	            }
1854	         }
1855	         // Now copy across any existing usage figures
1856	         foreach ($newMirrorArray as $k => $m)
1857	         {
1858	            if (isset($mirrorArray[$k]))
1859	            {
1860	               $newMirrorArray[$k]['requests'] = $mirrorArray[$k]['requests'];
1861	            }
1862	         }
1863	         $mirrorStr = $this->compressMirrorArray($newMirrorArray);
1864	      }
1865
1866	      $dlMirrors['download_mirror']=$mirrorStr;
1867	      $dlMirrors['download_mirror_type']=intval($_POST['download_mirror_type']);
1868
1869	      if ($id) // Its an edit
1870	      {
1871	         	// Process triggers before calling admin_update so trigger messages can be shown
1872	         	$data = array('method'=>'update', 'table'=>'download', 'id'=>$id, 'plugin'=>'download', 'function'=>'update_download');
1873	         	$hooks = $e107->e_event->triggerHook($data);
1874
1875	   			$mes->add($hooks, E_MESSAGE_SUCCESS);
1876
1877				$updateArray = array_merge($dlInfo,$dlMirrors);
1878				$updateArray['WHERE'] = 'download_id='.intval($id);
1879
1880				$mes->addAuto($sql->db_Update('download',$updateArray), 'update', DOWLAN_2." (<a href='".e_PLUGIN."download/download.php?view.".$id."'>".$_POST['download_name']."</a>)");
1881
1882				$dlInfo['download_id'] = $id;
1883				$this->downloadLog('DOWNL_06',$dlInfo,$dlMirrors);
1884				$dlInfo['download_datestamp'] = $time;      // This is what 0.7 did, regardless of settings
1885				unset($dlInfo['download_class']);         // Also replicating 0.7
1886				$e_event->trigger('dlupdate', $dlInfo); // @deprecated
1887
1888				e107::getEvent()->trigger('admin_download_update',$dlInfo);
1889	      }
1890	      else // Its a new entry.
1891	      {
1892		         if ($download_id = $sql->insert('download',array_merge($dlInfo,$dlMirrors)))
1893		         {
1894		            // Process triggers before calling admin_update so trigger messages can be shown
1895		            $data = array('method'=>'create', 'table'=>'download', 'id'=>$download_id, 'plugin'=>'download', 'function'=>'create_download');
1896		            $hooks = $e107->e_event->triggerHook($data);
1897
1898		            $mes->add($hooks, E_MESSAGE_SUCCESS);
1899
1900		            $mes->addAuto($download_id, 'insert', DOWLAN_1." (<a href='".e_PLUGIN."download/download.php?view.".$download_id."'>".$_POST['download_name']."</a>)");
1901
1902		            $dlInfo['download_id'] = $download_id;
1903		            $this->downloadLog('DOWNL_05',$dlInfo,$dlMirrors);
1904		            $dlInfo['download_datestamp'] = $time;      // This is what 0.7 did, regardless of settings
1905		            unset($dlInfo['download_class']);         // Also replicating 0.7
1906		            $e_event->trigger("dlpost", $dlInfo); // @deprecated
1907
1908					e107::getEvent()->trigger('admin_download_create',$dlInfo);
1909
1910		            if ($_POST['remove_upload'])
1911		            {
1912		               $sql->db_Update("upload", "upload_active='1' WHERE upload_id='".$_POST['remove_id']."'");
1913		               $mess = "<br/>".$_POST['download_name']." ".DOWLAN_104;
1914		               $mess .= "<br/><br/><a href='".e_ADMIN."upload.php'>".DOWLAN_105."</a>";
1915		               $this->show_message($mess);
1916		            }
1917		         }
1918	      }
1919	   }
1920
1921
1922		// Turn the array into a string which can be stored in the DB
1923		function compressMirrorArray($source)
1924	   	{
1925	      	if (!is_array($source) || !count($source)) return '';
1926	      	$inter = array();
1927	      	foreach ($source as $s)
1928	      	{
1929	      	   $inter[] = $s['id'].','.$s['url'].','.$s['requests'].','.$s['filesize'];
1930	      	}
1931	      	return implode(chr(1),$inter);
1932	   	}
1933
1934
1935
1936
1937
1938
1939
1940		function show_existing_mirrors()
1941		{
1942			$sql 		= e107::getDb();
1943			$tp 		= e107::getParser();
1944			$mes 		= e107::getMessage();
1945			$fl			= e107::getFile();
1946
1947			$action		= $this->action;
1948			$subAction	= $this->subAction;
1949			$id			= $this->id;
1950
1951			global $delete, $del_id, $admin_log;
1952
1953	      require_once(e_HANDLER."form_handler.php");
1954	      $frm = new e_form();
1955
1956
1957	      if ($delete == "mirror")
1958	      {
1959	         $mes->addAuto($sql -> db_Delete("download_mirror", "mirror_id=".$del_id), delete, DOWLAN_135);
1960	         e107::getLog()->add('DOWNL_14','ID: '.$del_id,E_LOG_INFORMATIVE,'');
1961	      }
1962
1963
1964	      if (!$sql -> select("download_mirror"))
1965	      {
1966	   			$mes->addInfo(DOWLAN_144);
1967	         // $text = "<div style='text-align:center;'>".DOWLAN_144."</div>"; // No mirrors defined yet
1968	      }
1969	      else
1970	      {
1971
1972	         $text = "<div>
1973	         <form method='post' action='".e_SELF."?".e_QUERY."'>
1974	         <table style='".ADMIN_WIDTH."' class='adminlist'>
1975	         <tr>
1976	         <td style='width: 10%; text-align: center;' class='forumheader'>ID</td>
1977	         <td style='width: 30%;' class='forumheader'>".DOWLAN_12."</td>
1978	         <td style='width: 30%;' class='forumheader'>".DOWLAN_136."</td>
1979	         <td style='width: 30%; text-align: center;' class='forumheader'>".LAN_OPTIONS."</td>
1980	         </tr>
1981	         ";
1982
1983	         $mirrorList = $sql -> db_getList();
1984
1985	         foreach($mirrorList as $mirror)
1986	         {
1987	            extract($mirror);
1988	            $text .= "
1989
1990	            <tr>
1991	            <td style='width: 10%; text-align: center;'>$mirror_id</td>
1992	            <td style='width: 30%;'>".$tp -> toHTML($mirror_name)."</td>
1993	            <td style='width: 30%;'>".($mirror_image ? "<img src='".e_FILE."downloadimages/".$mirror_image."' alt=''/>" : LAN_NONE)."</td>
1994	            <td style='width: 30%; text-align: center;'>
1995	            <a href='".e_SELF."?mirror.edit.{$mirror_id}'>".ADMIN_EDIT_ICON."</a>
1996	            <input type='image' title='".LAN_DELETE."' name='delete[mirror_{$mirror_id}]' src='".ADMIN_DELETE_ICON_PATH."' onclick=\"return jsconfirm('".DOWLAN_137." [ID: $mirror_id ]')\"/>
1997	            </td>
1998	            </tr>
1999	            ";
2000	         }
2001	         $text .= "</table></form></div>";
2002
2003	      }
2004
2005	     // $ns -> tablerender(DOWLAN_138, $text);
2006		  echo $text;
2007
2008	      $imagelist = $fl->get_files(e_FILE.'downloadimages/');
2009
2010	      if ($subAction == "edit" && !defined("SUBMITTED"))
2011	      {
2012	         $sql -> select("download_mirror", "*", "mirror_id='".intval($id)."' ");
2013	         $mirror = $sql -> fetch();
2014	         extract($mirror);
2015	         $edit = TRUE;
2016	      }
2017	      else
2018	      {
2019	         unset($mirror_name, $mirror_url, $mirror_image, $mirror_location, $mirror_description);
2020	         $edit = FALSE;
2021	      }
2022
2023	      $text = "<div>
2024	      <form method='post' action='".e_SELF."?".e_QUERY."' id='dataform'>\n
2025	      <table class='table adminform'>
2026
2027	      <tr>
2028	      <td style='width: 30%;'>".DOWLAN_12."</td>
2029	      <td style='width: 70%;'>
2030	      <input class='form-control input-xxlarge' type='text' name='mirror_name' size='60' value='{$mirror_name}' maxlength='200'/>
2031	      </td>
2032	      </tr>
2033
2034	      <tr>
2035	      <td style='width: 30%;'>".DOWLAN_139."</td>
2036	      <td style='width: 70%;'>
2037	      <input class='form-control input-xxlarge' type='text' name='mirror_url' size='70' value='{$mirror_url}' maxlength='255'/>
2038	      </td>
2039	      </tr>
2040
2041	      <tr>
2042	      <td style='width: 30%;'>".DOWLAN_136."</td>
2043	      <td style='width: 70%;'>
2044	      <input class='form-control input-xxlarge' type='text' id='mirror_image' name='mirror_image' size='60' value='{$mirror_image}' maxlength='200'/>
2045
2046
2047	      <br /><input class='btn btn-default btn-secondary button' type ='button' style='cursor:pointer' size='30' value='".DOWLAN_42."' onclick='expandit(this)'/>
2048	      <div id='imagefile' style='display:none;{head}'>";
2049
2050	      $text .= DOWLAN_140."<br/>";
2051	      foreach($imagelist as $file)
2052	      {
2053	         $text .= "<a href=\"javascript:insertext('".$file['fname']."','mirror_image','imagefile')\"><img src='".e_FILE."downloadimages/".$file['fname']."' alt=''/></a> ";
2054	      }
2055
2056	      $text .= "</div>
2057	      </td>
2058	      </tr>
2059
2060	      <tr>
2061	      <td style='width: 30%;'>".DOWLAN_141."</td>
2062	      <td style='width: 70%;'>
2063	      <input class='form-control' type='text' name='mirror_location' size='60' value='$mirror_location' maxlength='200'/>
2064	      </td>
2065	      </tr>
2066
2067	      <tr>
2068	      <td style='width: 30%;'>".DOWLAN_18."</td>
2069	      <td style='width: 70%;'>";
2070	      $text .= $frm->bbarea('mirror_description',$mirror_description);
2071	      $text .= "</td>
2072	      </tr>
2073
2074	      <tr>
2075	      <td colspan='2' class='forumheader' style='text-align:center;'>
2076	      ".($edit ? "<input class='btn btn-default btn-secondary button' type='submit' name='submit_mirror' value='".DOWLAN_142."'/><input type='hidden' name='id' value='{$mirror_id}'/>" : "<input class='btn button' type='submit' name='submit_mirror' value='".DOWLAN_143."'/>")."
2077	      </td>
2078	      </tr>
2079
2080	      </table>
2081	      </form>
2082	      </div>";
2083
2084	      $caption = ($edit ? DOWLAN_142 : DOWLAN_143);
2085			echo $text;
2086	      // $ns -> tablerender($caption, $text);
2087	   }
2088
2089		function submit_mirror()
2090	   	{
2091			global $admin_log;
2092
2093			$tp = e107::getParser();
2094			$sql = e107::getDb();
2095			$mes = e107::getMessage();
2096
2097	 		define("SUBMITTED", TRUE);
2098
2099		      if (isset($_POST['mirror_name']) && isset($_POST['mirror_url']))
2100		      {
2101		         $name = $tp -> toDB($_POST['mirror_name']);
2102		         $url = $tp -> toDB($_POST['mirror_url']);
2103		         $location = $tp -> toDB($_POST['mirror_location']);
2104		         $description = $tp -> toDB($_POST['mirror_description']);
2105
2106		         $logString = $name.'[!br!]'.$url.'[!br!]'.$location.'[!br!]'.$description;
2107
2108		         if (isset($_POST['id']))
2109		         {
2110		            $mes->addAuto($sql -> db_Update("download_mirror", "mirror_name='{$name}', mirror_url='{$url}', mirror_image='".$tp->toDB($_POST['mirror_image'])."', mirror_location='{$location}', mirror_description='{$description}' WHERE mirror_id=".intval($_POST['id'])), 'update', DOWLAN_133);
2111		            e107::getLog()->add('DOWNL_13','ID: '.intval($_POST['id']).'[!br!]'.$logString,E_LOG_INFORMATIVE,'');
2112		         }
2113		         else
2114		         {
2115		            $mes->addAuto($sql -> db_Insert("download_mirror", "0, '{$name}', '{$url}', '".$tp->toDB($_POST['mirror_image'])."', '{$location}', '{$description}', 0"), 'insert', DOWLAN_134);
2116		            e107::getLog()->add('DOWNL_12',$logString,E_LOG_INFORMATIVE,'');
2117		         }
2118		      }
2119	   }
2120
2121	private function supported_secure_link_variables_html()
2122	{
2123		require_once(__DIR__."/../handlers/NginxSecureLinkMd5Decorator.php");
2124		$supported_secure_link_variables_html = "<ul>";
2125		foreach(NginxSecureLinkMd5Decorator::supported_variables() as $variable)
2126		{
2127			$supported_secure_link_variables_html .= "<li><code>$variable</code></li>";
2128		}
2129		$supported_secure_link_variables_html .= "</ul>";
2130		return $supported_secure_link_variables_html;
2131	}
2132
2133	private function mirror_order_options_html($pref)
2134	{
2135		return ($pref['mirror_order'] == "0" ? "<option value='0' selected='selected'>".DOWLAN_161."</option>" : "<option value='0'>".DOWLAN_161."</option>").
2136			($pref['mirror_order'] == "1" ? "<option value='1' selected='selected'>".LAN_ID."</option>" : "<option value='1'>".LAN_ID."</option>").
2137			($pref['mirror_order'] == "2" ? "<option value='2' selected='selected'>".DOWLAN_12."</option>" : "<option value='2'>".DOWLAN_12."</option>");
2138	}
2139
2140		function show_download_options()
2141		{
2142		   	global $pref, $ns;
2143
2144			require_once(e_HANDLER."form_handler.php");
2145			$frm = new e_form(true); //enable inner tabindex counter
2146
2147			$agree_flag = $pref['agree_flag'];
2148		   	$agree_text = $pref['agree_text'];
2149		      $c = $pref['download_php'] ? " checked = 'checked' " : "";
2150		      $sacc = (varset($pref['download_incinfo'],0) == '1') ? " checked = 'checked' " : "";
2151		      $order_options = array(
2152		         "download_id"        => "Id No.",
2153		         "download_datestamp" => LAN_DATE,
2154		         "download_requested" => LAN_PLUGIN_DOWNLOAD_NAME,
2155		         "download_name"      => DOWLAN_59,
2156		         "download_author"    => DOWLAN_15
2157		      );
2158		      $sort_options = array(
2159		         "ASC"    => DOWLAN_62,
2160		         "DESC"   => DOWLAN_63
2161		      );
2162
2163		   	$text = "
2164
2165					   <ul class='nav nav-tabs'>
2166						   <li class='active'><a data-toggle='tab' href='#core-download-download1'>".LAN_DL_DOWNLOAD_OPT_GENERAL."</a></li>
2167						   <li><a data-toggle='tab' href='#core-download-download2'>".LAN_DL_DOWNLOAD_OPT_BROKEN."</a></li>
2168						   <li><a data-toggle='tab' href='#core-download-download3'>".LAN_DL_DOWNLOAD_OPT_AGREE."</a></li>
2169						   <li><a data-toggle='tab' href='#core-download-download4'>".LAN_DL_DOWNLOAD_OPT_SECURITY."</a></li>
2170						   <li><a data-toggle='tab' href='#core-download-download5'>".LAN_DL_UPLOAD."</a></li>
2171					   </ul>
2172
2173		        		<form method='post' action='".e_SELF."?".e_QUERY."'>\n
2174		        		<div class='tab-content'>
2175		   				<div class='tab-pane active' id='core-download-download1'>
2176		            	   <div>
2177		            		   <table class='table adminform'>
2178		            		      <colgroup>
2179		            		         <col style='width:30%'/>
2180		            		         <col style='width:70%'/>
2181		            		      </colgroup>
2182		            		      <tr>
2183		            		         <td>".LAN_DL_USE_PHP."</td>
2184		            		         <td>"
2185		            		            .$frm->checkbox('download_php', '1', $pref['download_php'])
2186		            		            .$frm->label(LAN_DL_USE_PHP_INFO, 'download_php', '1')
2187		            		         ."</td>
2188		            		      </tr>
2189		            		      <tr>
2190		            		         <td>".LAN_DL_SUBSUB_CAT."</td>
2191		            		         <td>"
2192		            		            .$frm->checkbox('download_subsub', '1', $pref['download_subsub'])
2193		            		            .$frm->label(LAN_DL_SUBSUB_CAT_INFO, 'download_subsub', '1')
2194		            		         ."</td>
2195		            		      </tr>
2196		            		      <tr>
2197		            		         <td>".LAN_DL_SUBSUB_COUNT."</td>
2198		            		         <td>"
2199		            		            .$frm->checkbox('download_incinfo', '1', $pref['download_incinfo'])
2200		            		            .$frm->label(LAN_DL_SUBSUB_COUNT_INFO, 'download_incinfo', '1')
2201		            		         ."</td>
2202		            		      </tr>
2203		            		      <tr>
2204		               		      <td>".DOWLAN_55."</td>
2205		            		         <td>".$frm->text('download_view', $pref['download_view'], '4', array('size'=>'4'))."</td>
2206		            		      </tr>
2207		            		      <tr>
2208		            		         <td>".DOWLAN_56."</td>
2209		            		         <td>".$frm->select('download_order', $order_options, $pref['download_order'])."</td>
2210		            		      </tr>
2211		            		      <tr>
2212		            		         <td>".LAN_ORDER."</td>
2213		             		         <td>".$frm->select('download_sort', $sort_options, $pref['download_sort'])."</td>
2214		            		      </tr>
2215		            		      <tr>
2216		               		      <td>".DOWLAN_160."</td>
2217		               		      <td>
2218		                  		      <select name='mirror_order' class='form-control'>".$this->mirror_order_options_html($pref)."
2219		            		            </select>
2220		               		      </td>
2221		            		      </tr>
2222		            		      <tr>
2223		            		         <td>".DOWLAN_164."</td>
2224		            		         <td><input type='text' name='recent_download_days' class='form-control' value='".$pref['recent_download_days']."' size='3' maxlength='3'/>
2225		            		         </td>
2226		            		      </tr>
2227		            		   </table>
2228		            		</div>
2229				   		</div>
2230		   				<div class='tab-pane' id='core-download-download2'>
2231		            	   <div>
2232		            		   <table class='table adminform'>
2233		            		      <colgroup>
2234		            		         <col style='width:30%'/>
2235		            		         <col style='width:70%'/>
2236		            		      </colgroup>
2237		            		      <tr>
2238		               		      <td>".DOWLAN_151."</td>
2239		               		      <td>". r_userclass("download_reportbroken", $pref['download_reportbroken'])."</td>
2240		            		      </tr>";
2241
2242		            		      //moved to e_notify
2243		            		      /*
2244		            		      <tr>
2245		               		      <td>".DOWLAN_150."</td>
2246		               		      <td>". ($pref['download_email'] ? "<input type='checkbox' name='download_email' value='1' checked='checked'/>" : "<input type='checkbox' name='download_email' value='1'/>")."</td>
2247		            		      </tr>*/
2248		    $text .= "
2249		            		   </table>
2250		            		</div>
2251				   		</div>
2252		   				<div class='tab-pane' id='core-download-download3'>
2253		            	   <div>
2254		            		   <table class='table adminform'>
2255		            		      <colgroup>
2256		            		         <col style='width:30%'/>
2257		            		         <col style='width:70%'/>
2258		            		      </colgroup>
2259		            		      <tr>
2260		               		      <td>".DOWLAN_100."</td>
2261		               		      <td>". ($agree_flag ? "<input type='checkbox' name='agree_flag' value='1' checked='checked'/>" : "<input type='checkbox' name='agree_flag' value='1'/>")."</td>
2262		            		      </tr>
2263		            		      <tr>
2264		            		         <td>".DOWLAN_101."</td>
2265		               	   	   <td>".$frm->bbarea('agree_text',$agree_text)."</td>
2266		            		      </tr>
2267		            		      <tr>
2268		            		         <td>".DOWLAN_146."</td>
2269		            		         <td>".$frm->bbarea('download_denied',$pref['download_denied'])."</td>
2270		            		      </tr>
2271		            		   </table>
2272		            		</div>
2273				   		</div>
2274		   				<div class='tab-pane' id='core-download-download4'>
2275		            	   <div>
2276		            	   		<p style='padding: 8px'>
2277		            	   			".LAN_DL_SECURITY_DESCRIPTION."
2278								</p>
2279		            		   <table class='table adminform'>
2280		            		      <colgroup>
2281		            		         <col style='width:30%'/>
2282		            		         <col style='width:70%'/>
2283		            		      </colgroup>
2284		            		      <tr>
2285		            		         <td>".LAN_DL_SECURITY_MODE."</td>
2286		            		         <td>".$frm->select('download_security_mode', $this->security_options, $pref['download_security_mode'])."</td>
2287		            		      </tr>
2288		            		      <tbody id='nginx-secure_link_md5' ".($pref['download_security_mode'] === 'nginx-secure_link_md5' ? "" : "style='display:none'").">
2289		            		      	<tr>
2290		            		     	 	<td>".LAN_DL_SECURITY_NGINX_SECURELINKMD5_EXPRESSION."</td>
2291		            		     	 	<td>
2292		            		     	 		".$frm->text('download_security_expression', $pref['download_security_expression'], 1024)."
2293		            		     	 		<div class='field-help'>".LAN_DL_SECURITY_NGINX_SECURELINKMD5_EXPRESSION_HELP."</div>
2294		            		     	 		<small><a href='#' onclick='event.preventDefault();$(\"#supported-nginx-variables\").toggle();this.blur()'>
2295		            		     	 			".LAN_DL_SECURITY_NGINX_SUPPORTED_VARIABLES_TOGGLE."
2296		            		     	 		</a></small>
2297		            		     	 		<div id='supported-nginx-variables' style='display:none'>
2298		            	   						".$this->supported_secure_link_variables_html()."
2299		            		     	 		</div>
2300		            		     	 	</td>
2301		            		      	</tr>
2302		            		      	<tr>
2303		            		      		<td>".LAN_DL_SECURITY_LINK_EXPIRY."</td>
2304		            		      		<td>
2305		            		     	 		".$frm->text('download_security_link_expiry', $pref['download_security_link_expiry'], 16, array('pattern' => '\d+'))."
2306		            		      			<div class='field-help'>".LAN_DL_SECURITY_LINK_EXPIRY_HELP."</div>
2307		            		      		</td>
2308		            		      	</tr>
2309								  </tbody>
2310		            		   </table>
2311		            		</div>
2312				   		</div>
2313				   		<div class='tab-pane' id='core-download-download5'>
2314		            	   <div>
2315		            		   <table class='table adminform'>
2316		            		      <colgroup>
2317		            		         <col style='width:30%'/>
2318		            		         <col style='width:70%'/>
2319		            		      </colgroup>
2320		            		      <tr>
2321		            		         <td>".DOWLAN_XXX."</td>
2322		            		         <td>//TODO</td>
2323		            		      </tr>
2324		            		   </table>
2325		            		</div>
2326				   		</div>
2327						   <div class='buttons-bar center'>
2328		                  <input class='btn btn-default btn-secondary button' type='submit' name='updatedownlaodoptions' value='".DOWLAN_64."'/>
2329		               </div>
2330
2331		           </div>
2332		           </form>
2333		      ";
2334
2335		   	  e107::js('footer-inline', "
2336		   	  $('#download-security-mode').on('change', function() {
2337		   	    var mode = $(this).val();
2338
2339		   	    if (mode == 'nginx-secure_link_md5') {
2340		   	        $('#nginx-secure_link_md5').show('slow');
2341		   	        return;
2342		   	    }
2343
2344		   	    $('#nginx-secure_link_md5').hide('slow');
2345		   	  });
2346		   	  ");
2347
2348		      echo $text;
2349		   }
2350
2351
2352
2353
2354
2355		function downloadLog($aText, &$dlInfo, &$mirrorInfo=NULL)
2356		{
2357			global $admin_log;
2358			$logString = DOWLAN_9;
2359			foreach ($dlInfo as $k => $v)
2360			{
2361				$logString .= '[!br!]'.$k.'=>'.$v;
2362			}
2363			if ($mirrorInfo != NULL)
2364			{
2365				foreach ($mirrorInfo as $k => $v)
2366				{
2367					$logString .= '[!br!]'.$k.'=>'.$v;
2368				}
2369			}
2370			e107::getLog()->add($aText,$logString,E_LOG_INFORMATIVE,'');
2371	   }
2372
2373
2374
2375
2376
2377		function move_file($oldname,$newname)
2378		{
2379
2380			$mes = e107::getMessage();
2381
2382			if (file_exists($newname))
2383		    {
2384		    	return TRUE;
2385		    }
2386
2387			if (!file_exists($oldname) || is_dir($oldname))
2388			{
2389				$mes->addError(DOWLAN_68 . " : ".$oldname);
2390		        return FALSE;
2391			}
2392
2393			$directory = dirname($newname);
2394			if (is_writable($directory))
2395			{
2396		         if (!rename($oldname,$newname))
2397		         {
2398		            $mes->addError(DOWLAN_152." ".$oldname ." -> ".$newname);
2399		            return FALSE;
2400		         }
2401		         else
2402		         {
2403		            return TRUE;
2404		         }
2405			}
2406			else
2407			{
2408				$mes->addError($directory ." ".LAN_NOTWRITABLE);
2409				return FALSE;
2410			}
2411	   }
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421		// Given the string which is stored in the DB, turns it into an array of mirror entries
2422	   // If $byID is true, the array index is the mirror ID. Otherwise its a simple array
2423	   function makeMirrorArray($source, $byID = FALSE)
2424	   {
2425	      $ret = array();
2426	      if ($source)
2427	      {
2428	         $mirrorTArray = explode(chr(1), $source);
2429
2430	         $count = 0;
2431	         foreach($mirrorTArray as $mirror)
2432	         {
2433	            if ($mirror)
2434	            {
2435	               list($mid, $murl, $mreq, $msize) = explode(",", $mirror);
2436	               $ret[$byID ? $mid : $count] = array('id' => $mid, 'url' => $murl, 'requests' => $mreq, 'filesize' => $msize);
2437	               $count++;
2438	            }
2439	         }
2440	      }
2441	      return $ret;
2442	   }
2443
2444
2445
2446}
2447
2448class download_main_admin_form_ui extends e_admin_form_ui
2449{
2450
2451	function download_category($curVal,$mode) // not really necessary since we can use 'dropdown' - but just an example of a custom function.
2452	{
2453		if($mode == 'read')
2454		{
2455			return $curVal.' (custom!)';
2456		}
2457
2458		if($mode == 'batch') // Custom Batch List for release_type
2459		{
2460			return array('theme'=>"Theme","plugin"=>'Plugin');
2461		}
2462
2463		if($mode == 'filter') // Custom Filter List for release_type
2464		{
2465			return array('theme'=>"Theme","plugin"=>'Plugin');
2466		}
2467
2468		$types = array("theme","plugin");
2469		$text = "<select class='form-control' name='release_type' >";
2470		foreach($types as $val)
2471		{
2472			$selected = ($curVal == $val) ? "selected='selected'" : "";
2473			$text .= "<option value='{$val}' {$selected}>".$val."</option>\n";
2474		}
2475		$text .= "</select>";
2476		return $text;
2477	}
2478
2479
2480	function download_active($curVal,$mode)
2481	{
2482		$download_status[0] = DOWLAN_122; // Inactive;
2483      	$download_status[1] = DOWLAN_123; // Active
2484      	$download_status[2] = DOWLAN_124;
2485
2486		if($mode == 'read')
2487		{
2488			$status = array(ADMIN_FALSE_ICON,ADMIN_TRUE_ICON,ADMIN_WARNING_ICON);
2489			return $status[$curVal];
2490		}
2491
2492		if($mode == 'batch' || $mode == 'filter') // Custom Batch List for download_active
2493		{
2494			return $download_status;
2495		}
2496
2497		return "&nbsp;";
2498	}
2499
2500
2501	// Filter List for 'Issues'
2502	function issue($curVal,$mode)
2503	{
2504		if($mode == 'filter')
2505		{
2506			return array(
2507				'duplicates'	=> DOWLAN_166,
2508				'orphans'		=> DOWLAN_167, // TODO
2509				'missing'		=> DOWLAN_168,
2510				'nocategory' 	=> DOWLAN_178,
2511				'filesize'		=> DOWLAN_66,
2512				'log'			=> DOWLAN_171
2513			);
2514
2515		}
2516
2517		return "&nbsp;";
2518	}
2519
2520
2521	function download_mirror_type($curVal,$mode)
2522	{
2523		switch ($curVal)
2524		{
2525       		case 1:
2526         	return DOWLAN_196;
2527        	break;
2528         	default:
2529  			// return DOWLAN_197;
2530  		}
2531	}
2532}
2533
2534
2535class download_mirror_ui extends e_admin_ui
2536{
2537
2538		protected $pluginTitle		= LAN_PLUGIN_DOWNLOAD_NAME;
2539		protected $pluginName		= 'download';
2540		protected $table			= 'download_mirror';
2541		protected $pid				= 'mirror_id';
2542		protected $perPage			= 10;
2543		protected $batchDelete		= true;
2544	//	protected $batchCopy		= true;
2545	//	protected $sortField		= 'somefield_order';
2546	//	protected $orderStep		= 10;
2547	//	protected $tabs			= array('Tabl 1','Tab 2'); // Use 'tab'=>0  OR 'tab'=>1 in the $fields below to enable.
2548
2549	//	protected $listQry      	= "SELECT * FROM #tableName WHERE field != '' "; // Example Custom Query. LEFT JOINS allowed. Should be without any Order or Limit.
2550
2551		protected $listOrder		= 'mirror_id DESC';
2552
2553		protected $fields 		= array (  'checkboxes' =>   array ( 'title' => '', 'type' => null, 'data' => null, 'width' => '5%', 'thclass' => 'center', 'forced' => '1', 'class' => 'center', 'toggle' => 'e-multiselect',  ),
2554		  'mirror_id' 			=>   array ( 'title' => LAN_ID, 'data' => 'int', 'width' => '5%', 'help' => '', 'readParms' => '', 'writeParms' => '', 'class' => 'left', 'thclass' => 'left',  ),
2555		  'mirror_name' 		=>   array ( 'title' => LAN_TITLE, 'type' => 'text', 'data' => 'str', 'width' => 'auto', 'inline' => true, 'help' => '', 'readParms' => '', 'writeParms' => '', 'class' => 'left', 'thclass' => 'left',  ),
2556		  'mirror_url' 			=>   array ( 'title' => LAN_URL, 'type' => 'url', 'data' => 'str', 'width' => 'auto', 'inline' => true, 'help' => '', 'readParms' => '', 'writeParms' => '', 'class' => 'left', 'thclass' => 'left',  ),
2557		  'mirror_image' 		=>   array ( 'title' => LAN_IMAGE, 'type' => 'image', 'data' => 'str', 'width' => 'auto', 'help' => '', 'readParms' => '', 'writeParms' => '', 'class' => 'left', 'thclass' => 'left',  ),
2558		  'mirror_location' 	=>   array ( 'title' => DOWLAN_141, 'type' => 'text', 'data' => 'str', 'width' => 'auto', 'inline' => true, 'help' => '', 'readParms' => '', 'writeParms' => '', 'class' => 'center', 'thclass' => 'center',  ),
2559		  'mirror_description' 	=>   array ( 'title' => LAN_DESCRIPTION, 'type' => 'bbarea', 'data' => 'str', 'width' => '40%', 'help' => '', 'readParms' => '', 'writeParms' => '', 'class' => 'left', 'thclass' => 'left',  ),
2560		  'mirror_count' 		=>   array ( 'title' => 'Count', 'type' => 'hidden', 'data' => 'int', 'width' => 'auto', 'help' => '', 'readParms' => '', 'writeParms' => '', 'class' => 'center', 'thclass' => 'center',  ),
2561		  'options' 			=>   array ( 'title' => LAN_OPTIONS, 'type' => null, 'data' => null, 'width' => '10%', 'thclass' => 'center last', 'class' => 'center last', 'forced' => '1',  ),
2562		);
2563
2564		protected $fieldpref = array('mirror_name', 'mirror_url', 'mirror_image', 'mirror_location');
2565
2566
2567		public function init()
2568		{
2569			// Set drop-down values (if any).
2570
2571		}
2572
2573	/*
2574		// optional - override edit page.
2575		public function customPage()
2576		{
2577			$ns = e107::getRender();
2578			$text = 'Hello World!';
2579			$ns->tablerender('Hello',$text);
2580
2581		}
2582	*/
2583
2584}
2585
2586
2587
2588class download_mirror_form_ui extends e_admin_form_ui
2589{
2590
2591}
2592
2593class download_broken_ui extends e_admin_ui
2594{
2595
2596	protected $pluginTitle		= LAN_PLUGIN_DOWNLOAD_NAME;
2597	protected $pluginName		= 'download';
2598	protected $table			= 'generic';
2599	protected $pid				= 'gen_id';
2600	protected $perPage 			= 10;
2601	protected $listQry			= "SELECT g.*,u.user_name FROM `#generic` AS g LEFT JOIN `#user` AS u ON g.gen_user_id = u.user_id WHERE g.gen_type='Broken Download'";
2602	protected $listOrder		= 'gen_datestamp ASC';
2603
2604	protected $fields 		= array (
2605		'checkboxes' =>   array ( 'title' => '', 'type' => null, 'data' => null, 'width' => '5%', 'thclass' => 'center', 'forced' => '1', 'class' => 'center', 'toggle' => 'e-multiselect',  ),
2606        'gen_id' 				=> array ( 'title' => LAN_ID, 'type' => 'number', 'nolist' => true,	'data' => 'int', 'width' => '5%', 'help' => '', 'readParms' => '', 'writeParms' => '', 'class' => 'left', 'thclass' => 'left',  ),
2607        'gen_datestamp' 		=> array ( 'title' => LAN_DATESTAMP, 'type' => 'datestamp', 'data' => 'int', 'width' => '10%', 'filter' => true, 'help' => '', 'readParms' => '', 'writeParms' => '', 'class' => 'left', 'thclass' => 'left',  ),
2608        //'gen_intdata' 		=> array ( 'title' =>  LAN_ID, 'type' => 'number', 'batch'=>false, 'data' => 'int', 'width' => '5%', 'help' => '', 'readParms' => '', 'writeParms' => '', 'class' => 'center', 'thclass' => 'center',  ),
2609        'gen_ip' 				=> array ( 'title' => LAN_TITLE, 'type' => 'text', 'data' => 'str', 'width' => 'auto', 'help' => '', 'readParms' => '', 'writeParms' => '', 'class' => 'left', 'thclass' => 'left',  ),
2610        'gen_chardata' 		=> array ( 'title' => LAN_DESCRIPTION, 'type' => 'text', 'data' => 'str', 'width' => '40%', 'help' => '', 'readParms' => '', 'writeParms' => '', 'class' => 'left', 'thclass' => 'left', ),
2611        'gen_user_id' 		=> array ( 'title' => DOWLAN_199, 'type' => 'user', 'batch'=>false, 'data' => 'int', 'width' => '5%', 'help' => '', 'readParms' => 'idField=gen_user_id', 'writeParms' => '', 'class' => 'left', 'thclass' => 'left nowrap',  ),
2612        'options'				=> array ( 'title' => LAN_OPTIONS, 'type' => 'method', 'data' => null, 'width' => '10%', 'thclass' => 'center last', 'class' => 'center last', 'forced' => '1', 'readParms'=>'edit=0'  ),
2613	);
2614
2615	protected $fieldpref = array('gen_datestamp', 'gen_ip', 'gen_chardata', 'gen_user_id');
2616
2617	protected $batchOptions = array();
2618
2619	// optional
2620	public function init()
2621	{
2622
2623	}
2624
2625	public function afterDelete($deleted_data, $id, $deleted_check)
2626	{
2627
2628	}
2629
2630	public function renderHelp()
2631	{
2632		$help_text = str_replace("[br]", "<br />", DOWLAN_HELP_11);
2633		$help_text = str_replace(array("[", "]"), array("<a href='".e_ADMIN_ABS."notify.php'>"), $help_text);
2634
2635		return array('caption' => LAN_HELP, 'text' => $help_text);
2636	}
2637
2638}
2639
2640
2641
2642class download_broken_form_ui extends e_admin_form_ui
2643{
2644
2645	function options($att, $value, $id, $attributes)
2646	{
2647		if($attributes['mode'] == 'read')
2648		{
2649			$download_id = $this->getController()->getListModel()->get('gen_intdata');
2650
2651			$text = "<div class='btn-group'>";
2652			$text .= "<a class='btn btn-default' href='".e_SELF."?mode=main&action=edit&id=". $download_id."'>".ADMIN_VIEW_ICON."</a>";
2653			$text .= $this->renderValue('options', $value, array('readParms' => 'edit=0'), $id);
2654			$text .= "</div>";
2655
2656			return $text;
2657		}
2658	}
2659}